Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(maker-core,desktop): 处理 R9 review 的 1+3 条意见
yan3168da95b660
diff --git a/apps/desktop/src/main/remote-ssh/__tests__/agentProxy.test.ts b/apps/desktop/src/main/remote-ssh/__tests__/agentProxy.test.tsindex 3f0648743d..1095c01395 100644--- a/apps/desktop/src/main/remote-ssh/__tests__/agentProxy.test.ts+++ b/apps/desktop/src/main/remote-ssh/__tests__/agentProxy.test.ts@@ -43,10 +43,12 @@ vi.mock('node:fs', async (importOriginal) => {});import {+ applyAgentProxyForHost,buildAgentProxyEnv,buildAgentProxyEnvUppercase,buildAgentProxyMarkerContent,ensureAgentProxyTunnel,+ getAgentProxyTunnelState,killRemoteCodexDaemon,reconcileCodexAgentProxyEnv,} from '../agent-proxy';@@ -280,6 +282,87 @@ describe('killRemoteCodexDaemon', () => {});});+describe('applyAgentProxyForHost disable path', () => {+ it('reports apply error when the daemon survives pkill during proxy disable (codex R9 P2)', async () => {+ // 先 enable 建隧道 (marker 已就位)。+ setSshHostAgentProxy('test-host', PREF);+ const { host } = makeFakeHost({ marker: "export HTTPS_PROXY='http://127.0.0.1:17893'" });+ await applyAgentProxyForHost(host);+ expect(getAgentProxyTunnelState('test-host')?.active).toBe(true);++ // disable: 隧道拆 + marker 清, 但 daemon 没死透 — 旧 daemon 还握着指向+ // 已关闭端口的 proxy env, 卡片必须落错误而不是谎称「已关闭」。+ setSshHostAgentProxy('test-host', null);+ 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);+ };+ await applyAgentProxyForHost(host);+ const state = getAgentProxyTunnelState('test-host');+ expect(state?.active).toBe(false);+ expect(state?.lastError).toMatch(/survived pkill/);+ });++ it('serializes concurrent reconciles per host so a fast-path caller never probes mid-restart (codex R9 P2)', async () => {+ // 并发 reconcile (两个 transport 的 beforeDaemonProbe 同时触发): 第一个+ // 还在等 killRemoteCodexDaemon 时, 第二个必须排队, 不得走 marker-match+ // fast path 直接去 probe 旧 daemon。+ setSshHostAgentProxy('test-host', PREF);+ const { host, state } = makeFakeHost({ marker: null });++ let killStarted = false;+ let releaseKill: (() => void) | null = null;+ const baseExec = host.exec.bind(host);+ host.exec = async (cmd: string, execOpts?: { input?: string }) => {+ if (cmd.includes('pkill')) {+ // 进入 kill-and-wait 即翻牌 (baseExec 的记录要等释放后才有,+ // 不能拿 execCalls 当等待信号)。+ killStarted = true;+ await new Promise<void>((resolve) => {+ releaseKill = resolve;+ });+ }+ return baseExec(cmd, execOpts);+ };++ const order: string[] = [];+ const first = reconcileCodexAgentProxyEnv(host).then((r) => {+ order.push('first-done');+ return r;+ });+ // 等第一个写完 marker 并卡在 kill-and-wait 阶段。+ await vi.waitFor(() => {+ expect(killStarted).toBe(true);+ });+ const second = reconcileCodexAgentProxyEnv(host).then((r) => {+ order.push('second-done');+ return r;+ });+ // 第二个已入队但不得开工: 给它一拍机会, 确认没有第二个 cat/pkill 发生。+ await Promise.resolve();+ const execCountWhileFirstBlocked = state.execCalls.length;+ await Promise.resolve();+ expect(state.execCalls.length).toBe(execCountWhileFirstBlocked);++ releaseKill?.();+ const [r1, r2] = await Promise.all([first, second]);+ expect(r1.markerChanged).toBe(true);+ expect(r1.daemonRestarted).toBe(true);+ // 第二个在第一个完成后才走对账: 此时 marker 已一致 → fast path 零副作用。+ expect(r2).toEqual({ markerChanged: false, daemonRestarted: false });+ expect(order).toEqual(['first-done', 'second-done']);+ expect(state.pkillCount).toBe(1);+ });+});+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.tsindex eba33f1428..e9559baaef 100644--- a/apps/desktop/src/main/remote-ssh/agent-proxy.ts+++ b/apps/desktop/src/main/remote-ssh/agent-proxy.ts@@ -331,6 +331,31 @@ exit 3*/export async function reconcileCodexAgentProxyEnv(host: RemoteHost,+): Promise<{ markerChanged: boolean; daemonRestarted: boolean }> {+ // per-host 串行链 (codex R9 P2): 并发 reconcile (两个 transport 的+ // beforeDaemonProbe 与 ready-hook 同时触发) 时, 若第一个还在等+ // killRemoteCodexDaemon 而第二个走 marker-match fast path, 第二个会直接去+ // probe 旧 daemon — attach 到 stale-env daemon, 或握手途中被 pkill。+ // 所有调用按 host 排队, 后来者等前一个写完 marker + 杀完 daemon 再走自己+ // 的对账 (那时 fast path 才真的代表「环境已一致」)。+ const prev = reconcileChains.get(host.id) ?? Promise.resolve();+ const run = prev.then(() => reconcileCodexAgentProxyEnvSerialized(host));+ // 链上只存 settled 版 (前一个失败不堵后一个); 调用方拿自己的 run 结果。+ const tracked = run.then(+ () => undefined,+ () => undefined,+ );+ reconcileChains.set(host.id, tracked);+ void tracked.then(() => {+ if (reconcileChains.get(host.id) === tracked) reconcileChains.delete(host.id);+ });+ return run;+}++const reconcileChains = new Map<string, Promise<void>>();++async function reconcileCodexAgentProxyEnvSerialized(+ host: RemoteHost,): Promise<{ markerChanged: boolean; daemonRestarted: boolean }> {const pref = getSshHostAgentProxy(host.id);let desired: string | null = null;@@ -365,7 +390,16 @@ export async function applyAgentProxyForHost(host: RemoteHost): Promise<void> {try {if (!pref) {await closeAllForwards(host);- await reconcileCodexAgentProxyEnv(host);+ const reconciled = await reconcileCodexAgentProxyEnv(host);+ // 隧道已拆但旧 daemon 没死透 = 它还握着指向已关闭端口的 proxy env,+ // 后续 codex turn 全部 proxy-connect 失败, 而 marker/隧道状态已清、+ // UI 显示 proxy 已关 (codex R9 P2) — 按 apply 失败上报, 让用户在+ // 卡片上看到错误而不是一个说谎的「已关闭」。+ if (reconciled.markerChanged && !reconciled.daemonRestarted) {+ throw new Error(+ 'codex daemon survived pkill after proxy disable; it still holds the old proxy env (retry disable or restart the host)',+ );+ }tunnelStates.delete(host.id);emitState(host.id);return;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.tsindex 1b3535129c..e624842fb6 100644--- a/packages/maker-core/src/agents/codex/app-server/host.test.ts+++ b/packages/maker-core/src/agents/codex/app-server/host.test.ts@@ -118,4 +118,25 @@ describe('AppServerHost.request startup timeout', () => {await host.shutdown();});++ it('treats timeoutMs as an overall deadline across startup + request (copilot R9)', async () => {+ // timeoutMs 不是「startup 一次 + request 再一次」的双重施加: startup 用掉+ // 的预算要从 request 里扣, 最坏等待仍是 1× timeoutMs — 否则 60s 关键 RPC+ // 在冷启动路径上最坏拖到 ~120s, UI 长时间卡 generating。+ // DelayedTransport(40): startup ~40ms, 预算 50ms → request 只剩 ~10ms。+ // 1× 语义 ~50ms 超时; 2× 语义要 ~90ms (40 + 50) 才超时。+ const host = new AppServerHost({+ createTransport: () => new DelayedTransport(40),+ logger,+ clientInfo: { name: 'cindy-test', version: '0.0.0' },+ });++ const startedAt = Date.now();+ await expect(host.request('turn/start', {}, { timeoutMs: 50 })).rejects.toThrow(+ /timed out after \d+ms|consumed the entire/,+ );+ expect(Date.now() - startedAt).toBeLessThan(70);++ 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.tsindex 65b4288929..d494161bc1 100644--- a/packages/maker-core/src/agents/codex/app-server/host.ts+++ b/packages/maker-core/src/agents/codex/app-server/host.ts@@ -497,8 +497,12 @@ export class AppServerHost {// 冷启动 / transport 重建时 ensureStarted 本身也可能永不返回 (远端 daemon// bootstrap 挂死 / SSH 通道无响应) — 调用方显式给 timeoutMs 时同样给它// 上界, 否则「关键 RPC 加超时」在启动路径上形同虚设 (greptile R6 P1)。+ // timeoutMs 是 startup + request 的整体 deadline (copilot R9): startup 用掉+ // 的预算从 request 里扣, 否则最坏等 2× timeoutMs, 与「关键 RPC 60s 上界」+ // 的意图冲突, UI 仍可能长时间卡 generating。const started = this.ensureStarted();if (opts?.timeoutMs != null) {+ const deadline = Date.now() + opts.timeoutMs;let timer: NodeJS.Timeout | null = null;try {await Promise.race([@@ -518,9 +522,14 @@ export class AppServerHost {} finally {if (timer) clearTimeout(timer);}- } else {- await started;+ const remaining = deadline - Date.now();+ if (remaining <= 0) {+ throw new Error(`app-server startup (for ${method}) consumed the entire ${opts.timeoutMs}ms timeout budget`);+ }+ if (!this.client) throw new Error('AppServerHost: client missing after ensureStarted (unreachable)');+ return this.client.request<R>(method, params, { ...opts, timeoutMs: remaining });}+ 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.tsindex 69a8dc7238..b7cc7e6291 100644--- a/packages/maker-core/src/agents/codex/index.test.ts+++ b/packages/maker-core/src/agents/codex/index.test.ts@@ -6390,6 +6390,131 @@ describe('CodexAgent turn lifecycle', () => {await handle.close();});+ it('buffers an ambiguous turnStarted during a retry-pending window and interrupts it once the response proves it an orphan (codex R9 P2)', async () => {+ // 第一次 turn/start 失败立孤儿守卫; 第二次 send 的 turn/start 在飞期间+ // 第一次的迟到 started 到达 — 归属不明 (协议不带 request id), 必须缓冲+ // 隔离而不是接受 (否则孤儿 item 事件渲染到第二次 send 下)。响应到了按+ // turnId 对账: 不一致 → interrupt + 墓碑; 响应的 turn 正常激活。+ const firstStart = deferred<unknown>();+ const secondStart = deferred<unknown>();+ let attempt = 0;+ const agent = new CodexAgent(createDeps());+ const host = installFakeHost(agent, (method) => {+ if (method === Method.TurnStart) {+ attempt += 1;+ if (attempt === 1) return firstStart.promise;+ return secondStart.promise;+ }+ return undefined;+ });+ const handle = await agent.startSession({+ sessionId: 'session-buffered-orphan-started',+ 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]();++ // 第一次 send → turn/start 悬挂 → 失败 (立孤儿守卫)。+ const send1 = handle.send({ type: 'user', content: 'first' });+ for (let i = 0; i < 5; i += 1) {+ if (host.request.mock.calls.some(([method]) => method === Method.TurnStart)) break;+ await Promise.resolve();+ }+ firstStart.reject(new Error('codex app-server turn/start timed out after 60000ms'));+ await send1;+ 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 },+ });++ // 第二次 send → turn/start 在飞 → 第一次的迟到 started 到达: 缓冲隔离,+ // 既不激活也不立即 interrupt (归属未定)。+ const send2 = handle.send({ type: 'user', content: 'second' });+ for (let i = 0; i < 5; i += 1) {+ if (host.request.mock.calls.filter(([method]) => method === Method.TurnStart).length >= 2) break;+ await Promise.resolve();+ }+ handlers.turnStarted?.({ threadId: 'start-thread-id', turn: { id: 'orphan-turn' } });+ expect(handle.isTurnRunning?.()).toBe(false);+ expect(handle.getCurrentTurnId?.()).toBeNull();+ expect(+ host.request.mock.calls.some(+ ([method, params]) =>+ method === Method.TurnInterrupt && (params as { turnId?: string }).turnId === 'orphan-turn',+ ),+ ).toBe(false);++ // 第二次响应 turn-2 ≠ orphan-turn → 孤儿坐实: interrupt + 墓碑; turn-2 激活。+ secondStart.resolve({ turn: { id: 'turn-2' } });+ await send2;+ await vi.waitFor(() => {+ expect(host.request).toHaveBeenCalledWith(+ Method.TurnInterrupt,+ expect.objectContaining({ threadId: 'start-thread-id', turnId: 'orphan-turn' }),+ );+ });+ expect(handle.isTurnRunning?.()).toBe(true);+ expect(handle.getCurrentTurnId?.()).toBe('turn-2');+ await handle.close();+ });++ it('activates a buffered turnStarted when the turn/start response returns the same id (codex R9 P2)', async () => {+ // 同款 pending 窗口, 但到达的 started 就是在飞 RPC 自己的 (合法+ // started-before-resp 与孤儿守卫共存): 缓冲期间不激活; 响应 id 一致 →+ // 正常激活, 不发 interrupt。+ const firstStart = deferred<unknown>();+ const secondStart = deferred<unknown>();+ let attempt = 0;+ const agent = new CodexAgent(createDeps());+ const host = installFakeHost(agent, (method) => {+ if (method === Method.TurnStart) {+ attempt += 1;+ if (attempt === 1) return firstStart.promise;+ return secondStart.promise;+ }+ return undefined;+ });+ const handle = await agent.startSession({+ sessionId: 'session-buffered-started-accepted',+ model: 'gpt-5.4',+ workingDir: '/repo',+ });+ const subscribeCalls = host.subscribeThread.mock.calls as unknown as Array<[string, ThreadEventHandlers]>;+ const handlers = subscribeCalls[0]?.[1];++ const send1 = handle.send({ type: 'user', content: 'first' });+ for (let i = 0; i < 5; i += 1) {+ if (host.request.mock.calls.some(([method]) => method === Method.TurnStart)) break;+ await Promise.resolve();+ }+ firstStart.reject(new Error('codex app-server turn/start timed out after 60000ms'));+ await send1;++ const send2 = handle.send({ type: 'user', content: 'second' });+ for (let i = 0; i < 5; i += 1) {+ if (host.request.mock.calls.filter(([method]) => method === Method.TurnStart).length >= 2) break;+ await Promise.resolve();+ }+ // 在飞 RPC 自己的 started 先到: 缓冲, 不立即激活。+ handlers.turnStarted?.({ threadId: 'start-thread-id', turn: { id: 'early-turn' } });+ expect(handle.isTurnRunning?.()).toBe(false);+ expect(handle.getCurrentTurnId?.()).toBeNull();++ // 响应 id 一致 → 激活, 全程无 interrupt。+ secondStart.resolve({ turn: { id: 'early-turn' } });+ await send2;+ expect(handle.isTurnRunning?.()).toBe(true);+ expect(handle.getCurrentTurnId?.()).toBe('early-turn');+ expect(+ host.request.mock.calls.some(([method]) => method === Method.TurnInterrupt),+ ).toBe(false);+ 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.tsindex fb812cdcf3..c2c42ee377 100644--- a/packages/maker-core/src/agents/codex/index.ts+++ b/packages/maker-core/src/agents/codex/index.ts@@ -2090,6 +2090,12 @@ export class CodexAgent extends BaseAgent {// turn/start RPC 失败(超时/拒绝)后置位: server 可能实际已建 turn,// 迟到的孤儿 turnStarted 由 turnStarted handler 拦下并补 interrupt。let turnStartFailedWithoutTurnId = false;+ // 孤儿守卫生效期间又有新 turn/start 在飞时, 到达的 turnStarted 归属不明+ // (协议不带 request id: 可能是失败 RPC 的孤儿, 也可能是在飞 RPC 合法的+ // started-before-resp) — 先缓冲隔离, 等响应到了按 turnId 对账: 一致激活,+ // 不一致 interrupt + 墓碑 (codex R9 P2)。缓冲期间不置 currentTurnId,+ // 孤儿 turn 的 item 事件不会被渲染到本次 send 下。+ const bufferedOrphanTurnIds = new Set<string>();type TurnCompletedParams = Parameters<NonNullable<ThreadEventHandlers['turnCompleted']>>[0];// 正常完成的 turn 也必须保留墓碑:app-server 允许 turn/completed 早于仍在// 后台收尾的 item 事件到达。没有这层墓碑时,currentTurnId 已清空,迟到 item@@ -4127,10 +4133,20 @@ export class CodexAgent extends BaseAgent {if (turnsCompletedBeforeStartResp.has(params.turn.id)) return;// turn/start RPC 已失败(超时/拒绝)但 daemon 实际已建 turn — 迟到的孤儿// turnStarted 不得重新激活已报终态错误的会话 (greptile P1): 立墓碑 +- // 补 interrupt 让 daemon 停掉这个没人消费的 turn。仅在没有新 turn/start- // 在飞时判定 — 在飞期间到达的 started 按正常路径处理 (与成功路径的- // started-先于-resp 乱序共存; 该固有歧义不由本守卫承担)。- if (turnStartFailedWithoutTurnId && !isTurnStartPending && currentTurnId === null) {+ // 补 interrupt 让 daemon 停掉这个没人消费的 turn。+ if (turnStartFailedWithoutTurnId && currentTurnId === null) {+ if (isTurnStartPending) {+ // 新 turn/start 在飞 → 归属不明 (失败 RPC 的孤儿 vs 在飞 RPC 合法的+ // started-before-resp, 协议层无法区分): 缓冲隔离, 等响应按 turnId+ // 对账 (codex R9 P2)。直接接受会让孤儿 turn 的 item 事件渲染到+ // 本次 send 下。+ bufferedOrphanTurnIds.add(params.turn.id);+ log.debug('buffering ambiguous turnStarted until turn/start response arrives', {+ turnId: params.turn.id,+ threadId,+ });+ return;+ }terminalErroredTurnIds.add(params.turn.id);log.warn('ignoring orphan turnStarted from a failed turn/start — interrupting server-side turn', {turnId: params.turn.id,@@ -4204,6 +4220,9 @@ export class CodexAgent extends BaseAgent {}},turnCompleted: (params) => {+ // daemon 自己跑完的 buffered 孤儿 turn 无需再等对账 — 出缓冲防泄漏+ // (codex R9 P2); completed 本体走既有 stale/墓碑路径。+ bufferedOrphanTurnIds.delete(params.turn.id);handleTurnCompleted(params);},itemStarted: (params) => {@@ -4597,6 +4616,38 @@ export class CodexAgent extends BaseAgent {// 普通 LLM 错误 / 超时 / auth 失败照原路径报错。const handleTurnStartResp = (resp: TurnStartResponse): void => {if (resp.turn?.id) {+ // 缓冲的歧义 started 对账 (codex R9 P2): 本响应确立在飞 RPC 的+ // turnId — 缓冲里 id 一致的是它的合法 started (下方正常激活),+ // 不一致的是失败 RPC 的孤儿 (interrupt + 墓碑, 没人消费)。+ if (bufferedOrphanTurnIds.size > 0) {+ const wasBuffered = bufferedOrphanTurnIds.has(resp.turn.id);+ for (const bufferedId of bufferedOrphanTurnIds) {+ if (bufferedId === resp.turn.id) continue;+ terminalErroredTurnIds.add(bufferedId);+ log.warn('buffered turnStarted proven orphan by turn/start response — interrupting', {+ turnId: bufferedId,+ acceptedTurnId: resp.turn.id,+ threadId,+ });+ if (threadId) {+ host.request(Method.TurnInterrupt, { threadId, turnId: bufferedId }).catch((e2: unknown) => {+ log.warn('buffered orphan turn interrupt failed (best-effort)', {+ turnId: bufferedId,+ error: e2 instanceof Error ? e2.message : String(e2),+ });+ });+ }+ }+ bufferedOrphanTurnIds.clear();+ if (wasBuffered) {+ // 合法 started 曾被缓冲: 补做 turnStarted 正常路径被跳过的+ // per-turn 状态重置 (与 turnStarted handler 同款)。+ proposedPlanText = null;+ translatorRt.lastAuthErrorKey = null;+ translatorRt.networkRetryNotice = null;+ turnRetryTracker.reset();+ }+ }// turn/start 成功 → 孤儿守卫解除 (上次失败的 RPC 若也有迟到 started,// 那是一次新的语义重叠, 由 turn id 匹配路径处理)。turnStartFailedWithoutTurnId = false;@@ -4762,6 +4813,20 @@ export class CodexAgent extends BaseAgent {isTurnInFlight = false;currentTurnPlanModeActive = false;}+ // 缓冲的歧义 started 随本次失败一并坐实孤儿身份 (codex R9 P2):+ // 没人消费, 全部 interrupt + 墓碑。+ for (const bufferedId of bufferedOrphanTurnIds) {+ terminalErroredTurnIds.add(bufferedId);+ if (threadId) {+ host.request(Method.TurnInterrupt, { threadId, turnId: bufferedId }).catch((e2: unknown) => {+ log.warn('buffered orphan turn interrupt failed (best-effort)', {+ turnId: bufferedId,+ error: e2 instanceof Error ? e2.message : String(e2),+ });+ });+ }+ }+ bufferedOrphanTurnIds.clear();log.error('turn/start failed', { error: String(finalErr) });eventQueue.push({type: 'error',