Skip to content

armgit / jan

Public Imported from GitHub
0

Jan is an open source alternative to ChatGPT that runs 100% offline on your computer.

feat(cowork): stream a write's body into its card, as the TUI does

Akarshan Biswas13736b65f83f
diff --git a/web-app/src/containers/message/AgentToolWidget.tsx b/web-app/src/containers/message/AgentToolWidget.tsx
index ac0127f13..9705d7243 100644
--- a/web-app/src/containers/message/AgentToolWidget.tsx
+++ b/web-app/src/containers/message/AgentToolWidget.tsx
@@ -18,6 +18,7 @@ import {
type ToolCallBar,
} from '@/lib/toolPresentation'
import { cn } from '@/lib/utils'
+import { writeTail } from '@/lib/streamingWrite'
import { useToolCallRuntime } from '@/hooks/useToolCallRuntime'
import { Caret, ToolBar } from './ToolBar'
@@ -69,6 +70,35 @@ const DiffBlock = memo(({ diff }: { diff: string }) => (
DiffBlock.displayName = 'DiffBlock'
+/**
+ * A `write`'s file content as it streams in: a window on the tail, numbered
+ * from where it actually sits in the file, so a long write reads as progress
+ * rather than as a spinner. Mirrors the TUI's streaming-write preview.
+ */
+const WritePreviewBlock = memo(({ body }: { body: string }) => {
+ const { lines, skipped } = useMemo(() => writeTail(body), [body])
+ // Fixed to the widest number in view, so the text does not shift sideways as
+ // the count crosses 10 and 100.
+ const gutter = String(skipped + lines.length).length
+
+ return (
+ <div className="mt-1.5 max-h-56 overflow-hidden rounded-md border bg-card/40 py-1 font-mono text-xs">
+ {lines.map((line, i) => (
+ <div key={i} className="flex gap-2 px-2">
+ <span className="shrink-0 select-none tabular-nums text-muted-foreground/40">
+ {String(skipped + i + 1).padStart(gutter, ' ')}
+ </span>
+ <span className="min-w-0 whitespace-pre-wrap wrap-break-word text-muted-foreground">
+ {line || ' '}
+ </span>
+ </div>
+ ))}
+ </div>
+ )
+})
+
+WritePreviewBlock.displayName = 'WritePreviewBlock'
+
export type TerminalWidgetProps = {
bar: Extract<ToolCallBar, { variant: 'terminal' }>
state: ToolUIPart['state']
@@ -228,7 +258,8 @@ export const AgentToolWidget = memo(
// `ls` with no path lists the workspace root; show that rather than a bar
// that reads as though an argument failed to stream.
const value =
- bar.target || (LISTING_TOOLS.has(bar.tool) ? t('tools:toolCall.workspaceRoot') : '')
+ bar.target ||
+ (LISTING_TOOLS.has(bar.tool) ? t('tools:toolCall.workspaceRoot') : '')
return (
<div className="space-y-1.5">
@@ -255,12 +286,19 @@ export const AgentToolWidget = memo(
</div>
)}
- {running && !errorText && (
- <div className="px-2 text-sm">
- <Shimmer duration={1}>
- {t(RUNNING_KEYS[bar.tool] ?? 'tools:toolCall.reading')}
- </Shimmer>
- </div>
+ {/* The body says more than "Writing…" ever could, so it replaces the
+ throbber the moment the first line arrives. */}
+ {running && !errorText && bar.body ? (
+ <WritePreviewBlock body={bar.body} />
+ ) : (
+ running &&
+ !errorText && (
+ <div className="px-2 text-sm">
+ <Shimmer duration={1}>
+ {t(RUNNING_KEYS[bar.tool] ?? 'tools:toolCall.reading')}
+ </Shimmer>
+ </div>
+ )
)}
{!running &&
diff --git a/web-app/src/containers/message/__tests__/AgentToolWidget.test.tsx b/web-app/src/containers/message/__tests__/AgentToolWidget.test.tsx
index c38ec4a17..76427749b 100644
--- a/web-app/src/containers/message/__tests__/AgentToolWidget.test.tsx
+++ b/web-app/src/containers/message/__tests__/AgentToolWidget.test.tsx
@@ -36,6 +36,41 @@ describe('AgentToolWidget', () => {
expect(screen.getByText(key)).toBeInTheDocument()
})
+ /// The body is the work, and a large write takes long enough that a verb
+ /// says nothing about it -- so the preview takes the throbber's place.
+ it('previews a write body instead of naming the verb', () => {
+ render(
+ <AgentToolWidget
+ bar={{
+ variant: 'workspace',
+ tool: 'write',
+ target: 'game.html',
+ body: '<!doctype html>\n<html>',
+ }}
+ state="input-streaming"
+ toolCallId="tc1"
+ />
+ )
+ expect(screen.queryByText('tools:toolCall.writing')).not.toBeInTheDocument()
+ expect(screen.getByText('<!doctype html>')).toBeInTheDocument()
+ // Numbered, so a window onto a long file says where it sits.
+ expect(screen.getByText('1')).toBeInTheDocument()
+ expect(screen.getByText('2')).toBeInTheDocument()
+ })
+
+ /// Before the body opens there is nothing to preview, and the verb is all
+ /// there is to say.
+ it('keeps the verb until the body starts arriving', () => {
+ render(
+ <AgentToolWidget
+ bar={{ variant: 'workspace', tool: 'write', target: 'game.html' }}
+ state="input-streaming"
+ toolCallId="tc1"
+ />
+ )
+ expect(screen.getByText('tools:toolCall.writing')).toBeInTheDocument()
+ })
+
it('prompts for a pattern rather than a path on grep', () => {
renderRunning('grep')
expect(
diff --git a/web-app/src/hooks/useCoworkRun.ts b/web-app/src/hooks/useCoworkRun.ts
index b1e2e6576..9026eb513 100644
--- a/web-app/src/hooks/useCoworkRun.ts
+++ b/web-app/src/hooks/useCoworkRun.ts
@@ -164,11 +164,6 @@ type CoworkRunState = {
appendToken: (sid: string, text: string) => void
pushToolTurn: (sid: string, turn: CoworkTurn) => void
updateToolTurn: (sid: string, callId: string, patch: Partial<CoworkTurn>) => void
- // `tool_call_started`: open a live tool row before any args exist, so the
- // card shows a spot the user can watch fill as the arguments stream.
- announceToolCall: (sid: string, id: string, name: string) => void
- // `tool_call_args_delta`: append raw JSON argument text to the running row.
- appendToolArgs: (sid: string, id: string, delta: string) => void
/** Empty a session's subagent lanes at the start of a run, so the panel shows
* this run's children rather than every child the session ever had. */
resetSubagents: (sid: string) => void
@@ -245,35 +240,6 @@ export const useCoworkRun = create<CoworkRunState>()((set, get) => ({
return next === turns ? {} : { liveTurns: { ...s.liveTurns, [sid]: next } }
}),
- announceToolCall: (sid, id, name) =>
- set((s) => {
- const turns = s.liveTurns[sid] ?? []
- if (turns.some((tn) => tn.role === 'tool' && tn.callId === id)) return {}
- return {
- liveTurns: {
- ...s.liveTurns,
- [sid]: [
- ...turns,
- { role: 'tool', content: '', callId: id, name, args: null, argsLive: '', status: 'running' },
- ],
- },
- }
- }),
-
- appendToolArgs: (sid, id, delta) =>
- set((s) => {
- const turns = s.liveTurns[sid] ?? []
- const idx = turns.findIndex((tn) => tn.role === 'tool' && tn.callId === id)
- if (idx === -1) return {}
- const prev = turns[idx].argsLive ?? ''
- return {
- liveTurns: {
- ...s.liveTurns,
- [sid]: [...turns.slice(0, idx), { ...turns[idx], argsLive: prev + delta }, ...turns.slice(idx + 1)],
- },
- }
- }),
-
resetSubagents: (sid) =>
set((s) => ({ subagents: { ...s.subagents, [sid]: [] } })),
diff --git a/web-app/src/lib/__tests__/coworkTurns.test.ts b/web-app/src/lib/__tests__/coworkTurns.test.ts
index ed301547c..c15d1861f 100644
--- a/web-app/src/lib/__tests__/coworkTurns.test.ts
+++ b/web-app/src/lib/__tests__/coworkTurns.test.ts
@@ -16,11 +16,7 @@ describe('coworkTurnsToUIMessages', () => {
{ role: 'assistant', content: 'answer' },
{ role: 'user', content: 'second' },
])
- expect(messages.map((m) => m.role)).toEqual([
- 'user',
- 'assistant',
- 'user',
- ])
+ expect(messages.map((m) => m.role)).toEqual(['user', 'assistant', 'user'])
})
it('maps a tool turn onto a tool-<name> part carrying its input', () => {
@@ -44,7 +40,13 @@ describe('coworkTurnsToUIMessages', () => {
it('leaves a running tool call awaiting output', () => {
const part = toolPart([
- { role: 'tool', content: '', callId: 'c', name: 'bash', status: 'running' },
+ {
+ role: 'tool',
+ content: '',
+ callId: 'c',
+ name: 'bash',
+ status: 'running',
+ },
])
expect(part.state).toBe('input-available')
expect(part.output).toBeUndefined()
@@ -95,6 +97,44 @@ describe('coworkTurnsToUIMessages', () => {
expect(part.output).toBe('legacy body')
})
+ /// A write's body is the work, so the card reads it out of the raw argument
+ /// fragment rather than holding empty until the closing brace lands.
+ it('reads a running call out of its still-streaming arguments', () => {
+ const part = toolPart([
+ {
+ role: 'tool',
+ content: '',
+ callId: 'c',
+ name: 'write',
+ status: 'running',
+ argsLive: '{"path":"game.html","content":"<!doctype html>\\n<htm',
+ },
+ ])
+ expect(part.state).toBe('input-streaming')
+ expect(part.input).toEqual({
+ path: 'game.html',
+ content: '<!doctype html>\n<htm',
+ })
+ })
+
+ /// Once the call is complete its parsed arguments are authoritative: the
+ /// fragment they were read from is a prefix of them.
+ it('prefers the settled arguments over the fragment', () => {
+ const part = toolPart([
+ {
+ role: 'tool',
+ content: '',
+ callId: 'c',
+ name: 'write',
+ status: 'running',
+ argsLive: '{"path":"game.htm',
+ args: { path: 'game.html', content: 'done' },
+ },
+ ])
+ expect(part.state).toBe('input-available')
+ expect(part.input).toEqual({ path: 'game.html', content: 'done' })
+ })
+
it('keeps ids unique across prefixes so committed and live turns can merge', () => {
const turns: CoworkTurn[] = [{ role: 'user', content: 'hi' }]
const committed = coworkTurnsToUIMessages(turns, 'c')
diff --git a/web-app/src/lib/__tests__/partialJson.test.ts b/web-app/src/lib/__tests__/partialJson.test.ts
new file mode 100644
index 000000000..c8a79632a
--- /dev/null
+++ b/web-app/src/lib/__tests__/partialJson.test.ts
@@ -0,0 +1,73 @@
+import { describe, it, expect } from 'vitest'
+import {
+ partialJsonField,
+ partialToolInput,
+ unescapePartialJsonString,
+} from '../partialJson'
+
+/// Mirrors `partial_json_field_reads_a_truncated_value` in the TUI: the two
+/// readers see the same fragments, so they are held to the same cases.
+describe('partialJsonField', () => {
+ it('reads a closed value', () => {
+ const done = '{"path":"a.html","content":"<h1>hi</h1>"}'
+ expect(partialJsonField(done, 'path')).toBe('a.html')
+ expect(partialJsonField(done, 'content')).toBe('<h1>hi</h1>')
+ })
+
+ it('takes everything that arrived when the value is cut', () => {
+ const cut = '{"path":"a.html","content":"<!doctype html>\\n<html'
+ expect(partialJsonField(cut, 'content')).toBe('<!doctype html>\\n<html')
+ })
+
+ it('reports nothing before the field opens', () => {
+ expect(partialJsonField('{"path":"a.htm', 'content')).toBeUndefined()
+ })
+
+ it('does not end the value on an escaped quote', () => {
+ expect(partialJsonField('{"content":"say \\"hi\\" now', 'content')).toBe(
+ 'say \\"hi\\" now'
+ )
+ })
+
+ /// The field name can occur inside an earlier value, which is why this scans
+ /// for `"name":` and a quote rather than for the name alone.
+ it('skips the name occurring inside an earlier value', () => {
+ const decoy = '{"path":"my\\"content\\".txt","content":"real'
+ expect(partialJsonField(decoy, 'content')).toBe('real')
+ })
+})
+
+describe('unescapePartialJsonString', () => {
+ it('survives a cut escape', () => {
+ expect(unescapePartialJsonString('a\\nb')).toBe('a\nb')
+ // Dangling backslash: the escape's payload has not arrived.
+ expect(unescapePartialJsonString('a\\nb\\')).toBe('a\nb')
+ // An even run is a real escaped backslash, so it stays.
+ expect(unescapePartialJsonString('a\\\\')).toBe('a\\')
+ // Partial \u escape.
+ expect(unescapePartialJsonString('hi \\u26')).toBe('hi ')
+ expect(unescapePartialJsonString('hi ☃')).toBe('hi ☃')
+ })
+})
+
+describe('partialToolInput', () => {
+ it('reads the arguments a card is built from, mid-stream', () => {
+ const raw = '{"path":"game.html","content":"<!doctype html>\\n<htm'
+ expect(partialToolInput(raw)).toEqual({
+ path: 'game.html',
+ content: '<!doctype html>\n<htm',
+ })
+ })
+
+ /// A count or an id arrives whole or not at all, so half of one would be a
+ /// lie rather than a preview.
+ it('reads only string arguments', () => {
+ expect(partialToolInput('{"query":"rust","count":1')).toEqual({
+ query: 'rust',
+ })
+ })
+
+ it('is empty before anything has arrived', () => {
+ expect(partialToolInput('{"pa')).toEqual({})
+ })
+})
diff --git a/web-app/src/lib/__tests__/streamingWrite.test.ts b/web-app/src/lib/__tests__/streamingWrite.test.ts
new file mode 100644
index 000000000..15299e4bc
--- /dev/null
+++ b/web-app/src/lib/__tests__/streamingWrite.test.ts
@@ -0,0 +1,61 @@
+import { describe, it, expect } from 'vitest'
+import {
+ writeTail,
+ STREAM_TAIL_LINES,
+ STREAM_MAX_LINE_CHARS,
+} from '../streamingWrite'
+
+describe('writeTail', () => {
+ it('keeps a short body whole', () => {
+ expect(writeTail('a\nb\nc')).toEqual({ lines: ['a', 'b', 'c'], skipped: 0 })
+ })
+
+ it('windows a long body onto its tail, counting what scrolled off', () => {
+ const body = Array.from({ length: 20 }, (_, i) => `line ${i + 1}`).join(
+ '\n'
+ )
+ const { lines, skipped } = writeTail(body)
+ expect(lines).toHaveLength(STREAM_TAIL_LINES)
+ expect(skipped).toBe(20 - STREAM_TAIL_LINES)
+ // Numbered from `skipped`, so line 9 is where the window starts.
+ expect(lines[0]).toBe(`line ${skipped + 1}`)
+ expect(lines.at(-1)).toBe('line 20')
+ })
+
+ /// Split on `\n`, not by lines: a trailing newline is the empty line the
+ /// model just opened, and dropping it makes the preview look stalled.
+ it('shows the empty line a trailing newline opened', () => {
+ expect(writeTail('a\n').lines).toEqual(['a', ''])
+ })
+
+ /// Minified content is one line that grows for the whole write, and the cost
+ /// of rendering it grows with it -- on every delta.
+ it('clamps the open line to its tail, where the new bytes land', () => {
+ const open = 'x'.repeat(STREAM_MAX_LINE_CHARS + 50) + 'END'
+ const { lines } = writeTail(`done\n${open}`)
+ expect(lines[1].startsWith('…')).toBe(true)
+ expect(lines[1].endsWith('END')).toBe(true)
+ expect([...lines[1]]).toHaveLength(STREAM_MAX_LINE_CHARS + 1)
+ })
+
+ /// A finished line keeps its head, which is where it reads from.
+ it('clamps a finished line to its head', () => {
+ const long = 'START' + 'y'.repeat(STREAM_MAX_LINE_CHARS + 50)
+ const { lines } = writeTail(`${long}\nopen`)
+ expect(lines[0].startsWith('START')).toBe(true)
+ expect(lines[0].endsWith('…')).toBe(true)
+ expect([...lines[0]]).toHaveLength(STREAM_MAX_LINE_CHARS + 1)
+ })
+
+ /// The budget is in characters, not bytes: a line of multi-byte text is no
+ /// wider on screen than the same number of ASCII ones.
+ it('counts characters, not bytes, when clamping', () => {
+ const e = '\u00e9'
+ expect(writeTail(e.repeat(STREAM_MAX_LINE_CHARS)).lines[0]).not.toContain(
+ '\u2026'
+ )
+ expect(writeTail(e.repeat(STREAM_MAX_LINE_CHARS + 1)).lines[0]).toContain(
+ '\u2026'
+ )
+ })
+})
diff --git a/web-app/src/lib/coworkTurns.ts b/web-app/src/lib/coworkTurns.ts
index 805df15d5..861928166 100644
--- a/web-app/src/lib/coworkTurns.ts
+++ b/web-app/src/lib/coworkTurns.ts
@@ -2,6 +2,7 @@
import type { UIMessage } from 'ai'
import type { CoworkTurn } from '@/types/coworkSession'
import { reasoningPartsFromText } from '@/lib/messages'
+import { partialToolInput } from '@/lib/partialJson'
/**
* Adapts the code screen's flat `CoworkTurn[]` transcript into the AI SDK
@@ -31,7 +32,11 @@ export function coworkTurnsToUIMessages(
const ensureAssistant = (index: number) => {
if (!assistant) {
- assistant = { id: `${idPrefix}-asst-${index}`, role: 'assistant', parts: [] }
+ assistant = {
+ id: `${idPrefix}-asst-${index}`,
+ role: 'assistant',
+ parts: [],
+ }
}
return assistant
}
@@ -63,15 +68,22 @@ export function coworkTurnsToUIMessages(
// tool turn -> a `tool-<name>` part on the current assistant message.
const name = turn.name ?? 'tool'
const running = turn.status === 'running'
+ // Arguments arrive as raw JSON text before the call is complete, so a
+ // running turn is read out of that fragment (`input-streaming`). A `write`
+ // is the reason: its body *is* the work, and holding the card empty until
+ // the last byte lands shows nothing for the whole write.
+ const streamed = running && turn.args == null && turn.argsLive
const part: any = {
type: `tool-${name}`,
toolCallId: turn.callId ?? `code-tool-${i}`,
- input: turn.args,
- state: running
- ? 'input-available'
- : turn.isError
- ? 'output-error'
- : 'output-available',
+ input: streamed ? partialToolInput(turn.argsLive as string) : turn.args,
+ state: streamed
+ ? 'input-streaming'
+ : running
+ ? 'input-available'
+ : turn.isError
+ ? 'output-error'
+ : 'output-available',
}
if (!running) {
diff --git a/web-app/src/lib/partialJson.ts b/web-app/src/lib/partialJson.ts
new file mode 100644
index 000000000..e0c19dfc7
--- /dev/null
+++ b/web-app/src/lib/partialJson.ts
@@ -0,0 +1,106 @@
+/**
+ * Reading a JSON object that is still streaming, and is therefore almost
+ * certainly truncated mid-value.
+ *
+ * Port of the TUI's `partial_json_field` / `unescape_partial_json_string`
+ * (`core::cli::tui`), which exist for the same reason: a real parser cannot help
+ * with a prefix like `{"path":"a.html","content":"<!doctype html>\n<html` --
+ * there is no closing quote and no closing brace. Both surfaces show a `write`
+ * as it arrives, so both need to read the body out of a fragment.
+ */
+
+/**
+ * One *string-valued* field of a streaming JSON object, still escaped.
+ *
+ * Scans for `"<field>"` followed by `:` and an opening quote, then walks the
+ * value honouring backslash escapes, stopping at the closing quote or at the
+ * end of the input -- whichever comes first.
+ */
+export function partialJsonField(
+ raw: string,
+ field: string
+): string | undefined {
+ const needle = `"${field}"`
+ let rest = raw
+ for (;;) {
+ const at = rest.indexOf(needle)
+ if (at === -1) return undefined
+ const after = rest.slice(at + needle.length)
+ const afterColon = after.trimStart()
+ // The name can also appear inside an earlier string value; if what follows
+ // is not `: "`, keep looking.
+ if (!afterColon.startsWith(':')) {
+ rest = after
+ continue
+ }
+ const opened = afterColon.slice(1).trimStart()
+ if (!opened.startsWith('"')) {
+ rest = after
+ continue
+ }
+ const value = opened.slice(1)
+ let escaped = false
+ for (let i = 0; i < value.length; i++) {
+ const c = value[i]
+ if (escaped) escaped = false
+ else if (c === '\\') escaped = true
+ else if (c === '"') return value.slice(0, i)
+ }
+ // No closing quote: the value is still streaming, so take all of it.
+ return value
+ }
+}
+
+/**
+ * Turn a raw JSON string body into display text, tolerating a truncated tail.
+ *
+ * The stream can cut anywhere, including the middle of an escape sequence, so a
+ * dangling `\` and a partial `\uXXXX` are dropped before parsing. Falls back to
+ * the raw text if it still will not parse: a preview is never worth failing a
+ * render over.
+ */
+export function unescapePartialJsonString(raw: string): string {
+ let s = raw
+ // Partial `\uXXXX`: 0-3 hex digits have arrived so far.
+ const at = s.lastIndexOf('\\u')
+ if (at !== -1) {
+ const tail = s.slice(at + 2)
+ if (tail.length < 4 && /^[0-9a-fA-F]*$/.test(tail)) s = s.slice(0, at)
+ }
+ // Dangling escape: an odd number of trailing backslashes means the last one
+ // is opening an escape whose payload has not arrived.
+ const slashes = /\\*$/.exec(s)?.[0].length ?? 0
+ if (slashes % 2 === 1) s = s.slice(0, -1)
+ try {
+ return JSON.parse(`"${s}"`) as string
+ } catch {
+ return s
+ }
+}
+
+/**
+ * The string arguments a tool card can be built from, read out of a buffer that
+ * is still arriving.
+ *
+ * Only string fields: a number or an id arrives whole or not at all, and half a
+ * number is a lie rather than a preview. A field that has not started streaming
+ * is absent, which the card renders as an empty bar.
+ */
+const PREVIEW_FIELDS = [
+ 'path',
+ 'content',
+ 'command',
+ 'query',
+ 'url',
+ 'pattern',
+ 'name',
+] as const
+
+export function partialToolInput(raw: string): Record<string, string> {
+ const out: Record<string, string> = {}
+ for (const field of PREVIEW_FIELDS) {
+ const value = partialJsonField(raw, field)
+ if (value !== undefined) out[field] = unescapePartialJsonString(value)
+ }
+ return out
+}
diff --git a/web-app/src/lib/streamingWrite.ts b/web-app/src/lib/streamingWrite.ts
new file mode 100644
index 000000000..3376529f8
--- /dev/null
+++ b/web-app/src/lib/streamingWrite.ts
@@ -0,0 +1,62 @@
+/**
+ * The live preview of a `write` whose body is still arriving.
+ *
+ * Port of the TUI's streaming-write window (`starting_call_lines` /
+ * `refresh_preview` in `core::cli::tui`). A file write is the one tool call
+ * whose arguments are worth watching: they are the work, and a large one takes
+ * long enough that a spinner says nothing.
+ */
+
+/** Trailing lines kept on screen. Enough to see the write progressing without
+ * the preview owning the transcript. */
+export const STREAM_TAIL_LINES = 12
+
+/**
+ * Longest line kept. Minified content (a bundle, a JSON blob) is one line that
+ * grows for the whole write, and the cost of rendering it grows with it -- on
+ * every delta. Wide enough that nothing a user could have read is dropped.
+ */
+export const STREAM_MAX_LINE_CHARS = 300
+
+/** Marks a line the clamp cut. */
+const ELLIPSIS = '…'
+
+export type WritePreview = {
+ /** The window, oldest first. */
+ lines: string[]
+ /** Lines that scrolled off above it, so the gutter can number the rest. */
+ skipped: number
+}
+
+/**
+ * The last [`STREAM_TAIL_LINES`] lines of `body`.
+ *
+ * Split on `\n` rather than by lines so a trailing newline shows as the empty
+ * line the model just opened -- that is where the next content lands, and
+ * dropping it makes the preview look stalled.
+ */
+export function writeTail(body: string): WritePreview {
+ const all = body.split('\n')
+ const lines = all.slice(Math.max(0, all.length - STREAM_TAIL_LINES))
+ // The last line is the one still being written; the rest are finished.
+ const open = lines.length - 1
+ return {
+ lines: lines.map((line, i) => clampPreviewLine(line, i === open)),
+ skipped: all.length - lines.length,
+ }
+}
+
+/**
+ * Clamp one preview line, marking it where it was cut.
+ *
+ * `open` marks the line still being written, which keeps its *tail*: that is
+ * where new bytes land, so it is the end that shows the write progressing. A
+ * finished line keeps its head, where it reads from.
+ */
+function clampPreviewLine(line: string, open: boolean): string {
+ const chars = [...line]
+ if (chars.length <= STREAM_MAX_LINE_CHARS) return line
+ return open
+ ? ELLIPSIS + chars.slice(chars.length - STREAM_MAX_LINE_CHARS).join('')
+ : chars.slice(0, STREAM_MAX_LINE_CHARS).join('') + ELLIPSIS
+}
diff --git a/web-app/src/lib/toolPresentation.ts b/web-app/src/lib/toolPresentation.ts
index 7595e51d5..af923c295 100644
--- a/web-app/src/lib/toolPresentation.ts
+++ b/web-app/src/lib/toolPresentation.ts
@@ -19,8 +19,18 @@ export type ToolCallBar =
* The workspace tools. `target` is whatever the call is really about -- a path
* for read/ls, the pattern for find/grep, the entry name for memory/skill --
* with `detail` carrying the secondary argument when there is one.
+ *
+ * `body` is a `write`'s file content. It is the one argument worth showing
+ * while it streams: it is the work itself, and a large write takes long
+ * enough that a spinner says nothing about it.
*/
- | { variant: 'workspace'; tool: string; target: string; detail?: string }
+ | {
+ variant: 'workspace'
+ tool: string
+ target: string
+ detail?: string
+ body?: string
+ }
/**
* Owned by the RAG extension (extensions/rag-extension/src/tools.ts) and not
@@ -48,7 +58,11 @@ export function describeNativeToolCall(
typeof value === 'number' ? value : undefined
if (origin.kind === 'web-search') {
- return { variant: 'search', query: asString(args.query), count: asCount(args.count) }
+ return {
+ variant: 'search',
+ query: asString(args.query),
+ count: asCount(args.count),
+ }
}
if (origin.kind === 'web-fetch') {
return { variant: 'address', url: asString(args.url) }
@@ -58,7 +72,9 @@ export function describeNativeToolCall(
variant: 'documents',
query: asString(args.query),
count: asCount(args.top_k),
- fileCount: Array.isArray(args.file_ids) ? args.file_ids.length : undefined,
+ fileCount: Array.isArray(args.file_ids)
+ ? args.file_ids.length
+ : undefined,
}
}
if (origin.kind === 'agent') {
@@ -85,6 +101,7 @@ export function describeNativeToolCall(
variant: 'workspace',
tool: toolName,
target: asString(args.path) || asString(args.name),
+ body: toolName === 'write' ? asString(args.content) : undefined,
}
}
return undefined
@@ -168,7 +185,7 @@ export function parseWebFetchOutput(output: unknown): WebFetchPage | undefined {
typeof output === 'string'
? output
: typeof (output as { content?: unknown })?.content === 'string'
- ? ((output as { content: string }).content)
+ ? (output as { content: string }).content
: undefined
if (text === undefined) return undefined
diff --git a/web-app/src/routes/cowork.tsx b/web-app/src/routes/cowork.tsx
index db3ad4781..676fa740b 100644
--- a/web-app/src/routes/cowork.tsx
+++ b/web-app/src/routes/cowork.tsx
@@ -378,9 +378,24 @@ function CoworkPage() {
},
onToolStart: (callId, name) =>
pushLive([
- { role: 'tool', content: '', callId, name, status: 'running' },
+ {
+ role: 'tool',
+ content: '',
+ callId,
+ name,
+ status: 'running',
+ argsLive: '',
+ },
]),
- onToolArgsDelta: () => {},
+ // Raw JSON, appended as it arrives. The transcript reads a `write`'s
+ // destination and body straight out of this fragment, so the card fills
+ // in as the model types rather than waiting for the closing brace.
+ onToolArgsDelta: (callId, delta) => {
+ const row = liveTurnsRef.current.find((turn) => turn.callId === callId)
+ if (!row) return
+ row.argsLive = (row.argsLive ?? '') + delta
+ setLiveTurns([...liveTurnsRef.current])
+ },
onToolCall: (call) => {
const row = liveTurnsRef.current.find(
(turn) => turn.callId === call.toolCallId