Files
opencode-manager/frontend/src/components/message/ToolCallPart.tsx
T

261 lines
9.0 KiB
TypeScript

import { useState, useRef, useEffect } from 'react'
import type { components } from '@/api/opencode-types'
import { useSettings } from '@/hooks/useSettings'
import { useUserBash } from '@/stores/userBashStore'
import { detectFileReferences } from '@/lib/fileReferences'
import { Copy } from 'lucide-react'
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>
)
}
type ToolPart = components['schemas']['ToolPart']
interface ToolCallPartProps {
part: ToolPart
onFileClick?: (filePath: string, lineNumber?: number) => void
}
function ClickableJson({ json, onFileClick }: { json: unknown; onFileClick?: (filePath: string) => void }) {
const jsonString = JSON.stringify(json, null, 2)
const references = detectFileReferences(jsonString)
if (references.length === 0) {
return <pre className="bg-accent p-2 rounded text-xs overflow-x-auto">{jsonString}</pre>
}
const parts: React.ReactNode[] = []
let lastIndex = 0
references.forEach((ref, index) => {
if (ref.startIndex > lastIndex) {
parts.push(jsonString.slice(lastIndex, ref.startIndex))
}
parts.push(
<span
key={`ref-${index}`}
onClick={(e) => {
e.stopPropagation()
onFileClick?.(ref.filePath)
}}
className="text-blue-600 dark:text-blue-400 hover:text-blue-700 dark:hover:text-blue-300 cursor-pointer underline decoration-dotted"
title={`Click to open ${ref.filePath}`}
>
{ref.fullMatch}
</span>
)
lastIndex = ref.endIndex
})
if (lastIndex < jsonString.length) {
parts.push(jsonString.slice(lastIndex))
}
return <pre className="bg-accent p-2 rounded text-xs overflow-x-auto">{parts}</pre>
}
export function ToolCallPart({ part, onFileClick }: ToolCallPartProps) {
const { preferences } = useSettings()
const { userBashCommands } = useUserBash()
const outputRef = useRef<HTMLDivElement>(null)
const isUserBashCommand = part.tool === 'bash' &&
part.state.status === 'completed' &&
typeof part.state.input?.command === 'string' &&
userBashCommands.has(part.state.input.command)
const defaultExpanded = isUserBashCommand || (preferences?.expandToolCalls ?? false)
const [expanded, setExpanded] = useState(defaultExpanded)
useEffect(() => {
if (part.tool === 'bash' && expanded && outputRef.current) {
outputRef.current.scrollIntoView({ behavior: 'smooth', block: 'start' })
}
}, [expanded, part.tool])
const getStatusColor = () => {
switch (part.state.status) {
case 'completed':
return 'text-green-600 dark:text-green-400'
case 'error':
return 'text-red-600 dark:text-red-400'
case 'running':
return 'text-yellow-600 dark:text-yellow-400'
default:
return 'text-muted-foreground'
}
}
const getStatusIcon = () => {
switch (part.state.status) {
case 'completed':
return '✓'
case 'error':
return '✗'
case 'running':
return '⟳'
default:
return '○'
}
}
const getPreviewText = () => {
if (part.state.status === 'pending') return null
const input = part.state.input as Record<string, unknown>
if (!input) return null
switch (part.tool) {
case 'read':
case 'write':
case 'edit':
return (input.filePath as string) || null
case 'bash':
return (input.command as string) || null
case 'glob':
return (input.pattern as string) || null
case 'grep':
return (input.pattern as string) || null
case 'list':
return (input.path as string) || '.'
case 'task':
return (input.description as string) || null
default:
return null
}
}
const previewText = getPreviewText()
const isFileTool = ['read', 'write', 'edit'].includes(part.tool)
if (isUserBashCommand) {
const command = part.state.input.command as string
const output = part.state.status === 'completed' ? part.state.output : ''
return (
<div ref={outputRef} className="my-2">
<div className="flex items-center gap-2 text-sm mb-2">
<span className="text-green-600 dark:text-green-400">✓</span>
<span className="font-medium">$</span>
<span className="text-foreground">{command}</span>
{part.state.status === 'completed' && part.state.time && (
<span className="text-muted-foreground text-xs ml-auto">
{((part.state.time.end - part.state.time.start) / 1000).toFixed(2)}s
</span>
)}
</div>
<pre className="bg-accent p-3 rounded text-xs overflow-x-auto whitespace-pre-wrap cursor-pointer hover:bg-accent/80 transition-colors"
onClick={() => navigator.clipboard.writeText(output)}
title="Click to copy output">
{output}
</pre>
</div>
)
}
return (
<div className="border border-border rounded-lg overflow-hidden my-2">
<button
onClick={() => setExpanded(!expanded)}
className="w-full px-4 py-2 bg-card hover:bg-card-hover text-left flex items-center gap-2 text-sm min-w-0"
>
<span className={getStatusColor()}>{getStatusIcon()}</span>
<span className="font-medium">{part.tool}</span>
{previewText && isFileTool ? (
<span
onClick={(e) => {
e.stopPropagation()
if (onFileClick) {
onFileClick(previewText)
}
}}
className="text-blue-600 dark:text-blue-400 text-xs truncate hover:text-blue-700 dark:hover:text-blue-300 cursor-pointer underline decoration-dotted"
title={`Click to open ${previewText}`}
>
{previewText}
</span>
) : previewText ? (
<span className="text-muted-foreground text-xs truncate">{previewText}</span>
) : null}
<span className="text-muted-foreground text-xs ml-auto">({part.state.status})</span>
</button>
{expanded && (
<div className="bg-card space-y-2">
{part.state.status === 'running' && (
<div className="text-sm">
<div className="text-zinc-400 mb-1">Input:</div>
<ClickableJson json={part.state.input} onFileClick={onFileClick} />
</div>
)}
{part.state.status === 'completed' && (
<>
{part.tool === 'bash' ? (
<div className="text-sm">
<div className="flex items-center gap-2 mb-1">
<div className="text-muted-foreground">Command:</div>
<CopyButton
content={typeof part.state.input?.command === 'string' ? part.state.input.command : ''}
title="Copy command"
/>
</div>
<div className="bg-accent p-2 rounded text-xs overflow-x-auto">
<span className="text-green-600 dark:text-green-400">$</span> {typeof part.state.input?.command === 'string' ? part.state.input.command : ''}
</div>
</div>
) : (
<div className="text-sm">
<div className="text-muted-foreground mb-1">Input:</div>
<ClickableJson json={part.state.input} onFileClick={onFileClick} />
</div>
)}
<div className="text-sm" ref={outputRef}>
<div className="text-muted-foreground mb-1">Output:</div>
<pre className="bg-accent p-2 rounded text-xs overflow-x-auto whitespace-pre-wrap cursor-pointer hover:bg-accent/80 transition-colors"
onClick={() => part.state.status === 'completed' && navigator.clipboard.writeText(part.state.output)}
title="Click to copy output">
{part.state.status === 'completed' ? part.state.output : ''}
</pre>
</div>
{part.state.time && (
<div className="text-xs text-muted-foreground">
Duration: {((part.state.time.end - part.state.time.start) / 1000).toFixed(2)}s
</div>
)}
</>
)}
{part.state.status === 'error' && (
<div className="text-sm">
<div className="text-red-600 dark:text-red-400 mb-1">Error:</div>
<pre className="bg-accent p-2 rounded text-xs overflow-x-auto text-red-600 dark:text-red-300">
{part.state.error}
</pre>
</div>
)}
</div>
)}
</div>
)
}