perf(files): keep parked trees idle and batch the watcher re-arm

This commit is contained in:
Menghuan1918 committed 2026-10-24 02:17:07 +08:00
1 parent 27a920f85b
commit 4cb7937a37
6 files changed
+146 -39

No files matched your search

+20 -3
View File
@@ -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<Record<string, LevelData>>({})
/**
* 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
+7 -1
View File
@@ -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). */
+11 -6
View File
@@ -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])
}
+69 -16
View File
@@ -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<typeof createSidebarStore>, 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<typeof createSidebarStore>, tab: () => SidebarTab): Promise<{
async function mountHostWithTreeWithCwd(
ctx: Context,
store: ReturnType<typeof createSidebarStore>,
tab: () => SidebarTab,
options: { visible?: boolean; onRender?: () => void } = {},
): Promise<{
container: HTMLDivElement
rerender: (visible: boolean) => Promise<void>
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<void> => {
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)
+33 -7
View File
@@ -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()
+6 -6
View File
@@ -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()
})