mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
feat(frontend): restyle the session transcript as a plain log with collapsible tool details
This commit is contained in:
1 parent
ac0e5d6fa0
commit
8004496f10
30 files changed
+1334
-611
No files matched your search
@@ -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',
|
||||
},
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -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<string, string> = {
|
||||
|
||||
@@ -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(<ComposerActivityBar sessionID="session-a" />)
|
||||
|
||||
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(<ComposerActivityBar sessionID="session-a" />)
|
||||
|
||||
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)
|
||||
|
||||
@@ -25,11 +25,11 @@ const ACTIVITY_PRESENTATION = {
|
||||
} as const satisfies Record<string, { label: string; tone: ScannerTone }>
|
||||
|
||||
/**
|
||||
* 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"
|
||||
>
|
||||
<ScannerBars tone={activity.tone} />
|
||||
<ScannerBars tone={activity.tone} className="h-1.5 md:h-2" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -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<typeof lowlight.highlight>['children'][number]
|
||||
|
||||
const ROW_CLASS: Record<DiffRow['kind'], string> = {
|
||||
add: 'bg-diff-add/15',
|
||||
remove: 'bg-diff-delete/15',
|
||||
context: '',
|
||||
gap: '',
|
||||
}
|
||||
|
||||
const MARKER_CLASS: Record<DiffRow['kind'], string> = {
|
||||
add: 'text-diff-add',
|
||||
remove: 'text-diff-delete',
|
||||
context: 'text-muted-foreground',
|
||||
gap: 'text-muted-foreground',
|
||||
}
|
||||
|
||||
const MARKER_TEXT: Record<DiffRow['kind'], string> = {
|
||||
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 (
|
||||
<span key={key} className={className}>
|
||||
{node.children.map((child, index) => renderHighlightedNode(child, index))}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
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 (
|
||||
<span className="block font-mono text-xs leading-5">
|
||||
{rows.map((row, index) => (
|
||||
<span
|
||||
key={index}
|
||||
className={cn('grid', ROW_CLASS[row.kind])}
|
||||
style={{ gridTemplateColumns }}
|
||||
>
|
||||
<span className="select-none pr-2 text-right text-muted-foreground">
|
||||
{row.kind === 'gap' ? '' : row.newLine ?? row.oldLine}
|
||||
</span>
|
||||
<span className={cn('select-none', MARKER_CLASS[row.kind])}>{MARKER_TEXT[row.kind]}</span>
|
||||
<span className="whitespace-pre-wrap break-all">{highlighted[index]}</span>
|
||||
</span>
|
||||
))}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
@@ -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 (
|
||||
<div className="pl-3">
|
||||
<div>
|
||||
{expandable ? (
|
||||
<button
|
||||
type="button"
|
||||
@@ -187,7 +194,8 @@ function ExecuteCallRow({ call, onFileClick }: { call: ExecuteCall; onFileClick?
|
||||
|
||||
export function ExecuteToolPart({ part, isWaitingPermission, onFileClick }: ExecuteToolPartProps) {
|
||||
const { preferences } = useSettings()
|
||||
const [expanded, setExpanded] = useState(preferences?.expandToolCalls ?? false)
|
||||
const [detailsOpen, setDetailsOpen] = useToolDetailsState(preferences?.expandToolCalls ?? false)
|
||||
const previewCallLimit = useMobile() ? MOBILE_PREVIEW_CALL_LIMIT : PREVIEW_CALL_LIMIT
|
||||
const metadata = toolMetadata(part)
|
||||
const calls = executeCalls(metadata.toolCalls)
|
||||
const code = executeCode(part)
|
||||
@@ -230,48 +238,39 @@ export function ExecuteToolPart({ part, isWaitingPermission, onFileClick }: Exec
|
||||
return <span>○</span>
|
||||
})()
|
||||
|
||||
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 (
|
||||
<div className={`border rounded-lg overflow-hidden my-2 transition-all ${borderStyle}`}>
|
||||
<div className="flex items-center bg-card">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setExpanded(!expanded)}
|
||||
aria-expanded={expanded}
|
||||
className="min-w-0 flex-1 px-4 py-2 hover:bg-card-hover text-left flex items-center gap-2 text-sm"
|
||||
>
|
||||
<span className={statusColor}>{statusIcon}</span>
|
||||
<span className="font-medium">execute</span>
|
||||
<span className={`text-xs ml-auto ${failed ? 'text-destructive' : 'text-muted-foreground'}`}>
|
||||
{statusLabel}
|
||||
</span>
|
||||
</button>
|
||||
</div>
|
||||
<div className={cn('my-1', isWaitingPermission && 'border-l-2 border-highlight pl-2')}>
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setDetailsOpen(!detailsOpen)}
|
||||
aria-expanded={detailsOpen}
|
||||
className={cn(TRANSCRIPT_ROW_CLASS, 'group hover:text-foreground transition-colors')}
|
||||
>
|
||||
<span className={cn('shrink-0', statusColor)}>{statusIcon}</span>
|
||||
<span className="shrink-0 font-medium text-foreground">execute</span>
|
||||
<span className={cn('ml-auto shrink-0 text-xs', failed && 'text-destructive')}>
|
||||
{statusLabel}
|
||||
</span>
|
||||
</button>
|
||||
|
||||
{calls.length > 0 && (
|
||||
<div className="px-4 pb-2 space-y-0.5">
|
||||
{calls.map((call, index) => (
|
||||
{!detailsOpen && calls.length > 0 && (
|
||||
<div className={cn(TRANSCRIPT_DETAIL_CLASS, 'space-y-0.5')}>
|
||||
{calls.slice(0, previewCallLimit).map((call, index) => (
|
||||
<ExecuteCallRow key={`${call.tool}-${index}`} call={call} onFileClick={onFileClick} />
|
||||
))}
|
||||
{calls.length > previewCallLimit && (
|
||||
<div className="text-xs text-muted-foreground">({calls.length - previewCallLimit} more calls)</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<ToolContentFiles part={part} className="px-4 pb-2" />
|
||||
<ToolContentFiles part={part} className={TRANSCRIPT_DETAIL_CLASS} />
|
||||
|
||||
{!expanded && errorPreview.length > 0 && (
|
||||
<div className="px-4 pb-2 font-mono text-xs text-destructive">
|
||||
{!detailsOpen && errorPreview.length > 0 && (
|
||||
<div className={cn(TRANSCRIPT_DETAIL_CLASS, 'font-mono text-xs text-destructive')}>
|
||||
{errorPreview.map((line, index) => (
|
||||
<div key={index} className="whitespace-pre-wrap break-words">
|
||||
{index === 0 ? `↳ ${line}` : ` ${line}`}
|
||||
@@ -280,57 +279,63 @@ export function ExecuteToolPart({ part, isWaitingPermission, onFileClick }: Exec
|
||||
</div>
|
||||
)}
|
||||
|
||||
{expanded && (
|
||||
<div className="bg-card space-y-3 p-3">
|
||||
<div className="text-sm">
|
||||
<div className="text-muted-foreground mb-1">Code</div>
|
||||
{code ? (
|
||||
<HighlightedCode content={code} language="ts" digits={digits} />
|
||||
) : (
|
||||
<div className="text-xs text-muted-foreground">Waiting for code…</div>
|
||||
)}
|
||||
<ToolDetails open={detailsOpen} onOpenChange={setDetailsOpen} title="execute">
|
||||
{calls.length > 0 && (
|
||||
<div className="space-y-0.5">
|
||||
{calls.map((call, index) => (
|
||||
<ExecuteCallRow key={`${call.tool}-${index}`} call={call} onFileClick={onFileClick} />
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="text-sm">
|
||||
<div className="text-muted-foreground mb-1">Output</div>
|
||||
{parsedOutput ? (
|
||||
<>
|
||||
<HighlightedCode content={parsedOutput.json} language="json" digits={digits} />
|
||||
{parsedOutput.rest && (
|
||||
<pre className="mt-1 whitespace-pre-wrap break-words text-xs text-foreground">
|
||||
{parsedOutput.rest}
|
||||
</pre>
|
||||
)}
|
||||
</>
|
||||
) : displayOutput ? (
|
||||
<pre
|
||||
className={`whitespace-pre-wrap break-words text-xs ${failed ? 'text-destructive' : 'text-foreground'}`}
|
||||
>
|
||||
{displayOutput}
|
||||
</pre>
|
||||
) : (
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{status === 'completed' ? 'No output' : 'Waiting for output…'}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-4">
|
||||
{code && (
|
||||
<div className="flex items-center gap-1">
|
||||
<CopyButton content={code} title="Copy code" />
|
||||
<span className="text-xs text-muted-foreground">Copy code</span>
|
||||
</div>
|
||||
)}
|
||||
{output && (
|
||||
<div className="flex items-center gap-1">
|
||||
<CopyButton content={output} title="Copy output" />
|
||||
<span className="text-xs text-muted-foreground">Copy output</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="text-sm">
|
||||
<div className="text-muted-foreground mb-1">Code</div>
|
||||
{code ? (
|
||||
<HighlightedCode content={code} language="ts" digits={digits} />
|
||||
) : (
|
||||
<div className="text-xs text-muted-foreground">Waiting for code…</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="text-sm">
|
||||
<div className="text-muted-foreground mb-1">Output</div>
|
||||
{parsedOutput ? (
|
||||
<>
|
||||
<HighlightedCode content={parsedOutput.json} language="json" digits={digits} />
|
||||
{parsedOutput.rest && (
|
||||
<pre className="mt-1 whitespace-pre-wrap break-words text-xs text-foreground">
|
||||
{parsedOutput.rest}
|
||||
</pre>
|
||||
)}
|
||||
</>
|
||||
) : displayOutput ? (
|
||||
<pre
|
||||
className={`whitespace-pre-wrap break-words text-xs ${failed ? 'text-destructive' : 'text-foreground'}`}
|
||||
>
|
||||
{displayOutput}
|
||||
</pre>
|
||||
) : (
|
||||
<div className="text-xs text-muted-foreground">
|
||||
{status === 'completed' ? 'No output' : 'Waiting for output…'}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-4">
|
||||
{code && (
|
||||
<div className="flex items-center gap-1">
|
||||
<CopyButton content={code} title="Copy code" />
|
||||
<span className="text-xs text-muted-foreground">Copy code</span>
|
||||
</div>
|
||||
)}
|
||||
{output && (
|
||||
<div className="flex items-center gap-1">
|
||||
<CopyButton content={output} title="Copy output" />
|
||||
<span className="text-xs text-muted-foreground">Copy output</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</ToolDetails>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -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 (
|
||||
<pre className="bg-accent p-2 text-xs overflow-x-auto">
|
||||
{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 <div key={index} className={tone}>{line || ' '}</div>
|
||||
})}
|
||||
</pre>
|
||||
)
|
||||
}
|
||||
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 (
|
||||
<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"
|
||||
const pathLabel = relativePath && (
|
||||
isFileLink ? (
|
||||
<span
|
||||
onClick={handleFileClick}
|
||||
className="min-w-0 truncate text-primary text-xs hover:underline cursor-pointer"
|
||||
>
|
||||
<div className="flex items-center gap-2 min-w-0">
|
||||
<span className="text-success flex-shrink-0">✓</span>
|
||||
<span className="font-medium flex-shrink-0">{toolName}</span>
|
||||
{filePath && (
|
||||
isFileLink ? (
|
||||
<span
|
||||
onClick={handleFileClick}
|
||||
className="text-primary text-xs truncate hover:underline cursor-pointer"
|
||||
{relativePath}
|
||||
</span>
|
||||
) : (
|
||||
<span className="min-w-0 truncate text-muted-foreground text-xs">{relativePath}</span>
|
||||
)
|
||||
)
|
||||
|
||||
if (filediff) {
|
||||
return (
|
||||
<>
|
||||
<div className="my-1 w-full bg-muted px-3 py-2 md:px-4 md:py-3">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => hasExpandableContent && setDetailsOpen(!detailsOpen)}
|
||||
aria-label={relativePath ? `${toolName} ${relativePath}` : toolName}
|
||||
className="flex w-full min-w-0 items-center gap-2 font-mono text-xs text-muted-foreground text-left transition-colors hover:text-foreground"
|
||||
>
|
||||
<span className="flex-shrink-0">←</span>
|
||||
<span className="flex-shrink-0 font-medium text-foreground">{toolName}</span>
|
||||
{pathLabel}
|
||||
<span className="ml-auto flex flex-shrink-0 items-center gap-2">
|
||||
<DiffStats additions={filediff.additions} deletions={filediff.deletions} />
|
||||
<span className="text-muted-foreground text-xs">{getDuration()}</span>
|
||||
{detailsOpen ? <ChevronUp className="w-4 h-4 text-muted-foreground" /> : <ChevronDown className="w-4 h-4 text-muted-foreground" />}
|
||||
</span>
|
||||
</button>
|
||||
|
||||
{!detailsOpen && previewRows.length > 0 && (
|
||||
<div className="mt-1">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setDetailsOpen(true)}
|
||||
aria-label={`Show diff for ${relativePath ?? toolName}`}
|
||||
className="block w-full text-left"
|
||||
>
|
||||
{getRelativePath(filePath)}
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-muted-foreground text-xs truncate">{getRelativePath(filePath)}</span>
|
||||
)
|
||||
<DiffLines rows={previewRows} language={language} />
|
||||
</button>
|
||||
{hiddenLineCount > 0 && (
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setDetailsOpen(true)}
|
||||
className="text-muted-foreground text-xs transition-colors hover:text-foreground"
|
||||
>
|
||||
({hiddenLineCount} more lines)
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{detailsOpen && !isMobile && (
|
||||
<div className="mt-1">
|
||||
<DiffLines rows={diffRows} language={language} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
{isMobile && (
|
||||
<ToolDetails open={detailsOpen} onOpenChange={setDetailsOpen} title={detailsTitle}>
|
||||
<DiffLines rows={diffRows} language={language} />
|
||||
</ToolDetails>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-2 flex-shrink-0">
|
||||
{filediff && <DiffStats additions={filediff.additions} deletions={filediff.deletions} />}
|
||||
|
||||
<ToolContentFiles part={part} className={TRANSCRIPT_DETAIL_CLASS} />
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="my-1">
|
||||
<button
|
||||
onClick={() => hasExpandableContent && setDetailsOpen(!detailsOpen)}
|
||||
className={cn(TRANSCRIPT_ROW_CLASS, 'group hover:text-foreground transition-colors')}
|
||||
>
|
||||
<span className="flex-shrink-0 text-success">✓</span>
|
||||
<span className="flex-shrink-0 font-medium text-foreground">{toolName}</span>
|
||||
{pathLabel}
|
||||
<span className="ml-auto flex flex-shrink-0 items-center gap-2">
|
||||
<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" />
|
||||
detailsOpen ? <ChevronUp className="w-4 h-4 text-muted-foreground" /> : <ChevronDown className="w-4 h-4 text-muted-foreground" />
|
||||
)}
|
||||
</div>
|
||||
</span>
|
||||
</button>
|
||||
|
||||
<ToolContentFiles part={part} className="px-3 pb-2 bg-card" />
|
||||
<ToolContentFiles part={part} className={TRANSCRIPT_DETAIL_CLASS} />
|
||||
|
||||
{expanded && hasExpandableContent && (
|
||||
<div className="bg-card p-0">
|
||||
{filediff && <PatchViewer patch={filediff.patch} />}
|
||||
{content && !filediff && <CodePreview fileName={filePath || ''} content={content} />}
|
||||
</div>
|
||||
{hasExpandableContent && (
|
||||
<ToolDetails open={detailsOpen} onOpenChange={setDetailsOpen} title={detailsTitle}>
|
||||
{content && <CodePreview fileName={filePath || ''} content={content} />}
|
||||
</ToolDetails>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
|
||||
@@ -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 (
|
||||
<div role={isAborted ? 'status' : 'alert'} title={error.message} className={`my-1 flex min-w-0 items-start gap-1.5 text-xs ${tone}`}>
|
||||
|
||||
@@ -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<typeof import('@/hooks/useMobile')>()),
|
||||
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(<MessagePart part={completedShell({ command: 'git status' }, 'clean tree')} />)
|
||||
|
||||
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(<MessagePart part={toolPart('shell', { status: 'streaming', input: '' })} />)
|
||||
|
||||
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(<MessagePart part={projected!} />)
|
||||
|
||||
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(
|
||||
<MessagePart
|
||||
part={toolPart('edit', {
|
||||
status: 'completed',
|
||||
input: { path: '/test/file.txt' },
|
||||
content: [{ type: 'text', text: 'edited' }],
|
||||
metadata: {
|
||||
files: [
|
||||
{
|
||||
file: '/test/file.txt',
|
||||
patch: `diff --git a/file.txt b/file.txt\n--- a/file.txt\n+++ b/file.txt\n@@ -1 +1,20 @@\n${changedLines}`,
|
||||
additions: 20,
|
||||
deletions: 0,
|
||||
status: 'modified',
|
||||
},
|
||||
],
|
||||
},
|
||||
})}
|
||||
/>,
|
||||
)
|
||||
|
||||
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(
|
||||
<MessagePart
|
||||
@@ -649,21 +722,47 @@ describe('MessagePart', () => {
|
||||
/>,
|
||||
)
|
||||
|
||||
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(
|
||||
<MessagePart
|
||||
part={toolPart('edit', {
|
||||
status: 'completed',
|
||||
input: { path: '/test/file.ts' },
|
||||
content: [{ type: 'text', text: 'edited' }],
|
||||
metadata: {
|
||||
files: [
|
||||
{
|
||||
file: '/test/file.ts',
|
||||
patch: '@@ -1 +1,2 @@\n const value = 1\n+const added = 2',
|
||||
additions: 1,
|
||||
deletions: 0,
|
||||
status: 'modified',
|
||||
},
|
||||
],
|
||||
},
|
||||
})}
|
||||
/>,
|
||||
)
|
||||
|
||||
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', () => {
|
||||
|
||||
@@ -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 (
|
||||
<details className="border border-border rounded-lg my-2">
|
||||
<summary className="px-4 py-2 bg-muted hover:bg-accent cursor-pointer text-sm font-medium">
|
||||
<details className="my-1">
|
||||
<summary className="cursor-pointer py-0.5 text-sm text-muted-foreground hover:text-foreground">
|
||||
Reasoning
|
||||
</summary>
|
||||
<div className="p-4 bg-card text-sm text-muted-foreground whitespace-pre-wrap">
|
||||
<div className={cn(TRANSCRIPT_DETAIL_CLASS, 'text-sm text-muted-foreground whitespace-pre-wrap')}>
|
||||
{part.text}
|
||||
</div>
|
||||
</details>
|
||||
|
||||
@@ -1,103 +1,76 @@
|
||||
import { cn } from '@/lib/utils'
|
||||
|
||||
function Bar({ className }: { className: string }) {
|
||||
return <div className={cn('animate-pulse rounded', className)} />
|
||||
}
|
||||
|
||||
function UserTurnSkeleton({ widths }: { widths: string[] }) {
|
||||
return (
|
||||
<div className="py-2">
|
||||
<div className="border-l-[3px] border-primary/40 bg-muted px-4 py-3">
|
||||
<div className="space-y-2">
|
||||
{widths.map((width, index) => (
|
||||
<Bar key={index} className={cn('h-4 bg-accent', width)} />
|
||||
))}
|
||||
</div>
|
||||
<Bar className="mt-3 h-3 w-16 bg-accent" />
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function TurnFooterSkeleton() {
|
||||
return (
|
||||
<div className="mt-3 flex items-center gap-2">
|
||||
<Bar className="h-3 w-10 bg-primary/30" />
|
||||
<Bar className="h-3 w-24 bg-muted" />
|
||||
<Bar className="h-3 w-12 bg-muted" />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
function AssistantTurnSkeleton() {
|
||||
return (
|
||||
<div className="py-2">
|
||||
<div className="space-y-2">
|
||||
<Bar className="h-4 w-full bg-muted" />
|
||||
<Bar className="h-4 w-5/6 bg-muted" />
|
||||
<div className="flex items-center gap-2 py-0.5">
|
||||
<Bar className="h-3 w-3 bg-muted" />
|
||||
<Bar className="h-3 w-40 bg-muted" />
|
||||
</div>
|
||||
<div className="space-y-1.5 bg-muted px-3 py-2 md:px-4 md:py-3">
|
||||
<Bar className="h-3 w-1/2 bg-accent" />
|
||||
<Bar className="h-3 w-3/4 bg-accent" />
|
||||
<Bar className="h-3 w-2/3 bg-accent" />
|
||||
</div>
|
||||
<Bar className="h-4 w-2/3 bg-muted" />
|
||||
</div>
|
||||
<TurnFooterSkeleton />
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
/** Placeholder transcript shown while a session loads, mirroring the CLI-style turn layout. */
|
||||
export function MessageSkeleton() {
|
||||
return (
|
||||
<div className="flex flex-col space-y-2 p-2 overflow-x-hidden">
|
||||
{/* User message skeleton */}
|
||||
<div className="flex flex-col">
|
||||
<div className="w-full rounded-lg p-1.5 bg-primary/20 border border-primary/30">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<div className="h-3 w-12 bg-muted animate-pulse rounded" />
|
||||
<div className="h-3 w-16 bg-muted animate-pulse rounded" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<div className="h-4 bg-muted animate-pulse rounded w-3/4" />
|
||||
<div className="h-4 bg-muted animate-pulse rounded w-1/2" />
|
||||
</div>
|
||||
<div className="flex flex-col overflow-x-hidden p-2" aria-hidden="true">
|
||||
<UserTurnSkeleton widths={['w-3/4', 'w-1/2']} />
|
||||
<AssistantTurnSkeleton />
|
||||
<UserTurnSkeleton widths={['w-4/5']} />
|
||||
<AssistantTurnSkeleton />
|
||||
<UserTurnSkeleton widths={['w-2/3']} />
|
||||
<div className="py-2">
|
||||
<div className="flex items-center gap-2 text-muted-foreground">
|
||||
<span className="animate-pulse">▋</span>
|
||||
<Bar className="h-4 w-20 bg-muted" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Assistant message skeleton */}
|
||||
<div className="flex flex-col">
|
||||
<div className="w-full rounded-lg p-1.5 bg-card/50 border border-border">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<div className="h-3 w-16 bg-muted animate-pulse rounded" />
|
||||
<div className="h-3 w-16 bg-muted animate-pulse rounded" />
|
||||
<div className="flex items-center gap-1">
|
||||
<div className="h-3 w-20 bg-primary/20 animate-pulse rounded" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<div className="h-4 bg-muted animate-pulse rounded w-full" />
|
||||
<div className="h-4 bg-muted animate-pulse rounded w-5/6" />
|
||||
<div className="h-4 bg-muted animate-pulse rounded w-2/3" />
|
||||
<div className="h-20 bg-muted/50 animate-pulse rounded mt-3" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex flex-col">
|
||||
<div className="w-full rounded-lg p-1.5 bg-primary/20 border border-primary/30">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<div className="h-3 w-12 bg-muted animate-pulse rounded" />
|
||||
<div className="h-3 w-16 bg-muted animate-pulse rounded" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<div className="h-4 bg-muted animate-pulse rounded w-3/4" />
|
||||
<div className="h-4 bg-muted animate-pulse rounded w-1/2" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Assistant message skeleton */}
|
||||
<div className="flex flex-col">
|
||||
<div className="w-full rounded-lg p-1.5 bg-card/50 border border-border">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<div className="h-3 w-16 bg-muted animate-pulse rounded" />
|
||||
<div className="h-3 w-16 bg-muted animate-pulse rounded" />
|
||||
<div className="flex items-center gap-1">
|
||||
<div className="h-3 w-20 bg-primary/20 animate-pulse rounded" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<div className="h-4 bg-muted animate-pulse rounded w-full" />
|
||||
<div className="h-4 bg-muted animate-pulse rounded w-5/6" />
|
||||
<div className="h-4 bg-muted animate-pulse rounded w-2/3" />
|
||||
<div className="h-20 bg-muted/50 animate-pulse rounded mt-3" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Second user message skeleton */}
|
||||
<div className="flex flex-col">
|
||||
<div className="w-full rounded-lg p-1.5 bg-primary/20 border border-primary/30">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<div className="h-3 w-12 bg-muted animate-pulse rounded" />
|
||||
<div className="h-3 w-16 bg-muted animate-pulse rounded" />
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<div className="h-4 bg-muted animate-pulse rounded w-4/5" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Loading assistant message */}
|
||||
<div className="flex flex-col">
|
||||
<div className="w-full rounded-lg p-1.5 bg-card/50 border border-border animate-pulse-subtle">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<div className="h-3 w-16 bg-muted animate-pulse rounded" />
|
||||
<div className="h-3 w-16 bg-muted animate-pulse rounded" />
|
||||
<div className="flex items-center gap-1">
|
||||
<span className="animate-pulse">●</span>
|
||||
<div className="h-3 w-24 bg-primary/20 animate-pulse rounded" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-2 text-muted-foreground">
|
||||
<span className="animate-pulse">▋</span>
|
||||
<div className="h-4 w-20 bg-muted animate-pulse rounded" />
|
||||
</div>
|
||||
<div className="mt-3 flex items-center gap-2">
|
||||
<Bar className="h-3 w-10 bg-primary/30" />
|
||||
<Bar className="h-3 w-24 bg-muted" />
|
||||
<span className="animate-pulse-subtle text-xs text-info">streaming</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
)
|
||||
}
|
||||
|
||||
@@ -24,12 +24,18 @@ const mocks = vi.hoisted(() => ({
|
||||
useSettings: vi.fn(),
|
||||
useRefreshMessage: vi.fn(),
|
||||
useSessionAgent: vi.fn(),
|
||||
useMobile: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useSettings', () => ({
|
||||
useSettings: mocks.useSettings,
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useMobile', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('@/hooks/useMobile')>()),
|
||||
useMobile: mocks.useMobile,
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useRemoveMessage', () => ({
|
||||
useRefreshMessage: () => mocks.useRefreshMessage(),
|
||||
}))
|
||||
@@ -147,6 +153,7 @@ describe('MessageThread', () => {
|
||||
mutate: vi.fn(),
|
||||
})
|
||||
mocks.useSessionAgent.mockReturnValue({ agent: 'test-agent' })
|
||||
mocks.useMobile.mockReturnValue(false)
|
||||
useUIState.getState().setIsEditingMessage(false)
|
||||
})
|
||||
|
||||
@@ -474,7 +481,28 @@ describe('MessageThread', () => {
|
||||
)
|
||||
|
||||
expect(screen.getByText('Hello')).toBeInTheDocument()
|
||||
expect(screen.getByText('You')).toBeInTheDocument()
|
||||
expect(screen.queryByText('You')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders the assistant footer with agent, model, and duration', () => {
|
||||
setupSettings({ simpleChatMode: false, showReasoning: false })
|
||||
|
||||
render(
|
||||
<MessageThread
|
||||
sessionID="test-session"
|
||||
messages={[
|
||||
assistantMessage('2', [textPart('Done')], {
|
||||
agent: 'build',
|
||||
time: { created: 0, completed: 93_000 },
|
||||
}),
|
||||
]}
|
||||
pending={[]}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByText('Build')).toBeInTheDocument()
|
||||
expect(screen.getByText('test-model')).toBeInTheDocument()
|
||||
expect(screen.getByText('1m 33s')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('exposes the message id on a rendered user message', () => {
|
||||
@@ -530,6 +558,36 @@ describe('MessageThread', () => {
|
||||
expect(screen.getByText('12 tests passed')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('collapses a long shell output behind the preview and reveals it on click', () => {
|
||||
setupSettings({ simpleChatMode: false, showReasoning: false })
|
||||
|
||||
const lines = Array.from({ length: 25 }, (_, index) => `line-${String(index + 1).padStart(2, '0')}`)
|
||||
const output = lines.join('\n')
|
||||
const messages: SessionMessageInfo[] = [
|
||||
{
|
||||
id: 'shell-long',
|
||||
type: 'shell',
|
||||
shellID: 'sh_long',
|
||||
command: 'seq 25',
|
||||
status: 'exited',
|
||||
exit: 0,
|
||||
output: { output, cursor: output.length, size: output.length, truncated: false },
|
||||
time: { created: Date.now() },
|
||||
},
|
||||
]
|
||||
|
||||
render(<MessageThread sessionID="test-session" messages={messages} pending={[]} />)
|
||||
|
||||
expect(screen.getByText('(15 earlier lines)')).toBeInTheDocument()
|
||||
expect(screen.getByText(/line-25/)).toBeInTheDocument()
|
||||
expect(screen.queryByText(/line-01/)).not.toBeInTheDocument()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Show shell details' }))
|
||||
|
||||
expect(screen.getByText(/line-01/)).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Copy output' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders a projected compaction banner from the fixtures', () => {
|
||||
setupSettings({ simpleChatMode: false, showReasoning: false })
|
||||
|
||||
|
||||
@@ -28,6 +28,9 @@ import { readShowArtifactCall } from '@/lib/artifactTool'
|
||||
import { groupExplorationParts, type AssistantContentItem } from '@/lib/explorationGroups'
|
||||
import type { WalkthroughSource } from '@opencode-manager/shared/schemas'
|
||||
import { ExplorationGroup } from './ExplorationGroup'
|
||||
import { ShellPreview, ToolDetails, useToolDetailsState } from './ToolDetails'
|
||||
import { cn, formatDuration } from '@/lib/utils'
|
||||
import { getAgentStyleVars } from '@/lib/agent-colors'
|
||||
|
||||
function getMessageText(message: SessionMessageInfo): string {
|
||||
switch (message.type) {
|
||||
@@ -169,7 +172,7 @@ function UserAttachments({ files: attachedFiles, agents: attachedAgents, skills:
|
||||
|
||||
function MessageDivider({ label }: { label: string }) {
|
||||
return (
|
||||
<div className="flex items-center gap-2 my-1 text-xs text-muted-foreground">
|
||||
<div className="flex items-center gap-2 my-2 text-xs text-muted-foreground">
|
||||
<span className="h-px flex-1 bg-border" />
|
||||
<span className="shrink-0">{label}</span>
|
||||
<span className="h-px flex-1 bg-border" />
|
||||
@@ -224,7 +227,7 @@ function SessionNotice({
|
||||
const { text, completion } = sessionNoticeContent(message)
|
||||
|
||||
if (!completion) {
|
||||
return <div className="my-1 px-3 py-1 text-xs text-muted-foreground truncate">◈ {text}</div>
|
||||
return <div className="my-2 px-3 py-1 text-xs text-muted-foreground truncate">◈ {text}</div>
|
||||
}
|
||||
|
||||
const tone = completion.state === 'error'
|
||||
@@ -246,17 +249,18 @@ function SessionNotice({
|
||||
type="button"
|
||||
onClick={() => onChildSessionClick(childID)}
|
||||
aria-live="polite"
|
||||
className="my-1 block w-full px-3 py-1 text-left text-xs truncate hover:underline"
|
||||
className="my-2 block w-full px-3 py-1 text-left text-xs truncate hover:underline"
|
||||
>
|
||||
{content}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
|
||||
return <div aria-live="polite" className="my-1 px-3 py-1 text-xs truncate">{content}</div>
|
||||
return <div aria-live="polite" className="my-2 px-3 py-1 text-xs truncate">{content}</div>
|
||||
}
|
||||
|
||||
function ShellMessage({ message }: { message: SessionMessageShell }) {
|
||||
const [detailsOpen, setDetailsOpen] = useToolDetailsState(false)
|
||||
const output = message.output?.output ?? ''
|
||||
const statusLabel = message.status === 'running'
|
||||
? 'running'
|
||||
@@ -265,26 +269,33 @@ function ShellMessage({ message }: { message: SessionMessageShell }) {
|
||||
: `${message.status} (exit ${message.exit})`
|
||||
|
||||
return (
|
||||
<div className="rounded-lg border border-border bg-card/50 p-2 my-1">
|
||||
<div className="flex items-center gap-2 text-sm min-w-0">
|
||||
<span className="text-success shrink-0">$</span>
|
||||
<span className="text-foreground truncate">{message.command}</span>
|
||||
<span className="text-muted-foreground text-xs ml-auto shrink-0">{statusLabel}</span>
|
||||
</div>
|
||||
<>
|
||||
<ShellPreview
|
||||
command={message.command}
|
||||
output={output}
|
||||
onClick={() => setDetailsOpen(!detailsOpen)}
|
||||
status={<span className="ml-auto shrink-0 text-xs text-muted-foreground">{statusLabel}</span>}
|
||||
/>
|
||||
{output && (
|
||||
<div className="relative mt-1">
|
||||
<pre className="bg-accent p-2 rounded text-xs overflow-x-auto whitespace-pre-wrap">{output}</pre>
|
||||
<CopyButton content={output} title="Copy output" className="absolute top-1 right-1" iconSize="sm" />
|
||||
</div>
|
||||
<ToolDetails
|
||||
open={detailsOpen}
|
||||
onOpenChange={setDetailsOpen}
|
||||
title={`$ ${message.command}`}
|
||||
>
|
||||
<div className="relative">
|
||||
<pre className="bg-accent p-2 rounded text-xs overflow-x-auto whitespace-pre-wrap">{output}</pre>
|
||||
<CopyButton content={output} title="Copy output" className="absolute top-1 right-1" iconSize="sm" />
|
||||
</div>
|
||||
</ToolDetails>
|
||||
)}
|
||||
</div>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function CompactionBanner({ message }: { message: SessionMessageCompaction }) {
|
||||
if (message.status === 'running') {
|
||||
return (
|
||||
<div className="flex items-center gap-2 my-1 text-xs text-muted-foreground">
|
||||
<div className="flex items-center gap-2 my-2 text-xs text-muted-foreground">
|
||||
<Loader2 className="w-3.5 h-3.5 animate-spin" />
|
||||
<span>Compacting session...</span>
|
||||
</div>
|
||||
@@ -293,38 +304,41 @@ function CompactionBanner({ message }: { message: SessionMessageCompaction }) {
|
||||
|
||||
if (message.status === 'failed') {
|
||||
return (
|
||||
<div className="my-1 rounded-lg border border-destructive/30 bg-destructive/10 px-3 py-1.5 text-xs text-destructive">
|
||||
Compaction failed: {message.error.message}
|
||||
<div className="my-2 border-l-2 border-destructive pl-2 text-xs text-destructive">
|
||||
✗ Compaction failed: {message.error.message}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="my-1 rounded-lg border border-border bg-card/50 px-3 py-1.5 text-xs text-muted-foreground">
|
||||
<span className="font-medium">Session compacted</span>
|
||||
{message.summary && <p className="mt-0.5 whitespace-pre-wrap">{message.summary}</p>}
|
||||
</div>
|
||||
<>
|
||||
<MessageDivider label="Session compacted" />
|
||||
{message.summary && (
|
||||
<p className="mt-0.5 text-xs text-muted-foreground whitespace-pre-wrap text-center">
|
||||
{message.summary}
|
||||
</p>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
function QueuedPromptRow({ item }: { item: SessionInboxUser }) {
|
||||
return (
|
||||
<div className="w-full rounded-lg p-1.5 bg-warning/10 border border-warning/30">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<span className="text-xs font-medium text-muted-foreground">You</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{new Date(item.time.created).toLocaleTimeString()}
|
||||
</span>
|
||||
<span className="text-xs font-semibold bg-warning text-warning-foreground px-1.5 py-0.5 rounded">
|
||||
{item.delivery === 'queue' ? 'QUEUED' : 'STEERING'}
|
||||
</span>
|
||||
<div className="py-2">
|
||||
<div className="border-l-[3px] border-dashed border-muted-foreground bg-muted/60 px-4 py-3 text-muted-foreground">
|
||||
<ClickableUserMessage content={item.payload.text} onClick={() => {}} isEditable={false} />
|
||||
<UserAttachments
|
||||
files={item.payload.files}
|
||||
agents={item.payload.agents}
|
||||
skills={item.payload.skills}
|
||||
/>
|
||||
<div className="mt-2 flex items-center gap-2 text-xs text-muted-foreground">
|
||||
<span>{new Date(item.time.created).toLocaleTimeString()}</span>
|
||||
<span className="font-mono text-[11px] font-semibold tracking-wider text-warning">
|
||||
{item.delivery === 'queue' ? 'QUEUED' : 'STEERING'}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
<ClickableUserMessage content={item.payload.text} onClick={() => {}} isEditable={false} />
|
||||
<UserAttachments
|
||||
files={item.payload.files}
|
||||
agents={item.payload.agents}
|
||||
skills={item.payload.skills}
|
||||
/>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -386,70 +400,73 @@ const MessageRow = memo(function MessageRow({
|
||||
if (!hasRenderableContent(message, simpleChatMode, showReasoning)) return null
|
||||
|
||||
return (
|
||||
<div className="flex flex-col group" data-message-id={message.id}>
|
||||
<div
|
||||
className="group py-2"
|
||||
data-message-id={message.id}
|
||||
>
|
||||
<div
|
||||
className={`w-full rounded-lg p-1.5 ${
|
||||
isEditingThisMessage
|
||||
? 'bg-primary/30 border border-primary/50'
|
||||
: 'bg-primary/20 border border-primary/30'
|
||||
}`}
|
||||
className={cn(
|
||||
'border-l-[3px] bg-muted px-4 py-3',
|
||||
isEditingThisMessage ? 'border-info' : 'border-primary',
|
||||
)}
|
||||
>
|
||||
<div className="flex items-center justify-between gap-2 mb-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs font-medium text-muted-foreground">You</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{new Date(message.time.created).toLocaleTimeString()}
|
||||
</span>
|
||||
{canEditUserMessage && nextAssistantMessageId && (
|
||||
<button
|
||||
onClick={() => handleStartEditUserMessage(message.id, nextAssistantMessageId)}
|
||||
className="p-1 rounded hover:bg-accent text-muted-foreground hover:text-foreground transition-colors"
|
||||
title="Edit message"
|
||||
>
|
||||
<Pencil className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{canUndoUserMessage && (
|
||||
<UserMessageActionButtons
|
||||
<div className="text-foreground">
|
||||
{isEditingThisMessage && nextAssistantMessageId ? (
|
||||
<EditableUserMessage
|
||||
sessionId={sessionID}
|
||||
directory={directory}
|
||||
userMessageId={message.id}
|
||||
userMessageContent={messageTextContent}
|
||||
onUndo={onUndoMessage}
|
||||
content={messageTextContent}
|
||||
assistantMessageId={nextAssistantMessageId}
|
||||
onCancel={handleCancelEdit}
|
||||
model={model}
|
||||
/>
|
||||
) : simpleChatMode ? (
|
||||
<ClickableUserMessage
|
||||
content={messageTextContent}
|
||||
onClick={() => {}}
|
||||
isEditable={false}
|
||||
/>
|
||||
) : (
|
||||
<ClickableUserMessage
|
||||
content={messageTextContent}
|
||||
onClick={() => handleStartEditUserMessage(message.id, nextAssistantMessageId ?? '')}
|
||||
isEditable={false}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{isEditingThisMessage && nextAssistantMessageId ? (
|
||||
<EditableUserMessage
|
||||
sessionId={sessionID}
|
||||
directory={directory}
|
||||
content={messageTextContent}
|
||||
assistantMessageId={nextAssistantMessageId}
|
||||
onCancel={handleCancelEdit}
|
||||
model={model}
|
||||
/>
|
||||
) : simpleChatMode ? (
|
||||
<ClickableUserMessage
|
||||
content={messageTextContent}
|
||||
onClick={() => {}}
|
||||
isEditable={false}
|
||||
/>
|
||||
) : (
|
||||
<ClickableUserMessage
|
||||
content={messageTextContent}
|
||||
onClick={() => handleStartEditUserMessage(message.id, nextAssistantMessageId ?? '')}
|
||||
isEditable={false}
|
||||
/>
|
||||
)}
|
||||
|
||||
<UserAttachments
|
||||
files={message.files}
|
||||
agents={message.agents}
|
||||
skills={message.skills}
|
||||
/>
|
||||
|
||||
<div className="mt-2 flex items-center gap-2 text-xs text-muted-foreground">
|
||||
<span>{new Date(message.time.created).toLocaleTimeString()}</span>
|
||||
{((canEditUserMessage && nextAssistantMessageId) || canUndoUserMessage) ? (
|
||||
<span className="flex items-center gap-1 transition-opacity md:opacity-0 md:group-hover:opacity-100 md:group-focus-within:opacity-100">
|
||||
{canEditUserMessage && nextAssistantMessageId && (
|
||||
<button
|
||||
onClick={() => handleStartEditUserMessage(message.id, nextAssistantMessageId)}
|
||||
className="p-1 rounded hover:bg-accent text-muted-foreground hover:text-foreground transition-colors"
|
||||
title="Edit message"
|
||||
>
|
||||
<Pencil className="w-3.5 h-3.5" />
|
||||
</button>
|
||||
)}
|
||||
|
||||
{canUndoUserMessage && (
|
||||
<UserMessageActionButtons
|
||||
sessionId={sessionID}
|
||||
directory={directory}
|
||||
userMessageId={message.id}
|
||||
userMessageContent={messageTextContent}
|
||||
onUndo={onUndoMessage}
|
||||
/>
|
||||
)}
|
||||
</span>
|
||||
) : null}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
@@ -496,66 +513,77 @@ const MessageRow = memo(function MessageRow({
|
||||
: 0
|
||||
|
||||
return (
|
||||
<div className="flex flex-col group" data-message-id={message.id}>
|
||||
<div
|
||||
className={`w-full rounded-lg p-1.5 bg-card/50 border border-border ${streaming ? 'animate-pulse-subtle' : ''}`}
|
||||
>
|
||||
<div className="flex items-center justify-between gap-2 mb-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-xs font-medium text-muted-foreground">
|
||||
{message.model.id}
|
||||
</span>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
{new Date(message.time.created).toLocaleTimeString()}
|
||||
</span>
|
||||
<div
|
||||
className="group py-2"
|
||||
data-message-id={message.id}
|
||||
>
|
||||
<div className="space-y-2">
|
||||
{contentItems.map((item, itemIndex) => (
|
||||
<div key={`${message.id}-${item.type === 'exploration' ? `exploration-${item.parts[0].id}` : `${item.part.type}-${itemIndex}`}`}>
|
||||
{item.type === 'exploration' ? (
|
||||
<ExplorationGroup
|
||||
parts={item.parts}
|
||||
messageID={message.id}
|
||||
directory={directory}
|
||||
repoFullPath={repoFullPath}
|
||||
repoLocalPath={repoLocalPath}
|
||||
onFileClick={onFileClick}
|
||||
onChildSessionClick={onChildSessionClick}
|
||||
onOpenWalkthrough={onOpenWalkthrough}
|
||||
/>
|
||||
) : (
|
||||
<MessagePart
|
||||
part={item.part}
|
||||
messageID={message.id}
|
||||
directory={directory}
|
||||
repoFullPath={repoFullPath}
|
||||
repoLocalPath={repoLocalPath}
|
||||
shellOutcome={shellOutcomeFor(item.part)}
|
||||
onFileClick={onFileClick}
|
||||
onChildSessionClick={onChildSessionClick}
|
||||
onOpenWalkthrough={onOpenWalkthrough}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
{!simpleChatMode && message.snapshot?.files && (
|
||||
<StepFileChanges
|
||||
files={message.snapshot.files}
|
||||
snapshot={message.snapshot.end}
|
||||
onFileClick={onFileClick}
|
||||
/>
|
||||
)}
|
||||
{message.retry && <RetryPart retry={message.retry} />}
|
||||
{message.error && <MessageError error={message.error} />}
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
{contentItems.map((item, itemIndex) => (
|
||||
<div key={`${message.id}-${item.type === 'exploration' ? `exploration-${item.parts[0].id}` : `${item.part.type}-${itemIndex}`}`}>
|
||||
{item.type === 'exploration' ? (
|
||||
<ExplorationGroup
|
||||
parts={item.parts}
|
||||
messageID={message.id}
|
||||
directory={directory}
|
||||
repoFullPath={repoFullPath}
|
||||
repoLocalPath={repoLocalPath}
|
||||
onFileClick={onFileClick}
|
||||
onChildSessionClick={onChildSessionClick}
|
||||
onOpenWalkthrough={onOpenWalkthrough}
|
||||
/>
|
||||
) : (
|
||||
<MessagePart
|
||||
part={item.part}
|
||||
messageID={message.id}
|
||||
directory={directory}
|
||||
repoFullPath={repoFullPath}
|
||||
repoLocalPath={repoLocalPath}
|
||||
shellOutcome={shellOutcomeFor(item.part)}
|
||||
onFileClick={onFileClick}
|
||||
onChildSessionClick={onChildSessionClick}
|
||||
onOpenWalkthrough={onOpenWalkthrough}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
{!simpleChatMode && message.snapshot?.files && (
|
||||
<StepFileChanges
|
||||
files={message.snapshot.files}
|
||||
snapshot={message.snapshot.end}
|
||||
onFileClick={onFileClick}
|
||||
/>
|
||||
)}
|
||||
{message.retry && <RetryPart retry={message.retry} />}
|
||||
{message.error && <MessageError error={message.error} />}
|
||||
</div>
|
||||
|
||||
<div className="text-xs text-muted-foreground my-1 flex items-center gap-2">
|
||||
{!(isFree) && <span>${(message.cost ?? 0).toFixed(4)} • {totalTokens} tokens</span>}
|
||||
<div className="mt-3 flex flex-wrap items-center gap-x-2 gap-y-1 text-xs text-muted-foreground">
|
||||
<span style={getAgentStyleVars(message.agent)} className="font-medium text-[var(--agent-color)]">
|
||||
{message.agent.charAt(0).toUpperCase() + message.agent.slice(1)}
|
||||
</span>
|
||||
<span aria-hidden="true">·</span>
|
||||
<span className="text-foreground">{message.model.id}</span>
|
||||
{message.time.completed !== undefined ? (
|
||||
<>
|
||||
<span aria-hidden="true">·</span>
|
||||
<span>{formatDuration(message.time.completed - message.time.created)}</span>
|
||||
</>
|
||||
) : streaming ? (
|
||||
<>
|
||||
<span aria-hidden="true">·</span>
|
||||
<span className="animate-pulse-subtle text-info">streaming</span>
|
||||
</>
|
||||
) : null}
|
||||
{!(isFree) && (
|
||||
<>
|
||||
<span aria-hidden="true">·</span>
|
||||
<span>${(message.cost ?? 0).toFixed(4)} • {totalTokens} tokens</span>
|
||||
</>
|
||||
)}
|
||||
<span className="flex items-center gap-1 transition-opacity md:opacity-0 md:group-hover:opacity-100 md:group-focus-within:opacity-100">
|
||||
<CopyButton content={messageTextContent} title="Copy message" />
|
||||
{messageTextContent && <TTSButton messageId={message.id} content={messageTextContent} />}
|
||||
</div>
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
@@ -583,8 +611,8 @@ const MessageRow = memo(function MessageRow({
|
||||
|
||||
if (message.type === 'skill') {
|
||||
return (
|
||||
<div className="my-1 rounded-lg border border-info/20 bg-info/5 px-3 py-1.5 text-xs text-muted-foreground">
|
||||
Skill loaded: <span className="font-medium text-foreground">{message.name}</span>
|
||||
<div className="my-2 text-xs text-muted-foreground">
|
||||
◈ Skill loaded: <span className="font-medium text-foreground">{message.name}</span>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen, fireEvent, waitFor, within } from '@testing-library/react'
|
||||
import { render, screen, fireEvent, waitFor, within, act } from '@testing-library/react'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { PromptInput } from './PromptInput'
|
||||
import { useSessionStatus } from '@/stores/sessionStatusStore'
|
||||
import { createCommandActionsMock } from '@/test/test-utils'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
@@ -146,6 +147,22 @@ describe('PromptInput composer layout', () => {
|
||||
mocks.useHasBackgroundActivity.mockReturnValue(false)
|
||||
})
|
||||
|
||||
it('anchors the activity bar in the gap above the controls row', () => {
|
||||
useSessionStatus.getState().setStatus('test-session', { type: 'busy' })
|
||||
|
||||
renderComponent()
|
||||
|
||||
const bar = screen.getByRole('progressbar', { name: 'Session working' })
|
||||
expect(controlsRow()).toContainElement(bar)
|
||||
expect(controlsRow().firstElementChild).toBe(bar)
|
||||
expect(bar).toHaveClass('absolute', 'bottom-full')
|
||||
expect(promptInput().compareDocumentPosition(bar) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()
|
||||
|
||||
act(() => {
|
||||
useSessionStatus.getState().clearStatus('test-session')
|
||||
})
|
||||
})
|
||||
|
||||
describe('primary action placement', () => {
|
||||
it('omits the submit button while the prompt is empty', () => {
|
||||
renderComponent()
|
||||
|
||||
@@ -1592,7 +1592,6 @@ return (
|
||||
<div role="status" aria-live="polite" className="sr-only">
|
||||
{sessionActivityAnnouncement}
|
||||
</div>
|
||||
<ComposerActivityBar sessionID={sessionID} />
|
||||
{composerModeStyle && (
|
||||
<span
|
||||
data-testid="composer-mode-badge"
|
||||
@@ -1663,7 +1662,8 @@ return (
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div ref={composerControlsRowRef} data-testid="composer-controls-row" className="flex gap-1.5 md:gap-2 items-center justify-between">
|
||||
<div ref={composerControlsRowRef} data-testid="composer-controls-row" className="relative flex gap-1.5 md:gap-2 items-center justify-between">
|
||||
<ComposerActivityBar sessionID={sessionID} />
|
||||
<div className="flex flex-1 md:flex-initial gap-1.5 md:gap-2 items-center min-w-0">
|
||||
{mobileVoiceRecorderState ? (
|
||||
<>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { memo, useEffect, useState } from 'react'
|
||||
import type { SessionMessageAssistantRetry } from '@opencode-manager/shared/opencode'
|
||||
import { RefreshCw, AlertTriangle } from 'lucide-react'
|
||||
import { RefreshCw } from 'lucide-react'
|
||||
|
||||
interface RetryPartProps {
|
||||
retry: SessionMessageAssistantRetry
|
||||
@@ -31,32 +31,19 @@ export const RetryPart = memo(function RetryPart({ retry }: RetryPartProps) {
|
||||
}, [nextTimestamp])
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-3 p-3 my-2 rounded-lg bg-warning/10 border border-warning/30">
|
||||
<div className="flex-shrink-0">
|
||||
<div className="relative">
|
||||
<RefreshCw className="w-5 h-5 text-warning animate-spin" style={{ animationDuration: '2s' }} />
|
||||
<AlertTriangle className="w-3 h-3 text-warning absolute -bottom-0.5 -right-0.5" />
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm font-medium text-warning">
|
||||
Retry attempt {retry.attempt}
|
||||
</span>
|
||||
{countdown > 0 ? (
|
||||
<span className="text-xs text-warning/80">
|
||||
(retrying in {countdown}s)
|
||||
</span>
|
||||
) : (
|
||||
<span className="text-xs text-warning/80">
|
||||
(retrying...)
|
||||
</span>
|
||||
)}
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground truncate mt-0.5">
|
||||
{retry.error.message}
|
||||
</p>
|
||||
</div>
|
||||
<div className="my-1 flex min-w-0 items-center gap-2 text-xs">
|
||||
<RefreshCw
|
||||
className="w-3.5 h-3.5 flex-shrink-0 text-warning animate-spin"
|
||||
style={{ animationDuration: '2s' }}
|
||||
/>
|
||||
<span className="font-medium text-warning">Retry attempt {retry.attempt}</span>
|
||||
{countdown > 0 ? (
|
||||
<span className="text-warning/80">(retrying in {countdown}s)</span>
|
||||
) : (
|
||||
<span className="text-warning/80">(retrying...)</span>
|
||||
)}
|
||||
<span aria-hidden="true" className="text-muted-foreground">·</span>
|
||||
<span className="min-w-0 truncate text-muted-foreground">{retry.error.message}</span>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
@@ -1,6 +1,8 @@
|
||||
import { useState } from 'react'
|
||||
import { ChevronDown, ChevronUp } from 'lucide-react'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { getRelativePath } from './FileToolRender'
|
||||
import { TRANSCRIPT_DETAIL_CLASS, TRANSCRIPT_ROW_CLASS } from './transcriptStyles'
|
||||
|
||||
interface StepFileChangesProps {
|
||||
files: string[]
|
||||
@@ -24,22 +26,23 @@ export function StepFileChanges({ files, snapshot, onFileClick }: StepFileChange
|
||||
const hiddenCount = files.length - INITIAL_FILES_SHOWN
|
||||
|
||||
return (
|
||||
<div className="border border-border rounded-lg overflow-hidden my-2">
|
||||
<div className="my-1">
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => hasMoreFiles && 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"
|
||||
className={cn(TRANSCRIPT_ROW_CLASS, 'hover:text-foreground transition-colors')}
|
||||
>
|
||||
<span className="font-medium">File Changes ({files.length} {fileNoun(files.length)})</span>
|
||||
<div className="flex items-center gap-2 flex-shrink-0">
|
||||
{snapshot && <span className="text-muted-foreground text-xs font-mono">{snapshot.slice(0, 8)}</span>}
|
||||
<span aria-hidden="true">±</span>
|
||||
<span className="font-medium text-foreground">File Changes ({files.length} {fileNoun(files.length)})</span>
|
||||
<span className="ml-auto flex flex-shrink-0 items-center gap-2">
|
||||
{snapshot && <span className="text-xs text-muted-foreground">{snapshot.slice(0, 8)}</span>}
|
||||
{hasMoreFiles && (
|
||||
expanded ? <ChevronUp className="w-4 h-4 text-muted-foreground" /> : <ChevronDown className="w-4 h-4 text-muted-foreground" />
|
||||
expanded ? <ChevronUp className="w-3.5 h-3.5" /> : <ChevronDown className="w-3.5 h-3.5" />
|
||||
)}
|
||||
</div>
|
||||
</span>
|
||||
</button>
|
||||
|
||||
<div className="bg-card px-3 py-2 space-y-1">
|
||||
<div className={cn(TRANSCRIPT_DETAIL_CLASS, 'space-y-0.5')}>
|
||||
{displayedFiles.map((file) => (
|
||||
<button
|
||||
key={file}
|
||||
@@ -56,7 +59,7 @@ export function StepFileChanges({ files, snapshot, onFileClick }: StepFileChange
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setExpanded(!expanded)}
|
||||
className="text-xs text-muted-foreground hover:text-foreground flex items-center gap-1 mt-1"
|
||||
className="text-xs text-muted-foreground hover:text-foreground flex items-center gap-1"
|
||||
>
|
||||
{expanded ? <ChevronUp className="w-3 h-3" /> : <ChevronDown className="w-3 h-3" />}
|
||||
{expanded ? 'Show less' : `+${hiddenCount} more ${fileNoun(hiddenCount)}`}
|
||||
|
||||
@@ -361,6 +361,39 @@ describe('ToolCallPart execute renderer', () => {
|
||||
expect(gutters[0].style.width).toBe(gutters[1].style.width)
|
||||
})
|
||||
|
||||
it('caps the collapsed child call preview and reports the hidden count', () => {
|
||||
const manyCalls = Array.from({ length: 8 }, (_, index) => ({
|
||||
tool: `cua-driver.call_${index}`,
|
||||
status: 'completed',
|
||||
input: { index },
|
||||
}))
|
||||
|
||||
renderWithProviders(<ToolCallPart part={completedExecute({ toolCalls: manyCalls })} messageID="msg_1" />)
|
||||
|
||||
expect(screen.getAllByRole('button', { name: /cua-driver\.call_/ })).toHaveLength(5)
|
||||
expect(screen.getByText('(3 more calls)')).toBeInTheDocument()
|
||||
expect(screen.queryByText('Code')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('cua-driver.call_5 [index=5]')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('reveals the code and output detail from the header on desktop', () => {
|
||||
const manyCalls = Array.from({ length: 8 }, (_, index) => ({
|
||||
tool: `cua-driver.call_${index}`,
|
||||
status: 'completed',
|
||||
input: { index },
|
||||
}))
|
||||
|
||||
renderWithProviders(<ToolCallPart part={completedExecute({ toolCalls: manyCalls })} messageID="msg_1" />)
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /execute/ }))
|
||||
|
||||
expect(screen.getByText('Code')).toBeInTheDocument()
|
||||
expect(screen.getByText('Output')).toBeInTheDocument()
|
||||
expect(screen.queryByText('(3 more calls)')).not.toBeInTheDocument()
|
||||
expect(screen.getAllByRole('button', { name: /cua-driver\.call_/ })).toHaveLength(8)
|
||||
expect(screen.getByText('cua-driver.call_5 [index=5]')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('reports a completed script that failed at runtime', () => {
|
||||
renderWithProviders(
|
||||
<ToolCallPart
|
||||
@@ -628,6 +661,46 @@ describe('ToolCallPart open walkthrough action', () => {
|
||||
})
|
||||
})
|
||||
|
||||
describe('ToolCallPart shell preview', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mocks.useSettings.mockReturnValue({
|
||||
preferences: { expandToolCalls: false },
|
||||
isLoading: false,
|
||||
updateSettings: vi.fn(),
|
||||
isUpdating: false,
|
||||
})
|
||||
mocks.useToolCallPermission.mockReturnValue(null)
|
||||
})
|
||||
|
||||
it('shows only the tail of a long shell output until the details are opened', () => {
|
||||
const lines = Array.from({ length: 25 }, (_, index) => `line ${index + 1}`)
|
||||
|
||||
renderWithProviders(
|
||||
<ToolCallPart
|
||||
part={{
|
||||
type: 'tool',
|
||||
id: 'call_lines',
|
||||
name: 'shell',
|
||||
time: { created: 1, ran: 2, completed: 3 },
|
||||
state: {
|
||||
status: 'completed',
|
||||
input: { command: 'seq 25' },
|
||||
content: [{ type: 'text', text: lines.join('\n') }],
|
||||
metadata: {},
|
||||
},
|
||||
}}
|
||||
messageID="msg_1"
|
||||
/>,
|
||||
)
|
||||
|
||||
const preview = screen.getByRole('button', { name: 'Show shell details' })
|
||||
expect(within(preview).getByText('(15 earlier lines)')).toBeInTheDocument()
|
||||
expect(preview.textContent).toMatch(/\bline 25\b/)
|
||||
expect(preview.textContent).not.toMatch(/\bline 1\b/)
|
||||
})
|
||||
})
|
||||
|
||||
describe('ToolCallPart show artifact action', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
|
||||
@@ -1,13 +1,14 @@
|
||||
import { useState, useRef, useEffect, useMemo, memo } from 'react'
|
||||
import { 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 { useMobile } from '@/hooks/useMobile'
|
||||
import { clampDisplayText } from '@/lib/clampDisplayText'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { ExternalLink, Loader2, Shield } from 'lucide-react'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { Button } from '@/components/ui/button'
|
||||
@@ -34,7 +35,9 @@ import { getFileApiUrl } from '@/api/files'
|
||||
import { ArtifactPart } from './ArtifactPart'
|
||||
import { ExecuteToolPart } from './ExecuteToolPart'
|
||||
import { FileReferenceText } from './FileReferenceText'
|
||||
import { ShellPreview, ToolDetails, useToolDetailsState } from './ToolDetails'
|
||||
import { ToolContentFiles } from './ToolContentFiles'
|
||||
import { TRANSCRIPT_DETAIL_CLASS, TRANSCRIPT_ROW_CLASS } from './transcriptStyles'
|
||||
import type { WalkthroughSource } from '@opencode-manager/shared/schemas'
|
||||
|
||||
function BoundedPre({ content, className }: { content: string; className: string }) {
|
||||
@@ -76,7 +79,7 @@ function ClickableJson({ json, onFileClick }: { json: unknown; onFileClick?: (fi
|
||||
|
||||
export const ToolCallPart = memo(function ToolCallPart({ part, messageID, directory, repoFullPath, repoLocalPath, shellOutcome, onFileClick, onChildSessionClick, onOpenWalkthrough }: ToolCallPartProps) {
|
||||
const { preferences } = useSettings()
|
||||
const { userBashCommands } = useUserBash()
|
||||
const isMobile = useMobile()
|
||||
const isSubagent = part.name === 'subagent'
|
||||
const subagentSessionId = isSubagent ? subagentSessionID(part) : undefined
|
||||
const backgroundSubagent = isSubagent ? backgroundChildSessionID(part) : undefined
|
||||
@@ -117,16 +120,14 @@ export const ToolCallPart = memo(function ToolCallPart({ part, messageID, direct
|
||||
return typeof provider === 'string' ? provider : undefined
|
||||
})()
|
||||
const sandboxProviderLabel = sandboxProvider !== undefined && sandboxProvider !== 'ocm' ? sandboxProvider : undefined
|
||||
const isUserBashCommand = part.state.status === 'completed' &&
|
||||
typeof displayCommand === 'string' &&
|
||||
userBashCommands.has(displayCommand)
|
||||
const [expanded, setExpanded] = useState(isUserBashCommand || (preferences?.expandToolCalls ?? false))
|
||||
const [detailsOpen, setDetailsOpen] = useToolDetailsState(preferences?.expandToolCalls ?? false)
|
||||
|
||||
useEffect(() => {
|
||||
if (part.name === 'shell' && expanded && outputRef.current) {
|
||||
if (isMobile) return
|
||||
if (part.name === 'shell' && detailsOpen && outputRef.current) {
|
||||
outputRef.current.scrollIntoView({ behavior: 'smooth', block: 'nearest' })
|
||||
}
|
||||
}, [expanded, part.name])
|
||||
}, [detailsOpen, isMobile, part.name])
|
||||
|
||||
const getStatusColor = () => {
|
||||
if (isBackgroundShell) return backgroundTaskStatusColor(shellStatus)
|
||||
@@ -263,7 +264,7 @@ export const ToolCallPart = memo(function ToolCallPart({ part, messageID, direct
|
||||
return (
|
||||
<button
|
||||
onClick={() => onChildSessionClick?.(subagentSessionId)}
|
||||
className="my-1 w-full rounded-lg border border-info/20 bg-info/5 px-3 py-1.5 text-left text-xs text-muted-foreground hover:bg-info/10 hover:border-info/30 transition-all duration-200 shadow-sm shadow-info/5"
|
||||
className="my-1 flex w-full min-w-0 items-center gap-2 py-0.5 text-left text-xs text-muted-foreground hover:text-foreground transition-colors"
|
||||
title="View subagent session"
|
||||
>
|
||||
{content}
|
||||
@@ -272,7 +273,7 @@ export const ToolCallPart = memo(function ToolCallPart({ part, messageID, direct
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="my-1 rounded-lg border border-info/20 bg-info/5 px-3 py-1.5 text-xs text-muted-foreground shadow-sm shadow-info/5">
|
||||
<div className="my-1 flex w-full min-w-0 items-center gap-2 py-0.5 text-left text-xs text-muted-foreground">
|
||||
{content}
|
||||
</div>
|
||||
)
|
||||
@@ -287,60 +288,129 @@ export const ToolCallPart = memo(function ToolCallPart({ part, messageID, direct
|
||||
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 (
|
||||
<div className="my-2">
|
||||
<div className="flex items-center gap-2 text-sm mb-2">
|
||||
{isBackgroundShell ? renderShellLifecycleIcon(shellStatus) : <span className="text-success">✓</span>}
|
||||
<span className="font-medium">$</span>
|
||||
<span className="text-foreground">{command}</span>
|
||||
{sandboxIndicator}
|
||||
{backgroundIndicator}
|
||||
{ran !== undefined && completed !== undefined && (
|
||||
<span className="text-muted-foreground text-xs ml-auto">
|
||||
{((completed - ran) / 1000).toFixed(2)}s
|
||||
</span>
|
||||
const output = toolOutputText(part)
|
||||
const statusLabel = isWaitingPermission
|
||||
? 'awaiting permission'
|
||||
: isBackgroundShell
|
||||
? lifecycleLabel(shellStatus)
|
||||
: part.state.status
|
||||
const commandBlock = (
|
||||
<div className="text-sm">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<div className="text-muted-foreground">Command:</div>
|
||||
<CopyButton content={displayCommand ?? ''} title="Copy command" />
|
||||
</div>
|
||||
<div className="bg-accent p-2 rounded text-xs overflow-x-auto whitespace-pre-wrap break-words">
|
||||
<span className="text-success">$</span> {displayCommand ?? ''}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
|
||||
const detailContent = (
|
||||
<>
|
||||
{part.state.status === 'streaming' && (
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<div className="flex gap-0.5">
|
||||
<span className="w-1.5 h-1.5 rounded-full bg-primary animate-bounce" style={{ animationDelay: '0ms' }} />
|
||||
<span className="w-1.5 h-1.5 rounded-full bg-primary animate-bounce" style={{ animationDelay: '150ms' }} />
|
||||
<span className="w-1.5 h-1.5 rounded-full bg-primary animate-bounce" style={{ animationDelay: '300ms' }} />
|
||||
</div>
|
||||
<span>Preparing tool call...</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{part.state.status === 'running' && (
|
||||
<div className="text-sm">
|
||||
{part.name === 'shell' ? commandBlock : (
|
||||
<>
|
||||
<div className="text-muted-foreground mb-1">Input:</div>
|
||||
<ClickableJson json={part.state.input} onFileClick={onFileClick} />
|
||||
</>
|
||||
)}
|
||||
<div className={`flex items-center gap-2 mt-2 text-xs ${isWaitingPermission ? 'text-highlight' : 'text-warning'}`}>
|
||||
<Loader2 className="w-3 h-3 animate-spin" />
|
||||
<span>{isWaitingPermission ? 'Waiting for permission...' : 'Running...'}</span>
|
||||
</div>
|
||||
</div>
|
||||
<div className="relative">
|
||||
<BoundedPre content={output} className="bg-accent p-3 rounded text-xs overflow-x-auto whitespace-pre-wrap" />
|
||||
<CopyButton content={output} title="Copy output" className="absolute top-2 right-2" />
|
||||
)}
|
||||
|
||||
{part.state.status === 'completed' && (
|
||||
<>
|
||||
{part.name === 'shell' ? commandBlock : (
|
||||
<div className="text-sm">
|
||||
<div className="text-muted-foreground mb-1">Input:</div>
|
||||
<ClickableJson json={part.state.input} onFileClick={onFileClick} />
|
||||
</div>
|
||||
)}
|
||||
{output && (
|
||||
<div className="text-sm">
|
||||
<div className="text-muted-foreground mb-1">Output:</div>
|
||||
<div className="relative">
|
||||
<BoundedPre
|
||||
content={output}
|
||||
className="bg-accent p-2 rounded text-xs overflow-x-auto whitespace-pre-wrap break-all"
|
||||
/>
|
||||
<CopyButton content={output} title="Copy output" className="absolute top-1 right-1" iconSize="sm" />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{part.time.ran !== undefined && part.time.completed !== undefined && (
|
||||
<div className="text-xs text-muted-foreground">
|
||||
Duration: {((part.time.completed - part.time.ran) / 1000).toFixed(2)}s
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{part.state.status === 'error' && (
|
||||
<div className="text-sm">
|
||||
<div className="text-destructive mb-1">Error:</div>
|
||||
<BoundedPre
|
||||
content={part.state.error.message}
|
||||
className="bg-accent p-2 rounded text-xs overflow-x-auto whitespace-pre-wrap break-words text-destructive"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)
|
||||
|
||||
if (part.name === 'shell') {
|
||||
return (
|
||||
<div ref={outputRef} className={cn('my-1', isWaitingPermission && 'border-l-2 border-highlight pl-2')}>
|
||||
<ShellPreview
|
||||
command={displayCommand ?? ''}
|
||||
output={output}
|
||||
onClick={() => setDetailsOpen(!detailsOpen)}
|
||||
status={
|
||||
<span className="flex shrink-0 items-center gap-1.5 text-xs text-muted-foreground">
|
||||
<span className={getStatusColor()}>{getStatusIcon()}</span>
|
||||
<span>{statusLabel}</span>
|
||||
{sandboxIndicator}
|
||||
{backgroundIndicator}
|
||||
</span>
|
||||
}
|
||||
/>
|
||||
<ToolContentFiles part={part} className={TRANSCRIPT_DETAIL_CLASS} />
|
||||
<ToolDetails
|
||||
open={detailsOpen}
|
||||
onOpenChange={setDetailsOpen}
|
||||
title={`$ ${displayCommand ?? ''}`}
|
||||
>
|
||||
{detailContent}
|
||||
</ToolDetails>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
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 (
|
||||
<div ref={outputRef} className={`border rounded-lg overflow-hidden my-2 transition-all ${getBorderStyle()}`}>
|
||||
<div className="flex items-center bg-card">
|
||||
<div ref={outputRef} className={cn('my-1', isWaitingPermission && 'border-l-2 border-highlight pl-2')}>
|
||||
<div className="flex items-center gap-2">
|
||||
<button
|
||||
onClick={() => setExpanded(!expanded)}
|
||||
className="min-w-0 flex-1 px-4 py-2 hover:bg-card-hover text-left flex items-center gap-2 text-sm"
|
||||
onClick={() => setDetailsOpen(!detailsOpen)}
|
||||
className={cn(TRANSCRIPT_ROW_CLASS, 'group hover:text-foreground transition-colors')}
|
||||
>
|
||||
<span className={getStatusColor()}>{getStatusIcon()}</span>
|
||||
<span className="font-medium">{part.name}</span>
|
||||
<span className={cn('shrink-0', getStatusColor())}>{getStatusIcon()}</span>
|
||||
<span className="shrink-0 font-medium text-foreground">{part.name}</span>
|
||||
{sandboxIndicator}
|
||||
{backgroundIndicator}
|
||||
|
||||
@@ -352,25 +422,23 @@ export const ToolCallPart = memo(function ToolCallPart({ part, messageID, direct
|
||||
onFileClick(previewText)
|
||||
}
|
||||
}}
|
||||
className="text-primary text-xs truncate hover:text-primary-hover cursor-pointer underline decoration-dotted"
|
||||
className="min-w-0 truncate text-primary text-xs hover:text-primary-hover cursor-pointer underline decoration-dotted"
|
||||
title={`Click to open ${previewText}`}
|
||||
>
|
||||
{previewText}
|
||||
</span>
|
||||
) : previewText ? (
|
||||
<span className="text-muted-foreground text-xs truncate">{previewText}</span>
|
||||
<span className="min-w-0 truncate text-muted-foreground text-xs">{previewText}</span>
|
||||
) : null}
|
||||
|
||||
<span className="text-muted-foreground text-xs ml-auto">
|
||||
{isWaitingPermission ? 'awaiting permission' : isBackgroundShell ? lifecycleLabel(shellStatus) : part.state.status}
|
||||
</span>
|
||||
<span className="ml-auto shrink-0 text-xs">{statusLabel}</span>
|
||||
</button>
|
||||
|
||||
{openWalkthrough ? (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="mr-2 h-7 shrink-0"
|
||||
className="h-7 shrink-0"
|
||||
onClick={() => onOpenWalkthrough?.(openWalkthrough.source)}
|
||||
>
|
||||
Open walkthrough
|
||||
@@ -378,97 +446,15 @@ export const ToolCallPart = memo(function ToolCallPart({ part, messageID, direct
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<ToolContentFiles part={part} className="px-4 py-2 bg-card" />
|
||||
<ToolContentFiles part={part} className={TRANSCRIPT_DETAIL_CLASS} />
|
||||
|
||||
{expanded && (
|
||||
<div className="bg-card space-y-2 p-3">
|
||||
{part.state.status === 'streaming' && (
|
||||
<div className="flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<div className="flex gap-0.5">
|
||||
<span className="w-1.5 h-1.5 rounded-full bg-primary animate-bounce" style={{ animationDelay: '0ms' }} />
|
||||
<span className="w-1.5 h-1.5 rounded-full bg-primary animate-bounce" style={{ animationDelay: '150ms' }} />
|
||||
<span className="w-1.5 h-1.5 rounded-full bg-primary animate-bounce" style={{ animationDelay: '300ms' }} />
|
||||
</div>
|
||||
<span>Preparing tool call...</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{part.state.status === 'running' && (
|
||||
part.name === 'shell' ? (
|
||||
<div className="text-sm">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<div className="text-muted-foreground">Command:</div>
|
||||
<CopyButton content={displayCommand ?? ''} title="Copy command" />
|
||||
</div>
|
||||
<div className="bg-accent p-2 rounded text-xs overflow-x-auto whitespace-pre-wrap break-words">
|
||||
<span className="text-success">$</span> {displayCommand ?? ''}
|
||||
</div>
|
||||
<div className={`flex items-center gap-2 mt-2 text-xs ${isWaitingPermission ? 'text-highlight' : 'text-warning'}`}>
|
||||
<Loader2 className="w-3 h-3 animate-spin" />
|
||||
<span>{isWaitingPermission ? 'Waiting for permission...' : 'Running...'}</span>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-sm">
|
||||
<div className="text-muted-foreground mb-1">Input:</div>
|
||||
<ClickableJson json={part.state.input} onFileClick={onFileClick} />
|
||||
<div className={`flex items-center gap-2 mt-2 text-xs ${isWaitingPermission ? 'text-highlight' : 'text-warning'}`}>
|
||||
<Loader2 className="w-3 h-3 animate-spin" />
|
||||
<span>{isWaitingPermission ? 'Waiting for permission...' : 'Running...'}</span>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
)}
|
||||
|
||||
{part.state.status === 'completed' && (
|
||||
<>
|
||||
{part.name === 'shell' ? (
|
||||
<div className="text-sm">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<div className="text-muted-foreground">Command:</div>
|
||||
<CopyButton content={displayCommand ?? ''} title="Copy command" />
|
||||
</div>
|
||||
<div className="bg-accent p-2 rounded text-xs overflow-x-auto whitespace-pre-wrap break-words">
|
||||
<span className="text-success">$</span> {displayCommand ?? ''}
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="text-sm">
|
||||
<div className="text-muted-foreground mb-1">Input:</div>
|
||||
<ClickableJson json={part.state.input} onFileClick={onFileClick} />
|
||||
</div>
|
||||
)}
|
||||
{output && (
|
||||
<div className="text-sm">
|
||||
<div className="text-muted-foreground mb-1">Output:</div>
|
||||
<div className="relative">
|
||||
<BoundedPre
|
||||
content={output}
|
||||
className="bg-accent p-2 rounded text-xs overflow-x-auto whitespace-pre-wrap break-all"
|
||||
/>
|
||||
<CopyButton content={output} title="Copy output" className="absolute top-1 right-1" iconSize="sm" />
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{part.time.ran !== undefined && part.time.completed !== undefined && (
|
||||
<div className="text-xs text-muted-foreground">
|
||||
Duration: {((part.time.completed - part.time.ran) / 1000).toFixed(2)}s
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{part.state.status === 'error' && (
|
||||
<div className="text-sm">
|
||||
<div className="text-destructive mb-1">Error:</div>
|
||||
<BoundedPre
|
||||
content={part.state.error.message}
|
||||
className="bg-accent p-2 rounded text-xs overflow-x-auto whitespace-pre-wrap break-words text-destructive"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
<ToolDetails
|
||||
open={detailsOpen}
|
||||
onOpenChange={setDetailsOpen}
|
||||
title={part.name + (previewText ? ` ${previewText}` : '')}
|
||||
>
|
||||
{detailContent}
|
||||
</ToolDetails>
|
||||
</div>
|
||||
)
|
||||
})
|
||||
@@ -0,0 +1,119 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { render, screen } from '@testing-library/react'
|
||||
import { ShellPreview, ToolDetails, useToolDetailsState } from './ToolDetails'
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
useMobile: vi.fn(),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useMobile', async (importOriginal) => ({
|
||||
...(await importOriginal<typeof import('@/hooks/useMobile')>()),
|
||||
useMobile: mocks.useMobile,
|
||||
}))
|
||||
|
||||
const Details = ({ open, onOpenChange }: { open: boolean; onOpenChange: (open: boolean) => void }) => (
|
||||
<ToolDetails open={open} onOpenChange={onOpenChange} title="$ git status">
|
||||
<p>detail body</p>
|
||||
</ToolDetails>
|
||||
)
|
||||
|
||||
function StateProbe({ defaultOpen }: { defaultOpen: boolean }) {
|
||||
const [open] = useToolDetailsState(defaultOpen)
|
||||
return <span>{open ? 'open' : 'closed'}</span>
|
||||
}
|
||||
|
||||
describe('ToolDetails', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('renders the detail inline on desktop when open', () => {
|
||||
mocks.useMobile.mockReturnValue(false)
|
||||
|
||||
render(<Details open onOpenChange={vi.fn()} />)
|
||||
|
||||
expect(screen.getByText('detail body')).toBeInTheDocument()
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders nothing inline on desktop when closed', () => {
|
||||
mocks.useMobile.mockReturnValue(false)
|
||||
|
||||
render(<Details open={false} onOpenChange={vi.fn()} />)
|
||||
|
||||
expect(screen.queryByText('detail body')).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders the detail inside a dialog on mobile when open', () => {
|
||||
mocks.useMobile.mockReturnValue(true)
|
||||
|
||||
render(<Details open onOpenChange={vi.fn()} />)
|
||||
|
||||
expect(screen.getByRole('dialog')).toBeInTheDocument()
|
||||
expect(screen.getByText('detail body')).toBeInTheDocument()
|
||||
expect(screen.getByText('$ git status')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('renders nothing on mobile when closed', () => {
|
||||
mocks.useMobile.mockReturnValue(true)
|
||||
|
||||
render(<Details open={false} onOpenChange={vi.fn()} />)
|
||||
|
||||
expect(screen.queryByRole('dialog')).not.toBeInTheDocument()
|
||||
expect(screen.queryByText('detail body')).not.toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
describe('useToolDetailsState', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('starts closed on mobile even when the default is open', () => {
|
||||
mocks.useMobile.mockReturnValue(true)
|
||||
|
||||
render(<StateProbe defaultOpen />)
|
||||
|
||||
expect(screen.getByText('closed')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('starts open on desktop when the default is open', () => {
|
||||
mocks.useMobile.mockReturnValue(false)
|
||||
|
||||
render(<StateProbe defaultOpen />)
|
||||
|
||||
expect(screen.getByText('open')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('starts closed on desktop when the default is closed', () => {
|
||||
mocks.useMobile.mockReturnValue(false)
|
||||
|
||||
render(<StateProbe defaultOpen={false} />)
|
||||
|
||||
expect(screen.getByText('closed')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
|
||||
describe('ShellPreview', () => {
|
||||
const output = Array.from({ length: 25 }, (_, index) => `line ${index + 1}`).join('\n')
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
})
|
||||
|
||||
it('shows the last 10 output lines on desktop', () => {
|
||||
mocks.useMobile.mockReturnValue(false)
|
||||
|
||||
render(<ShellPreview command="ls" output={output} onClick={vi.fn()} />)
|
||||
|
||||
expect(screen.getByText('(15 earlier lines)')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows only the last 4 output lines on mobile', () => {
|
||||
mocks.useMobile.mockReturnValue(true)
|
||||
|
||||
render(<ShellPreview command="ls" output={output} onClick={vi.fn()} />)
|
||||
|
||||
expect(screen.getByText('(21 earlier lines)')).toBeInTheDocument()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,86 @@
|
||||
import { useState, type ReactNode } from 'react'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { useMobile } from '@/hooks/useMobile'
|
||||
import { tailLines } from '@/lib/clampDisplayText'
|
||||
import { cn } from '@/lib/utils'
|
||||
import { TRANSCRIPT_DETAIL_CLASS } from './transcriptStyles'
|
||||
|
||||
const SHELL_PREVIEW_LINES = 10
|
||||
const MOBILE_SHELL_PREVIEW_LINES = 4
|
||||
|
||||
/** Tool-detail disclosure state that stays closed on mobile unless the user opens it. */
|
||||
export function useToolDetailsState(defaultOpen: boolean): [boolean, (open: boolean) => void] {
|
||||
const isMobile = useMobile()
|
||||
const [open, setOpen] = useState(() => defaultOpen && !isMobile)
|
||||
return [open, setOpen]
|
||||
}
|
||||
|
||||
/** Renders tool detail content inline on desktop and in a fullscreen dialog on mobile. */
|
||||
export function ToolDetails({
|
||||
open,
|
||||
onOpenChange,
|
||||
title,
|
||||
children,
|
||||
}: {
|
||||
open: boolean
|
||||
onOpenChange: (open: boolean) => void
|
||||
title: string
|
||||
children: ReactNode
|
||||
}) {
|
||||
const isMobile = useMobile()
|
||||
|
||||
if (isMobile) {
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent mobileFullscreen className="flex flex-col gap-0 p-0">
|
||||
<DialogHeader className="border-b border-border px-4 py-3">
|
||||
<DialogTitle className="truncate pr-8 font-mono text-sm">{title}</DialogTitle>
|
||||
</DialogHeader>
|
||||
<div className="min-h-0 flex-1 overflow-y-auto space-y-3 p-4">{children}</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
)
|
||||
}
|
||||
|
||||
return open ? <div className={cn(TRANSCRIPT_DETAIL_CLASS, 'space-y-2')}>{children}</div> : null
|
||||
}
|
||||
|
||||
/** Compact shell call summary that reveals the full detail when clicked. */
|
||||
export function ShellPreview({
|
||||
command,
|
||||
output,
|
||||
onClick,
|
||||
status,
|
||||
}: {
|
||||
command: string
|
||||
output: string
|
||||
onClick: () => void
|
||||
status?: ReactNode
|
||||
}) {
|
||||
const isMobile = useMobile()
|
||||
const tail = tailLines(output, isMobile ? MOBILE_SHELL_PREVIEW_LINES : SHELL_PREVIEW_LINES)
|
||||
|
||||
return (
|
||||
<button
|
||||
type="button"
|
||||
onClick={onClick}
|
||||
aria-label="Show shell details"
|
||||
className="my-1 block w-full bg-muted px-3 py-2 text-left font-mono text-xs text-foreground hover:bg-accent transition-colors md:px-4 md:py-3"
|
||||
>
|
||||
<div className="flex items-start gap-2">
|
||||
<div className="line-clamp-1 min-w-0 flex-1 break-all md:line-clamp-2">
|
||||
<span className="text-success">$</span> {command}
|
||||
</div>
|
||||
{status}
|
||||
</div>
|
||||
{tail.text && (
|
||||
<div className="mt-1.5 md:mt-2">
|
||||
{tail.hiddenCount > 0 && (
|
||||
<div className="text-muted-foreground">({tail.hiddenCount} earlier lines)</div>
|
||||
)}
|
||||
<div className="whitespace-pre-wrap break-all text-muted-foreground">{tail.text}</div>
|
||||
</div>
|
||||
)}
|
||||
</button>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
/** Row-level layout for a transcript entry header and its summary line. */
|
||||
export const TRANSCRIPT_ROW_CLASS = 'flex w-full min-w-0 items-center gap-2 min-h-7 py-0.5 text-left font-mono text-[12.5px] text-muted-foreground'
|
||||
|
||||
/** Indented, left-ruled block that holds detail content beneath a transcript row. */
|
||||
export const TRANSCRIPT_DETAIL_CLASS = 'ml-1.5 mt-1 border-l border-border pl-3'
|
||||
@@ -2,6 +2,7 @@ import cronstrue from 'cronstrue'
|
||||
import { formatDistanceToNow } from 'date-fns'
|
||||
import type { CreateScheduleJobRequest, ScheduleJob, ScheduleRun, ScheduleWorkspaceMode, UpdateScheduleJobRequest } from '@opencode-manager/shared/types'
|
||||
import type { RadioOption } from '@/components/ui/radio-option-group'
|
||||
import { formatDuration } from '@/lib/utils'
|
||||
|
||||
export const intervalOptions = [
|
||||
{ label: '15m', value: 15 },
|
||||
@@ -350,14 +351,7 @@ export function formatTimestamp(value: number | null): string {
|
||||
}
|
||||
|
||||
export function formatRunDuration(run: Pick<ScheduleRun, 'startedAt' | 'finishedAt'>, now: number = Date.now()): string {
|
||||
const totalSeconds = Math.max(0, Math.round(((run.finishedAt ?? now) - run.startedAt) / 1000))
|
||||
const hours = Math.floor(totalSeconds / 3600)
|
||||
const minutes = Math.floor((totalSeconds % 3600) / 60)
|
||||
const seconds = totalSeconds % 60
|
||||
|
||||
if (hours > 0) return `${hours}h ${minutes}m`
|
||||
if (minutes > 0) return `${minutes}m ${seconds}s`
|
||||
return `${seconds}s`
|
||||
return formatDuration((run.finishedAt ?? now) - run.startedAt)
|
||||
}
|
||||
|
||||
export function getJobStatusTone(job: ScheduleJob): string {
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect } from 'vitest'
|
||||
import { clampDisplayText } from './clampDisplayText'
|
||||
import { clampDisplayText, tailLines } from './clampDisplayText'
|
||||
|
||||
const line = (index: number) => `line ${index} ${'x'.repeat(20)}`
|
||||
|
||||
@@ -22,3 +22,22 @@ describe('clampDisplayText', () => {
|
||||
expect(clamped.endsWith(lines[lines.length - 1])).toBe(true)
|
||||
})
|
||||
})
|
||||
|
||||
describe('tailLines', () => {
|
||||
it('keeps short text whole', () => {
|
||||
expect(tailLines('one\ntwo\nthree', 10)).toEqual({ hiddenCount: 0, text: 'one\ntwo\nthree' })
|
||||
})
|
||||
|
||||
it('returns the last lines and counts the hidden ones', () => {
|
||||
const lines = Array.from({ length: 25 }, (_, index) => `line ${index}`)
|
||||
|
||||
const tail = tailLines(lines.join('\n'), 10)
|
||||
|
||||
expect(tail.hiddenCount).toBe(15)
|
||||
expect(tail.text).toBe(lines.slice(15).join('\n'))
|
||||
})
|
||||
|
||||
it('ignores a single trailing newline', () => {
|
||||
expect(tailLines('one\ntwo\nthree\n', 2)).toEqual({ hiddenCount: 1, text: 'two\nthree' })
|
||||
})
|
||||
})
|
||||
@@ -8,6 +8,18 @@ function formatOmittedSize(size: number): string {
|
||||
: `${(size / (1024 * 1024)).toFixed(1)} MB`
|
||||
}
|
||||
|
||||
/** Returns the last `maxLines` lines of `text` and how many leading lines were dropped. */
|
||||
export function tailLines(text: string, maxLines: number): { hiddenCount: number; text: string } {
|
||||
const trimmed = text.endsWith('\n') ? text.slice(0, -1) : text
|
||||
if (trimmed === '') return { hiddenCount: 0, text: '' }
|
||||
const lines = trimmed.split('\n')
|
||||
if (lines.length <= maxLines) return { hiddenCount: 0, text: trimmed }
|
||||
return {
|
||||
hiddenCount: lines.length - maxLines,
|
||||
text: lines.slice(lines.length - maxLines).join('\n'),
|
||||
}
|
||||
}
|
||||
|
||||
export function clampDisplayText(text: string): string {
|
||||
if (text.length <= DISPLAY_LIMIT) return text
|
||||
const headCut = text.lastIndexOf('\n', DISPLAY_HEAD_LENGTH)
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
import { parseUnifiedDiff } from './diffLines'
|
||||
|
||||
describe('parseUnifiedDiff', () => {
|
||||
it('numbers context, added, and removed lines from the hunk header', () => {
|
||||
const rows = parseUnifiedDiff(
|
||||
['@@ -10,4 +20,5 @@', ' unchanged', '-removed', '+added', ' trailing'].join('\n'),
|
||||
)
|
||||
|
||||
expect(rows).toEqual([
|
||||
{ kind: 'context', oldLine: 10, newLine: 20, text: 'unchanged' },
|
||||
{ kind: 'remove', oldLine: 11, text: 'removed' },
|
||||
{ kind: 'add', newLine: 21, text: 'added' },
|
||||
{ kind: 'context', oldLine: 12, newLine: 22, text: 'trailing' },
|
||||
])
|
||||
})
|
||||
|
||||
it('emits a gap row between hunks and continues numbering from each header', () => {
|
||||
const rows = parseUnifiedDiff(
|
||||
['@@ -1,2 +1,2 @@', ' first', '+second', '@@ -40,1 +40,1 @@', '-old', '+new'].join('\n'),
|
||||
)
|
||||
|
||||
expect(rows.map((row) => row.kind)).toEqual(['context', 'add', 'gap', 'remove', 'add'])
|
||||
expect(rows[1]).toMatchObject({ newLine: 2 })
|
||||
expect(rows[3]).toMatchObject({ oldLine: 40 })
|
||||
expect(rows[4]).toMatchObject({ newLine: 40 })
|
||||
})
|
||||
|
||||
it('skips diff headers, index lines, and no-newline markers', () => {
|
||||
const rows = parseUnifiedDiff(
|
||||
[
|
||||
'diff --git a/file.ts b/file.ts',
|
||||
'index 1234567..89abcde 100644',
|
||||
'--- a/file.ts',
|
||||
'+++ b/file.ts',
|
||||
'@@ -1 +1 @@',
|
||||
'-before',
|
||||
'+after',
|
||||
'\\ No newline at end of file',
|
||||
].join('\n'),
|
||||
)
|
||||
|
||||
expect(rows).toEqual([
|
||||
{ kind: 'remove', oldLine: 1, text: 'before' },
|
||||
{ kind: 'add', newLine: 1, text: 'after' },
|
||||
])
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,58 @@
|
||||
export type DiffRowKind = 'add' | 'remove' | 'context' | 'gap'
|
||||
|
||||
export interface DiffRow {
|
||||
kind: DiffRowKind
|
||||
oldLine?: number
|
||||
newLine?: number
|
||||
text: string
|
||||
}
|
||||
|
||||
const HUNK_HEADER = /^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@/
|
||||
|
||||
/** Parses a unified diff patch into numbered rows, emitting a gap row between hunks. */
|
||||
export function parseUnifiedDiff(patch: string): DiffRow[] {
|
||||
const rows: DiffRow[] = []
|
||||
let oldLine = 0
|
||||
let newLine = 0
|
||||
let inHunk = false
|
||||
|
||||
for (const line of patch.split('\n')) {
|
||||
if (line.startsWith('diff --git')) {
|
||||
inHunk = false
|
||||
continue
|
||||
}
|
||||
|
||||
if (line.startsWith('index ') || line.startsWith('\\ No newline')) continue
|
||||
|
||||
const hunk = HUNK_HEADER.exec(line)
|
||||
if (hunk) {
|
||||
oldLine = Number(hunk[1])
|
||||
newLine = Number(hunk[2])
|
||||
if (inHunk && rows.length > 0) rows.push({ kind: 'gap', text: '' })
|
||||
inHunk = true
|
||||
continue
|
||||
}
|
||||
|
||||
if (!inHunk) continue
|
||||
|
||||
if (line.startsWith('+')) {
|
||||
rows.push({ kind: 'add', newLine, text: line.slice(1) })
|
||||
newLine += 1
|
||||
continue
|
||||
}
|
||||
|
||||
if (line.startsWith('-')) {
|
||||
rows.push({ kind: 'remove', oldLine, text: line.slice(1) })
|
||||
oldLine += 1
|
||||
continue
|
||||
}
|
||||
|
||||
if (line.startsWith(' ')) {
|
||||
rows.push({ kind: 'context', oldLine, newLine, text: line.slice(1) })
|
||||
oldLine += 1
|
||||
newLine += 1
|
||||
}
|
||||
}
|
||||
|
||||
return rows
|
||||
}
|
||||
@@ -53,6 +53,18 @@ export function randomId(): string {
|
||||
return `${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 11)}`
|
||||
}
|
||||
|
||||
/** Formats a millisecond duration as `Xh Ym`, `Xm Ys`, or `Xs`, clamped to zero. */
|
||||
export function formatDuration(ms: number): string {
|
||||
const totalSeconds = Math.max(0, Math.round(ms / 1000))
|
||||
const hours = Math.floor(totalSeconds / 3600)
|
||||
const minutes = Math.floor((totalSeconds % 3600) / 60)
|
||||
const seconds = totalSeconds % 60
|
||||
|
||||
if (hours > 0) return `${hours}h ${minutes}m`
|
||||
if (minutes > 0) return `${minutes}m ${seconds}s`
|
||||
return `${seconds}s`
|
||||
}
|
||||
|
||||
export function formatShortRelativeTime(date: Date, now: Date = new Date()): string {
|
||||
const diffMs = now.getTime() - date.getTime()
|
||||
const diffSeconds = Math.floor(diffMs / 1000)
|
||||
|
||||
Generated
+3
@@ -186,6 +186,9 @@ importers:
|
||||
jsqr:
|
||||
specifier: ^1.4.0
|
||||
version: 1.4.0
|
||||
lowlight:
|
||||
specifier: ^3.3.0
|
||||
version: 3.3.0
|
||||
lucide-react:
|
||||
specifier: ^0.546.0
|
||||
version: 0.546.0(react@19.2.3)
|
||||
|
||||
Reference in new issue
Block a user