From 38a82db0e31c33e06b8bc460a3ca465bbf0f68b5 Mon Sep 17 00:00:00 2001 From: ZinChl <123862319+ZinChl@users.noreply.github.com> Date: Wed, 30 Sep 2026 01:56:11 +0800 Subject: [PATCH] =?UTF-8?q?fix(files):=20fs.trees=20=E6=8C=89=E5=AE=BF?= =?UTF-8?q?=E4=B8=BB=E4=B8=8A=E9=99=90=E5=88=86=E5=9D=97=EF=BC=8C=E5=B1=95?= =?UTF-8?q?=E5=BC=80=E9=9B=86=20=E2=89=A564=20=E7=9A=84=E4=BC=9A=E8=AF=9D?= =?UTF-8?q?=E4=B8=8D=E5=86=8D=E6=95=B4=E6=A0=91=E6=8A=A5=E9=94=99=EF=BC=88?= =?UTF-8?q?#799=EF=BC=89?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 宿主对一次 `fs.trees` 批量请求有硬上限 `FS_TREES_MAX_PATHS = 64`,超限 **整批** `bad-request`;而客户端把 root + 全部展开目录放进**一次**请求 (loadLevels)。展开集按会话持久化,所以累计展开到 64+ 的用户每次挂载/刷新 都被整批拒绝,catch 把所有无缓存层写成 error —— 整棵树报错,只能手动折叠。 改动: - 新增 `src/fs-batch.ts`:把行上限放成**两半共用的零依赖模块**(`prefs-shared.ts` 的同一模式),宿主 `src/index.ts` 改为 re-export,客户端按同一常量分块, 两边不会再漂移。 - `src/client/FileTree.tsx` 的 `loadLevels`:把可见集按上限切块、并发请求, 并保留批量路由的**逐层错误粒度**——某一批失败只标记它自己携带的层, 不会再把其它批已经拿到的列表一起标红(原先单请求失败时会标记全部 wanted)。缓存/代际(generation)语义不变。 - 宿主上限保持不动(那是针对恶意超大批量的防线)。 测试:`tests/file-tree-batch-load.spec.tsx` 新增两例——71 个可见路径切成 64 + 7 两批且每个路径恰好出现一次;某一批失败时另一批的层仍正常渲染。 回退 FileTree 的分块后这两例当场红、原有 8 例仍绿(已实测)。 --- src/client/FileTree.tsx | 60 ++++++++++++++++++++--------- src/fs-batch.ts | 10 +++++ src/index.ts | 8 +++- tests/file-tree-batch-load.spec.tsx | 45 ++++++++++++++++++++++ 4 files changed, 103 insertions(+), 20 deletions(-) create mode 100644 src/fs-batch.ts diff --git a/src/client/FileTree.tsx b/src/client/FileTree.tsx index 222ad268..bf45b51c 100644 --- a/src/client/FileTree.tsx +++ b/src/client/FileTree.tsx @@ -49,7 +49,8 @@ import { } from '@deepseek-ai/dsh-client-ui-primitives' import { SiCursor, SiZedindustries } from 'react-icons/si' import { VscFolderOpened, VscLinkExternal, VscPin, VscPinned } from 'react-icons/vsc' -import { api, archiveBuild, archiveDownloadUrl, archiveStatus, downloadUrl, type FsEntry } from './api.ts' +import { api, archiveBuild, archiveDownloadUrl, archiveStatus, downloadUrl, type FsEntry, type FsLevel } from './api.ts' +import { FS_TREES_MAX_PATHS } from '../fs-batch.ts' import { builtinFileIcon, builtinFolderIcon } from './file-icons.tsx' import { IconUploadOutline16, IconVscode16 } from './icons.tsx' import { isImeComposition } from './ime-guard.ts' @@ -662,33 +663,56 @@ export function FileTree(props: { // 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, {}) + // 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 + // the visible set into cap-sized batches and keep the per-level error + // identity the batch route is built around: a batch that fails marks only + // the levels it carried. + const batches: string[][] = [] + for (let index = 0; index < wanted.length; index += FS_TREES_MAX_PATHS) { + batches.push(wanted.slice(index, index + FS_TREES_MAX_PATHS)) + } // 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). - api.fsTrees({ sessionId, cwd }, wanted).then((result) => { + type BatchOutcome = + | { batch: string[]; ok: true; levels: FsLevel[] } + | { batch: string[]; ok: false; message: string } + void Promise.all(batches.map(async (batch): Promise => { + try { + return { batch, ok: true, levels: (await api.fsTrees({ sessionId, cwd }, batch)).levels } + } catch (error: unknown) { + return { batch, ok: false, message: error instanceof Error ? error.message : String(error) } + } + })).then((settled) => { if (generation !== generationRef.current) return setLoadError(null) - for (const level of result.levels) { - storeLevel(level.path, { - entries: level.entries, - truncated: level.truncated, - ...(level.error !== undefined ? { error: level.error } : {}), - }) - } - }).catch((error: unknown) => { - if (generation !== generationRef.current) return - const message = error instanceof Error ? error.message : String(error) + let failure = '' let keptListing = false - for (const path of wanted) { - const level = dataRef.current[path] - if (level?.entries !== undefined) { - keptListing = true + for (const outcome of settled) { + if (outcome.ok) { + for (const level of outcome.levels) { + storeLevel(level.path, { + entries: level.entries, + truncated: level.truncated, + ...(level.error !== undefined ? { error: level.error } : {}), + }) + } continue } - storeLevel(path, { error: message }) + if (failure === '') failure = outcome.message + for (const path of outcome.batch) { + const level = dataRef.current[path] + if (level?.entries !== undefined) { + keptListing = true + continue + } + storeLevel(path, { error: outcome.message }) + } } // Levels that had a listing keep it; the hint explains why they are not // fresher. With nothing to keep, the per-level rows already say it. - setLoadError(keptListing ? message : null) + if (failure !== '') setLoadError(keptListing ? failure : null) }) }, [sessionId, cwd, storeLevel]) diff --git a/src/fs-batch.ts b/src/fs-batch.ts new file mode 100644 index 00000000..8992f3c8 --- /dev/null +++ b/src/fs-batch.ts @@ -0,0 +1,10 @@ +/** + * Row bound of ONE `fs.trees` batch request. + * + * Shared by both halves so they cannot drift: the host refuses a larger batch + * outright (`too many paths (max N)`), and the client splits the visible set on + * the same number — a session whose persisted expansion set reaches the cap + * used to blank its WHOLE file tree on every mount/refresh. Kept free of + * runtime dependencies so the browser bundle pulls nothing in with it. + */ +export const FS_TREES_MAX_PATHS = 64 diff --git a/src/index.ts b/src/index.ts index 260e87df..c6e9934a 100644 --- a/src/index.ts +++ b/src/index.ts @@ -50,6 +50,9 @@ import { buildSidechatApi } from './sidechat-routes.ts' import { createAssistantLiveBuffer, type AssistantLiveBuffer } from './assistant-live.ts' import { readJsonBody, requireString, SidebarError, writeError, writeJson, writeOk } from './wire.ts' import { readPersistedSession } from './session-store.ts' +// Shared with the client's batch splitter: the two halves must agree on the +// row bound, so it lives in a dependency-free module both can import. +import { FS_TREES_MAX_PATHS } from './fs-batch.ts' export { Config } export type { SidebarConfig, ResolvedSidebarConfig } @@ -75,8 +78,9 @@ export { archiveNameOf, collectZipEntries, contentDispositionOf, disambiguateArc /** Plugin identity for cordis.yml rows. */ export const name = 'dsh-better-sidebar' -/** Row bound of one `fs.trees` batch request (a mount/refresh sends what it shows). */ -export const FS_TREES_MAX_PATHS = 64 +/** Row bound of one `fs.trees` batch request (a mount/refresh sends what it + * shows, split into cap-sized batches by the client — see `fs-batch.ts`). */ +export { FS_TREES_MAX_PATHS } /** One level of an `fs.trees` batch: either a listing or that level's failure. */ export interface SidebarFsLevel { diff --git a/tests/file-tree-batch-load.spec.tsx b/tests/file-tree-batch-load.spec.tsx index c9e11c44..d204fe5e 100644 --- a/tests/file-tree-batch-load.spec.tsx +++ b/tests/file-tree-batch-load.spec.tsx @@ -19,6 +19,7 @@ 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 { FS_TREES_MAX_PATHS } from '../src/fs-batch.ts' import { setupReactAct } from './test-utils.ts' setupReactAct() @@ -167,6 +168,50 @@ describe('FileTree level loading is batched', () => { expect(harness.container.textContent).toContain('d8-file.ts') }) + it('splits a visible set larger than the host cap into cap-sized batches', async () => { + // The expansion set persists per session, so a heavy session can cross the + // host's row bound. ONE oversized request used to be refused outright + // (`too many paths (max 64)`) and every level fell back to an error row; + // the tree now splits on the same number the host enforces. + const many = Array.from({ length: FS_TREES_MAX_PATHS + 6 }, (_, index) => `/tmp/d${index + 1}`) + harness = mountTree(many) + await flush() + + expect(fsTrees).toHaveBeenCalledTimes(2) + const sizes = fsTrees.mock.calls.map(call => (call[1] as string[]).length).sort((a, b) => a - b) + expect(sizes).toEqual([6 + 1, FS_TREES_MAX_PATHS]) + // Every visible path is asked for exactly once across the batches. + expect(fsTrees.mock.calls.flatMap(call => call[1] as string[]).sort()).toEqual(['/tmp', ...many].sort()) + // …and the tree renders instead of collapsing into error rows. + expect(harness.container.textContent).toContain('d1-file.ts') + expect(harness.container.textContent).not.toContain('too many paths') + }) + + it('keeps one failed batch from blanking the levels another batch carried', async () => { + // Batching must not cost the route's per-level error identity: a batch that + // fails marks only ITS paths, never the whole visible set. + const many = Array.from({ length: FS_TREES_MAX_PATHS + 6 }, (_, index) => `/tmp/d${index + 1}`) + fsTrees.mockImplementation(async (_scope: unknown, paths: readonly string[]) => { + // The trailing (small) batch fails; the leading one keeps working. + if (paths.length < 32) throw new Error('too many paths (max 64)') + return { + levels: paths.map(path => path === '/tmp' + ? { + path, + entries: many.map(dir => ({ name: dir.slice('/tmp/'.length), path: dir, isDir: true })), + truncated: false, + } + : levelOf(path)), + } + }) + harness = mountTree(many) + await flush() + // The levels the leading batch carried are NOT marked as failed… + expect(harness.container.textContent).toContain('d1-file.ts') + // …while the failed batch's own levels say why they are missing. + expect(harness.container.textContent).toContain('too many paths') + }) + it('lists only the newly expanded directory (batch of 1)', async () => { harness = mountTree(DIRS) await flush()