From 27a920f85b69245bb00358b86f9d57f9a1ea9b6b Mon Sep 17 00:00:00 2001 From: Menghuan1918 Date: Sat, 24 Oct 2026 02:17:05 +0800 Subject: [PATCH 1/9] perf(tasks): coalesce wheel zooms to one commit per frame --- src/client/TasksGraph.tsx | 39 ++++++++++++++++++++++++++++++--------- tests/tasks-page.spec.tsx | 35 +++++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+), 9 deletions(-) diff --git a/src/client/TasksGraph.tsx b/src/client/TasksGraph.tsx index 794a283a..33f47420 100644 --- a/src/client/TasksGraph.tsx +++ b/src/client/TasksGraph.tsx @@ -358,6 +358,18 @@ export function TasksGraph(props: TasksGraphProps): ReactNode { return () => { observer.disconnect() } }, [fit]) + /** + * Wheel zoom is applied at most once per animation frame, for the same + * reason the pan is: a trackpad (and a high-report-rate mouse) delivers + * several wheel events per display frame, and every one of them + * used to commit a full canvas re-render. Each event chains off the PENDING + * transform rather than the last drawn one, so coalescing never loses a zoom + * step — the old code re-read `tfRef` for every event and only one step + * survived the frame. + */ + const wheelBatcher = useRef(createFrameBatcher()).current + const pendingWheelRef = useRef<{ x: number; y: number; k: number } | null>(null) + // Wheel-zoom to cursor (non-passive: the page must not scroll). useEffect(() => { const container = containerRef.current @@ -367,24 +379,30 @@ export function TasksGraph(props: TasksGraphProps): ReactNode { const rect = container.getBoundingClientRect() const mx = event.clientX - rect.left const my = event.clientY - rect.top - const { x, y, k } = tfRef.current + const base = pendingWheelRef.current ?? tfRef.current // Wheel deltas arrive in pixels, lines or pages depending on the device; // normalise first, or a line-scrolling mouse zooms 30× slower than a // trackpad (and a trackpad pinch, which reports ctrlKey, feels stuck). const unit = event.deltaMode === 1 ? 16 : event.deltaMode === 2 ? 100 : 1 - const next = Math.min(ZOOM_MAX, Math.max(ZOOM_MIN, k * Math.exp(-event.deltaY * unit * 0.0014))) - if (next === k) return + const next = Math.min(ZOOM_MAX, Math.max(ZOOM_MIN, base.k * Math.exp(-event.deltaY * unit * 0.0014))) + if (next === base.k) return touchedRef.current = true stopGlide() - setTf(clampTf({ - x: mx - (mx - x) * (next / k), - y: my - (my - y) * (next / k), + pendingWheelRef.current = { + x: mx - (mx - base.x) * (next / base.k), + y: my - (my - base.y) * (next / base.k), k: next, - })) + } + wheelBatcher.schedule(() => { + const pending = pendingWheelRef.current + if (pending === null) return + pendingWheelRef.current = null + setTf(clampTf(pending)) + }) } container.addEventListener('wheel', onWheel, { passive: false }) return () => { container.removeEventListener('wheel', onWheel) } - }, [clampTf, stopGlide]) + }, [clampTf, stopGlide, wheelBatcher]) const zoomBy = useCallback((factor: number): void => { const container = containerRef.current @@ -428,7 +446,10 @@ export function TasksGraph(props: TasksGraphProps): ReactNode { const panBatcher = useRef(createFrameBatcher()).current const pendingPanRef = useRef<{ x: number; y: number; k: number } | null>(null) const draggingRef = useRef(false) - useEffect(() => () => { panBatcher.dispose() }, [panBatcher]) + useEffect(() => () => { + panBatcher.dispose() + wheelBatcher.dispose() + }, [panBatcher, wheelBatcher]) const onPointerDown = useCallback((event: ReactPointerEvent): void => { if (event.button !== 0) return diff --git a/tests/tasks-page.spec.tsx b/tests/tasks-page.spec.tsx index 99d09091..6a404f38 100644 --- a/tests/tasks-page.spec.tsx +++ b/tests/tasks-page.spec.tsx @@ -614,6 +614,41 @@ describe('Tasks page graph interactions and team board', () => { unmount() }) + it('coalesces wheel zooms into one update per animation frame without losing steps', async () => { + const store = makeStore(snapshotWithChildren(2)) + const { container, unmount } = renderRoot( + createElement(SubagentView, { sessionId: 'root', active: true, ctx: makeCtx(store) }), + ) + const canvas = container.querySelector('[role="group"]') as HTMLElement + const inner = canvas.querySelector('div[style*="transform"]') as HTMLElement + const scaleOf = (style: string | null): number => Number(/scale\(([\d.]+)\)/.exec(style ?? '')?.[1] ?? NaN) + await act(async () => { await new Promise(resolve => requestAnimationFrame(() => resolve())) }) + const settled = inner.getAttribute('style') + const baseScale = scaleOf(settled) + + // A trackpad reports several wheel events between two frames. None may + // commit on its own, and the frame must apply the SUM of the deltas (the + // old code re-read the drawn transform for every event, so only one step + // survived). + const steps = 5 + await act(async () => { + for (let step = 0; step < steps; step += 1) { + canvas.dispatchEvent(new WheelEvent('wheel', { + deltaY: -10, clientX: 100, clientY: 100, bubbles: true, cancelable: true, + })) + } + }) + expect(inner.getAttribute('style'), 'no commit before the frame').toBe(settled) + + await act(async () => { await new Promise(resolve => requestAnimationFrame(() => resolve())) }) + const afterFrame = scaleOf(inner.getAttribute('style')) + expect(afterFrame, 'the frame applies the batch').not.toBe(baseScale) + // One event per frame would give base * e^0.014; the coalesced frame gives + // base * e^(0.014 * steps). + expect(afterFrame).toBeCloseTo(baseScale * Math.exp(0.014 * steps), 3) + unmount() + }) + it('activates a graph node after a background pointerdown (no click theft)', async () => { const navigation: NavigationSpy = { opened: [] } const store = makeStore(snapshotWithChildren(1)) From 4cb7937a37e080b1fc92e4fec9b5b1081e515f4b Mon Sep 17 00:00:00 2001 From: Menghuan1918 Date: Sat, 24 Oct 2026 02:17:07 +0800 Subject: [PATCH 2/9] perf(files): keep parked trees idle and batch the watcher re-arm --- src/client/FileTree.tsx | 23 +++++++- src/client/TreePanel.tsx | 8 ++- src/client/use-dir-watch.ts | 17 ++++-- tests/editor-host.spec.tsx | 85 +++++++++++++++++++++++------ tests/file-tree-batch-load.spec.tsx | 40 +++++++++++--- tests/file-tree-dir-watch.spec.tsx | 12 ++-- 6 files changed, 146 insertions(+), 39 deletions(-) diff --git a/src/client/FileTree.tsx b/src/client/FileTree.tsx index 6eb65b57..55726c3f 100644 --- a/src/client/FileTree.tsx +++ b/src/client/FileTree.tsx @@ -587,6 +587,9 @@ export function FileTree(props: { /** The live props for the stable callbacks below (identity churns per render). */ const propsRef = useRef(props) propsRef.current = props + /** Live visibility for the load effects: a parked tree fetches nothing. */ + const visibleRef = useRef(visible !== false) + visibleRef.current = visible !== false const [data, setData] = useState>({}) /** * Registry revision for the file-icon feature: bumps on ANY registry @@ -927,6 +930,11 @@ export function FileTree(props: { loadLevels([dir], { force: true }) }, [loadLevels]) + /** Re-list a SET of directories in ONE batch (the parked→visible re-arm). */ + const retryDirs = useCallback((dirs: readonly string[]) => { + if (dirs.length > 0) loadLevels([...dirs], { force: true }) + }, [loadLevels]) + /** * Settle the tree after one rename/delete landed at `prefix`: drop every * cached level at or under the old path, collapse the now-stale expanded @@ -980,6 +988,10 @@ export function FileTree(props: { useEffect(() => { if (lastTick.current === refreshTick) return lastTick.current = refreshTick + // A parked tree drops the tick outright: the watcher's re-arm re-lists the + // whole watched set when the tab comes back, so forcing a load here would + // only duplicate that batch (and do it off screen). + if (visibleRef.current === false) return generationRef.current += 1 forceNextLoad.current = true }, [refreshTick]) @@ -1002,8 +1014,13 @@ export function FileTree(props: { // Load the visible set in ONE batch request; already-loaded levels (kept // in the cache) are not refetched, so this asks only for what is new — a // refresh tick re-lists root + every expanded directory in one POST. + // + // A PARKED tree issues nothing: nobody can see the rows, and the watcher's + // re-arm re-lists the whole watched set once on the way back. Visibility is + // read through a ref, NOT a dependency — making it one would fire a second + // batch alongside that re-arm. const root = cwd - if (root === undefined) return + if (root === undefined || visibleRef.current === false) return const force = forceNextLoad.current forceNextLoad.current = false loadLevels([root, ...expanded], { force }) @@ -1035,13 +1052,13 @@ export function FileTree(props: { // it was opened stayed stale for the rest of the session. A PARKED tree // (the host keeps every visited tab body mounted) closes the socket — and // with it the host's `fs.watch` handles — and re-lists the watched levels - // once when it comes back. + // once (ONE batch) when it comes back. useDirectoryWatch({ sessionId, root: cwd, dirs: expanded, visible: visible !== false, - onStale: retryDir, + onStale: retryDirs, }) // Bring a "Show in folder" reveal into view: the ancestors expand above diff --git a/src/client/TreePanel.tsx b/src/client/TreePanel.tsx index 97be92b0..51f9b1c1 100644 --- a/src/client/TreePanel.tsx +++ b/src/client/TreePanel.tsx @@ -118,7 +118,13 @@ export function TreePanel(props: { // refresh click. Re-focusing the window bumps the tick automatically, and // integrations can force a refresh by dispatching a bubbling // `dsh-sidebar:refresh-files` event on `window`. + // + // A PARKED panel (the host keeps every visited tab body mounted) listens to + // neither: a focus bump would force a full re-list of a tree nobody can see. + // It catches up through the directory watcher's one batched refresh when it + // becomes visible again (see FileTree's `visibleRef`). useEffect(() => { + if (visible === false) return const bump = (): void => { setRefreshTick(tick => tick + 1) } window.addEventListener('focus', bump) window.addEventListener('dsh-sidebar:refresh-files', bump) @@ -126,7 +132,7 @@ export function TreePanel(props: { window.removeEventListener('focus', bump) window.removeEventListener('dsh-sidebar:refresh-files', bump) } - }, []) + }, [visible]) /** One-line upload status under the search row ('' hides the hint). */ const [uploadStatus, setUploadStatus] = useState('') /** Whether the status line is a failure/cancel (error color, stays visible). */ diff --git a/src/client/use-dir-watch.ts b/src/client/use-dir-watch.ts index f58f37f3..2bdc6d14 100644 --- a/src/client/use-dir-watch.ts +++ b/src/client/use-dir-watch.ts @@ -47,10 +47,14 @@ export interface DirectoryWatchOptions { */ visible?: boolean /** - * A directory whose listing is stale. - * @param dir - absolute directory path, exactly the form the tree keys levels by. + * Directories whose listings are stale. + * + * A watch notice names one directory. The parked→visible re-arm names the + * WHOLE watched set at once: the caller re-lists it in one batch request + * instead of firing one request per directory. + * @param dirs - absolute directory paths, exactly the form the tree keys levels by. */ - onStale: (dir: string) => void + onStale: (dirs: readonly string[]) => void } /** How long to wait before re-opening a dropped socket; failures back off to the cap. */ @@ -146,7 +150,7 @@ export function useDirectoryWatch(options: DirectoryWatchOptions): void { watching.add(frame.dir) return } - if (frame.ok === undefined) staleRef.current(frame.dir) + if (frame.ok === undefined) staleRef.current([frame.dir]) } socket.onclose = () => { if (closed) return @@ -175,13 +179,14 @@ export function useDirectoryWatch(options: DirectoryWatchOptions): void { * Re-armed after being parked: the socket is brand new (the old one's * notices are gone with it), so nothing the host saw while the tree was * hidden was delivered. Re-list every watched directory once instead of - * showing a listing that may be minutes old. + * showing a listing that may be minutes old — as ONE batch (the caller + * re-lists the set in a single `fs.trees` request), not one per directory. */ const wasArmedRef = useRef(armed) useEffect(() => { const previous = wasArmedRef.current wasArmedRef.current = armed if (!armed || previous) return - for (const dir of wantedRef.current) staleRef.current(dir) + if (wantedRef.current.length > 0) staleRef.current(wantedRef.current) }, [armed]) } diff --git a/tests/editor-host.spec.tsx b/tests/editor-host.spec.tsx index 256affa7..3e532bc0 100644 --- a/tests/editor-host.spec.tsx +++ b/tests/editor-host.spec.tsx @@ -10,7 +10,7 @@ */ // @vitest-environment jsdom import { beforeEach, describe, expect, it, vi } from 'vitest' -import { createElement, useEffect, type ReactNode } from 'react' +import { createElement, Profiler, useEffect, type ReactNode } from 'react' import { createRoot } from 'react-dom/client' import { act } from 'react-dom/test-utils' import type { Context } from '../src/context-types.ts' @@ -282,29 +282,44 @@ function mountHost(ctx: Context, store: ReturnType, t * context-menu scenarios need the file row in the DOM). The scope carries the * session cwd — without a root the docked tree has nothing to list. */ -async function mountHostWithTreeWithCwd(ctx: Context, store: ReturnType, tab: () => SidebarTab): Promise<{ +async function mountHostWithTreeWithCwd( + ctx: Context, + store: ReturnType, + tab: () => SidebarTab, + options: { visible?: boolean; onRender?: () => void } = {}, +): Promise<{ container: HTMLDivElement + rerender: (visible: boolean) => Promise unmount: () => void }> { const container = document.createElement('div') document.body.append(container) const root = createRoot(container) - await act(async () => { - root.render(createElement(EditorHost, { - ctx, - store, - scope: { sessionId, cwd: '/tmp' }, - tab: tab(), - expanded: [], - revealed: [], - onToggleDir: () => {}, - onReferenceFile: () => {}, - })) - await Promise.resolve() - await Promise.resolve() - }) + let visible = options.visible + const render = async (): Promise => { + await act(async () => { + const host = createElement(EditorHost, { + ctx, + store, + scope: { sessionId, cwd: '/tmp' }, + tab: tab(), + expanded: [], + revealed: [], + onToggleDir: () => {}, + onReferenceFile: () => {}, + visible, + }) + root.render(options.onRender === undefined + ? host + : createElement(Profiler, { id: 'editor-host', onRender: options.onRender }, host)) + await Promise.resolve() + await Promise.resolve() + }) + } + await render() return { container, + rerender: async (next: boolean) => { visible = next; await render() }, unmount: () => { act(() => { root.unmount() }) container.remove() @@ -856,6 +871,44 @@ describe('EditorHost native-tab context-menu actions', { timeout: 120_000 }, () } }) + it('a parked tree ignores window focus and re-lists the watched set once on return', async () => { + // The host keeps every visited tab body mounted, so a hidden tree used to + // answer every window focus with a forced full re-list (one per mounted + // panel). It must stay silent while parked and catch up in ONE batch. + let commits = 0 + const store = createSidebarStore() + const { service } = spyService(store) + service.registerTab({ id: 'editor', title: 'Editor', dedupeKey: (tab: SidebarTab) => tab.path, component: () => null }) + store.setSession(sessionId) + store.setPrefs({ ...store.getPrefs(), editorExplorer: false }) + service.openTab({ + type: 'editor', title: 'a.ts', path: '/tmp/a.ts', id: 'editor:/tmp/a.ts', meta: { treeOpen: true }, + }) + const fileTab = (): SidebarTab => + allLeaves(store.getSnapshot().state!.bottomSplits).flatMap(leaf => leaf.tabs) + .find(tab => tab.path === '/tmp/a.ts')! + const { container, rerender, unmount } = await mountHostWithTreeWithCwd( + fakeCtx(service) as unknown as Context, store, fileTab, { onRender: () => { commits += 1 } }, + ) + try { + await waitForTreeRow(container, 'a.ts') + expect(treeAnswers().calls).toBe(1) + + await rerender(false) + commits = 0 + await act(async () => { window.dispatchEvent(new Event('focus')) }) + expect(treeAnswers().calls, 'a parked tree does not answer window focus').toBe(1) + // The parked panel must not even re-render on a focus bump: one state + // update would reconcile every row of a tree nobody can see. + expect(commits, 'a parked tree does not re-render on window focus').toBe(0) + + await rerender(true) + expect(treeAnswers().calls, 'the return re-lists the watched set once').toBe(2) + } finally { + unmount() + } + }) + it('keeps the bottom-workbench split for a tab that lives there', async () => { const store = createSidebarStore() const { service } = spyService(store) diff --git a/tests/file-tree-batch-load.spec.tsx b/tests/file-tree-batch-load.spec.tsx index d204fe5e..47875bae 100644 --- a/tests/file-tree-batch-load.spec.tsx +++ b/tests/file-tree-batch-load.spec.tsx @@ -84,16 +84,16 @@ class FakeSocket { interface Harness { container: HTMLDivElement - /** Re-render with a new expansion set; `refreshTick` only when bumping it. */ - rerender: (expanded: string[], refreshTick?: number) => void + /** Re-render with a new expansion set; `refreshTick`/`visible` only when changed. */ + rerender: (expanded: string[], refreshTick?: number, visible?: boolean) => void unmount: () => void } -function mountTree(expanded: string[] = DIRS, refreshTick = 0): Harness { +function mountTree(expanded: string[] = DIRS, refreshTick = 0, visible = true): Harness { const container = document.createElement('div') document.body.append(container) const root: Root = createRoot(container) - const render = (dirs: string[], tick: number): void => { + const render = (dirs: string[], tick: number, shown: boolean): void => { root.render(createElement(FileTree, { sessionId: 's1', cwd: '/tmp', @@ -105,15 +105,18 @@ function mountTree(expanded: string[] = DIRS, refreshTick = 0): Harness { refreshTick: tick, onUploadRequest: () => {}, busy: false, + visible: shown, })) } let tick = refreshTick - act(() => { render(expanded, tick) }) + let shown = visible + act(() => { render(expanded, tick, shown) }) return { container, - rerender: (dirs: string[], nextTick?: number) => { + rerender: (dirs: string[], nextTick?: number, nextVisible?: boolean) => { if (nextTick !== undefined) tick = nextTick - act(() => { render(dirs, tick) }) + if (nextVisible !== undefined) shown = nextVisible + act(() => { render(dirs, tick, shown) }) }, unmount: () => { act(() => { root.unmount() }); container.remove() }, } @@ -232,6 +235,29 @@ describe('FileTree level loading is batched', () => { expect(batchPaths(0)).toEqual(['/tmp', ...DIRS].sort()) }) + it('does no work while parked, then re-lists the watched set in ONE request when shown', async () => { + // The host keeps every visited tab body mounted. A parked tree must not + // answer refresh ticks or expansion changes (they are other tabs' work), + // and coming back must not fire one request per watched directory. + harness = mountTree(DIRS, 0, false) + await flush() + expect(fsTrees).not.toHaveBeenCalled() + + // Another tab of the same session expands a directory while this one is + // parked: the change is dropped, and the same expansion array is handed + // back when the tab returns (the shell keeps the session state's identity). + const parkedExpanded = [...DIRS, '/tmp/d9'] + harness.rerender(parkedExpanded, 1, false) + await flush() + expect(fsTrees).not.toHaveBeenCalled() + + harness.rerender(parkedExpanded, 1, true) + await flush() + expect(fsTrees).toHaveBeenCalledTimes(1) + expect(batchPaths(0)).toEqual(['/tmp', ...DIRS, '/tmp/d9'].sort()) + expect(fsTree).not.toHaveBeenCalled() + }) + it('re-lists ONLY the stale level when the directory watcher reports one', async () => { harness = mountTree(DIRS) await flush() diff --git a/tests/file-tree-dir-watch.spec.tsx b/tests/file-tree-dir-watch.spec.tsx index 108384f6..6c57e4ad 100644 --- a/tests/file-tree-dir-watch.spec.tsx +++ b/tests/file-tree-dir-watch.spec.tsx @@ -57,7 +57,7 @@ class FakeSocket { } } -function Probe(props: { dirs: string[]; root: string | undefined; visible: boolean; onStale: (dir: string) => void }): ReactNode { +function Probe(props: { dirs: string[]; root: string | undefined; visible: boolean; onStale: (dirs: readonly string[]) => void }): ReactNode { useDirectoryWatch({ sessionId: 's1', root: props.root, @@ -76,7 +76,7 @@ interface Harness { } function mountProbe( - onStale: (dir: string) => void, + onStale: (dirs: readonly string[]) => void, options: { visible?: boolean; dirs?: string[]; root?: string | undefined } = {}, ): Harness { const { visible = true, dirs = ['/tmp/a'] } = options @@ -184,7 +184,7 @@ describe('useDirectoryWatch', () => { act(() => { socket.frame({ dir: '/tmp/a', ok: false }) }) expect(onStale).not.toHaveBeenCalled() act(() => { socket.frame({ dir: '/tmp/a' }) }) - expect(onStale).toHaveBeenCalledWith('/tmp/a') + expect(onStale).toHaveBeenCalledWith(['/tmp/a']) // A malformed frame is ignored outright. act(() => { socket.frame({ nope: 1 }) }) expect(onStale).toHaveBeenCalledTimes(1) @@ -244,16 +244,16 @@ describe('useDirectoryWatch', () => { ]) // ...and every level is re-listed once: whatever changed while parked was // seen by nobody, so the parked listing may be minutes old. - expect(onStale.mock.calls.map(([dir]) => dir)).toEqual(['/tmp', '/tmp/a', '/tmp/a/b']) + expect(onStale.mock.calls.map(([dirs]) => dirs)).toEqual([['/tmp', '/tmp/a', '/tmp/a/b']]) // Re-rendering the same inputs refreshes nothing again. harness.rerender(['/tmp/a', '/tmp/a/b'], true) - expect(onStale).toHaveBeenCalledTimes(3) + expect(onStale).toHaveBeenCalledTimes(1) // A parked-unparked cycle repeats exactly once more. harness.rerender(['/tmp/a', '/tmp/a/b'], false) harness.rerender(['/tmp/a', '/tmp/a/b'], true) - expect(onStale).toHaveBeenCalledTimes(6) + expect(onStale).toHaveBeenCalledTimes(2) expect(FakeSocket.instances).toHaveLength(2) harness.unmount() }) From b1efd9226bb9d765de61e4123a91d8b011594299 Mon Sep 17 00:00:00 2001 From: Menghuan1918 Date: Sat, 24 Oct 2026 02:17:07 +0800 Subject: [PATCH 3/9] perf(sidechat): cache the per-row prose rewrite --- src/client/SideChatView.tsx | 43 +++++++++++++++++++++---- tests/sidechat-markdown-labels.spec.tsx | 34 +++++++++++++++++++ 2 files changed, 71 insertions(+), 6 deletions(-) diff --git a/src/client/SideChatView.tsx b/src/client/SideChatView.tsx index 767cc761..feb219de 100644 --- a/src/client/SideChatView.tsx +++ b/src/client/SideChatView.tsx @@ -479,8 +479,11 @@ function toolLeading(name: string, failed: boolean): React.ReactNode { * object so a row body never rebuilds them per render. */ interface RowSurface { /** The row's prose pass: local image destinations become session media URLs - * first, then the surface's local-link pass runs (see the view's wiring). */ - rewrite: (text: string) => string + * first, then the surface's local-link pass runs (see the view's wiring). + * Takes the ROW (not its text) so the view can reuse an unchanged row's + * rewrite result by object identity. Only prose rows (user / assistant) + * carry `text`; the other kinds never run this pass. */ + rewrite: (row: Extract) => string /** Open one delivered file through the plugin's own open path. */ openFile: (path: string) => void /** The session-scoped media URL of one image deliverable. */ @@ -499,7 +502,7 @@ function renderRow(row: SidechatTranscriptRow, labels: RowLabels, surface: RowSu case 'user': return (
- +
) case 'assistant': @@ -509,7 +512,7 @@ function renderRow(row: SidechatTranscriptRow, labels: RowLabels, surface: RowSu instead of restarting it; only the durable (settled) message is the final parse. It rides the row's own flag so a superseded live row never claims to be settled. */} - + ) case 'reasoning': @@ -746,6 +749,34 @@ export function SideChatView(props: { ), [rewriteChatLinks, scope], ) + /** The media URL base the rewrite bakes into image destinations. */ + const transportBase = hostTransportBase() + /** + * The row-level prose pass, memoized by ROW OBJECT: the transcript reuses an + * unchanged row's object across updates (`sidechat-transcript.ts`), so a + * composer keystroke or a streaming push must not re-run two regex passes + * over every unchanged row's text. The cache is rebuilt when the inputs the + * pass resolves against change (session, cwd, transport base); the row's own + * text is compared too, so a row mutated in place never serves a stale + * rewrite. + */ + const rewriteCache = useMemo(() => { + // The cache is keyed by rows, but its RESULTS were resolved against the + // session cwd and the transport base, so it must not outlive either. The + // reads below make the dependency real to the hook linter (the repo's + // `void wantedKey` idiom). + void scope.sessionId + void scope.cwd + void transportBase + return new WeakMap() + }, [scope.sessionId, scope.cwd, transportBase]) + const rewriteRow = useCallback((row: Extract): string => { + const cached = rewriteCache.get(row) + if (cached !== undefined && cached.text === row.text) return cached.out + const out = rewriteChatText(row.text) + rewriteCache.set(row, { text: row.text, out }) + return out + }, [rewriteCache, rewriteChatText]) /** Open one delivered file: the plugin's own editor path, session-scoped * like every other open in this view (a relative path resolves against the * session cwd). */ @@ -765,12 +796,12 @@ export function SideChatView(props: { const deliverableTitlePath = useCallback((path: string): string => resolveSidebarPath(scope.cwd, path), [scope.cwd]) const rowSurface = useMemo( () => ({ - rewrite: rewriteChatText, + rewrite: rewriteRow, openFile: openDeliveredFile, media: deliverableMediaUrl, resolvePath: deliverableTitlePath, }), - [rewriteChatText, openDeliveredFile, deliverableMediaUrl, deliverableTitlePath], + [rewriteRow, openDeliveredFile, deliverableMediaUrl, deliverableTitlePath], ) const transcriptRef = useCallback((element: HTMLDivElement | null) => { scrollRef.current = element diff --git a/tests/sidechat-markdown-labels.spec.tsx b/tests/sidechat-markdown-labels.spec.tsx index d60c2c1c..9ca2c447 100644 --- a/tests/sidechat-markdown-labels.spec.tsx +++ b/tests/sidechat-markdown-labels.spec.tsx @@ -32,6 +32,20 @@ const markdownRenders = vi.hoisted(() => ({ calls: [] as Array<{ text: string; streaming: boolean | undefined }>, })) +/** How many times the session-scoped prose pass ran (one call per row rewritten). */ +const rewriteCalls = vi.hoisted(() => ({ count: 0 })) + +vi.mock('../src/client/markdown-images.ts', async (importOriginal) => { + const actual = await importOriginal() + return { + ...actual, + rewriteProseLocalImageUrls: (...args: Parameters) => { + rewriteCalls.count += 1 + return actual.rewriteProseLocalImageUrls(...args) + }, + } +}) + vi.mock('@deepseek-ai/dsh-client-ui-primitives', async (importOriginal) => { const actual = await importOriginal() const react = await import('react') @@ -157,6 +171,26 @@ describe('SideChatView markdown re-parse (C3)', () => { view.unmount() }) + it('does not re-run the prose rewrite for unchanged rows on a composer keystroke', async () => { + harness.wire.events = settledConversation() + const view = harness.mount() + await harness.flush() + + // Guard: the rewrite really ran for the mounted rows (a mock that never + // applied would make the zero-delta assertion vacuous). + expect(rewriteCalls.count).toBeGreaterThan(0) + rewriteCalls.count = 0 + + harness.typeComposer('a') + await harness.flush() + harness.typeComposer('ab') + await harness.flush() + expect(harness.composerValue()).toBe('ab') + expect(rewriteCalls.count, 'a composer keystroke re-ran the prose rewrite for unchanged rows').toBe(0) + + view.unmount() + }) + it('passes streaming to an unsettled live row and not to the settled message', async () => { const settled = 'settled-answer' const live = 'live-token' From 2237f3787b05a1192689d91505fc5e15fa86da9d Mon Sep 17 00:00:00 2001 From: Menghuan1918 Date: Sat, 24 Oct 2026 02:17:10 +0800 Subject: [PATCH 4/9] perf(diff): parse a patch once and cap the default expansion --- src/client/changes/DiffPane.tsx | 18 ++++++++--- src/client/diff/DiffFiles.tsx | 38 +++++++++++++++++----- tests/diff-files-collapse.spec.tsx | 52 ++++++++++++++++++++++++++++++ 3 files changed, 96 insertions(+), 12 deletions(-) diff --git a/src/client/changes/DiffPane.tsx b/src/client/changes/DiffPane.tsx index 976b7f2d..e2929a3c 100644 --- a/src/client/changes/DiffPane.tsx +++ b/src/client/changes/DiffPane.tsx @@ -430,18 +430,27 @@ export function DiffPane({ target, ctx, scope, height, onHeightCommit, onClose, [htmlOp, scope, contentAbs], ) - // Header stats for git targets come off the parsed patch text. - const gitStats = useMemo(() => { + /** + * ONE parse of the patch per target: the header stats and the file rows both + * read it. Parsing an ≤8MB patch twice on the UI thread (once here for the + * stats, once inside DiffFiles) was visible when a large commit was opened. + */ + const gitParsed = useMemo(() => { if (target.kind !== 'git' || diffText === null || diffText === '') return null + return parseUnifiedDiff(diffText) + }, [target.kind, diffText]) + // Header stats for git targets come off that shared parse. + const gitStats = useMemo(() => { + if (gitParsed === null) return null let added = 0 let deleted = 0 - for (const file of parseUnifiedDiff(diffText).files) { + for (const file of gitParsed.files) { const stats = diffStats(unifiedSegments(file)) added += stats.added deleted += stats.deleted } return { added, deleted } - }, [target, diffText]) + }, [gitParsed]) // ── Resize: drag the top handle; commit on release (persisted by the // shell). Arrow keys resize by a step for keyboard users. ──────────── @@ -662,6 +671,7 @@ export function DiffPane({ target, ctx, scope, height, onHeightCommit, onClose, {((diffText !== null && diffText !== '') || untracked !== undefined) && ( { const expanded = new Set() + let budget = 0 files.forEach((file, index) => { const path = displayPath(file.newPath === '/dev/null' ? file.oldPath : file.newPath) - if (!file.binary && file.hunks.length > 0 + const isSource = !file.binary && file.hunks.length > 0 && !TEST_PATH.test(path) && !DOC_PATH.test(path) && !GENERATED_PATH.test(path) - && SOURCE_PATH.test(path)) { - expanded.add(index) - } + && SOURCE_PATH.test(path) + if (!isSource) return + const changedLines = file.hunks.reduce((total, hunk) => total + hunk.lines.length, 0) + if (expanded.size > 0 && budget + changedLines > DEFAULT_EXPANDED_LINE_BUDGET) return + expanded.add(index) + budget += changedLines }) return expanded } @@ -48,6 +64,12 @@ function fileTag(file: DiffFile): string | null { export interface DiffFilesProps { /** Unified diff text (`git.diff` or `git.commit-diff` payloads). */ diff: string + /** A parse the caller ALREADY did for its own header stats: rendering the + * same ≤8MB patch twice on the UI thread was visible on large commits. The + * component trusts it as-is (the changes pane passes the parse it just + * summarized); omit it to parse `diff` here. Ignored for untracked files, + * whose synthetic full-file addition comes from their content. */ + parsed?: ParsedDiff /** Untracked-file content: when present, renders as a full-file addition instead of parsing. */ untrackedPath?: string untrackedContent?: string @@ -58,13 +80,13 @@ export interface DiffFilesProps { resolveFold?: (file: DiffFile, segment: FoldSegment) => Promise } -export function DiffFiles({ diff, untrackedPath, untrackedContent, resolveFold }: DiffFilesProps) { +export function DiffFiles({ diff, parsed: provided, untrackedPath, untrackedContent, resolveFold }: DiffFilesProps) { const parsed = useMemo(() => { if (untrackedPath !== undefined) { return { files: [untrackedFile(untrackedPath, untrackedContent ?? '')] } } - return parseUnifiedDiff(diff) - }, [diff, untrackedPath, untrackedContent]) + return provided ?? parseUnifiedDiff(diff) + }, [provided, diff, untrackedPath, untrackedContent]) const [expandedFiles, setExpandedFiles] = useState>(() => defaultExpandedFiles(parsed.files)) useEffect(() => { setExpandedFiles(defaultExpandedFiles(parsed.files)) }, [parsed]) diff --git a/tests/diff-files-collapse.spec.tsx b/tests/diff-files-collapse.spec.tsx index 408c6701..1e7a3bc5 100644 --- a/tests/diff-files-collapse.spec.tsx +++ b/tests/diff-files-collapse.spec.tsx @@ -4,6 +4,7 @@ import { createElement } from 'react' import { createRoot, type Root } from 'react-dom/client' import { act } from 'react-dom/test-utils' import { DiffFiles } from '../src/client/diff/DiffFiles.tsx' +import { parseUnifiedDiff } from '../src/client/diff/rows.ts' import { setupReactAct } from './test-utils.ts' setupReactAct() @@ -57,4 +58,55 @@ describe('DiffFiles file folding', () => { container.remove() } }) + + it('caps the default expansion by changed lines, not by file count', () => { + // Six source files of 600 changed lines each: the first three fill the + // 2000-line budget, so the other three start folded (their headers still + // carry the +/− stats and can be opened one by one). + const parts: string[] = [] + for (let file = 0; file < 6; file += 1) { + parts.push( + `diff --git a/src/f${file}.ts b/src/f${file}.ts`, + `--- a/src/f${file}.ts`, + `+++ b/src/f${file}.ts`, + '@@ -1,300 +1,300 @@', + ) + for (let line = 0; line < 300; line += 1) parts.push(`-old-${file}-${line}`, `+new-${file}-${line}`) + } + const container = document.createElement('div') + document.body.append(container) + const root: Root = createRoot(container) + try { + act(() => { root.render(createElement(DiffFiles, { diff: parts.join('\n') })) }) + const headers = [...container.querySelectorAll('button[aria-expanded]')] + expect(headers).toHaveLength(6) + expect(headers.map(header => header.getAttribute('aria-expanded'))) + .toEqual(['true', 'true', 'true', 'false', 'false', 'false']) + // Only the three budgeted files mount their rows (600 each; the pairs + // render as `mod`, so count every change class and not just `add`). + expect(container.querySelectorAll('[data-kind="add"], [data-kind="del"], [data-kind="mod"], [data-kind="context"]')) + .toHaveLength(1800) + } finally { + act(() => { root.unmount() }) + container.remove() + } + }) + + it('renders the caller-supplied parse instead of parsing the patch again', () => { + // The changes pane parses one patch for BOTH its header stats and these + // rows; a second parse of an ≤8MB patch on the UI thread was the cost. + const parsed = parseUnifiedDiff(diff) + const container = document.createElement('div') + document.body.append(container) + const root: Root = createRoot(container) + try { + act(() => { root.render(createElement(DiffFiles, { diff: 'not a unified diff', parsed })) }) + const headers = [...container.querySelectorAll('button[aria-expanded]')] + expect(headers).toHaveLength(3) + expect(container.textContent).toContain('new-a') + } finally { + act(() => { root.unmount() }) + container.remove() + } + }) }) From 0a4a94c7047c2ded13bbcd66db6e25d0a58fd1ab Mon Sep 17 00:00:00 2001 From: Menghuan1918 Date: Sat, 24 Oct 2026 02:17:10 +0800 Subject: [PATCH 5/9] perf(graph): window the commit history rows --- src/client/changes/GitGraphSection.tsx | 57 ++++++++++++++++++-- src/client/changes/git-graph-windowing.ts | 64 +++++++++++++++++++++++ tests/e2e/git-graph.e2e.ts | 8 ++- tests/git-graph-ui.spec.tsx | 47 +++++++++++++++++ tests/git-graph-windowing.spec.ts | 56 ++++++++++++++++++++ 5 files changed, 226 insertions(+), 6 deletions(-) create mode 100644 src/client/changes/git-graph-windowing.ts create mode 100644 tests/git-graph-windowing.spec.ts diff --git a/src/client/changes/GitGraphSection.tsx b/src/client/changes/GitGraphSection.tsx index 8572a4ee..a3962fda 100644 --- a/src/client/changes/GitGraphSection.tsx +++ b/src/client/changes/GitGraphSection.tsx @@ -7,7 +7,7 @@ * Mounted by {@link GitLens} on the repo/worktree target the lens has already * selected; it owns its own bounded page (`git.graph`) and reports the * selected commit upward for the tab's bottom pane (`details` tab). */ -import { useEffect, useMemo, useRef, useState, type MouseEvent } from 'react' +import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type MouseEvent } from 'react' import { Button, IconBranchOutlineRegular, IconCheckOutlineRegular, IconGlobeOutlineRegular, } from '@deepseek-ai/dsh-client-ui-primitives' @@ -17,6 +17,8 @@ import { relativeTime, t } from '../locales.ts' import { Notice } from '../ui/index.ts' import { AnchoredPopover } from '../AnchoredPopover.tsx' import { edgePath, layoutGraph } from './graph-layout.ts' +import { createFrameBatcher } from '../frame-batcher.ts' +import { windowedRange } from './git-graph-windowing.ts' import css from './graph.module.css' type GraphPage = Awaited> @@ -138,6 +140,38 @@ export function GitGraphSection({ scope, worktree, visible, refreshTick = 0, onP const appending = useRef(false) const scrollRef = useRef(null) const sentinelRef = useRef(null) + /** + * The scroll container's measured viewport, and the per-frame coalescer that + * keeps it in step with a scroll stream (a trackpad fires several scroll + * events per display frame; one commit per frame is enough to move the + * window, and each commit reads layout once). + */ + const [view, setView] = useState({ scrollTop: 0, height: 0 }) + const scrollBatcher = useRef(createFrameBatcher()).current + const syncWindow = useCallback((): void => { + const node = scrollRef.current + if (node === null) return + const scrollTop = node.scrollTop + const height = node.clientHeight + setView(current => (current.scrollTop === scrollTop && current.height === height + ? current + : { scrollTop, height })) + }, []) + // A page append/shrink changes the content under the scroll position; the + // browser clamps a stale scrollTop only after the DOM commit, so re-read it + // in the layout phase. The pure range function clamps anyway. + useLayoutEffect(() => { syncWindow() }, [syncWindow, page?.entries.length]) + // A panel resize (the details pane opening, a window resize, the sidebar + // width drag) changes how many rows fit: re-measure so the mounted window + // still covers the viewport instead of leaving a blank band. + useEffect(() => { + const node = scrollRef.current + if (node === null || typeof ResizeObserver === 'undefined') return + const observer = new ResizeObserver(() => { syncWindow() }) + observer.observe(node) + return () => { observer.disconnect() } + }, [syncWindow]) + useEffect(() => () => { scrollBatcher.dispose() }, [scrollBatcher]) /** Row hover preview: the middle information rung between the one-line row * (pills + subject) and the details card (everything). It opens only after * a short dwell so scrolling past rows never flashes cards; the pointer @@ -227,6 +261,12 @@ export function GitGraphSection({ scope, worktree, visible, refreshTick = 0, onP const rows = useMemo(() => layoutGraph(page?.entries ?? []), [page?.entries]) const width = Math.max(28, ...rows.map(row => laneX(row.laneCount) + 2)) + const range = windowedRange({ + count: page?.entries.length ?? 0, + rowHeight: ROW_HEIGHT, + scrollTop: view.scrollTop, + viewportHeight: view.height, + }) const remotes = useMemo(() => remoteRefNames(branches), [branches]) const selectedIndex = selectedRef?.kind === 'commit' && selectedRef.worktree === worktree @@ -262,7 +302,8 @@ export function GitGraphSection({ scope, worktree, visible, refreshTick = 0, onP setPage(null) } - return
+ return
-
+
{ + // The window may unmount the row the hover card is anchored to. + if (hover !== null || hoverTimer.current !== null) cancelHover() + scrollBatcher.schedule(syncWindow) + }}> {error !== null &&
{stale ? t('graphStale') : t('graphLoadError')}{!stale && `: ${error}`}
} {loading &&
{t('loading')}
} {!loading && !error && page !== null && page.entries.length === 0 &&
{t(page.isRepo ? 'graphEmpty' : 'notRepo')}
} - {page?.entries.map((entry, index) => { + {range.top > 0 &&