mirror of
https://github.com/chriswritescode-dev/opencode-manager.git
synced 2026-12-05 12:24:30 +01:00
Merge pull request #457 from chriswritescode-dev/feat/plain-log-transcript
feat(frontend): restyle the session transcript as a plain log with collapsible tool details
This commit is contained in:
45 files changed
+2116
-858
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",
|
||||
|
||||
@@ -35,7 +35,7 @@ import { SwipeNavigationProvider, useSwipeNavigation } from '@/contexts/SwipeNav
|
||||
import { PermissionRequestDialog } from './components/session/PermissionRequestDialog'
|
||||
import { SSHHostKeyDialog } from './components/ssh/SSHHostKeyDialog'
|
||||
import { loginLoader, setupLoader, registerLoader, protectedLoader } from './lib/auth-loaders'
|
||||
import { getSwipeBackTarget } from '@/lib/navigation'
|
||||
import { getSwipeBackTarget, isSessionDetailRoute } from '@/lib/navigation'
|
||||
import { onNotificationClick } from '@/lib/serviceWorker'
|
||||
import { useAuth } from '@/hooks/useAuth'
|
||||
import { useOpenCodeFailureToast } from '@/hooks/useOpenCodeFailureToast'
|
||||
@@ -198,7 +198,7 @@ function AppShell() {
|
||||
)
|
||||
|
||||
const canOpenMoreWithSwipe = () => {
|
||||
return /^\/repos\/[^/]+\/sessions\/[^/]+$/.test(location.pathname) && !openSheet
|
||||
return isSessionDetailRoute(location.pathname) && !openSheet
|
||||
}
|
||||
|
||||
const { bind: bindMoreSwipe } = useRightEdgeSwipe(
|
||||
|
||||
@@ -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 || toolName === 'Write'
|
||||
? (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', () => {
|
||||
@@ -582,6 +648,51 @@ describe('MessagePart', () => {
|
||||
expect(screen.getByText('/test/file.txt')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('expands a write tool preview when expand diffs is enabled', () => {
|
||||
setupSettings({
|
||||
simpleChatMode: false,
|
||||
showReasoning: false,
|
||||
expandToolCalls: false,
|
||||
expandDiffs: true,
|
||||
})
|
||||
|
||||
renderWithProviders(
|
||||
<MessagePart
|
||||
part={toolPart('write', {
|
||||
status: 'completed',
|
||||
input: { path: '/test/file.txt', content: 'written preview line' },
|
||||
content: [{ type: 'text', text: 'Wrote file successfully' }],
|
||||
metadata: {},
|
||||
})}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByText('written preview line')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('collapses a write tool preview when only expand tool calls is enabled', () => {
|
||||
setupSettings({
|
||||
simpleChatMode: false,
|
||||
showReasoning: false,
|
||||
expandToolCalls: true,
|
||||
expandDiffs: false,
|
||||
})
|
||||
|
||||
renderWithProviders(
|
||||
<MessagePart
|
||||
part={toolPart('write', {
|
||||
status: 'completed',
|
||||
input: { path: '/test/file.txt', content: 'written preview line' },
|
||||
content: [{ type: 'text', text: 'Wrote file successfully' }],
|
||||
metadata: {},
|
||||
})}
|
||||
/>,
|
||||
)
|
||||
|
||||
expect(screen.getByText('/test/file.txt')).toBeInTheDocument()
|
||||
expect(screen.queryByText('written preview line')).toBeNull()
|
||||
})
|
||||
|
||||
it('makes legacy filePath read, write, and filediff edit calls clickable', () => {
|
||||
const onFileClick = vi.fn()
|
||||
const legacy = (name: string, metadata: Record<string, unknown>) =>
|
||||
@@ -631,6 +742,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 +767,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 })
|
||||
|
||||
@@ -626,6 +684,26 @@ describe('MessageThread', () => {
|
||||
expect(screen.queryByText(/File Changes/)).not.toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('omits the agent name from the assistant footer in simple chat mode', () => {
|
||||
const messages = [assistantMessage('2', [textPart('Updated files')], { agent: 'build' })]
|
||||
|
||||
setupSettings({ simpleChatMode: true, showReasoning: false })
|
||||
const simple = render(
|
||||
<MessageThread sessionID="test-session" messages={messages} pending={[]} />,
|
||||
)
|
||||
|
||||
expect(screen.queryByText('Build')).not.toBeInTheDocument()
|
||||
expect(screen.getByText('test-model')).toBeInTheDocument()
|
||||
|
||||
simple.unmount()
|
||||
|
||||
setupSettings({ simpleChatMode: false, showReasoning: false })
|
||||
render(<MessageThread sessionID="test-session" messages={messages} pending={[]} />)
|
||||
|
||||
expect(screen.getByText('Build')).toBeInTheDocument()
|
||||
expect(screen.getByText('test-model')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows the empty state when there are no messages or pending prompts', () => {
|
||||
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,81 @@ 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">
|
||||
{!simpleChatMode && (
|
||||
<>
|
||||
<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 +615,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 flex-wrap 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 break-words 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)}`}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
|
||||
import { act, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
|
||||
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
||||
import { MemoryRouter } from 'react-router-dom'
|
||||
@@ -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,106 @@ 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 shell details scrolling', () => {
|
||||
const originalScrollIntoView = Element.prototype.scrollIntoView
|
||||
const scrollIntoView = vi.fn()
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mocks.useSettings.mockReturnValue({
|
||||
preferences: { expandToolCalls: false },
|
||||
isLoading: false,
|
||||
updateSettings: vi.fn(),
|
||||
isUpdating: false,
|
||||
})
|
||||
mocks.useToolCallPermission.mockReturnValue(null)
|
||||
Element.prototype.scrollIntoView = scrollIntoView
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
Element.prototype.scrollIntoView = originalScrollIntoView
|
||||
})
|
||||
|
||||
const completedShell = (): SessionMessageAssistantTool => ({
|
||||
type: 'tool',
|
||||
id: 'call_scroll',
|
||||
name: 'shell',
|
||||
time: { created: 1, ran: 2, completed: 3 },
|
||||
state: {
|
||||
status: 'completed',
|
||||
input: { command: 'seq 25' },
|
||||
content: [{ type: 'text', text: 'line 24\nline 25' }],
|
||||
metadata: {},
|
||||
},
|
||||
})
|
||||
|
||||
it('does not scroll when the shell details open from the preference', () => {
|
||||
mocks.useSettings.mockReturnValue({
|
||||
preferences: { expandToolCalls: true },
|
||||
isLoading: false,
|
||||
updateSettings: vi.fn(),
|
||||
isUpdating: false,
|
||||
})
|
||||
|
||||
renderWithProviders(<ToolCallPart part={completedShell()} messageID="msg_1" />)
|
||||
|
||||
expect(screen.getByText('Command:')).toBeInTheDocument()
|
||||
expect(scrollIntoView).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('scrolls once when the user opens the shell details', () => {
|
||||
renderWithProviders(<ToolCallPart part={completedShell()} messageID="msg_1" />)
|
||||
|
||||
expect(screen.queryByText('Command:')).not.toBeInTheDocument()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'Show shell details' }))
|
||||
|
||||
expect(screen.getByText('Command:')).toBeInTheDocument()
|
||||
expect(scrollIntoView).toHaveBeenCalledTimes(1)
|
||||
expect(scrollIntoView).toHaveBeenCalledWith({ behavior: 'smooth', block: 'nearest' })
|
||||
})
|
||||
})
|
||||
|
||||
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
|
||||
@@ -99,6 +102,7 @@ export const ToolCallPart = memo(function ToolCallPart({ part, messageID, direct
|
||||
const pendingPermission = useToolCallPermission(part.id, messageID)
|
||||
const isWaitingPermission = part.state.status === 'running' && pendingPermission !== null
|
||||
const outputRef = useRef<HTMLDivElement>(null)
|
||||
const userOpenedDetailsRef = useRef(false)
|
||||
const input = toolInput(part)
|
||||
const openWalkthrough = readOpenWalkthroughCall(part)
|
||||
const rawCommand = part.name === 'shell' && typeof input?.command === 'string'
|
||||
@@ -117,16 +121,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) {
|
||||
outputRef.current.scrollIntoView({ behavior: 'smooth', block: 'nearest' })
|
||||
}
|
||||
}, [expanded, part.name])
|
||||
if (part.name !== 'shell' || !detailsOpen || !userOpenedDetailsRef.current) return
|
||||
userOpenedDetailsRef.current = false
|
||||
if (isMobile) return
|
||||
outputRef.current?.scrollIntoView({ behavior: 'smooth', block: 'nearest' })
|
||||
}, [detailsOpen, isMobile, part.name])
|
||||
|
||||
const getStatusColor = () => {
|
||||
if (isBackgroundShell) return backgroundTaskStatusColor(shellStatus)
|
||||
@@ -263,7 +265,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 +274,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 +289,133 @@ 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={() => {
|
||||
const nextOpen = !detailsOpen
|
||||
if (nextOpen) userOpenedDetailsRef.current = true
|
||||
setDetailsOpen(nextOpen)
|
||||
}}
|
||||
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 +427,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 +451,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,167 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest'
|
||||
import { fireEvent, 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, setOpen] = useToolDetailsState(defaultOpen)
|
||||
return (
|
||||
<>
|
||||
<span>{open ? 'open' : 'closed'}</span>
|
||||
<button type="button" onClick={() => setOpen(false)}>
|
||||
close details
|
||||
</button>
|
||||
</>
|
||||
)
|
||||
}
|
||||
|
||||
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()
|
||||
})
|
||||
|
||||
it('follows a default that turns open after mount on desktop', () => {
|
||||
mocks.useMobile.mockReturnValue(false)
|
||||
|
||||
const { rerender } = render(<StateProbe defaultOpen={false} />)
|
||||
|
||||
expect(screen.getByText('closed')).toBeInTheDocument()
|
||||
|
||||
rerender(<StateProbe defaultOpen />)
|
||||
|
||||
expect(screen.getByText('open')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('keeps the user choice when a later default differs', () => {
|
||||
mocks.useMobile.mockReturnValue(false)
|
||||
|
||||
const { rerender } = render(<StateProbe defaultOpen />)
|
||||
|
||||
expect(screen.getByText('open')).toBeInTheDocument()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: 'close details' }))
|
||||
|
||||
expect(screen.getByText('closed')).toBeInTheDocument()
|
||||
|
||||
rerender(<StateProbe defaultOpen />)
|
||||
|
||||
expect(screen.getByText('closed')).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('closes when the viewport shrinks to mobile after opening on desktop', () => {
|
||||
mocks.useMobile.mockReturnValue(false)
|
||||
|
||||
const { rerender } = render(<StateProbe defaultOpen />)
|
||||
|
||||
expect(screen.getByText('open')).toBeInTheDocument()
|
||||
|
||||
mocks.useMobile.mockReturnValue(true)
|
||||
rerender(<StateProbe defaultOpen />)
|
||||
|
||||
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,90 @@
|
||||
import { useMemo, useState, type ReactNode } from 'react'
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog'
|
||||
import { useMobile } from '@/hooks/useMobile'
|
||||
import { clampDisplayText, 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 follows the preference until the user toggles it and never auto-opens on mobile. */
|
||||
export function useToolDetailsState(defaultOpen: boolean): [boolean, (open: boolean) => void] {
|
||||
const isMobile = useMobile()
|
||||
const [userOpen, setUserOpen] = useState<boolean | null>(null)
|
||||
return [userOpen ?? (defaultOpen && !isMobile), setUserOpen]
|
||||
}
|
||||
|
||||
/** 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 lineLimit = isMobile ? MOBILE_SHELL_PREVIEW_LINES : SHELL_PREVIEW_LINES
|
||||
const tail = useMemo(() => {
|
||||
const result = tailLines(output, lineLimit)
|
||||
return { ...result, text: clampDisplayText(result.text) }
|
||||
}, [output, lineLimit])
|
||||
|
||||
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>
|
||||
)
|
||||
}
|
||||
@@ -34,7 +34,7 @@ export const UserMessageActionButtons = memo(function UserMessageActionButtons({
|
||||
}
|
||||
|
||||
return (
|
||||
<div className={`flex items-center gap-1 ${isMobile ? 'opacity-100' : 'opacity-0 group-hover:opacity-100'} transition-opacity`}>
|
||||
<div className={`flex items-center gap-1 ${isMobile ? 'opacity-100' : 'opacity-0 group-hover:opacity-100 group-focus-within:opacity-100'} transition-opacity`}>
|
||||
<button
|
||||
onClick={handleUndo}
|
||||
disabled={undoMessage.isPending}
|
||||
|
||||
@@ -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'
|
||||
@@ -20,10 +20,10 @@ import { cn } from '@/lib/utils'
|
||||
|
||||
const LOCAL_SERVER_LABEL = 'OC Manager'
|
||||
|
||||
export type LinkedServersVariant = 'sidebar' | 'rail' | 'sheet'
|
||||
export type LinkedServersVariant = 'sidebar' | 'rail' | 'sheet' | 'header'
|
||||
|
||||
interface LinkedServersNavProps {
|
||||
/** `sidebar` renders the full-width trigger row, `rail` the collapsed icon button, `sheet` the mobile sheet row. */
|
||||
/** `sidebar` renders the full-width trigger row, `rail` the collapsed icon button, `sheet` the mobile sheet row, `header` a compact page-header trigger. */
|
||||
variant?: LinkedServersVariant
|
||||
}
|
||||
|
||||
@@ -218,7 +218,9 @@ export function LinkedServersNav({ variant = 'sidebar' }: LinkedServersNavProps)
|
||||
'flex items-center rounded-md text-sm text-foreground transition-colors duration-150',
|
||||
'hover:bg-accent/50',
|
||||
'focus:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 focus-visible:ring-offset-background',
|
||||
isRail ? 'mx-auto h-9 w-9 justify-center' : 'h-9 w-full gap-2 px-2',
|
||||
isRail && 'mx-auto h-9 w-9 justify-center',
|
||||
variant === 'header' && 'h-8 min-w-0 max-w-[45vw] gap-2 px-2 sm:max-w-xs',
|
||||
(variant === 'sidebar' || variant === 'sheet') && 'h-9 w-full gap-2 px-2',
|
||||
)}
|
||||
>
|
||||
<span className="relative flex shrink-0">
|
||||
|
||||
@@ -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,43 +0,0 @@
|
||||
import type { OpenCodeServerStatus } from '@opencode-manager/shared/schemas'
|
||||
|
||||
interface ConnectionStatusProps {
|
||||
status?: OpenCodeServerStatus
|
||||
isLoading: boolean
|
||||
}
|
||||
|
||||
/**
|
||||
* Connection indicator for a linked server: checking, unknown, unreachable with its error, or
|
||||
* connected with the server version.
|
||||
*/
|
||||
export function ConnectionStatus({ status, isLoading }: ConnectionStatusProps) {
|
||||
if (isLoading) {
|
||||
return <span className="text-xs text-muted-foreground">Checking connection...</span>
|
||||
}
|
||||
|
||||
if (!status) {
|
||||
return (
|
||||
<span className="flex items-center gap-1.5 text-xs text-muted-foreground">
|
||||
<span className="h-2 w-2 rounded-full bg-muted-foreground/50" />
|
||||
Unknown
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
if (!status.connected) {
|
||||
return (
|
||||
<span className="flex items-center gap-1.5 text-xs text-destructive" title={status.error ?? undefined}>
|
||||
<span className="h-2 w-2 rounded-full bg-destructive" />
|
||||
Unreachable
|
||||
{status.error ? <span className="text-muted-foreground">· {status.error}</span> : null}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<span className="flex items-center gap-1.5 text-xs text-success">
|
||||
<span className="h-2 w-2 rounded-full bg-success" />
|
||||
Connected
|
||||
{status.version ? <span className="text-muted-foreground">· v{status.version}</span> : null}
|
||||
</span>
|
||||
)
|
||||
}
|
||||
@@ -72,6 +72,7 @@ function mockHooks(preferences: UserPreferences = buildPreferences()) {
|
||||
speak: vi.fn(),
|
||||
speakWithConfig: vi.fn(),
|
||||
speakMessage: vi.fn(),
|
||||
queueMessage: vi.fn(),
|
||||
stop: vi.fn(),
|
||||
state: 'idle',
|
||||
error: null,
|
||||
|
||||
@@ -72,6 +72,14 @@ const revokeObjectURL = vi.fn()
|
||||
const textA = 'Alpha one. Alpha two. Alpha three. Alpha four. Alpha five.'
|
||||
const textB = 'Bravo one. Bravo two. Bravo three. Bravo four. Bravo five.'
|
||||
|
||||
async function flushPlayback() {
|
||||
await act(async () => {
|
||||
for (let tick = 0; tick < 20; tick += 1) {
|
||||
await Promise.resolve()
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
function setPreferences(overrides: Partial<TTSConfig> = {}) {
|
||||
mocks.useSettings.mockReturnValue({
|
||||
preferences: {
|
||||
@@ -294,3 +302,148 @@ describe('TTSProvider playback isolation', () => {
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('TTSProvider message queue', () => {
|
||||
const QUEUE_PAUSE_MS = 600
|
||||
const firstText = 'Alpha plays first.'
|
||||
const queuedText = 'Bravo waits in queue.'
|
||||
const interruptingText = 'Charlie interrupts.'
|
||||
|
||||
beforeEach(() => {
|
||||
vi.useFakeTimers()
|
||||
})
|
||||
|
||||
afterEach(() => {
|
||||
vi.useRealTimers()
|
||||
})
|
||||
|
||||
it('plays a queued message only after the active playback ends and the pause elapses', async () => {
|
||||
setPreferences()
|
||||
renderProvider()
|
||||
|
||||
await act(async () => {
|
||||
void ttsRef.current!.speakMessage('A', firstText)
|
||||
})
|
||||
await flushPlayback()
|
||||
|
||||
expect(FakeAudio.instances).toHaveLength(1)
|
||||
const firstAudio = FakeAudio.instances[0]
|
||||
expect(firstAudio.paused).toBe(false)
|
||||
expect(ttsRef.current!.activeMessageId).toBe('A')
|
||||
|
||||
await act(async () => {
|
||||
ttsRef.current!.queueMessage('B', queuedText)
|
||||
})
|
||||
await flushPlayback()
|
||||
|
||||
expect(FakeAudio.instances).toHaveLength(1)
|
||||
expect(firstAudio.paused).toBe(false)
|
||||
expect(ttsRef.current!.activeMessageId).toBe('A')
|
||||
expect(ttsRef.current!.isPlaying).toBe(true)
|
||||
|
||||
await act(async () => {
|
||||
firstAudio.onended!()
|
||||
})
|
||||
await flushPlayback()
|
||||
|
||||
expect(FakeAudio.instances).toHaveLength(1)
|
||||
expect(ttsRef.current!.isIdle).toBe(true)
|
||||
expect(ttsRef.current!.activeMessageId).toBeNull()
|
||||
|
||||
await act(async () => {
|
||||
vi.advanceTimersByTime(QUEUE_PAUSE_MS - 1)
|
||||
})
|
||||
await flushPlayback()
|
||||
|
||||
expect(FakeAudio.instances).toHaveLength(1)
|
||||
|
||||
await act(async () => {
|
||||
vi.advanceTimersByTime(1)
|
||||
})
|
||||
await flushPlayback()
|
||||
|
||||
expect(FakeAudio.instances).toHaveLength(2)
|
||||
expect(FakeAudio.instances[1].paused).toBe(false)
|
||||
expect(ttsRef.current!.activeMessageId).toBe('B')
|
||||
expect(ttsRef.current!.isPlaying).toBe(true)
|
||||
})
|
||||
|
||||
it('drops queued messages when playback is stopped', async () => {
|
||||
setPreferences()
|
||||
renderProvider()
|
||||
|
||||
await act(async () => {
|
||||
void ttsRef.current!.speakMessage('A', firstText)
|
||||
})
|
||||
await flushPlayback()
|
||||
|
||||
await act(async () => {
|
||||
ttsRef.current!.queueMessage('B', queuedText)
|
||||
})
|
||||
await flushPlayback()
|
||||
|
||||
await act(async () => {
|
||||
FakeAudio.instances[0].onended!()
|
||||
})
|
||||
await flushPlayback()
|
||||
|
||||
await act(async () => {
|
||||
ttsRef.current!.stop()
|
||||
})
|
||||
|
||||
await act(async () => {
|
||||
vi.advanceTimersByTime(1000)
|
||||
})
|
||||
await flushPlayback()
|
||||
|
||||
expect(FakeAudio.instances).toHaveLength(1)
|
||||
expect(fetchBodies).not.toContain(queuedText)
|
||||
expect(ttsRef.current!.state).toBe('idle')
|
||||
expect(ttsRef.current!.activeMessageId).toBeNull()
|
||||
})
|
||||
|
||||
it('clears queued messages when a manual speakMessage interrupts playback', async () => {
|
||||
setPreferences()
|
||||
renderProvider()
|
||||
|
||||
await act(async () => {
|
||||
void ttsRef.current!.speakMessage('A', firstText)
|
||||
})
|
||||
await flushPlayback()
|
||||
|
||||
await act(async () => {
|
||||
ttsRef.current!.queueMessage('B', queuedText)
|
||||
})
|
||||
await flushPlayback()
|
||||
|
||||
await act(async () => {
|
||||
void ttsRef.current!.speakMessage('C', interruptingText)
|
||||
})
|
||||
await flushPlayback()
|
||||
|
||||
expect(FakeAudio.instances).toHaveLength(2)
|
||||
expect(FakeAudio.instances[0].paused).toBe(true)
|
||||
expect(ttsRef.current!.activeMessageId).toBe('C')
|
||||
|
||||
await act(async () => {
|
||||
vi.advanceTimersByTime(1000)
|
||||
})
|
||||
await flushPlayback()
|
||||
|
||||
expect(FakeAudio.instances).toHaveLength(2)
|
||||
expect(fetchBodies).not.toContain(queuedText)
|
||||
|
||||
await act(async () => {
|
||||
FakeAudio.instances[1].onended!()
|
||||
})
|
||||
await flushPlayback()
|
||||
|
||||
await act(async () => {
|
||||
vi.advanceTimersByTime(1000)
|
||||
})
|
||||
await flushPlayback()
|
||||
|
||||
expect(FakeAudio.instances).toHaveLength(2)
|
||||
expect(ttsRef.current!.state).toBe('idle')
|
||||
})
|
||||
})
|
||||
@@ -9,6 +9,12 @@ export { TTSContext, type TTSContextValue, type TTSState, type TTSConfig } from
|
||||
|
||||
const SENTENCE_REGEX = /(?<=[.!?])\s+/
|
||||
const SENTENCES_PER_CHUNK = 2
|
||||
const QUEUE_PAUSE_MS = 600
|
||||
|
||||
interface QueuedMessage {
|
||||
messageId: string
|
||||
text: string
|
||||
}
|
||||
|
||||
function splitIntoChunks(text: string): string[] {
|
||||
const sentences = text.split(SENTENCE_REGEX).filter(s => s.trim().length > 0)
|
||||
@@ -42,6 +48,10 @@ export function TTSProvider({ children }: TTSProviderProps) {
|
||||
const chunksRef = useRef<string[]>([])
|
||||
const chunkIndexRef = useRef(0)
|
||||
const chunkAudioRef = useRef<Map<number, Promise<Blob | null>>>(new Map())
|
||||
const queueRef = useRef<QueuedMessage[]>([])
|
||||
const busyRef = useRef(false)
|
||||
const advanceTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null)
|
||||
const playMessageRef = useRef<((messageId: string, text: string) => Promise<boolean>) | null>(null)
|
||||
|
||||
// Web Speech API reference
|
||||
const webSpeechSynthRef = useRef<ReturnType<typeof getWebSpeechSynthesizer> | null>(null)
|
||||
@@ -94,7 +104,20 @@ export function TTSProvider({ children }: TTSProviderProps) {
|
||||
chunkIndexRef.current = 0
|
||||
}, [])
|
||||
|
||||
const stop = useCallback(() => {
|
||||
const clearAdvanceTimer = useCallback(() => {
|
||||
if (advanceTimerRef.current !== null) {
|
||||
clearTimeout(advanceTimerRef.current)
|
||||
advanceTimerRef.current = null
|
||||
}
|
||||
}, [])
|
||||
|
||||
const clearQueue = useCallback(() => {
|
||||
queueRef.current = []
|
||||
clearAdvanceTimer()
|
||||
}, [clearAdvanceTimer])
|
||||
|
||||
const resetPlayback = useCallback(() => {
|
||||
clearAdvanceTimer()
|
||||
playbackIdRef.current += 1
|
||||
cleanup()
|
||||
setState('idle')
|
||||
@@ -102,14 +125,51 @@ export function TTSProvider({ children }: TTSProviderProps) {
|
||||
setOriginalText(null)
|
||||
setActiveMessageId(null)
|
||||
setError(null)
|
||||
}, [cleanup])
|
||||
}, [cleanup, clearAdvanceTimer])
|
||||
|
||||
const stop = useCallback(() => {
|
||||
clearQueue()
|
||||
busyRef.current = false
|
||||
resetPlayback()
|
||||
}, [clearQueue, resetPlayback])
|
||||
|
||||
const failPlayback = useCallback(() => {
|
||||
clearQueue()
|
||||
busyRef.current = false
|
||||
setActiveMessageId(null)
|
||||
}, [clearQueue])
|
||||
|
||||
const advanceQueue = useCallback((playbackId: number) => {
|
||||
if (playbackIdRef.current !== playbackId) return
|
||||
|
||||
clearAdvanceTimer()
|
||||
const next = queueRef.current.shift()
|
||||
|
||||
setState('idle')
|
||||
setCurrentText(null)
|
||||
setActiveMessageId(null)
|
||||
|
||||
if (!next) {
|
||||
busyRef.current = false
|
||||
return
|
||||
}
|
||||
|
||||
advanceTimerRef.current = setTimeout(() => {
|
||||
advanceTimerRef.current = null
|
||||
if (playbackIdRef.current !== playbackId) return
|
||||
void playMessageRef.current?.(next.messageId, next.text)
|
||||
}, QUEUE_PAUSE_MS)
|
||||
}, [clearAdvanceTimer])
|
||||
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
clearAdvanceTimer()
|
||||
queueRef.current = []
|
||||
busyRef.current = false
|
||||
playbackIdRef.current += 1
|
||||
cleanup()
|
||||
}
|
||||
}, [cleanup])
|
||||
}, [cleanup, clearAdvanceTimer])
|
||||
|
||||
// External API synthesis
|
||||
const synthesizeExternal = useCallback(async (text: string, signal: AbortSignal | undefined, playbackId: number): Promise<Blob | null> => {
|
||||
@@ -180,12 +240,10 @@ export function TTSProvider({ children }: TTSProviderProps) {
|
||||
}, [getChunkAudio])
|
||||
|
||||
const playChunk = useCallback(async (index: number, playbackId: number) => {
|
||||
if (playbackIdRef.current !== playbackId || index >= chunksRef.current.length) {
|
||||
if (playbackIdRef.current === playbackId) {
|
||||
setState('idle')
|
||||
setCurrentText(null)
|
||||
setActiveMessageId(null)
|
||||
}
|
||||
if (playbackIdRef.current !== playbackId) return
|
||||
|
||||
if (index >= chunksRef.current.length) {
|
||||
advanceQueue(playbackId)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -228,6 +286,7 @@ export function TTSProvider({ children }: TTSProviderProps) {
|
||||
if (audioRef.current === audio) {
|
||||
audioRef.current = null
|
||||
}
|
||||
failPlayback()
|
||||
setError('Audio playback failed')
|
||||
setState('error')
|
||||
}
|
||||
@@ -236,20 +295,23 @@ export function TTSProvider({ children }: TTSProviderProps) {
|
||||
await audio.play()
|
||||
} catch (err) {
|
||||
if (playbackIdRef.current !== playbackId) return
|
||||
failPlayback()
|
||||
setError(err instanceof Error ? err.message : 'TTS failed')
|
||||
setState('error')
|
||||
}
|
||||
}, [getChunkAudio, prefetchChunk])
|
||||
}, [getChunkAudio, prefetchChunk, advanceQueue, failPlayback])
|
||||
|
||||
// Builtin Web Speech synthesis - takes explicit config and optional messageId
|
||||
const speakBuiltinWithConfig = useCallback(async (text: string, config: TTSConfig, messageId: string | null = null): Promise<boolean> => {
|
||||
if (!isWebSpeechSupported()) {
|
||||
failPlayback()
|
||||
setError('Web Speech API not supported in this browser')
|
||||
setState('error')
|
||||
return false
|
||||
}
|
||||
|
||||
if (!text?.trim()) {
|
||||
failPlayback()
|
||||
setError('No text provided')
|
||||
setState('error')
|
||||
return false
|
||||
@@ -258,12 +320,14 @@ export function TTSProvider({ children }: TTSProviderProps) {
|
||||
const sanitizedText = sanitizeForTTS(text)
|
||||
|
||||
if (!sanitizedText?.trim()) {
|
||||
failPlayback()
|
||||
setError('No readable content after sanitization')
|
||||
setState('error')
|
||||
return false
|
||||
}
|
||||
|
||||
stop()
|
||||
resetPlayback()
|
||||
busyRef.current = true
|
||||
const playbackId = playbackIdRef.current
|
||||
setError(null)
|
||||
|
||||
@@ -287,13 +351,12 @@ export function TTSProvider({ children }: TTSProviderProps) {
|
||||
|
||||
synth.onEnd(() => {
|
||||
if (playbackIdRef.current !== playbackId) return
|
||||
setState('idle')
|
||||
setCurrentText(null)
|
||||
setActiveMessageId(null)
|
||||
advanceQueue(playbackId)
|
||||
})
|
||||
|
||||
synth.onError((err) => {
|
||||
if (playbackIdRef.current !== playbackId) return
|
||||
failPlayback()
|
||||
setError(err)
|
||||
setState('error')
|
||||
})
|
||||
@@ -311,15 +374,17 @@ export function TTSProvider({ children }: TTSProviderProps) {
|
||||
return true
|
||||
} catch (err) {
|
||||
if (playbackIdRef.current !== playbackId) return false
|
||||
failPlayback()
|
||||
setError(err instanceof Error ? err.message : 'TTS failed')
|
||||
setState('error')
|
||||
return false
|
||||
}
|
||||
}, [stop, getSynthesizer])
|
||||
}, [resetPlayback, advanceQueue, failPlayback, getSynthesizer])
|
||||
|
||||
// Internal helper to start external TTS playback
|
||||
const startExternalPlayback = useCallback((sanitizedText: string, original: string, messageId: string | null): boolean => {
|
||||
stop()
|
||||
resetPlayback()
|
||||
busyRef.current = true
|
||||
const playbackId = playbackIdRef.current
|
||||
setError(null)
|
||||
|
||||
@@ -337,11 +402,11 @@ export function TTSProvider({ children }: TTSProviderProps) {
|
||||
playChunk(0, playbackId)
|
||||
|
||||
return true
|
||||
}, [stop, playChunk])
|
||||
}, [resetPlayback, playChunk])
|
||||
|
||||
// Config-aware speak function - takes explicit config and optional messageId
|
||||
const speakWithConfig = useCallback(async (text: string, config: TTSConfig, messageId: string | null = null): Promise<boolean> => {
|
||||
const playWithConfig = useCallback(async (text: string, config: TTSConfig, messageId: string | null = null): Promise<boolean> => {
|
||||
if (!config.enabled) {
|
||||
failPlayback()
|
||||
setError('TTS is not enabled')
|
||||
setState('error')
|
||||
return false
|
||||
@@ -351,82 +416,113 @@ export function TTSProvider({ children }: TTSProviderProps) {
|
||||
|
||||
if (configIsBuiltin) {
|
||||
if (!isWebSpeechSupported()) {
|
||||
failPlayback()
|
||||
setError('Web Speech API not supported in this browser')
|
||||
setState('error')
|
||||
return false
|
||||
}
|
||||
return speakBuiltinWithConfig(text, config, messageId)
|
||||
} else {
|
||||
if (!config.apiKey) {
|
||||
setError('API key not configured')
|
||||
setState('error')
|
||||
return false
|
||||
}
|
||||
|
||||
if (!config.voice || !config.model) {
|
||||
setError('Voice or model not configured')
|
||||
setState('error')
|
||||
return false
|
||||
}
|
||||
|
||||
const sanitizedText = sanitizeForTTS(text)
|
||||
|
||||
if (!sanitizedText?.trim()) {
|
||||
setError('No readable content after sanitization')
|
||||
setState('error')
|
||||
return false
|
||||
}
|
||||
|
||||
return startExternalPlayback(sanitizedText, text, messageId)
|
||||
}
|
||||
}, [speakBuiltinWithConfig, startExternalPlayback])
|
||||
|
||||
// Message-aware speak function - tracks active message id
|
||||
if (!config.apiKey) {
|
||||
failPlayback()
|
||||
setError('API key not configured')
|
||||
setState('error')
|
||||
return false
|
||||
}
|
||||
|
||||
if (!config.voice || !config.model) {
|
||||
failPlayback()
|
||||
setError('Voice or model not configured')
|
||||
setState('error')
|
||||
return false
|
||||
}
|
||||
|
||||
const sanitizedText = sanitizeForTTS(text)
|
||||
|
||||
if (!sanitizedText?.trim()) {
|
||||
failPlayback()
|
||||
setError('No readable content after sanitization')
|
||||
setState('error')
|
||||
return false
|
||||
}
|
||||
|
||||
return startExternalPlayback(sanitizedText, text, messageId)
|
||||
}, [speakBuiltinWithConfig, startExternalPlayback, failPlayback])
|
||||
|
||||
const buildStoredConfig = useCallback((): TTSConfig | null => {
|
||||
if (!ttsConfig) return null
|
||||
|
||||
return {
|
||||
enabled: ttsConfig.enabled ?? false,
|
||||
provider: ttsConfig.provider ?? 'external',
|
||||
endpoint: ttsConfig.endpoint ?? '',
|
||||
apiKey: ttsConfig.apiKey ?? '',
|
||||
voice: ttsConfig.voice ?? '',
|
||||
model: ttsConfig.model ?? '',
|
||||
speed: ttsConfig.speed ?? 1.0,
|
||||
}
|
||||
}, [ttsConfig])
|
||||
|
||||
const playMessage = useCallback(async (messageId: string, text: string): Promise<boolean> => {
|
||||
const config = buildStoredConfig()
|
||||
|
||||
if (!config) {
|
||||
failPlayback()
|
||||
setError('TTS is not configured')
|
||||
setState('error')
|
||||
return false
|
||||
}
|
||||
|
||||
return playWithConfig(text, config, messageId)
|
||||
}, [buildStoredConfig, playWithConfig, failPlayback])
|
||||
|
||||
useEffect(() => {
|
||||
playMessageRef.current = playMessage
|
||||
}, [playMessage])
|
||||
|
||||
const speakWithConfig = useCallback(async (text: string, config: TTSConfig): Promise<boolean> => {
|
||||
clearQueue()
|
||||
return playWithConfig(text, config)
|
||||
}, [clearQueue, playWithConfig])
|
||||
|
||||
const speakMessage = useCallback(async (messageId: string, text: string): Promise<boolean> => {
|
||||
if (!ttsConfig) {
|
||||
setError('TTS is not configured')
|
||||
setState('error')
|
||||
return false
|
||||
}
|
||||
clearQueue()
|
||||
return playMessage(messageId, text)
|
||||
}, [clearQueue, playMessage])
|
||||
|
||||
const config: TTSConfig = {
|
||||
enabled: ttsConfig.enabled ?? false,
|
||||
provider: ttsConfig.provider ?? 'external',
|
||||
endpoint: ttsConfig.endpoint ?? '',
|
||||
apiKey: ttsConfig.apiKey ?? '',
|
||||
voice: ttsConfig.voice ?? '',
|
||||
model: ttsConfig.model ?? '',
|
||||
speed: ttsConfig.speed ?? 1.0,
|
||||
}
|
||||
|
||||
return speakWithConfig(text, config, messageId)
|
||||
}, [ttsConfig, speakWithConfig])
|
||||
|
||||
// Main speak function - uses stored preferences
|
||||
const speak = useCallback(async (text: string): Promise<boolean> => {
|
||||
if (!ttsConfig) {
|
||||
clearQueue()
|
||||
|
||||
const config = buildStoredConfig()
|
||||
|
||||
if (!config) {
|
||||
setError('TTS is not configured')
|
||||
setState('error')
|
||||
return false
|
||||
}
|
||||
|
||||
const config: TTSConfig = {
|
||||
enabled: ttsConfig.enabled ?? false,
|
||||
provider: ttsConfig.provider ?? 'external',
|
||||
endpoint: ttsConfig.endpoint ?? '',
|
||||
apiKey: ttsConfig.apiKey ?? '',
|
||||
voice: ttsConfig.voice ?? '',
|
||||
model: ttsConfig.model ?? '',
|
||||
speed: ttsConfig.speed ?? 1.0,
|
||||
return playWithConfig(text, config)
|
||||
}, [clearQueue, buildStoredConfig, playWithConfig])
|
||||
|
||||
const queueMessage = useCallback((messageId: string, text: string) => {
|
||||
if (messageId === activeMessageId || queueRef.current.some((item) => item.messageId === messageId)) {
|
||||
return
|
||||
}
|
||||
|
||||
return speakWithConfig(text, config)
|
||||
}, [ttsConfig, speakWithConfig])
|
||||
if (busyRef.current) {
|
||||
queueRef.current.push({ messageId, text })
|
||||
return
|
||||
}
|
||||
|
||||
void playMessage(messageId, text)
|
||||
}, [activeMessageId, playMessage])
|
||||
|
||||
const value = {
|
||||
speak,
|
||||
speakWithConfig,
|
||||
speakMessage,
|
||||
queueMessage,
|
||||
stop,
|
||||
state,
|
||||
error,
|
||||
|
||||
@@ -16,6 +16,7 @@ export interface TTSContextValue {
|
||||
speak: (text: string) => Promise<boolean>
|
||||
speakWithConfig: (text: string, config: TTSConfig) => Promise<boolean>
|
||||
speakMessage: (messageId: string, text: string) => Promise<boolean>
|
||||
queueMessage: (messageId: string, text: string) => void
|
||||
stop: () => void
|
||||
state: TTSState
|
||||
error: string | null
|
||||
|
||||
@@ -18,7 +18,7 @@ vi.mock('../useSettings', () => ({
|
||||
|
||||
interface MockTTSReturn {
|
||||
speak: ReturnType<typeof vi.fn>
|
||||
speakMessage: ReturnType<typeof vi.fn>
|
||||
queueMessage: ReturnType<typeof vi.fn>
|
||||
stop: ReturnType<typeof vi.fn>
|
||||
isEnabled: boolean
|
||||
isPlaying: boolean
|
||||
@@ -33,6 +33,7 @@ const createMessage = (
|
||||
id: string,
|
||||
completed?: number,
|
||||
text = 'Test message text',
|
||||
finish?: SessionMessageAssistant['finish'],
|
||||
): SessionMessageAssistant => ({
|
||||
id,
|
||||
type: 'assistant',
|
||||
@@ -42,6 +43,7 @@ const createMessage = (
|
||||
created: Date.now(),
|
||||
...(completed ? { completed } : {}),
|
||||
},
|
||||
...(finish ? { finish } : {}),
|
||||
content: [{ type: 'text', text }],
|
||||
})
|
||||
|
||||
@@ -68,14 +70,14 @@ const createAssistantMessageWithoutText = (id: string): SessionMessageAssistant
|
||||
|
||||
describe('useAutoPlayLastResponse', () => {
|
||||
const mockSpeak = vi.fn()
|
||||
const mockSpeakMessage = vi.fn()
|
||||
const mockQueueMessage = vi.fn()
|
||||
const mockStop = vi.fn()
|
||||
const mockUpdateSettings = vi.fn()
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks()
|
||||
mockSpeak.mockClear()
|
||||
mockSpeakMessage.mockClear()
|
||||
mockQueueMessage.mockClear()
|
||||
mockStop.mockClear()
|
||||
mockUpdateSettings.mockClear()
|
||||
})
|
||||
@@ -86,7 +88,7 @@ describe('useAutoPlayLastResponse', () => {
|
||||
} = {}) => {
|
||||
const mockTTS: MockTTSReturn = {
|
||||
speak: mockSpeak,
|
||||
speakMessage: mockSpeakMessage,
|
||||
queueMessage: mockQueueMessage,
|
||||
stop: mockStop,
|
||||
isEnabled: options.ttsEnabled ?? true,
|
||||
isPlaying: false,
|
||||
@@ -115,7 +117,7 @@ describe('useAutoPlayLastResponse', () => {
|
||||
return mockTTS
|
||||
}
|
||||
|
||||
it('does NOT call speakMessage when tts.enabled is false', () => {
|
||||
it('does NOT call queueMessage when tts.enabled is false', () => {
|
||||
setup({ ttsEnabled: false, autoPlay: true })
|
||||
|
||||
const message = createMessage('1', Date.now())
|
||||
@@ -124,14 +126,13 @@ describe('useAutoPlayLastResponse', () => {
|
||||
sessionId: 'test-session',
|
||||
lastAssistantMessage: message,
|
||||
lastAssistantText: 'Test text',
|
||||
isStreamingResponse: false,
|
||||
})
|
||||
)
|
||||
|
||||
expect(mockSpeakMessage).not.toHaveBeenCalled()
|
||||
expect(mockQueueMessage).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does NOT call speakMessage when tts.autoPlay is false', () => {
|
||||
it('does NOT call queueMessage when tts.autoPlay is false', () => {
|
||||
setup({ ttsEnabled: true, autoPlay: false })
|
||||
|
||||
const message = createMessage('1', Date.now())
|
||||
@@ -140,14 +141,13 @@ describe('useAutoPlayLastResponse', () => {
|
||||
sessionId: 'test-session',
|
||||
lastAssistantMessage: message,
|
||||
lastAssistantText: 'Test text',
|
||||
isStreamingResponse: false,
|
||||
})
|
||||
)
|
||||
|
||||
expect(mockSpeakMessage).not.toHaveBeenCalled()
|
||||
expect(mockQueueMessage).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does NOT call speakMessage on mount when last message was already time.completed', () => {
|
||||
it('does NOT call queueMessage on mount when last message was already time.completed', () => {
|
||||
setup()
|
||||
|
||||
const message = createMessage('1', Date.now() - 1000)
|
||||
@@ -156,14 +156,13 @@ describe('useAutoPlayLastResponse', () => {
|
||||
sessionId: 'test-session',
|
||||
lastAssistantMessage: message,
|
||||
lastAssistantText: 'Test text',
|
||||
isStreamingResponse: false,
|
||||
})
|
||||
)
|
||||
|
||||
expect(mockSpeakMessage).not.toHaveBeenCalled()
|
||||
expect(mockQueueMessage).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('CALLS speakMessage exactly once when lastAssistantMessage transitions from incomplete to completed', () => {
|
||||
it('CALLS queueMessage exactly once when lastAssistantMessage transitions from incomplete to completed', () => {
|
||||
setup()
|
||||
|
||||
const incompleteMessage = createMessage('1')
|
||||
@@ -174,26 +173,120 @@ describe('useAutoPlayLastResponse', () => {
|
||||
sessionId: 'test-session',
|
||||
lastAssistantMessage: incompleteMessage,
|
||||
lastAssistantText: 'Test text',
|
||||
isStreamingResponse: false,
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
expect(mockSpeakMessage).not.toHaveBeenCalled()
|
||||
expect(mockQueueMessage).not.toHaveBeenCalled()
|
||||
|
||||
const completedMessage = createMessage('1', Date.now())
|
||||
rerender({
|
||||
sessionId: 'test-session',
|
||||
lastAssistantMessage: completedMessage,
|
||||
lastAssistantText: 'Test text',
|
||||
isStreamingResponse: false,
|
||||
})
|
||||
|
||||
expect(mockSpeakMessage).toHaveBeenCalledTimes(1)
|
||||
expect(mockSpeakMessage).toHaveBeenCalledWith('1', 'Test text')
|
||||
expect(mockQueueMessage).toHaveBeenCalledTimes(1)
|
||||
expect(mockQueueMessage).toHaveBeenCalledWith('1', 'Test text')
|
||||
})
|
||||
|
||||
it('does NOT call speakMessage when unattributed playback is active, and does not speak it after playback ends', () => {
|
||||
it('queues a completed tool-calls step narration and then the following final response for a session with a baseline', () => {
|
||||
setup()
|
||||
|
||||
const { rerender } = renderHook(
|
||||
(props) => useAutoPlayLastResponse(props),
|
||||
{
|
||||
initialProps: {
|
||||
sessionId: 'test-session',
|
||||
lastAssistantMessage: createMessage('0', Date.now()),
|
||||
lastAssistantText: 'Baseline text',
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
expect(mockQueueMessage).not.toHaveBeenCalled()
|
||||
|
||||
rerender({
|
||||
sessionId: 'test-session',
|
||||
lastAssistantMessage: createMessage('1'),
|
||||
lastAssistantText: 'Narration',
|
||||
})
|
||||
|
||||
expect(mockQueueMessage).not.toHaveBeenCalled()
|
||||
|
||||
rerender({
|
||||
sessionId: 'test-session',
|
||||
lastAssistantMessage: createMessage('1', Date.now(), 'Narration', 'tool-calls'),
|
||||
lastAssistantText: 'Narration',
|
||||
})
|
||||
|
||||
expect(mockQueueMessage).toHaveBeenCalledTimes(1)
|
||||
expect(mockQueueMessage).toHaveBeenNthCalledWith(1, '1', 'Narration')
|
||||
|
||||
rerender({
|
||||
sessionId: 'test-session',
|
||||
lastAssistantMessage: createMessage('2'),
|
||||
lastAssistantText: 'Final',
|
||||
})
|
||||
|
||||
expect(mockQueueMessage).toHaveBeenCalledTimes(1)
|
||||
|
||||
rerender({
|
||||
sessionId: 'test-session',
|
||||
lastAssistantMessage: createMessage('2', Date.now(), 'Final', 'stop'),
|
||||
lastAssistantText: 'Final',
|
||||
})
|
||||
|
||||
expect(mockQueueMessage).toHaveBeenCalledTimes(2)
|
||||
expect(mockQueueMessage).toHaveBeenNthCalledWith(1, '1', 'Narration')
|
||||
expect(mockQueueMessage).toHaveBeenNthCalledWith(2, '2', 'Final')
|
||||
})
|
||||
|
||||
it('queues a completed tool-calls step narration and then the following final response for a fresh session', () => {
|
||||
setup()
|
||||
|
||||
const { rerender } = renderHook(
|
||||
(props) => useAutoPlayLastResponse(props),
|
||||
{
|
||||
initialProps: {
|
||||
sessionId: 'test-session',
|
||||
lastAssistantMessage: undefined,
|
||||
lastAssistantText: '',
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
expect(mockQueueMessage).not.toHaveBeenCalled()
|
||||
|
||||
rerender({
|
||||
sessionId: 'test-session',
|
||||
lastAssistantMessage: createMessage('1'),
|
||||
lastAssistantText: 'Narration',
|
||||
})
|
||||
|
||||
expect(mockQueueMessage).not.toHaveBeenCalled()
|
||||
|
||||
rerender({
|
||||
sessionId: 'test-session',
|
||||
lastAssistantMessage: createMessage('1', Date.now(), 'Narration', 'tool-calls'),
|
||||
lastAssistantText: 'Narration',
|
||||
})
|
||||
|
||||
expect(mockQueueMessage).toHaveBeenCalledTimes(1)
|
||||
expect(mockQueueMessage).toHaveBeenNthCalledWith(1, '1', 'Narration')
|
||||
|
||||
rerender({
|
||||
sessionId: 'test-session',
|
||||
lastAssistantMessage: createMessage('2', Date.now(), 'Final', 'stop'),
|
||||
lastAssistantText: 'Final',
|
||||
})
|
||||
|
||||
expect(mockQueueMessage).toHaveBeenCalledTimes(2)
|
||||
expect(mockQueueMessage).toHaveBeenNthCalledWith(1, '1', 'Narration')
|
||||
expect(mockQueueMessage).toHaveBeenNthCalledWith(2, '2', 'Final')
|
||||
})
|
||||
|
||||
it('does NOT call queueMessage when unattributed playback is active, and does not speak it after playback ends', () => {
|
||||
const mockTTS = setup()
|
||||
|
||||
const incompleteMessage = createMessage('1')
|
||||
@@ -204,7 +297,6 @@ describe('useAutoPlayLastResponse', () => {
|
||||
sessionId: 'test-session',
|
||||
lastAssistantMessage: incompleteMessage,
|
||||
lastAssistantText: 'Test text',
|
||||
isStreamingResponse: false,
|
||||
},
|
||||
}
|
||||
)
|
||||
@@ -217,23 +309,21 @@ describe('useAutoPlayLastResponse', () => {
|
||||
sessionId: 'test-session',
|
||||
lastAssistantMessage: completedMessage,
|
||||
lastAssistantText: 'Test text',
|
||||
isStreamingResponse: false,
|
||||
})
|
||||
|
||||
expect(mockSpeakMessage).not.toHaveBeenCalled()
|
||||
expect(mockQueueMessage).not.toHaveBeenCalled()
|
||||
|
||||
mockTTS.isPlaying = false
|
||||
rerender({
|
||||
sessionId: 'test-session',
|
||||
lastAssistantMessage: completedMessage,
|
||||
lastAssistantText: 'Test text',
|
||||
isStreamingResponse: false,
|
||||
})
|
||||
|
||||
expect(mockSpeakMessage).not.toHaveBeenCalled()
|
||||
expect(mockQueueMessage).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('CALLS speakMessage when a message-attributed playback is active', () => {
|
||||
it('CALLS queueMessage when a message-attributed playback is active', () => {
|
||||
const mockTTS = setup()
|
||||
|
||||
const incompleteMessage = createMessage('1')
|
||||
@@ -244,7 +334,6 @@ describe('useAutoPlayLastResponse', () => {
|
||||
sessionId: 'test-session',
|
||||
lastAssistantMessage: incompleteMessage,
|
||||
lastAssistantText: 'Test text',
|
||||
isStreamingResponse: false,
|
||||
},
|
||||
}
|
||||
)
|
||||
@@ -257,14 +346,13 @@ describe('useAutoPlayLastResponse', () => {
|
||||
sessionId: 'test-session',
|
||||
lastAssistantMessage: completedMessage,
|
||||
lastAssistantText: 'Test text',
|
||||
isStreamingResponse: false,
|
||||
})
|
||||
|
||||
expect(mockSpeakMessage).toHaveBeenCalledTimes(1)
|
||||
expect(mockSpeakMessage).toHaveBeenCalledWith('1', 'Test text')
|
||||
expect(mockQueueMessage).toHaveBeenCalledTimes(1)
|
||||
expect(mockQueueMessage).toHaveBeenCalledWith('1', 'Test text')
|
||||
})
|
||||
|
||||
it('does NOT call speakMessage twice for the same message id across multiple rerenders', () => {
|
||||
it('does NOT call queueMessage twice for the same message id across multiple rerenders', () => {
|
||||
setup()
|
||||
|
||||
const message = createMessage('1', Date.now())
|
||||
@@ -275,24 +363,22 @@ describe('useAutoPlayLastResponse', () => {
|
||||
sessionId: 'test-session',
|
||||
lastAssistantMessage: message,
|
||||
lastAssistantText: 'Test text',
|
||||
isStreamingResponse: false,
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
expect(mockSpeakMessage).not.toHaveBeenCalled()
|
||||
expect(mockQueueMessage).not.toHaveBeenCalled()
|
||||
|
||||
rerender({
|
||||
sessionId: 'test-session',
|
||||
lastAssistantMessage: message,
|
||||
lastAssistantText: 'Test text',
|
||||
isStreamingResponse: false,
|
||||
})
|
||||
|
||||
expect(mockSpeakMessage).not.toHaveBeenCalled()
|
||||
expect(mockQueueMessage).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('CALLS speakMessage for a subsequent new message id after the baseline', () => {
|
||||
it('CALLS queueMessage for a subsequent new message id after the baseline', () => {
|
||||
setup()
|
||||
|
||||
const firstMessage = createMessage('1', Date.now() - 2000)
|
||||
@@ -304,23 +390,21 @@ describe('useAutoPlayLastResponse', () => {
|
||||
sessionId: 'test-session',
|
||||
lastAssistantMessage: firstMessage,
|
||||
lastAssistantText: 'First text',
|
||||
isStreamingResponse: false,
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
expect(mockSpeakMessage).not.toHaveBeenCalled()
|
||||
expect(mockQueueMessage).not.toHaveBeenCalled()
|
||||
|
||||
const secondMessage = createMessage('2', Date.now())
|
||||
rerender({
|
||||
sessionId: 'test-session',
|
||||
lastAssistantMessage: secondMessage,
|
||||
lastAssistantText: 'Second text',
|
||||
isStreamingResponse: false,
|
||||
})
|
||||
|
||||
expect(mockSpeakMessage).toHaveBeenCalledTimes(1)
|
||||
expect(mockSpeakMessage).toHaveBeenCalledWith('2', 'Second text')
|
||||
expect(mockQueueMessage).toHaveBeenCalledTimes(1)
|
||||
expect(mockQueueMessage).toHaveBeenCalledWith('2', 'Second text')
|
||||
})
|
||||
|
||||
it('resets baseline when sessionId changes', () => {
|
||||
@@ -335,42 +419,92 @@ describe('useAutoPlayLastResponse', () => {
|
||||
sessionId: 'session-1',
|
||||
lastAssistantMessage: message1,
|
||||
lastAssistantText: 'Session 1 text',
|
||||
isStreamingResponse: false,
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
expect(mockSpeakMessage).not.toHaveBeenCalled()
|
||||
expect(mockQueueMessage).not.toHaveBeenCalled()
|
||||
|
||||
const message2 = createMessage('1', Date.now())
|
||||
rerender({
|
||||
sessionId: 'session-2',
|
||||
lastAssistantMessage: message2,
|
||||
lastAssistantText: 'Session 2 text',
|
||||
isStreamingResponse: false,
|
||||
})
|
||||
|
||||
expect(mockSpeakMessage).toHaveBeenCalledTimes(1)
|
||||
expect(mockSpeakMessage).toHaveBeenCalledWith('1', 'Session 2 text')
|
||||
expect(mockQueueMessage).toHaveBeenCalledTimes(1)
|
||||
expect(mockQueueMessage).toHaveBeenCalledWith('1', 'Session 2 text')
|
||||
})
|
||||
|
||||
it('does NOT call speakMessage when isStreamingResponse is true', () => {
|
||||
it('CALLS queueMessage once for the first reply in a fresh session when it starts empty then streams to completion', () => {
|
||||
setup()
|
||||
|
||||
const message = createMessage('1', Date.now())
|
||||
renderHook(() =>
|
||||
useAutoPlayLastResponse({
|
||||
sessionId: 'test-session',
|
||||
lastAssistantMessage: message,
|
||||
lastAssistantText: 'Test text',
|
||||
isStreamingResponse: true,
|
||||
})
|
||||
const { rerender } = renderHook(
|
||||
(props) => useAutoPlayLastResponse(props),
|
||||
{
|
||||
initialProps: {
|
||||
sessionId: 'test-session',
|
||||
lastAssistantMessage: undefined,
|
||||
lastAssistantText: '',
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
expect(mockSpeakMessage).not.toHaveBeenCalled()
|
||||
expect(mockQueueMessage).not.toHaveBeenCalled()
|
||||
|
||||
rerender({
|
||||
sessionId: 'test-session',
|
||||
lastAssistantMessage: createMessage('1'),
|
||||
lastAssistantText: 'Test text',
|
||||
})
|
||||
|
||||
expect(mockQueueMessage).not.toHaveBeenCalled()
|
||||
|
||||
rerender({
|
||||
sessionId: 'test-session',
|
||||
lastAssistantMessage: createMessage('1', Date.now()),
|
||||
lastAssistantText: 'Test text',
|
||||
})
|
||||
|
||||
expect(mockQueueMessage).toHaveBeenCalledTimes(1)
|
||||
expect(mockQueueMessage).toHaveBeenCalledWith('1', 'Test text')
|
||||
})
|
||||
|
||||
it('does NOT call speakMessage when lastAssistantText is empty', () => {
|
||||
it('CALLS queueMessage once when mounting on a completed message without text and then completing a new reply', () => {
|
||||
setup()
|
||||
|
||||
const { rerender } = renderHook(
|
||||
(props) => useAutoPlayLastResponse(props),
|
||||
{
|
||||
initialProps: {
|
||||
sessionId: 'test-session',
|
||||
lastAssistantMessage: createAssistantMessageWithoutText('0'),
|
||||
lastAssistantText: '',
|
||||
},
|
||||
}
|
||||
)
|
||||
|
||||
expect(mockQueueMessage).not.toHaveBeenCalled()
|
||||
|
||||
rerender({
|
||||
sessionId: 'test-session',
|
||||
lastAssistantMessage: createMessage('1'),
|
||||
lastAssistantText: 'Reply',
|
||||
})
|
||||
|
||||
expect(mockQueueMessage).not.toHaveBeenCalled()
|
||||
|
||||
rerender({
|
||||
sessionId: 'test-session',
|
||||
lastAssistantMessage: createMessage('1', Date.now()),
|
||||
lastAssistantText: 'Reply',
|
||||
})
|
||||
|
||||
expect(mockQueueMessage).toHaveBeenCalledTimes(1)
|
||||
expect(mockQueueMessage).toHaveBeenCalledWith('1', 'Reply')
|
||||
})
|
||||
|
||||
it('does NOT call queueMessage when lastAssistantText is empty', () => {
|
||||
setup()
|
||||
|
||||
const message = createMessage('1', Date.now())
|
||||
@@ -379,14 +513,13 @@ describe('useAutoPlayLastResponse', () => {
|
||||
sessionId: 'test-session',
|
||||
lastAssistantMessage: message,
|
||||
lastAssistantText: '',
|
||||
isStreamingResponse: false,
|
||||
})
|
||||
)
|
||||
|
||||
expect(mockSpeakMessage).not.toHaveBeenCalled()
|
||||
expect(mockQueueMessage).not.toHaveBeenCalled()
|
||||
})
|
||||
|
||||
it('does NOT call speakMessage when lastAssistantText is whitespace only', () => {
|
||||
it('does NOT call queueMessage when lastAssistantText is whitespace only', () => {
|
||||
setup()
|
||||
|
||||
const message = createMessage('1', Date.now())
|
||||
@@ -395,11 +528,10 @@ describe('useAutoPlayLastResponse', () => {
|
||||
sessionId: 'test-session',
|
||||
lastAssistantMessage: message,
|
||||
lastAssistantText: ' ',
|
||||
isStreamingResponse: false,
|
||||
})
|
||||
)
|
||||
|
||||
expect(mockSpeakMessage).not.toHaveBeenCalled()
|
||||
expect(mockQueueMessage).not.toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
@@ -7,7 +7,6 @@ interface UseAutoPlayLastResponseParams {
|
||||
sessionId: string
|
||||
lastAssistantMessage: SessionMessageInfo | undefined
|
||||
lastAssistantText: string
|
||||
isStreamingResponse: boolean
|
||||
}
|
||||
|
||||
interface PlayableAssistantMessage {
|
||||
@@ -35,9 +34,8 @@ export function useAutoPlayLastResponse({
|
||||
sessionId,
|
||||
lastAssistantMessage,
|
||||
lastAssistantText,
|
||||
isStreamingResponse,
|
||||
}: UseAutoPlayLastResponseParams): void {
|
||||
const { speakMessage, isEnabled: ttsEnabled, isPlaying, isLoading, activeMessageId } = useTTS()
|
||||
const { queueMessage, isEnabled: ttsEnabled, isPlaying, isLoading, activeMessageId } = useTTS()
|
||||
const { preferences } = useSettings()
|
||||
|
||||
const autoPlayEnabled = preferences?.tts?.autoPlay ?? false
|
||||
@@ -76,7 +74,7 @@ export function useAutoPlayLastResponse({
|
||||
return
|
||||
}
|
||||
|
||||
if (isStreamingResponse || !lastAssistantMessage) {
|
||||
if (!lastAssistantMessage) {
|
||||
return
|
||||
}
|
||||
|
||||
@@ -100,7 +98,7 @@ export function useAutoPlayLastResponse({
|
||||
lastSpokenIdRef.current = messageId
|
||||
lastKnownCompletedRef.current[messageId] = true
|
||||
if (hasSeenIncompleteRef.current && shouldAutoSpeak) {
|
||||
speakMessage(messageId, lastAssistantText)
|
||||
queueMessage(messageId, lastAssistantText)
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -108,7 +106,7 @@ export function useAutoPlayLastResponse({
|
||||
if (!wasCompleted && messageId === lastSpokenIdRef.current) {
|
||||
lastKnownCompletedRef.current[messageId] = true
|
||||
if (shouldAutoSpeak) {
|
||||
speakMessage(messageId, lastAssistantText)
|
||||
queueMessage(messageId, lastAssistantText)
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -117,15 +115,14 @@ export function useAutoPlayLastResponse({
|
||||
lastSpokenIdRef.current = messageId
|
||||
lastKnownCompletedRef.current[messageId] = true
|
||||
if (shouldAutoSpeak) {
|
||||
speakMessage(messageId, lastAssistantText)
|
||||
queueMessage(messageId, lastAssistantText)
|
||||
}
|
||||
}
|
||||
}, [
|
||||
ttsEnabled,
|
||||
autoPlayEnabled,
|
||||
isStreamingResponse,
|
||||
lastAssistantMessage,
|
||||
lastAssistantText,
|
||||
speakMessage,
|
||||
queueMessage,
|
||||
])
|
||||
}
|
||||
@@ -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
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { getSessionListPath, getSwipeBackTarget, getAssistantPath, getAssistantSessionListPath, isAssistantPath, getPathWithReturnTo, getReturnToPath, getRepoPath, getServerProjectPath, getServerSessionPath, getSessionPath, parseRepoRoute, parseServerProjectRoute, parseServerSessionRoute } from './navigation';
|
||||
import { getSessionListPath, getSwipeBackTarget, getAssistantPath, getAssistantSessionListPath, isAssistantPath, getPathWithReturnTo, getReturnToPath, getRepoPath, getServerProjectPath, getServerSessionPath, getSessionPath, isSessionDetailRoute, parseRepoRoute, parseServerProjectRoute, parseServerSessionRoute } from './navigation';
|
||||
|
||||
describe('getAssistantPath', () => {
|
||||
it('returns /assistant', () => {
|
||||
@@ -206,6 +206,31 @@ describe('return target helpers', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('isSessionDetailRoute', () => {
|
||||
it('matches local session detail routes', () => {
|
||||
expect(isSessionDetailRoute('/repos/42/sessions/abc')).toBe(true);
|
||||
expect(isSessionDetailRoute('/repos/0/sessions/ses_assistant')).toBe(true);
|
||||
});
|
||||
|
||||
it('matches linked server session detail routes', () => {
|
||||
expect(isSessionDetailRoute('/servers/srv_kitchen/sessions/ses_abc')).toBe(true);
|
||||
expect(isSessionDetailRoute('/servers/https%3A%2F%2Fhost/sessions/ses_abc')).toBe(true);
|
||||
});
|
||||
|
||||
it('matches trailing-slash session detail routes', () => {
|
||||
expect(isSessionDetailRoute('/repos/42/sessions/abc/')).toBe(true);
|
||||
expect(isSessionDetailRoute('/servers/srv_kitchen/sessions/ses_abc/')).toBe(true);
|
||||
});
|
||||
|
||||
it('rejects everything else', () => {
|
||||
expect(isSessionDetailRoute('/')).toBe(false);
|
||||
expect(isSessionDetailRoute('/repos/42')).toBe(false);
|
||||
expect(isSessionDetailRoute('/servers/srv_kitchen/projects')).toBe(false);
|
||||
expect(isSessionDetailRoute('/servers/srv_kitchen/sessions')).toBe(false);
|
||||
expect(isSessionDetailRoute('/assistant')).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getSwipeBackTarget', () => {
|
||||
describe('session detail routes', () => {
|
||||
it('returns repo path for normal session detail', () => {
|
||||
|
||||
@@ -65,6 +65,11 @@ export function parseServerSessionRoute(pathname: string): { serverId: string; s
|
||||
return { serverId, sessionId };
|
||||
}
|
||||
|
||||
export function isSessionDetailRoute(pathname: string): boolean {
|
||||
const normalizedPathname = pathname.replace(/\/+$/, '');
|
||||
return /^\/repos\/[^/]+\/sessions\/[^/]+$/.test(normalizedPathname) || parseServerSessionRoute(normalizedPathname) !== null;
|
||||
}
|
||||
|
||||
export function parseRepoRoute(pathname: string): { repoId: number | null; section: string | null; sessionId: string | null } {
|
||||
const match = /^\/repos\/(\d+)(?:\/([^/]+)(?:\/([^/]+))?)?/.exec(pathname);
|
||||
if (!match) {
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -1,41 +1,21 @@
|
||||
import { useState } from "react";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { Plus, FolderOpen, CalendarClock, Settings } from "lucide-react";
|
||||
import { Plus, FolderOpen, CalendarClock } from "lucide-react";
|
||||
import { LOCAL_OPENCODE_SERVER_ID } from "@opencode-manager/shared/schemas";
|
||||
import { RepoList } from "@/components/repo/RepoList";
|
||||
import { AddRepoDialog } from "@/components/repo/AddRepoDialog";
|
||||
import { FileBrowserSheet } from "@/components/file-browser/FileBrowserSheet";
|
||||
import { RemoteProjectList } from "@/components/servers/RemoteProjectList";
|
||||
import { ConnectionStatus } from "@/components/servers/ConnectionStatus";
|
||||
import { Header } from "@/components/ui/header";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import { PendingActionsGroup } from "@/components/notifications/PendingActionsGroup";
|
||||
import { LinkedServersNav } from "@/components/navigation/LinkedServersNav";
|
||||
import { ToolSidePanel } from "@/components/navigation/ToolSidePanel";
|
||||
import { useDialogParam } from "@/hooks/useDialogParam";
|
||||
import { useMobile } from "@/hooks/useMobile";
|
||||
import { useOpenCodeServerStatuses } from "@/hooks/useOpenCodeServers";
|
||||
import { useSettingsDialog } from "@/hooks/useSettingsDialog";
|
||||
import { useSidebarServerSelection } from "@/hooks/useSidebarServerSelection";
|
||||
import { useToolPanel } from "@/hooks/useToolPanel";
|
||||
|
||||
function LinkedServerHeaderActions({ serverId }: { serverId: string }) {
|
||||
const { statusById, isLoading } = useOpenCodeServerStatuses();
|
||||
const { openTab } = useSettingsDialog();
|
||||
const status = statusById[serverId];
|
||||
|
||||
return (
|
||||
<>
|
||||
<span className="flex max-w-[45vw] items-center overflow-hidden sm:max-w-none">
|
||||
<ConnectionStatus status={status} isLoading={isLoading && !status} />
|
||||
</span>
|
||||
<Button variant="outline" size="sm" className="hidden sm:flex" onClick={() => openTab('servers')}>
|
||||
<Settings className="mr-1 h-4 w-4" />
|
||||
Manage servers
|
||||
</Button>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function Repos() {
|
||||
const navigate = useNavigate();
|
||||
const [addRepoOpen, setAddRepoOpen] = useState(false);
|
||||
@@ -60,7 +40,7 @@ export function Repos() {
|
||||
<div className="flex items-center gap-1">
|
||||
<PendingActionsGroup />
|
||||
</div>
|
||||
{isLocalServer ? (
|
||||
{isLocalServer && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
@@ -70,9 +50,8 @@ export function Repos() {
|
||||
>
|
||||
<FolderOpen className="w-4 h-4" />
|
||||
</Button>
|
||||
) : (
|
||||
<LinkedServerHeaderActions serverId={selectedServerId} />
|
||||
)}
|
||||
<LinkedServersNav variant="header" />
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => navigate('/schedules')}
|
||||
|
||||
@@ -365,7 +365,6 @@ export function SessionDetail() {
|
||||
sessionId: sessionId ?? '',
|
||||
lastAssistantMessage,
|
||||
lastAssistantText,
|
||||
isStreamingResponse,
|
||||
});
|
||||
|
||||
const handleShowSessionsDialog = useCallback(() => setSessionsDialogOpen(true), []);
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
import { act, fireEvent, render, screen } from '@testing-library/react'
|
||||
import { act, render, screen, within } from '@testing-library/react'
|
||||
import userEvent from '@testing-library/user-event'
|
||||
import { MemoryRouter, Route, Routes, useLocation } from 'react-router-dom'
|
||||
import { LOCAL_OPENCODE_SERVER_ID } from '@opencode-manager/shared/schemas'
|
||||
import { Repos } from '../Repos'
|
||||
@@ -29,6 +30,11 @@ vi.mock('@/hooks/useSettingsDialog', () => ({
|
||||
}),
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useActiveWork', () => ({
|
||||
useServerActivityState: () => null,
|
||||
useLocalActivityState: () => null,
|
||||
}))
|
||||
|
||||
vi.mock('@/hooks/useMobile', () => ({
|
||||
isMobileViewport: () => false,
|
||||
useMobile: () => false,
|
||||
@@ -127,7 +133,6 @@ describe('Repos', () => {
|
||||
expect(screen.queryByText('local-repos')).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: 'Repo' })).not.toBeInTheDocument()
|
||||
expect(screen.queryByRole('button', { name: 'Open files' })).not.toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: /Manage servers/ })).toHaveClass('hidden', 'sm:flex')
|
||||
expect(screen.getByRole('button', { name: 'All Schedules' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Settings' })).toBeInTheDocument()
|
||||
})
|
||||
@@ -148,42 +153,39 @@ describe('Repos', () => {
|
||||
expect(screen.getByTestId('location')).toHaveTextContent('/')
|
||||
})
|
||||
|
||||
it('shows the connection status of the selected linked server', () => {
|
||||
it('names the selected linked server in the header with its connection state', () => {
|
||||
useSidebarServerStore.setState({ serverId: 'srv_kitchen' })
|
||||
|
||||
renderRepos()
|
||||
|
||||
expect(screen.getByText(/Connected/)).toBeInTheDocument()
|
||||
expect(screen.getByText(/v2\.0\.15/)).toBeInTheDocument()
|
||||
const switcher = screen.getByRole('button', { name: 'Switch server, current: Kitchen' })
|
||||
expect(switcher).toHaveTextContent('Kitchen')
|
||||
expect(within(switcher).getByRole('img', { name: 'Connected' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('shows an unreachable linked server with its error', () => {
|
||||
useSidebarServerStore.setState({ serverId: 'srv_kitchen' })
|
||||
mocks.useOpenCodeServerStatuses.mockReturnValue({
|
||||
statuses: [],
|
||||
statusById: {
|
||||
srv_kitchen: {
|
||||
serverId: 'srv_kitchen',
|
||||
connected: false,
|
||||
version: null,
|
||||
error: 'connection refused',
|
||||
},
|
||||
},
|
||||
isLoading: false,
|
||||
})
|
||||
|
||||
it('shows the server switcher on the local server and keeps local-only actions', () => {
|
||||
renderRepos()
|
||||
|
||||
expect(screen.getByText(/Unreachable/)).toBeInTheDocument()
|
||||
expect(screen.getByText(/connection refused/)).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Switch server, current: OC Manager' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Repo' })).toBeInTheDocument()
|
||||
expect(screen.getByRole('button', { name: 'Open files' })).toBeInTheDocument()
|
||||
})
|
||||
|
||||
it('opens the servers settings tab from the header', () => {
|
||||
it('switches servers and opens server settings from the header dropdown', async () => {
|
||||
const user = userEvent.setup()
|
||||
useSidebarServerStore.setState({ serverId: 'srv_kitchen' })
|
||||
|
||||
renderRepos()
|
||||
|
||||
fireEvent.click(screen.getByRole('button', { name: /Manage servers/ }))
|
||||
await user.click(screen.getByRole('button', { name: 'Switch server, current: Kitchen' }))
|
||||
await user.click(await screen.findByRole('menuitem', { name: /OC Manager/ }))
|
||||
|
||||
expect(screen.getByText('local-repos')).toBeInTheDocument()
|
||||
expect(screen.getByTestId('location')).toHaveTextContent('/')
|
||||
|
||||
act(() => useSidebarServerStore.getState().selectServer('srv_kitchen'))
|
||||
await user.click(screen.getByRole('button', { name: 'Switch server, current: Kitchen' }))
|
||||
await user.click(await screen.findByRole('menuitem', { name: /Manage servers/ }))
|
||||
|
||||
expect(mocks.openTab).toHaveBeenCalledWith('servers')
|
||||
})
|
||||
|
||||
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