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(maker-core,desktop): 处理 R6 review 的 2 P1 + 1 P2

yan89e583eaa690
diff --git a/apps/desktop/src/main/remote-ssh/__tests__/agentProxy.test.ts b/apps/desktop/src/main/remote-ssh/__tests__/agentProxy.test.ts
index b5e67d827c..cd0766cdc0 100644
--- a/apps/desktop/src/main/remote-ssh/__tests__/agentProxy.test.ts
+++ b/apps/desktop/src/main/remote-ssh/__tests__/agentProxy.test.ts
@@ -47,6 +47,7 @@ import {
buildAgentProxyEnvUppercase,
buildAgentProxyMarkerContent,
ensureAgentProxyTunnel,
+ killRemoteCodexDaemon,
reconcileCodexAgentProxyEnv,
} from '../agent-proxy';
import {
@@ -217,6 +218,38 @@ describe('reconcileCodexAgentProxyEnv', () => {
});
});
+describe('killRemoteCodexDaemon', () => {
+ it('waits for the daemon to actually exit after TERM before returning (greptile R6 P2)', async () => {
+ // pkill 只保证信号送达 — 脚本必须 TERM 后轮询等进程消失, 没死透再 KILL,
+ // 防旧 daemon 在 dying 窗口里响应探活被复用 (旧 env, marker 变更静默落空)。
+ const { host, state } = makeFakeHost();
+ const result = await killRemoteCodexDaemon(host);
+ expect(result).toEqual({ ok: true });
+ expect(state.pkillCount).toBe(1);
+ const script = state.execCalls.find((c) => c.cmd.includes('pkill'))?.cmd ?? '';
+ expect(script).toContain('pgrep');
+ expect(script).toContain('pkill -9');
+ });
+
+ it('reports pkill_failed when the daemon survives TERM+KILL', async () => {
+ const { host } = makeFakeHost();
+ const baseExec = host.exec.bind(host);
+ host.exec = async (cmd: string, execOpts?: { input?: string }) => {
+ if (cmd.includes('pkill')) {
+ return {
+ stdout: '',
+ stderr: 'daemon still alive after TERM(5s)+KILL(2s)',
+ exitCode: 3,
+ signal: null,
+ };
+ }
+ return baseExec(cmd, execOpts);
+ };
+ const result = await killRemoteCodexDaemon(host);
+ expect(result).toMatchObject({ ok: false, reason: 'pkill_failed' });
+ });
+});
+
describe('ssh-host-prefs-store agentProxy', () => {
it('round-trips an enabled pref', () => {
setSshHostAgentProxy('h1', PREF);
diff --git a/apps/desktop/src/main/remote-ssh/agent-proxy.ts b/apps/desktop/src/main/remote-ssh/agent-proxy.ts
index 74eb35d033..4b9d13f48c 100644
--- a/apps/desktop/src/main/remote-ssh/agent-proxy.ts
+++ b/apps/desktop/src/main/remote-ssh/agent-proxy.ts
@@ -252,19 +252,41 @@ async function writeRemoteMarker(host: RemoteHost, content: string | null): Prom
export async function killRemoteCodexDaemon(
host: RemoteHost,
): Promise<{ ok: true } | { ok: false; reason: 'pkill_failed'; detail?: string }> {
+ // TERM 后必须等到进程真正消失 (review: PR #715 greptile R6): pkill 只保证
+ // 信号送达 — 旧 daemon 若在 dying 窗口里响应 daemon version 探活,
+ // transport 会复用它 (旧 env), marker 变更静默落空。先 TERM + 轮询 5s,
+ // 没死透再 KILL + 轮询 2s; 仍活着按失败上报 (调用方走降级提示)。
+ // pgrep 不会匹配自身; bash 包装进程 cmdline 里的 pattern 文本经 [c]odex
+ // trick 处理后同样不命中 (与 pkill 的自排除同理)。
const killScript = `
USER_NAME=$(id -un 2>/dev/null)
if [ -z "$USER_NAME" ]; then echo "id -un returned empty" >&2; exit 2; fi
-pkill -u "$USER_NAME" -f '\\.xdt-server.*codex-home.*[c]odex app-server'
+PAT='\\.xdt-server.*codex-home.*[c]odex app-server'
+pkill -u "$USER_NAME" -f "$PAT"
rc=$?
case "$rc" in
- 0|1) exit 0 ;;
+ 0) ;;
+ 1) exit 0 ;;
*) echo "pkill rc=$rc" >&2; exit "$rc" ;;
esac
+i=0
+while [ $i -lt 5 ]; do
+ pgrep -u "$USER_NAME" -f "$PAT" >/dev/null 2>&1 || exit 0
+ i=$((i+1)); sleep 1
+done
+pkill -9 -u "$USER_NAME" -f "$PAT" 2>/dev/null || true
+i=0
+while [ $i -lt 2 ]; do
+ pgrep -u "$USER_NAME" -f "$PAT" >/dev/null 2>&1 || exit 0
+ i=$((i+1)); sleep 1
+done
+echo "daemon still alive after TERM(5s)+KILL(2s)" >&2
+exit 3
`;
try {
const result = await host.exec(`bash -c ${shellQuote(killScript)}`, {
- timeoutMs: 5_000,
+ // 脚本最坏路径: TERM 轮询 5s + KILL 轮询 2s + ssh/exec 开销 — 给 15s。
+ timeoutMs: 15_000,
label: 'kill-codex-daemon',
});
if (result.exitCode !== 0) {
diff --git a/packages/maker-core/src/agents/codex/app-server/host.test.ts b/packages/maker-core/src/agents/codex/app-server/host.test.ts
new file mode 100644
index 0000000000..1b3535129c
--- /dev/null
+++ b/packages/maker-core/src/agents/codex/app-server/host.test.ts
@@ -0,0 +1,121 @@
+import { describe, expect, it, vi } from 'vitest';
+
+import { AppServerHost } from './host.js';
+import type { Logger } from '../../../interfaces/logger.js';
+import type { Transport, LineHandler, StderrHandler, CloseHandler } from './transport.js';
+
+/** 任何请求都永不回应的 transport — 模拟远端 daemon bootstrap 挂死 / SSH 通道无响应。 */
+class HangingTransport implements Transport {
+ private readonly closeHandlers = new Set<CloseHandler>();
+
+ async writeLine(_line: string): Promise<void> {
+ // 请求照收, 永远不回 response → initialize 挂起。
+ }
+
+ onLine(_handler: LineHandler): () => void {
+ return () => {};
+ }
+
+ onClose(handler: CloseHandler): () => void {
+ this.closeHandlers.add(handler);
+ return () => this.closeHandlers.delete(handler);
+ }
+
+ onStderr(_handler: StderrHandler): () => void {
+ return () => {};
+ }
+
+ async close(reason = 'test close'): Promise<void> {
+ for (const handler of this.closeHandlers) handler({ reason });
+ }
+}
+
+/** 所有请求延迟 respondDelayMs 回应的 transport — initialize 最终能完成。 */
+class DelayedTransport implements Transport {
+ private readonly lineHandlers = new Set<LineHandler>();
+ private readonly closeHandlers = new Set<CloseHandler>();
+
+ constructor(private readonly respondDelayMs: number) {}
+
+ async writeLine(line: string): Promise<void> {
+ const msg = JSON.parse(line) as { id?: unknown };
+ if (msg.id == null) return; // notification (initialized 等), 无 response
+ setTimeout(() => {
+ const result = {
+ userAgent: 'mock-codex/test',
+ codexHome: '/tmp/codex-home',
+ platformOs: 'linux',
+ };
+ for (const handler of this.lineHandlers) handler(JSON.stringify({ id: msg.id, result }));
+ }, this.respondDelayMs);
+ }
+
+ onLine(handler: LineHandler): () => void {
+ this.lineHandlers.add(handler);
+ return () => this.lineHandlers.delete(handler);
+ }
+
+ onClose(handler: CloseHandler): () => void {
+ this.closeHandlers.add(handler);
+ return () => this.closeHandlers.delete(handler);
+ }
+
+ onStderr(_handler: StderrHandler): () => void {
+ return () => {};
+ }
+
+ async close(reason = 'test close'): Promise<void> {
+ for (const handler of this.closeHandlers) handler({ reason });
+ }
+}
+
+const logger: Logger = {
+ trace: vi.fn(),
+ debug: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ fatal: vi.fn(),
+ child: () => logger,
+};
+
+describe('AppServerHost.request startup timeout', () => {
+ it('bounds a hung ensureStarted by the caller-provided timeoutMs (greptile R6 P1)', async () => {
+ // 冷启动 / transport 重建时 ensureStarted 本身也可能永不返回 — 调用方显式
+ // 给的 timeoutMs 必须同样覆盖启动路径, 否则「关键 RPC 加超时」形同虚设。
+ const host = new AppServerHost({
+ createTransport: () => new HangingTransport(),
+ logger,
+ clientInfo: { name: 'cindy-test', version: '0.0.0' },
+ });
+
+ await expect(host.request('turn/start', {}, { timeoutMs: 50 })).rejects.toThrow(
+ 'app-server startup (for turn/start) timed out after 50ms',
+ );
+
+ await host.shutdown();
+ });
+
+ it('keeps the in-flight bootstrap reusable for a later request after a startup timeout', async () => {
+ // 超时只截断本次等待 — bootstrap 仍在后台继续 (startPromise 保留),
+ // 后续 request 直接复用, 不重新 spawn。
+ const createTransport = vi.fn(() => new DelayedTransport(60));
+ const host = new AppServerHost({
+ createTransport,
+ logger,
+ clientInfo: { name: 'cindy-test', version: '0.0.0' },
+ });
+
+ await expect(host.request('turn/start', {}, { timeoutMs: 20 })).rejects.toThrow(
+ /app-server startup.*timed out/,
+ );
+
+ // 后台 bootstrap (60ms) 完成后, 同一个 startPromise 直接可用。
+ await expect(host.request('turn/start', {}, { timeoutMs: 1_000 })).resolves.toMatchObject({
+ userAgent: 'mock-codex/test',
+ });
+ expect(createTransport).toHaveBeenCalledTimes(1);
+
+ await host.shutdown();
+ });
+});
diff --git a/packages/maker-core/src/agents/codex/app-server/host.ts b/packages/maker-core/src/agents/codex/app-server/host.ts
index e40ac37372..65b4288929 100644
--- a/packages/maker-core/src/agents/codex/app-server/host.ts
+++ b/packages/maker-core/src/agents/codex/app-server/host.ts
@@ -494,7 +494,33 @@ export class AppServerHost {
params?: unknown,
opts?: { timeoutMs?: number },
): Promise<R> {
- await this.ensureStarted();
+ // 冷启动 / transport 重建时 ensureStarted 本身也可能永不返回 (远端 daemon
+ // bootstrap 挂死 / SSH 通道无响应) — 调用方显式给 timeoutMs 时同样给它
+ // 上界, 否则「关键 RPC 加超时」在启动路径上形同虚设 (greptile R6 P1)。
+ const started = this.ensureStarted();
+ if (opts?.timeoutMs != null) {
+ let timer: NodeJS.Timeout | null = null;
+ try {
+ await Promise.race([
+ started,
+ new Promise<never>((_, reject) => {
+ timer = setTimeout(() => {
+ reject(new Error(`app-server startup (for ${method}) timed out after ${opts.timeoutMs}ms`));
+ }, opts.timeoutMs);
+ timer.unref?.();
+ }),
+ ]);
+ } catch (err) {
+ // 超时后 started 仍在后台继续 (下次 request 可直接复用) — 挂一个
+ // swallow catch 防它迟到 reject 时变成 unhandled rejection。
+ started.catch(() => { /* late startup failure swallowed after timeout */ });
+ throw err;
+ } finally {
+ if (timer) clearTimeout(timer);
+ }
+ } else {
+ await started;
+ }
if (!this.client) throw new Error('AppServerHost: client missing after ensureStarted (unreachable)');
return this.client.request<R>(method, params, opts);
}
diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.ts
index 50badf4dde..69a8dc7238 100644
--- a/packages/maker-core/src/agents/codex/index.test.ts
+++ b/packages/maker-core/src/agents/codex/index.test.ts
@@ -6323,6 +6323,73 @@ describe('CodexAgent turn lifecycle', () => {
await handle.close();
});
+ it('clears an accepted started-before-resp turn when turn/start later fails (greptile R6 P1)', async () => {
+ // started-before-resp 是协议允许的乱序: turnStarted 先于响应到达并被接受
+ // (currentTurnId/isTurnInFlight 置位) — 随后 turn/start RPC 失败时, 失败收口
+ // 必须把这个活跃 turn 一起收掉, 否则 UI 已 Done 但 isTurnRunning() 永真,
+ // 下一条 send 被 in-flight guard 挡死。
+ const turnStart = deferred<unknown>();
+ let failTurnStart = true;
+ const agent = new CodexAgent(createDeps());
+ const host = installFakeHost(agent, (method) => {
+ if (method === Method.TurnStart) {
+ if (failTurnStart) return turnStart.promise;
+ return { turn: { id: 'turn-2' } };
+ }
+ return undefined;
+ });
+ const handle = await agent.startSession({
+ sessionId: 'session-started-before-resp-failure',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ });
+ const subscribeCalls = host.subscribeThread.mock.calls as unknown as Array<[string, ThreadEventHandlers]>;
+ const handlers = subscribeCalls[0]?.[1];
+ const iterator = handle.events()[Symbol.asyncIterator]();
+
+ const sendPromise = handle.send({ type: 'user', content: 'hello' });
+ for (let i = 0; i < 5; i += 1) {
+ if (host.request.mock.calls.some(([method]) => method === Method.TurnStart)) break;
+ await Promise.resolve();
+ }
+ expect(host.request.mock.calls.filter(([method]) => method === Method.TurnStart)).toHaveLength(1);
+
+ // started-before-resp: turnStarted 先于响应到达并被接受, turn 状态置位。
+ handlers.turnStarted?.({ threadId: 'start-thread-id', turn: { id: 'early-turn' } });
+ expect(handle.isTurnRunning?.()).toBe(true);
+ expect(handle.getCurrentTurnId?.()).toBe('early-turn');
+
+ // turn/start 随后失败 → 失败收口把活跃 turn 一起收掉: 清状态 + 补 interrupt。
+ turnStart.reject(new Error('codex app-server turn/start timed out after 60000ms'));
+ await sendPromise;
+
+ expect(await nextEvent(iterator)).toMatchObject({ type: 'status', data: { isRunning: true } });
+ expect(await nextEvent(iterator)).toMatchObject({ type: 'error', data: { isTerminal: true } });
+ expect(await nextEvent(iterator)).toMatchObject({
+ type: 'status',
+ data: { status: 'Done', isRunning: false },
+ });
+ expect(handle.isTurnRunning?.()).toBe(false);
+ expect(handle.getCurrentTurnId?.()).toBeNull();
+ await vi.waitFor(() => {
+ expect(host.request).toHaveBeenCalledWith(
+ Method.TurnInterrupt,
+ expect.objectContaining({ threadId: 'start-thread-id', turnId: 'early-turn' }),
+ );
+ });
+
+ // 该 turn 已立墓碑: 迟到的 turnCompleted 被挡, 不产生 UI 事件。
+ handlers.turnCompleted?.({ threadId: 'start-thread-id', turn: { id: 'early-turn', status: 'completed' } });
+ await expect(nextEvent(iterator)).rejects.toThrow('timed out waiting for event');
+
+ // 下一条 send 不被 in-flight guard 挡死, turn 正常激活。
+ failTurnStart = false;
+ await handle.send({ type: 'user', content: 'again' });
+ expect(handle.isTurnRunning?.()).toBe(true);
+ expect(handle.getCurrentTurnId?.()).toBe('turn-2');
+ await handle.close();
+ });
+
it('clears running state and emits done status after terminal error notification', async () => {
const agent = new CodexAgent(createDeps());
const host = installFakeHost(agent);
diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.ts
index c09f8ebe14..fb812cdcf3 100644
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@ -4741,6 +4741,27 @@ export class CodexAgent extends BaseAgent {
// turn/start 只是响应没回来。立孤儿守卫: 之后迟到的 turnStarted 不得
// 重新激活会话 (greptile P1: 已报终态错误的会话又回到 generating)。
turnStartFailedWithoutTurnId = true;
+ // turnStarted 也可能已先于响应到达并被接受 (started-before-resp 是
+ // 协议允许的乱序) — 此时 currentTurnId/isTurnInFlight 已置位, 失败
+ // 收口必须把这个活跃 turn 一起收掉: 立墓碑挡后续事件 + 清 turn 状态 +
+ // 补 interrupt (daemon 侧该 turn 还在跑)。否则 UI 已 Done 但
+ // handle.isTurnRunning() 永真, 下一条 send 被 in-flight guard 挡死
+ // (greptile R6 P1)。
+ if (currentTurnId) {
+ const orphanTurnId = currentTurnId;
+ terminalErroredTurnIds.add(orphanTurnId);
+ if (threadId) {
+ host.request(Method.TurnInterrupt, { threadId, turnId: orphanTurnId }).catch((e2: unknown) => {
+ log.warn('turn/start-failure orphan interrupt failed (best-effort)', {
+ turnId: orphanTurnId,
+ error: e2 instanceof Error ? e2.message : String(e2),
+ });
+ });
+ }
+ currentTurnId = null;
+ isTurnInFlight = false;
+ currentTurnPlanModeActive = false;
+ }
log.error('turn/start failed', { error: String(finalErr) });
eventQueue.push({
type: 'error',