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): 修复 Codex response-first turn 初始化 (#3099)
nextzhou95af24629a25
diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.tsindex cd51b6d8ad..d349489757 100644--- a/packages/maker-core/src/agents/codex/index.test.ts+++ b/packages/maker-core/src/agents/codex/index.test.ts@@ -347,6 +347,37 @@ function deferred<T>() {return { promise, resolve, reject };}+const ROOT_TURN_START_ORDER_CASES = [+ {+ name: 'response-first',+ sessionSuffix: 'response-first',+ steps: [+ { kind: 'response', at: 2_000 },+ { kind: 'started', at: 3_000 },+ ],+ expectedDurationMs: 2_000,+ },+ {+ name: 'notification-first',+ sessionSuffix: 'notification-first',+ steps: [+ { kind: 'started', at: 2_000 },+ { kind: 'response', at: 3_000 },+ ],+ expectedDurationMs: 3_000,+ },+ {+ name: 'duplicate turn/started',+ sessionSuffix: 'duplicate-started',+ steps: [+ { kind: 'response', at: 2_000 },+ { kind: 'started', at: 3_000 },+ { kind: 'started', at: 3_500 },+ ],+ expectedDurationMs: 2_000,+ },+] as const;+async function waitForExpectation(assertion: () => void | Promise<void>, timeoutMs = 1_000): Promise<void> {const deadline = Date.now() + timeoutMs;let lastError: unknown;@@ -15062,12 +15093,83 @@ describe('CodexAgent MCP thread context hooks', () => {await handle.close();});- it('excludes a server-resolved approval wait from the completed turn duration', async () => {+ it.each(ROOT_TURN_START_ORDER_CASES)(+ 'starts generation timing once for $name root-turn activation',+ async ({ sessionSuffix, steps, expectedDurationMs }) => {+ let now = 1_000;+ const nowSpy = vi.spyOn(Date, 'now').mockImplementation(() => now);+ try {+ const turnStartResponse = deferred<{ turn: { id: string } }>();+ const agent = new CodexAgent(createDeps());+ const host = installFakeHost(agent, (method) => {+ if (method === Method.TurnStart) return turnStartResponse.promise;+ return undefined;+ });+ const handle = await agent.startSession({+ sessionId: `session-turn-start-order-${sessionSuffix}`,+ model: 'gpt-5.4',+ workingDir: '/repo',+ });+ const handlers = host.getThreadHandlers();+ if (!handlers?.turnStarted || !handlers.turnCompleted) {+ throw new Error('expected turn lifecycle handlers');+ }+ const events: AgentEvent[] = [];+ void (async () => {+ for await (const event of handle.events()) events.push(event);+ })();++ const sendPromise = handle.send({ type: 'user', content: 'hello' });+ await waitForExpectation(() => {+ expect(host.request).toHaveBeenCalledWith(+ Method.TurnStart,+ expect.any(Object),+ expect.any(Object),+ );+ });++ for (const step of steps) {+ now = step.at;+ if (step.kind === 'response') {+ turnStartResponse.resolve({ turn: { id: 'turn-ordering' } });+ await sendPromise;+ } else {+ handlers.turnStarted({+ threadId: 'start-thread-id',+ turn: { id: 'turn-ordering' },+ });+ }+ }++ now = 5_000;+ handlers.turnCompleted({+ threadId: 'start-thread-id',+ turn: { id: 'turn-ordering', status: 'completed' },+ });+ await waitForExpectation(() => {+ expect(events.some((event) => event.type === 'done')).toBe(true);+ });+ const done = events.find((event) => event.type === 'done');+ expect((done?.data as { usage?: { durationMs?: number } }).usage?.durationMs)+ .toBe(expectedDurationMs);++ await handle.close();+ } finally {+ nowSpy.mockRestore();+ }+ },+ );++ it('starts response-first generation timing at turn/started and excludes an approval wait', async () => {let now = 1_000;const nowSpy = vi.spyOn(Date, 'now').mockImplementation(() => now);try {const agent = new CodexAgent(createDeps());- const host = installFakeHost(agent);+ const turnStartResponse = deferred<{ turn: { id: string } }>();+ const host = installFakeHost(agent, (method) => {+ if (method === Method.TurnStart) return turnStartResponse.promise;+ return undefined;+ });const handle = await agent.startSession({sessionId: 'session-approval-generation-timing',model: 'gpt-5.4',@@ -15090,8 +15192,24 @@ describe('CodexAgent MCP thread context hooks', () => {const interactionResolver = vi.fn(() => new Promise<never>(() => {}));handle.setInteractionResolver(interactionResolver);+ const sendPromise = handle.send({ type: 'user', content: 'run pwd' });+ await waitForExpectation(() => {+ expect(host.request).toHaveBeenCalledWith(+ Method.TurnStart,+ expect.any(Object),+ expect.any(Object),+ );+ });+ now = 5_000;+ turnStartResponse.resolve({ turn: { id: 'turn-1' } });+ await sendPromise;++ // The RPC response only establishes ownership. Generation timing starts+ // from the later turn/started notification, matching the real app-server+ // response-first sequence.+ now = 7_000;handlers.turnStarted({ threadId: 'start-thread-id', turn: { id: 'turn-1' } });- now = 2_000;+ now = 8_000;const approvalPromise = handlers.commandExecutionApproval({threadId: 'start-thread-id',turnId: 'turn-1',@@ -15101,17 +15219,17 @@ describe('CodexAgent MCP thread context hooks', () => {});await waitForExpectation(() => expect(interactionResolver).toHaveBeenCalledTimes(1));- now = 10_000;+ now = 16_000;handlers.serverRequestResolved({threadId: 'start-thread-id',requestId: 'approval-item-1',});await expect(approvalPromise).resolves.toEqual({ decision: 'decline' });- now = 12_000;+ now = 18_000;handlers.turnCompleted({threadId: 'start-thread-id',- turn: { id: 'turn-1', status: 'completed', durationMs: 11_000 },+ turn: { id: 'turn-1', status: 'completed', durationMs: 17_000 },});await waitForExpectation(() => expect(events.some((event) => event.type === 'done')).toBe(true));const done = events.find((event) => event.type === 'done');@@ -15123,7 +15241,7 @@ describe('CodexAgent MCP thread context hooks', () => {}});- it('resets generation timing when turn/start response arrives before turnStarted', async () => {+ it('resets prior generation timing on response without starting before turnStarted', async () => {let now = 1_000;const nowSpy = vi.spyOn(Date, 'now').mockImplementation(() => now);try {@@ -15204,7 +15322,7 @@ describe('CodexAgent MCP thread context hooks', () => {expect(events.some((event) => event.type === 'done')).toBe(true),);const done = events.find((event) => event.type === 'done');- expect((done?.data as { usage?: { durationMs?: number } }).usage?.durationMs).toBe(2_500);+ expect((done?.data as { usage?: { durationMs?: number } }).usage?.durationMs).toBe(1_500);await handle.close();} finally {@@ -16858,6 +16976,114 @@ describe('CodexAgent rewind', () => {});describe('CodexAgent turn lifecycle', () => {+ it.each(ROOT_TURN_START_ORDER_CASES)(+ 'preserves same-turn retry state across $name activation signals',+ async ({ sessionSuffix, steps }) => {+ const agent = new CodexAgent(createDeps());+ const turnStartResponse = deferred<{ turn: { id: string } }>();+ const host = installFakeHost(agent, (method) => {+ if (method === Method.TurnStart) return turnStartResponse.promise;+ if (method === Method.TurnInterrupt) return {};+ return undefined;+ });+ const handle = await agent.startSession({+ sessionId: `session-turn-retry-state-${sessionSuffix}`,+ model: 'gpt-5.4',+ workingDir: '/repo',+ });+ const handlers = host.getThreadHandlers();+ if (!handlers?.turnStarted || !handlers.error) {+ throw new Error('expected turn lifecycle and error handlers');+ }+ const events: AgentEvent[] = [];+ void (async () => {+ for await (const event of handle.events()) events.push(event);+ })();++ const sendPromise = handle.send({ type: 'user', content: 'hello' });+ await waitForExpectation(() => {+ expect(host.request).toHaveBeenCalledWith(+ Method.TurnStart,+ expect.any(Object),+ expect.any(Object),+ );+ });+ const applyStep = async (step: (typeof steps)[number]) => {+ if (step.kind === 'response') {+ turnStartResponse.resolve({ turn: { id: 'turn-retry-state' } });+ await sendPromise;+ } else {+ handlers.turnStarted({+ threadId: 'start-thread-id',+ turn: { id: 'turn-retry-state' },+ });+ }+ };++ await applyStep(steps[0]);+ const authError = {+ threadId: 'start-thread-id',+ turnId: 'turn-retry-state',+ willRetry: true,+ error: { message: 'unexpected status 401 Unauthorized: Missing bearer' },+ } as const;+ const rateLimitError = {+ threadId: 'start-thread-id',+ turnId: 'turn-retry-state',+ willRetry: true,+ error: { message: 'unexpected status 429 Too Many Requests' },+ } as const;+ const backendError = {+ threadId: 'start-thread-id',+ turnId: 'turn-retry-state',+ willRetry: true,+ error: { message: 'unexpected status 403 Forbidden, url: https://chatgpt.com/backend-api/codex/responses' },+ } as const;++ handlers.error(authError);+ handlers.error(rateLimitError);+ handlers.error(rateLimitError);+ for (let index = 0; index < 29; index += 1) {+ handlers.error(backendError);+ }++ for (const step of steps.slice(1)) {+ await applyStep(step);+ }+ handlers.error(authError);+ handlers.error(rateLimitError);+ handlers.error(backendError);++ await waitForExpectation(() => {+ expect(+ events.some(+ (event) =>+ event.type === 'error'+ && (event.data as { isTerminal?: boolean }).isTerminal === true,+ ),+ ).toBe(true);+ });+ const errorEvents = events.filter((event) => event.type === 'error');+ expect(+ errorEvents.filter(+ (event) => (event.data as { isTerminal?: boolean }).isTerminal === false,+ ),+ ).toHaveLength(2);+ expect(errorEvents.at(-1)?.data).toMatchObject({+ isTerminal: true,+ message: expect.stringContaining('Codex backend unreachable'),+ });+ await waitForExpectation(() => {+ expect(host.request).toHaveBeenCalledWith(Method.TurnInterrupt, {+ threadId: 'start-thread-id',+ turnId: 'turn-retry-state',+ });+ });++ await handle.close();+ },+ );+it('escalates a persistent willRetry retry-loop to a terminal error (issue #677)', async () => {// 远端摸不到 Codex 后端时 daemon 无限发 willRetry=true — 升级逻辑应在阈值处// 合成终态错误并复位 turn (isTurnRunning=false + Done status), 消息里带原始@@ -23582,6 +23808,102 @@ describe('CodexAgent context window reporting', () => {await handle.close();});+ it.each(ROOT_TURN_START_ORDER_CASES)(+ 'clears prior diffs once for $name root-turn activation',+ async ({ sessionSuffix, steps }) => {+ const currentTurnResponse = deferred<{ turn: { id: string } }>();+ let turnStartCount = 0;+ const agent = new CodexAgent(createDeps());+ const host = installFakeHost(agent, (method) => {+ if (method !== Method.TurnStart) return undefined;+ turnStartCount += 1;+ if (turnStartCount === 1) return { turn: { id: 'turn-previous-diff' } };+ if (turnStartCount === 2) return currentTurnResponse.promise;+ throw new Error('unexpected extra turn/start');+ });+ const handle = await agent.startSession({+ sessionId: `session-turn-diff-isolation-${sessionSuffix}`,+ model: 'gpt-5.4',+ workingDir: '/repo',+ });+ const events: AgentEvent[] = [];+ void (async () => {+ for await (const event of handle.events()) events.push(event);+ })();+ const handlers = host.getThreadHandlers();+ if (+ !handlers?.turnStarted+ || !handlers.turnCompleted+ || !handlers.turnDiffUpdated+ || !handlers.descendantThreadStarted+ || !handlers.descendantNotification+ ) {+ throw new Error('expected turn and descendant handlers');+ }++ await handle.send({ type: 'user', content: 'first turn' });+ handlers.turnStarted({+ threadId: 'start-thread-id',+ turn: { id: 'turn-previous-diff' },+ });+ handlers.descendantThreadStarted({+ thread: { id: 'child-previous-diff', parentThreadId: 'start-thread-id' },+ });+ handlers.descendantNotification('child-previous-diff', 'turn/diff/updated', {+ threadId: 'child-previous-diff',+ turnId: 'child-previous-turn',+ diff: 'diff --git a/previous-child.txt b/previous-child.txt\n--- a/previous-child.txt\n+++ b/previous-child.txt\n@@ -1 +1 @@\n-old\n+previous-child\n',+ });+ handlers.turnCompleted({+ threadId: 'start-thread-id',+ turn: { id: 'turn-previous-diff', status: 'completed' },+ });++ const sendPromise = handle.send({ type: 'user', content: 'second turn' });+ await waitForExpectation(() => expect(turnStartCount).toBe(2));+ const applyStep = async (step: (typeof steps)[number]) => {+ if (step.kind === 'response') {+ currentTurnResponse.resolve({ turn: { id: 'turn-current-diff' } });+ await sendPromise;+ } else {+ handlers.turnStarted({+ threadId: 'start-thread-id',+ turn: { id: 'turn-current-diff' },+ });+ }+ };++ await applyStep(steps[0]);+ handlers.turnDiffUpdated({+ threadId: 'start-thread-id',+ turnId: 'turn-current-diff',+ diff: 'diff --git a/current-root.txt b/current-root.txt\n--- a/current-root.txt\n+++ b/current-root.txt\n@@ -1 +1 @@\n-old\n+current-root\n',+ });+ for (const step of steps.slice(1)) {+ await applyStep(step);+ }+ handlers.descendantThreadStarted({+ thread: { id: 'child-current-diff', parentThreadId: 'start-thread-id' },+ });+ handlers.descendantNotification('child-current-diff', 'turn/diff/updated', {+ threadId: 'child-current-diff',+ turnId: 'child-current-turn',+ diff: 'diff --git a/current-child.txt b/current-child.txt\n--- a/current-child.txt\n+++ b/current-child.txt\n@@ -1 +1 @@\n-old\n+current-child\n',+ });++ await vi.waitFor(() => {+ const last = events.filter((event) => event.type === 'turn_diff').at(-1);+ const diff = (last?.data as { diff?: string } | undefined)?.diff ?? '';+ expect(last?.data).toMatchObject({ turnId: 'turn-current-diff' });+ expect(diff).toContain('+current-root');+ expect(diff).toContain('+current-child');+ expect(diff).not.toContain('+previous-child');+ });++ await handle.close();+ },+ );+it('ignores descendant diffs that arrive after the child turn is terminal', 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 b4f32346fb..e799a4d848 100644--- a/packages/maker-core/src/agents/codex/index.ts+++ b/packages/maker-core/src/agents/codex/index.ts@@ -3027,7 +3027,7 @@ export class CodexAgent extends BaseAgent {};let isTurnInFlight = false;/**- * 本 handle 上「起过多少个 turn」的单调计数器,每次 isTurnInFlight 被置活 +1。+ * 本 handle 上「起过多少个 turn」的单调计数器,每个新 turn 首次被置活时 +1。** 存在的唯一理由:延迟很久的善后动作(upstream-idle 看门狗那条要等两次 interrupt* ack、最长 20s)不能只看**当下**有没有 turn 在跑 —— 新 turn 完全可能在这段窗口里@@ -5994,6 +5994,34 @@ export class CodexAgent extends BaseAgent {reconnectStallRemainingMs = 0;reconnectStallSliceStartedAt = 0;}+ /**+ * Adopt a root turn exactly once, regardless of whether the turn/start RPC+ * response or turn/started notification arrives first.+ *+ * The response is the authoritative ownership boundary, while the+ * notification is the generation-timing boundary. Adoption clears stale+ * timing immediately without starting the new clock, and keeps the other+ * per-turn resets from running twice when both signals arrive.+ */+ function activateRootTurn(turnId: string): void {+ const isNewTurn = currentTurnId !== turnId;+ currentTurnId = turnId;+ isTurnInFlight = true;+ if (!isNewTurn) return;++ resetCodexGenerationTiming(translatorRt);+ turnDiffSnapshots.clear();+ proposedPlanText = null;+ translatorRt.lastAuthErrorKey = null;+ translatorRt.networkRetryNotice = null;+ turnRetryTracker.reset();+ turnStartGeneration += 1;+ if (reconnectStallTimer && reconnectStallTurnId === turnId) {+ reconnectStallTurnGeneration = turnStartGeneration;+ } else {+ clearReconnectStall();+ }+ }function clearReconnectStallCleanup(turnId?: string): void {if (turnId && reconnectStallCleanupTurnId !== turnId) return;reconnectStallCleanupTurnId = null;@@ -9333,17 +9361,7 @@ export class CodexAgent extends BaseAgent {startedOwner[1].capabilitySelectionText,);}- currentTurnId = params.turn.id;- if (!wasSameTurn) turnDiffSnapshots.clear();- isTurnInFlight = true;- turnStartGeneration += 1; // 见声明处:延迟善后靠它判断"期间起过新 turn"- if (!wasSameTurn) {- if (reconnectStallTimer && reconnectStallTurnId === params.turn.id) {- reconnectStallTurnGeneration = turnStartGeneration;- } else {- clearReconnectStall();- }- }+ activateRootTurn(params.turn.id);// turn 开始 → 球在上游,起 idle 表(后续任何事件都会重置它)。armUpstreamIdle();// turn/start 在飞期间权限被收紧 (turnStarted 通知可能先于 turn/start resp@@ -9353,23 +9371,11 @@ export class CodexAgent extends BaseAgent {void interruptTurnForPermissionTighten(params.turn.id);}if (!wasSameTurn) currentTurnPlanModeActive = pendingTurnStartPlanMode ?? planCycleActive;- // 新 turn 开始 → 丢弃上一 turn 未消费的 proposed plan (正常路径已在- // handleTurnCompleted 清空, 这里防御 stale)。same-turn 的晚到 started- // 不清 (codex R15 P1): buffered turn 的 item 事件可能先于它的 started- // 被重放 (interceptProposedPlanItem 已存 plan), 随后到达的同 id- // started 若无条件清空, plan 模式下刚重放的 proposed plan 永久丢失。- if (!wasSameTurn) proposedPlanText = null;terminalErroredTurnIds.delete(params.turn.id);- if (!wasSameTurn) beginCodexGenerationTurn(translatorRt, params.turn.id);- // Reset auth retry-loop dedupe key — 让下一个 turn 重新可以 emit 第一条- // auth error。详见 translator.translateErrorNotification dedupe 逻辑。- translatorRt.lastAuthErrorKey = null;- // 持续重试透出状态同理 (字段名沿旧称 networkRetryNotice, 实际已对任意- // 持续性 willRetry 错误透出, 不限 networkish — issue #677): 新 turn- // 重新计数, 可再透出一条。- translatorRt.networkRetryNotice = null;- // retry 升级计数同样按 turn 隔离 — 新 turn 从零计。- turnRetryTracker.reset();+ // Generation starts at the local receipt of turn/started, never at the+ // earlier RPC response. The helper is idempotent for duplicate started+ // notifications, including when the response already adopted this id.+ beginCodexGenerationTurn(translatorRt, params.turn.id);// 产出记账**不在这里清**: 它按 turn id 存(producedOutputTurnIds), 新 turn 天然// 从"零产出"起算, 同一 turn 的重复 / 迟到 started 也不会抹掉已记的账 —— 这两条// 以前靠 `if (!wasSameTurn)` 的时序守卫维持(review #844 codex P1), 现在是结构性的。@@ -10515,15 +10521,7 @@ export class CodexAgent extends BaseAgent {?? Date.now(),...(turnModel ? { model: turnModel } : {}),});- currentTurnId = resp.turn.id;- beginCodexGenerationTurn(translatorRt, resp.turn.id);- isTurnInFlight = true;- turnStartGeneration += 1; // 见声明处:延迟善后靠它判断"期间起过新 turn"- if (reconnectStallTimer && reconnectStallTurnId === resp.turn.id) {- reconnectStallTurnGeneration = turnStartGeneration;- } else {- clearReconnectStall();- }+ activateRootTurn(resp.turn.id);currentTurnPlanModeActive = turnStartsInPlanMode;pendingTurnStartPlanMode = null;startRolloutPlanFallback(resp.turn.id);