diff --git a/frontend/eslint.config.js b/frontend/eslint.config.js index 926b5140..26bf0810 100644 --- a/frontend/eslint.config.js +++ b/frontend/eslint.config.js @@ -30,7 +30,7 @@ export default defineConfig([ }, }, { - files: ['src/components/ui/**/*.{ts,tsx}', 'src/components/message/FileToolRender.tsx'], + files: ['src/components/ui/**/*.{ts,tsx}', 'src/components/message/FileToolRender.tsx', 'src/components/message/CodePreview.tsx', 'src/components/message/ToolDetails.tsx'], rules: { 'react-refresh/only-export-components': 'off', }, diff --git a/frontend/package.json b/frontend/package.json index e4a6eddb..b7b4dfd4 100644 --- a/frontend/package.json +++ b/frontend/package.json @@ -39,6 +39,7 @@ "date-fns": "^4.1.0", "diff": "^8.0.2", "jsqr": "^1.4.0", + "lowlight": "^3.3.0", "lucide-react": "^0.546.0", "mermaid": "^11.12.2", "react": "^19.1.1", diff --git a/frontend/src/components/message/CodePreview.tsx b/frontend/src/components/message/CodePreview.tsx index 8ee22e48..945a5c24 100644 --- a/frontend/src/components/message/CodePreview.tsx +++ b/frontend/src/components/message/CodePreview.tsx @@ -15,7 +15,8 @@ function extractFileFromPath(path: string): string { return parts[parts.length - 1] || path } -function detectLanguage(fileName: string): string { +/** Maps a file name to the lowlight language name used for previews. */ +export function detectLanguage(fileName: string): string { const ext = fileName.split('.').pop()?.toLowerCase() const langMap: Record = { diff --git a/frontend/src/components/message/ComposerActivityBar.test.tsx b/frontend/src/components/message/ComposerActivityBar.test.tsx index d1468742..3af4647b 100644 --- a/frontend/src/components/message/ComposerActivityBar.test.tsx +++ b/frontend/src/components/message/ComposerActivityBar.test.tsx @@ -41,15 +41,15 @@ describe('ComposerActivityBar', () => { expect(container).toBeEmptyDOMElement() }) - it('sits inside the docked composer on mobile and below the composer on desktop', () => { + it('fills the gap above the controls row without taking layout height', () => { useSessionStatus.getState().setStatus('session-a', { type: 'busy' }) render() const bar = screen.getByRole('progressbar', { name: 'Session working' }) - expect(bar).toHaveClass('pointer-events-none', 'flex') - expect(bar).toHaveClass('absolute', 'inset-x-3', 'bottom-4', 'md:-bottom-[11px]') + expect(bar).toHaveClass('pointer-events-none', 'flex', 'absolute', 'inset-x-0', 'bottom-full') expect(bar).not.toHaveClass('fixed') + expect(bar).not.toHaveClass('pb-1.5') }) it('renders a masked segment track with only the sweeping window', () => { @@ -58,7 +58,7 @@ describe('ComposerActivityBar', () => { render() const track = trackOf(screen.getByRole('progressbar', { name: 'Session working' })) - expect(track).toHaveClass('scanner-track', 'relative', 'h-2', 'w-full') + expect(track).toHaveClass('scanner-track', 'relative', 'h-1.5', 'md:h-2', 'w-full') const children = Array.from(track.children) as HTMLElement[] expect(children).toHaveLength(1) diff --git a/frontend/src/components/message/ComposerActivityBar.tsx b/frontend/src/components/message/ComposerActivityBar.tsx index 05e9bbe1..57518bdf 100644 --- a/frontend/src/components/message/ComposerActivityBar.tsx +++ b/frontend/src/components/message/ComposerActivityBar.tsx @@ -25,11 +25,11 @@ const ACTIVITY_PRESENTATION = { } as const satisfies Record /** - * Session activity scanner shown by the composer. On mobile it sits inside the bottom edge of the - * docked composer; from `md` it is anchored in the gap below the composer frame. A fading lit window - * of 4x8px segments sweeps across the strip. Renders nothing while the session is idle and has no - * background activity; otherwise announces the current activity through an indeterminate - * progressbar. + * Session activity scanner shown by the composer. It overlays the gap above the bottom controls row + * without taking layout height, so the composer never resizes or jumps when activity starts or stops. + * A fading lit window of 4x8px segments sweeps across the strip. Renders nothing while the session is + * idle and has no background activity; otherwise announces the current activity through an + * indeterminate progressbar. */ export function ComposerActivityBar({ sessionID }: ComposerActivityBarProps) { const status = useSessionStatusForSession(sessionID) @@ -52,9 +52,9 @@ export function ComposerActivityBar({ sessionID }: ComposerActivityBarProps) { aria-label={label} aria-valuemin={0} aria-valuemax={100} - className="pointer-events-none absolute inset-x-3 bottom-4 flex md:-bottom-[11px]" + className="pointer-events-none absolute inset-x-0 bottom-full flex" > - + ) } diff --git a/frontend/src/components/message/DiffLines.tsx b/frontend/src/components/message/DiffLines.tsx new file mode 100644 index 00000000..a6e9db46 --- /dev/null +++ b/frontend/src/components/message/DiffLines.tsx @@ -0,0 +1,82 @@ +import { useMemo, type ReactNode } from 'react' +import { common, createLowlight } from 'lowlight' +import type { DiffRow } from '@/lib/diffLines' +import { cn } from '@/lib/utils' + +const lowlight = createLowlight(common) + +type HighlightedNode = ReturnType['children'][number] + +const ROW_CLASS: Record = { + add: 'bg-diff-add/15', + remove: 'bg-diff-delete/15', + context: '', + gap: '', +} + +const MARKER_CLASS: Record = { + add: 'text-diff-add', + remove: 'text-diff-delete', + context: 'text-muted-foreground', + gap: 'text-muted-foreground', +} + +const MARKER_TEXT: Record = { + add: '+', + remove: '-', + context: ' ', + gap: '⋯', +} + +function renderHighlightedNode(node: HighlightedNode, key: number): ReactNode { + if (node.type === 'text') return node.value + if (node.type !== 'element') return null + + const rawClassName = node.properties?.className + const className = Array.isArray(rawClassName) + ? rawClassName.join(' ') + : typeof rawClassName === 'string' + ? rawClassName + : undefined + + return ( + + {node.children.map((child, index) => renderHighlightedNode(child, index))} + + ) +} + +function highlightLine(text: string, language: string): ReactNode { + if (!text || !lowlight.registered(language)) return text + return lowlight + .highlight(language, text) + .children.map((node, index) => renderHighlightedNode(node, index)) +} + +/** Renders unified diff rows as a themed, line-numbered, syntax-highlighted block. */ +export function DiffLines({ rows, language }: { rows: DiffRow[]; language: string }) { + const highlighted = useMemo( + () => rows.map((row) => (row.kind === 'gap' ? row.text : highlightLine(row.text, language))), + [rows, language], + ) + const maxLineNumber = rows.reduce((max, row) => Math.max(max, row.newLine ?? row.oldLine ?? 0), 0) + const gridTemplateColumns = `${Math.max(String(maxLineNumber).length, 1)}ch 1ch minmax(0, 1fr)` + + return ( + + {rows.map((row, index) => ( + + + {row.kind === 'gap' ? '' : row.newLine ?? row.oldLine} + + {MARKER_TEXT[row.kind]} + {highlighted[index]} + + ))} + + ) +} diff --git a/frontend/src/components/message/ExecuteToolPart.tsx b/frontend/src/components/message/ExecuteToolPart.tsx index 3a7e226a..1d3b92bc 100644 --- a/frontend/src/components/message/ExecuteToolPart.tsx +++ b/frontend/src/components/message/ExecuteToolPart.tsx @@ -3,12 +3,19 @@ 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 { useMobile } from '@/hooks/useMobile' import { toolMetadata } from '@/lib/backgroundWork' import { clampDisplayText } from '@/lib/clampDisplayText' +import { cn } from '@/lib/utils' import { markdownRehypePlugins } from '@/lib/markdownRehypePlugins' import { CopyButton } from '@/components/ui/copy-button' import { FileReferenceText } from './FileReferenceText' import { ToolContentFiles } from './ToolContentFiles' +import { ToolDetails, useToolDetailsState } from './ToolDetails' +import { TRANSCRIPT_DETAIL_CLASS, TRANSCRIPT_ROW_CLASS } from './transcriptStyles' + +const PREVIEW_CALL_LIMIT = 5 +const MOBILE_PREVIEW_CALL_LIMIT = 3 type ExecuteCallStatus = 'running' | 'completed' | 'error' @@ -152,7 +159,7 @@ function ExecuteCallRow({ call, onFileClick }: { call: ExecuteCall; onFileClick? ) return ( -
+
{expandable ? ( -
+
+ - {calls.length > 0 && ( -
- {calls.map((call, index) => ( + {!detailsOpen && calls.length > 0 && ( +
+ {calls.slice(0, previewCallLimit).map((call, index) => ( ))} + {calls.length > previewCallLimit && ( +
({calls.length - previewCallLimit} more calls)
+ )}
)} - + - {!expanded && errorPreview.length > 0 && ( -
+ {!detailsOpen && errorPreview.length > 0 && ( +
{errorPreview.map((line, index) => (
{index === 0 ? `↳ ${line}` : ` ${line}`} @@ -280,57 +279,63 @@ export function ExecuteToolPart({ part, isWaitingPermission, onFileClick }: Exec
)} - {expanded && ( -
-
-
Code
- {code ? ( - - ) : ( -
Waiting for code…
- )} + + {calls.length > 0 && ( +
+ {calls.map((call, index) => ( + + ))}
+ )} -
-
Output
- {parsedOutput ? ( - <> - - {parsedOutput.rest && ( -
-                    {parsedOutput.rest}
-                  
- )} - - ) : displayOutput ? ( -
-                {displayOutput}
-              
- ) : ( -
- {status === 'completed' ? 'No output' : 'Waiting for output…'} -
- )} -
- -
- {code && ( -
- - Copy code -
- )} - {output && ( -
- - Copy output -
- )} -
+
+
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/FileToolRender.tsx b/frontend/src/components/message/FileToolRender.tsx index 3b67c708..d2d1af66 100644 --- a/frontend/src/components/message/FileToolRender.tsx +++ b/frontend/src/components/message/FileToolRender.tsx @@ -1,10 +1,16 @@ -import React, { useState } from 'react' +import React, { useMemo } from 'react' import type { FileDiffInfo, SessionMessageAssistantTool } from '@opencode-manager/shared/opencode' import { useSettings } from '@/hooks/useSettings' +import { useMobile } from '@/hooks/useMobile' import { isLocalOpenCodeServer, useOpenCodeServerId } from '@/contexts/OpenCodeServerContext' import { DiffStats } from './DiffStats' -import { CodePreview } from './CodePreview' +import { CodePreview, detectLanguage } from './CodePreview' +import { DiffLines } from './DiffLines' import { ToolContentFiles } from './ToolContentFiles' +import { ToolDetails, useToolDetailsState } from './ToolDetails' +import { TRANSCRIPT_DETAIL_CLASS, TRANSCRIPT_ROW_CLASS } from './transcriptStyles' +import { parseUnifiedDiff } from '@/lib/diffLines' +import { cn } from '@/lib/utils' import { ChevronDown, ChevronUp } from 'lucide-react' function isFileDiff(data: unknown): data is FileDiffInfo { @@ -42,26 +48,8 @@ export function getRelativePath(filePath: string): string { return filePath } -function PatchViewer({ patch }: { patch: string }) { - const lines = patch.split('\n') - - return ( -
-      {lines.map((line, index) => {
-        const tone = line.startsWith('@@')
-          ? 'text-info'
-          : line.startsWith('+++') || line.startsWith('---')
-            ? 'text-muted-foreground'
-            : line.startsWith('+')
-              ? 'text-diff-add'
-              : line.startsWith('-')
-                ? 'text-diff-delete'
-                : 'text-muted-foreground'
-        return 
{line || ' '}
- })} -
- ) -} +const PATCH_PREVIEW_LINE_COUNT = 8 +const MOBILE_PATCH_PREVIEW_LINE_COUNT = 4 interface FileToolRenderProps { part: SessionMessageAssistantTool @@ -74,18 +62,24 @@ interface FileToolRenderProps { function FileToolRender({ part, filediff, filePath, content, toolName, onFileClick }: FileToolRenderProps) { const { preferences } = useSettings() + const isMobile = useMobile() const isRemoteServer = !isLocalOpenCodeServer(useOpenCodeServerId()) const isReadTool = toolName === 'Read' - const isEditTool = toolName === 'Edit' - const isWriteTool = toolName === 'Write' + const hasDiff = Boolean(filediff) const hasExpandableContent = !isReadTool && (filediff || content) const isFileLink = Boolean(onFileClick) && !isRemoteServer - - const isFileMutatingTool = isEditTool || isWriteTool - const defaultExpanded = isFileMutatingTool + + const defaultExpanded = hasDiff ? (preferences?.expandDiffs ?? true) : (preferences?.expandToolCalls ?? false) - const [expanded, setExpanded] = useState(defaultExpanded) + const [detailsOpen, setDetailsOpen] = useToolDetailsState(defaultExpanded) + const relativePath = filePath ? getRelativePath(filePath) : undefined + const detailsTitle = relativePath ? `${toolName} ${relativePath}` : toolName + const diffRows = useMemo(() => (filediff ? parseUnifiedDiff(filediff.patch) : []), [filediff]) + const language = useMemo(() => detectLanguage(filePath ?? ''), [filePath]) + const previewLineCount = isMobile ? MOBILE_PATCH_PREVIEW_LINE_COUNT : PATCH_PREVIEW_LINE_COUNT + const previewRows = diffRows.slice(0, previewLineCount) + const hiddenLineCount = diffRows.length - previewRows.length const getDuration = () => { if (part.time.ran === undefined || part.time.completed === undefined) return '' @@ -99,44 +93,102 @@ function FileToolRender({ part, filediff, filePath, content, toolName, onFileCli } } - return ( -
- + + {!detailsOpen && previewRows.length > 0 && ( +
+ + {hiddenLineCount > 0 && ( + + )} +
+ )} + + {detailsOpen && !isMobile && ( +
+ +
+ )} + + {isMobile && ( + + + )}
-
- {filediff && } + + + + ) + } + + return ( +
+
+ - + - {expanded && hasExpandableContent && ( -
- {filediff && } - {content && !filediff && } -
+ {hasExpandableContent && ( + + {content && } + )}
) diff --git a/frontend/src/components/message/MessageError.tsx b/frontend/src/components/message/MessageError.tsx index 68e45e0c..9cbe8e15 100644 --- a/frontend/src/components/message/MessageError.tsx +++ b/frontend/src/components/message/MessageError.tsx @@ -36,7 +36,7 @@ export const MessageError = memo(function MessageError({ error }: MessageErrorPr const isAborted = error.type === 'aborted' const tone = isAborted ? 'text-muted-foreground' - : 'rounded-md border border-destructive/30 bg-destructive/10 px-2 py-1 text-destructive' + : 'border-l-2 border-destructive pl-2 text-destructive' return (
diff --git a/frontend/src/components/message/MessagePart.test.tsx b/frontend/src/components/message/MessagePart.test.tsx index a6c7a2b3..69a50254 100644 --- a/frontend/src/components/message/MessagePart.test.tsx +++ b/frontend/src/components/message/MessagePart.test.tsx @@ -15,12 +15,18 @@ import type { const mocks = vi.hoisted(() => ({ useSettings: vi.fn(), + useMobile: vi.fn(), })) vi.mock('@/hooks/useSettings', () => ({ useSettings: mocks.useSettings, })) +vi.mock('@/hooks/useMobile', async (importOriginal) => ({ + ...(await importOriginal()), + useMobile: mocks.useMobile, +})) + interface MockSettingsReturn { preferences: { simpleChatMode: boolean @@ -79,6 +85,7 @@ const completedShell = ( describe('MessagePart', () => { beforeEach(() => { vi.clearAllMocks() + mocks.useMobile.mockReturnValue(false) setupSettings({ simpleChatMode: false, showReasoning: false, @@ -240,12 +247,13 @@ describe('MessagePart', () => { it('renders a completed shell tool with its output', () => { renderWithProviders() - expect(screen.getByText('shell')).toBeInTheDocument() + const preview = screen.getByRole('button', { name: 'Show shell details' }) expect(screen.getByText('git status')).toBeInTheDocument() - fireEvent.click(screen.getByRole('button')) + fireEvent.click(preview) - expect(screen.getByText('clean tree')).toBeInTheDocument() + expect(screen.getByText('Output:')).toBeInTheDocument() + expect(document.querySelector('pre')?.textContent).toBe('clean tree') }) it('renders a running shell tool with its command', () => { @@ -261,7 +269,9 @@ describe('MessagePart', () => { it('renders a streaming tool with a preparing state', () => { renderWithProviders() - expect(screen.getByText('shell')).toBeInTheDocument() + fireEvent.click(screen.getByRole('button', { name: 'Show shell details' })) + + expect(screen.getByText('Preparing tool call...')).toBeInTheDocument() }) it('renders an error tool with the error message', () => { @@ -291,12 +301,12 @@ describe('MessagePart', () => { renderWithProviders() - expect(screen.getByText('shell')).toBeInTheDocument() + const preview = screen.getByRole('button', { name: 'Show shell details' }) expect(screen.getByText('bun test')).toBeInTheDocument() - fireEvent.click(screen.getByRole('button')) + fireEvent.click(preview) - expect(screen.getByText('12 tests passed')).toBeInTheDocument() + expect(document.querySelector('pre')?.textContent).toBe('12 tests passed') }) it('renders null for a non-subagent tool in simpleChatMode', () => { @@ -562,9 +572,65 @@ describe('MessagePart', () => { />, ) + const header = screen.getByRole('button', { name: /Edit \/test\/file\.txt/ }) + expect(within(header).getByText('←')).toBeInTheDocument() expect(screen.getByText('/test/file.txt')).toBeInTheDocument() expect(screen.getByText('+1')).toBeInTheDocument() expect(screen.getByText('-1')).toBeInTheDocument() + expect(screen.getByText('old')).toBeInTheDocument() + expect(screen.getByText('new')).toBeInTheDocument() + }) + + it('previews the first changed lines of a long patch until the diff is opened', () => { + setupSettings({ + simpleChatMode: false, + showReasoning: false, + expandToolCalls: false, + expandDiffs: false, + }) + + const changedLines = Array.from({ length: 20 }, (_, index) => `+line ${index + 1}`).join('\n') + + renderWithProviders( + , + ) + + const header = screen.getByRole('button', { name: /Edit \/test\/file\.txt/ }) + expect(within(header).getByText('←')).toBeInTheDocument() + + const preview = screen.getByRole('button', { name: 'Show diff for /test/file.txt' }) + expect(within(preview).getByText('line 1')).toBeInTheDocument() + expect(within(preview).getByText('line 8')).toBeInTheDocument() + expect(within(preview).queryByText('line 9')).toBeNull() + expect(within(preview).getByText('1')).toBeInTheDocument() + expect(within(preview).getByText('8')).toBeInTheDocument() + expect(within(preview).queryByText('9')).toBeNull() + expect(screen.getByText('(12 more lines)')).toBeInTheDocument() + expect(screen.queryByText('line 20')).toBeNull() + + fireEvent.click(preview) + + expect(screen.queryByRole('button', { name: 'Show diff for /test/file.txt' })).toBeNull() + expect(screen.getByText('line 9')).toBeInTheDocument() + expect(screen.getByText('line 20')).toBeInTheDocument() + expect(screen.getByText('20')).toBeInTheDocument() }) it('renders a write tool with its file path', () => { @@ -631,6 +697,13 @@ describe('MessagePart', () => { }) it('renders every file of a multi-file patch with per-file links', () => { + setupSettings({ + simpleChatMode: false, + showReasoning: false, + expandToolCalls: false, + expandDiffs: true, + }) + const onFileClick = vi.fn() renderWithProviders( { />, ) - expect(screen.getByText('src/a.ts')).toBeInTheDocument() - expect(screen.getByText('src/b.ts')).toBeInTheDocument() - - const buttons = screen.getAllByRole('button') - expect(buttons).toHaveLength(2) - fireEvent.click(buttons[0]) - fireEvent.click(buttons[1]) - - expect(screen.getByText('+new-a')).toBeInTheDocument() - expect(screen.getByText('+new-b')).toBeInTheDocument() + expect(screen.getByRole('button', { name: /Patch src\/a\.ts/ })).toBeInTheDocument() + expect(screen.getByRole('button', { name: /Patch src\/b\.ts/ })).toBeInTheDocument() + expect(screen.getByText('old-a')).toBeInTheDocument() + expect(screen.getByText('old-b')).toBeInTheDocument() fireEvent.click(screen.getByText('src/a.ts')) expect(onFileClick).toHaveBeenCalledWith('src/a.ts') fireEvent.click(screen.getByText('src/b.ts')) expect(onFileClick).toHaveBeenCalledWith('src/b.ts') + + fireEvent.click(screen.getByRole('button', { name: /Patch src\/a\.ts/ })) + + expect(screen.getByRole('button', { name: 'Show diff for src/a.ts' })).toBeInTheDocument() + expect(screen.queryByRole('button', { name: 'Show diff for src/b.ts' })).toBeNull() + }) + + it('syntax highlights added rows with the themed diff tints', () => { + const { container } = renderWithProviders( + , + ) + + const addedRow = container.querySelector('[class*="bg-diff-add/15"]') + expect(addedRow).not.toBeNull() + expect(addedRow?.querySelector('.hljs-keyword')?.textContent).toBe('const') }) it('falls back to the generic tool output when a patch has no diff metadata', () => { diff --git a/frontend/src/components/message/MessagePart.tsx b/frontend/src/components/message/MessagePart.tsx index 5a0d60db..94495075 100644 --- a/frontend/src/components/message/MessagePart.tsx +++ b/frontend/src/components/message/MessagePart.tsx @@ -4,6 +4,8 @@ import { TextPart } from './TextPart' import { ToolCallPart } from './ToolCallPart' import { readShowArtifactCall } from '@/lib/artifactTool' import { useSettings } from '@/hooks/useSettings' +import { cn } from '@/lib/utils' +import { TRANSCRIPT_DETAIL_CLASS } from './transcriptStyles' import type { ShellNoticeOutcome } from '@/lib/backgroundWork' import type { WalkthroughSource } from '@opencode-manager/shared/schemas' @@ -33,11 +35,11 @@ export const MessagePart = memo(function MessagePart({ part, messageID, director if (simpleChatMode || !showReasoning) return null if (!part.text.trim()) return null return ( -
- +
+ Reasoning -
+
{part.text}
diff --git a/frontend/src/components/message/MessageSkeleton.tsx b/frontend/src/components/message/MessageSkeleton.tsx index 79b54fd0..d17f52c7 100644 --- a/frontend/src/components/message/MessageSkeleton.tsx +++ b/frontend/src/components/message/MessageSkeleton.tsx @@ -1,103 +1,76 @@ +import { cn } from '@/lib/utils' +function Bar({ className }: { className: string }) { + return
+} +function UserTurnSkeleton({ widths }: { widths: string[] }) { + return ( +
+
+
+ {widths.map((width, index) => ( + + ))} +
+ +
+
+ ) +} + +function TurnFooterSkeleton() { + return ( +
+ + + +
+ ) +} + +function AssistantTurnSkeleton() { + return ( +
+
+ + +
+ + +
+
+ + + +
+ +
+ +
+ ) +} + +/** Placeholder transcript shown while a session loads, mirroring the CLI-style turn layout. */ export function MessageSkeleton() { return ( -
- {/* User message skeleton */} -
-
-
-
-
-
-
-
-
-
+