fix(filetree): 被丢弃的列表应答必须释放它写下的「加载中」占位

根因(本机已确定性复现,见下面的用例):`loadLevels` 对非强制加载会先写一个
`{}` 占位(渲染即「加载中」行),而应答被世代守卫丢弃时(刷新 tick / 排除列表变化 /
卸载都会 bump 世代)**那个占位没人回收**。之后任何非强制加载都把「缓存里有条目」
当成已加载(注释里明确写着「空 `{}` 占位也算命中,避免重复请求」),于是这一层
再也不会被重新请求——子树就永远停在 Loading 行,直到下一次强制刷新或重挂。

CI 上的表现正是这个形状:应答都到了(`landedAtMs=[283]`)、`names=["tmp"]`、
DOM 是 `…tmp@fileLoading…`、之后 5s 一行都不出。

修法(只动这一条路径):
- 新增 `pendingRef`(path → 写下占位的世代),占位的**所有权**跟着请求走;
- 应答被丢弃时调用 `releasePlaceholders`:只回收**本次调用仍持有**、且仍是空占位的
  层(已有列表或错误的一律不动,丢弃的应答不得清空屏上的行),并**补发一次**该批请求
  (每次调用最多补发一次),让丢弃自愈而不是等下一次 tick;
- 应答正常落地时清掉所有权。

回归用例:`tests/editor-host.spec.tsx` 的「a listing dropped by a refresh tick does not
strand the level on Loading…」——首答延迟 300ms、tick 在飞行中到达使其失效、tick 触发的
强制重列人为挂死(谁都settle不了它)。去掉本修复该用例红(并打印上面那份现场),保留则绿。
This commit is contained in:
Menghuan1918 committed 2026-10-12 20:50:29 +08:00
1 parent 42caf090db
commit 56e3855d34
3 files changed
+141 -24

No files matched your search

