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 an edit's replacements, and close the task card on dispatch

Akarshan Biswasfcace4d957b2
diff --git a/web-app/src/containers/message/AgentToolWidget.tsx b/web-app/src/containers/message/AgentToolWidget.tsx
index 9705d7243..e1cb1b647 100644
--- a/web-app/src/containers/message/AgentToolWidget.tsx
+++ b/web-app/src/containers/message/AgentToolWidget.tsx
@@ -18,7 +18,7 @@ import {
type ToolCallBar,
} from '@/lib/toolPresentation'
import { cn } from '@/lib/utils'
-import { writeTail } from '@/lib/streamingWrite'
+import { editPreview, writeTail } from '@/lib/streamingArgs'
import { useToolCallRuntime } from '@/hooks/useToolCallRuntime'
import { Caret, ToolBar } from './ToolBar'
@@ -99,6 +99,37 @@ const WritePreviewBlock = memo(({ body }: { body: string }) => {
WritePreviewBlock.displayName = 'WritePreviewBlock'
+/**
+ * An `edit`'s replacements as they arrive: what is going out, what is coming
+ * in. Superseded by the real diff (`DiffBlock`) the moment the call lands --
+ * that one is computed against the file and knows what actually changed, which
+ * the arguments alone cannot say.
+ */
+const EditPreviewBlock = memo(
+ ({ edits }: { edits: { old_string: string; new_string?: string }[] }) => {
+ const { rows } = useMemo(() => editPreview(edits), [edits])
+
+ return (
+ <div className="mt-1.5 max-h-56 overflow-hidden rounded-md border bg-card/40 py-1 font-mono text-xs">
+ {rows.map((row, i) => (
+ <div
+ key={i}
+ className={cn(
+ 'whitespace-pre-wrap wrap-break-word px-2',
+ diffLineTone(row.sign)
+ )}
+ >
+ {row.sign}
+ {row.text || ' '}
+ </div>
+ ))}
+ </div>
+ )
+ }
+)
+
+EditPreviewBlock.displayName = 'EditPreviewBlock'
+
export type TerminalWidgetProps = {
bar: Extract<ToolCallBar, { variant: 'terminal' }>
state: ToolUIPart['state']
@@ -286,10 +317,12 @@ export const AgentToolWidget = memo(
</div>
)}
- {/* The body says more than "Writing…" ever could, so it replaces the
- throbber the moment the first line arrives. */}
+ {/* The arguments say more than "Writing…" ever could, so they replace
+ the throbber the moment the first line arrives. */}
{running && !errorText && bar.body ? (
<WritePreviewBlock body={bar.body} />
+ ) : running && !errorText && bar.edits ? (
+ <EditPreviewBlock edits={bar.edits} />
) : (
running &&
!errorText && (
diff --git a/web-app/src/containers/message/SubagentToolWidget.tsx b/web-app/src/containers/message/SubagentToolWidget.tsx
index 6a85c6239..40df43814 100644
--- a/web-app/src/containers/message/SubagentToolWidget.tsx
+++ b/web-app/src/containers/message/SubagentToolWidget.tsx
@@ -1,35 +1,27 @@
import { memo } from 'react'
-import type { ToolUIPart } from 'ai'
import { IconSparkles } from '@tabler/icons-react'
import { Shimmer } from '@/components/ai-elements/shimmer'
import { useTranslation } from '@/i18n/react-i18next-compat'
-import { isToolRunning, type ToolCallBar } from '@/lib/toolPresentation'
+import { type ToolCallBar } from '@/lib/toolPresentation'
export type SubagentToolWidgetProps = {
bar: Extract<ToolCallBar, { variant: 'subagent' }>
- state: ToolUIPart['state']
- errorText?: string
}
/**
- * A `task` call: which subagent was launched, and the brief it was launched
- * with.
+ * A `task` being dispatched: which subagent, and the brief it is being launched
+ * with, as both stream in.
*
- * Deliberately says nothing about how the child is getting on. `task` returns
- * as soon as the child starts, so this card settles within a second of being
- * drawn, while the run it started goes on for minutes -- and the tasks panel
- * follows that for its whole life. A card that also tried to report progress
- * would be reporting a run it stopped watching.
- *
- * The result text is not shown either: it is a sentence addressed to the model
- * ("keep working rather than waiting for it"), and the file it names is only
- * useful to the model. A failed dispatch *is* shown, because a rejected call
- * is the one thing here the user may need to act on.
+ * Only shown while the call is in flight (`ToolCallCard` drops it once the call
+ * settles). `task` returns the moment the child starts, so a settled card marks
+ * a launch that is over, while the run it began goes on for minutes with the
+ * tasks panel following it -- a card left open here would be a second, frozen
+ * account of a run it had stopped watching. What the dispatch returned, a
+ * refusal included, stays one click away inside the collapsed card.
*/
export const SubagentToolWidget = memo(
- ({ bar, state, errorText }: SubagentToolWidgetProps) => {
+ ({ bar }: SubagentToolWidgetProps) => {
const { t } = useTranslation()
- const running = isToolRunning(state)
return (
<div className="space-y-1.5">
@@ -50,19 +42,9 @@ export const SubagentToolWidget = memo(
</p>
)}
- {errorText ? (
- <div className="rounded-md bg-destructive/10 px-2 py-1.5 text-sm text-destructive">
- {errorText}
- </div>
- ) : running ? (
- <div className="px-2 text-sm">
- <Shimmer duration={1}>{t('tools:toolCall.dispatching')}</Shimmer>
- </div>
- ) : (
- <p className="px-2 text-sm text-muted-foreground/70">
- {t('tools:toolCall.subagentRunning')}
- </p>
- )}
+ <div className="px-2 text-sm">
+ <Shimmer duration={1}>{t('tools:toolCall.dispatching')}</Shimmer>
+ </div>
</div>
)
}
diff --git a/web-app/src/containers/message/ToolCallCard.tsx b/web-app/src/containers/message/ToolCallCard.tsx
index db712ad68..6c0d3127d 100644
--- a/web-app/src/containers/message/ToolCallCard.tsx
+++ b/web-app/src/containers/message/ToolCallCard.tsx
@@ -11,7 +11,7 @@ import { ToolProgressRow } from '@/components/ai-elements/tool-runtime'
import { useToolOrigin } from '@/hooks/useToolOrigin'
import { useTranslation } from '@/i18n/react-i18next-compat'
import { completedToolLabel } from '@/lib/agentActivity'
-import { describeNativeToolCall } from '@/lib/toolPresentation'
+import { describeNativeToolCall, isToolRunning } from '@/lib/toolPresentation'
import { isToolPart, type MessagePartLike } from './types'
import { RagToolWidget } from './RagToolWidget'
import { WebToolWidget } from './WebToolWidget'
@@ -61,10 +61,23 @@ export const ToolCallCard = memo(
// `skill_read` reads as a bare tool name otherwise; the label names the
// skill actually being loaded, which is the only interesting part of it.
+ // A `task` names its subagent for a stronger reason: its widget goes away
+ // once the child is launched, so without this a fan-out collapses to three
+ // identical rows.
const title =
toolName === 'skill_read'
? completedToolLabel(toolName, part.input, part.state)
- : toolName
+ : bar?.variant === 'subagent' && bar.name
+ ? `${toolName}: ${bar.name}`
+ : toolName
+
+ // A `task` widget describes a launch, and the launch is over the moment the
+ // call settles: the child then runs for minutes with the tasks panel
+ // following it, so leaving the card open would park a static "Running in
+ // the background" under every dispatch. Every other widget reports its own
+ // call, which is still worth reading afterwards.
+ const showBar =
+ bar && (bar.variant !== 'subagent' || isToolRunning(part.state))
return (
<Tool
@@ -83,7 +96,7 @@ export const ToolCallCard = memo(
input={bar ? undefined : part.input}
/>
<ToolProgressRow toolCallId={part.toolCallId} />
- {bar && (
+ {showBar && (
<div className="mt-2">
{bar.variant === 'documents' ? (
<RagToolWidget
@@ -102,11 +115,7 @@ export const ToolCallCard = memo(
errorText={errorText}
/>
) : bar.variant === 'subagent' ? (
- <SubagentToolWidget
- bar={bar}
- state={part.state}
- errorText={errorText}
- />
+ <SubagentToolWidget bar={bar} />
) : bar.variant === 'workspace' ? (
<AgentToolWidget
bar={bar}
@@ -128,8 +137,10 @@ export const ToolCallCard = memo(
<ToolContent title={title}>
{Boolean(part.input) && <ToolInput input={part.input} />}
<ToolApprovalActions />
- {/* The widget already presents the result for native tools. */}
- {!bar &&
+ {/* The widget already presents the result for native tools -- but a
+ `task` has none once it settles, so its outcome (a refusal, most
+ of all) has to stay reachable here. */}
+ {!showBar &&
(isError ? (
<ToolOutput
output={undefined}
diff --git a/web-app/src/containers/message/__tests__/AgentToolWidget.test.tsx b/web-app/src/containers/message/__tests__/AgentToolWidget.test.tsx
index 76427749b..5d87c5cad 100644
--- a/web-app/src/containers/message/__tests__/AgentToolWidget.test.tsx
+++ b/web-app/src/containers/message/__tests__/AgentToolWidget.test.tsx
@@ -58,6 +58,26 @@ describe('AgentToolWidget', () => {
expect(screen.getByText('2')).toBeInTheDocument()
})
+ /// Same reasoning as the write body: for an `edit` the arguments are the
+ /// work, so they replace the throbber rather than sitting behind it.
+ it('previews an edit as a diff while it streams', () => {
+ render(
+ <AgentToolWidget
+ bar={{
+ variant: 'workspace',
+ tool: 'edit',
+ target: 'a.ts',
+ edits: [{ old_string: 'before', new_string: 'after' }],
+ }}
+ state="input-streaming"
+ toolCallId="tc1"
+ />
+ )
+ expect(screen.queryByText('tools:toolCall.editing')).not.toBeInTheDocument()
+ expect(screen.getByText('-before')).toBeInTheDocument()
+ expect(screen.getByText('+after')).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', () => {
diff --git a/web-app/src/containers/message/__tests__/SubagentToolWidget.test.tsx b/web-app/src/containers/message/__tests__/SubagentToolWidget.test.tsx
index c9cc8e10b..3fc69f117 100644
--- a/web-app/src/containers/message/__tests__/SubagentToolWidget.test.tsx
+++ b/web-app/src/containers/message/__tests__/SubagentToolWidget.test.tsx
@@ -16,46 +16,16 @@ const bar = {
describe('SubagentToolWidget', () => {
it('names the subagent and its brief while the call streams', () => {
- render(<SubagentToolWidget bar={bar} state="input-streaming" />)
+ render(<SubagentToolWidget bar={bar} />)
expect(screen.getByText('researcher')).toBeInTheDocument()
expect(screen.getByText(bar.task)).toBeInTheDocument()
expect(screen.getByText('tools:toolCall.dispatching')).toBeInTheDocument()
})
it('prompts for the subagent before the name arrives', () => {
- render(
- <SubagentToolWidget
- bar={{ variant: 'subagent', name: '', task: '' }}
- state="input-streaming"
- />
- )
+ render(<SubagentToolWidget bar={{ variant: 'subagent', name: '', task: '' }} />)
expect(
screen.getByText('tools:toolCall.subagentPlaceholder')
).toBeInTheDocument()
})
-
- /// `task` returns as soon as the child starts, so a settled card means
- /// "dispatched", not "finished" -- the tasks panel is what follows the run.
- it('reads as running once the call settles', () => {
- render(<SubagentToolWidget bar={bar} state="output-available" />)
- expect(
- screen.getByText('tools:toolCall.subagentRunning')
- ).toBeInTheDocument()
- })
-
- /// A rejected dispatch is the one thing on this card the user may need to
- /// act on, so it is not left folded away in the raw output.
- it('shows a refused dispatch', () => {
- render(
- <SubagentToolWidget
- bar={bar}
- state="output-error"
- errorText="unknown subagent 'researcher': no saved definition"
- />
- )
- expect(screen.getByText(/no saved definition/)).toBeInTheDocument()
- expect(
- screen.queryByText('tools:toolCall.subagentRunning')
- ).not.toBeInTheDocument()
- })
})
diff --git a/web-app/src/containers/message/__tests__/ToolCallCard.test.tsx b/web-app/src/containers/message/__tests__/ToolCallCard.test.tsx
index cde9ac795..7369c0214 100644
--- a/web-app/src/containers/message/__tests__/ToolCallCard.test.tsx
+++ b/web-app/src/containers/message/__tests__/ToolCallCard.test.tsx
@@ -74,4 +74,36 @@ describe('ToolCallCard', () => {
)
expect(screen.getByText('title: Bug')).toBeInTheDocument()
})
+
+ /// The launch is over the moment the call settles, and the tasks panel follows
+ /// the run from there -- so the card collapses to its header rather than
+ /// parking a frozen account of a run it stopped watching.
+ it('shows a task widget only while the dispatch is in flight', () => {
+ origin.mockReturnValue({ kind: 'subagent' })
+ const part = {
+ type: 'tool-task',
+ toolCallId: 'tc1',
+ input: { subagent_name: 'researcher', description: 'Research MCP' },
+ }
+ const { rerender } = render(
+ <ToolCallCard
+ part={{ ...part, state: 'input-streaming' }}
+ messageId="m1"
+ />
+ )
+ expect(screen.getByText('researcher')).toBeInTheDocument()
+
+ rerender(
+ <ToolCallCard
+ part={{ ...part, state: 'output-available', output: 'started' }}
+ messageId="m1"
+ />
+ )
+ expect(screen.queryByText('Research MCP')).not.toBeInTheDocument()
+ // The subagent stays named on the header, so a fan-out does not collapse
+ // into three identical rows.
+ expect(
+ screen.getByText('tools:toolCall.used:task: researcher')
+ ).toBeInTheDocument()
+ })
})
diff --git a/web-app/src/lib/__tests__/partialJson.test.ts b/web-app/src/lib/__tests__/partialJson.test.ts
index c8a79632a..0b313a71a 100644
--- a/web-app/src/lib/__tests__/partialJson.test.ts
+++ b/web-app/src/lib/__tests__/partialJson.test.ts
@@ -1,6 +1,7 @@
import { describe, it, expect } from 'vitest'
import {
partialJsonField,
+ partialJsonStrings,
partialToolInput,
unescapePartialJsonString,
} from '../partialJson'
@@ -37,6 +38,25 @@ describe('partialJsonField', () => {
})
})
+/// `edit` carries an array of `{old_string, new_string}`, so its arguments are
+/// only readable as repeated fields.
+describe('partialJsonStrings', () => {
+ it('reads every occurrence in order', () => {
+ const raw = '{"edits":[{"old_string":"a","new_string":"b"},{"old_string":"c"'
+ expect(partialJsonStrings(raw, 'old_string')).toEqual(['a', 'c'])
+ expect(partialJsonStrings(raw, 'new_string')).toEqual(['b'])
+ })
+
+ it('takes the still-open last value, and stops there', () => {
+ const raw = '{"edits":[{"old_string":"a","new_string":"partial'
+ expect(partialJsonStrings(raw, 'new_string')).toEqual(['partial'])
+ })
+
+ it('is empty when the field never appears', () => {
+ expect(partialJsonStrings('{"path":"a"}', 'old_string')).toEqual([])
+ })
+})
+
describe('unescapePartialJsonString', () => {
it('survives a cut escape', () => {
expect(unescapePartialJsonString('a\\nb')).toBe('a\nb')
@@ -70,4 +90,22 @@ describe('partialToolInput', () => {
it('is empty before anything has arrived', () => {
expect(partialToolInput('{"pa')).toEqual({})
})
+
+ /// The result is shaped like the real arguments, so a streaming call and a
+ /// settled one read the same downstream.
+ it('rebuilds the edit pairs, keeping the one still streaming', () => {
+ const raw =
+ '{"path":"a.ts","edits":[{"old_string":"one","new_string":"1"},{"old_string":"two"'
+ expect(partialToolInput(raw)).toEqual({
+ path: 'a.ts',
+ edits: [
+ { old_string: 'one', new_string: '1' },
+ { old_string: 'two' },
+ ],
+ })
+ })
+
+ it('has no edits before the first pair opens', () => {
+ expect(partialToolInput('{"path":"a.ts","edi')).toEqual({ path: 'a.ts' })
+ })
})
diff --git a/web-app/src/lib/__tests__/streamingWrite.test.ts b/web-app/src/lib/__tests__/streamingArgs.test.ts
similarity index 59%
rename from web-app/src/lib/__tests__/streamingWrite.test.ts
rename to web-app/src/lib/__tests__/streamingArgs.test.ts
index 15299e4bc..beb5c751c 100644
--- a/web-app/src/lib/__tests__/streamingWrite.test.ts
+++ b/web-app/src/lib/__tests__/streamingArgs.test.ts
@@ -1,9 +1,10 @@
import { describe, it, expect } from 'vitest'
import {
+ editPreview,
writeTail,
STREAM_TAIL_LINES,
STREAM_MAX_LINE_CHARS,
-} from '../streamingWrite'
+} from '../streamingArgs'
describe('writeTail', () => {
it('keeps a short body whole', () => {
@@ -59,3 +60,50 @@ describe('writeTail', () => {
)
})
})
+
+describe('editPreview', () => {
+ it('reads as a diff: what goes out, then what comes in', () => {
+ const { rows, skipped } = editPreview([
+ { old_string: 'a\nb', new_string: 'A' },
+ ])
+ expect(rows).toEqual([
+ { sign: '-', text: 'a' },
+ { sign: '-', text: 'b' },
+ { sign: '+', text: 'A' },
+ ])
+ expect(skipped).toBe(0)
+ })
+
+ /// The pair with no replacement yet is the one being written, which is
+ /// exactly the one worth watching.
+ it('keeps a pair whose replacement has not arrived', () => {
+ const { rows } = editPreview([
+ { old_string: 'one', new_string: '1' },
+ { old_string: 'two' },
+ ])
+ expect(rows.map((r) => r.sign)).toEqual(['-', '+', '-'])
+ expect(rows.at(-1)).toEqual({ sign: '-', text: 'two' })
+ })
+
+ it('windows onto the tail, where the writing is', () => {
+ const edits = Array.from({ length: 10 }, (_, i) => ({
+ old_string: `old ${i}`,
+ new_string: `new ${i}`,
+ }))
+ const { rows, skipped } = editPreview(edits)
+ expect(rows).toHaveLength(STREAM_TAIL_LINES)
+ expect(skipped).toBe(20 - STREAM_TAIL_LINES)
+ expect(rows.at(-1)).toEqual({ sign: '+', text: 'new 9' })
+ })
+
+ it('clamps a long replacement the same way a write body is clamped', () => {
+ const { rows } = editPreview([
+ { old_string: 'x', new_string: 'y'.repeat(STREAM_MAX_LINE_CHARS + 5) },
+ ])
+ expect([...rows[1].text]).toHaveLength(STREAM_MAX_LINE_CHARS + 1)
+ })
+
+ it('has nothing to show before the first pair', () => {
+ expect(editPreview([])).toEqual({ rows: [], skipped: 0 })
+ })
+})
diff --git a/web-app/src/lib/partialJson.ts b/web-app/src/lib/partialJson.ts
index 18688e453..235738a61 100644
--- a/web-app/src/lib/partialJson.ts
+++ b/web-app/src/lib/partialJson.ts
@@ -20,11 +20,27 @@ export function partialJsonField(
raw: string,
field: string
): string | undefined {
+ for (const value of scanJsonStrings(raw, field)) return value
+ return undefined
+}
+
+/**
+ * Every occurrence of a string-valued field, in order.
+ *
+ * `edit` carries an array of `{old_string, new_string}` objects, so its
+ * arguments are only readable as repeated fields -- there is no single value to
+ * pull out the way a `write`'s body is.
+ */
+export function partialJsonStrings(raw: string, field: string): string[] {
+ return [...scanJsonStrings(raw, field)]
+}
+
+function* scanJsonStrings(raw: string, field: string): Generator<string> {
const needle = `"${field}"`
let rest = raw
for (;;) {
const at = rest.indexOf(needle)
- if (at === -1) return undefined
+ if (at === -1) return
const after = rest.slice(at + needle.length)
const afterColon = after.trimStart()
// The name can also appear inside an earlier string value; if what follows
@@ -40,14 +56,24 @@ export function partialJsonField(
}
const value = opened.slice(1)
let escaped = false
+ let end = -1
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)
+ else if (c === '"') {
+ end = i
+ break
+ }
+ }
+ if (end === -1) {
+ // No closing quote: the value is still streaming, so it is all of the
+ // rest -- and necessarily the last one.
+ yield value
+ return
}
- // No closing quote: the value is still streaming, so take all of it.
- return value
+ yield value.slice(0, end)
+ rest = value.slice(end + 1)
}
}
@@ -79,12 +105,16 @@ export function unescapePartialJsonString(raw: string): string {
}
/**
- * The string arguments a tool card can be built from, read out of a buffer that
- * is still arriving.
+ * The 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.
+ * String fields only, plus `edit`'s array of them: 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.
+ *
+ * The result is shaped like the real arguments, not like a bag of fragments, so
+ * everything downstream reads a streaming call and a settled one the same way.
*/
const PREVIEW_FIELDS = [
'path',
@@ -98,11 +128,35 @@ const PREVIEW_FIELDS = [
'description',
] as const
-export function partialToolInput(raw: string): Record<string, string> {
- const out: Record<string, string> = {}
+export type PartialEdit = { old_string: string; new_string?: string }
+
+export function partialToolInput(raw: string): Record<string, unknown> {
+ const out: Record<string, unknown> = {}
for (const field of PREVIEW_FIELDS) {
const value = partialJsonField(raw, field)
if (value !== undefined) out[field] = unescapePartialJsonString(value)
}
+ const edits = partialEdits(raw)
+ if (edits.length > 0) out.edits = edits
return out
}
+
+/**
+ * `edit`'s replacement pairs, as far as they have arrived.
+ *
+ * The two fields are emitted in order within each array element, so the n-th
+ * `old_string` belongs with the n-th `new_string`; a trailing `old_string` with
+ * no partner is the pair currently streaming, which is exactly the one worth
+ * watching.
+ */
+function partialEdits(raw: string): PartialEdit[] {
+ const olds = partialJsonStrings(raw, 'old_string')
+ const news = partialJsonStrings(raw, 'new_string')
+ return olds.map((old, i) => {
+ const pair: PartialEdit = { old_string: unescapePartialJsonString(old) }
+ if (i < news.length) {
+ pair.new_string = unescapePartialJsonString(news[i])
+ }
+ return pair
+ })
+}
diff --git a/web-app/src/lib/streamingWrite.ts b/web-app/src/lib/streamingArgs.ts
similarity index 50%
rename from web-app/src/lib/streamingWrite.ts
rename to web-app/src/lib/streamingArgs.ts
index 3376529f8..a4226125e 100644
--- a/web-app/src/lib/streamingWrite.ts
+++ b/web-app/src/lib/streamingArgs.ts
@@ -1,10 +1,10 @@
/**
- * The live preview of a `write` whose body is still arriving.
+ * Live previews of a file-mutating call whose arguments are 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.
+ * The `write` window is a port of the TUI's (`starting_call_lines` /
+ * `refresh_preview` in `core::cli::tui`). `edit` gets the same treatment for
+ * the same reason: for both of them the arguments *are* the work, and a large
+ * one takes long enough that a spinner says nothing about it.
*/
/** Trailing lines kept on screen. Enough to see the write progressing without
@@ -46,6 +46,49 @@ export function writeTail(body: string): WritePreview {
}
}
+/** One replacement line, as the sign a diff would give it. */
+export type EditRow = { sign: '-' | '+'; text: string }
+
+export type EditPreview = {
+ rows: EditRow[]
+ /** Rows that scrolled off above the window. */
+ skipped: number
+}
+
+/**
+ * An `edit`'s replacement pairs as a diff, while they are still arriving.
+ *
+ * Deliberately not the diff that lands when the call finishes: that one is
+ * computed against the file by `render_edit_diff` in Rust and knows which lines
+ * actually changed and what surrounds them. This has only the arguments, so it
+ * shows what is being replaced by what -- every line of `old_string` as a
+ * removal, every line of `new_string` as an addition. It is superseded the
+ * moment the real diff arrives.
+ *
+ * Windowed onto the tail for the same reason the write preview is: the newest
+ * rows are the ones being written.
+ */
+export function editPreview(
+ edits: { old_string: string; new_string?: string }[]
+): EditPreview {
+ const all: EditRow[] = []
+ for (const edit of edits) {
+ for (const text of edit.old_string.split('\n')) all.push({ sign: '-', text })
+ if (edit.new_string === undefined) continue
+ for (const text of edit.new_string.split('\n')) all.push({ sign: '+', text })
+ }
+ const rows = all.slice(Math.max(0, all.length - STREAM_TAIL_LINES))
+ // The last row is the one still being written.
+ const open = rows.length - 1
+ return {
+ rows: rows.map((row, i) => ({
+ ...row,
+ text: clampPreviewLine(row.text, i === open),
+ })),
+ skipped: all.length - rows.length,
+ }
+}
+
/**
* Clamp one preview line, marking it where it was cut.
*
diff --git a/web-app/src/lib/toolPresentation.ts b/web-app/src/lib/toolPresentation.ts
index d95c12210..01f423bff 100644
--- a/web-app/src/lib/toolPresentation.ts
+++ b/web-app/src/lib/toolPresentation.ts
@@ -20,9 +20,10 @@ export type ToolCallBar =
* 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.
+ * `body` (a `write`'s file content) and `edits` (an `edit`'s replacement
+ * pairs) are the arguments worth showing while they stream: for those two
+ * tools the arguments are the work itself, and a large one takes long enough
+ * that a spinner says nothing about it.
*/
| {
variant: 'workspace'
@@ -30,6 +31,7 @@ export type ToolCallBar =
target: string
detail?: string
body?: string
+ edits?: { old_string: string; new_string?: string }[]
}
/**
* `task`. The card answers "which subagent, and what did it just get asked
@@ -48,6 +50,27 @@ export const RAG_RETRIEVE_TOOL = 'retrieve'
const asString = (value: unknown): string =>
typeof value === 'string' ? value : ''
+/** `edit`'s replacement pairs, from settled arguments or a streaming fragment
+ * -- both carry the tool's own shape. A pair whose `new_string` has not arrived
+ * is the one being written, and is kept. */
+const asEdits = (
+ value: unknown
+): { old_string: string; new_string?: string }[] | undefined => {
+ if (!Array.isArray(value)) return undefined
+ const edits = value.flatMap((entry) => {
+ const old = (entry as { old_string?: unknown })?.old_string
+ if (typeof old !== 'string') return []
+ const next = (entry as { new_string?: unknown })?.new_string
+ return [
+ {
+ old_string: old,
+ new_string: typeof next === 'string' ? next : undefined,
+ },
+ ]
+ })
+ return edits.length > 0 ? edits : undefined
+}
+
/**
* Build the bar for a native tool call from its arguments. Arguments stream in,
* so a missing or partial value is normal and renders as an empty/partial bar
@@ -115,6 +138,7 @@ export function describeNativeToolCall(
tool: toolName,
target: asString(args.path) || asString(args.name),
body: toolName === 'write' ? asString(args.content) : undefined,
+ edits: toolName === 'edit' ? asEdits(args.edits) : undefined,
}
}
return undefined
diff --git a/web-app/src/locales/en/tools.json b/web-app/src/locales/en/tools.json
index e801699d7..c18200f37 100644
--- a/web-app/src/locales/en/tools.json
+++ b/web-app/src/locales/en/tools.json
@@ -40,7 +40,6 @@
"originSubagent": "Subagent",
"subagentPlaceholder": "subagent",
"dispatching": "Dispatching...",
- "subagentRunning": "Running in the background",
"subagentBrief": "Brief",
"viewRaw": "Raw",
"viewTable": "Table",