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(git): start POSIX commands in real process groups

DavidShen2be497439b2a
diff --git a/apps/desktop/src/main/__tests__/codexFileRewindExecutor.git-integration.test.ts b/apps/desktop/src/main/__tests__/codexFileRewindExecutor.git-integration.test.ts
index 730a63c22f..40a64774bd 100644
--- a/apps/desktop/src/main/__tests__/codexFileRewindExecutor.git-integration.test.ts
+++ b/apps/desktop/src/main/__tests__/codexFileRewindExecutor.git-integration.test.ts
@@ -1,5 +1,6 @@
import { promises as fs } from 'node:fs';
import path from 'node:path';
+import { setImmediate } from 'node:timers/promises';
import { afterAll, afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
@@ -177,6 +178,7 @@ describe('executeCodexFileRewindPlan', () => {
const savepoint = await editedSavepoint();
const rewindPlan = await plan(savepoint);
let queuedRan = false;
+ let rollbackFinished = false;
let queuedTask: Promise<void> | undefined;
const result = await executeCodexFileRewindPlanWithThreadRollback(
@@ -185,10 +187,12 @@ describe('executeCodexFileRewindPlan', () => {
{
commitThreadRollback: async () => {
queuedTask = enqueueGitRepoWrite(repoPath, async () => {
+ expect(rollbackFinished).toBe(true);
queuedRan = true;
});
- await new Promise((resolve) => setTimeout(resolve, 20));
+ await setImmediate();
expect(queuedRan).toBe(false);
+ rollbackFinished = true;
return { sdkSessionId: 'thread-ok' };
},
},
@@ -196,7 +200,8 @@ describe('executeCodexFileRewindPlan', () => {
);
expect(result.threadRollback).toEqual({ sdkSessionId: 'thread-ok' });
- expect(queuedRan).toBe(false);
+ // The lock protects rollback, not the caller's later promise continuation.
+ // A queued writer may already run after rollback succeeds and before this await.
await queuedTask;
expect(queuedRan).toBe(true);
}, REAL_GIT_TEST_TIMEOUT_MS);
diff --git a/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts b/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts
index 6d302922d9..c86ed73627 100644
--- a/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts
+++ b/apps/desktop/src/main/__tests__/makerSendToSessionOrdering.test.ts
@@ -443,10 +443,10 @@ describe('sendToSession ordering', () => {
);
const block = extractSendToSessionSource();
- expect(helperBlock).toContain('onAccepted: async () => {');
- expect(helperBlock).toContain('await opts.onAccepted?.();');
+ expect(helperBlock).toContain('onAccepted: async (signal) => {');
+ expect(helperBlock).toContain('await opts.onAccepted?.(signal);');
expect(helperBlock).toContain('await beginTurnChangeSetAtDispatch(session, anchorClientId);');
- expect(helperBlock).toContain('await gitSnapshotCoordinator.onTurnStart(session.id);');
+ expect(helperBlock).toContain('await gitSnapshotCoordinator.onTurnStart(session.id, signal);');
expect(helperBlock).toContain('const pendingHandoff = await agentHandoffPending.peek(session.id);');
expect(helperBlock).toContain('prependHandoffToUserMessage(');
expect(helperBlock).toContain("{ type: 'user', content: message },");
@@ -472,13 +472,13 @@ describe('sendToSession ordering', () => {
expect(begin).toBeGreaterThan(secondSeal);
expectOrder(
helperBlock,
- 'await opts.onAccepted?.();',
+ 'await opts.onAccepted?.(signal);',
'await beginTurnChangeSetAtDispatch(session, anchorClientId);',
);
expectOrder(
helperBlock,
'await beginTurnChangeSetAtDispatch(session, anchorClientId);',
- 'await gitSnapshotCoordinator.onTurnStart(session.id);',
+ 'await gitSnapshotCoordinator.onTurnStart(session.id, signal);',
);
expect(countOccurrences(block, 'sendUserMessageWithAwaitedGitBaseline(')).toBe(3);
expect(block).not.toContain(
diff --git a/apps/desktop/src/main/worktree/__tests__/gitExec.test.ts b/apps/desktop/src/main/worktree/__tests__/gitExec.test.ts
index 3f0edde785..0f8798c50f 100644
--- a/apps/desktop/src/main/worktree/__tests__/gitExec.test.ts
+++ b/apps/desktop/src/main/worktree/__tests__/gitExec.test.ts
@@ -15,11 +15,12 @@ type ExecCb = (err: Error | null, stdout: string, stderr: string) => void;
const mocks = vi.hoisted(() => ({
execFile: vi.fn(),
+ spawn: vi.fn(),
killProcessTree: vi.fn(),
withCrossProcessLock: vi.fn(),
}));
-vi.mock('node:child_process', () => ({ execFile: mocks.execFile }));
+vi.mock('node:child_process', () => ({ execFile: mocks.execFile, spawn: mocks.spawn }));
vi.mock('../../scheduler-host/proc-util', () => ({ killProcessTree: mocks.killProcessTree }));
vi.mock('../../device-link/crossProcessLock', () => ({
withCrossProcessLock: mocks.withCrossProcessLock,
@@ -164,6 +165,18 @@ async function flushMicrotasks() {
beforeEach(() => {
vi.useFakeTimers();
mocks.execFile.mockReset();
+ // Drive the same lifecycle fixtures through spawn's actual stream/close API.
+ mocks.spawn.mockReset().mockImplementation((file, args, opts) => {
+ const child = mocks.execFile(file, args, opts, (error: NodeJS.ErrnoException | null, stdout: string, stderr: string) => {
+ if (stdout) child.stdout.emit('data', Buffer.from(stdout));
+ if (stderr) child.stderr.emit('data', Buffer.from(stderr));
+ if (error && typeof error.code !== 'number') child.emit('error', error);
+ else child.emit('close', error?.code ?? 0, null);
+ });
+ child.stdout ??= new EventEmitter();
+ child.stderr ??= new EventEmitter();
+ return child;
+ });
mocks.killProcessTree.mockReset();
mocks.withCrossProcessLock.mockReset();
// 默认按「持锁成功」直通, 让 dubious-ownership 的 read+add 序列可逐步驱动;
@@ -181,6 +194,40 @@ afterEach(() => {
});
describe('gitExec timeoutMs', () => {
+ // #7351 CI: execFile silently discarded detached. Exercise spawn's actual
+ // boundary and byte streams; the old mock only checked the ignored option.
+ it.each([0, 128])('uses a detached POSIX spawn and preserves UTF-8 output for exit %s', async (code) => {
+ setPlatform('linux');
+ const state = installExecFileMock();
+ const pending = gitExec(['status'], '/repo');
+ expect(mocks.spawn).toHaveBeenCalledWith('git', ['status'], expect.objectContaining({ detached: true }));
+ const bytes = Buffer.from('\u4e2d\u6587');
+ state.child.stdout.emit('data', bytes.subarray(0, 2));
+ state.child.stdout.emit('data', bytes.subarray(2));
+ state.child.stderr.emit('data', Buffer.from('diagnostic'));
+ state.child.emit('close', code, null);
+ const output = { stdout: '\u4e2d\u6587', stderr: 'diagnostic' };
+ if (code === 0) await expect(pending).resolves.toEqual(output);
+ else await expect(pending).rejects.toMatchObject({ ...output, exitCode: code });
+ });
+
+ it.each(['stdout', 'stderr'] as const)('bounds POSIX %s and drains the process group on overflow', async (stream) => {
+ setPlatform('linux');
+ const state = installExecFileMock();
+ const { group } = installProcessKillMock();
+ const pending = gitExec(['status'], '/repo');
+ const observed = probe(pending);
+ state.child[stream].emit('data', Buffer.alloc(16 * 1024 * 1024 + 1));
+ await flushMicrotasks();
+ expect(group.signals).toContain('SIGTERM');
+ expect(observed.settled).toBe(false);
+ group.alive = false;
+ await vi.advanceTimersByTimeAsync(100);
+ await expect(pending).rejects.toMatchObject({
+ cleanupUnconfirmed: false, cause: { code: 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER' },
+ });
+ });
+
// #7259: unit tier. Explicit abort must kill the tree, not only drop its
// promise; a blocked child is the minimal reproduction. No wall-clock waits.
it.each(['win32', 'linux'] as const)('abort terminates the %s tree before settling', async (platform) => {
diff --git a/apps/desktop/src/main/worktree/gitExec.ts b/apps/desktop/src/main/worktree/gitExec.ts
index fb8ac7b229..f3e8b726c6 100644
--- a/apps/desktop/src/main/worktree/gitExec.ts
+++ b/apps/desktop/src/main/worktree/gitExec.ts
@@ -2,7 +2,7 @@
* worktree-parallel-sessions: git CLI 包装。
*
* 职责:
- * - 用 child_process.execFile 调用 git, 保留 stderr/stdout/exitCode
+ * - POSIX 用 detached spawn、Windows 用 execFile 调用 git,保留 stderr/stdout/exitCode
* - 自动处理 dubious-ownership: 若 stderr 含 "dubious ownership", 提取路径,
* 幂等地 `git config --global --add safe.directory <path>`(已存在则不重复添加),
* 重试**一次**原命令
@@ -12,7 +12,7 @@
* 这里只把 raw stderr/code/cause 暴露出去。
*/
-import { execFile, type ChildProcess, type ExecFileOptions } from 'node:child_process';
+import { execFile, spawn, type ChildProcess, type ExecFileOptions } from 'node:child_process';
import os from 'node:os';
import path from 'node:path';
import { assertGitDirectoryReady, currentOperationBudget, quarantineGitDirectory } from '../utils/operationBudget';
@@ -225,6 +225,44 @@ function pidMayBeAliveForGit(pid: number): boolean {
}
}
+/** execFile drops detached; POSIX must use spawn to actually own a process group. */
+function execDetachedGit(
+ file: string,
+ args: string[],
+ options: ExecFileOptions,
+ callback: (error: NodeJS.ErrnoException | null, stdout: string, stderr: string) => void,
+): ChildProcess {
+ const child = spawn(file, args, { cwd: options.cwd, env: options.env, detached: true });
+ const stdout: Buffer[] = [];
+ const stderr: Buffer[] = [];
+ let done = false;
+ const finish = (error: NodeJS.ErrnoException | null) => {
+ if (done) return;
+ done = true;
+ callback(error, Buffer.concat(stdout).toString('utf8'), Buffer.concat(stderr).toString('utf8'));
+ };
+ for (const [stream, chunks] of [[child.stdout, stdout], [child.stderr, stderr]] as const) {
+ let size = 0;
+ stream?.on('data', (chunk: Buffer) => {
+ if (done) return;
+ size += chunk.length;
+ if (size > (options.maxBuffer ?? 16 * 1024 * 1024)) {
+ finish(Object.assign(new Error('Git output exceeded maxBuffer'), { code: 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER' }));
+ return;
+ }
+ chunks.push(chunk);
+ });
+ }
+ child.once('error', finish);
+ child.once('close', (code, signal) => {
+ finish(code === 0 && signal === null ? null : Object.assign(
+ new Error(`Git exited with ${signal ?? code}`),
+ { code, signal },
+ ) as unknown as NodeJS.ErrnoException);
+ });
+ return child;
+}
+
/**
* 执行一次 git, 不做 dubious-ownership 自动重试(底层用)。
*/
@@ -266,8 +304,7 @@ function execFileOnce(
fn();
};
- // ExecFileOptions 类型没收录 detached,但 execFile 运行时把 options 原样传给
- // spawn,detached 照常生效——用交叉类型补上缺口。
+ // POSIX uses spawn through execDetachedGit; execFile does not forward detached.
const spawnOptions: ExecFileOptions & { detached: boolean } = {
cwd,
// 防止超大输出炸内存。listBranches/listFiles 这类正常情况远低于此。
@@ -293,7 +330,7 @@ function execFileOnce(
let child: ChildProcess;
try {
- child = execFile(
+ child = (process.platform === 'win32' ? execFile : execDetachedGit)(
'git',
[...args],
spawnOptions,
@@ -331,8 +368,8 @@ function execFileOnce(
// - typeof (err as any).code === 'number' → 子进程退出码
const numericCode = (err as unknown as { code?: unknown }).code;
const exitCode = typeof numericCode === 'number' ? numericCode : null;
- if (opts?.signal && errno.code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER') {
- stdioReleased = true;
+ if (errno.code === 'ERR_CHILD_PROCESS_STDIO_MAXBUFFER') {
+ stdioReleased = process.platform === 'win32';
// execFile only kills the immediate child on overflow.
queueMicrotask(() => startTreeCleanup((treeConfirmedGone) => new GitExecError({
args, exitCode, stderr: stderrStr, stdout: '', cause: errno,