Add @ mention support for agents and files, extract CopyButton component

This commit is contained in:
Chris Scott committed 2025-12-06 11:21:06 -08:00
1 parent 3e31dbcdf8
commit dc7964021d
11 files changed
+306 -99

No files matched your search

+6
View File
@@ -10,6 +10,7 @@ type ConfigResponse = paths['/config']['get']['responses']['200']['content']['ap
type CommandListResponse = paths['/command']['get']['responses']['200']['content']['application/json']
type CommandRequest = NonNullable<paths['/session/{id}/command']['post']['requestBody']>['content']['application/json']
type ShellRequest = NonNullable<paths['/session/{id}/shell']['post']['requestBody']>['content']['application/json']
type AgentListResponse = paths['/agent']['get']['responses']['200']['content']['application/json']
export class OpenCodeClient {
private client: AxiosInstance
@@ -121,6 +122,11 @@ export class OpenCodeClient {
return result.data
}
async listAgents() {
const response = await this.client.get<AgentListResponse>('/agent')
return response.data
}
getEventSourceURL() {
const base = this.baseURL.startsWith('http')
? this.baseURL
@@ -0,0 +1,90 @@
import { useEffect, useRef } from 'react'
import { Bot, FileText } from 'lucide-react'
export interface MentionItem {
type: 'file' | 'agent'
value: string
label: string
description?: string
}
interface MentionSuggestionsProps {
isOpen: boolean
items: MentionItem[]
onSelect: (item: MentionItem) => void
onClose: () => void
selectedIndex?: number
}
export function MentionSuggestions({
isOpen,
items,
onSelect,
onClose,
selectedIndex = 0
}: MentionSuggestionsProps) {
const listRef = useRef<HTMLDivElement>(null)
useEffect(() => {
if (!isOpen) return
const handleClickOutside = (e: MouseEvent) => {
if (listRef.current && !listRef.current.contains(e.target as Node)) {
onClose()
}
}
document.addEventListener('mousedown', handleClickOutside)
return () => document.removeEventListener('mousedown', handleClickOutside)
}, [isOpen, onClose])
useEffect(() => {
if (!isOpen || !listRef.current) return
const selectedItem = listRef.current.children[selectedIndex] as HTMLElement
if (selectedItem) {
selectedItem.scrollIntoView({ block: 'nearest' })
}
}, [selectedIndex, isOpen])
if (!isOpen || items.length === 0) return null
const getFilename = (path: string) => path.split('/').pop() || path
const getDirectory = (path: string) => {
const parts = path.split('/')
return parts.slice(0, -1).join('/') || '.'
}
return (
<div
ref={listRef}
className="absolute bottom-full left-0 right-0 mb-2 z-50 bg-background border border-border rounded-lg shadow-xl max-h-[30vh] md:max-h-[40vh] lg:max-h-[50vh] overflow-y-auto"
>
{items.map((item, idx) => (
<button
key={`${item.type}-${item.value}`}
onClick={() => onSelect(item)}
className={`w-full px-3 py-2 text-left transition-colors flex items-start gap-2 ${
idx === selectedIndex
? 'bg-primary text-primary-foreground'
: 'hover:bg-muted text-foreground'
}`}
>
{item.type === 'agent' ? (
<Bot className="w-4 h-4 mt-0.5 flex-shrink-0" />
) : (
<FileText className="w-4 h-4 mt-0.5 flex-shrink-0" />
)}
<div className="flex-1 min-w-0">
<div className="font-mono text-sm font-medium truncate">
{item.type === 'file' ? getFilename(item.value) : item.label}
</div>
<div className="text-xs opacity-70 mt-0.5 truncate">
{item.type === 'file' ? getDirectory(item.value) : item.description || 'Agent'}
</div>
</div>
</button>
))}
</div>
)
}
@@ -1,10 +1,11 @@
import { memo } from 'react'
import type { components } from '@/api/opencode-types'
import { Copy, Volume2, Square, Loader2 } from 'lucide-react'
import { Volume2, Square, Loader2 } from 'lucide-react'
import { TextPart } from './TextPart'
import { PatchPart } from './PatchPart'
import { ToolCallPart } from './ToolCallPart'
import { useTTS } from '@/hooks/useTTS'
import { CopyButton } from '@/components/ui/copy-button'
type Part = components['schemas']['Part']
@@ -14,6 +15,7 @@ interface MessagePartProps {
allParts?: Part[]
partIndex?: number
onFileClick?: (filePath: string, lineNumber?: number) => void
onChildSessionClick?: (sessionId: string) => void
messageTextContent?: string
}
@@ -52,29 +54,7 @@ function getCopyableContent(part: Part, allParts?: Part[]): string {
}
}
function CopyButton({ content, title, className = "" }: { content: string; title: string; className?: string }) {
const handleCopy = async () => {
try {
await navigator.clipboard.writeText(content)
} catch (error) {
console.error('Failed to copy content:', error)
}
}
if (!content.trim()) {
return null
}
return (
<button
onClick={handleCopy}
className={`p-1.5 rounded bg-card hover:bg-card-hover text-muted-foreground hover:text-foreground ${className}`}
title={title}
>
<Copy className="w-4 h-4" />
</button>
)
}
interface TTSButtonProps {
content: string
@@ -118,7 +98,7 @@ export function TTSButton({ content, className = "" }: TTSButtonProps) {
export const MessagePart = memo(function MessagePart({ part, role, allParts, partIndex, onFileClick, messageTextContent }: MessagePartProps) {
export const MessagePart = memo(function MessagePart({ part, role, allParts, partIndex, onFileClick, onChildSessionClick, messageTextContent }: MessagePartProps) {
const copyableContent = getCopyableContent(part, allParts)
switch (part.type) {
@@ -133,7 +113,7 @@ export const MessagePart = memo(function MessagePart({ part, role, allParts, par
case 'patch':
return <PatchPart part={part} />
case 'tool':
return <ToolCallPart part={part} onFileClick={onFileClick} />
return <ToolCallPart part={part} onFileClick={onFileClick} onChildSessionClick={onChildSessionClick} />
case 'reasoning':
return (
<details className="border border-border rounded-lg my-2">
@@ -16,6 +16,7 @@ interface MessageThreadProps {
directory?: string
messages?: MessageWithParts[]
onFileClick?: (filePath: string, lineNumber?: number) => void
onChildSessionClick?: (sessionId: string) => void
}
const isMessageStreaming = (msg: MessageWithParts): boolean => {
@@ -28,7 +29,7 @@ const isMessageThinking = (msg: MessageWithParts): boolean => {
return msg.parts.length === 0 && isMessageStreaming(msg)
}
export const MessageThread = memo(function MessageThread({ messages, onFileClick }: MessageThreadProps) {
export const MessageThread = memo(function MessageThread({ messages, onFileClick, onChildSessionClick }: MessageThreadProps) {
if (!messages || messages.length === 0) {
return (
<div className="flex items-center justify-center h-full text-muted-foreground">
@@ -86,6 +87,7 @@ export const MessageThread = memo(function MessageThread({ messages, onFileClick
allParts={msg.parts}
partIndex={index}
onFileClick={onFileClick}
onChildSessionClick={onChildSessionClick}
messageTextContent={msg.info.role === 'assistant' ? getMessageTextContent(msg) : undefined}
/>
</div>
+103 -62
View File
@@ -1,5 +1,5 @@
import { useState, useRef, useEffect, type KeyboardEvent } from 'react'
import { useSendPrompt, useAbortSession, useMessages, useSendShell, useConfig } from '@/hooks/useOpenCode'
import { useState, useRef, useEffect, useMemo, type KeyboardEvent } from 'react'
import { useSendPrompt, useAbortSession, useMessages, useSendShell, useConfig, useAgents } from '@/hooks/useOpenCode'
import { useSettings } from '@/hooks/useSettings'
import { useCommands } from '@/hooks/useCommands'
import { useCommandHandler } from '@/hooks/useCommandHandler'
@@ -9,8 +9,8 @@ import { useUserBash } from '@/stores/userBashStore'
import { ChevronDown } from 'lucide-react'
import { CommandSuggestions } from '@/components/command/CommandSuggestions'
import { FileSuggestions } from './FileSuggestions'
import { detectMentionTrigger, parsePromptToParts, getFilename } from '@/lib/promptParser'
import { MentionSuggestions, type MentionItem } from './MentionSuggestions'
import { detectMentionTrigger, parsePromptToParts, getFilename, filterAgentsByQuery } from '@/lib/promptParser'
import { getSessionModel } from '@/lib/model'
import { getModel, formatModelName } from '@/api/providers'
import type { components } from '@/api/opencode-types'
@@ -57,11 +57,12 @@ export function PromptInput({
const [showSuggestions, setShowSuggestions] = useState(false)
const [suggestionQuery, setSuggestionQuery] = useState('')
const [attachedFiles, setAttachedFiles] = useState(new Map<string, FileInfo>())
const [showFileSuggestions, setShowFileSuggestions] = useState(false)
const [fileQuery, setFileQuery] = useState('')
const [showMentionSuggestions, setShowMentionSuggestions] = useState(false)
const [mentionQuery, setMentionQuery] = useState('')
const [mentionRange, setMentionRange] = useState<{ start: number, end: number } | null>(null)
const [selectedFileIndex, setSelectedFileIndex] = useState(0)
const [selectedMentionIndex, setSelectedMentionIndex] = useState(0)
const [selectedCommandIndex, setSelectedCommandIndex] = useState(0)
const [selectedAgent, setSelectedAgent] = useState<string | null>(null)
const textareaRef = useRef<HTMLTextAreaElement>(null)
const sendPrompt = useSendPrompt(opcodeUrl, directory)
@@ -84,11 +85,36 @@ export function PromptInput({
const { files: searchResults } = useFileSearch(
opcodeUrl,
fileQuery,
showFileSuggestions,
mentionQuery,
showMentionSuggestions,
directory
)
const { data: agents = [] } = useAgents(opcodeUrl, directory)
const mentionItems = useMemo((): MentionItem[] => {
const filteredAgents = filterAgentsByQuery(
agents.map(a => ({ name: a.name, description: a.description })),
mentionQuery
)
const agentItems: MentionItem[] = filteredAgents.map(agent => ({
type: 'agent',
value: agent.name,
label: agent.name,
description: agent.description
}))
const fileItems: MentionItem[] = searchResults.map(file => ({
type: 'file',
value: file,
label: getFilename(file),
description: file
}))
return [...agentItems, ...fileItems]
}, [agents, searchResults, mentionQuery])
const { addUserBashCommand } = useUserBash()
@@ -134,11 +160,12 @@ export function PromptInput({
sessionID,
parts,
model: currentModel,
agent: currentMode
agent: selectedAgent || currentMode
})
setPrompt('')
setAttachedFiles(new Map())
setSelectedAgent(null)
if (textareaRef.current) {
textareaRef.current.style.height = 'auto'
}
@@ -192,42 +219,56 @@ export function PromptInput({
}
}
const handleFileSelect = (filePath: string) => {
const handleMentionSelect = (item: MentionItem) => {
if (!mentionRange || !textareaRef.current) return
const filename = getFilename(filePath)
const beforeMention = prompt.slice(0, mentionRange.start)
const afterMention = prompt.slice(mentionRange.end)
const newPrompt = beforeMention + '@' + filename + ' ' + afterMention
setPrompt(newPrompt)
const absolutePath = filePath.startsWith('/')
? filePath
: directory
? `${directory}/${filePath}`
: filePath
setAttachedFiles(prev => {
const next = new Map(prev)
next.set(filename.toLowerCase(), {
path: absolutePath,
name: filename
if (item.type === 'agent') {
const newPrompt = beforeMention + '@' + item.value + ' ' + afterMention
setPrompt(newPrompt)
setSelectedAgent(item.value)
setTimeout(() => {
if (textareaRef.current) {
const newCursorPos = beforeMention.length + item.value.length + 2
textareaRef.current.focus()
textareaRef.current.setSelectionRange(newCursorPos, newCursorPos)
}
}, 0)
} else {
const filename = getFilename(item.value)
const newPrompt = beforeMention + '@' + filename + ' ' + afterMention
setPrompt(newPrompt)
const absolutePath = item.value.startsWith('/')
? item.value
: directory
? `${directory}/${item.value}`
: item.value
setAttachedFiles(prev => {
const next = new Map(prev)
next.set(filename.toLowerCase(), {
path: absolutePath,
name: filename
})
return next
})
return next
})
setTimeout(() => {
if (textareaRef.current) {
const newCursorPos = beforeMention.length + filename.length + 2
textareaRef.current.focus()
textareaRef.current.setSelectionRange(newCursorPos, newCursorPos)
}
}, 0)
}
setShowFileSuggestions(false)
setFileQuery('')
setShowMentionSuggestions(false)
setMentionQuery('')
setMentionRange(null)
setTimeout(() => {
if (textareaRef.current) {
const newCursorPos = beforeMention.length + filename.length + 2
textareaRef.current.focus()
textareaRef.current.setSelectionRange(newCursorPos, newCursorPos)
}
}, 0)
}
const handleModeToggle = () => {
@@ -243,33 +284,33 @@ export function PromptInput({
return
}
if (showFileSuggestions && searchResults.length > 0) {
if (showMentionSuggestions && mentionItems.length > 0) {
if (e.key === 'ArrowDown') {
e.preventDefault()
setSelectedFileIndex(prev =>
prev < searchResults.length - 1 ? prev + 1 : prev
setSelectedMentionIndex(prev =>
prev < mentionItems.length - 1 ? prev + 1 : prev
)
return
}
if (e.key === 'ArrowUp') {
e.preventDefault()
setSelectedFileIndex(prev => prev > 0 ? prev - 1 : 0)
setSelectedMentionIndex(prev => prev > 0 ? prev - 1 : 0)
return
}
if (e.key === 'Enter') {
e.preventDefault()
if (searchResults[selectedFileIndex]) {
handleFileSelect(searchResults[selectedFileIndex])
if (mentionItems[selectedMentionIndex]) {
handleMentionSelect(mentionItems[selectedMentionIndex])
}
return
}
if (e.key === 'Escape') {
e.preventDefault()
setShowFileSuggestions(false)
setFileQuery('')
setShowMentionSuggestions(false)
setMentionQuery('')
setMentionRange(null)
return
}
@@ -314,8 +355,8 @@ export function PromptInput({
} else if (e.key === 'Escape') {
setShowSuggestions(false)
setSuggestionQuery('')
setShowFileSuggestions(false)
setFileQuery('')
setShowMentionSuggestions(false)
setMentionQuery('')
setMentionRange(null)
setPrompt('')
if (textareaRef.current) {
@@ -353,10 +394,10 @@ export function PromptInput({
const mentionTrigger = detectMentionTrigger(value, cursorPosition)
if (mentionTrigger) {
setFileQuery(mentionTrigger.query)
setMentionQuery(mentionTrigger.query)
setMentionRange({ start: mentionTrigger.start, end: mentionTrigger.end })
setShowFileSuggestions(true)
setSelectedFileIndex(0)
setShowMentionSuggestions(true)
setSelectedMentionIndex(0)
} else {
const commandMatch = value.slice(0, cursorPosition).match(/(^|\s)\/([a-zA-Z0-9_-]*)$/)
@@ -370,9 +411,9 @@ export function PromptInput({
setSuggestionQuery('')
}
if (showFileSuggestions) {
setShowFileSuggestions(false)
setFileQuery('')
if (showMentionSuggestions) {
setShowMentionSuggestions(false)
setMentionQuery('')
setMentionRange(null)
}
}
@@ -483,7 +524,7 @@ export function PromptInput({
<span className="font-mono">Cmd/Ctrl+Enter</span> - Send message
</DropdownMenuItem>
<DropdownMenuItem disabled className="text-xs text-muted-foreground">
<span className="font-mono">@</span> - Mention files
<span className="font-mono">@</span> - Mention files or agents
</DropdownMenuItem>
<DropdownMenuItem disabled className="text-xs text-muted-foreground">
<span className="font-mono">!</span> - Bash command mode
@@ -529,16 +570,16 @@ export function PromptInput({
selectedIndex={selectedCommandIndex}
/>
<FileSuggestions
isOpen={showFileSuggestions}
files={searchResults}
onSelect={handleFileSelect}
<MentionSuggestions
isOpen={showMentionSuggestions}
items={mentionItems}
onSelect={handleMentionSelect}
onClose={() => {
setShowFileSuggestions(false)
setFileQuery('')
setShowMentionSuggestions(false)
setMentionQuery('')
setMentionRange(null)
}}
selectedIndex={selectedFileIndex}
selectedIndex={selectedMentionIndex}
/>
</div>
)
@@ -6,7 +6,7 @@ import { Button } from "@/components/ui/button";
import { Checkbox } from "@/components/ui/checkbox";
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from "@/components/ui/dropdown-menu";
import { DeleteSessionDialog } from "./DeleteSessionDialog";
import { Trash2, GitBranch, Clock, Search, MoreHorizontal } from "lucide-react";
import { Trash2, Clock, Search, MoreHorizontal } from "lucide-react";
import { formatDistanceToNow } from "date-fns";
interface SessionListProps {
@@ -35,10 +35,13 @@ export const SessionList = ({
const filteredSessions = useMemo(() => {
if (!sessions) return [];
if (!searchQuery.trim()) return sessions;
const rootSessions = sessions.filter((session) => !session.parentID);
if (!searchQuery.trim()) return rootSessions;
const query = searchQuery.toLowerCase();
return sessions.filter((session) =>
return rootSessions.filter((session) =>
(session.title || "Untitled Session").toLowerCase().includes(query),
);
}, [sessions, searchQuery]);
@@ -216,12 +219,6 @@ export const SessionList = ({
{session.title || "Untitled Session"}
</h3>
<div className="flex items-center gap-3 mt-1 text-xs text-muted-foreground">
{session.parentID && (
<span className="flex items-center gap-1">
<GitBranch className="w-3 h-3" />
Forked
</span>
)}
<span className="flex items-center gap-1">
<Clock className="w-3 h-3" />
{formatDistanceToNow(new Date(session.time.updated), {
@@ -12,7 +12,7 @@ import { CommandsEditor } from './CommandsEditor'
import { AgentsEditor } from './AgentsEditor'
import { McpManager } from './McpManager'
import { settingsApi } from '@/api/settings'
import { useMutation } from '@tanstack/react-query'
import { useMutation, useQueryClient } from '@tanstack/react-query'
interface OpenCodeConfig {
id: number
@@ -24,6 +24,7 @@ interface OpenCodeConfig {
}
export function OpenCodeConfigManager() {
const queryClient = useQueryClient()
const [configs, setConfigs] = useState<OpenCodeConfig[]>([])
const [isLoading, setIsLoading] = useState(true)
const [isUpdating, setIsUpdating] = useState(false)
@@ -44,6 +45,8 @@ export function OpenCodeConfigManager() {
},
onSuccess: (data) => {
console.log('OpenCode server restarted successfully:', data.message)
// Invalidate agents cache after server restart
queryClient.invalidateQueries({ queryKey: ['opencode', 'agents'] })
},
onError: (error) => {
console.error('Failed to restart OpenCode server:', error)
@@ -62,9 +65,11 @@ export function OpenCodeConfigManager() {
}
}
const updateConfigContent = async (configName: string, newContent: Record<string, unknown>) => {
const updateConfigContent = async (configName: string, newContent: Record<string, unknown>, restartServer = false) => {
try {
setIsUpdating(true)
const previousContent = configs.find(c => c.name === configName)?.content
await settingsApi.updateOpenCodeConfig(configName, { content: newContent })
// Update the local state
@@ -78,6 +83,15 @@ export function OpenCodeConfigManager() {
if (selectedConfig && selectedConfig.name === configName) {
setSelectedConfig({ ...selectedConfig, content: newContent, updatedAt: Date.now() })
}
// Auto-restart server if agents were modified
const agentsChanged = JSON.stringify(previousContent?.agent) !== JSON.stringify(newContent.agent)
if (restartServer || agentsChanged) {
restartServerMutation.mutate()
}
// Invalidate agents cache so @ mentions get updated
queryClient.invalidateQueries({ queryKey: ['opencode', 'agents'] })
} catch (error) {
console.error('Failed to update config:', error)
} finally {
@@ -115,6 +129,8 @@ export function OpenCodeConfigManager() {
setIsCreateDialogOpen(false)
fetchConfigs()
// Invalidate agents cache in case new config has agents
queryClient.invalidateQueries({ queryKey: ['opencode', 'agents'] })
} catch (error) {
console.error('Failed to create config:', error)
throw error
@@ -131,6 +147,8 @@ export function OpenCodeConfigManager() {
await settingsApi.deleteOpenCodeConfig(config.name)
setDeleteConfirmConfig(null)
fetchConfigs()
// Invalidate agents cache in case deleted config had agents
queryClient.invalidateQueries({ queryKey: ['opencode', 'agents'] })
} catch (error) {
console.error('Failed to delete config:', error)
} finally {
@@ -282,8 +300,15 @@ export function OpenCodeConfigManager() {
onClose={() => setIsEditDialogOpen(false)}
onUpdate={async (content) => {
if (!editingConfig) return
const agentsChanged = JSON.stringify(editingConfig.content.agent) !== JSON.stringify(content.agent)
await settingsApi.updateOpenCodeConfig(editingConfig.name, { content })
await fetchConfigs()
// Auto-restart server if agents were modified
if (agentsChanged) {
restartServerMutation.mutate()
}
// Invalidate agents cache so @ mentions get updated
queryClient.invalidateQueries({ queryKey: ['opencode', 'agents'] })
}}
isUpdating={isUpdating}
/>
@@ -0,0 +1,31 @@
import { Copy } from 'lucide-react'
interface CopyButtonProps {
content: string
title: string
className?: string
}
export function CopyButton({ content, title, className = "" }: CopyButtonProps) {
const handleCopy = async () => {
try {
await navigator.clipboard.writeText(content)
} catch (error) {
console.error('Failed to copy content:', error)
}
}
if (!content.trim()) {
return null
}
return (
<button
onClick={handleCopy}
className={`p-1.5 rounded bg-card hover:bg-card-hover text-muted-foreground hover:text-foreground ${className}`}
title={title}
>
<Copy className="w-4 h-4" />
</button>
)
}
+10
View File
@@ -442,3 +442,13 @@ export const useConfig = (opcodeUrl: string | null | undefined) => {
enabled: !!client,
});
};
export const useAgents = (opcodeUrl: string | null | undefined, directory?: string) => {
const client = useOpenCodeClient(opcodeUrl, directory);
return useQuery({
queryKey: ["opencode", "agents", opcodeUrl, directory],
queryFn: () => client!.listAgents(),
enabled: !!client,
});
};
+12
View File
@@ -9,6 +9,11 @@ export interface MentionTrigger {
query: string
}
export interface AgentInfo {
name: string
description?: string
}
export function detectMentionTrigger(
text: string,
cursorPosition: number
@@ -26,6 +31,13 @@ export function detectMentionTrigger(
}
}
export function filterAgentsByQuery(agents: AgentInfo[], query: string): AgentInfo[] {
const lowerQuery = query.toLowerCase()
return agents.filter(agent =>
agent.name.toLowerCase().includes(lowerQuery)
)
}
export function parsePromptToParts(
rawInput: string,
fileMap: Map<string, FileInfo>
+13
View File
@@ -128,6 +128,16 @@ export function SessionDetail() {
setSelectedFilePath(undefined)
}, []);
const handleChildSessionClick = useCallback((childSessionId: string) => {
navigate(`/repos/${repoId}/sessions/${childSessionId}`)
}, [navigate, repoId]);
const handleParentSessionClick = useCallback(() => {
if (session?.parentID) {
navigate(`/repos/${repoId}/sessions/${session.parentID}`)
}
}, [navigate, repoId, session?.parentID]);
const handlePermissionResponse = useCallback(async (
permissionID: string,
permissionSessionID: string,
@@ -186,9 +196,11 @@ export function SessionDetail() {
isReconnecting={isReconnecting}
opcodeUrl={opcodeUrl}
repoDirectory={repoDirectory}
parentSessionId={session?.parentID}
onFileBrowserOpen={() => setFileBrowserOpen(true)}
onSettingsOpen={openSettings}
onSessionTitleUpdate={handleSessionTitleUpdate}
onParentSessionClick={handleParentSessionClick}
/>
<div className="flex-1 overflow-hidden flex flex-col relative">
@@ -202,6 +214,7 @@ export function SessionDetail() {
directory={repoDirectory}
messages={messages}
onFileClick={handleFileClick}
onChildSessionClick={handleChildSessionClick}
/>
) : null}
</div>