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): 创建 store 时即剪枝继承展开位 + watcher 错误重建带退避重试
Zhang Yunjin3bfff2633577
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 622fb65683..360e2883aa 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@@ -318,13 +318,14 @@ describe('useFileTree showIgnoredDirs option', () => {view.rerender({ reveal: false });});- // 数据还没回来:被忽略行已由首帧过滤拿掉,它的**整棵缓存**也一起丢了- // (否则 refresh() 会按 entries key 重扫它);展开态保持不动 —— 树其余部分- // 不重新挂载,不是逐级折叠。+ // 数据还没回来:被忽略行已由首帧过滤拿掉,它的整棵缓存与展开位也一起剪掉+ // (缓存留着会被 refresh() 按 entries key 重扫;展开位留着会被过渡窗口里的+ // 操作写进本 scope 的 localStorage);树的其余部分保持不动 —— 不重新挂载、+ // 不逐级折叠。expect(view.result.current.initialLoading).toBe(false);expect(view.result.current.entries.get('')?.map((e) => e.name)).toEqual(['src']);expect(view.result.current.entries.has('node_modules')).toBe(false);- expect(view.result.current.expanded.has('node_modules')).toBe(true);+ expect(view.result.current.expanded.has('node_modules')).toBe(false);// 过渡期不 warm 借来的子树 —— 不给被忽略路径白发 listDir。const hiddenCalls = mocks.listDir.mock.calls.filter((c) => c[0].showIgnoredDirs === false);expect(hiddenCalls.map((c) => c[0].relPath)).toEqual(['']);@@ -516,12 +517,11 @@ describe('useFileTree showIgnoredDirs option', () => {});/**- * 评审 P2:切到隐藏态后、root 数据回来前操作目录,会把继承来的 reveal-only- * 展开位写进隐藏 scope(那次 saveExpandedSet 早于剪枝);剪枝发生在 root 回来时,- * 必须**同步回写**清理后的集合,否则脏路径固化进 localStorage,下次挂载按它们- * 逐个 listDir。+ * 评审 P2(延续):进入隐藏态时就把继承的 reveal-only 展开位剪掉,所以过渡窗口+ * 里的任何操作写下的集合都是干净的 —— 不再依赖「root 回来时回写」兜底(根请求+ * 失败时那条路径根本不执行)。*/- it('剪枝时回写持久化,隐藏 scope 不残留 reveal-only 展开位', async () => {+ it('过渡窗口操作目录也不会把 reveal-only 展开位写进隐藏 scope', async () => {const revealedRoot: readonly DirEntry[] = [{ name: 'src', relPath: 'src', type: 'directory', size: 0, mtimeMs: 1 },{ name: 'node_modules', relPath: 'node_modules', type: 'directory', size: 0, mtimeMs: 1 },@@ -554,20 +554,20 @@ describe('useFileTree showIgnoredDirs option', () => {});await waitFor(() => expect(view.result.current.expanded.has('node_modules')).toBe(true));- // 切到隐藏态:root 挂起,处于过渡窗口;继承的展开位仍在内存里。+ // 切到隐藏态:root 挂起,处于过渡窗口;创建时就已剪掉继承来的展开位。await act(async () => {view.rerender({ reveal: false });});- expect(view.result.current.expanded.has('node_modules')).toBe(true);+ expect(view.result.current.expanded.has('node_modules')).toBe(false);- // 过渡窗口里操作普通目录 —— 这一发 saveExpandedSet 会带上继承来的- // node_modules(旧实现如此)。+ // 过渡窗口里操作普通目录 —— 写进隐藏 scope 的集合必须是干净的(旧实现会把+ // 继承来的 node_modules 一并写进去,之后只能靠 root 回来时的回写兜底)。mocks.saveExpandedSet.mockClear();await act(async () => {view.result.current.toggleFolder('src');});- // root 数据回来 → 剪枝 → 必须回写清理后的集合。+ // root 数据回来也不该改变这个结论。await act(async () => {pendingRoot.resolve(hiddenRoot);await Promise.resolve();@@ -584,6 +584,56 @@ describe('useFileTree showIgnoredDirs option', () => {view.unmount();});+ /**+ * 评审 P2:根请求**失败**时剪枝那条路径根本不会执行(它挂在 fetch 成功分支上),+ * 而继承来的 reveal-only 展开位仍会随用户操作写进本 scope 的 localStorage。+ * 所以创建 store 时就要按(可能已过滤的)继承树剪一次。+ */+ it('创建隐藏 store 时即剪掉继承的 reveal-only 展开位(根请求失败也不残留)', async () => {+ const revealedRoot: readonly DirEntry[] = [+ { name: 'src', relPath: 'src', type: 'directory', size: 0, mtimeMs: 1 },+ { name: 'node_modules', relPath: 'node_modules', type: 'directory', size: 0, mtimeMs: 1 },+ ];+ const revealedChild: readonly DirEntry[] = [+ { name: 'pkg', relPath: 'node_modules/pkg', type: 'directory', size: 0, mtimeMs: 1 },+ ];++ // 隐藏态的 listDir 全部失败(模拟根请求失败:剪枝没有第二次机会)。+ mocks.listDir.mockImplementation((args: { relPath?: string; showIgnoredDirs?: boolean }) => {+ if (!args.showIgnoredDirs) return Promise.reject(new Error('boom'));+ if (args.relPath === 'node_modules') return Promise.resolve(revealedChild);+ return Promise.resolve(revealedRoot);+ });++ const view = renderHook(+ ({ reveal }: { reveal: boolean }) =>+ useFileTree({ workdir: '/workdir-create-prune', showIgnoredDirs: reveal }),+ { initialProps: { reveal: true } },+ );+ await waitFor(() => expect(view.result.current.initialLoading).toBe(false));+ await act(async () => {+ view.result.current.toggleFolder('node_modules');+ });+ await waitFor(() => expect(view.result.current.expanded.has('node_modules')).toBe(true));++ mocks.saveExpandedSet.mockClear();+ await act(async () => {+ view.rerender({ reveal: false });+ });+ await waitFor(() => expect(view.result.current.loadError).toBe('load-failed'));++ // 即使根请求失败:隐藏 scope 已经写入了剪枝后的集合,且不含 node_modules。+ const persistedHidden = mocks.saveExpandedSet.mock.calls+ .filter((c) => c[2]?.showIgnoredDirs === false)+ .map((c) => c[1] as Set<string>)+ .at(-1);+ expect(persistedHidden).toBeDefined();+ expect(persistedHidden?.has('node_modules')).toBe(false);+ expect(view.result.current.expanded.has('node_modules')).toBe(false);++ view.unmount();+ });+/*** 兄弟 store 还在首次 listDir 上(慢通道)时不能冒充「已加载」:没有可显示内容* 就保持 initialLoading,否则 FileTreeView 会把空 rows 渲染成「此文件夹为空」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 ffcbb063ee..d60139724c 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@@ -419,6 +419,11 @@ function getOrCreateStore(opts: Required<UseFileTreeOptions>): FileTreeStore {refCount: 0,listeners: new Set(),};+ // 继承来的展开集合要按**(可能已过滤的)**树剪一次:剪枝那条路径挂在 fetch+ // 成功分支上,根请求失败时根本不会执行 —— 而 reveal-only 路径一旦被写进本+ // scope 的 localStorage(用户在错误恢复前操作目录、或 expandToPath 等路径),+ // 下次挂载就会变成最多 200 次无用 listDir(评审 P2)。剪完顺带回写本 scope。+ pruneExpandedForCurrentTree(store);stores.set(key, store);return store;}diff --git a/packages/remote-file-service/src/__tests__/watchOptions.test.ts b/packages/remote-file-service/src/__tests__/watchOptions.test.tsindex 07ec1a754b..edbd104746 100644--- a/packages/remote-file-service/src/__tests__/watchOptions.test.ts+++ b/packages/remote-file-service/src/__tests__/watchOptions.test.ts@@ -299,6 +299,39 @@ describe('WorkdirWatchManager 过滤开关', () => {manager.stopAll();});+ /**+ * 评审 P2:watcher 报错后紧接着的 reconcile 又失败时不能只记日志 —— 消费者+ * 意图还在 desired,但没有 watcher、也没有定时器再收敛,SSH 连接没断的情况下+ * 事件会永久停止。要有带退避与上限的重试(退避避免持续失败时紧密重建循环)。+ */+ it('watcher 出错后收敛失败:退避重试直到恢复', async () => {+ vi.useFakeTimers();+ try {+ const manager = new WorkdirWatchManager(() => {});+ await manager.start('/repo', { showIgnoredDirs: true }, 'desktop-tree');+ expect(h.created).toHaveLength(1);++ // 触发 error(拆掉 entry → 立即 reconcile),并让这次 reconcile 失败。+ let failWith = (_err: Error): void => {};+ h.gate = new Promise<void>((_resolve, reject) => {+ failWith = reject;+ });+ const onSpy = h.created[0].watcher.on as unknown as ReturnType<typeof vi.fn>;+ const handler = onSpy.mock.calls.find(([evt]) => evt === 'error')?.[1] as (err: Error) => void;+ handler(new Error('boom'));+ failWith(new Error('reconcile failed'));+ await vi.advanceTimersByTimeAsync(0);++ // 退避(500ms)后重试成功:重新建出活着的 watcher。+ await vi.advanceTimersByTimeAsync(600);+ expect(h.created.length).toBeGreaterThanOrEqual(2);+ expect(h.created.at(-1)?.closed).toBe(false);+ manager.stopAll();+ } finally {+ vi.useRealTimers();+ }+ });+/*** 评审 P1:启动失败时若把消费者的意图留在 desired 里,控制端只会清本地注册、* 不会再发 watchStop → daemon 里多出一个幽灵消费者:它抬高别的消费者的可见性diff --git a/packages/remote-file-service/src/watch.ts b/packages/remote-file-service/src/watch.tsindex 3c91ccd797..43211a7e8b 100644--- a/packages/remote-file-service/src/watch.ts+++ b/packages/remote-file-service/src/watch.ts@@ -126,6 +126,11 @@ function sameWatchOptions(a: WatchFilterOptions, b: WatchFilterOptions): booleanconst COALESCE_MS = 50;+/** watcher 报错后重建的退避参数:起点 / 上限 / 次数上限。 */+const RECONCILE_RETRY_BASE_MS = 500;+const RECONCILE_RETRY_MAX_MS = 8_000;+const RECONCILE_RETRY_LIMIT = 5;+export class WorkdirWatchManager {private readonly entries = new Map<string, WatchEntry>();/** 启动中的 workdir:has 判定与 entries.set 之间隔着 loadIgnoreMatcher 的@@ -141,6 +146,10 @@ export class WorkdirWatchManager {* 每轮重读它收敛。 */private readonly desired = new Map<string, Map<string, ConsumerIntent>>();+ /** watcher 报错后的重建重试定时器与次数(退避 + 上限,见 scheduleReconcileRetry)。 */+ private readonly retryTimers = new Map<string, NodeJS.Timeout>();+ private readonly retryAttempts = new Map<string, number>();+/** 没带 consumerId 的调用方(旧控制端 / 内部调用)归到这个默认消费者。 */private static readonly DEFAULT_CONSUMER = 'default';private readonly emit: (event: RemoteFileTreeEvent) => void;@@ -166,6 +175,7 @@ export class WorkdirWatchManager {this.desired.set(workdir, consumers);try {await this.reconcile(workdir);+ this.clearReconcileRetry(workdir); // 新意图已生效:旧的重试状态作废// 成功才记 committed:失败回滚只恢复到「真的生效过」的值。const settled = this.desired.get(workdir)?.get(consumerId);if (settled && settled.options === attempted) settled.committed = attempted;@@ -258,6 +268,52 @@ export class WorkdirWatchManager {return { showIgnoredDirs, hideMetaFiles: !showMetaFiles };}+ /**+ * watcher 报错后的收敛重试(退避 + 上限)。+ *+ * 为什么不能只 catch 一下:错误把 entry 拆掉后,如果紧接着的 reconcile 又失败+ * (远程挂载短暂不可用 / 目录正在被替换),消费者意图仍留在 desired、但已经+ * 没有 watcher,也没有任何定时器会再来收敛 —— SSH 连接没断的情况下,后续文件+ * 事件会永久停止,直到用户改开关或重挂载面板(评审 P2)。退避避免持续失败时+ * 形成紧密重建循环。+ */+ private scheduleReconcileRetry(workdir: string): void {+ if (this.retryTimers.has(workdir)) return;+ if (!this.desired.has(workdir)) return; // 期间消费者全撤了:不再重试+ const attempt = (this.retryAttempts.get(workdir) ?? 0) + 1;+ if (attempt > RECONCILE_RETRY_LIMIT) {+ this.retryAttempts.delete(workdir);+ log.warn('watch reconcile retries exhausted', workdir);+ return;+ }+ this.retryAttempts.set(workdir, attempt);+ const delay = Math.min(+ RECONCILE_RETRY_BASE_MS * 2 ** (attempt - 1),+ RECONCILE_RETRY_MAX_MS,+ );+ const timer = setTimeout(() => {+ this.retryTimers.delete(workdir);+ void this.reconcile(workdir)+ .then(() => this.retryAttempts.delete(workdir))+ .catch((err) => {+ log.warn('watch reconcile retry failed', workdir, String(err));+ this.scheduleReconcileRetry(workdir);+ });+ }, delay);+ timer.unref?.();+ this.retryTimers.set(workdir, timer);+ }++ /** 清掉某个 workdir 的重试状态(stop / 新 start 成功时调用)。 */+ private clearReconcileRetry(workdir: string): void {+ const timer = this.retryTimers.get(workdir);+ if (timer) {+ clearTimeout(timer);+ this.retryTimers.delete(workdir);+ }+ this.retryAttempts.delete(workdir);+ }+private async startInner(workdir: string, opts: WatchFilterOptions): Promise<void> {const matcher = await loadIgnoreMatcher(workdir, {hideMetaFiles: opts.hideMetaFiles,@@ -286,9 +342,14 @@ export class WorkdirWatchManager {log.warn('fs.watch error, dropping watcher', workdir, String(err));if (this.entries.get(workdir) !== entry) return; // 已被替换 / 停止:不碰新 entrythis.closeEntry(workdir);- void this.reconcile(workdir).catch((rerr) =>- log.warn('watch reconcile after error failed', workdir, String(rerr)),- );+ // 就地收敛;失败(挂载短暂不可用 / 目录正在被替换)则带退避重试,直到成功+ // 或耗尽 —— 只记日志会让这个入口静默失效到用户改开关(评审 P2)。+ void this.reconcile(workdir)+ .then(() => this.retryAttempts.delete(workdir))+ .catch((rerr) => {+ log.warn('watch reconcile after error failed', workdir, String(rerr));+ this.scheduleReconcileRetry(workdir);+ });});entry.watcher = watcher;if (this.stopDuringStart.delete(workdir)) {@@ -322,6 +383,7 @@ export class WorkdirWatchManager {}this.desired.delete(workdir);}+ this.clearReconcileRetry(workdir);// 撤销意图:收敛循环读到 desired 缺失即结束(piggyback 的新 start 会写回)。// 还在启动窗口:打标记让 startInner 完成时自拆(entries 里此刻还没有它)。if (this.starting.has(workdir)) this.stopDuringStart.add(workdir);@@ -345,6 +407,9 @@ export class WorkdirWatchManager {stopAll(): void {// 全部意图撤销:启动中的 workdir 也要让收敛循环看到「没有 desired」而结束。this.desired.clear();+ for (const timer of this.retryTimers.values()) clearTimeout(timer);+ this.retryTimers.clear();+ this.retryAttempts.clear();for (const workdir of [...this.starting.keys()]) this.stopDuringStart.add(workdir);for (const workdir of [...this.entries.keys()]) this.closeEntry(workdir);}