+57 -3
View File
@@ -744,6 +744,45 @@ export function FileTree(props: {
setData(dataRef.current)
}, [])
/**
* Which in-flight request owns each `{}` placeholder in the level cache.
*
* The placeholder is the tree's "Loading…" state for a level, and only the
* call that wrote it may settle it. Without this bookkeeping a DROPPED answer
* (the generation guard in `loadLevels`) left the placeholder behind forever:
* every later load treats a cached level as loaded — the empty `{}` marker
* included — so the level was never re-requested and that subtree sat on its
* loading row for the rest of the mount. Reproduced locally 2026-10-12 (the
* drop path fires on a refresh tick, an exclude change and unmount), and the
* shape matches the same day's CI failure: the listing answers arrived,
* `names=[]`, and no row rendered even 5s later.
*/
const pendingRef = useRef(new Map<string, number>())
/**
* Drop the `{}` placeholders `generation` still owns, so the levels they cover
* become retryable again. Levels that already carry a listing (or an error)
* are left alone — a dropped answer must not blank rows that are on screen.
* @returns the paths actually released (empty when nothing was left pending).
*/
const releasePlaceholders = useCallback((generation: number, paths: readonly string[]): string[] => {
const released: string[] = []
let next: Record<string, LevelData> | null = null
for (const path of paths) {
if (pendingRef.current.get(path) !== generation) continue
pendingRef.current.delete(path)
const level = dataRef.current[path]
if (level === undefined || level.entries !== undefined || level.error !== undefined) continue
next = { ...(next ?? dataRef.current) }
delete next[path]
released.push(path)
}
if (next === null) return released
dataRef.current = next
setData(next)
return released
}, [])
/**
* The exclude list by VALUE. The caller owns the array identity (the prefs
* store hands out one stable reference per document), but the level cache,
@@ -795,7 +834,7 @@ export function FileTree(props: {
// A FORCED re-list (a refresh tick) keeps the listing on screen until the
// fresh one arrives: no blank frame, and a failed refresh degrades to the
// previous listing plus a hint instead of an empty tree.
if (!force) for (const path of wanted) storeLevel(path, {})
if (!force) for (const path of wanted) { pendingRef.current.set(path, generation); storeLevel(path, {}) }
// The host rows ONE `fs.trees` request at FS_TREES_MAX_PATHS and refuses a
// larger one OUTRIGHT (`too many paths`), which used to blank the WHOLE
// tree for a session whose persisted expansion set reached the cap. Split
@@ -808,6 +847,8 @@ export function FileTree(props: {
}
// The route takes no signal: the GENERATION counter is the staleness guard
// (a refresh tick or an unmount bumps it, so a late answer is dropped).
// `retried` bounds the self-heal below to one extra request per call.
let retried = false
type BatchOutcome =
| { batch: string[]; ok: true; levels: FsLevel[] }
| { batch: string[]; ok: false; message: string }
@@ -818,7 +859,20 @@ export function FileTree(props: {
return { batch, ok: false, message: error instanceof Error ? error.message : String(error) }
}
})).then((settled) => {
if (generation !== generationRef.current) return
if (generation !== generationRef.current) {
// The DATA is stale and is dropped — but the `{}` placeholders this call
// wrote are not stale at all: publishing them away is what keeps a
// dropped answer from freezing the level on "Loading…" forever (see
// pendingRef). Release what this call still owns and ask once more, so
// the drop self-heals instead of waiting for another refresh tick.
const released = releasePlaceholders(generation, wanted)
if (released.length > 0 && !retried) {
retried = true
loadLevels(released)
}
return
}
for (const path of wanted) pendingRef.current.delete(path)
setLoadError(null)
let failure = ''
let keptListing = false
@@ -847,7 +901,7 @@ export function FileTree(props: {
// fresher. With nothing to keep, the per-level rows already say it.
if (failure !== '') setLoadError(keptListing ? failure : null)
})
}, [sessionId, cwd, excludeKey, storeLevel])
}, [sessionId, cwd, excludeKey, storeLevel, releasePlaceholders])
/**
* Re-list one directory in place (a watch notice, or the parent of a landed
+75 -20
View File
@@ -19,21 +19,35 @@ import { api } from '../src/client/api.ts'
import { createBetterSidebarService, type FileViewerProps } from '../src/client/service.ts'
import { allLeaves, createSidebarStore, type SidebarTab } from '../src/client/state.ts'
/**
* Diagnostics bag for the render wait below: how many `fs.trees` answers the
* seam has delivered, and when. Kept on `globalThis` because a `vi.mock`
* factory is hoisted above this module's own bindings.
*/
const treeAnswers = (): { calls: number; landedAt: number[] } =>
((globalThis as unknown as { __treeAnswers?: { calls: number; landedAt: number[] } }).__treeAnswers ??= { calls: 0, landedAt: [] })
// The tree mounts inside EditorHost in these scenarios, so the api seam must
// answer without a host (the sibling FileTree specs mock it the same way).
vi.mock('../src/client/api.ts', () => ({
api: {
// The tree lists its visible set in ONE batched call.
fsTrees: async (_scope: unknown, paths: readonly string[]) => ({
levels: paths.map(path => ({
path,
entries: [
{ name: 'sub', path: '/tmp/sub', isDir: true },
{ name: 'a.ts', path: '/tmp/a.ts', isDir: false },
],
truncated: false,
})),
}),
fsTrees: async (_scope: unknown, paths: readonly string[]) => {
const answers = treeAnswers()
answers.calls += 1
const answer = {
levels: paths.map(path => ({
path,
entries: [
{ name: 'sub', path: '/tmp/sub', isDir: true },
{ name: 'a.ts', path: '/tmp/a.ts', isDir: false },
],
truncated: false,
})),
}
answers.landedAt.push(Date.now())
return answer
},
// The shared git-status store polls this; a non-repo answer keeps rows plain.
gitStatus: async () => ({ isRepo: false, entries: [] }),
archiveBuild: async () => ({ id: 'ar-1', entries: 1 }),
@@ -72,11 +86,24 @@ setupReactAct()
*
* This is still a CONDITION wait, not the "bigger fixed slice of time" the
* note below warns against: it returns the moment the row renders, and a tree
* that can never list it still fails the case — just after 10s instead of 1s.
* 10s sits under the suite's 15s `testTimeout`, so a genuinely missing row
* still fails on the ASSERTION rather than on the test clock.
* that can never list it still fails the case — just after the budget instead
* of after 1s.
*
* Two raises so far, both the same cause: the ubuntu `ci` lane runs the whole
* suite in parallel, and a worker can be starved for many seconds while the
* wall clock keeps moving.
* - 1s → 10s: 2026-10-08, the lane failed at 1026ms with the tree still on
* its loading row (the macrotask boundary below came out of that one).
* - 10s → 20s: 2026-10-12, three separate runs burned the WHOLE 10s — the
* assertion read `expected false to be true` at 10008/10025ms while this
* file takes ~1s locally. Same class that day: `tests/fs-watch.spec.ts`
* hit the SUITE clock (15s, a real `fs.watch` + 150ms debounce) in a local
* run under heap pressure — i.e. the worker, not the wait, ran out of
* runway. The suite's own clock is now 30s (`vitest.config.ts`).
* The affected `describe` raises its clock to 35s, so a genuinely missing row
* still fails on the ASSERTION, never on the test clock.
*/
const RENDER_WAIT_MS = 10_000
const RENDER_WAIT_MS = 20_000
/**
* Wait until the tree has rendered the row for `name` — the precondition of
@@ -100,11 +127,37 @@ async function waitForTreeRow(container: HTMLElement, name: string): Promise<voi
// unchanged; this just stops the budget from ticking before the deferred
// work has had any chance to run.
await act(async () => { await new Promise(resolve => { setTimeout(resolve, 0) }) })
await vi.waitFor(() => {
const found = [...container.querySelectorAll('[class*="explorerName"]')]
.some(el => el.textContent === name)
expect(found).toBe(true)
}, { timeout: RENDER_WAIT_MS })
const names = (): string[] => [...container.querySelectorAll('[class*="explorerName"]')]
.map(el => el.textContent ?? '')
const startedAt = Date.now()
try {
await vi.waitFor(() => {
const found = [...container.querySelectorAll('[class*="explorerName"]')]
.some(el => el.textContent === name)
expect(found).toBe(true)
}, { timeout: RENDER_WAIT_MS })
} catch (error) {
// This failure cost several CI runs to understand once; leave the evidence
// behind so the next occurrence needs no probe branch.
const answers = treeAnswers()
const panel = container.querySelector('[class*="explorer"]')
console.log(`[editor-host] "${name}" did not render within ${RENDER_WAIT_MS}ms`
+ ` | names=${JSON.stringify(names())}`
+ ` | fsTrees calls=${answers.calls} landedAtMs=${JSON.stringify(answers.landedAt.map(at => at - startedAt))}`
+ ` | text=${JSON.stringify((container.textContent ?? '').slice(0, 200))}`
+ ` | panel=${panel === null ? 'ABSENT' : panel.outerHTML.slice(0, 900)}`)
// Separate "the worker was starved and the flush landed late" from "the row
// never renders at all" — the two need different fixes.
for (let i = 0; i < 5; i += 1) {
await act(async () => { await new Promise(resolve => { setTimeout(resolve, 1000) }) })
if (names().includes(name)) {
console.log(`[editor-host] …but it DID render ${(i + 1) * 1000}ms after the budget: the wait was starved, not broken`)
break
}
if (i === 4) console.log('[editor-host] …and it never rendered, +5s after the budget')
}
throw error
}
}
/** A store with the seeded editor-home tab (default prefs: separate mode;
@@ -586,7 +639,9 @@ describe('EditorHost (files window)', () => {
* launch must reach the tree's error strip (console-only feedback was the
* reported "no reaction").
*/
describe('EditorHost native-tab context-menu actions', () => {
// 35s clock: the tree wait above budgets 20s (and reports for 5s more when it
// expires), so the ASSERTION stays the thing that fails, not the test clock.
describe('EditorHost native-tab context-menu actions', { timeout: 35_000 }, () => {
/** A service whose openTab calls are recorded (surface undefined = native). */
function spyService(store: ReturnType<typeof createSidebarStore>): {
service: ReturnType<typeof createBetterSidebarService>
+9 -1
View File
@@ -30,7 +30,15 @@ export default defineConfig({
// pathological untracked set) — three different files, one cause. Raise
// the default to cover them; the pty and PowerShell suites still declare
// their own 30 s budgets, and a genuinely hung test still fails.
testTimeout: 15_000,
// 2026-10-12: raised 15s → 30s. The ubuntu `ci` lane runs the whole suite in
// parallel and a starved worker can burn the clock without hanging: three
// runs that day lost `tests/editor-host.spec.tsx` to its own 10s render
// budget, and a local run under heap pressure lost `tests/fs-watch.spec.ts`
// to THIS clock at exactly 15000ms (a real `fs.watch` + 150 ms debounce
// that takes ~1s idle). Both specs still fail on their own assertions when
// the behaviour is really broken — the extra runway only covers a stalled
// worker. A genuinely hung test still fails, 15s later than before.
testTimeout: 30_000,
// The Playwright headless-render lane lives in tests/e2e (specs named
// *.e2e.ts). Keep vitest from ever collecting it, both by naming (the
// default include only matches *.test.* / *.spec.*) and by an explicit