Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): preserve cwd deadline during Git ownership repair
guyong775dde557503
diff --git a/apps/desktop/src/main/__tests__/worktreeDetectCwd.test.ts b/apps/desktop/src/main/__tests__/worktreeDetectCwd.test.tsindex 152d9037a3..6ebf9abc6d 100644--- a/apps/desktop/src/main/__tests__/worktreeDetectCwd.test.ts+++ b/apps/desktop/src/main/__tests__/worktreeDetectCwd.test.ts@@ -104,6 +104,9 @@ describe('detectCwd → isInsideWorktree (I-1 fix)', () => {expect(failure).toMatchObject({ timedOut: true });await probe;expect(gitExecMock.mock.calls[0][2].timeoutMs).toBe(10_000 - realpathMs);+ for (const [, , opts] of gitExecMock.mock.calls) {+ expect(opts.deadlineAtMs).toBe(10_000);+ }if (realpathMs === 4_000) expect(gitExecMock).toHaveBeenCalledTimes(3);expect(vi.getTimerCount()).toBe(0);} finally {diff --git a/apps/desktop/src/main/__tests__/worktreeManagerRemove.test.ts b/apps/desktop/src/main/__tests__/worktreeManagerRemove.test.tsindex 2850d7722f..b111f9b733 100644--- a/apps/desktop/src/main/__tests__/worktreeManagerRemove.test.ts+++ b/apps/desktop/src/main/__tests__/worktreeManagerRemove.test.ts@@ -14,7 +14,7 @@ vi.mock('../worktree/runtimeLeases', () => ({* - dirty → stash 失败保留 / 成功后继续删* - clean 无引用 → git remove + store.del*/-import { beforeEach, describe, expect, it, vi } from 'vitest';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';import path from 'node:path';import fsSync from 'node:fs';import os from 'node:os';@@ -137,6 +137,8 @@ describe('removeWorktreeForSession', () => {beforeEach(async () => {vi.clearAllMocks();+ // These Git fixtures consume no simulated time; assert the shared budget exactly.+ vi.spyOn(performance, 'now').mockReturnValue(0);readWorktreeRuntimePathsMock.mockReset().mockResolvedValue(new Set());reclaimOrphanedRuntimeLeasesMock.mockReset().mockResolvedValue(0);storeMap.clear();@@ -177,6 +179,8 @@ describe('removeWorktreeForSession', () => {manager = await import('../worktree/WorktreeManager');});+ afterEach(() => vi.restoreAllMocks());+it('no store entry → no-op', async () => {await manager.removeWorktreeForSession('nope');expect(gitExecMock).not.toHaveBeenCalled();@@ -377,7 +381,7 @@ describe('removeWorktreeForSession', () => {expect(gitExecMock).toHaveBeenCalledWith(['rev-parse', '--show-toplevel', '--abbrev-ref', 'HEAD', '--git-dir', '--git-common-dir'],BASE_REPO,- { timeoutMs: 10_000 },+ { timeoutMs: 10_000, deadlineAtMs: 10_000 },);});diff --git a/apps/desktop/src/main/worktree/WorktreeManager.ts b/apps/desktop/src/main/worktree/WorktreeManager.tsindex 67577abbe0..8dc4ec0e0e 100644--- a/apps/desktop/src/main/worktree/WorktreeManager.ts+++ b/apps/desktop/src/main/worktree/WorktreeManager.ts@@ -421,7 +421,7 @@ async function detectCwdOnce(cwd: string): Promise<DetectCwdResp> {args, exitCode: null, stdout: '', stderr: 'directory probe deadline exceeded', timedOut: true,});}- return gitExec(args, dir, { timeoutMs });+ return gitExec(args, dir, { timeoutMs, deadlineAtMs: deadline });};// Git resolves relative metadata paths from the physical process cwd. A// symlink spelling can otherwise make an ordinary repo look like a linkeddiff --git a/apps/desktop/src/main/worktree/__tests__/gitExec.test.ts b/apps/desktop/src/main/worktree/__tests__/gitExec.test.tsindex 5c3825512f..d844c1eb06 100644--- a/apps/desktop/src/main/worktree/__tests__/gitExec.test.ts+++ b/apps/desktop/src/main/worktree/__tests__/gitExec.test.ts@@ -650,6 +650,114 @@ describe('gitExec dubious-ownership safe.directory', () => {for (let i = 0; i < 20; i += 1) await Promise.resolve();}+ // PR #6544: caller deadlines must include ownership repair, not restart for+ // config/read/add/retry. Existing timeoutMs tests cover only individual steps.+ // Production entry gitExec, unit tier: virtual 4999ms realpath + slow repair.+ it.each(['read', 'add', 'retry'])('shares the absolute deadline through ownership %s', async (stage) => {+ setPlatform('linux');+ const { calls, cbs } = installSequenceMock();+ mocks.withCrossProcessLock.mockImplementation(async (_lp, _opts, task) => {+ await new Promise((resolve) => setTimeout(resolve, 500));+ return task({ held: true });+ });+ await vi.advanceTimersByTimeAsync(4_999);+ let failure: unknown;+ const pending = gitExec(['rev-parse'], '/repo', { timeoutMs: 5_001, deadlineAtMs: 10_000 })+ .catch((error) => { failure = error; });+ try {+ await vi.advanceTimersByTimeAsync(4_000);+ cbs[0](new Error('dubious'), '', "fatal: detected dubious ownership in repository at '/repo'");+ await vi.advanceTimersByTimeAsync(500);+ if (stage !== 'read') {+ await vi.advanceTimersByTimeAsync(100);+ cbs[1](Object.assign(new Error('absent'), { code: 1 }), '', '');+ await flushDeep();+ }+ if (stage === 'retry') {+ await vi.advanceTimersByTimeAsync(100);+ cbs[2](null, '', '');+ await flushDeep();+ }+ await vi.advanceTimersByTimeAsync(10_000 - performance.now());+ expect(failure).toMatchObject({ timedOut: true });+ await pending;+ expect(calls).toHaveLength(stage === 'read' ? 2 : stage === 'add' ? 3 : 4);+ expect(vi.getTimerCount()).toBe(0);+ } finally {+ cbs.at(-1)?.(null, '/repo\n', '');+ await vi.runAllTimersAsync();+ await pending;+ }+ });++ it.each([false, true])('caps lock waiting and never starts config after expiry (held=%s)', async (held) => {+ const { calls, cbs } = installSequenceMock();+ mocks.withCrossProcessLock.mockImplementation(async (_lp, opts, task) => {+ await new Promise((resolve) => setTimeout(resolve, opts.waitMs));+ return task({ held, reason: held ? undefined : 'busy' });+ });+ let failure: unknown;+ const pending = gitExec(['rev-parse'], '/repo', { timeoutMs: 10_000, deadlineAtMs: 10_000 })+ .catch((error) => { failure = error; });+ try {+ await vi.advanceTimersByTimeAsync(9_999);+ cbs[0](new Error('dubious'), '', "fatal: detected dubious ownership in repository at '/repo'");+ await vi.advanceTimersByTimeAsync(1);+ expect(failure).toMatchObject({ timedOut: true });+ expect(mocks.withCrossProcessLock.mock.calls[0][1].waitMs).toBe(1);+ expect(calls).toEqual([['rev-parse']]);+ await pending;+ } finally {+ await vi.runAllTimersAsync();+ await pending;+ }+ });++ it('completes ownership repair and retry within the shared deadline', async () => {+ const { calls, cbs } = installSequenceMock();+ mocks.withCrossProcessLock.mockImplementation(async (_lp, _opts, task) => {+ await new Promise((resolve) => setTimeout(resolve, 500));+ return task({ held: true });+ });+ await vi.advanceTimersByTimeAsync(4_999);+ const pending = gitExec(['rev-parse'], '/repo', { timeoutMs: 5_001, deadlineAtMs: 10_000 });+ await vi.advanceTimersByTimeAsync(4_000);+ cbs[0](new Error('dubious'), '', "fatal: detected dubious ownership in repository at '/repo'");+ await vi.advanceTimersByTimeAsync(500);+ await vi.advanceTimersByTimeAsync(100);+ cbs[1](Object.assign(new Error('absent'), { code: 1 }), '', '');+ await flushDeep();+ await vi.advanceTimersByTimeAsync(100);+ cbs[2](null, '', '');+ await flushDeep();+ await vi.advanceTimersByTimeAsync(100);+ cbs[3](null, '/repo\n', '');+ await expect(pending).resolves.toEqual({ stdout: '/repo\n', stderr: '' });+ expect(calls).toEqual([+ ['rev-parse'],+ ['config', '--global', '--get-all', 'safe.directory'],+ ['config', '--global', '--add', 'safe.directory', '/repo'],+ ['rev-parse'],+ ]);+ expect(vi.getTimerCount()).toBe(0);+ });++ it('rejects an expired deadline before starting a Git process', async () => {+ const { calls, cbs } = installSequenceMock();+ let failure: unknown;+ const pending = gitExec(['status'], '/repo', { deadlineAtMs: performance.now() })+ .catch((error) => { failure = error; });+ try {+ await flushDeep();+ expect(failure).toMatchObject({ timedOut: true });+ expect(calls).toHaveLength(0);+ await pending;+ } finally {+ cbs.at(-1)?.(null, '', '');+ await pending;+ }+ });+it.each(['read', 'add', 'retry'])('bounds the safe.directory %s stage with the caller timeout', async (stage) => {setPlatform('linux');const { calls, cbs } = installSequenceMock();diff --git a/apps/desktop/src/main/worktree/gitExec.ts b/apps/desktop/src/main/worktree/gitExec.tsindex 2975225269..9954de1940 100644--- a/apps/desktop/src/main/worktree/gitExec.ts+++ b/apps/desktop/src/main/worktree/gitExec.ts@@ -83,10 +83,24 @@ export interface GitExecOpts {* 省略 = 不超时。*/timeoutMs?: number;+ /** Optional absolute performance.now() deadline shared by ownership repair and retries. */+ deadlineAtMs?: number;/** Called immediately after the git child is spawned. */onSpawn?: (pid: number) => void;}+/** Check the caller's monotonic budget before starting another repair step. */+function remainingDeadlineMs(deadlineAtMs: number | undefined, args: readonly string[]): number | undefined {+ if (deadlineAtMs === undefined) return undefined;+ const remaining = Math.ceil(deadlineAtMs - performance.now());+ if (remaining <= 0) {+ throw new GitExecError({+ args, exitCode: null, stdout: '', stderr: 'Git operation deadline exceeded', timedOut: true,+ });+ }+ return remaining;+}+/** POSIX 超时后 SIGTERM → SIGKILL 的宽限期:给 git 留出清理 .lock 的时间窗。 */const POSIX_KILL_GRACE_MS = 1_500;/** POSIX 宽限期内探测进程组是否清空的轮询间隔。 */@@ -211,8 +225,11 @@ function execFileOnce(cwd?: string,opts?: GitExecOpts,): Promise<GitExecResult> {- const diagnostic = beginExecFileDiagnostic('worktree.git');return new Promise((resolve, reject) => {+ const remaining = remainingDeadlineMs(opts?.deadlineAtMs, args);+ const timeoutMs = remaining === undefined ? opts?.timeoutMs+ : Math.min(remaining, opts?.timeoutMs && opts.timeoutMs > 0 ? opts.timeoutMs : remaining);+ const diagnostic = beginExecFileDiagnostic('worktree.git');// 超时不走 execFile 内建 timeout:它只终止直接子进程,且回调要等 stdout/stderr// 流关闭——被后代进程继承并占住时回调可能远超 deadline 才来。这里自管定时器,// 超时先终止整棵进程树/进程组(两个平台都含后代),再显式收口 Promise。@@ -490,7 +507,6 @@ function execFileOnce(reaper.unref?.();}- const timeoutMs = opts?.timeoutMs;if (timeoutMs !== undefined && timeoutMs > 0) {timer = setTimeout(() => {startTreeCleanup((treeConfirmedGone) =>@@ -567,7 +583,7 @@ export function safeDirectorySpellings(p: string): string[] {* 失败)必须向上抛,否则会把「读不到」误判成「未配置」而重复 --add,反而制造出* 本条修复要避免的重复条目。*/-async function readGlobalSafeDirectories(opts?: Pick<GitExecOpts, 'timeoutMs'>): Promise<string[]> {+async function readGlobalSafeDirectories(opts?: Pick<GitExecOpts, 'timeoutMs' | 'deadlineAtMs'>): Promise<string[]> {try {const { stdout } = await execFileOnce(['config', '--global', '--get-all', 'safe.directory'], undefined, opts);return stdout@@ -589,11 +605,15 @@ async function readGlobalSafeDirectories(opts?: Pick<GitExecOpts, 'timeoutMs'>):* dubious-ownership 错误还给调用方,而不是退化成并发写入重复条目。用底层* execFileOnce 而非 gitExec, 防止递归进入 dubious-ownership 分支。*/-async function ensureGlobalSafeDirectory(targetPath: string, opts?: Pick<GitExecOpts, 'timeoutMs'>): Promise<void> {+async function ensureGlobalSafeDirectory(targetPath: string, opts?: Pick<GitExecOpts, 'timeoutMs' | 'deadlineAtMs'>): Promise<void> {+ const configArgs = ['config', '--global', 'safe.directory'];+ const remaining = remainingDeadlineMs(opts?.deadlineAtMs, configArgs);await withCrossProcessLock(globalSafeDirectoryLockPath(),- { label: 'git-safe-directory', waitMs: 1_000 },+ { label: 'git-safe-directory', waitMs: Math.min(1_000, remaining ?? 1_000) },async (status) => {+ // Lock acquisition may finish after its wait budget; never start Git then.+ remainingDeadlineMs(opts?.deadlineAtMs, configArgs);if (!status.held) {throw new Error('could not acquire the global safe.directory lock');}@@ -630,7 +650,9 @@ export async function gitExec(const dubiousPath = extractDubiousPath(err.stderr) ?? cwd;if (dubiousPath) {try {- await ensureGlobalSafeDirectory(dubiousPath, { timeoutMs: opts?.timeoutMs });+ await ensureGlobalSafeDirectory(dubiousPath, {+ timeoutMs: opts?.timeoutMs, deadlineAtMs: opts?.deadlineAtMs,+ });// 配完 safe.directory 后重试原命令return await execFileOnce(args, cwd, opts);} catch (cause) {