Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): share cwd probe budget across realpath and Git

guyong9d8ed452c764
diff --git a/apps/desktop/src/main/__tests__/renameSessionTitlesInDb.test.ts b/apps/desktop/src/main/__tests__/renameSessionTitlesInDb.test.ts
index e6f0f5c4e3..be37906ca3 100644
--- a/apps/desktop/src/main/__tests__/renameSessionTitlesInDb.test.ts
+++ b/apps/desktop/src/main/__tests__/renameSessionTitlesInDb.test.ts
@@ -64,6 +64,7 @@ const h = vi.hoisted(() => {
});
vi.mock('electron', () => ({
+ app: { once: vi.fn() },
ipcMain: { handle: vi.fn() },
BrowserWindow: {
getAllWindows: () => [{ isDestroyed: () => false, webContents: { send: h.webContentsSend } }],
diff --git a/apps/desktop/src/main/__tests__/sessionsListIncludePinned.test.ts b/apps/desktop/src/main/__tests__/sessionsListIncludePinned.test.ts
index 3cddb23db6..f8cfbc29c2 100644
--- a/apps/desktop/src/main/__tests__/sessionsListIncludePinned.test.ts
+++ b/apps/desktop/src/main/__tests__/sessionsListIncludePinned.test.ts
@@ -67,6 +67,7 @@ const h = vi.hoisted(() => {
});
vi.mock('electron', () => ({
+ app: { once: vi.fn() },
ipcMain: { handle: h.ipcHandle },
BrowserWindow: { getAllWindows: () => [] },
}));
diff --git a/apps/desktop/src/main/__tests__/touchUserSendBroadcast.test.ts b/apps/desktop/src/main/__tests__/touchUserSendBroadcast.test.ts
index 2c64cc213f..728b9f32bf 100644
--- a/apps/desktop/src/main/__tests__/touchUserSendBroadcast.test.ts
+++ b/apps/desktop/src/main/__tests__/touchUserSendBroadcast.test.ts
@@ -85,6 +85,7 @@ const h = vi.hoisted(() => {
});
vi.mock('electron', () => ({
+ app: { once: vi.fn() },
ipcMain: { handle: vi.fn() },
BrowserWindow: {
getAllWindows: () => [{ isDestroyed: () => false, webContents: { send: h.webContentsSend } }],
diff --git a/apps/desktop/src/main/__tests__/worktreeDetectCwd.test.ts b/apps/desktop/src/main/__tests__/worktreeDetectCwd.test.ts
index a9ecef2f1d..152d9037a3 100644
--- a/apps/desktop/src/main/__tests__/worktreeDetectCwd.test.ts
+++ b/apps/desktop/src/main/__tests__/worktreeDetectCwd.test.ts
@@ -34,6 +34,8 @@ vi.mock('../worktree/gitExec', async () => {
beforeEach(() => {
gitExecMock.mockReset();
+ // Synchronous Git fixtures consume no work budget; fake-timer cases replace this clock.
+ vi.spyOn(performance, 'now').mockReturnValue(0);
// Synthetic paths need no filesystem I/O, including fake-timer timeout tests.
realpathMock.mockReset().mockRejectedValue(Object.assign(new Error('missing directory'), { code: 'ENOENT' }));
});
@@ -74,6 +76,42 @@ function setupGitMock(opts: {
}
describe('detectCwd → isInsideWorktree (I-1 fix)', () => {
+ // PR #6544: 5s realpath + 10s Git leaves no headroom in Mobile's 15s wait.
+ // Existing coverage bounds each phase separately, not their sum (unit tier).
+ it.each([
+ { fallback: false, realpathMs: 4_999 },
+ { fallback: true, realpathMs: 4_999 },
+ { fallback: true, realpathMs: 4_000 },
+ ])('shares the deadline across slow realpath and Git ($fallback, $realpathMs ms)', async ({ fallback, realpathMs }) => {
+ vi.useFakeTimers();
+ realpathMock.mockImplementation(() => new Promise((resolve) => {
+ setTimeout(() => resolve(path.resolve('/repo')), realpathMs);
+ }));
+ gitExecMock.mockImplementation((args: readonly string[], _cwd: string, opts: GitExecOpts) => {
+ const duration = fallback ? 2_000 : 6_000;
+ return new Promise((resolve, reject) => {
+ setTimeout(() => {
+ if (duration > opts.timeoutMs!) reject(timeoutError());
+ else resolve({ stdout: args.length > 3 && !fallback ? '/repo\nmain\n.git\n.git\n'
+ : args.includes('--show-toplevel') && args.length === 2 ? '/repo' : '.git' });
+ }, Math.min(duration, opts.timeoutMs!));
+ });
+ });
+ let failure: unknown;
+ const probe = detectCwd('/repo').catch((error) => { failure = error; });
+ try {
+ await vi.advanceTimersByTimeAsync(10_000);
+ expect(failure).toMatchObject({ timedOut: true });
+ await probe;
+ expect(gitExecMock.mock.calls[0][2].timeoutMs).toBe(10_000 - realpathMs);
+ if (realpathMs === 4_000) expect(gitExecMock).toHaveBeenCalledTimes(3);
+ expect(vi.getTimerCount()).toBe(0);
+ } finally {
+ await vi.runAllTimersAsync();
+ await probe;
+ }
+ });
+
// PR #6544: Git deadlines do not cover a stalled realpath. Four unresolved
// lookups must reject as unknown state and release queued probes (unit tier).
it('bounds physical-directory lookups and releases queued probes and same-path retries', async () => {
diff --git a/apps/desktop/src/main/git-review/__tests__/deviceOp.test.ts b/apps/desktop/src/main/git-review/__tests__/deviceOp.test.ts
index 487d436170..aab17de0e2 100644
--- a/apps/desktop/src/main/git-review/__tests__/deviceOp.test.ts
+++ b/apps/desktop/src/main/git-review/__tests__/deviceOp.test.ts
@@ -31,6 +31,7 @@ vi.mock('../../turn-change-set/store.js', () => ({
}));
vi.mock('electron', () => ({
+ app: { once: vi.fn() },
ipcMain: { handle: vi.fn() },
shell: { openPath: vi.fn() },
}));
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/regenerateSessionTitle.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/regenerateSessionTitle.test.ts
index d0f2f10835..640d42467e 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/regenerateSessionTitle.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/regenerateSessionTitle.test.ts
@@ -11,7 +11,7 @@ const logger = vi.hoisted(() => ({
debug: vi.fn(),
}));
-vi.mock('electron', () => ({ ipcMain: { handle: vi.fn() } }));
+vi.mock('electron', () => ({ app: { once: vi.fn() }, ipcMain: { handle: vi.fn() } }));
vi.mock('../../logger.js', () => ({
createLogger: () => logger,
}));
diff --git a/apps/desktop/src/main/worktree/WorktreeManager.ts b/apps/desktop/src/main/worktree/WorktreeManager.ts
index ad309408aa..67577abbe0 100644
--- a/apps/desktop/src/main/worktree/WorktreeManager.ts
+++ b/apps/desktop/src/main/worktree/WorktreeManager.ts
@@ -408,10 +408,21 @@ async function withPrecreatedWorktreeOperationQueue<T>(
*/
export const detectCwd = createCwdProbeScheduler(detectCwdOnce);
-// 每条探测命令都有界;复用 gitExec 的整树清理后才释放 scheduler slot。
-const CWD_PROBE_GIT_OPTS = { timeoutMs: 10_000 };
+// Share the work budget across realpath and every Git query. Git's additional
+// 3s process-tree cleanup still leaves response headroom under Mobile's 15s wait.
+const CWD_PROBE_TIMEOUT_MS = 10_000;
async function detectCwdOnce(cwd: string): Promise<DetectCwdResp> {
+ const deadline = performance.now() + CWD_PROBE_TIMEOUT_MS;
+ const probeGit = async (args: readonly string[], dir?: string) => {
+ const timeoutMs = Math.ceil(deadline - performance.now());
+ if (timeoutMs <= 0) {
+ throw new GitExecError({
+ args, exitCode: null, stdout: '', stderr: 'directory probe deadline exceeded', timedOut: true,
+ });
+ }
+ return gitExec(args, dir, { timeoutMs });
+ };
// Git resolves relative metadata paths from the physical process cwd. A
// symlink spelling can otherwise make an ordinary repo look like a linked
// worktree. Keep Git's existing error handling if the directory is unavailable.
@@ -425,10 +436,9 @@ async function detectCwdOnce(cwd: string): Promise<DetectCwdResp> {
// 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(
+ const { stdout } = await probeGit(
['rev-parse', '--show-toplevel', '--abbrev-ref', 'HEAD', '--git-dir', '--git-common-dir'],
cwd,
- CWD_PROBE_GIT_OPTS,
);
const lines = gitPathOutput(stdout).split(process.platform === 'win32' ? /\r?\n/ : /\n/);
if (lines.length === 4 && lines.every((line) => line.trim().length > 0)) {
@@ -454,7 +464,7 @@ async function detectCwdOnce(cwd: string): Promise<DetectCwdResp> {
};
// 1. git --version 探测安装
try {
- await gitExec(['--version'], undefined, CWD_PROBE_GIT_OPTS);
+ await probeGit(['--version']);
} catch (err) {
if (err instanceof GitExecError && err.timedOut) throw err;
if (err instanceof GitExecError && err.cause?.code === 'ENOENT') {
@@ -468,7 +478,7 @@ async function detectCwdOnce(cwd: string): Promise<DetectCwdResp> {
// 2. rev-parse --show-toplevel: 拿 repo 根
try {
- const { stdout } = await gitExec(['rev-parse', '--show-toplevel'], cwd, CWD_PROBE_GIT_OPTS);
+ const { stdout } = await probeGit(['rev-parse', '--show-toplevel'], cwd);
const toplevel = gitPathOutput(stdout);
if (toplevel) {
out.isGitRepo = true;
@@ -483,7 +493,7 @@ async function detectCwdOnce(cwd: string): Promise<DetectCwdResp> {
// 3. 当前分支
try {
- const { stdout } = await gitExec(['rev-parse', '--abbrev-ref', 'HEAD'], cwd, CWD_PROBE_GIT_OPTS);
+ const { stdout } = await probeGit(['rev-parse', '--abbrev-ref', 'HEAD'], cwd);
const branch = stdout.trim();
if (branch && branch !== 'HEAD') out.currentBranch = branch;
} catch (err) {
@@ -499,8 +509,8 @@ async function detectCwdOnce(cwd: string): Promise<DetectCwdResp> {
try {
// 任一命令失败后仍等另一条完成清理,不能提前释放目录探测槽位。
const results = await Promise.allSettled([
- gitExec(['rev-parse', '--git-dir'], cwd, CWD_PROBE_GIT_OPTS),
- gitExec(['rev-parse', '--git-common-dir'], cwd, CWD_PROBE_GIT_OPTS),
+ probeGit(['rev-parse', '--git-dir'], cwd),
+ probeGit(['rev-parse', '--git-common-dir'], cwd),
]);
for (const result of results) {
if (result.status === 'rejected' && result.reason instanceof GitExecError && result.reason.timedOut) {