merge #1057: perf(sidebar): 页签内容的会话 scope 改为按内容稳定,消除无关重渲染导致的整文件重读

This commit is contained in:
Menghuan1918 committed 2026-10-26 15:03:28 +08:00
commit 01a6fa573b
16 files changed
+300 -39

No files matched your search

+2 -4
View File
@@ -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 (
+3 -4
View File
@@ -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)
+1 -2
View File
@@ -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
View File
@@ -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
+2 -2
View File
@@ -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],
+1 -1
View File
@@ -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} />
),
},
]
+1 -2
View File
@@ -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(() => {
+12 -2
View File
@@ -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"
+2 -2
View File
@@ -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
+3 -2
View File
@@ -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)
+2 -2
View File
@@ -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)
+34
View File
@@ -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 -1
View File
@@ -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} />