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): settle cancelled yield turns and latch failed follow-ups
Dashb4ddb9bbcbb1
diff --git a/docs/dev-rules/maker-core-and-agent-behavior.md b/docs/dev-rules/maker-core-and-agent-behavior.mdindex 35046e2f81..7bc33c3e88 100644--- a/docs/dev-rules/maker-core-and-agent-behavior.md+++ b/docs/dev-rules/maker-core-and-agent-behavior.md@@ -92,10 +92,13 @@ timeout 不得触发自动换窗或 replay。Codex 当前没有与 Claude `AutoCask_user/plan 内部续段必须等 yield 空闲后再 `turn/start`,不得并发;Stop/close 取消 yield 时,排队中的内部续段必须退出而不是被当成正常空闲继续发送。只有 cell 真正结算的成功空闲才能唤醒排队续段;lost-handle、重试耗尽、- 续段 `turn/start` 失败等产品失败必须以 cancelled 释放 waiter,不得在用户+ 续段 `turn/start` 失败等产品失败必须以 cancelled 释放 waiter,并闩住后续+ `waitForYieldContinuationIdle()`,同时收掉未完成的 ask_user/plan 卡,不得在用户已看到失败后再开 ask_user/plan turn。续段启动失败的产品终态只由续段层发送一次(`yield-continuation-start-failed`),`handle.send` 不得再发一组- 通用终态。+ 通用终态。continuation 的 `turn/start` 已被服务端接受后若本地 Stop,即使+ `turnStarted` 已激活、随后 `interrupted` 被墓碑吞掉,也必须发出一条未认领的+ cancelled `done`,避免 Session 仍握着 `currentTurnAttemptToken`。续段必须继承铸造 claim 时的 `turnPermissionPolicy`,不得把无人值守只读边界重置成普通 Auto。Claude wake continuation 与 Codex yield continuation 先分账,不抽公共模块。diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.tsindex 33488f5ac4..fa17890f6f 100644--- a/packages/maker-core/src/agents/codex/index.test.ts+++ b/packages/maker-core/src/agents/codex/index.test.ts@@ -18111,6 +18111,89 @@ describe('CodexAgent yield continuation', () => {expect(handle.getCurrentTurnId?.()).not.toBe('turn-2');const state = handle.beginTurnContinuationWait?.(claimedDone?.turnContinuationId);expect(state === 'cancelled' || state === null).toBe(true);+ expect(events.some((event) => (+ event.type === 'done'+ && event.turnContinuationId == null+ && (event.data as { cancelled?: boolean }).cancelled === true+ ))).toBe(true);+ await handle.close();+ });++ it('emits an unclaimed cancelled done when Stop races a pending continuation after turnStarted', async () => {+ const agent = new CodexAgent(createDeps());+ let turnStarts = 0;+ const continuationStart = deferred<{ turn: { id: string } }>();+ const host = installFakeHost(agent, (method) => {+ if (method === Method.TurnStart) {+ turnStarts += 1;+ if (turnStarts === 1) return { turn: { id: 'turn-1' } };+ return continuationStart.promise;+ }+ if (method === Method.TurnInterrupt) return {};+ return undefined;+ });+ const handle = await agent.startSession({+ sessionId: 'session-yield-cancel-after-started-pending-rpc',+ model: 'gpt-5.4',+ workingDir: '/repo',+ });+ const handlers = host.getThreadHandlers();+ if (!handlers?.itemCompleted || !handlers.turnCompleted || !handlers.turnStarted) {+ throw new Error('expected item, turn, and started handlers');+ }+ const events = await collectYieldEvents(handle);+ await handle.send({ type: 'user', content: 'run typecheck' });+ handlers.itemCompleted({+ threadId: 'start-thread-id',+ turnId: 'turn-1',+ item: {+ id: 'item-exec-cancel-after-started',+ type: 'commandExecution',+ command: 'pnpm --filter desktop run typecheck',+ status: 'completed',+ aggregatedOutput: 'Script running with cell ID 226',+ },+ });+ handlers.turnCompleted({+ threadId: 'start-thread-id',+ turn: { id: 'turn-1', status: 'completed' },+ });+ await waitForExpectation(() => {+ expect(events.some((event) => event.type === 'done' && event.turnContinuationId != null)).toBe(true);+ });+ await vi.waitFor(() => {+ expect(turnStarts).toBe(2);+ });+ handlers.turnStarted({+ threadId: 'start-thread-id',+ turn: { id: 'turn-2', status: 'inProgress' },+ });+ expect(handle.getCurrentTurnId?.()).toBe('turn-2');+ await handle.abort();+ await waitForExpectation(() => {+ expect(events.filter((event) => (+ event.type === 'done'+ && event.turnContinuationId == null+ && (event.data as { cancelled?: boolean }).cancelled === true+ ))).toHaveLength(1);+ });+ continuationStart.resolve({ turn: { id: 'turn-2' } });+ await waitForExpectation(() => {+ expect(host.request).toHaveBeenCalledWith(Method.TurnInterrupt, {+ threadId: 'start-thread-id',+ turnId: 'turn-2',+ });+ });+ handlers.turnCompleted({+ threadId: 'start-thread-id',+ turn: { id: 'turn-2', status: 'interrupted' },+ });+ expect(events.filter((event) => (+ event.type === 'done'+ && event.turnContinuationId == null+ && (event.data as { cancelled?: boolean }).cancelled === true+ ))).toHaveLength(1);+ expect(handle.isTurnRunning?.()).toBe(false);await handle.close();});@@ -18983,6 +19066,92 @@ describe('CodexAgent yield continuation', () => {expect(handle.isTurnRunning?.()).toBe(false);await handle.close();});++ it('does not start ask_user after lost-handle if the user answers later', async () => {+ const agent = new CodexAgent(createDeps());+ let turnSeq = 0;+ const host = installFakeHost(agent, (method) => {+ if (method === Method.TurnStart) {+ turnSeq += 1;+ return { turn: { id: `turn-${turnSeq}` } };+ }+ return undefined;+ });+ const handle = await agent.startSession({+ sessionId: 'session-yield-lost-handle-then-late-ask-user',+ model: 'gpt-5.4',+ workingDir: '/repo',+ });+ const handlers = host.getThreadHandlers();+ if (!handlers?.itemCompleted || !handlers.turnCompleted || !handlers.requestUserInput) {+ throw new Error('expected item, turn, and user-input handlers');+ }+ const ownerDecision = deferred<InteractionDecision>();+ handle.setInteractionResolver(async () => ownerDecision.promise);+ const events = await collectYieldEvents(handle);+ await handle.send({ type: 'user', content: 'run typecheck' });+ void handlers.requestUserInput({+ threadId: 'start-thread-id',+ turnId: 'turn-1',+ itemId: 'item-ask-late',+ questions: [{+ id: 'native-q1',+ header: 'Question',+ question: 'Pick one',+ isOther: false,+ isSecret: false,+ options: [{ label: 'A', description: null }],+ }],+ }, { requestId: 'req-ask-late' });+ handlers.itemCompleted({+ threadId: 'start-thread-id',+ turnId: 'turn-1',+ item: {+ id: 'item-exec-ask-late',+ type: 'commandExecution',+ command: 'pnpm --filter desktop run typecheck',+ status: 'completed',+ aggregatedOutput: 'Script running with cell ID 226',+ },+ });+ handlers.turnCompleted({+ threadId: 'start-thread-id',+ turn: { id: 'turn-1', status: 'completed' },+ });+ await vi.waitFor(() => {+ expect(yieldTurnStartCalls(host)).toHaveLength(1);+ });+ handlers.turnStarted?.({+ threadId: 'start-thread-id',+ turn: { id: 'turn-2', status: 'inProgress' },+ });+ handlers.turnCompleted({+ threadId: 'start-thread-id',+ turn: { id: 'turn-2', status: 'completed' },+ });+ await waitForExpectation(() => {+ expect(events.some((event) => (+ event.type === 'error'+ && String((event.data as { reason?: string }).reason ?? '') === 'yield-continuation-lost-handle'+ ))).toBe(true);+ });+ expect(events.some((event) => (+ event.type === 'interaction_dismissed'+ && (event.data as { requestId?: string }).requestId === 'req-ask-late'+ ))).toBe(true);+ ownerDecision.resolve({+ kind: 'ask_user_question',+ answers: { 'Pick one': 'A' },+ });+ await new Promise((resolve) => setTimeout(resolve, 20));+ expect(host.request.mock.calls.filter(([method]) => method === Method.TurnStart)).toHaveLength(2);+ expect(events.some((event) => (+ event.type === 'error'+ && String((event.data as { message?: string }).message ?? '').includes('ask_user continuation turn failed to start')+ ))).toBe(false);+ expect(handle.isTurnRunning?.()).toBe(false);+ await handle.close();+ });});describe('CodexAgent steer', () => {diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.tsindex 63f1875033..dcb2c645bb 100644--- a/packages/maker-core/src/agents/codex/index.ts+++ b/packages/maker-core/src/agents/codex/index.ts@@ -3137,6 +3137,7 @@ export class CodexAgent extends BaseAgent {let yieldContinuationInFlight = false;let yieldContinuationAbort: AbortController | null = null;let yieldContinuationIdleWaiters: Array<(cancelled: boolean) => void> = [];+ let yieldContinuationProductFailed = false;const emitYieldContinuationState = (continuationId: number,state: 'awaiting' | 'active' | 'cancelled',@@ -3259,6 +3260,7 @@ export class CodexAgent extends BaseAgent {};yieldContinuationClaims.set(claim.id, claim);activeYieldContinuationId = claim.id;+ yieldContinuationProductFailed = false;log.info('yield continuation claim created', {continuationId: claim.id,originTurnId,@@ -3283,11 +3285,27 @@ export class CodexAgent extends BaseAgent {for (const resolve of waiters) resolve(cancelled);};const waitForYieldContinuationIdle = async (): Promise<boolean> => {+ if (yieldContinuationProductFailed) return true;if (activeYieldContinuationClaim() == null && !yieldContinuationInFlight) return false;return await new Promise<boolean>((resolve) => {yieldContinuationIdleWaiters.push(resolve);});};+ const emitCancelledYieldProductDone = (): void => {+ eventQueue.push({+ type: 'done',+ data: {+ type: 'codex/event/task_complete',+ cancelled: true,+ },+ source: 'codex',+ });+ eventQueue.push({+ type: 'status',+ data: { status: 'Done', ...usageTracker.snapshot(), isRunning: false },+ source: 'codex',+ });+ };const cancelActiveYieldContinuation = (reason: string): YieldContinuationClaim | null => {const claim = activeYieldContinuationClaim();abortYieldContinuationSend();@@ -3357,9 +3375,15 @@ export class CodexAgent extends BaseAgent {data: { status: 'Done', ...usageTracker.snapshot(), isRunning: false },source: 'codex',});- // Failure is a product terminal. Queued ask_user / plan waiters must exit- // rather than treat this as idle success and start another turn.+ // Failure is a product terminal. Latch so later ask_user / plan answers+ // cannot treat idle as permission to start another turn, and dismiss+ // unfinished cards from the failed product turn.+ yieldContinuationProductFailed = true;flushYieldContinuationIdleWaiters(true);+ planCycleActive = false;+ proposedPlanText = null;+ dismissAllPending(opts.reason, 'deny');+ dismissAllPendingUserInput(opts.reason);};const emitYieldContinuationStartFailure = (error: unknown, cells: YieldedExecCell[]): void => {emitYieldContinuationFailure({@@ -10948,6 +10972,7 @@ export class CodexAgent extends BaseAgent {const yieldAttempt = internalOpts?.[CODEX_YIELD_CONTINUATION];if (yieldAttempt == null && internalOpts?.[CODEX_INTERNAL_CONTINUATION] !== true) {cancelActiveYieldContinuation('new send');+ yieldContinuationProductFailed = false;}// 用户开启新 turn = 旧重连序列作废;deadline 不得跨 turn 误伤新请求。clearReconnectStall();@@ -11930,20 +11955,12 @@ export class CodexAgent extends BaseAgent {async abort() {const cancelledYield = cancelActiveYieldContinuation('aborted');- if (cancelledYield && !currentTurnId) {- eventQueue.push({- type: 'done',- data: {- type: 'codex/event/task_complete',- cancelled: true,- },- source: 'codex',- });- eventQueue.push({- type: 'status',- data: { status: 'Done', ...usageTracker.snapshot(), isRunning: false },- source: 'codex',- });+ // isolateCancelledTurnStart tombstones the accepted turn and swallows+ // interrupted turn/completed. Emit the unclaimed cancelled done here so+ // Session releases currentTurnAttemptToken even if turnStarted already+ // activated the continuation and the RPC is still pending.+ if (cancelledYield) {+ emitCancelledYieldProductDone();}clearReconnectStall();// 用户点 Stop = 明确不想继续这一轮,挂起的过载重投必须一起撤掉。