Skip to content

Node-based terminal manager for AI coding agents — tmux-backed terminals and parallel agent sessions as draggable nodes on an infinite pan/zoom canvas. macOS, Linux, and a browser Server Edition.

feat(chat): Edit/Write calls show an in-thread diff

review55f0f807a9b2
diff --git a/src/core/chat-tool-body.ts b/src/core/chat-tool-body.ts
index 27dc45456..4abe7f20d 100644
--- a/src/core/chat-tool-body.ts
+++ b/src/core/chat-tool-body.ts
@@ -17,7 +17,9 @@ export const TOOL_BODY_TRUNCATED = '\n\n… (truncated)'
const FENCE = /^\s*```/
-function capBody(s: string): string {
+/** Caps a long text at `TOOL_BODY_CAP`, then appends `TOOL_BODY_TRUNCATED` (a tool body, and each
+ * side of an Edit/Write diff in the chat parse). */
+export function capBody(s: string): string {
if (s.length <= TOOL_BODY_CAP) return s
let end = TOOL_BODY_CAP
// Do not leave half a surrogate pair (an emoji) dangling at the cut.
diff --git a/src/core/transcript-reader.test.ts b/src/core/transcript-reader.test.ts
index 445fe0328..bbd2f546b 100644
--- a/src/core/transcript-reader.test.ts
+++ b/src/core/transcript-reader.test.ts
@@ -120,6 +120,7 @@ import {
readChatWindow,
SYSTEM_RESULT_MAX
} from './transcript-reader'
+import { TOOL_BODY_CAP, TOOL_BODY_TRUNCATED } from './chat-tool-body'
const jl = (o: object): string => JSON.stringify(o) + '\n'
const said = (role: 'user' | 'assistant', text: string): string =>
@@ -518,6 +519,90 @@ describe('image parts (opt-in `rich`)', () => {
})
})
+describe('Edit / Write diffs (opt-in `rich`)', () => {
+ // The measured inputs (CLI 2.1.314): Edit → {file_path, old_string, new_string, replace_all?},
+ // Write → {file_path, content}.
+ const call = (id: string, name: string, input: unknown): string =>
+ jl({ type: 'assistant', message: { content: [{ type: 'tool_use', id, name, input }] } })
+ const toolPart = (raw: string, opts?: { rich?: boolean; thinking?: boolean }) =>
+ parseChatMessages(raw.split('\n'), opts).flatMap((m) => m.parts)
+
+ it('rich: Edit and Write tool calls carry a diff; a malformed input carries none', () => {
+ const raw =
+ call('e1', 'Edit', { file_path: '/a.ts', old_string: 'a\nb', new_string: 'a\nc', replace_all: false }) +
+ toolResult('e1', 'The file /a.ts has been updated.') +
+ call('w1', 'Write', { file_path: '/b.ts', content: 'x\ny\n' }) +
+ // An empty new_string deletes the old text: still a diff.
+ call('e2', 'Edit', { file_path: '/c.ts', old_string: 'gone', new_string: '' })
+ expect(toolPart(raw, { rich: true })).toEqual([
+ {
+ kind: 'tool',
+ name: 'Edit',
+ arg: '/a.ts',
+ diff: { filePath: '/a.ts', oldText: 'a\nb', newText: 'a\nc' },
+ result: 'The file /a.ts has been updated.'
+ },
+ { kind: 'tool', name: 'Write', arg: '/b.ts', diff: { filePath: '/b.ts', oldText: '', newText: 'x\ny\n' } },
+ { kind: 'tool', name: 'Edit', arg: '/c.ts', diff: { filePath: '/c.ts', oldText: 'gone', newText: '' } }
+ ])
+
+ const malformed = [
+ call('m1', 'Edit', { file_path: '', old_string: 'a', new_string: 'b' }),
+ call('m2', 'Edit', { file_path: 42, old_string: 'a', new_string: 'b' }),
+ call('m3', 'Edit', { old_string: 'a', new_string: 'b' }),
+ call('m4', 'Edit', { file_path: '/a.ts', old_string: 'a' }),
+ call('m5', 'Edit', { file_path: '/a.ts', old_string: null, new_string: 'b' }),
+ call('m6', 'Write', { file_path: '/a.ts' }),
+ call('m7', 'Write', { file_path: '/a.ts', content: ['x'] }),
+ call('m8', 'Edit', null),
+ call('m9', 'Write', 'not an object'),
+ // Another tool with the same field names is not an edit.
+ call('m10', 'MultiEdit', { file_path: '/a.ts', old_string: 'a', new_string: 'b' }),
+ call('m11', 'Read', { file_path: '/a.ts', content: 'x' })
+ ].join('')
+ const parts = toolPart(malformed, { rich: true })
+ expect(parts).toHaveLength(11)
+ for (const part of parts) {
+ expect(part.kind).toBe('tool')
+ expect('diff' in part, JSON.stringify(part)).toBe(false)
+ }
+ })
+
+ it('rich: each text is capped like a tool body, with the truncation marker', () => {
+ const long = 'x'.repeat(TOOL_BODY_CAP + 10)
+ const raw =
+ call('e1', 'Edit', { file_path: '/a.ts', old_string: long, new_string: long + 'y' }) +
+ call('w1', 'Write', { file_path: '/b.ts', content: long })
+ const diffs = toolPart(raw, { rich: true }).map((p) => (p.kind === 'tool' ? p.diff : undefined))
+ const capped = 'x'.repeat(TOOL_BODY_CAP) + TOOL_BODY_TRUNCATED
+ expect(diffs).toEqual([
+ { filePath: '/a.ts', oldText: capped, newText: capped },
+ { filePath: '/b.ts', oldText: '', newText: capped }
+ ])
+ })
+
+ it('without rich an Edit is the same chip as before', () => {
+ const raw =
+ call('e1', 'Edit', { file_path: '/a.ts', old_string: 'a', new_string: 'b' }) +
+ toolResult('e1', 'ok') +
+ call('w1', 'Write', { file_path: '/b.ts', content: 'x' })
+ const chips = [
+ { kind: 'tool', name: 'Edit', arg: '/a.ts', result: 'ok' },
+ { kind: 'tool', name: 'Write', arg: '/b.ts' }
+ ]
+ expect(toolPart(raw)).toEqual(chips)
+ expect(toolPart(raw, { thinking: true })).toEqual(chips)
+ })
+
+ it('rich rides the paged parser too: the diff sits beside the id', () => {
+ const file = Buffer.from(call('e1', 'Edit', { file_path: '/a.ts', old_string: 'a', new_string: 'b' }))
+ expect(parseChatWindow(file, 0, claudeChatRecordParser({ rich: true })).messages[0].parts).toEqual([
+ { kind: 'tool', name: 'Edit', arg: '/a.ts', diff: { filePath: '/a.ts', oldText: 'a', newText: 'b' }, id: 'e1' }
+ ])
+ expect(parseChatWindow(file, 0).messages[0].parts).toEqual([{ kind: 'tool', name: 'Edit', arg: '/a.ts', id: 'e1' }])
+ })
+})
+
describe('readChatWindow — byte windows read from a real file', () => {
let dir: string
afterEach(() => {
diff --git a/src/core/transcript-reader.ts b/src/core/transcript-reader.ts
index 5300f58c6..559b8a8a8 100644
--- a/src/core/transcript-reader.ts
+++ b/src/core/transcript-reader.ts
@@ -4,11 +4,12 @@
import fs from 'fs'
import os from 'os'
import path from 'path'
-import type { TranscriptLine, ChatMessage, ChatPart, ChatCarriedToolResult } from '../shared/types'
+import type { TranscriptLine, ChatMessage, ChatPart, ChatCarriedToolResult, ChatToolDiff } from '../shared/types'
import { transcriptRootFor } from './claude-accounts-core'
import { linkedClaudeConfigDirFor } from './claude-config-dir'
import { platform } from './platform'
-import { toolBody } from './chat-tool-body'
+import { capBody, toolBody } from './chat-tool-body'
+import { isRecord } from '../shared/is-record'
import { ASK_USER_QUESTION_TOOL, readQuestions } from '../shared/agents/permission-answer'
import { BASH_COMMAND_TOOL, CHAT_TOOL_ARG_MAX, COMMAND_OUTPUT_TOOL } from '../shared/chat-command'
import {
@@ -374,6 +375,7 @@ export interface ChatParseOptions {
* media type is in `CHAT_IMAGE_TYPES` and `data` is a non-empty string. An image inside a
* `tool_result` is tool output and stays out (`summarizeResult` ignores it, as before). Off by
* default, like `thinking`: the golden fixtures and the phone's `chat.page` never set it.
+ * Also: a `diff` on each `Edit` / `Write` tool part whose input reads (`toolDiff`).
*/
rich?: boolean
}
@@ -393,6 +395,28 @@ function imagePart(source: unknown): Extract<ChatPart, { kind: 'image' }> | null
if (typeof data !== 'string' || !data) return null
return { kind: 'image', mediaType, data }
}
+
+/**
+ * The change an `Edit` / `Write` call asked for (`ChatParseOptions.rich`), from its INPUT — measured
+ * (CLI 2.1.314) as `Edit → {file_path, old_string, new_string, replace_all?}` and
+ * `Write → {file_path, content}`. Undefined for any other tool or shape: the plain chip, as before.
+ * An empty `new_string` is a deletion and still a diff. Each text is capped like a tool body.
+ */
+function toolDiff(name: string, input: unknown): ChatToolDiff | undefined {
+ if (!isRecord(input)) return undefined
+ const filePath = input.file_path
+ if (typeof filePath !== 'string' || !filePath) return undefined
+ if (name === 'Edit') {
+ const { old_string: oldText, new_string: newText } = input
+ if (typeof oldText !== 'string' || typeof newText !== 'string') return undefined
+ return { filePath, oldText: capBody(oldText), newText: capBody(newText) }
+ }
+ if (name === 'Write') {
+ return typeof input.content === 'string' ? { filePath, oldText: '', newText: capBody(input.content) } : undefined
+ }
+ return undefined
+}
+
const userTextOf = (text: string, opts: ChatParseOptions | undefined): string =>
opts?.expandPastes === false ? text : expandPastedContent(text)
@@ -624,6 +648,9 @@ function parseChatRecords(
}
const body = toolBody(part.name, c.input)
if (body) part.body = body
+ // Opt-in (see `ChatParseOptions.rich`): without it an Edit is the plain chip, as before.
+ const diff = opts?.rich ? toolDiff(part.name, c.input) : undefined
+ if (diff) part.diff = diff
if (part.name === ASK_USER_QUESTION_TOOL) {
const questions = readQuestions(c.input)
if (questions) part.questions = questions
diff --git a/src/renderer/lib/chatDiff.test.ts b/src/renderer/lib/chatDiff.test.ts
new file mode 100644
index 000000000..855df66e2
--- /dev/null
+++ b/src/renderer/lib/chatDiff.test.ts
@@ -0,0 +1,62 @@
+import { describe, expect, it } from 'vitest'
+import { LINE_DIFF_MAX_CELLS, diffCounts, lineDiff, type DiffLine } from './chatDiff'
+
+const ctx = (text: string): DiffLine => ({ kind: 'ctx', text })
+const add = (text: string): DiffLine => ({ kind: 'add', text })
+const del = (text: string): DiffLine => ({ kind: 'del', text })
+
+describe('lineDiff — the in-thread Edit/Write diff', () => {
+ it('pairs unchanged lines as context and marks the rest', () => {
+ expect(lineDiff('a\nb\nc', 'a\nx\nc')).toEqual([ctx('a'), del('b'), add('x'), ctx('c')])
+ })
+
+ it('a deletion-only edit', () => {
+ expect(diffCounts(lineDiff('a\nb', ''))).toEqual({ added: 0, removed: 2 })
+ expect(lineDiff('a\nb', '')).toEqual([del('a'), del('b')])
+ })
+
+ it('a Write (no old text) is every line added', () => {
+ expect(lineDiff('', 'x\ny')).toEqual([add('x'), add('y')])
+ expect(lineDiff('', '')).toEqual([])
+ })
+
+ it('a trailing newline does not produce an empty extra line', () => {
+ expect(lineDiff('a\n', 'a\nb\n')).toEqual([ctx('a'), add('b')])
+ expect(lineDiff('', 'x\n')).toEqual([add('x')])
+ // A blank line in the middle (or a lone newline) is a real, empty line.
+ expect(lineDiff('a\n\nb', 'a\nb')).toEqual([ctx('a'), del(''), ctx('b')])
+ expect(lineDiff('', '\n')).toEqual([add('')])
+ })
+
+ it('keeps the longest common run: an insertion in the middle leaves both ends as context', () => {
+ expect(lineDiff('a\nb\nc\nd', 'a\nb\nnew\nc\nd')).toEqual([ctx('a'), ctx('b'), add('new'), ctx('c'), ctx('d')])
+ // A moved line pairs the longer common run, not the first match.
+ expect(lineDiff('m\na\nb\nc', 'a\nb\nc\nm')).toEqual([del('m'), ctx('a'), ctx('b'), ctx('c'), add('m')])
+ })
+
+ it('at exactly the size bound it still pairs', () => {
+ const old = Array.from({ length: 500 }, (_, i) => `l${i}`)
+ expect(old.length * old.length).toBe(LINE_DIFF_MAX_CELLS)
+ const out = lineDiff(old.join('\n'), old.map((l, i) => (i === 250 ? 'changed' : l)).join('\n'))
+ expect(diffCounts(out)).toEqual({ added: 1, removed: 1 })
+ expect(out.filter((l) => l.kind === 'ctx')).toHaveLength(499)
+ })
+
+ it('falls back to del-all/add-all past the size bound without pairing', () => {
+ const big = Array.from({ length: 600 }, (_, i) => `l${i}`).join('\n')
+ const out = lineDiff(big, big + '\nz')
+ expect(out.filter((l) => l.kind === 'ctx')).toHaveLength(0)
+ expect(out).toHaveLength(1201)
+ // Every old line first, then every new line, each in its own order.
+ expect(out.slice(0, 600).every((l, i) => l.kind === 'del' && l.text === `l${i}`)).toBe(true)
+ expect(out.slice(600).map((l) => l.text)).toEqual([...big.split('\n'), 'z'])
+ expect(out.slice(600).every((l) => l.kind === 'add')).toBe(true)
+ })
+})
+
+describe('diffCounts', () => {
+ it('counts added and removed lines; context counts as neither', () => {
+ expect(diffCounts([ctx('a'), del('b'), add('x'), add('y'), ctx('c')])).toEqual({ added: 2, removed: 1 })
+ expect(diffCounts([])).toEqual({ added: 0, removed: 0 })
+ })
+})
diff --git a/src/renderer/lib/chatDiff.ts b/src/renderer/lib/chatDiff.ts
new file mode 100644
index 000000000..7c6882f43
--- /dev/null
+++ b/src/renderer/lib/chatDiff.ts
@@ -0,0 +1,68 @@
+// The ⌘M thread's Edit/Write diff (nodes/ChatToolDiff.tsx): the line-by-line change a tool call
+// asked for, from the old and new text the parser read off its input (`ChatToolDiff`, shared/types).
+// No React — see chatDiff.test.ts for the pins.
+
+export type DiffLine = { kind: 'ctx' | 'add' | 'del'; text: string }
+
+/**
+ * The largest old × new line product diffed properly. The table is O(n·m) in time and memory, and
+ * each side can be a 64K-character text (`capBody`), so past this an edit is shown as every old line
+ * removed, then every new line added — still the whole change, just without the pairing.
+ */
+export const LINE_DIFF_MAX_CELLS = 250_000
+
+/** The text's lines; a trailing newline ends the last line rather than starting an empty one. */
+function linesOf(text: string): string[] {
+ if (text === '') return []
+ const lines = text.split('\n')
+ if (lines[lines.length - 1] === '') lines.pop()
+ return lines
+}
+
+/** A line-level diff of `oldText` → `newText`: the longest common subsequence of lines is context. */
+export function lineDiff(oldText: string, newText: string): DiffLine[] {
+ const a = linesOf(oldText)
+ const b = linesOf(newText)
+ const n = a.length
+ const m = b.length
+ if (n * m > LINE_DIFF_MAX_CELLS) {
+ return [...a.map((text): DiffLine => ({ kind: 'del', text })), ...b.map((text): DiffLine => ({ kind: 'add', text }))]
+ }
+ // lcs[i * w + j] = the LCS length of a[i..] and b[j..].
+ const w = m + 1
+ const lcs = new Uint32Array((n + 1) * w)
+ for (let i = n - 1; i >= 0; i--) {
+ for (let j = m - 1; j >= 0; j--) {
+ lcs[i * w + j] = a[i] === b[j] ? lcs[(i + 1) * w + j + 1] + 1 : Math.max(lcs[(i + 1) * w + j], lcs[i * w + j + 1])
+ }
+ }
+ const out: DiffLine[] = []
+ let i = 0
+ let j = 0
+ while (i < n && j < m) {
+ if (a[i] === b[j]) {
+ out.push({ kind: 'ctx', text: a[i] })
+ i++
+ j++
+ } else if (lcs[(i + 1) * w + j] >= lcs[i * w + j + 1]) {
+ // On a tie the removal comes first, so a replaced line reads `-old` then `+new`.
+ out.push({ kind: 'del', text: a[i++] })
+ } else {
+ out.push({ kind: 'add', text: b[j++] })
+ }
+ }
+ while (i < n) out.push({ kind: 'del', text: a[i++] })
+ while (j < m) out.push({ kind: 'add', text: b[j++] })
+ return out
+}
+
+/** The summary's `+N −M`: lines added and removed (context counts as neither). */
+export function diffCounts(lines: readonly DiffLine[]): { added: number; removed: number } {
+ let added = 0
+ let removed = 0
+ for (const l of lines) {
+ if (l.kind === 'add') added++
+ else if (l.kind === 'del') removed++
+ }
+ return { added, removed }
+}
diff --git a/src/renderer/nodes/ChatPanel.thread.test.tsx b/src/renderer/nodes/ChatPanel.thread.test.tsx
index 038495852..0b4e7c865 100644
--- a/src/renderer/nodes/ChatPanel.thread.test.tsx
+++ b/src/renderer/nodes/ChatPanel.thread.test.tsx
@@ -251,6 +251,78 @@ describe('⌘M thread look', () => {
expect(img.classList.contains('term-chat__image--full')).toBe(false)
})
+ it('an Edit renders as a diff chip with counts and colored lines', async () => {
+ await mount([
+ {
+ role: 'assistant',
+ parts: [
+ {
+ kind: 'tool',
+ name: 'Edit',
+ arg: '/a.ts',
+ diff: { filePath: '/a.ts', oldText: 'a\nb', newText: 'a\nc' },
+ result: 'The file /a.ts has been updated.'
+ }
+ ],
+ key: 0
+ }
+ ])
+ expect(host.querySelector('.term-chat__diff-counts')?.textContent).toBe('+1 −1')
+ expect(host.querySelectorAll('.term-chat__diff-line--add')).toHaveLength(1)
+ const chip = host.querySelector<HTMLDetailsElement>('details.term-chat__tool.term-chat__tool--diff')!
+ expect(chip.open).toBe(false)
+ expect(chip.querySelector('summary .term-chat__tool-name')?.textContent).toBe('Edit')
+ expect(chip.querySelector('summary .term-chat__tool-arg')?.textContent).toBe('/a.ts')
+ const lines = [...chip.querySelectorAll('pre.term-chat__diff > .term-chat__diff-line')]
+ expect(lines.map((l) => [l.className, l.textContent])).toEqual([
+ ['term-chat__diff-line term-chat__diff-line--ctx', ' a'],
+ ['term-chat__diff-line term-chat__diff-line--del', '-b'],
+ ['term-chat__diff-line term-chat__diff-line--add', '+c']
+ ])
+ // The result follows the diff, as on the plain chip.
+ expect(chip.querySelector('pre.term-chat__diff + pre.term-chat__tool-result')?.textContent).toBe(
+ 'The file /a.ts has been updated.'
+ )
+ })
+
+ it('a Write with no result is all added lines; a tool without a diff stays the plain chip', async () => {
+ await mount([
+ { role: 'user', parts: [{ kind: 'text', text: 'q' }], key: 0 },
+ {
+ role: 'assistant',
+ parts: [{ kind: 'tool', name: 'Write', arg: '/b.ts', diff: { filePath: '/b.ts', oldText: '', newText: 'x\ny\n' } }],
+ key: 10
+ },
+ { role: 'assistant', parts: [{ kind: 'text', text: 'Done.' }], key: 20 },
+ { role: 'assistant', parts: [{ kind: 'tool', name: 'Edit', arg: '/c.ts' }], key: 30 }
+ ])
+ const diffs = host.querySelectorAll('.term-chat__tool--diff')
+ expect(diffs).toHaveLength(1)
+ expect(diffs[0].querySelector('.term-chat__diff-counts')?.textContent).toBe('+2 −0')
+ expect(diffs[0].querySelector('.term-chat__tool-result')).toBeNull()
+ const plain = [...host.querySelectorAll('.term-chat__tool')].filter((t) => !t.classList.contains('term-chat__tool--diff'))
+ expect(plain).toHaveLength(1)
+ expect(plain[0].querySelector('.term-chat__diff')).toBeNull()
+ })
+
+ it('a diff chip inside a folded tool run is drawn as a diff chip there too', async () => {
+ await mount([
+ { role: 'user', parts: [{ kind: 'text', text: 'q' }], key: 0 },
+ { role: 'assistant', parts: [{ kind: 'tool', name: 'Read', arg: '/a.ts' }], key: 10 },
+ {
+ role: 'assistant',
+ parts: [{ kind: 'tool', name: 'Edit', arg: '/a.ts', diff: { filePath: '/a.ts', oldText: 'a', newText: 'b' } }],
+ key: 20
+ },
+ { role: 'assistant', parts: [{ kind: 'text', text: 'Done.' }], key: 30 }
+ ])
+ const group = host.querySelector('.term-chat__tool-group')!
+ expect(group.querySelector('.term-chat__tool-group-count')?.textContent).toBe('2 tool calls')
+ expect(group.querySelector('.term-chat__tool-group-body .term-chat__tool--diff .term-chat__diff-counts')?.textContent).toBe(
+ '+1 −1'
+ )
+ })
+
it('asks the reader for rich parts', async () => {
await mount([])
expect(lastPageArg().rich).toBe(true)
diff --git a/src/renderer/nodes/ChatPanel.tsx b/src/renderer/nodes/ChatPanel.tsx
index 8a4f2ca0c..b2c8e53b7 100644
--- a/src/renderer/nodes/ChatPanel.tsx
+++ b/src/renderer/nodes/ChatPanel.tsx
@@ -61,6 +61,7 @@ import { groupToolCalls, partPosition } from '../lib/chatToolGroups'
import { thinkingLabel } from '../lib/chatThinking'
import { ChatToolGroup } from './ChatToolGroup'
import { ChatImage } from './ChatImage'
+import { ChatToolDiff } from './ChatToolDiff'
import { FALLBACK_SESSION_NOTE, transcriptReadCwd } from '../lib/transcriptSession'
import { chatPageDirection, pageChatThread } from '../lib/chatPageKeys'
@@ -1043,6 +1044,9 @@ export function ChatPanel({
<AnswerControlsUpdating chip={mdChip} />
)}
</div>
+ ) : p.diff ? (
+ // An Edit / Write (the opt-in `rich` read): the plain chip plus `+N −M`, opening to the diff.
+ <ChatToolDiff key={key} name={p.name} diff={p.diff} result={p.result} />
) : (
<details key={key} className="term-chat__tool">
<summary>
diff --git a/src/renderer/nodes/ChatToolDiff.tsx b/src/renderer/nodes/ChatToolDiff.tsx
new file mode 100644
index 000000000..b6f349f2f
--- /dev/null
+++ b/src/renderer/nodes/ChatToolDiff.tsx
@@ -0,0 +1,36 @@
+import { useMemo } from 'react'
+import type { ChatToolDiff as ToolDiff } from '@shared/types'
+import { diffCounts, lineDiff, type DiffLine } from '../lib/chatDiff'
+
+const PREFIX: Record<DiffLine['kind'], string> = { ctx: ' ', add: '+', del: '-' }
+
+/**
+ * An `Edit` / `Write` call in the ⌘M thread: the same chip as any tool call (name, file path), with
+ * the lines added and removed in its summary, and the change itself as a colored line diff when
+ * opened (lib/chatDiff.ts). Closed by default and uncontrolled, like the plain chip, so a run of
+ * edits folds into a tool block like any other run of calls.
+ */
+export function ChatToolDiff({ name, diff, result }: { name: string; diff: ToolDiff; result?: string }): JSX.Element {
+ const lines = useMemo(() => lineDiff(diff.oldText, diff.newText), [diff.oldText, diff.newText])
+ const { added, removed } = diffCounts(lines)
+ return (
+ <details className="term-chat__tool term-chat__tool--diff">
+ <summary>
+ <span className="term-chat__tool-name">{name}</span>
+ <span className="term-chat__tool-arg">{diff.filePath}</span>
+ <span className="term-chat__diff-counts">
+ +{added} −{removed}
+ </span>
+ </summary>
+ <pre className="term-chat__diff">
+ {lines.map((l, k) => (
+ <span key={k} className={`term-chat__diff-line term-chat__diff-line--${l.kind}`}>
+ {PREFIX[l.kind]}
+ {l.text}
+ </span>
+ ))}
+ </pre>
+ {result && <pre className="term-chat__tool-result">{result}</pre>}
+ </details>
+ )
+}
diff --git a/src/renderer/styles.chat-view.test.ts b/src/renderer/styles.chat-view.test.ts
index a41864ff9..99bbbc9df 100644
--- a/src/renderer/styles.chat-view.test.ts
+++ b/src/renderer/styles.chat-view.test.ts
@@ -102,6 +102,16 @@ describe('⌘M thread: claude.ai look', () => {
expect(ruleBody('.term-chat__image')).toMatch(/max-height:\s*240px;/)
expect(ruleBody('.term-chat__image--full')).toMatch(/max-height:\s*none;/)
})
+
+ it('an Edit/Write diff keeps its whitespace, and added and removed lines are tinted differently', () => {
+ expect(ruleBody('.term-chat__diff')).toMatch(/white-space:\s*pre;/)
+ const bg = (selector: string): string => {
+ const m = ruleBody(selector).match(/background:\s*([^;]+);/)
+ expect(m, `no background in ${selector}`).toBeTruthy()
+ return m![1].trim()
+ }
+ expect(bg('.term-chat__diff-line--add')).not.toBe(bg('.term-chat__diff-line--del'))
+ })
})
describe('the shared .term-chat__input (plan "Revise…", question "Other") keeps a visible field', () => {
diff --git a/src/renderer/styles.css b/src/renderer/styles.css
index 5c365da17..90e7b3799 100644
--- a/src/renderer/styles.css
+++ b/src/renderer/styles.css
@@ -3688,6 +3688,44 @@ body,
font-size: 11px;
opacity: 0.85;
}
+/* An Edit / Write call (nodes/ChatToolDiff.tsx): the chip's summary ends in the `+N −M` counts, and
+ it opens to the line diff. The block is a one-column grid sized to its widest line (at least the
+ chip's width), so a line's tint spans the whole row even while the block is scrolled sideways;
+ code keeps its indentation (`pre`, never wrapped), and a long Write scrolls inside its own box. */
+.term-chat__diff-counts {
+ flex: 0 0 auto;
+ white-space: nowrap;
+ font-family: ui-monospace, monospace;
+ color: var(--muted);
+}
+.term-chat__diff {
+ display: grid;
+ grid-template-columns: minmax(max-content, 1fr);
+ margin: 6px 0 0;
+ padding: 4px 0;
+ max-height: 360px;
+ overflow: auto;
+ white-space: pre;
+ font-family: ui-monospace, monospace;
+ font-size: 11px;
+ line-height: 1.45;
+ background: var(--surface-sunken);
+ border-radius: 6px;
+}
+.term-chat__diff-line {
+ padding: 0 8px;
+}
+.term-chat__diff-line--ctx {
+ color: var(--muted);
+}
+.term-chat__diff-line--add {
+ color: var(--success);
+ background: color-mix(in srgb, var(--state-success) 12%, transparent);
+}
+.term-chat__diff-line--del {
+ color: var(--danger);
+ background: color-mix(in srgb, var(--state-error) 12%, transparent);
+}
/* A run of consecutive tool calls folded into one block (nodes/ChatToolGroup.tsx), closed by
default. Closed, it is one chip-sized line: a chevron, the count, the tools used. Open, the same
chips follow, indented under a hairline so they read as belonging to the line above. */
diff --git a/src/shared/chat-fixtures/README.md b/src/shared/chat-fixtures/README.md
index 889cc5a7f..e8ffc9088 100644
--- a/src/shared/chat-fixtures/README.md
+++ b/src/shared/chat-fixtures/README.md
@@ -100,6 +100,11 @@ nothing above changes. What it adds:
non-empty string. Any other type (`image/svg+xml` included) or source yields no part. An image
inside a `tool_result` is tool output and never becomes one. An image-only record yields no
message without the option and a user message with it.
+- A `diff: {filePath, oldText, newText}` on an `Edit` tool part (`{file_path, old_string,
+ new_string}`) or a `Write` one (`{file_path, content}`, `oldText: ""`), read from the call's input
+ when `file_path` is a non-empty string and the texts are strings (an empty `new_string` is a
+ deletion and still a diff). Each text is capped like a tool `body` (65536 UTF-16 units, then
+ `TOOL_BODY_TRUNCATED`). Any other shape yields no `diff`; `arg` and `result` are unchanged.
Decision cases: plan `restore` / `acceptEdits` / `manual` / `revise` (the revise text is trimmed),
question single / multi (labels joined with `, `) / free text (trimmed), and three refusals: a
diff --git a/src/shared/types.ts b/src/shared/types.ts
index 5cd594bcc..3046b4225 100644
--- a/src/shared/types.ts
+++ b/src/shared/types.ts
@@ -3626,11 +3626,28 @@ export type ChatPart =
* the SAME reader the held request's texts come from, so a surface can match the card to the
* held ticket. Absent = unreadable input = the card stays read-only. */
questions?: ChatQuestion[]
+ /** `Edit` / `Write` only, on the opt-in `rich` read (`ChatParseOptions.rich`): the change the
+ * call asked for, read from its INPUT — never from the result — so the renderer can draw it as
+ * a diff. Absent = any other tool, an unreadable input, or a read without `rich`. */
+ diff?: ChatToolDiff
/** The transcript's `tool_use` id. Set only by a PAGED read (`ChatTranscriptResult.olderCursor`
* present): a result carried across a page boundary (`unmatchedResults`) is attached by it. */
id?: string
}
+/**
+ * The change an `Edit` / `Write` tool call asked for (`ChatPart` tool `diff`). Edit's
+ * `{file_path, old_string, new_string}` maps to `{filePath, oldText, newText}`; Write's
+ * `{file_path, content}` to `{filePath, oldText: '', newText: content}`. An empty `newText` on an
+ * Edit is a deletion. Each text is capped like a tool body (`capBody`, core/chat-tool-body.ts: 64K
+ * characters, then `TOOL_BODY_TRUNCATED`).
+ */
+export interface ChatToolDiff {
+ filePath: string
+ oldText: string
+ newText: string
+}
+
/** A structured chat message reconstructed from a Claude session transcript. */
export interface ChatMessage {
role: 'user' | 'assistant'