import { useState, useRef, useEffect, useMemo, memo } from 'react' import { unwrapSandboxExecCommand } from '@opencode-manager/shared/utils' import { toolContentText, type SessionMessageAssistantTool } from '@opencode-manager/shared/opencode' import { useSettings } from '@/hooks/useSettings' import { useUserBash } from '@/stores/userBashStore' import { useChildLifecycleForSession } from '@/stores/sessionStatusStore' import { useToolCallPermission } from '@/contexts/EventContext' import { useChildSessionReconciliation } from '@/hooks/useOpenCode' import { useShell } from '@/hooks/useSessionShells' import { detectFileReferences } from '@/lib/fileReferences' import { ExternalLink, Loader2, Shield } from 'lucide-react' import { Badge } from '@/components/ui/badge' import { Button } from '@/components/ui/button' import { CopyButton } from '@/components/ui/copy-button' import { BackgroundTaskStatusIcon } from '@/components/session/BackgroundTaskStatusIcon' import { backgroundChildSessionID, backgroundShellID, backgroundTaskStatusColor, isRunningLifecycle, lifecycleLabel, shellToolLifecycle, subagentLifecycle, subagentSessionID, toolMetadata, type BackgroundTaskLifecycle, type ShellNoticeOutcome, } from '@/lib/backgroundWork' import { getToolInputPath, getToolSpecificRender } from './FileToolRender' import { readOpenWalkthroughCall } from '@/lib/walkthroughTool' import type { WalkthroughSource } from '@opencode-manager/shared/schemas' const DISPLAY_LIMIT = 30_000 const DISPLAY_HEAD_LENGTH = 20_000 const DISPLAY_TAIL_LENGTH = 10_000 function formatOmittedSize(size: number): string { return size < 1024 * 1024 ? `${(size / 1024).toFixed(1)} KB` : `${(size / (1024 * 1024)).toFixed(1)} MB` } function clampDisplayText(text: string): string { if (text.length <= DISPLAY_LIMIT) return text const headCut = text.lastIndexOf('\n', DISPLAY_HEAD_LENGTH) const head = headCut === -1 ? text.slice(0, DISPLAY_HEAD_LENGTH) : text.slice(0, headCut) const tailFrom = text.length - DISPLAY_TAIL_LENGTH const tailCut = text.indexOf('\n', tailFrom) const tail = tailCut === -1 ? text.slice(tailFrom) : text.slice(tailCut + 1) const omitted = formatOmittedSize(text.length - head.length - tail.length) const marker = `\n[… ${omitted} omitted — use the copy button for the full output …]\n` return head + marker + tail } function BoundedPre({ content, className }: { content: string; className: string }) { const clamped = useMemo(() => clampDisplayText(content), [content]) return
{clamped}
} interface ToolCallPartProps { part: SessionMessageAssistantTool messageID?: string directory?: string shellOutcome?: ShellNoticeOutcome onFileClick?: (filePath: string, lineNumber?: number) => void onChildSessionClick?: (sessionId: string) => void onOpenWalkthrough?: (source?: WalkthroughSource) => void } function toolInput(part: SessionMessageAssistantTool): Record | undefined { if (part.state.status === 'streaming') return undefined return part.state.input } function toolOutputText(part: SessionMessageAssistantTool): string { if (part.state.status === 'streaming') return '' return toolContentText(part.state.status === 'running' ? undefined : part.state.content) } function ClickableJson({ json, onFileClick }: { json: unknown; onFileClick?: (filePath: string) => void }) { const jsonString = useMemo(() => JSON.stringify(json, null, 2), [json]) const references = useMemo(() => detectFileReferences(jsonString), [jsonString]) if (references.length === 0) { return
{jsonString}
} const parts: React.ReactNode[] = [] let lastIndex = 0 references.forEach((ref, index) => { if (ref.startIndex > lastIndex) { parts.push(jsonString.slice(lastIndex, ref.startIndex)) } parts.push( { e.stopPropagation() onFileClick?.(ref.filePath) }} className="text-primary hover:text-primary-hover cursor-pointer underline decoration-dotted" title={`Click to open ${ref.filePath}`} > {ref.fullMatch} ) lastIndex = ref.endIndex }) if (lastIndex < jsonString.length) { parts.push(jsonString.slice(lastIndex)) } return
{parts}
} export const ToolCallPart = memo(function ToolCallPart({ part, messageID, directory, shellOutcome, onFileClick, onChildSessionClick, onOpenWalkthrough }: ToolCallPartProps) { const { preferences } = useSettings() const { userBashCommands } = useUserBash() const isSubagent = part.name === 'subagent' const subagentSessionId = isSubagent ? subagentSessionID(part) : undefined const backgroundSubagent = isSubagent ? backgroundChildSessionID(part) : undefined const subagentSessionLifecycle = useChildLifecycleForSession(subagentSessionId) useChildSessionReconciliation( subagentSessionId && (backgroundSubagent !== undefined || part.state.status === 'running') ? subagentSessionId : undefined, ) const subagentStatus = subagentLifecycle( part.state.status, backgroundSubagent !== undefined, subagentSessionLifecycle, ) const backgroundShell = part.name === 'shell' ? backgroundShellID(part) : undefined const { shell, listLoaded: shellListLoaded } = useShell(backgroundShell, directory) const shellStatus = shellToolLifecycle(backgroundShell, shell, shellListLoaded, shellOutcome) const isBackgroundShell = backgroundShell !== undefined const isBackgroundShellRunning = isBackgroundShell && isRunningLifecycle(shellStatus) const pendingPermission = useToolCallPermission(part.id, messageID) const isWaitingPermission = part.state.status === 'running' && pendingPermission !== null const outputRef = useRef(null) const input = toolInput(part) const openWalkthrough = readOpenWalkthroughCall(part) const rawCommand = part.name === 'shell' && typeof input?.command === 'string' ? input.command : undefined const displayCommand = useMemo( () => (rawCommand === undefined ? undefined : unwrapSandboxExecCommand(rawCommand)), [rawCommand] ) const isSandboxedCommand = part.state.status === 'completed' && (toolMetadata(part).sandbox === true || (rawCommand !== undefined && displayCommand !== rawCommand)) const isUserBashCommand = part.state.status === 'completed' && typeof displayCommand === 'string' && userBashCommands.has(displayCommand) const [expanded, setExpanded] = useState(isUserBashCommand || (preferences?.expandToolCalls ?? false)) useEffect(() => { if (part.name === 'shell' && expanded && outputRef.current) { outputRef.current.scrollIntoView({ behavior: 'smooth', block: 'nearest' }) } }, [expanded, part.name]) const getStatusColor = () => { if (isBackgroundShell) return backgroundTaskStatusColor(shellStatus) switch (part.state.status) { case 'completed': return 'text-success' case 'error': return 'text-destructive' case 'running': if (isWaitingPermission) return 'text-highlight' return 'text-warning' default: return 'text-muted-foreground' } } const renderShellLifecycleIcon = (status: BackgroundTaskLifecycle) => ( ) const getStatusIcon = () => { if (isBackgroundShell) return renderShellLifecycleIcon(shellStatus) switch (part.state.status) { case 'completed': return ✓ case 'error': return ✗ case 'running': return case 'streaming': return default: return ○ } } const getPreviewText = () => { if (!input) return null switch (part.name) { case 'read': case 'write': case 'edit': case 'patch': return getToolInputPath(input) ?? null case 'shell': return displayCommand || null case 'glob': case 'grep': return (input.pattern as string) || null case 'subagent': return (input.description as string) || null case 'webfetch': return (input.url as string) || null case 'websearch': return (input.query as string) || null default: return null } } const previewText = getPreviewText() const isFileTool = ['read', 'write', 'edit', 'patch'].includes(part.name) const isBackgroundSubagent = backgroundSubagent !== undefined const isBackgroundSubagentRunning = isBackgroundSubagent && isRunningLifecycle(subagentStatus) const isBackgrounded = isBackgroundShell ? isBackgroundShellRunning : isBackgroundSubagentRunning const backgroundIndicator = isBackgrounded ? ( background ) : null const sandboxIndicator = isSandboxedCommand ? ( sandbox ) : null if (isSubagent) { const status = part.state.status const isRunning = status !== 'streaming' && isRunningLifecycle(subagentStatus) const isCompleted = subagentStatus === 'completed' const isError = subagentStatus === 'failed' const description = previewText || 'Sub-agent task' const content = (
{status === 'streaming' && (
)} {isRunning && (
)} {isCompleted && ✓} {isError && ✗} {description} sub-agent {backgroundIndicator} {subagentSessionId && }
) if (subagentSessionId) { return ( ) } return (
{content}
) } const toolSpecificRender = getToolSpecificRender(part, onFileClick) if (toolSpecificRender) { return toolSpecificRender } if (isUserBashCommand) { const command = displayCommand ?? '' const output = toolOutputText(part) const ran = part.state.status === 'streaming' ? undefined : part.state.status === 'running' ? undefined : part.time.ran const completed = part.state.status === 'streaming' ? undefined : part.state.status === 'running' ? undefined : part.time.completed return (
{isBackgroundShell ? renderShellLifecycleIcon(shellStatus) : ✓} $ {command} {sandboxIndicator} {backgroundIndicator} {ran !== undefined && completed !== undefined && ( {((completed - ran) / 1000).toFixed(2)}s )}
) } const getBorderStyle = () => { switch (part.state.status) { case 'running': if (isWaitingPermission) return 'border-highlight/50 shadow-sm shadow-highlight/20' return 'border-warning/50 shadow-sm shadow-warning/10' case 'streaming': return 'border-primary/30' case 'error': return 'border-destructive/30' case 'completed': return 'border-border' default: return 'border-border' } } const output = toolOutputText(part) return (
{openWalkthrough ? ( ) : null}
{expanded && (
{part.state.status === 'streaming' && (
Preparing tool call...
)} {part.state.status === 'running' && ( part.name === 'shell' ? (
Command:
$ {displayCommand ?? ''}
{isWaitingPermission ? 'Waiting for permission...' : 'Running...'}
) : (
Input:
{isWaitingPermission ? 'Waiting for permission...' : 'Running...'}
) )} {part.state.status === 'completed' && ( <> {part.name === 'shell' ? (
Command:
$ {displayCommand ?? ''}
) : (
Input:
)} {output && (
Output:
)} {part.time.ran !== undefined && part.time.completed !== undefined && (
Duration: {((part.time.completed - part.time.ran) / 1000).toFixed(2)}s
)} )} {part.state.status === 'error' && (
Error:
)}
)}
) })