diff --git a/frontend/src/components/message/ExecuteToolPart.tsx b/frontend/src/components/message/ExecuteToolPart.tsx new file mode 100644 index 00000000..3f249dd0 --- /dev/null +++ b/frontend/src/components/message/ExecuteToolPart.tsx @@ -0,0 +1,331 @@ +import { memo, useMemo, useState } from 'react' +import ReactMarkdown from 'react-markdown' +import { Loader2 } from 'lucide-react' +import { toolContentText, type SessionMessageAssistantTool } from '@opencode-manager/shared/opencode' +import { useSettings } from '@/hooks/useSettings' +import { toolMetadata } from '@/lib/backgroundWork' +import { clampDisplayText } from '@/lib/clampDisplayText' +import { markdownRehypePlugins } from '@/lib/markdownRehypePlugins' +import { CopyButton } from '@/components/ui/copy-button' +import { FileReferenceText } from './FileReferenceText' + +type ExecuteCallStatus = 'running' | 'completed' | 'error' + +interface ExecuteCall { + tool: string + status: ExecuteCallStatus + input?: Record +} + +interface ExecuteToolPartProps { + part: SessionMessageAssistantTool + isWaitingPermission: boolean + onFileClick?: (filePath: string) => void +} + +interface ParsedOutput { + json: string + rest?: string +} + +const OUTPUT_TAIL_PATTERN = /\n\n(Warnings|Logs):\n/ + +function isRecord(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +function executeCalls(value: unknown): ExecuteCall[] { + if (!Array.isArray(value)) return [] + return value.flatMap((call) => { + if (!isRecord(call)) return [] + const tool = call.tool + const status = call.status + if (typeof tool !== 'string') return [] + if (status !== 'running' && status !== 'completed' && status !== 'error') return [] + return [{ tool, status, input: isRecord(call.input) ? call.input : undefined }] + }) +} + +function primitiveInputSummary(input: Record): string { + const entries = Object.entries(input).filter(([, value]) => ( + typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean' + )) + if (entries.length === 0) return '' + return `[${entries.map(([key, value]) => `${key}=${String(value)}`).join(', ')}]` +} + +function executeCallSummary(call: ExecuteCall): string { + const args = primitiveInputSummary(call.input ?? {}).replace(/\s+/g, ' ') + return `${call.tool}${args ? ` ${args}` : ''}` +} + +function executeCode(part: SessionMessageAssistantTool): string | undefined { + if (part.state.status === 'streaming') return undefined + const code = part.state.input.code + return typeof code === 'string' && code ? code : undefined +} + +function executeOutputText(part: SessionMessageAssistantTool): string { + if (part.state.status === 'error') return part.state.error.message.trim() + if (part.state.status !== 'completed') return '' + return toolContentText(part.state.content).trim() +} + +function parseOutput(text: string): ParsedOutput | undefined { + if (!text.startsWith('{') && !text.startsWith('[')) return undefined + const tail = text.search(OUTPUT_TAIL_PATTERN) + const json = tail === -1 ? text : text.slice(0, tail) + try { + JSON.parse(json) + } catch { + return undefined + } + return { json, rest: tail === -1 ? undefined : text.slice(json.length).trim() || undefined } +} + +function trimTrailingNewlines(text: string): string { + return text.replace(/\n+$/, '') +} + +function lineCount(text: string | undefined): number { + return text ? trimTrailingNewlines(text).split('\n').length : 0 +} + +function formatDuration(ms: number): string { + if (ms < 1000) return `${Math.max(0, Math.round(ms))}ms` + return `${(ms / 1000).toFixed(2)}s` +} + +function longestBacktickRun(text: string): number { + const runs = text.match(/`+/g) ?? [] + return runs.reduce((longest, run) => Math.max(longest, run.length), 0) +} + +const HighlightedCode = memo(function HighlightedCode({ + content, + language, + digits, +}: { + content: string + language: 'ts' | 'json' + digits: number +}) { + const body = trimTrailingNewlines(content) + const markdown = useMemo(() => { + const fence = '`'.repeat(Math.max(3, longestBacktickRun(body) + 1)) + return `${fence}${language}\n${body}\n${fence}` + }, [body, language]) + const gutter = useMemo( + () => body.split('\n').map((_, index) => String(index + 1)).join('\n'), + [body], + ) + + return ( +
+
+ {gutter} +
+
+ {markdown} +
+
+ ) +}) + +function ExecuteCallRow({ call, onFileClick }: { call: ExecuteCall; onFileClick?: (filePath: string) => void }) { + const [expanded, setExpanded] = useState(false) + const entries = Object.entries(call.input ?? {}) + const expandable = entries.length > 0 + const isError = call.status === 'error' + const color = isError ? 'text-destructive' : 'text-muted-foreground' + + const summary = ( + <> + {isError ? '✗' : '›'} + {executeCallSummary(call)} + + ) + + return ( +
+ {expandable ? ( + + ) : ( +
{summary}
+ )} + {expanded && ( +
+ {entries.map(([key, value]) => ( +
+ {key}: + + + +
+ ))} +
+ )} +
+ ) +} + +export function ExecuteToolPart({ part, isWaitingPermission, onFileClick }: ExecuteToolPartProps) { + const { preferences } = useSettings() + const [expanded, setExpanded] = useState(preferences?.expandToolCalls ?? false) + const metadata = toolMetadata(part) + const calls = executeCalls(metadata.toolCalls) + const code = executeCode(part) + const output = executeOutputText(part) + const displayOutput = useMemo(() => clampDisplayText(output), [output]) + const parsedOutput = useMemo( + () => (displayOutput === output ? parseOutput(output) : undefined), + [displayOutput, output], + ) + const failed = part.state.status === 'error' || metadata.error === true + const status = part.state.status + + const statusLabel = (() => { + if (status === 'streaming') return 'Receiving code…' + if (isWaitingPermission) return 'awaiting permission' + if (status === 'running') return 'Running' + const duration = part.time.completed !== undefined + ? ` · ${formatDuration(part.time.completed - (part.time.ran ?? part.time.created))}` + : '' + return `${failed ? 'Failed' : 'Completed'}${duration}` + })() + + const statusColor = (() => { + if (status === 'error') return 'text-destructive' + if (status === 'running') return isWaitingPermission ? 'text-highlight' : 'text-warning' + if (failed) return 'text-destructive' + if (status === 'completed') return 'text-success' + return 'text-muted-foreground' + })() + + const statusIcon = (() => { + if (status === 'streaming') { + return + } + if (status === 'running') return + if (failed) return ✗ + if (status === 'completed') return ✓ + return ○ + })() + + const borderStyle = status === 'running' + ? isWaitingPermission + ? 'border-highlight/50 shadow-sm shadow-highlight/20' + : 'border-warning/50 shadow-sm shadow-warning/10' + : status === 'streaming' + ? 'border-primary/30' + : failed + ? 'border-destructive/30' + : 'border-border' + + const digits = String(Math.max(lineCount(code), lineCount(parsedOutput?.json), 1)).length + const errorPreview = failed && output ? output.split('\n').slice(0, 4) : [] + + return ( +
+
+ +
+ + {calls.length > 0 && ( +
+ {calls.map((call, index) => ( + + ))} +
+ )} + + {!expanded && errorPreview.length > 0 && ( +
+ {errorPreview.map((line, index) => ( +
+ {index === 0 ? `↳ ${line}` : ` ${line}`} +
+ ))} +
+ )} + + {expanded && ( +
+
+
Code
+ {code ? ( + + ) : ( +
Waiting for code…
+ )} +
+ +
+
Output
+ {parsedOutput ? ( + <> + + {parsedOutput.rest && ( +
+                    {parsedOutput.rest}
+                  
+ )} + + ) : displayOutput ? ( +
+                {displayOutput}
+              
+ ) : ( +
+ {status === 'completed' ? 'No output' : 'Waiting for output…'} +
+ )} +
+ +
+ {code && ( +
+ + Copy code +
+ )} + {output && ( +
+ + Copy output +
+ )} +
+
+ )} +
+ ) +} diff --git a/frontend/src/components/message/FileReferenceText.tsx b/frontend/src/components/message/FileReferenceText.tsx new file mode 100644 index 00000000..a1a9e9e2 --- /dev/null +++ b/frontend/src/components/message/FileReferenceText.tsx @@ -0,0 +1,47 @@ +import { useMemo, type ReactNode } from 'react' +import { detectFileReferences } from '@/lib/fileReferences' + +interface FileReferenceTextProps { + text: string + onFileClick?: (filePath: string) => void +} + +export function FileReferenceText({ text, onFileClick }: FileReferenceTextProps) { + const parts = useMemo(() => { + const references = detectFileReferences(text) + if (references.length === 0) return text + + const segments: ReactNode[] = [] + let lastIndex = 0 + + references.forEach((ref, index) => { + if (ref.startIndex > lastIndex) { + segments.push(text.slice(lastIndex, ref.startIndex)) + } + + segments.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 < text.length) { + segments.push(text.slice(lastIndex)) + } + + return segments + }, [text, onFileClick]) + + return <>{parts} +} diff --git a/frontend/src/components/message/ToolCallPart.test.tsx b/frontend/src/components/message/ToolCallPart.test.tsx index 87e752d3..fe148a98 100644 --- a/frontend/src/components/message/ToolCallPart.test.tsx +++ b/frontend/src/components/message/ToolCallPart.test.tsx @@ -292,6 +292,143 @@ describe('ToolCallPart background indicator', () => { }) }) +describe('ToolCallPart execute renderer', () => { + beforeEach(() => { + vi.clearAllMocks() + mocks.useSettings.mockReturnValue({ + preferences: { expandToolCalls: false }, + isLoading: false, + updateSettings: vi.fn(), + isUpdating: false, + }) + mocks.useToolCallPermission.mockReturnValue(null) + }) + + const completedExecute = ( + metadata: Record, + text = '{"windows":[{"title":"Untitled"}]}', + ): SessionMessageAssistantTool => ({ + type: 'tool', + id: 'call_exec', + name: 'execute', + time: { created: 1, ran: 2, completed: 3 }, + state: { + status: 'completed', + input: { + code: 'const result = await tools.listWindows({ app: "TextEdit" })\nconsole.log(result)', + }, + content: [{ type: 'text', text }], + metadata, + }, + }) + + const childCalls = [ + { tool: 'cua-driver.list_windows', status: 'completed', input: { app: 'TextEdit' } }, + { tool: 'cua-driver.click', status: 'error', input: { x: 10 } }, + ] + + it('lists child calls while collapsed and marks errors', () => { + renderWithProviders() + + expect(screen.getByText('cua-driver.list_windows [app=TextEdit]')).toBeInTheDocument() + expect(screen.getByText('cua-driver.click [x=10]')).toBeInTheDocument() + expect(screen.getByText('✗')).toBeInTheDocument() + }) + + it('renders line-numbered code and output sections when expanded', () => { + mocks.useSettings.mockReturnValue({ + preferences: { expandToolCalls: true }, + isLoading: false, + updateSettings: vi.fn(), + isUpdating: false, + }) + + const { container } = renderWithProviders( + , + ) + + expect(screen.getByText('Code')).toBeInTheDocument() + expect(screen.getByText('Output')).toBeInTheDocument() + expect(container.querySelector('code.language-ts')?.textContent).toContain('const result = await tools.listWindows') + expect(container.querySelector('code.language-json')?.textContent).toContain('"windows"') + + const gutters = screen.getAllByTestId('execute-line-numbers') + expect(gutters[0].textContent).toBe('1\n2') + expect(gutters[1].textContent).toBe('1') + expect(gutters[0].style.width).toBe(gutters[1].style.width) + }) + + it('reports a completed script that failed at runtime', () => { + renderWithProviders( + , + ) + + expect(screen.getByText(/Failed/)).toBeInTheDocument() + expect(screen.getByText('↳ Error: tool not found')).toBeInTheDocument() + expect(screen.queryByText('Completed')).not.toBeInTheDocument() + }) + + const runningExecute = (): SessionMessageAssistantTool => ({ + type: 'tool', + id: 'call_exec', + name: 'execute', + time: { created: 1, ran: 2 }, + state: { + status: 'running', + input: { code: 'await tools.listWindows({ app: "TextEdit" })' }, + metadata: {}, + }, + }) + + it('shows the waiting permission state while the script awaits permission', () => { + mocks.useToolCallPermission.mockReturnValue( + permissionFor({ type: 'tool', messageID: 'msg_1', id: 'call_exec' }), + ) + + renderWithProviders() + + expect(screen.getByText('awaiting permission')).toBeInTheDocument() + expect(screen.queryByText('Running')).not.toBeInTheDocument() + }) + + it('toggles aria-expanded on the header button', () => { + renderWithProviders() + + const header = screen.getByRole('button', { name: /execute/ }) + expect(header).toHaveAttribute('aria-expanded', 'false') + + fireEvent.click(header) + + expect(header).toHaveAttribute('aria-expanded', 'true') + }) + + it('opens a file reference from an expanded child call input', () => { + const onFileClick = vi.fn() + const part: SessionMessageAssistantTool = { + type: 'tool', + id: 'call_exec', + name: 'execute', + time: { created: 1, ran: 2, completed: 3 }, + state: { + status: 'completed', + input: { code: 'await tools.read({ path: "src/app.ts" })' }, + content: [{ type: 'text', text: 'read ok' }], + metadata: { toolCalls: [{ tool: 'read', status: 'completed', input: { path: 'src/app.ts' } }] }, + }, + } + + renderWithProviders() + + fireEvent.click(screen.getByRole('button', { name: /read \[path=src\/app.ts\]/ })) + fireEvent.click(screen.getByTitle('Click to open src/app.ts')) + + expect(onFileClick).toHaveBeenCalledWith('src/app.ts') + }) +}) + describe('ToolCallPart open walkthrough action', () => { beforeEach(() => { vi.clearAllMocks() diff --git a/frontend/src/components/message/ToolCallPart.tsx b/frontend/src/components/message/ToolCallPart.tsx index 0e435e91..1d6fe497 100644 --- a/frontend/src/components/message/ToolCallPart.tsx +++ b/frontend/src/components/message/ToolCallPart.tsx @@ -7,7 +7,7 @@ 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 { clampDisplayText } from '@/lib/clampDisplayText' import { ExternalLink, Loader2, Shield } from 'lucide-react' import { Badge } from '@/components/ui/badge' import { Button } from '@/components/ui/button' @@ -32,30 +32,10 @@ import { readShowArtifactCall } from '@/lib/artifactTool' import { getWorkspaceFilePath } from '@/lib/markdownLinks' import { getFileApiUrl } from '@/api/files' import { ArtifactPart } from './ArtifactPart' +import { ExecuteToolPart } from './ExecuteToolPart' +import { FileReferenceText } from './FileReferenceText' 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}
@@ -85,42 +65,12 @@ function toolOutputText(part: SessionMessageAssistantTool): string { 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}
+ return ( +
+      
+    
+ ) } export const ToolCallPart = memo(function ToolCallPart({ part, messageID, directory, repoFullPath, repoLocalPath, shellOutcome, onFileClick, onChildSessionClick, onOpenWalkthrough }: ToolCallPartProps) { @@ -327,6 +277,10 @@ export const ToolCallPart = memo(function ToolCallPart({ part, messageID, direct ) } + if (part.name === 'execute') { + return + } + const toolSpecificRender = getToolSpecificRender(part, onFileClick) if (toolSpecificRender) { return toolSpecificRender diff --git a/frontend/src/lib/clampDisplayText.test.ts b/frontend/src/lib/clampDisplayText.test.ts new file mode 100644 index 00000000..3a432899 --- /dev/null +++ b/frontend/src/lib/clampDisplayText.test.ts @@ -0,0 +1,24 @@ +import { describe, it, expect } from 'vitest' +import { clampDisplayText } from './clampDisplayText' + +const line = (index: number) => `line ${index} ${'x'.repeat(20)}` + +describe('clampDisplayText', () => { + it('returns short text unchanged', () => { + const text = 'short output\nwith two lines' + + expect(clampDisplayText(text)).toBe(text) + }) + + it('shortens text over the display limit while keeping the head and tail', () => { + const lines = Array.from({ length: 2000 }, (_, index) => line(index)) + const text = lines.join('\n') + + const clamped = clampDisplayText(text) + + expect(clamped.length).toBeLessThan(text.length) + expect(clamped).toContain('omitted — use the copy button') + expect(clamped.startsWith(lines[0])).toBe(true) + expect(clamped.endsWith(lines[lines.length - 1])).toBe(true) + }) +}) diff --git a/frontend/src/lib/clampDisplayText.ts b/frontend/src/lib/clampDisplayText.ts new file mode 100644 index 00000000..d846c6e6 --- /dev/null +++ b/frontend/src/lib/clampDisplayText.ts @@ -0,0 +1,21 @@ +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` +} + +export 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 +}