From 31dc3b4572ec23a880380c7cb19044a058c4ceb5 Mon Sep 17 00:00:00 2001 From: unsc9 <438590997@qq.com> Date: Sun, 25 Oct 2026 20:41:54 +0800 Subject: [PATCH] perf(sidebar): give every consumer one stable session scope MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A tab body keys memos and effects off `scope` (the diff pane resolves its media/html routes from it, the editor restores its preview scroll, the side chat rebuilds its prose-rewrite cache), but the tab cell built `{ sessionId, cwd }` fresh on every render. Every such dependency therefore looked changed whenever the cell re-rendered — which the memo comparator allows exactly when a COMPARED field moves: `expanded` on a directory toggle, plus `revealed`, `localeRevision`, `tabsVersion`. The diff preview then re-ran its whole-document rewrite and its content tab re-issued a whole-file `fs.read`, flashing its loading row. `useSessionScope` is now the one place a scope for a component tree is built; the tab cell, the diff tab, the native tab adapter, and the shell's badge / rightActions / `+` menu / lifecycle-callback seams all use it. Those last ones are documented external plug-in surfaces, so a plug-in memoizing on `scope` stops churning on every unrelated re-render too. Stabilizing the object removes the only path the diff pane's `content` tab had to re-read after the file changed on disk, so the header's refresh button now drives it explicitly (the pane owns the gesture; the loader no longer leaks its internal counter). Seven comments asserted that the scope object's identity churns on every render; that premise is gone, so the ones that still apply say what they actually guard. --- CHANGELOG.md | 1 + src/client/DiffTab.tsx | 6 +- src/client/EditorHost.tsx | 7 +- src/client/PdfView.tsx | 3 +- src/client/Sidebar.tsx | 26 +++-- src/client/TextEditor.tsx | 4 +- src/client/builtins/tabs.tsx | 2 +- src/client/changes/ChangesTab.tsx | 3 +- src/client/changes/DiffPane.tsx | 14 ++- src/client/diff/use-git-diff.ts | 4 +- src/client/native/tab-adapter.tsx | 5 +- src/client/ops-stream.ts | 4 +- src/client/session-scope.ts | 34 +++++++ src/client/sidebar/TabContent.tsx | 9 +- tests/diff-git-target.spec.tsx | 58 ++++++++++- tests/tab-content-scope.spec.tsx | 159 ++++++++++++++++++++++++++++++ 16 files changed, 300 insertions(+), 39 deletions(-) create mode 100644 src/client/session-scope.ts create mode 100644 tests/tab-content-scope.spec.tsx diff --git a/CHANGELOG.md b/CHANGELOG.md index 6326c730..1de9f730 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,7 @@ ### 未发布 +- ⚡ **页签内容不再因无关重渲染而重读整份文件**:页签 body 拿到的 `scope` 对象此前每次渲染都新建,而编辑器、差异预览、侧聊都拿它当记忆化/副作用的依赖;只要某个**被比较的字段**变了(在文件树里展开目录走 `expanded`,以及 `revealed`、语言切换、页签注册表更新),差异预览就会重跑全文改写、「内容」页重新读取整份文件并闪一下加载态。现在 `scope` 由 `useSessionScope` 按会话与 cwd 缓存,页签内容、差异页签、以及徽标 / 右侧动作区 / `+` 菜单的注册表接口共用同一份稳定对象(后三者是对外部插件公开的接口,插件对 `scope` 做记忆化不再逐渲染失效)。差异预览「内容」页的刷新改由表头刷新按钮驱动——它此前只靠这种副作用顺带刷新,改稳之后会失去刷新路径。 - ⚡ **卡顿扫描与一轮低风险收敛**(前端页面 + 宿主 `/sidebar/*` 请求;逐条取证与误报核实见[扫描记录](docs/plans/2026-10-24-perf-scan.md)): - **文件树在隐藏页签里不再干活**:宿主把访问过的页签 body 常驻挂载,此前每个隐藏的文件树仍会在窗口获得焦点、刷新 tick 或另一个树展开目录时发 `fs.trees` 并重渲染整棵树;现在停靠树在隐藏时不加载(含折叠链预加载:隐藏后才返回的在飞层不会再拉下一节)、不监听焦点刷新,重新可见时由目录 watcher 对整套被 watch 的目录发一次批量 `fs.trees`(此前是每目录一次 POST;隐藏期间恰好没有缓存且展开集身份同时变化时最多两批,超过宿主 64 条路径上限仍按上限拆批)。 - **任务图滚轮缩放改为每帧一次提交**:高回报率滚轮/触控板此前每个 wheel 事件都重绘整张图,且每帧只保住一步缩放;现在与平移共用 `frame batcher`,同一帧的缩放量按步夹紧后完整复合、只提交一次(与逐帧应用等价);背景拖拽期间滚轮让位给拖拽,避免两种手势互相覆盖。 diff --git a/src/client/DiffTab.tsx b/src/client/DiffTab.tsx index 18f63e8e..9ff56819 100644 --- a/src/client/DiffTab.tsx +++ b/src/client/DiffTab.tsx @@ -10,7 +10,6 @@ * untracked fallbacks and the per-file fold cache cannot drift apart); * rendering goes through the shared {@link DiffFiles} renderer. */ -import { useMemo } from 'react' import { IconRefreshOutlineRegular } from '@deepseek-ai/dsh-client-ui-primitives' import type { SessionScope } from './api.ts' import type { SidebarDiffRef } from './state.ts' @@ -19,9 +18,8 @@ import { useGitDiffTarget } from './diff/use-git-diff.ts' import { t } from './locales.ts' import css from './sidebar.module.css' -export function DiffTab(props: { sessionId: string; cwd: string | undefined; diff: SidebarDiffRef }) { - const { sessionId, cwd, diff } = props - const scope = useMemo(() => ({ sessionId, cwd }), [sessionId, cwd]) +export function DiffTab(props: { scope: SessionScope; diff: SidebarDiffRef }) { + const { scope, diff } = props const { loading, error, diffText, untracked, refresh, resolveFold } = useGitDiffTarget(diff, scope) return ( diff --git a/src/client/EditorHost.tsx b/src/client/EditorHost.tsx index cadcaced..9a8f7d8e 100644 --- a/src/client/EditorHost.tsx +++ b/src/client/EditorHost.tsx @@ -479,8 +479,8 @@ export function EditorHost(props: { } apply(planFirstMatch(ctx.get('betterSidebar')?.matchFileViewer(path), mediaUrlOf)) return () => { cancelled = true; controller.abort() } - // The deps are deliberately granular: the scope object's identity churns, - // only its sessionId / cwd fields gate the (re)fetch. + // Granular deps: only these two fields gate the (re)fetch (see + // session-scope.ts for why the object itself is no longer a signal). // eslint-disable-next-line react-hooks/exhaustive-deps }, [scope.sessionId, scope.cwd, path, ctx, showEmpty, isDir, reloadSeq]) @@ -532,8 +532,7 @@ export function EditorHost(props: { // button stays the explicit escape hatch in both cases. if (toolbar?.dirty === true || toolbar?.mode === 'edit') return setReloadSeq(sequence => sequence + 1) - // Granular deps: the scope object's identity churns, so only its - // sessionId / cwd fields gate this decision. + // Granular deps: only the two scope fields gate this decision. }, [ops, path, scope.sessionId, scope.cwd, toolbar?.dirty, toolbar?.mode]) const treeOpen = treeOpenOf(tab) diff --git a/src/client/PdfView.tsx b/src/client/PdfView.tsx index 8cb7ab32..4f65debd 100644 --- a/src/client/PdfView.tsx +++ b/src/client/PdfView.tsx @@ -40,8 +40,7 @@ export function PdfView(props: { scope: SessionScope; path: string; title: strin controller.abort() if (objectUrl !== undefined) URL.revokeObjectURL(objectUrl) } - // Granular scope fields: the scope object's identity churns, only its - // sessionId / cwd fields gate the fetch. + // Granular scope fields: only these two gate the fetch. // eslint-disable-next-line react-hooks/exhaustive-deps }, [scope.sessionId, scope.cwd, path]) diff --git a/src/client/Sidebar.tsx b/src/client/Sidebar.tsx index ae6b41b7..7a6a0827 100644 --- a/src/client/Sidebar.tsx +++ b/src/client/Sidebar.tsx @@ -52,6 +52,7 @@ import { useRightPanelOpen } from './sidebar/right-panel-open.ts' import type { TabDragPayload } from './TabBar.tsx' import { t } from './locales.ts' import { useSessionRoot } from './use-session-root.ts' +import { useSessionScope } from './session-scope.ts' import css from './sidebar.module.css' /** @@ -268,18 +269,22 @@ export function Sidebar(props: { ctx: Context; store: SidebarStore }) { // signal `renderTab` already gates its tab bodies on, so a collapsed shell // holds no session-root timer (the store adds `document.hidden` on top). const cwd = useSessionRoot(ctx, sessionId, { visible: state?.bottomOpen === true }) + // The scope the registry seams receive (badge / rightActions / + menu). Stable + // by content (session-scope.ts): external plugins may memoize on it, and it is + // rebuilt in three different callbacks below. + const shellScope = useSessionScope(sessionId, cwd) // The + menu options ride a memo so the workbench does not rebuild the // array identity across renders that did not change the store (drag state, // viewport resize): fresh arrays per render re-rendered every LeafView's // + affordance whether or not anything tab-related moved. const newTabOptions = useMemo( - () => (state === undefined || sessionId === undefined ? [] : buildNewTabOptions(state, ctx, { sessionId, cwd })), + () => (state === undefined || shellScope === undefined ? [] : buildNewTabOptions(state, ctx, shellScope)), // state is the whole session state — every field it wraps is fair game // for the descriptors' available() callbacks. (The render's own guard // sits below every hook; this memo must handle the no-session case // itself.) - [state, ctx, sessionId, cwd], + [state, ctx, shellScope], ) // Host feeds (sidebar/use-host-feeds.ts): the agent-opens WebSocket push @@ -496,13 +501,13 @@ export function Sidebar(props: { ctx: Context; store: SidebarStore }) { // Route through the service: the tab-bar close is the canonical close // path (finds the pane itself, fires descriptor.onClose); the session // scope (with its cwd) rides to the callback. - ctx.get('betterSidebar')?.closeTab(tabId, sessionId === undefined ? undefined : { sessionId, cwd }) + ctx.get('betterSidebar')?.closeTab(tabId, shellScope) }, activateTab: (paneId, tabId) => { // Route through the service: same reducer (finds the pane, sets the // active pane) and fires descriptor.onActivate; the session scope // (with its cwd) rides to the callback. - ctx.get('betterSidebar')?.activateTab(tabId, sessionId === undefined ? undefined : { sessionId, cwd }) + ctx.get('betterSidebar')?.activateTab(tabId, shellScope) }, focusPane: (paneId) => { store.reduce(s => ({ ...s, activePane: paneId })) }, moveTabToEdge: (payload: TabDragPayload, toPane: string, zone: DropZone) => { @@ -521,7 +526,8 @@ export function Sidebar(props: { ctx: Context; store: SidebarStore }) { resizeSplit: (splitId, index, deltaFrac) => { store.reduce(s => resizeSplitIn(s, splitId, index, deltaFrac)) }, - }), [store, sessionId, cwd, ctx]) + // shellScope carries cwd (memoized on sessionId+cwd), so it stands in for it. + }), [store, sessionId, ctx, shellScope]) /** * The explorer's @-reference button. The token is spelled against the @@ -581,7 +587,7 @@ export function Sidebar(props: { ctx: Context; store: SidebarStore }) { // The session scope rides along: lifecycle callbacks receive it. The // open is bottom-targeted so the tab lands in THIS workbench, not in the // native right Sidebar. - service.openTab({ type: optionId, title, target: 'bottom' }, { sessionId, cwd }) + service.openTab({ type: optionId, title, target: 'bottom' }, shellScope) } /** @@ -607,10 +613,10 @@ export function Sidebar(props: { ctx: Context; store: SidebarStore }) { */ const tabBadgeOf = (tab: SidebarTab): ReactNode => { const descriptor = ctx.get('betterSidebar')?.getTab(tab.type) - if (descriptor?.badge === undefined) return null + if (descriptor?.badge === undefined || shellScope === undefined) return null let value: string | number | null | undefined try { - value = descriptor.badge(ctx, { sessionId, cwd }, state) + value = descriptor.badge(ctx, shellScope, state) } catch (error) { console.error('[dsh-better-sidebar] tab badge error:', error) return null @@ -639,9 +645,9 @@ export function Sidebar(props: { ctx: Context; store: SidebarStore }) { */ const tabRightActionsOf = (tab: SidebarTab, paneId: string): ReactNode => { const descriptor = ctx.get('betterSidebar')?.getTab(tab.type) - if (descriptor?.rightActions === undefined) return null + if (descriptor?.rightActions === undefined || shellScope === undefined) return null try { - return descriptor.rightActions(ctx, { sessionId, cwd }, state, tab, paneId) + return descriptor.rightActions(ctx, shellScope, state, tab, paneId) } catch (error) { console.error('[dsh-better-sidebar] tab rightActions error:', error) return null diff --git a/src/client/TextEditor.tsx b/src/client/TextEditor.tsx index 1a87dd11..90ffcb2e 100644 --- a/src/client/TextEditor.tsx +++ b/src/client/TextEditor.tsx @@ -180,8 +180,8 @@ export function TextEditor(props: FileViewerProps) { /** Bumped by every save: the uncommitted diff moved while the file's git * status entry (which only tracks its XY code) did not. */ const [gitRevision, setGitRevision] = useState(0) - /** The view-side identity of the gutter's git source (stable across the - * scope object's per-render identity churn). */ + /** The view-side identity of the gutter's git source: rebuilt only when a + * field it reads actually moves. */ const gitHost = useMemo( () => ({ scope: { sessionId: scope.sessionId, cwd: scope.cwd, repoRoot: scope.repoRoot }, path }), [scope.sessionId, scope.cwd, scope.repoRoot, path], diff --git a/src/client/builtins/tabs.tsx b/src/client/builtins/tabs.tsx index 4472dc32..3a8a52df 100644 --- a/src/client/builtins/tabs.tsx +++ b/src/client/builtins/tabs.tsx @@ -318,7 +318,7 @@ export function builtinTabs(ctx: Context): readonly TabDescriptor[] { dedupeKey: (tab) => tab.id, component: ({ scope, tab }) => ( tab.diff === undefined ? null - : + : ), }, ] diff --git a/src/client/changes/ChangesTab.tsx b/src/client/changes/ChangesTab.tsx index 385747a7..c6b18475 100644 --- a/src/client/changes/ChangesTab.tsx +++ b/src/client/changes/ChangesTab.tsx @@ -152,8 +152,7 @@ export function ChangesTab({ ctx, store, scope, tab, visible, onOpenFile, onOpen } finally { if (generation === pollGen.current) pullingRef.current = false } - // Granular scope fields: the scope object's identity churns, only its - // sessionId / cwd fields gate the poll target. + // Granular scope fields: only these two gate the poll target. // eslint-disable-next-line react-hooks/exhaustive-deps }, [scope.sessionId, scope.cwd]) useEffect(() => { diff --git a/src/client/changes/DiffPane.tsx b/src/client/changes/DiffPane.tsx index e2929a3c..8f653702 100644 --- a/src/client/changes/DiffPane.tsx +++ b/src/client/changes/DiffPane.tsx @@ -308,6 +308,11 @@ export function DiffPane({ target, ctx, scope, height, onHeightCommit, onClose, const [gitContent, setGitContent] = useState< { status: 'idle' | 'loading' | 'binary' | 'large' } | { status: 'text'; text: string } | { status: 'error'; error: string } >({ status: 'idle' }) + // The pane owns the refresh GESTURE: the header button bumps this, and both + // loaders reload on it. The scope is stable, so a plain re-render no longer + // re-reads the file as a side effect — without this the content tab would + // keep bytes read before the file changed, and it has no other reload path. + const [refreshSeq, setRefreshSeq] = useState(0) useEffect(() => { if (gitWorktree === null) { setGitContent({ status: 'idle' }); return } // Deferred until the content view is the one on screen: opening a file to @@ -327,7 +332,7 @@ export function DiffPane({ target, ctx, scope, height, onHeightCommit, onClose, setGitContent({ status: 'error', error: reason instanceof Error ? reason.message : String(reason) }) }) return () => { controller.abort() } - }, [gitWorktree, scope, active]) + }, [gitWorktree, scope, active, refreshSeq]) // ── Op target material (pure snapshots; the prior content came with the // target so a running op shows what is already known). ──────────────── @@ -589,7 +594,12 @@ export function DiffPane({ target, ctx, scope, height, onHeightCommit, onClose, icon={} label={t('refresh')} disabled={loading} - onClick={refresh} + onClick={() => { + // Both views reload: the patch (refresh) and the whole-file + // content tab, which read its bytes through its own fs.read. + refresh() + setRefreshSeq(sequence => sequence + 1) + }} /> (null) - // Granular scope fields: the scope object's identity churns, only these - // three gate the target (the same rule the sibling call sites used). + // Granular scope fields: only these three gate the target (this hook also + // accepts a caller-assembled scope). const sessionId = scope.sessionId const cwd = scope.cwd const repoRoot = ref?.repoRoot diff --git a/src/client/native/tab-adapter.tsx b/src/client/native/tab-adapter.tsx index 2a3d67e8..78813de7 100644 --- a/src/client/native/tab-adapter.tsx +++ b/src/client/native/tab-adapter.tsx @@ -23,7 +23,7 @@ * Nothing here is a singleton: the registry is created once per client * activation and handed to every registration. */ -import { createElement, useEffect, useMemo, useSyncExternalStore } from 'react' +import { createElement, useEffect, useSyncExternalStore } from 'react' import type { ComponentType, ReactNode } from 'react' import type { Context } from '../../context-types.ts' import type { SessionScope } from '../api.ts' @@ -33,6 +33,7 @@ import { ContextDiagnosticsHost } from '../context-diagnostics-ui.tsx' import type { ContextDiagnostics } from '../context-diagnostics.ts' import { referenceInChat } from '../reference-in-chat.ts' import { useSessionRoot } from '../use-session-root.ts' +import { useSessionScope } from '../session-scope.ts' import type { BetterSidebarService, NativePathTab } from '../service.ts' import { t } from '../locales.ts' import { isUnread, toggleExpanded } from '../state.ts' @@ -496,7 +497,7 @@ export function NativeTabBody(props: NativeBodyInjected & NativeBodyFrameworkPro // visited tab body mounted, so an un-gated 5 s `session.cwd` per body is one // host-side `git` spawn per tab per tick, forever. const cwd = useSessionRoot(ctx, scopeSessionId, { visible: nativeTab.visible }) - const scope = useMemo((): SessionScope => ({ sessionId: scopeSessionId, cwd }), [scopeSessionId, cwd]) + const scope = useSessionScope(scopeSessionId, cwd) // `version` is not read: it only forces this render when the record changed. void version const derived = props.paramsOf?.(info) diff --git a/src/client/ops-stream.ts b/src/client/ops-stream.ts index aae48e1f..35796a96 100644 --- a/src/client/ops-stream.ts +++ b/src/client/ops-stream.ts @@ -309,8 +309,8 @@ export function useFileOpStream(scope: SessionScope, enabled: boolean): FileOpSt } }, [enabled, sessionId]) - // Granular scope fields: the scope object's identity churns every render, - // only its sessionId / cwd gate the request target. + // Granular scope fields: only these two gate the request target (callers + // may assemble a scope object themselves). const cwd = scope.cwd const pull = useCallback(async (signal: AbortSignal): Promise => { await pullStream(streamOf(sessionId), { sessionId, cwd }, signal) diff --git a/src/client/session-scope.ts b/src/client/session-scope.ts new file mode 100644 index 00000000..3ff86029 --- /dev/null +++ b/src/client/session-scope.ts @@ -0,0 +1,34 @@ +/** + * The one place a {@link SessionScope} object is built for a component tree. + * + * A scope is handed to tab bodies, badges, right-actions and the + menu, and + * those key memos and effects off it. Building `{ sessionId, cwd }` inline on + * every render made every such dependency look changed whenever the sidebar + * shell re-rendered, so the same bug kept reappearing one call site at a time + * (the tab cell's diff preview re-ran its whole-document rewrite and its + * content tab re-issued a whole-file `fs.read`; a badge or an external + * plugin's memo would churn the same way). + * + * Consumers that hand a scope to a tab body must use this; consumers that only + * build one to pass INTO an api call (`api.fsRead({ sessionId, cwd }, …)`) do + * not — the object never outlives the call there. + */ +import { useMemo } from 'react' +import type { SessionScope } from './api.ts' + +/** + * A scope object keyed by CONTENT: the same object is returned across renders + * until the session or the cwd really changes. + * + * @param sessionId - the conversation id, or `undefined` for a shell mounted + * with no conversation selected (the scope is then absent). + * @param cwd - the session's working directory, when known. + */ +export function useSessionScope(sessionId: string, cwd: string | undefined): SessionScope +export function useSessionScope(sessionId: string | undefined, cwd: string | undefined): SessionScope | undefined +export function useSessionScope(sessionId: string | undefined, cwd: string | undefined): SessionScope | undefined { + return useMemo( + () => (sessionId === undefined ? undefined : { sessionId, cwd }), + [sessionId, cwd], + ) +} diff --git a/src/client/sidebar/TabContent.tsx b/src/client/sidebar/TabContent.tsx index 9a729f3e..5dc18871 100644 --- a/src/client/sidebar/TabContent.tsx +++ b/src/client/sidebar/TabContent.tsx @@ -8,6 +8,7 @@ import { createElement, memo } from 'react' import type { Context } from '../../context-types.ts' import type { SidebarState, SidebarStore, SidebarTab } from '../state.ts' import type { SessionScope } from '../api.ts' +import { useSessionScope } from '../session-scope.ts' import { OrphanedTab } from '../OrphanedTab.tsx' import { RenderBoundary } from '../RenderBoundary.tsx' import { tabContentCompare, type TabContentMemoKey } from '../tab-content-memo.ts' @@ -34,7 +35,13 @@ interface TabContentProps extends TabContentMemoKey { /** Render the content of one tab (dispatched by type). */ export const TabContent = memo(function TabContent(props: TabContentProps) { const { tab, sessionId, cwd, expanded, revealed, onToggleDir, onReferenceFile, ctx, store, visible, onSubagentJump, onOpenDiff } = props - const scope = { sessionId, cwd } + // Stable by content (see session-scope.ts): a tab body keys its memos and + // effects off this object, so rebuilding it per render made every such + // dependency look changed whenever a COMPARED field moved — a directory + // toggle (`expanded`), a reveal, a locale switch. The diff preview then + // re-ran its whole-document rewrite and its content tab re-issued a + // whole-file `fs.read`, flashing its loading row. + const scope = useSessionScope(sessionId, cwd) const descriptor = ctx.get('betterSidebar')?.getTab(tab.type) if (descriptor === undefined) { return diff --git a/tests/diff-git-target.spec.tsx b/tests/diff-git-target.spec.tsx index ef127873..57d64a25 100644 --- a/tests/diff-git-target.spec.tsx +++ b/tests/diff-git-target.spec.tsx @@ -17,8 +17,9 @@ import { api } from '../src/client/api.ts' import type { Context } from '../src/context-types.ts' import type { SessionScope } from '../src/client/api.ts' import type { SidebarDiffRef } from '../src/client/state.ts' +import { t } from '../src/client/locales.ts' -import { setupReactAct } from './test-utils.ts' +import { setupReactAct, renderRoot } from './test-utils.ts' setupReactAct() const SCOPE: SessionScope = { sessionId: 's1', cwd: '/p' } @@ -120,6 +121,55 @@ describe('useGitDiffTarget through the inline preview pane (DiffPane)', () => { container.remove() } }) + + /** + * The `content` tab holds bytes from its OWN `fs.read`, not from the patch + * the rest of the pane shows. The header's refresh button only bumps the + * diff loader's counter, so unless the content effect listens to that + * counter the tab keeps serving bytes read before the file changed — and it + * has no other reload path (the scope is stable, so re-renders no longer + * re-read as a side effect). + */ + it('re-reads the content tab on the header refresh button', async () => { + const worktree: SidebarDiffRef = { kind: 'worktree', path: 'src/a.ts', staged: false } + vi.spyOn(api, 'gitDiff').mockResolvedValue({ diff: STAGED_PATCH }) + const read = vi.spyOn(api, 'fsRead') + .mockResolvedValueOnce({ kind: 'text', content: 'first-bytes', size: 11 }) + .mockResolvedValue({ kind: 'text', content: 'second-bytes', size: 12 }) + + // The pane hosts its own tab state only through `onSelectTab`; without it + // the strip renders but `onSelect` is a no-op, so the test drives the + // selection the way the changes tab does. + const mounted = renderRoot(createElement(DiffPane, { + target: { kind: 'git', ref: worktree }, + ctx: {} as Context, + scope: SCOPE, + height: 300, + activeTab: 'content', + onSelectTab: () => {}, + onHeightCommit: () => {}, + onClose: () => {}, + onExpand: () => {}, + })) + try { + await flushEffects() + + // The content tab loads lazily, only while on screen. + expect(mounted.container.textContent).toContain('first-bytes') + + // The refresh button must reload it, since nothing else can. Selected by + // the locale-aware label the rest of this suite uses. + const refreshButton = mounted.container.querySelector(`button[aria-label="${t('refresh')}"]`) + expect(refreshButton).not.toBeNull() + await act(async () => { refreshButton!.click() }) + await flushEffects() + + expect(read.mock.calls.length).toBeGreaterThanOrEqual(2) + expect(mounted.container.textContent).toContain('second-bytes') + } finally { + mounted.unmount() + } + }) }) describe('useGitDiffTarget through the dedicated diff tab (DiffTab)', () => { @@ -132,8 +182,7 @@ describe('useGitDiffTarget through the dedicated diff tab (DiffTab)', () => { try { act(() => { root.render(createElement(DiffTab, { - sessionId: 's1', - cwd: '/p', + scope: SCOPE, diff: { kind: 'commit', hash: 'abc1234', hashFull: 'a'.repeat(40), subject: 'subject' }, })) }) @@ -156,8 +205,7 @@ describe('useGitDiffTarget through the dedicated diff tab (DiffTab)', () => { try { act(() => { root.render(createElement(DiffTab, { - sessionId: 's1', - cwd: '/p', + scope: SCOPE, diff: { kind: 'worktree', path: 'src/a.ts', staged: false }, })) }) diff --git a/tests/tab-content-scope.spec.tsx b/tests/tab-content-scope.spec.tsx new file mode 100644 index 00000000..74863ec1 --- /dev/null +++ b/tests/tab-content-scope.spec.tsx @@ -0,0 +1,159 @@ +/** + * The `scope` object a tab body receives must be stable across re-renders of + * the Sidebar shell. + * + * Tab bodies key memos and effects off `scope` (DiffPane resolves its media / + * html routes from it, TextEditor restores the preview scroll, the side chat + * rebuilds its prose-rewrite cache). The cell used to build `{ sessionId, cwd }` + * fresh on every render, so every one of those dependencies looked changed + * whenever the cell re-rendered. The cell re-renders when a COMPARED memo field + * moves (`tab-content-memo.ts`) — a directory toggle reaches every mounted tab + * through `expanded`, and `revealed` / `localeRevision` / `tabsVersion` do the + * same; a bare poll tick does NOT, because the comparator already absorbs it. + * On those re-renders the diff preview re-ran its whole-document rewrite and + * its content tab re-issued a whole-file `fs.read`, flashing its loading row. + * + * The regression: the cell DOES re-render, but the scope it hands down must be + * the SAME object, and must only become a new one when the session or cwd + * actually changes. + */ +// @vitest-environment jsdom +import { afterEach, describe, expect, it } from 'vitest' +import { createElement } from 'react' + +import { setupReactAct, renderRoot } from './test-utils.ts' +setupReactAct() + +import { TabContent } from '../src/client/sidebar/TabContent.tsx' +import type { SessionScope } from '../src/client/api.ts' +import type { Context } from '../src/context-types.ts' +import type { SidebarStore, SidebarTab } from '../src/client/state.ts' +import type { TabContentMemoKey } from '../src/client/tab-content-memo.ts' + +const TAB: SidebarTab = { id: 'tab:1', type: 'probe', title: 'Probe' } + +/** Every scope object the tab body was rendered with, in order. */ +const seen: SessionScope[] = [] + +function ProbeBody(props: { scope: SessionScope }): null { + seen.push(props.scope) + return null +} + +/** A context whose service resolves exactly one registered tab type. */ +function makeCtx(): Context { + const service = { + getTab: (type: string) => (type === TAB.type + ? { id: TAB.type, title: 'Probe', component: ProbeBody } + : undefined), + } + return { get: (name: string) => (name === 'betterSidebar' ? service : undefined) } as unknown as Context +} + +/** Everything the comparator looks at except `tab` / `paneId` (fixed here). + * Derived from the real key so a field the comparator gains later is not + * silently left uncovered here. */ +type Fields = Partial> + +/** Stable array identities, like the store's own `state.expanded` / `revealed` + * (a fresh `[]` on every render would itself be a compared change). */ +const EMPTY_A: string[] = [] +const EMPTY_B: string[] = [] + +function mountCell(): { rerender: (fields?: Fields) => void; unmount: () => void } { + const ctx = makeCtx() + const store = {} as SidebarStore + let current: Fields = { expanded: EMPTY_A, revealed: EMPTY_B } + + const element = (): ReturnType => createElement(TabContent, { + tab: TAB, + paneId: 'pane:a', + sessionId: current.sessionId ?? 'session:1', + cwd: 'cwd' in current ? current.cwd : '/workspace', + // Fixed across every case: `visible` moving is the tab being parked or + // shown, which no case here varies (so it is deliberately not in `Fields`). + visible: true, + expanded: current.expanded ?? EMPTY_A, + revealed: current.revealed ?? EMPTY_B, + localeRevision: current.localeRevision ?? 'en-US', + tabsVersion: current.tabsVersion ?? 0, + onToggleDir: () => {}, + onReferenceFile: () => {}, + ctx, + store, + onSubagentJump: () => {}, + onOpenDiff: () => {}, + }) + + const root = renderRoot(element()) + return { + rerender: (fields = {}) => { + current = { ...current, ...fields } + root.rerender(element()) + }, + unmount: root.unmount, + } +} + +afterEach(() => { document.body.innerHTML = '' }) + +describe('TabContent scope identity', () => { + it('keeps the same scope object when only `expanded` changes', () => { + seen.length = 0 + const shell = mountCell() + const first = seen.at(-1) + expect(first).toBeDefined() + + shell.rerender({ expanded: ['/workspace/src'] }) + // The cell really did re-render (not a memo skip)... + expect(seen.length).toBe(2) + // ...and handed down the SAME scope. + expect(seen[1]).toBe(first) + + shell.rerender({ expanded: ['/workspace/src', '/workspace/tests'] }) + expect(seen.length).toBe(3) + expect(seen[2]).toBe(first) + shell.unmount() + }) + + /** + * The other compared fields reach the body the same way and must not churn + * the scope either — these are the triggers a perf investigation should + * actually follow (a bare poll tick is absorbed by the comparator and never + * gets here at all). + */ + it.each([ + ['revealed', { revealed: ['/workspace/a.ts'] }], + ['localeRevision', { localeRevision: 'zh-CN' }], + ['tabsVersion', { tabsVersion: 1 }], + ] as Array<[string, Fields]>)('keeps the same scope object when only %s changes', (_label, change) => { + seen.length = 0 + const shell = mountCell() + const first = seen.at(-1) + + shell.rerender(change) + expect(seen.length).toBe(2) + expect(seen[1]).toBe(first) + shell.unmount() + }) + + it('builds a new scope when the session changes', () => { + seen.length = 0 + const shell = mountCell() + const first = seen.at(-1) + shell.rerender({ sessionId: 'session:2' }) + expect(seen.at(-1)).not.toBe(first) + expect(seen.at(-1)?.sessionId).toBe('session:2') + shell.unmount() + }) + + it('builds a new scope when the cwd changes', () => { + seen.length = 0 + const shell = mountCell() + const first = seen.at(-1) + shell.rerender({ cwd: '/other' }) + expect(seen.at(-1)).not.toBe(first) + expect(seen.at(-1)?.cwd).toBe('/other') + shell.unmount() + }) +})