Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(file-browser): 切开关不被借来的展开态覆盖本 scope 记录(PR #4398 轮七)
Zhang Yunjin8fdfa0f8e1b4
diff --git a/apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/__tests__/useFileTree.test.tsx b/apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/__tests__/useFileTree.test.tsxindex 9fa32aff2c..d30c57ac13 100644--- a/apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/__tests__/useFileTree.test.tsx+++ b/apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/__tests__/useFileTree.test.tsx@@ -16,7 +16,9 @@ const mocks = vi.hoisted(() => {fileBrowserApiFor: vi.fn(),isDeviceTooOldError: vi.fn(() => false),listDir: vi.fn(),- loadExpandedSet: vi.fn(() => new Set<string>()),+ loadExpandedSet: vi.fn(+ (_workdir: string, _opts?: { showIgnoredDirs?: boolean }) => new Set<string>(),+ ),deviceSupportsRevealIgnoredDirs: vi.fn(async (): Promise<boolean | null> => true,),@@ -75,6 +77,8 @@ describe('useFileTree refresh scheduling', () => {vi.clearAllMocks();mocks.eventCallbacks.length = 0;mocks.fileBrowserApiFor.mockReturnValue({ listDir: mocks.listDir });+ // clearAllMocks 不重置实现:用例自设的 loadExpandedSet 行为要在每个用例前复位。+ mocks.loadExpandedSet.mockImplementation(() => new Set<string>());});it('limits a directory refresh to one trailing scan during a watcher storm', async () => {@@ -137,6 +141,8 @@ describe('useFileTree showIgnoredDirs option', () => {mocks.eventCallbacks.length = 0;mocks.listDir.mockResolvedValue([]);mocks.fileBrowserApiFor.mockReturnValue({ listDir: mocks.listDir });+ // clearAllMocks 不重置实现:用例自设的 loadExpandedSet 行为要在每个用例前复位。+ mocks.loadExpandedSet.mockImplementation(() => new Set<string>());});it('listDir / startWatch 带上开关值', async () => {@@ -343,6 +349,103 @@ describe('useFileTree showIgnoredDirs option', () => {view.unmount();});+ /**+ * 评审 P1(PR #4398 轮七):创建 store 时借的是另一半 scope 的过渡快照,而剪枝+ * 会**同步回写本 scope 的 localStorage** —— 剪之前必须先读本 scope 自己的持久+ * 记录并豁免它,否则切回隐藏态时用户原有(本 scope)的展开位会被一起抹掉。+ */+ it('切回隐藏态时保留本 scope 已持久化的展开位', async () => {+ const revealedRoot: readonly DirEntry[] = [+ { name: 'src', relPath: 'src', type: 'directory', size: 0, mtimeMs: 1 },+ { name: 'docs', relPath: 'docs', type: 'directory', size: 0, mtimeMs: 1 },+ { name: 'node_modules', relPath: 'node_modules', type: 'directory', size: 0, mtimeMs: 1 },+ ];+ const hiddenRoot = revealedRoot.filter((entry) => entry.name !== 'node_modules');+ mocks.listDir.mockImplementation((args: { showIgnoredDirs?: boolean }) =>+ Promise.resolve(args.showIgnoredDirs ? revealedRoot : hiddenRoot),+ );+ // 上一次会话里 hidden scope 自己存过展开位:docs。+ mocks.loadExpandedSet.mockImplementation(+ (_workdir: string, opts?: { showIgnoredDirs?: boolean }) =>+ opts?.showIgnoredDirs ? new Set<string>() : new Set(['docs']),+ );++ const view = renderHook(+ ({ reveal }: { reveal: boolean }) =>+ useFileTree({ workdir: '/workdir-scope-keep', showIgnoredDirs: reveal }),+ { initialProps: { reveal: true } },+ );+ await waitFor(() => expect(view.result.current.initialLoading).toBe(false));+ await act(async () => {+ view.result.current.toggleFolder('node_modules');+ });+ expect(view.result.current.expanded.has('node_modules')).toBe(true);++ await act(async () => {+ view.rerender({ reveal: false });+ });++ // 剪枝回写必须保留本 scope 既有的 'docs',同时仍然剪掉借来的 node_modules。+ const hiddenWrites = mocks.saveExpandedSet.mock.calls+ .filter((call) => (call[2] as { showIgnoredDirs?: boolean } | undefined)?.showIgnoredDirs === false)+ .map((call) => call[1] as Set<string>);+ expect(hiddenWrites.length).toBeGreaterThan(0);+ const lastWrite = hiddenWrites.at(-1)!;+ expect(lastWrite.has('docs')).toBe(true);+ expect(lastWrite.has('node_modules')).toBe(false);++ // 内存里也保留:切回后 docs 仍是展开态。+ expect(view.result.current.expanded.has('docs')).toBe(true);+ expect(view.result.current.expanded.has('node_modules')).toBe(false);++ view.unmount();+ });++ /**+ * 评审 P1(PR #4398 轮七)的另一半:反向切到放行态时,seed 是**隐藏态**的树+ * (本来就看不到被忽略目录),不能拿它判断放行态自己的展开位不可达 —— `keep`+ * 必须豁免本 scope 的持久记录,否则用户在放行态展开的 node_modules 会在切回时+ * 被剪掉。+ */+ it('切到放行态时保留本 scope 已持久化的展开位(借来的隐藏树判不了它)', async () => {+ const hiddenRoot: readonly DirEntry[] = [+ { name: 'src', relPath: 'src', type: 'directory', size: 0, mtimeMs: 1 },+ ];+ const revealedRoot: readonly DirEntry[] = [+ ...hiddenRoot,+ { name: 'node_modules', relPath: 'node_modules', type: 'directory', size: 0, mtimeMs: 2 },+ ];+ mocks.listDir.mockImplementation((args: { showIgnoredDirs?: boolean }) =>+ Promise.resolve(args.showIgnoredDirs ? revealedRoot : hiddenRoot),+ );+ // 放行态 scope 上次会话存过 node_modules 展开位。+ mocks.loadExpandedSet.mockImplementation(+ (_workdir: string, opts?: { showIgnoredDirs?: boolean }) =>+ opts?.showIgnoredDirs ? new Set(['node_modules']) : new Set<string>(),+ );++ const view = renderHook(+ ({ reveal }: { reveal: boolean }) =>+ useFileTree({ workdir: '/workdir-scope-keep-reveal', showIgnoredDirs: reveal }),+ { initialProps: { reveal: false } },+ );+ await waitFor(() => expect(view.result.current.initialLoading).toBe(false));++ await act(async () => {+ view.rerender({ reveal: true });+ });++ // 借来的隐藏树里没有 node_modules,不能因此把放行态自己的展开位剪掉:+ // 要么没回写,要么回写里必须带着它。+ const revealWrites = mocks.saveExpandedSet.mock.calls+ .filter((call) => (call[2] as { showIgnoredDirs?: boolean } | undefined)?.showIgnoredDirs === true)+ .map((call) => call[1] as Set<string>);+ expect(revealWrites.every((set) => set.has('node_modules'))).toBe(true);+ expect(view.result.current.expanded.has('node_modules')).toBe(true);++ view.unmount();+ });+/*** 评审 P1:被忽略目录嵌在已展开的普通目录下时(`packages/foo/node_modules`),* 只滤根列表的实现会把它一直留在展开的父目录下 —— 而且 prune 拿过期的 reveal@@ -802,6 +905,7 @@ describe('useFileTree device 的 showIgnoredDirs 能力探测', () => {mocks.eventCallbacks.length = 0;mocks.listDir.mockResolvedValue([]);mocks.fileBrowserApiFor.mockReturnValue({ listDir: mocks.listDir });+ mocks.loadExpandedSet.mockImplementation(() => new Set<string>());mocks.deviceSupportsRevealIgnoredDirs.mockImplementation(async () => true);mocks.reconnectEpoch.current = 0;});diff --git a/apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useFileTree.ts b/apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useFileTree.tsindex 1b6a696e64..fdf36f69c5 100644--- a/apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useFileTree.ts+++ b/apps/desktop/src/renderer/features/cc-agent/workdir-browse/hooks/useFileTree.ts@@ -353,12 +353,19 @@ function findRevealSiblingSnapshot(* 查不到祖先列表(缓存被清 / 还没拉过)时保守保留 —— 宁可留一个 stale 展开位,* 也不能把用户真实的展开态删掉。*- * 剪枝后**同步回写持久化**(评审 P2):过渡窗口里 root 数据还没到时,用户若做过- * 一次 toggleFolder,那次 saveExpandedSet 会把继承来的 reveal-only 路径一并- * 写进本 scope —— 不回写就会把它们固化进 localStorage,下次挂载按这些路径逐个- * listDir(上限 200 个,SSH / device-link 上代价明显)。+ * 剪枝后**同步回写持久化**(评审 P2):过渡窗口里 root 数据还没到时,用户若做过+ * 一次 toggleFolder,那次 saveExpandedSet 会把继承来的 reveal-only 路径一并+ * 写进本 scope —— 不回写就会把它们固化进 localStorage,下次挂载按这些路径逐个+ * listDir(上限 200 个,SSH / device-link 上代价明显)。+ *+ * `keep`:目标 scope **自己持久化过**的展开位,豁免剪枝。回写是整份覆盖,调用方+ * 必须先把这些路径并进 `snapshot.expanded` 再调本函数,否则它们会被这次回写抹掉+ * (评审 P1:借来的树只能当过渡内容,不能拿它否定本 scope 自己的记录)。*/-function pruneExpandedForCurrentTree(store: FileTreeStore): void {+function pruneExpandedForCurrentTree(+ store: FileTreeStore,+ opts?: { keep?: ReadonlySet<string> },+): void {if (!store.snapshot.entries.has(ROOT_KEY)) return;const reachable = (relPath: string): boolean => {const parts = relPath.split('/');@@ -375,7 +382,7 @@ function pruneExpandedForCurrentTree(store: FileTreeStore): void {const next = new Set<string>();let changed = false;for (const relPath of store.snapshot.expanded) {- if (relPath === ROOT_KEY || reachable(relPath)) next.add(relPath);+ if (relPath === ROOT_KEY || opts?.keep?.has(relPath) || reachable(relPath)) next.add(relPath);else changed = true;}if (!changed) return;@@ -391,6 +398,12 @@ function getOrCreateStore(opts: Required<UseFileTreeOptions>): FileTreeStore {// 切开关路径:借另一半 reveal scope 的整棵树当首帧内容,不经过 initialLoading// 空白;首次挂载(无兄弟 store)仍走原来的 loading 路径。const seed = findRevealSiblingSnapshot(opts);+ // 本 scope 自己持久化过的展开位:seed 是**过渡内容**,而下面的剪枝会同步回写+ // 本 scope 的 localStorage —— 不先读出来并进快照,「借来的树里不可达」就会+ // 连带抹掉本 scope 原有记录(评审 P1:切回隐藏态后目录无故全部折叠)。+ const persistedExpanded = loadExpandedSet(opts.workdir, {+ showIgnoredDirs: opts.showIgnoredDirs,+ });// 兄弟 store 可能还卡在首次 listDir 上(慢通道):没有可显示内容时不得冒充// 「已加载」—— 否则 FileTreeView 会把 initialLoading:false + 空 rows 渲染成// 「此文件夹为空」,而不是延迟 loading 态。终态错误可显示(渲染错误占位)。@@ -411,7 +424,8 @@ function getOrCreateStore(opts: Required<UseFileTreeOptions>): FileTreeStore {entries: opts.showIgnoredDirs? seed.entries: filterSeedTreeForHiddenView(seed.entries),- expanded: seed.expanded,+ // 借来的过渡展开态 + 本 scope 已有的持久记录(见上方 persistedExpanded)。+ expanded: new Set([...seed.expanded, ...persistedExpanded]),// 新 store 自己还没有 in-flight 请求,seed 的 loadingPaths 不继承。loadingPaths: new Set(),initialLoading: false,@@ -438,7 +452,9 @@ function getOrCreateStore(opts: Required<UseFileTreeOptions>): FileTreeStore {// 成功分支上,根请求失败时根本不会执行 —— 而 reveal-only 路径一旦被写进本// scope 的 localStorage(用户在错误恢复前操作目录、或 expandToPath 等路径),// 下次挂载就会变成最多 200 次无用 listDir(评审 P2)。剪完顺带回写本 scope。- pruneExpandedForCurrentTree(store);+ // `keep` = 本 scope 自己的持久记录:借来的树只能判「借来的路径」,不能否定本+ // scope 的展开位(评审 P1)。+ pruneExpandedForCurrentTree(store, { keep: persistedExpanded });stores.set(key, store);return store;}