From 5256eef3abdcdee0b24401deb71ae743b0c25981 Mon Sep 17 00:00:00 2001 From: HuanLinOTO Date: Thu, 1 Oct 2026 17:13:10 +0800 Subject: [PATCH] =?UTF-8?q?fix(files):=20=E7=9B=AE=E5=BD=95=E7=BA=A7?= =?UTF-8?q?=E5=88=AB=E5=8A=A0=E8=BD=BD=E5=A4=B1=E8=B4=A5=E4=B8=8D=E5=86=8D?= =?UTF-8?q?=E8=A2=AB=E5=BD=93=E6=88=90=E7=BC=93=E5=AD=98=E5=91=BD=E4=B8=AD?= =?UTF-8?q?=EF=BC=8C=E8=87=AA=E5=8A=A8=E5=8A=A0=E8=BD=BD=E8=B7=AF=E5=BE=84?= =?UTF-8?q?=E5=8F=AF=E9=87=8D=E8=AF=95=EF=BC=88#677=20=E7=A7=BB=E6=A4=8D?= =?UTF-8?q?=E5=88=B0=20loadLevels=20=E6=96=B0=E5=BD=A2=E7=8A=B6=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit PR #677 was written against the pre-0.24.1 loadDir shape (one fs.tree per directory): its error branch stored { error } in the level cache and the cache-hit guard `dataRef.current[dir] !== undefined` treated that failure as "already loaded", so the automatic load path never re-requested a failed level; only the force path (refresh tick / fence-notice retry) recovered. FileTree.tsx has since been rewritten around batched loadLevels (one fs.trees POST for the visible set, commit 98a446b), but the bug survived the rewrite in a new spot: BOTH failure branches now store an error in the same cache — (a) a per-level `error` riding an otherwise-successful batch, and (b) `{ error }` written by the whole-request catch for levels with no listing — and the non-force `wanted` filter (`dataRef.current[path] === undefined`) counted both as cache hits. Port, in current idioms: - The non-force filter now admits a cached entry only when it carries no `error`: `cached === undefined || cached.error !== undefined`. The host guarantees a failed level never carries entries (fs.trees returns `{ entries: [], error }` in place), so `error` alone identifies "nothing usable cached" for both failure branches. - The empty `{}` placeholder of an in-flight load is still a hit, so a re-render while a batch is open does not duplicate the request. - The retry rides the batch route (wanted subset only; levels that DID list stay cached) and reuses the existing non-force flow, which stores `{}` first — same behavior the original fix gave loadDir. - loadLevels' doc comment gains the "only a LISTING settles a level" rule. Not ported: the original diff's comment wording about "the fence notice's retry button" — that notice (and isOutsideWorkspaceMessage usage in the tree) no longer exists in the current shape; recovery paths today are the refresh tick and watch-notice/mutation re-lists, and after this fix any automatic re-load of the expanded set. Tests: tests/file-tree-level-retry.spec.tsx adapts the PR's spec to the batched shape (fsTrees mock, batch-load-spec harness): (1) a per-level error is re-requested as a batch of 1 on the next automatic load (with an added assertion that an in-flight batch is NOT duplicated), (2) levels stored by a failed whole request are all retryable. Both go red on the unfixed filter (verified: "expected to be called 2 times, but got 1"). All 9 file-tree suites (47 tests) and tsc --noEmit stay green. --- src/client/FileTree.tsx | 19 ++- tests/file-tree-level-retry.spec.tsx | 195 +++++++++++++++++++++++++++ 2 files changed, 211 insertions(+), 3 deletions(-) create mode 100644 tests/file-tree-level-retry.spec.tsx diff --git a/src/client/FileTree.tsx b/src/client/FileTree.tsx index 222ad268..895dd101 100644 --- a/src/client/FileTree.tsx +++ b/src/client/FileTree.tsx @@ -640,8 +640,10 @@ export function FileTree(props: { * a directory each cost exactly one POST — not one per level (the N+1 the * file list was reported for). Levels already loaded (including the empty * placeholder of an in-flight fetch) are left alone, so an expand only asks - * for what is genuinely missing; a stale response — the cache was wiped by a - * refresh tick — is dropped instead of overwriting fresher data. + * for what is genuinely missing — but only a LISTING settles a level: a + * cached failure is asked for again, so one bad read does not stick for the + * rest of the mount. A stale response — the cache was wiped by a refresh + * tick — is dropped instead of overwriting fresher data. * * A level the host failed to read comes back with its own `error` and is * stored on that level alone (the other levels render normally). When the @@ -655,7 +657,18 @@ export function FileTree(props: { const force = options?.force === true const wanted = force ? [...new Set(paths)] - : paths.filter(path => dataRef.current[path] === undefined) + : paths.filter((path) => { + // Only a LISTING settles a level: both failure branches below store + // their error in this same cache, so treating every entry as + // "already loaded" made one failed read (a host restart, a transient + // fs error) stick for the rest of the mount — the automatic load + // path re-ran for the expanded set and skipped the level, and the + // only ways out were a refresh tick or a remount. An error entry + // stays retryable; the empty `{}` placeholder of an in-flight load + // is still a hit (a re-render must not duplicate the open request). + const cached = dataRef.current[path] + return cached === undefined || cached.error !== undefined + }) if (wanted.length === 0) return const generation = generationRef.current // A FORCED re-list (a refresh tick) keeps the listing on screen until the diff --git a/tests/file-tree-level-retry.spec.tsx b/tests/file-tree-level-retry.spec.tsx new file mode 100644 index 00000000..b537e953 --- /dev/null +++ b/tests/file-tree-level-retry.spec.tsx @@ -0,0 +1,195 @@ +/** + * A directory level whose load FAILED must be fetched again by the next + * automatic load instead of being cached like a listing (PR #677, ported to + * the batched `loadLevels` shape). + * + * Both failure branches of `loadLevels` store their error in the level cache — + * a per-level `error` riding a successful batch, and `{ error }` from a failed + * whole request — and the cache-hit filter treated every entry as "already + * loaded". One bad read (a host restart, a transient fs error) then stuck for + * the rest of the mount: re-rendering the tree with the same expansion set + * re-ran the load effect, which skipped the failed level, and the only ways + * out were a refresh tick (the force path) or a remount. The load effect + * re-runs whenever the expanded set's identity changes, which is the retry + * this guards — while levels that DID list stay cached, and a load that is + * still in flight is not duplicated. + */ +// @vitest-environment jsdom +import { afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest' +import { createElement } from 'react' +import { createRoot, type Root } from 'react-dom/client' +import { act } from 'react-dom/test-utils' +import { FileTree } from '../src/client/FileTree.tsx' + +import { setupReactAct } from './test-utils.ts' +setupReactAct() + +// vitest 4.1.11+ follows the OS locale; pin en-US so the copy is English. +beforeAll(() => { + Object.defineProperty(window.navigator, 'language', { value: 'en-US', configurable: true }) +}) + +const fsTree = vi.hoisted(() => vi.fn()) +const fsTrees = vi.hoisted(() => vi.fn()) + +vi.mock('../src/client/api.ts', () => ({ + api: { + fsTree: (...args: unknown[]) => fsTree(...args), + fsTrees: (...args: unknown[]) => fsTrees(...args), + // The tree reads the shared git-status store; a non-repo answer keeps + // every row plain. + gitStatus: async () => ({ isRepo: false, entries: [] }), + }, + downloadUrl: () => '/sidebar/file', +})) + +/** The smallest WebSocket the directory watcher talks to (never opened — no + * watch notice is part of this spec; the retry comes from the load effect). */ +class FakeSocket { + static instances: FakeSocket[] = [] + static readonly OPEN = 1 + static readonly CONNECTING = 0 + readyState = FakeSocket.CONNECTING + readonly url: string + onopen: (() => void) | null = null + onmessage: ((event: { data: string }) => void) | null = null + onclose: (() => void) | null = null + constructor(url: string) { + this.url = url + FakeSocket.instances.push(this) + } + send(): void {} + close(): void { this.readyState = 3 } + open(): void { this.readyState = FakeSocket.OPEN; this.onopen?.() } + frame(payload: unknown): void { this.onmessage?.({ data: JSON.stringify(payload) }) } +} + +/** One level's listing: the root lists `src`, `src` lists one file. */ +function levelOf(path: string): { + path: string; entries: { name: string; path: string; isDir: boolean }[]; truncated: boolean +} { + if (path === '/tmp') { + return { path, entries: [{ name: 'src', path: '/tmp/src', isDir: true }], truncated: false } + } + return { path, entries: [{ name: 'inner.ts', path: '/tmp/src/inner.ts', isDir: false }], truncated: false } +} + +/** The paths a batch call was asked for (sorted: the cache decides membership, + * not the order). */ +function batchPaths(index: number): string[] { + const call = fsTrees.mock.calls[index] + if (call === undefined) throw new Error(`no fs.trees call #${index}`) + return (call[1] as string[]).slice().sort() +} + +interface Harness { + container: HTMLDivElement + /** Re-render with a NEW array holding the same expansion set: the load + * effect's `expanded` dependency changes identity, re-running the + * automatic (non-forced) load — the retry path this spec guards. */ + rerender: (expanded: string[]) => void + unmount: () => void +} + +function mountTree(expanded: string[]): Harness { + const container = document.createElement('div') + document.body.append(container) + const root: Root = createRoot(container) + const render = (dirs: string[]): void => { + root.render(createElement(FileTree, { + sessionId: 's1', + cwd: '/tmp', + expanded: dirs, + revealed: [], + onToggle: () => {}, + onOpenFile: () => {}, + onReferenceFile: () => {}, + refreshTick: 0, + onUploadRequest: () => {}, + busy: false, + })) + } + act(() => { render(expanded) }) + return { + container, + rerender: (dirs: string[]) => { act(() => { render(dirs) }) }, + unmount: () => { act(() => { root.unmount() }); container.remove() }, + } +} + +/** Flush the batch promise chain. */ +async function flush(): Promise { + await act(async () => { + await Promise.resolve() + await Promise.resolve() + await Promise.resolve() + }) +} + +let harness: Harness +beforeEach(() => { + FakeSocket.instances = [] + vi.stubGlobal('WebSocket', FakeSocket) + fsTree.mockReset() + fsTrees.mockReset() + fsTrees.mockImplementation(async (_scope: unknown, paths: readonly string[]) => ({ + levels: paths.map(path => levelOf(path)), + })) +}) + +afterEach(() => { + harness.unmount() + document.body.innerHTML = '' + vi.unstubAllGlobals() +}) + +describe('FileTree directory-level loading retries failures', () => { + it('re-requests a level that came back with a per-level error', async () => { + // The first batch fails the child level IN PLACE (the batch itself + // succeeds — one unreadable directory must not blank the whole tree); the + // next answer succeeds, as it would once the host recovers. + fsTrees.mockImplementationOnce(async (_scope: unknown, paths: readonly string[]) => ({ + levels: paths.map(path => path === '/tmp/src' + ? { path, entries: [], truncated: false, error: 'cannot read src' } + : levelOf(path)), + })) + harness = mountTree(['/tmp/src']) + // A re-render while the batch is still in flight must NOT duplicate the + // request: the `{}` placeholder of the open load is a cache hit too. + harness.rerender(['/tmp/src']) + await flush() + expect(fsTrees).toHaveBeenCalledTimes(1) + expect(batchPaths(0)).toEqual(['/tmp', '/tmp/src']) + expect(harness.container.textContent).toContain('cannot read src') + expect(harness.container.textContent).not.toContain('inner.ts') + + // The parent re-renders with a fresh array holding the same expansion + // set: the load effect re-runs, and the failed level has to be requested + // again — while the root that DID list stays cached (batch of 1). + harness.rerender(['/tmp/src']) + await flush() + expect(fsTrees).toHaveBeenCalledTimes(2) + expect(batchPaths(1)).toEqual(['/tmp/src']) + expect(harness.container.textContent).toContain('inner.ts') + // The retry rides the batch route (the N+1 shape stays gone). + expect(fsTree).not.toHaveBeenCalled() + }) + + it('re-requests levels stored by a failed whole batch request', async () => { + // The first batch dies wholesale (host restart, network gone): every + // wanted level — including the root — is stored as a bare failure. + fsTrees.mockRejectedValueOnce(new Error('listing offline')) + harness = mountTree(['/tmp/src']) + await flush() + expect(harness.container.textContent).toContain('listing offline') + expect(harness.container.textContent).not.toContain('inner.ts') + + // Same fresh-array re-render: BOTH stored failures are retryable, so the + // retry batch is the full visible set again. + harness.rerender(['/tmp/src']) + await flush() + expect(fsTrees).toHaveBeenCalledTimes(2) + expect(batchPaths(1)).toEqual(['/tmp', '/tmp/src']) + expect(harness.container.textContent).toContain('inner.ts') + }) +})