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.

perf(chat): keystrokes no longer re-render diff chips and images

reviewcc76b4f9ed7c
diff --git a/src/renderer/nodes/ChatImage.tsx b/src/renderer/nodes/ChatImage.tsx
index ecd9a53e2..4841b9990 100644
--- a/src/renderer/nodes/ChatImage.tsx
+++ b/src/renderer/nodes/ChatImage.tsx
@@ -1,12 +1,16 @@
-import { useState } from 'react'
+import { memo, useState } from 'react'
/**
* An image the user attached to a prompt, in the ⌘M thread: a height-capped thumbnail inside the
* bubble that a click shows at full size (and a second click shrinks back). The parser hands over
* only an allowlisted raster type with a base64 payload (`CHAT_IMAGE_TYPES`), so the `data:` URL is
* never markup. Lazy: a long thread of screenshots decodes only the ones scrolled into view.
+ *
+ * `memo`: every keystroke in the composer re-renders the thread, and each render rebuilt (and React
+ * re-compared) a `data:` URL megabytes long — ten 2 MB images cost ~18 ms per keystroke (measured:
+ * production React 18, jsdom). Its props are the part's own strings, unchanged between keystrokes.
*/
-export function ChatImage({ mediaType, data }: { mediaType: string; data: string }): JSX.Element {
+export const ChatImage = memo(function ChatImage({ mediaType, data }: { mediaType: string; data: string }): JSX.Element {
const [full, setFull] = useState(false)
return (
<img
@@ -17,4 +21,4 @@ export function ChatImage({ mediaType, data }: { mediaType: string; data: string
onClick={() => setFull((f) => !f)}
/>
)
-}
+})
diff --git a/src/renderer/nodes/ChatPanel.thread.test.tsx b/src/renderer/nodes/ChatPanel.thread.test.tsx
index a52c063c5..fc39657d1 100644
--- a/src/renderer/nodes/ChatPanel.thread.test.tsx
+++ b/src/renderer/nodes/ChatPanel.thread.test.tsx
@@ -294,11 +294,13 @@ describe('⌘M thread look', () => {
}
])
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')
+ // The diff body is drawn once the chip is opened (ChatToolDiff.test.tsx pins the closed state).
+ await act(async () => chip.querySelector('summary')!.click())
+ expect(host.querySelectorAll('.term-chat__diff-line--add')).toHaveLength(1)
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'],
@@ -311,6 +313,49 @@ describe('⌘M thread look', () => {
)
})
+ it('typing in the composer neither re-renders nor remounts an open diff chip or an image', async () => {
+ // The composer's draft is ChatPanel state, so every keystroke re-renders the panel. A diff chip
+ // (thousands of line elements when open) and an image (a `data:` URL megabytes long) must sit
+ // that out: same props, so `memo` skips them.
+ await mount([
+ { role: 'user', parts: [{ kind: 'image', mediaType: 'image/png', data: 'AAAA' }], key: 0 },
+ {
+ role: 'assistant',
+ parts: [{ kind: 'tool', name: 'Edit', arg: '/a.ts', diff: { filePath: '/a.ts', oldText: 'a', newText: 'b' } }],
+ key: 10
+ }
+ ])
+ const chip = host.querySelector<HTMLDetailsElement>('details.term-chat__tool--diff')!
+ await act(async () => chip.querySelector('summary')!.click())
+ const pre = host.querySelector('pre.term-chat__diff')!
+ const img = host.querySelector('img.term-chat__image')!
+ expect(pre).not.toBeNull()
+ // React swaps a host element's props record (`__reactProps$…`) on every commit that renders it
+ // with a new event handler — both elements take an inline one — so an unchanged record means the
+ // component did not run. (DOM identity alone cannot tell: React reuses the nodes either way.)
+ const propsRecord = (el: Element): unknown => {
+ const k = Object.keys(el).find((key) => key.startsWith('__reactProps$'))
+ expect(k, 'React no longer keeps a props record on the element').toBeDefined()
+ return (el as unknown as Record<string, unknown>)[k!]
+ }
+ const before = { chip: propsRecord(chip), img: propsRecord(img) }
+ const ta = host.querySelector('textarea')!
+ const setValue = Object.getOwnPropertyDescriptor(HTMLTextAreaElement.prototype, 'value')!.set!
+ for (const draft of ['h', 'he', 'hey']) {
+ await act(async () => {
+ setValue.call(ta, draft)
+ ta.dispatchEvent(new Event('input', { bubbles: true }))
+ })
+ }
+ expect(ta.value).toBe('hey')
+
+ expect(host.querySelector('pre.term-chat__diff')).toBe(pre)
+ expect(host.querySelector('img.term-chat__image')).toBe(img)
+ expect(chip.open).toBe(true)
+ expect(propsRecord(chip)).toBe(before.chip)
+ expect(propsRecord(img)).toBe(before.img)
+ })
+
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 },
diff --git a/src/renderer/nodes/ChatToolDiff.test.tsx b/src/renderer/nodes/ChatToolDiff.test.tsx
new file mode 100644
index 000000000..17d56dd16
--- /dev/null
+++ b/src/renderer/nodes/ChatToolDiff.test.tsx
@@ -0,0 +1,59 @@
+// @vitest-environment jsdom
+import { act } from 'react'
+import { createRoot, type Root } from 'react-dom/client'
+import { afterEach, beforeEach, describe, expect, it } from 'vitest'
+import { ChatToolDiff } from './ChatToolDiff'
+
+/**
+ * The Edit / Write chip (ChatPanel draws it; its thread glue is pinned in ChatPanel.thread.test.tsx).
+ * A diff side can be 64K characters (`capText`), i.e. thousands of line elements: the body is built
+ * only while the chip is OPEN, so a thread of closed edits carries none of them.
+ */
+
+;(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true
+
+let host: HTMLDivElement
+let root: Root
+beforeEach(() => {
+ host = document.createElement('div')
+ document.body.appendChild(host)
+ root = createRoot(host)
+})
+afterEach(async () => {
+ await act(async () => root.unmount())
+ host.remove()
+})
+
+const diff = { filePath: '/a.ts', oldText: 'a\nb', newText: 'a\nc' }
+const chip = (): HTMLDetailsElement => host.querySelector<HTMLDetailsElement>('details.term-chat__tool--diff')!
+const toggle = async (): Promise<void> => {
+ await act(async () => chip().querySelector('summary')!.click())
+}
+
+describe('ChatToolDiff', () => {
+ it('draws no diff body while closed; the summary still counts the change', async () => {
+ await act(async () => root.render(<ChatToolDiff name="Edit" diff={diff} result="ok" />))
+
+ expect(chip().open).toBe(false)
+ expect(chip().querySelector('summary .term-chat__diff-counts')?.textContent).toBe('+1 −1')
+ expect(chip().querySelector('pre.term-chat__diff')).toBeNull()
+ expect(chip().querySelector('.term-chat__diff-line')).toBeNull()
+ })
+
+ it('opening draws the diff (before the result); closing drops it again', async () => {
+ await act(async () => root.render(<ChatToolDiff name="Edit" diff={diff} result="ok" />))
+
+ await toggle()
+
+ expect(chip().open).toBe(true)
+ const lines = [...chip().querySelectorAll('pre.term-chat__diff > .term-chat__diff-line')]
+ expect(lines.map((l) => l.textContent)).toEqual([' a', '-b', '+c'])
+ expect(chip().querySelector('pre.term-chat__diff + pre.term-chat__tool-result')?.textContent).toBe('ok')
+
+ await toggle()
+
+ expect(chip().open).toBe(false)
+ expect(chip().querySelector('pre.term-chat__diff')).toBeNull()
+ expect(chip().querySelector('summary .term-chat__diff-counts')?.textContent).toBe('+1 −1')
+ })
+})
diff --git a/src/renderer/nodes/ChatToolDiff.tsx b/src/renderer/nodes/ChatToolDiff.tsx
index b6f349f2f..07b75f332 100644
--- a/src/renderer/nodes/ChatToolDiff.tsx
+++ b/src/renderer/nodes/ChatToolDiff.tsx
@@ -1,4 +1,4 @@
-import { useMemo } from 'react'
+import { memo, useMemo, useState } from 'react'
import type { ChatToolDiff as ToolDiff } from '@shared/types'
import { diffCounts, lineDiff, type DiffLine } from '../lib/chatDiff'
@@ -9,12 +9,30 @@ const PREFIX: Record<DiffLine['kind'], string> = { ctx: ' ', add: '+', del: '-'
* 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.
+ *
+ * A side can be 64K characters (`capText`), i.e. thousands of line elements, so the diff body is
+ * built only while the chip is open (`onToggle` mirrors the native state) — the summary's counts
+ * need the line diff, never its DOM.
+ *
+ * `memo`: the composer's draft is ChatPanel state, so every keystroke re-renders the thread, and
+ * 20,000 loaded diff lines cost ~38 ms per keystroke (measured: production React 18, jsdom). Its
+ * props are the message part's own `diff` object and strings: the same references from one
+ * keystroke to the next.
*/
-export function ChatToolDiff({ name, diff, result }: { name: string; diff: ToolDiff; result?: string }): JSX.Element {
+export const ChatToolDiff = memo(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)
+ const { added, removed } = useMemo(() => diffCounts(lines), [lines])
+ const [open, setOpen] = useState(false)
return (
- <details className="term-chat__tool term-chat__tool--diff">
+ <details className="term-chat__tool term-chat__tool--diff" onToggle={(e) => setOpen(e.currentTarget.open)}>
<summary>
<span className="term-chat__tool-name">{name}</span>
<span className="term-chat__tool-arg">{diff.filePath}</span>
@@ -22,15 +40,17 @@ export function ChatToolDiff({ name, diff, result }: { name: string; diff: ToolD
+{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>
+ {open && (
+ <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>
)
-}
+})