From 4fd658fc7db470f842fcdffaf910371d63a229d9 Mon Sep 17 00:00:00 2001 From: Chris Scott Date: Fri, 26 Dec 2025 18:07:33 -0500 Subject: [PATCH] Add diff expansion controls with ContentDiffViewer and CodePreview components --- frontend/eslint.config.js | 2 +- frontend/src/api/types/settings.ts | 1 + .../src/components/message/CodePreview.tsx | 128 +++++++++++++ .../components/message/ContentDiffViewer.tsx | 173 ++++++++++++++++++ frontend/src/components/message/DiffStats.tsx | 31 ++++ .../src/components/message/FileToolRender.tsx | 154 ++++++++++++++++ .../src/components/message/MessagePart.tsx | 2 +- frontend/src/components/message/PatchPart.tsx | 44 ++--- .../src/components/message/ToolCallPart.tsx | 51 +++--- .../components/settings/GeneralSettings.tsx | 14 ++ shared/src/schemas/settings.ts | 2 + 11 files changed, 549 insertions(+), 53 deletions(-) create mode 100644 frontend/src/components/message/CodePreview.tsx create mode 100644 frontend/src/components/message/ContentDiffViewer.tsx create mode 100644 frontend/src/components/message/DiffStats.tsx create mode 100644 frontend/src/components/message/FileToolRender.tsx diff --git a/frontend/eslint.config.js b/frontend/eslint.config.js index 1e49644b..4a9a62bc 100644 --- a/frontend/eslint.config.js +++ b/frontend/eslint.config.js @@ -21,7 +21,7 @@ export default defineConfig([ }, }, { - files: ['src/components/ui/**/*.{ts,tsx}'], + files: ['src/components/ui/**/*.{ts,tsx}', 'src/components/message/FileToolRender.tsx'], rules: { 'react-refresh/only-export-components': 'off', }, diff --git a/frontend/src/api/types/settings.ts b/frontend/src/api/types/settings.ts index ff65ae92..99559510 100644 --- a/frontend/src/api/types/settings.ts +++ b/frontend/src/api/types/settings.ts @@ -29,6 +29,7 @@ export interface UserPreferences { autoScroll: boolean showReasoning: boolean expandToolCalls: boolean + expandDiffs: boolean keyboardShortcuts: Record customCommands: CustomCommand[] customAgents: CustomAgent[] diff --git a/frontend/src/components/message/CodePreview.tsx b/frontend/src/components/message/CodePreview.tsx new file mode 100644 index 00000000..82b10ad9 --- /dev/null +++ b/frontend/src/components/message/CodePreview.tsx @@ -0,0 +1,128 @@ +import React from 'react' +import { Copy } from 'lucide-react' +import { useMobile } from '@/hooks/useMobile' +import { cn } from '@/lib/utils' + +interface CodePreviewProps { + fileName: string + content: string +} + +const INITIAL_CODE_LINES = 20 + +function extractFileFromPath(path: string): string { + const parts = path.split('/') + return parts[parts.length - 1] || path +} + +function detectLanguage(fileName: string): string { + const ext = fileName.split('.').pop()?.toLowerCase() + + const langMap: Record = { + ts: 'typescript', + tsx: 'typescript', + js: 'javascript', + jsx: 'javascript', + py: 'python', + rb: 'ruby', + go: 'go', + rs: 'rust', + java: 'java', + cs: 'csharp', + cpp: 'cpp', + c: 'c', + h: 'c', + json: 'json', + yaml: 'yaml', + yml: 'yaml', + toml: 'toml', + xml: 'xml', + html: 'html', + css: 'css', + scss: 'scss', + sass: 'sass', + svg: 'svg', + md: 'markdown', + sh: 'bash', + bash: 'bash', + zsh: 'bash', + fish: 'bash', + sql: 'sql', + php: 'php', + swift: 'swift', + kt: 'kotlin', + dart: 'dart', + } + + return langMap[ext || ''] || 'plaintext' +} + +export function CodePreview({ fileName, content }: CodePreviewProps) { + const isMobile = useMobile() + const [copied, setCopied] = React.useState(false) + const [showMore, setShowMore] = React.useState(false) + + const language = detectLanguage(fileName) + const fileExtension = fileName.split('.').pop() || language + + const lines = content.split('\n') + const totalLines = lines.length + const isLargeFile = totalLines > INITIAL_CODE_LINES + + const displayedContent = isLargeFile && !showMore + ? lines.slice(0, INITIAL_CODE_LINES).join('\n') + : content + + const handleCopy = async () => { + try { + await navigator.clipboard.writeText(content) + setCopied(true) + setTimeout(() => setCopied(false), 2000) + } catch (err) { + console.error('Failed to copy:', err) + } + } + + return ( +
+
+ {extractFileFromPath(fileName)} + +
+ +
+
+
+            
+              {displayedContent}
+            
+          
+
+
+ + {isLargeFile && !showMore && ( + + )} + + {isLargeFile && showMore && ( + + )} +
+ ) +} \ No newline at end of file diff --git a/frontend/src/components/message/ContentDiffViewer.tsx b/frontend/src/components/message/ContentDiffViewer.tsx new file mode 100644 index 00000000..f439517a --- /dev/null +++ b/frontend/src/components/message/ContentDiffViewer.tsx @@ -0,0 +1,173 @@ +import { useState } from 'react' +import { useMobile } from '@/hooks/useMobile' +import { Plus, Minus, ChevronDown, ChevronUp } from 'lucide-react' +import { diffLines } from 'diff' +import type { Change } from 'diff' +import { cn } from '@/lib/utils' + +interface ContentDiffViewerProps { + before: string + after: string +} + +const CONTEXT_LINES = 1 +const MAX_LINE_DISPLAY_LENGTH = 200 + +interface DiffLineEntry { + type: 'add' | 'remove' | 'context' + content: string + oldLineNumber?: number + newLineNumber?: number +} + +function truncateLine(line: string): string { + if (line.length <= MAX_LINE_DISPLAY_LENGTH) { + return line + } + return line.substring(0, MAX_LINE_DISPLAY_LENGTH) + '...' +} + +export function ContentDiffViewer({ before, after }: ContentDiffViewerProps) { + const isMobile = useMobile() + const [showMore, setShowMore] = useState(false) + + const computeDiffLines = (): DiffLineEntry[] => { + const difference = diffLines(before, after, { + ignoreWhitespace: false, + }) + + const result: DiffLineEntry[] = [] + let oldLine = 0 + let newLine = 0 + + difference.forEach((change: Change) => { + const lines = change.value.split('\n') + if (lines[lines.length - 1] === '') { + lines.pop() + } + + lines.forEach((line) => { + if (change.added) { + newLine++ + result.push({ + type: 'add', + content: line, + newLineNumber: newLine, + }) + } else if (change.removed) { + oldLine++ + result.push({ + type: 'remove', + content: line, + oldLineNumber: oldLine, + }) + } else { + oldLine++ + newLine++ + result.push({ + type: 'context', + content: line, + oldLineNumber: oldLine, + newLineNumber: newLine, + }) + } + }) + }) + + return result + } + + const getCompressedDiff = (allLines: DiffLineEntry[]): DiffLineEntry[] => { + const changedIndices = new Set() + + allLines.forEach((line, index) => { + if (line.type === 'add' || line.type === 'remove') { + for (let i = Math.max(0, index - CONTEXT_LINES); i <= Math.min(allLines.length - 1, index + CONTEXT_LINES); i++) { + changedIndices.add(i) + } + } + }) + + return allLines.filter((_, index) => changedIndices.has(index)) + } + + const allLines = computeDiffLines() + const compressedLines = getCompressedDiff(allLines) + + const displayedLines = showMore ? allLines : compressedLines + const hiddenCount = allLines.length - compressedLines.length + + if (compressedLines.length === 0) { + return ( +
+ No changes +
+ ) + } + + return ( +
+
+ {displayedLines.map((line, index) => { + const isAdd = line.type === 'add' + const isRemove = line.type === 'remove' + + return ( +
+ {!isMobile && ( +
+ + {line.oldLineNumber || ''} + + + {line.newLineNumber || ''} + +
+ )} +
+ {isAdd && } + {isRemove && } +
+
+                {truncateLine(line.content)}
+              
+
+ ) + })} +
+ + {!showMore && hiddenCount > 0 && ( + + )} + + {showMore && hiddenCount > 0 && ( + + )} +
+ ) +} \ No newline at end of file diff --git a/frontend/src/components/message/DiffStats.tsx b/frontend/src/components/message/DiffStats.tsx new file mode 100644 index 00000000..cdc0e0c2 --- /dev/null +++ b/frontend/src/components/message/DiffStats.tsx @@ -0,0 +1,31 @@ +interface DiffStatsProps { + additions: number + deletions: number + variant?: 'default' | 'compact' +} + +export function DiffStats({ additions, deletions, variant = 'default' }: DiffStatsProps) { + if (additions === 0 && deletions === 0) { + return null + } + + const compact = variant === 'compact' + + return ( + + {additions > 0 && ( + + {compact ? `+${additions}` : `+${additions}`} + + )} + {additions > 0 && deletions > 0 && ( + {compact ? '/' : ' '} + )} + {deletions > 0 && ( + + {compact ? `-${deletions}` : `-${deletions}`} + + )} + + ) +} \ No newline at end of file diff --git a/frontend/src/components/message/FileToolRender.tsx b/frontend/src/components/message/FileToolRender.tsx new file mode 100644 index 00000000..b77c7072 --- /dev/null +++ b/frontend/src/components/message/FileToolRender.tsx @@ -0,0 +1,154 @@ +import React, { useState } from 'react' +import type { components } from '@/api/opencode-types' +import { useSettings } from '@/hooks/useSettings' +import { DiffStats } from './DiffStats' +import { ContentDiffViewer } from './ContentDiffViewer' +import { CodePreview } from './CodePreview' +import { ChevronDown, ChevronUp } from 'lucide-react' + +type ToolPart = components['schemas']['ToolPart'] + +export interface FileDiffData { + file: string + before: string + after: string + additions: number + deletions: number +} + +function isFileDiff(data: unknown): data is FileDiffData { + return ( + typeof data === 'object' && + data !== null && + 'file' in data && + 'before' in data && + 'after' in data && + 'additions' in data && + 'deletions' in data && + typeof (data as FileDiffData).file === 'string' && + typeof (data as FileDiffData).before === 'string' && + typeof (data as FileDiffData).after === 'string' && + typeof (data as FileDiffData).additions === 'number' && + typeof (data as FileDiffData).deletions === 'number' + ) +} + +export function getRelativePath(filePath: string): string { + const reposIndex = filePath.indexOf('/repos/') + if (reposIndex !== -1) { + return filePath.substring(reposIndex + 7) + } + + const workspaceIndex = filePath.indexOf('/workspace/') + if (workspaceIndex !== -1) { + return filePath.substring(workspaceIndex + 11) + } + + if (filePath.startsWith('/Users/') || filePath.startsWith('/home/')) { + const parts = filePath.split('/') + const lastThree = parts.slice(-3) + return lastThree.join('/') + } + + return filePath +} + +interface FileToolRenderProps { + part: ToolPart + filediff?: FileDiffData + filePath?: string + content?: string + toolName: string + onFileClick?: (filePath: string, lineNumber?: number) => void +} + +export function FileToolRender({ part, filediff, filePath, content, toolName, onFileClick }: FileToolRenderProps) { + const { preferences } = useSettings() + const isReadTool = toolName === 'Read' + const isEditTool = toolName === 'Edit' + const hasExpandableContent = !isReadTool && (filediff || content) + + const defaultExpanded = isEditTool + ? (preferences?.expandDiffs ?? true) + : (preferences?.expandToolCalls ?? false) + const [expanded, setExpanded] = useState(defaultExpanded) + + const getDuration = () => { + if (part.state.status === 'completed' && part.state.time) { + return ((part.state.time.end - part.state.time.start) / 1000).toFixed(2) + 's' + } + return '' + } + + const handleFileClick = (e: React.MouseEvent) => { + e.stopPropagation() + if (onFileClick && filePath) { + onFileClick(filePath) + } + } + + return ( +
+ + + {expanded && hasExpandableContent && ( +
+ {filediff && } + {content && !filediff && } +
+ )} +
+ ) +} + +export function getToolSpecificRender(part: ToolPart, onFileClick?: (filePath: string) => void): React.ReactElement | null { + if (part.state.status !== 'completed') return null + + if (part.tool === 'edit') { + const filediff = part.state.metadata?.filediff + const filePath = part.state.input?.filePath as string | undefined + if (filediff && isFileDiff(filediff)) { + return + } + } + + if (part.tool === 'write') { + const filePath = part.state.input?.filePath as string | undefined + const content = part.state.input?.content as string | undefined + if (filePath) { + return + } + } + + if (part.tool === 'read') { + const filePath = part.state.input?.filePath as string | undefined + if (filePath) { + return + } + } + + return null +} \ No newline at end of file diff --git a/frontend/src/components/message/MessagePart.tsx b/frontend/src/components/message/MessagePart.tsx index b138371d..d4123545 100644 --- a/frontend/src/components/message/MessagePart.tsx +++ b/frontend/src/components/message/MessagePart.tsx @@ -114,7 +114,7 @@ export const MessagePart = memo(function MessagePart({ part, role, allParts, par } return case 'patch': - return + return case 'tool': return case 'reasoning': diff --git a/frontend/src/components/message/PatchPart.tsx b/frontend/src/components/message/PatchPart.tsx index f1c295d1..0d5df523 100644 --- a/frontend/src/components/message/PatchPart.tsx +++ b/frontend/src/components/message/PatchPart.tsx @@ -1,38 +1,34 @@ -import { useState } from 'react' import type { components } from '@/api/opencode-types' +import { getRelativePath } from './FileToolRender' -type PatchPart = components['schemas']['PatchPart'] +type PatchPartType = components['schemas']['PatchPart'] interface PatchPartProps { - part: PatchPart + part: PatchPartType + onFileClick?: (filePath: string) => void } -export function PatchPart({ part }: PatchPartProps) { - const [expanded, setExpanded] = useState(true) - +export function PatchPart({ part, onFileClick }: PatchPartProps) { return ( -
- + {part.hash.slice(0, 8)} +
- {expanded && ( -
-
- {part.files.map((file, index) => ( -
-
{file}
-
- ))} +
+ {part.files.map((file, index) => ( +
onFileClick?.(file)} + > + {getRelativePath(file)}
-
- )} + ))} +
) -} +} \ No newline at end of file diff --git a/frontend/src/components/message/ToolCallPart.tsx b/frontend/src/components/message/ToolCallPart.tsx index 6b9e8149..2b748f59 100644 --- a/frontend/src/components/message/ToolCallPart.tsx +++ b/frontend/src/components/message/ToolCallPart.tsx @@ -6,6 +6,7 @@ import { detectFileReferences } from '@/lib/fileReferences' import { ExternalLink, Loader2 } from 'lucide-react' import { CopyButton } from '@/components/ui/copy-button' import { TodoListDisplay } from './TodoListDisplay' +import { getToolSpecificRender } from './FileToolRender' type ToolPart = components['schemas']['ToolPart'] type Todo = components['schemas']['Todo'] @@ -71,15 +72,12 @@ export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCal const { preferences } = useSettings() const { userBashCommands } = useUserBash() const outputRef = useRef(null) - const isUserBashCommand = part.tool === 'bash' && + const isUserBashCommand = part.tool === 'bash' && part.state.status === 'completed' && typeof part.state.input?.command === 'string' && userBashCommands.has(part.state.input.command) const isTodoTool = part.tool === 'todowrite' || part.tool === 'todoread' - - // Todo tools show expanded content by default, other tools use preference - const defaultExpanded = isUserBashCommand || isTodoTool || (preferences?.expandToolCalls ?? false) - const [expanded, setExpanded] = useState(defaultExpanded) + const [expanded, setExpanded] = useState(isUserBashCommand || isTodoTool || (preferences?.expandToolCalls ?? false)) useEffect(() => { if (part.tool === 'bash' && expanded && outputRef.current) { @@ -117,7 +115,7 @@ export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCal const getPreviewText = () => { if (part.state.status === 'pending') return null - + const input = part.state.input as Record if (!input) return null @@ -150,8 +148,7 @@ export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCal } const state = part.state - - // For completed state - has output and metadata + if (state.status === 'completed') { if (state.metadata?.todos && Array.isArray(state.metadata.todos)) { return state.metadata.todos as Todo[] @@ -161,17 +158,15 @@ export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCal if (parsed) return parsed } } - - // For running state - might have metadata + if (state.status === 'running' && state.metadata?.todos && Array.isArray(state.metadata.todos)) { return state.metadata.todos as Todo[] } - - // For any state - try input (used by todowrite) + if (state.input?.todos && Array.isArray(state.input.todos)) { return state.input.todos as Todo[] } - + return null } @@ -179,7 +174,6 @@ export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCal const todoData = getTodoData() const isFileTool = ['read', 'write', 'edit'].includes(part.tool) - // For todo tools, render the TodoListDisplay directly without wrapper if (isTodoTool) { if (part.state.status === 'pending') { return ( @@ -228,6 +222,11 @@ export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCal return null } + const toolSpecificRender = getToolSpecificRender(part, onFileClick) + if (toolSpecificRender) { + return toolSpecificRender + } + if (isUserBashCommand) { const command = part.state.input.command as string const output = part.state.status === 'completed' ? part.state.output : '' @@ -243,7 +242,7 @@ export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCal )} -
 navigator.clipboard.writeText(output)}
              title="Click to copy output">
           {output}
@@ -275,8 +274,7 @@ export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCal
       >
         {getStatusIcon()}
         {part.tool}
-        
-        {/* Header preview text */}
+
         {previewText && isFileTool ? (
            {
@@ -293,7 +291,7 @@ export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCal
         ) : previewText ? (
           {previewText}
         ) : null}
-        
+
         {part.tool === 'task' && (() => {
           let sessionId: string | undefined = part.metadata?.sessionId as string | undefined
           if (!sessionId && part.state.status !== 'pending' && 'metadata' in part.state) {
@@ -316,7 +314,6 @@ export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCal
         ({part.state.status})
       
 
-      {/* Expanded content for non-todo tools */}
       {expanded && (
         
{part.state.status === 'pending' && ( @@ -336,9 +333,9 @@ export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCal
Command:
-
@@ -368,9 +365,9 @@ export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCal
Command:
-
@@ -385,7 +382,7 @@ export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCal )}
Output:
-
 part.state.status === 'completed' && navigator.clipboard.writeText(part.state.output)}
                      title="Click to copy output">
                   {part.state.status === 'completed' ? part.state.output : ''}
@@ -411,4 +408,4 @@ export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCal
       )}
     
) -} +} \ No newline at end of file diff --git a/frontend/src/components/settings/GeneralSettings.tsx b/frontend/src/components/settings/GeneralSettings.tsx index 69fbaef9..167c4cbc 100644 --- a/frontend/src/components/settings/GeneralSettings.tsx +++ b/frontend/src/components/settings/GeneralSettings.tsx @@ -136,6 +136,20 @@ export function GeneralSettings() { />
+
+
+ +

+ Show file diffs expanded by default for edit operations +

+
+ updateSettings({ expandDiffs: checked })} + /> +
+
diff --git a/shared/src/schemas/settings.ts b/shared/src/schemas/settings.ts index 46e0f7c9..93913a66 100644 --- a/shared/src/schemas/settings.ts +++ b/shared/src/schemas/settings.ts @@ -68,6 +68,7 @@ export const UserPreferencesSchema = z.object({ autoScroll: z.boolean(), showReasoning: z.boolean(), expandToolCalls: z.boolean(), + expandDiffs: z.boolean(), keyboardShortcuts: z.record(z.string(), z.string()), customCommands: z.array(CustomCommandSchema), customAgents: z.array(CustomAgentSchema), @@ -95,6 +96,7 @@ export const DEFAULT_USER_PREFERENCES = { autoScroll: true, showReasoning: false, expandToolCalls: false, + expandDiffs: true, keyboardShortcuts: DEFAULT_KEYBOARD_SHORTCUTS, customCommands: [], customAgents: [],