Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): bound foreground worktree validation and batch Git probes (#4109)
Dash94573ab1afe7
diff --git a/apps/desktop/scripts/benchmark-worktree-focus.mjs b/apps/desktop/scripts/benchmark-worktree-focus.mjsnew file mode 100644index 0000000000..584a05607d--- /dev/null+++ b/apps/desktop/scripts/benchmark-worktree-focus.mjs@@ -0,0 +1,243 @@+/**+ * Explicit, real-Git benchmark (not a unit test).+ * node apps/desktop/scripts/benchmark-worktree-focus.mjs <baseline-ref>+ * Executes the baseline/current detectCwd and WorktreeProvider source with a+ * minimal hooks/IPC harness. Git is real; Electron, rendering and IPC are not.+ * Cooldown time is virtual, reported execution times exclude that wait.+ */+import assert from 'node:assert/strict';+import { execFile } from 'node:child_process';+import fs from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';+import { performance } from 'node:perf_hooks';+import { promisify } from 'node:util';+import vm from 'node:vm';+import ts from 'typescript';++const exec = promisify(execFile);+const baseline = process.argv[2];+if (!baseline) throw new Error('Pass the baseline Git ref explicitly');+const root = (await exec('git', ['rev-parse', '--show-toplevel'])).stdout.trim();+const managerPath = 'apps/desktop/src/main/worktree/WorktreeManager.ts';+const providerPath = 'apps/desktop/src/renderer/contexts/WorktreeContext.tsx';+const source = async (ref, file) =>+ ref+ ? (await exec('git', ['show', `${ref}:${file}`], { cwd: root })).stdout+ : fs.readFile(path.join(root, file), 'utf8');+const versions = await Promise.all(+ [baseline, null].map(async (ref) => ({+ label: ref ? 'before' : 'after',+ manager: await source(ref, managerPath),+ provider: await source(ref, providerPath),+ })),+);++function functionsOnly(sourceText, names, tsx = false) {+ const ast = ts.createSourceFile(+ tsx ? 'source.tsx' : 'source.ts',+ sourceText,+ ts.ScriptTarget.Latest,+ true,+ tsx ? ts.ScriptKind.TSX : ts.ScriptKind.TS,+ );+ const statements = ast.statements.filter(+ (s) =>+ (ts.isFunctionDeclaration(s) && names.includes(s.name?.text)) ||+ (ts.isVariableStatement(s) &&+ s.declarationList.declarations.some((d) => names.includes(d.name.getText(ast)))),+ );+ assert.equal(statements.length, names.length, 'benchmark source extraction drifted');+ return ts.transpileModule(statements.map((s) => s.getText(ast)).join('\n'), {+ compilerOptions: {+ target: ts.ScriptTarget.ES2022,+ module: ts.ModuleKind.CommonJS,+ jsx: ts.JsxEmit.React,+ },+ }).outputText;+}++const fixture = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-worktree-focus-'));+const env = Object.fromEntries(+ Object.entries(process.env).filter(([key]) => !key.startsWith('GIT_')),+);+Object.assign(env, {+ GIT_CONFIG_GLOBAL: process.platform === 'win32' ? 'NUL' : os.devNull,+ GIT_CONFIG_NOSYSTEM: '1',+ GIT_TERMINAL_PROMPT: '0',+});+const rawGit = (args, cwd) => exec('git', args, { cwd, env, windowsHide: true });+const tick = () => new Promise(setImmediate);++async function run(version, dirs, scenario) {+ let count = 0,+ active = 0,+ peak = 0,+ probes = 0,+ now = 0;+ let metas = {};+ const effects = [],+ disposers = [],+ listeners = new Map(),+ timers = new Map();+ const statsReset = () => {+ count = 0;+ peak = 0;+ };+ const gitExec = async (args, cwd) => {+ count++;+ peak = Math.max(peak, ++active);+ try {+ return await rawGit(args, cwd);+ } finally {+ active--;+ }+ };+ const context = vm.createContext({+ exports: {},+ path,+ gitExec,+ GitExecError: Error,+ getManagedWorktreeBasePath: () => null,+ log: {+ warn: (...args) => {+ throw new Error(JSON.stringify(args));+ },+ },+ React: { createElement: () => null },+ WorktreeContext: { Provider: {} },+ useRef: (current) => ({ current }),+ useCallback: (fn) => fn,+ useMemo: (fn) => fn(),+ useState: () => [+ metas,+ (value) => {+ metas = typeof value === 'function' ? value(metas) : value;+ },+ ],+ useEffect: (fn) => effects.push(fn),+ Date: { now: () => now },+ setTimeout: (fn, ms) => {+ const id = Symbol();+ timers.set(id, { fn, at: now + ms });+ return id;+ },+ clearTimeout: (id) => timers.delete(id),+ window: {+ addEventListener: (name, fn) => listeners.set(name, fn),+ removeEventListener: (name) => listeners.delete(name),+ electronAPI: {+ worktreeListAll: async () => dirs.map((dir, i) => ({ sessionId: String(i), path: dir })),+ worktreeDetectCwd: async ({ cwd }) => {+ probes++;+ try {+ return await context.detectCwd(cwd);+ } finally {+ probes--;+ }+ },+ },+ },+ });+ vm.runInContext(functionsOnly(version.manager, ['detectCwd']), context);+ const names = ['isLiveOfficialPath', 'WorktreeProvider'];+ if (version.label === 'after')+ names.push('FOREGROUND_REFRESH_INTERVAL_MS', 'VALIDATION_CONCURRENCY');+ vm.runInContext(functionsOnly(version.provider, names, true), context);+ const drain = async () => {+ const deadline = performance.now() + 120_000;+ do {+ if (performance.now() > deadline) throw new Error('benchmark timed out');+ await new Promise((resolve) => setTimeout(resolve, 2));+ } while (probes || active);+ await tick();+ };+ let start = performance.now();+ context.WorktreeProvider({ children: null });+ effects.forEach((fn) => disposers.push(fn()));+ await drain();+ assert.equal(Object.keys(metas).length, dirs.length);+ if (scenario !== 'cold') {+ statsReset();+ now = scenario === 'warm-focus' ? 1000 : 20_000;+ start = performance.now();+ listeners.get('focus')();+ // All ten focus events arrive while the first Git probe is still running.+ await tick();+ for (let i = 1; i < 10; i++) listeners.get('focus')();+ await drain();+ }+ const immediate = {+ gitProcesses: count,+ peakGitProcesses: peak,+ elapsedMs: +(performance.now() - start).toFixed(2),+ };+ let trailing = null;+ if (timers.size) {+ statsReset();+ start = performance.now();+ for (const [id, timer] of timers) {+ timers.delete(id);+ now = timer.at;+ timer.fn();+ }+ await drain();+ trailing = {+ gitProcesses: count,+ peakGitProcesses: peak,+ elapsedMs: +(performance.now() - start).toFixed(2),+ };+ }+ assert.equal(Object.keys(metas).length, dirs.length);+ disposers.forEach((dispose) => dispose?.());+ return { version: version.label, worktrees: dirs.length, scenario, ...immediate, trailing };+}++try {+ const repo = path.join(fixture, 'repo');+ await fs.mkdir(repo);+ await rawGit(['init', '--quiet'], repo);+ await rawGit(+ [+ '-c',+ 'user.name=Benchmark',+ '-c',+ '[email protected]',+ 'commit',+ '--quiet',+ '--allow-empty',+ '-m',+ 'fixture',+ ],+ repo,+ );+ const dirs = [];+ for (let i = 0; i < 100; i++) {+ const dir = path.join(fixture, `worktree-${i}`);+ await rawGit(['worktree', 'add', '--quiet', '--detach', dir, 'HEAD'], repo);+ dirs.push(dir);+ }+ console.log(+ JSON.stringify({+ platform: process.platform,+ arch: process.arch,+ node: process.version,+ git: (await rawGit(['--version'], repo)).stdout.trim(),+ baseline,+ note: 'Real temporary Git worktrees; source-level hooks/IPC harness; not Electron/Windows UI profiling.',+ }),+ );+ for (let repeat = 1; repeat <= 3; repeat++) {+ for (const size of [10, 30, 100]) {+ for (const scenario of ['cold', 'focus-burst', 'warm-focus']) {+ for (const version of repeat % 2 ? versions : [...versions].reverse()) {+ console.log(+ JSON.stringify({ repeat, ...(await run(version, dirs.slice(0, size), scenario)) }),+ );+ }+ }+ }+ }+} finally {+ await fs.rm(fixture, { recursive: true, force: true });+}diff --git a/apps/desktop/src/main/__tests__/worktreeDetectCwd.git-integration.test.ts b/apps/desktop/src/main/__tests__/worktreeDetectCwd.git-integration.test.tsnew file mode 100644index 0000000000..74c20518e8--- /dev/null+++ b/apps/desktop/src/main/__tests__/worktreeDetectCwd.git-integration.test.ts@@ -0,0 +1,78 @@+import { execFile } from 'node:child_process';+import fs from 'node:fs/promises';+import os from 'node:os';+import path from 'node:path';+import { promisify } from 'node:util';+import { afterEach, expect, it, vi } from 'vitest';++import { detectCwd } from '../worktree/WorktreeManager';++const exec = promisify(execFile);+let fixture: string | undefined;++afterEach(async () => {+ vi.unstubAllEnvs();+ if (fixture) await fs.rm(fixture, { recursive: true, force: true });+});++it('preserves real Git snapshots for attached, detached, unborn, missing and nested directories', async () => {+ for (const key of Object.keys(process.env)) {+ if (key.startsWith('GIT_')) vi.stubEnv(key, undefined);+ }+ vi.stubEnv('GIT_CONFIG_GLOBAL', process.platform === 'win32' ? 'NUL' : os.devNull);+ vi.stubEnv('GIT_CONFIG_NOSYSTEM', '1');+ fixture = await fs.mkdtemp(path.join(os.tmpdir(), 'cindy-detect-cwd-'));+ const repo = path.join(fixture, 'repo');+ await fs.mkdir(repo);+ const git = (...args: string[]) => exec('git', args, { cwd: repo, windowsHide: true });+ await git('init', '--initial-branch=main');+ expect(await detectCwd(repo)).toMatchObject({+ isGitRepo: true,+ isInsideWorktree: false,+ gitInstalled: true,+ });+ await git(+ '-c',+ 'user.name=Test',+ '-c',+ '[email protected]',+ 'commit',+ '--allow-empty',+ '-m',+ 'fixture',+ );+ expect(await detectCwd(repo)).toMatchObject({ currentBranch: 'main', isInsideWorktree: false });++ const linked = path.join(fixture, 'linked');+ await git('worktree', 'add', '-b', 'feature', linked);+ const snapshot = await detectCwd(linked);+ expect(snapshot).toMatchObject({+ isGitRepo: true,+ isInsideWorktree: true,+ currentBranch: 'feature',+ });+ const subdir = path.join(linked, 'nested');+ await fs.mkdir(subdir);+ expect(await detectCwd(subdir)).toEqual(snapshot);+ await git('-C', linked, 'checkout', '--detach');+ expect(await detectCwd(linked)).toEqual({ ...snapshot, currentBranch: undefined });+ await git('worktree', 'remove', '--force', linked);+ expect(await detectCwd(linked)).toMatchObject({+ isGitRepo: false,+ isInsideWorktree: false,+ gitInstalled: true,+ });+ expect(await detectCwd(fixture)).toMatchObject({+ isGitRepo: false,+ isInsideWorktree: false,+ gitInstalled: true,+ });++ if (process.platform !== 'win32') {+ const newlinePath = path.join(fixture, 'line\nbreak');+ await git('worktree', 'add', '--detach', newlinePath);+ const newlineSnapshot = await detectCwd(newlinePath);+ expect(newlineSnapshot).toMatchObject({ isGitRepo: true, isInsideWorktree: true });+ expect(newlineSnapshot.repoRoot).toBe(await fs.realpath(newlinePath));+ }+}, 30_000);diff --git a/apps/desktop/src/main/__tests__/worktreeDetectCwd.test.ts b/apps/desktop/src/main/__tests__/worktreeDetectCwd.test.tsindex ab7290fce9..ece963a884 100644--- a/apps/desktop/src/main/__tests__/worktreeDetectCwd.test.ts+++ b/apps/desktop/src/main/__tests__/worktreeDetectCwd.test.ts@@ -17,9 +17,7 @@ const { gitExecMock } = vi.hoisted(() => ({gitExecMock: vi.fn(),}));vi.mock('../worktree/gitExec', async () => {- const actual = await vi.importActual<typeof import('../worktree/gitExec')>(- '../worktree/gitExec',- );+ const actual = await vi.importActual<typeof import('../worktree/gitExec')>('../worktree/gitExec');return {...actual,gitExec: (args: readonly string[], cwd?: string) => gitExecMock(args, cwd),@@ -48,7 +46,8 @@ function setupGitMock(opts: {const a = args.join(' ');if (a === '--version') return { stdout: 'git version 2.45.0\n', stderr: '' };if (a === 'rev-parse --show-toplevel') return { stdout: `${opts.toplevel}\n`, stderr: '' };- if (a === 'rev-parse --abbrev-ref HEAD') return { stdout: `${opts.branch ?? 'main'}\n`, stderr: '' };+ if (a === 'rev-parse --abbrev-ref HEAD')+ return { stdout: `${opts.branch ?? 'main'}\n`, stderr: '' };if (a === 'rev-parse --git-dir') return { stdout: `${opts.gitDir}\n`, stderr: '' };if (a === 'rev-parse --git-common-dir') return { stdout: `${opts.gitCommonDir}\n`, stderr: '' };throw new Error(`unexpected gitExec call: ${a}`);@@ -56,6 +55,33 @@ function setupGitMock(opts: {}describe('detectCwd → isInsideWorktree (I-1 fix)', () => {+ it.each([+ ['linked', '/repo/.git/worktrees/feature', '/repo/.git', 'feature', true],+ ['main', '.git', '.git', 'main', false],+ ['detached', '/repo/.git/worktrees/feature', '/repo/.git', 'HEAD', true],+ ])(+ 'reads a %s worktree snapshot with one Git process',+ async (_label, gitDir, commonDir, branch, linked) => {+ gitExecMock.mockResolvedValue({ stdout: `/repo\n${branch}\n${gitDir}\n${commonDir}\n` });+ expect(await detectCwd('/repo')).toEqual({+ isGitRepo: true,+ isInsideWorktree: linked,+ gitInstalled: true,+ supportsRecoveryKeyDiscard: true,+ repoRoot: path.resolve('/repo'),+ ...(branch !== 'HEAD' ? { currentBranch: branch } : {}),+ });+ expect(gitExecMock).toHaveBeenCalledOnce();+ },+ );++ it('retains separate queries when combined output has ambiguous newlines', async () => {+ setupGitMock({ toplevel: '/repo', gitDir: '.git', gitCommonDir: '.git' });+ gitExecMock.mockResolvedValueOnce({ stdout: '/repo\nwith-newline\nmain\n.git\n.git\n' });+ expect(await detectCwd('/repo')).toMatchObject({ isGitRepo: true, isInsideWorktree: false });+ expect(gitExecMock).toHaveBeenCalledTimes(6);+ });+it('returns isInsideWorktree=true for a Cindy-created worktree', async () => {const baseRepo = path.resolve('/tmp/repo');const wtPath = path.join(baseRepo, '.cindy-worktrees', 'jolly-turing');diff --git a/apps/desktop/src/main/__tests__/worktreeManagerRemove.test.ts b/apps/desktop/src/main/__tests__/worktreeManagerRemove.test.tsindex 8e6aa89e44..a2d9f7751c 100644--- a/apps/desktop/src/main/__tests__/worktreeManagerRemove.test.ts+++ b/apps/desktop/src/main/__tests__/worktreeManagerRemove.test.ts@@ -135,10 +135,12 @@ describe('removeWorktreeForSession', () => {}return { stdout: '', stderr: '' };});- crossProcessLockMock.mockReset().mockImplementation(- (_lockPath: string, _opts: unknown, task: (status: unknown) => Promise<unknown>) =>- task({ held: true }),- );+ crossProcessLockMock+ .mockReset()+ .mockImplementation(+ (_lockPath: string, _opts: unknown, task: (status: unknown) => Promise<unknown>) =>+ task({ held: true }),+ );isWorktreeDirtyMock.mockReset().mockResolvedValue(false);autoStashMock.mockReset().mockResolvedValue(true);restoreAutoStashMock.mockReset().mockResolvedValue(true);@@ -829,11 +831,11 @@ describe('removeWorktreeForSession', () => {});it('discard pre-created: recovery waits for an in-flight create before deciding the record is absent', async () => {- let releaseGitVersion!: () => void;+ let releaseGitProbe!: () => void;gitExecMock.mockImplementationOnce(() =>new Promise<{ stdout: string; stderr: string }>((resolve) => {- releaseGitVersion = () =>+ releaseGitProbe = () =>resolve({stdout: 'git version 2.50.0\n',stderr: '',@@ -849,7 +851,10 @@ describe('removeWorktreeForSession', () => {recoveryKey,});await vi.waitFor(() => {- expect(gitExecMock).toHaveBeenCalledWith(['--version']);+ expect(gitExecMock).toHaveBeenCalledWith(+ ['rev-parse', '--show-toplevel', '--abbrev-ref', 'HEAD', '--git-dir', '--git-common-dir'],+ BASE_REPO,+ );});let discardSettled = false;@@ -861,7 +866,7 @@ describe('removeWorktreeForSession', () => {await Promise.resolve();expect(discardSettled).toBe(false);- releaseGitVersion();+ releaseGitProbe();await expect(create).resolves.toMatchObject({ ok: false });await expect(discard).resolves.toEqual({ status: 'absent' });});@@ -1104,9 +1109,7 @@ describe('removeWorktreeForSession', () => {// 目录已删、store.del 已执行; 拿不到锁时不得做无锁 --unset-all, 而是落盘待下次启动补清expect(- gitExecMock.mock.calls.some(- ([args]) => Array.isArray(args) && args.includes('--unset-all'),- ),+ gitExecMock.mock.calls.some(([args]) => Array.isArray(args) && args.includes('--unset-all')),).toBe(false);expect(pendingSafeDirectoryCleanups).toContain(meta.path);});@@ -1147,9 +1150,7 @@ describe('removeWorktreeForSession', () => {// 复用路径: 不 --unset-all(条目归新 worktree), 只从待办移除expect(- gitExecMock.mock.calls.some(- ([args]) => Array.isArray(args) && args.includes(reusedPath),- ),+ gitExecMock.mock.calls.some(([args]) => Array.isArray(args) && args.includes(reusedPath)),).toBe(false);// 孤儿路径: 正常清理并出队expect(gitExecMock).toHaveBeenCalledWith([diff --git a/apps/desktop/src/main/worktree/WorktreeManager.ts b/apps/desktop/src/main/worktree/WorktreeManager.tsindex 1ce65cafe4..51c478effb 100644--- a/apps/desktop/src/main/worktree/WorktreeManager.ts+++ b/apps/desktop/src/main/worktree/WorktreeManager.ts@@ -26,7 +26,12 @@ import {} from './nameGenerator';import { readAttachedWorktreeBranch } from './attachedBranch';import { classifyError, type ClassifyInput } from './errorClassifier';-import { gitExec, GitExecError, globalSafeDirectoryLockPath, safeDirectorySpellings } from './gitExec';+import {+ gitExec,+ GitExecError,+ globalSafeDirectoryLockPath,+ safeDirectorySpellings,+} from './gitExec';import { withCrossProcessLock } from '../device-link/crossProcessLock';import { applyWorktreeIncludeFile, listChangedWorktreeIncludeFiles } from './includePatternsEngine';import { hasKeepSentinel, isManagedWorktreePath } from './safety';@@ -112,9 +117,7 @@ function activeWorktreePath(meta: WorktreeMeta): string {* 返回实际成功清理或本就不存在(exit 5)的目标; 其余失败仅告警、不算已清理, 由调用方* 决定是否落盘推迟到下次启动再试。*/-async function unsetSafeDirectoryEntriesLocked(- targets: Iterable<string>,-): Promise<string[]> {+async function unsetSafeDirectoryEntriesLocked(targets: Iterable<string>): Promise<string[]> {const cleaned: string[] = [];for (const target of targets) {let failed = false;@@ -393,6 +396,29 @@ async function withPrecreatedWorktreeOperationQueue<T>(* 探测 cwd 状态: 是否 git repo / 是否在 worktree 内 / git 是否可用 / 当前分支 / repo root*/export async function detectCwd(cwd: string): Promise<DetectCwdResp> {+ // One Git process returns the same snapshot that previously needed five.+ // Unborn HEADs, older Git versions and newline-containing paths retain the+ // individual-query fallback below rather than changing the IPC contract.+ try {+ const { stdout } = await gitExec(+ ['rev-parse', '--show-toplevel', '--abbrev-ref', 'HEAD', '--git-dir', '--git-common-dir'],+ cwd,+ );+ const lines = stdout.trim().split(/\r?\n/);+ if (lines.length === 4 && lines.every((line) => line.trim().length > 0)) {+ const [root, branch, gitDir, commonDir] = lines;+ return {+ isGitRepo: true,+ isInsideWorktree: path.resolve(cwd, gitDir.trim()) !== path.resolve(cwd, commonDir.trim()),+ gitInstalled: true,+ supportsRecoveryKeyDiscard: true,+ repoRoot: path.resolve(root.trim()),+ ...(branch !== 'HEAD' ? { currentBranch: branch.trim() } : {}),+ };+ }+ } catch {+ // Preserve the existing partial results and error classification.+ }const out: DetectCwdResp = {isGitRepo: false,isInsideWorktree: false,diff --git a/apps/desktop/src/renderer/__tests__/worktreeContextRecycleRefresh.test.tsx b/apps/desktop/src/renderer/__tests__/worktreeContextRecycleRefresh.test.tsxindex 52758d1bbd..9a059430bb 100644--- a/apps/desktop/src/renderer/__tests__/worktreeContextRecycleRefresh.test.tsx+++ b/apps/desktop/src/renderer/__tests__/worktreeContextRecycleRefresh.test.tsx@@ -65,9 +65,7 @@ beforeEach(() => {},localDb: {sessionsPush: {- onCreated: (- cb: (payload: { sessionId: string }, ownerStamp?: unknown) => void,- ) => {+ onCreated: (cb: (payload: { sessionId: string }, ownerStamp?: unknown) => void) => {mocks.sessionCreatedListeners.add(cb);return () => mocks.sessionCreatedListeners.delete(cb);},@@ -79,6 +77,8 @@ beforeEach(() => {afterEach(() => {cleanup();+ vi.useRealTimers();+ vi.restoreAllMocks();});describe('WorktreeContext recycle refresh', () => {@@ -193,9 +193,7 @@ describe('WorktreeContext recycle refresh', () => {resolveFirst({ sessionId: 'first', path: '/tmp/wt/first' });});- expect(view.getByTestId('ids').textContent).toBe(- 'first:/tmp/wt/first,second:/tmp/wt/second',- );+ expect(view.getByTestId('ids').textContent).toBe('first:/tmp/wt/first,second:/tmp/wt/second');expect(mocks.worktreeListAll).toHaveBeenCalledOnce();});@@ -275,7 +273,7 @@ describe('WorktreeContext recycle refresh', () => {expect(mocks.worktreeListAll).toHaveBeenCalledOnce();});- it('still performs a full validation when the window regains focus', async () => {+ it('still performs a full validation when the window regains focus after the cooldown', async () => {mocks.worktreeListAll.mockResolvedValue([]);render(<WorktreeProvider>@@ -284,11 +282,128 @@ describe('WorktreeContext recycle refresh', () => {);await waitFor(() => expect(mocks.worktreeListAll).toHaveBeenCalledOnce());+ vi.spyOn(Date, 'now').mockReturnValue(Date.now() + 15_001);act(() => window.dispatchEvent(new Event('focus')));await waitFor(() => expect(mocks.worktreeListAll).toHaveBeenCalledTimes(2));});+ it('bounds probes and merges repeated focus while validation is in flight', async () => {+ mocks.worktreeListAll.mockResolvedValue(+ Array.from({ length: 6 }, (_, i) => ({+ sessionId: String(i),+ path: `/tmp/wt/${i}`,+ })),+ );+ const releases: Array<() => void> = [];+ let active = 0;+ let peak = 0;+ mocks.worktreeDetectCwd.mockImplementation(+ () =>+ new Promise((resolve) => {+ peak = Math.max(peak, ++active);+ releases.push(() => {+ active--;+ resolve({ isInsideWorktree: true });+ });+ }),+ );+ const view = render(+ <WorktreeProvider>+ <Probe />+ </WorktreeProvider>,+ );+ await waitFor(() => expect(releases).toHaveLength(2));+ act(() => {+ for (let i = 0; i < 10; i++) window.dispatchEvent(new Event('focus'));+ });+ expect(mocks.worktreeListAll).toHaveBeenCalledOnce();+ for (let i = 0; i < 3; i++) {+ await act(async () => {+ releases.splice(0).forEach((release) => release());+ });+ }+ expect(peak).toBe(2);+ expect(mocks.worktreeDetectCwd).toHaveBeenCalledTimes(6);+ expect(view.getByTestId('ids').textContent).toContain('5:/tmp/wt/5');+ });++ it('keeps badges during cooldown, applies recycle immediately, and checks external removal on the trailing refresh', async () => {+ mocks.worktreeListAll.mockResolvedValue([+ { sessionId: 'archived', path: '/tmp/wt/archived' },+ { sessionId: 'external', path: '/tmp/wt/external' },+ ]);+ const view = render(+ <WorktreeProvider>+ <Probe />+ </WorktreeProvider>,+ );+ await waitFor(() => expect(view.getByTestId('ids').textContent).toContain('external'));+ vi.useFakeTimers();+ act(() => {+ for (let i = 0; i < 10; i++) window.dispatchEvent(new Event('focus'));+ });+ expect(mocks.worktreeListAll).toHaveBeenCalledOnce();+ expect(view.getByTestId('ids').textContent).toContain('external');+ mocks.worktreeGetForSession.mockResolvedValue(null);+ await act(async () => emitWorktreeChanged('archived'));+ expect(view.getByTestId('ids').textContent).toBe('external:/tmp/wt/external');+ mocks.worktreeListAll.mockResolvedValue([{ sessionId: 'external', path: '/tmp/wt/external' }]);+ mocks.worktreeDetectCwd.mockResolvedValue({ isInsideWorktree: false });+ await act(async () => vi.advanceTimersByTimeAsync(15_000));+ expect(mocks.worktreeListAll).toHaveBeenCalledTimes(2);+ expect(view.getByTestId('ids').textContent).toBe('');+ });++ it('rechecks an external removal when focus arrives during an older scan', async () => {+ mocks.worktreeListAll.mockResolvedValue([{ sessionId: 'external', path: '/tmp/wt/external' }]);+ let release!: (value: unknown) => void;+ mocks.worktreeDetectCwd.mockImplementationOnce(+ () =>+ new Promise((resolve) => {+ release = resolve;+ }),+ );+ const view = render(+ <WorktreeProvider>+ <Probe />+ </WorktreeProvider>,+ );+ await waitFor(() => expect(mocks.worktreeDetectCwd).toHaveBeenCalledOnce());+ vi.useFakeTimers();+ act(() => window.dispatchEvent(new Event('focus')));+ // Even a scan longer than the cooldown must not swallow the focus hint.+ await act(async () => vi.advanceTimersByTimeAsync(15_000));+ expect(mocks.worktreeListAll).toHaveBeenCalledOnce();+ await act(async () => release({ isInsideWorktree: true }));+ expect(view.getByTestId('ids').textContent).toContain('external');+ mocks.worktreeDetectCwd.mockResolvedValue({ isInsideWorktree: false });+ await act(async () => vi.advanceTimersByTimeAsync(15_000));+ expect(view.getByTestId('ids').textContent).toBe('');+ expect(mocks.worktreeListAll).toHaveBeenCalledTimes(2);+ });++ it('does not let an in-flight full snapshot resurrect a recycled entry', async () => {+ mocks.worktreeListAll.mockResolvedValue([{ sessionId: 'gone', path: '/tmp/wt/gone' }]);+ let release!: (value: unknown) => void;+ mocks.worktreeDetectCwd.mockImplementation(+ () =>+ new Promise((resolve) => {+ release = resolve;+ }),+ );+ const view = render(+ <WorktreeProvider>+ <Probe />+ </WorktreeProvider>,+ );+ await waitFor(() => expect(mocks.worktreeDetectCwd).toHaveBeenCalledOnce());+ mocks.worktreeGetForSession.mockResolvedValue(null);+ await act(async () => emitWorktreeChanged('gone'));+ await act(async () => release({ isInsideWorktree: true }));+ expect(view.getByTestId('ids').textContent).toBe('');+ });+it('unsubscribes on unmount so a later push cannot refresh a dead tree', async () => {mocks.worktreeListAll.mockResolvedValue([]);const view = render(diff --git a/apps/desktop/src/renderer/contexts/WorktreeContext.tsx b/apps/desktop/src/renderer/contexts/WorktreeContext.tsxindex 5d032da919..7748056da5 100644--- a/apps/desktop/src/renderer/contexts/WorktreeContext.tsx+++ b/apps/desktop/src/renderer/contexts/WorktreeContext.tsx@@ -29,6 +29,8 @@ import type { WorktreeMeta } from '@/lib/worktree.types';import { createLogger } from '@/lib/logger';const log = createLogger('WorktreeContext');+const FOREGROUND_REFRESH_INTERVAL_MS = 15_000;+const VALIDATION_CONCURRENCY = 2;/** store 仍可能留着已被 `git worktree remove` 的路径;探测失败不摘标,避免 IPC 抖动清空侧栏。 */async function isLiveOfficialPath(cwd: string): Promise<boolean> {@@ -58,38 +60,52 @@ export function WorktreeProvider({ children }: { children: ReactNode }) {const fullRefreshGenerationRef = useRef(0);const eventGenerationRef = useRef(0);const sessionEventGenerationsRef = useRef(new Map<string, number>());-- const refresh = useCallback(async () => {- const myTurn = ++fullRefreshGenerationRef.current;- const eventGenerationAtStart = eventGenerationRef.current;- try {- const list = await window.electronAPI.worktreeListAll();- // 中间发生了更新的 refresh,丢弃本次结果- if (myTurn !== fullRefreshGenerationRef.current) return;- const next: Record<string, WorktreeMeta> = {};- await Promise.all(- (list ?? []).map(async (meta) => {- if (!meta?.sessionId || !meta.path) return;- if (!(await isLiveOfficialPath(meta.path))) return;- if (myTurn !== fullRefreshGenerationRef.current) return;- next[meta.sessionId] = meta;- }),- );- if (myTurn !== fullRefreshGenerationRef.current) return;- setMetas((current) => {- const merged = { ...next };- // 全量探测期间若某个 session 收到更晚的权威事件,只保留该 session 当前- // 的增量结果;未完成的增量请求随后会再落一次,不能让旧全量快照回写。- for (const [sessionId, generation] of sessionEventGenerationsRef.current) {- if (generation <= eventGenerationAtStart) continue;- if (current[sessionId]) merged[sessionId] = current[sessionId];- else delete merged[sessionId];- }- return merged;- });- } catch (err) {- log.warn('refresh failed:', err);- }+ const refreshInFlightRef = useRef<Promise<void> | null>(null);+ const lastRefreshAtRef = useRef(-Infinity);++ const refresh = useCallback(() => {+ if (refreshInFlightRef.current) return refreshInFlightRef.current;+ const pending = (async () => {+ const myTurn = ++fullRefreshGenerationRef.current;+ const eventGenerationAtStart = eventGenerationRef.current;+ try {+ const list = await window.electronAPI.worktreeListAll();+ // 中间发生了更新的 refresh,丢弃本次结果+ if (myTurn !== fullRefreshGenerationRef.current) return;+ const next: Record<string, WorktreeMeta> = {};+ let index = 0;+ const validateNext = async () => {+ while (index < (list?.length ?? 0)) {+ if (myTurn !== fullRefreshGenerationRef.current) return;+ const meta = list[index++];+ if (!meta?.sessionId || !meta.path) continue;+ if (!(await isLiveOfficialPath(meta.path))) continue;+ next[meta.sessionId] = meta;+ }+ };+ await Promise.all(Array.from({ length: VALIDATION_CONCURRENCY }, validateNext));+ if (myTurn !== fullRefreshGenerationRef.current) return;+ setMetas((current) => {+ const merged = { ...next };+ // 全量探测期间若某个 session 收到更晚的权威事件,只保留该 session 当前+ // 的增量结果;未完成的增量请求随后会再落一次,不能让旧全量快照回写。+ for (const [sessionId, generation] of sessionEventGenerationsRef.current) {+ if (generation <= eventGenerationAtStart) continue;+ if (current[sessionId]) merged[sessionId] = current[sessionId];+ else delete merged[sessionId];+ }+ return merged;+ });+ lastRefreshAtRef.current = Date.now();+ } catch (err) {+ log.warn('refresh failed:', err);+ }+ })();+ refreshInFlightRef.current = pending;+ void pending.finally(() => {+ refreshInFlightRef.current = null;+ });+ return pending;}, []);const refreshSession = useCallback(async (sessionId: string) => {@@ -122,12 +138,30 @@ export function WorktreeProvider({ children }: { children: ReactNode }) {}, []);useEffect(() => {+ let trailingRefresh: ReturnType<typeof setTimeout> | undefined;void refresh();const onFocus = () => {- void refresh();+ const remaining = refreshInFlightRef.current+ ? FOREGROUND_REFRESH_INTERVAL_MS+ : FOREGROUND_REFRESH_INTERVAL_MS - (Date.now() - lastRefreshAtRef.current);+ if (remaining <= 0) {+ if (trailingRefresh !== undefined) clearTimeout(trailingRefresh);+ trailingRefresh = undefined;+ void refresh();+ } else if (trailingRefresh === undefined) {+ // A final focus within the cooldown still gets a trailing check, even+ // if the user stays here. External worktree removal cannot stay stale.+ trailingRefresh = setTimeout(() => {+ trailingRefresh = undefined;+ onFocus();+ }, remaining);+ }};window.addEventListener('focus', onFocus);- return () => window.removeEventListener('focus', onFocus);+ return () => {+ window.removeEventListener('focus', onFocus);+ if (trailingRefresh !== undefined) clearTimeout(trailingRefresh);+ };}, [refresh]);// 权威时机在这条推送上:main 侧的 worktree 回收是 fire-and-forget 的异步链