merge #1057: perf(sidebar): 页签内容的会话 scope 改为按内容稳定,消除无关重渲染导致的整文件重读
This commit is contained in:
commit
01a6fa573b
16 files changed
+300
-39
No files matched your search
@@ -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`,同一帧的缩放量按步夹紧后完整复合、只提交一次(与逐帧应用等价);背景拖拽期间滚轮让位给拖拽,避免两种手势互相覆盖。
|
||||
|
||||
@@ -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<SessionScope>(() => ({ 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 (
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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])
|
||||
|
||||
|
||||
+16
-10
@@ -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
|
||||
|
||||
@@ -202,8 +202,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<GitGutterHost>(
|
||||
() => ({ scope: { sessionId: scope.sessionId, cwd: scope.cwd, repoRoot: scope.repoRoot }, path }),
|
||||
[scope.sessionId, scope.cwd, scope.repoRoot, path],
|
||||
|
||||
@@ -318,7 +318,7 @@ export function builtinTabs(ctx: Context): readonly TabDescriptor[] {
|
||||
dedupeKey: (tab) => tab.id,
|
||||
component: ({ scope, tab }) => (
|
||||
tab.diff === undefined ? null
|
||||
: <DiffTab sessionId={scope.sessionId} cwd={scope.cwd} diff={tab.diff} />
|
||||
: <DiffTab scope={scope} diff={tab.diff} />
|
||||
),
|
||||
},
|
||||
]
|
||||
|
||||
@@ -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(() => {
|
||||
|
||||
@@ -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={<IconRefreshOutlineRegular size={14} />}
|
||||
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)
|
||||
}}
|
||||
/>
|
||||
<IconButton
|
||||
size="sm"
|
||||
|
||||
@@ -49,8 +49,8 @@ export function useGitDiffTarget(ref: SidebarDiffRef | null, scope: SessionScope
|
||||
// land on the wrong contents).
|
||||
const [effectiveStaged, setEffectiveStaged] = useState<boolean | null>(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
|
||||
|
||||
@@ -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'
|
||||
@@ -500,7 +501,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)
|
||||
|
||||
@@ -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<void> => {
|
||||
await pullStream(streamOf(sessionId), { sessionId, cwd }, signal)
|
||||
|
||||
@@ -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<SessionScope | undefined>(
|
||||
() => (sessionId === undefined ? undefined : { sessionId, cwd }),
|
||||
[sessionId, cwd],
|
||||
)
|
||||
}
|
||||
@@ -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 <OrphanedTab ctx={ctx} store={store} scope={scope} tab={tab} visible={visible} />
|
||||
|
||||
@@ -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<HTMLButtonElement>(`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 },
|
||||
}))
|
||||
})
|
||||
|
||||
@@ -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<Omit<TabContentMemoKey, 'tab' | 'paneId'>>
|
||||
|
||||
/** 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<typeof createElement> => 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()
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user