Add diff expansion controls with ContentDiffViewer and CodePreview components

This commit is contained in:
Chris Scott committed 2025-12-26 18:07:33 -05:00
1 parent 55b6ab3c87
commit 4fd658fc7d
11 files changed
+549 -53

No files matched your search

+1
View File
@@ -29,6 +29,7 @@ export interface UserPreferences {
autoScroll: boolean
showReasoning: boolean
expandToolCalls: boolean
expandDiffs: boolean
keyboardShortcuts: Record<string, string>
customCommands: CustomCommand[]
customAgents: CustomAgent[]
@@ -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<string, string> = {
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 (
<div className="flex flex-col bg-background">
<div className="px-3 py-2 bg-muted/30 border-b border-border/50 flex items-center justify-between text-xs">
<span className="font-medium truncate flex-1">{extractFileFromPath(fileName)}</span>
<button
onClick={handleCopy}
className="p-1 hover:bg-accent rounded flex-shrink-0"
title={copied ? 'Copied!' : 'Copy'}
>
<Copy className={cn('w-3.5 h-3.5', copied && 'text-green-500')} />
</button>
</div>
<div className={cn('overflow-y-auto', isMobile ? 'max-h-64' : 'max-h-96')}>
<div className="p-4">
<pre className={cn('text-xs', isMobile && 'whitespace-pre-wrap break-all')}>
<code className={`language-${fileExtension}`}>
{displayedContent}
</code>
</pre>
</div>
</div>
{isLargeFile && !showMore && (
<button
onClick={() => setShowMore(true)}
className="mx-3 my-2 px-3 py-1.5 bg-muted hover:bg-muted/70 border border-border/50 rounded text-xs text-muted-foreground"
>
Show more ({totalLines - INITIAL_CODE_LINES} more lines)
</button>
)}
{isLargeFile && showMore && (
<button
onClick={() => setShowMore(false)}
className="mx-3 my-2 px-3 py-1.5 bg-muted hover:bg-muted/70 border border-border/50 rounded text-xs text-muted-foreground"
>
Show less
</button>
)}
</div>
)
}
@@ -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<number>()
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 (
<div className="px-3 py-2 text-xs text-muted-foreground">
No changes
</div>
)
}
return (
<div className="flex flex-col bg-background">
<div className="overflow-y-auto max-h-48">
{displayedLines.map((line, index) => {
const isAdd = line.type === 'add'
const isRemove = line.type === 'remove'
return (
<div
key={index}
className={cn(
'flex font-mono text-xs',
isAdd && 'bg-green-500/10',
isRemove && 'bg-red-500/10',
)}
>
{!isMobile && (
<div className="flex-shrink-0 w-14 flex text-muted-foreground/50 text-[10px]">
<span className="w-7 px-1 text-right">
{line.oldLineNumber || ''}
</span>
<span className="w-7 px-1 text-right">
{line.newLineNumber || ''}
</span>
</div>
)}
<div className="w-4 flex-shrink-0 flex items-center justify-center">
{isAdd && <Plus className="w-2.5 h-2.5 text-green-500" />}
{isRemove && <Minus className="w-2.5 h-2.5 text-red-500" />}
</div>
<pre
className={cn(
'flex-1 px-1 py-0.5 whitespace-pre-wrap break-all',
isAdd && 'text-green-600 dark:text-green-400',
isRemove && 'text-red-600 dark:text-red-400',
)}
>
{truncateLine(line.content)}
</pre>
</div>
)
})}
</div>
{!showMore && hiddenCount > 0 && (
<button
onClick={() => setShowMore(true)}
className="px-3 py-1 text-xs text-muted-foreground hover:text-foreground flex items-center gap-1"
>
<ChevronDown className="w-3 h-3" />
+{hiddenCount} more lines
</button>
)}
{showMore && hiddenCount > 0 && (
<button
onClick={() => setShowMore(false)}
className="px-3 py-1 text-xs text-muted-foreground hover:text-foreground flex items-center gap-1"
>
<ChevronUp className="w-3 h-3" />
Show less
</button>
)}
</div>
)
}
@@ -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 (
<span className="flex items-center gap-1 text-xs font-mono">
{additions > 0 && (
<span className="text-green-600 dark:text-green-400">
{compact ? `+${additions}` : `+${additions}`}
</span>
)}
{additions > 0 && deletions > 0 && (
<span className="text-muted-foreground">{compact ? '/' : ' '}</span>
)}
{deletions > 0 && (
<span className="text-red-600 dark:text-red-400">
{compact ? `-${deletions}` : `-${deletions}`}
</span>
)}
</span>
)
}
@@ -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 (
<div className="border border-border rounded-lg overflow-hidden my-2">
<button
onClick={() => hasExpandableContent && setExpanded(!expanded)}
className="w-full px-3 py-1.5 bg-card hover:bg-card-hover text-left flex items-center justify-between text-sm gap-2"
>
<div className="flex items-center gap-2 min-w-0">
<span className="text-green-600 dark:text-green-400 flex-shrink-0">✓</span>
<span className="font-medium flex-shrink-0">{toolName}</span>
{filePath && (
<span
onClick={handleFileClick}
className="text-blue-600 dark:text-blue-400 text-xs truncate hover:underline cursor-pointer"
>
{getRelativePath(filePath)}
</span>
)}
</div>
<div className="flex items-center gap-2 flex-shrink-0">
{filediff && <DiffStats additions={filediff.additions} deletions={filediff.deletions} />}
<span className="text-muted-foreground text-xs">{getDuration()}</span>
{hasExpandableContent && (
expanded ? <ChevronUp className="w-4 h-4 text-muted-foreground" /> : <ChevronDown className="w-4 h-4 text-muted-foreground" />
)}
</div>
</button>
{expanded && hasExpandableContent && (
<div className="bg-card p-0">
{filediff && <ContentDiffViewer before={filediff.before} after={filediff.after} />}
{content && !filediff && <CodePreview fileName={filePath || ''} content={content} />}
</div>
)}
</div>
)
}
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 <FileToolRender part={part} filediff={filediff} filePath={filePath} toolName="Edit" onFileClick={onFileClick} />
}
}
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 <FileToolRender part={part} filePath={filePath} content={content} toolName="Write" onFileClick={onFileClick} />
}
}
if (part.tool === 'read') {
const filePath = part.state.input?.filePath as string | undefined
if (filePath) {
return <FileToolRender part={part} filePath={filePath} toolName="Read" onFileClick={onFileClick} />
}
}
return null
}
@@ -114,7 +114,7 @@ export const MessagePart = memo(function MessagePart({ part, role, allParts, par
}
return <TextPart part={part} />
case 'patch':
return <PatchPart part={part} />
return <PatchPart part={part} onFileClick={onFileClick} />
case 'tool':
return <ToolCallPart part={part} onFileClick={onFileClick} onChildSessionClick={onChildSessionClick} />
case 'reasoning':
+20 -24
View File
@@ -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 (
<div className="border border-zinc-800 rounded-lg overflow-hidden my-2">
<button
onClick={() => setExpanded(!expanded)}
className="w-full px-4 py-2 bg-zinc-900 hover:bg-zinc-800 text-left flex items-center justify-between text-sm"
>
<div className="border border-border rounded-lg overflow-hidden my-2">
<div className="px-3 py-1.5 bg-card flex items-center justify-between text-sm">
<span className="font-medium">
File Changes ({part.files.length} file{part.files.length !== 1 ? 's' : ''})
</span>
<span className="text-zinc-400 text-xs font-mono">{part.hash.slice(0, 8)}</span>
</button>
<span className="text-muted-foreground text-xs font-mono">{part.hash.slice(0, 8)}</span>
</div>
{expanded && (
<div className="bg-zinc-950 p-4">
<div className="space-y-2">
{part.files.map((file, index) => (
<div key={index} className="text-sm">
<div className="font-mono text-zinc-400 mb-1">{file}</div>
</div>
))}
<div className="bg-card px-3 py-2 space-y-1">
{part.files.map((file, index) => (
<div
key={index}
className="text-xs font-mono text-blue-600 dark:text-blue-400 hover:underline cursor-pointer"
onClick={() => onFileClick?.(file)}
>
{getRelativePath(file)}
</div>
</div>
)}
))}
</div>
</div>
)
}
}
@@ -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<HTMLDivElement>(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<string, unknown>
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
</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"
<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}
@@ -275,8 +274,7 @@ export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCal
>
<span className={getStatusColor()}>{getStatusIcon()}</span>
<span className="font-medium">{part.tool}</span>
{/* Header preview text */}
{previewText && isFileTool ? (
<span
onClick={(e) => {
@@ -293,7 +291,7 @@ export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCal
) : previewText ? (
<span className="text-muted-foreground text-xs truncate">{previewText}</span>
) : 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
<span className="text-muted-foreground text-xs ml-auto">({part.state.status})</span>
</button>
{/* Expanded content for non-todo tools */}
{expanded && (
<div className="bg-card space-y-2 p-3">
{part.state.status === 'pending' && (
@@ -336,9 +333,9 @@ export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCal
<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"
<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 whitespace-pre-wrap break-words">
@@ -368,9 +365,9 @@ export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCal
<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"
<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 whitespace-pre-wrap break-words">
@@ -385,7 +382,7 @@ export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCal
)}
<div className="text-sm">
<div className="text-muted-foreground mb-1">Output:</div>
<pre className="bg-accent p-2 rounded text-xs overflow-x-auto whitespace-pre-wrap break-all cursor-pointer hover:bg-accent/80 transition-colors"
<pre className="bg-accent p-2 rounded text-xs overflow-x-auto whitespace-pre-wrap break-all 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 : ''}
@@ -411,4 +408,4 @@ export function ToolCallPart({ part, onFileClick, onChildSessionClick }: ToolCal
)}
</div>
)
}
}
@@ -136,6 +136,20 @@ export function GeneralSettings() {
/>
</div>
<div className="flex flex-row items-center justify-between rounded-lg border border-border p-4">
<div className="space-y-0.5">
<Label htmlFor="expandDiffs" className="text-base">Expand diffs</Label>
<p className="text-sm text-muted-foreground">
Show file diffs expanded by default for edit operations
</p>
</div>
<Switch
id="expandDiffs"
checked={preferences?.expandDiffs ?? true}
onCheckedChange={(checked) => updateSettings({ expandDiffs: checked })}
/>
</div>
<div className="space-y-2">
<Label htmlFor="gitToken">GitHub Personal Access Token</Label>
<div className="flex gap-2">