Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(interaction): 修复确认请求串线、提交丢失与提前完成 (#4365)
Dashd432f6808fbf
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.tsindex 7717c1148e..c475a11c95 100644--- a/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts+++ b/apps/desktop/src/main/maker-ipc/__tests__/sessionEventPipeline.test.ts@@ -427,13 +427,14 @@ describe('production Session event pipeline', () => {await h.dispose();});- it('keeps continuation segments running, then seals the final product boundary', async () => {+ it.each(['claude-code', 'codex'] as const)('keeps %s continuation segments running, then seals the final product boundary', async (source) => {const h = harness();+ Object.defineProperty(h.session, 'agentKind', { value: source });vi.setSystemTime(1000);- h.emit(event('status', { isRunning: true }, { source: 'claude-code' }));+ h.emit(event('status', { isRunning: true }, { source }));effects.fn('consumeLastAssistantPersistId').mockReturnValueOnce('segment-row');vi.setSystemTime(3000);- h.emit(event('done', {}, { source: 'claude-code', turnContinuationId: 0 }));+ h.emit(event('done', {}, { source, turnContinuationId: 0 }));expect(h.activity.isSessionInTurn('task')).toBe(true);expect(h.deps.notifyGoalIdleAfterTurnSettled).not.toHaveBeenCalled();expect(effects.fn('turn-drain')).not.toHaveBeenCalled();@@ -444,15 +445,20 @@ describe('production Session event pipeline', () => {expect(h.deps.orcaTeamServiceForEvents.handleWorkerTerminalTurn).not.toHaveBeenCalled();effects.fn('recordTurnUsageOnMessage').mockClear();vi.setSystemTime(5000);- h.emit(event('done', { total_cost_usd: 0, duration_ms: 20 }, { source: 'claude-code' }));+ h.emit(event('done', { total_cost_usd: 0, duration_ms: 20 }, { source }));expect(h.activity.isSessionInTurn('task')).toBe(false);expect(h.deps.notifyGoalIdleAfterTurnSettled).toHaveBeenCalledOnce();await microtasks();- expect(effects.fn('recordTurnUsageOnMessage')).toHaveBeenCalledWith({- sessionId: 'task',- clientId: 'segment-row',- turnUsageDetails: expect.objectContaining({ turnDurationMs: 4000 }),- });+ if (source === 'claude-code') {+ expect(effects.fn('recordTurnUsageOnMessage')).toHaveBeenCalledWith({+ sessionId: 'task',+ clientId: 'segment-row',+ turnUsageDetails: expect.objectContaining({ turnDurationMs: 4000 }),+ });+ } else {+ // A synthetic Codex terminal carries no second copy of SDK usage.+ expect(effects.fn('recordTurnUsageOnMessage')).not.toHaveBeenCalled();+ }await h.dispose();});diff --git a/apps/desktop/src/renderer/__tests__/askUserDoneRace.test.ts b/apps/desktop/src/renderer/__tests__/askUserDoneRace.test.tsindex 6e259f5538..e35ffb947f 100644--- a/apps/desktop/src/renderer/__tests__/askUserDoneRace.test.ts+++ b/apps/desktop/src/renderer/__tests__/askUserDoneRace.test.ts@@ -5,6 +5,8 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';+vi.mock('@/lib/toast', () => ({ toast: { warning: vi.fn() } }));+vi.mock('@/lib/messageService', () => ({list: vi.fn(async () => []),create: vi.fn(async () => ({}) as unknown),@@ -193,6 +195,23 @@ describe('ask_user 与 done 的时序', () => {expect(pendingAskStatuses()).toEqual(['pending']);});+ it('Codex SDK completion does not finish the product while confirmation remains', async () => {+ makerChatStore.setSessionRuntime(SESSION_ID, { agentKind: 'codex' });+ onEvent?.({ sessionId: SESSION_ID, event: { type: 'status', source: 'codex', data: { isRunning: true } } });+ emitAskUserRequest('human-1');+ for (const type of ['status', 'done'] as const) {+ onEvent?.({ sessionId: SESSION_ID, event: { type, source: 'codex', turnContinuationId: 17,+ data: { status: 'Done', isRunning: false } } });+ }+ expect(makerChatStore.getSnapshot(SESSION_ID).agentStatus.isRunning).toBe(true);+ expect(makerChatStore.getSnapshot(SESSION_ID).pendingAskUser?.requestId).toBe('human-1');+ makerChatStore.answerUserQuestion(SESSION_ID, 'human-1', { 'Proceed?': 'Yes' });+ await vi.waitFor(() => expect(makerChatStore.getSnapshot(SESSION_ID).pendingAskUser).toBeNull());+ expect(makerChatStore.getSnapshot(SESSION_ID).agentStatus.isRunning).toBe(true);+ emitDone('codex');+ expect(makerChatStore.getSnapshot(SESSION_ID).agentStatus.isRunning).toBe(false);+ });+it('codex:done 的 Host 快照重放保留答题状态及 questions 引用', async () => {makerChatStore.setSessionRuntime(SESSION_ID, { agentKind: 'codex' });emitAskUserRequest('ask-replay', [{@@ -304,7 +323,7 @@ describe('ask_user 与 done 的时序', () => {});});- it('codex:输家乐观答案会被赢家 dismissal 覆盖', () => {+ it('codex:晚到的成功回执不覆盖赢家 dismissal', async () => {makerChatStore.setSessionRuntime(SESSION_ID, { agentKind: 'codex' });emitAskUserRequest('ask-5');emitDone('codex');@@ -313,8 +332,7 @@ describe('ask_user 与 done 的时序', () => {});expect(makerChatStore.getSnapshot(SESSION_ID).messages.find((m) => m.role === 'ask_user')).toMatchObject({- askUserStatus: 'answered',- askUserAnswers: { '桌面版这次要采用哪种范围?': '只展示和搜索' },+ askUserStatus: 'pending',});onInteractionDismissed?.({@@ -328,10 +346,92 @@ describe('ask_user 与 done 的时序', () => {},});+ await new Promise((resolve) => setTimeout(resolve, 0));expect(makerChatStore.getSnapshot(SESSION_ID).messages.find((m) => m.role === 'ask_user')).toMatchObject({askUserStatus: 'answered',askUserAnswers: { '桌面版这次要采用哪种范围?': '完整编辑(推荐)' },});});+ it.each(['ask', 'approve', 'revise', 'cancel'] as const)('%s keeps the card until accepted and allows retry after rejection', async (action) => {+ makerChatStore.setSessionRuntime(SESSION_ID, { agentKind: 'codex' });+ if (action === 'ask') emitAskUserRequest('receipt');+ else onInteractionRequest?.({ sessionId: SESSION_ID, request: {+ kind: 'plan_review', requestId: 'receipt', plan: '# Keep this edited plan',+ }, persistId: 'receipt-message' });+ emitDone('codex');+ const original = action === 'ask' ? makerChatStore.getSnapshot(SESSION_ID).pendingAskUser+ : makerChatStore.getSnapshot(SESSION_ID).pendingPlanReview;+ const resolveInteraction = vi.mocked(window.electronAPI.maker.resolveInteraction);+ let resolve!: (receipt: { accepted: boolean }) => void;+ resolveInteraction.mockImplementationOnce(() => new Promise((done) => { resolve = done; }));+ const submit = () => {+ if (action === 'ask') makerChatStore.answerUserQuestion(SESSION_ID, 'receipt', { 'Choose?': 'A' });+ else if (action === 'cancel') makerChatStore.cancelPlanReview(SESSION_ID, 'receipt');+ else makerChatStore.respondToPlanReview(SESSION_ID, 'receipt', action === 'approve', 'Keep my feedback');+ };+ const pending = () => action === 'ask' ? makerChatStore.getSnapshot(SESSION_ID).pendingAskUser+ : makerChatStore.getSnapshot(SESSION_ID).pendingPlanReview;+ submit(); submit();+ expect(resolveInteraction).toHaveBeenCalledTimes(1);+ expect(pending()).toBe(original);+ resolve({ accepted: false });+ await new Promise((done) => setTimeout(done, 0));+ expect(pending()).toBe(original);+ expect(updateMessageContent).not.toHaveBeenCalled();+ submit();+ await vi.waitFor(() => expect(pending()).toBeNull());+ expect(resolveInteraction).toHaveBeenCalledTimes(2);+ expect(updateMessageContent).not.toHaveBeenCalled();+ });++ it.each(['reject', 'missing', 'timeout'] as const)('retains an unanswered card after a %s receipt and can retry', async (failure) => {+ makerChatStore.setSessionRuntime(SESSION_ID, { agentKind: 'codex' });+ emitAskUserRequest('failed-receipt');+ const resolveInteraction = vi.mocked(window.electronAPI.maker.resolveInteraction);+ if (failure === 'reject') resolveInteraction.mockRejectedValueOnce(new Error('offline'));+ if (failure === 'missing') resolveInteraction.mockResolvedValueOnce(undefined as never);+ if (failure === 'timeout') {+ vi.useFakeTimers();+ resolveInteraction.mockImplementationOnce(() => new Promise(() => {}));+ }+ try {+ makerChatStore.answerUserQuestion(SESSION_ID, 'failed-receipt', { 'Choose?': 'A' });+ if (failure === 'timeout') await vi.advanceTimersByTimeAsync(15_001);+ else await new Promise((done) => setTimeout(done, 0));+ expect(makerChatStore.getSnapshot(SESSION_ID).pendingAskUser?.requestId).toBe('failed-receipt');+ expect(pendingAskStatuses()).toEqual(['pending']);+ } finally { vi.useRealTimers(); }+ makerChatStore.answerUserQuestion(SESSION_ID, 'failed-receipt', { 'Choose?': 'A' });+ await vi.waitFor(() => expect(pendingAskStatuses()).toEqual(['answered']));+ });++ it('ignores a late receipt after the task was purged', async () => {+ emitAskUserRequest('old');+ let resolve!: (receipt: { accepted: boolean }) => void;+ vi.mocked(window.electronAPI.maker.resolveInteraction).mockImplementationOnce(() => new Promise((done) => { resolve = done; }));+ makerChatStore.answerUserQuestion(SESSION_ID, 'old', { 'Choose?': 'A' });+ makerChatStore.purgeSession(SESSION_ID);+ emitAskUserRequest('new');+ resolve({ accepted: true });+ await new Promise((done) => setTimeout(done, 0));+ expect(makerChatStore.getSnapshot(SESSION_ID).pendingAskUser?.requestId).toBe('new');+ expect(pendingAskStatuses()).toEqual(['pending']);+ });++ it('restores a detached question after renderer reload and accepts its answer', async () => {+ const request = { kind: 'ask_user_question', requestId: 'codex:connection:0',+ questions: [{ question: 'Choose?' }] };+ makerChatStore.setSessionRuntime(SESSION_ID, { agentKind: 'codex' });+ emitAskUserRequest(request.requestId, request.questions);+ emitDone('codex');+ makerChatStore.purgeSession(SESSION_ID);+ getPendingInteractions.mockResolvedValue([{ request, persistId: 'persist-reloaded' }]);+ await makerChatStore.reconcilePendingInteractions(SESSION_ID);+ expect(makerChatStore.getSnapshot(SESSION_ID).pendingAskUser?.requestId).toBe(request.requestId);+ makerChatStore.answerUserQuestion(SESSION_ID, request.requestId, { 'Choose?': 'A' });+ await vi.waitFor(() => expect(pendingAskStatuses()).toEqual(['answered']));+ expect(makerChatStore.getSnapshot(SESSION_ID).pendingAskUser).toBeNull();+ });+});diff --git a/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts b/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.tsindex 6957edf9c2..7f18fb6743 100644--- a/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts+++ b/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts@@ -1369,15 +1369,13 @@ describe('远程交互接线不变式', () => {// 状态变更未广播收敛」家族残留,锁住防回归 ──────────────────────────────────────────const mainSrc = (rel: string) => readFileSync(resolve(__dirname, '../../main', rel), 'utf8');- it('F1: ask 本地远程都只由 main 落库;plan answered 写库仍远程跳过', () => {+ it.each(['answerUserQuestion', 'respondToPlanReview', 'cancelPlanReview', 'submitPlanReviewDecision'])(+ 'F1: %s 本地远程都只由 main 落库,避免迟到提交覆盖权威决定', (name) => {const src = read('lib/makerChatStore.ts');- const askStart = src.indexOf('function answerUserQuestion(');- expect(askStart).toBeGreaterThan(-1);- const askEnd = src.indexOf('\nfunction ', askStart + 1);- const askBody = src.slice(askStart, askEnd === -1 ? undefined : askEnd);- expect(askBody).not.toContain('askMsg');- expect(askBody).not.toContain('messageService');- expect(src).toContain('if (planMsg && !isRemoteSession(sessionId))');+ const start = src.indexOf(`function ${name}(`);+ expect(start).toBeGreaterThan(-1);+ const end = src.indexOf('\nfunction ', start + 1);+ expect(src.slice(start, end === -1 ? undefined : end)).not.toContain('messageService');});it('F2: fork IPC handler 广播 sessions:created(否则 fork 会话在被控端/其它控制端不出现)', () => {diff --git a/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts b/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.tsindex 8ce88be9be..0933beb027 100644--- a/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts+++ b/apps/desktop/src/renderer/__tests__/makerChatStoreTextDeltaBatching.test.ts@@ -298,7 +298,7 @@ function installElectronBridge(): void {return vi.fn();},send: vi.fn(async () => ({ accepted: true })),- resolveInteraction: vi.fn(async () => {}),+ resolveInteraction: vi.fn(async () => ({ accepted: true })),submitPluginSetupInline: vi.fn(async () => {}),getPendingInteractions,steer: vi.fn(async () => true),@@ -6635,7 +6635,7 @@ describe('makerChatStore text delta batching', () => {);});- it('preserves terminal interaction state on late initial DB-created echoes', () => {+ it('preserves terminal interaction state on late initial DB-created echoes', async () => {emitInteractionRequest({kind: 'ask_user_question',@@ -6656,6 +6656,7 @@ describe('makerChatStore text delta batching', () => {makerChatStore.answerUserQuestion(SESSION_ID, 'ask-terminal', { 'Continue?': 'Yes' });makerChatStore.respondToPlanReview(SESSION_ID, 'plan-terminal', false, 'Needs more detail');+ await flushPromises();expect(makerChatStore.getSnapshot(SESSION_ID).messages).toEqual(expect.arrayContaining([diff --git a/apps/desktop/src/renderer/__tests__/planReviewDoneRace.test.ts b/apps/desktop/src/renderer/__tests__/planReviewDoneRace.test.tsindex 3497558963..cb4b8483c3 100644--- a/apps/desktop/src/renderer/__tests__/planReviewDoneRace.test.ts+++ b/apps/desktop/src/renderer/__tests__/planReviewDoneRace.test.ts@@ -126,7 +126,7 @@ function installElectronBridge(): void {generateTitle: vi.fn(async () => ({ title: 't' })),getPendingInteractions,setPlanMode: vi.fn(async () => {}),- resolveInteraction: vi.fn(async () => {}),+ resolveInteraction: vi.fn(async () => ({ accepted: true })),abortSession: vi.fn(async () => {}),closeSession: vi.fn(async () => {}),listActive: vi.fn(async () => []),@@ -570,13 +570,14 @@ describe('cancelPlanReview(取消本次审阅)', () => {makerChatStore.purgeSession(SESSION_ID);});- it('关卡片、气泡标 cancelled, 决策发 deny + dismissed', () => {+ it('关卡片、气泡标 cancelled, 决策发 deny + dismissed', async () => {makerChatStore.setSessionRuntime(SESSION_ID, { agentKind: 'codex' });emitPlanReviewRequest('pr-cancel');emitDone('codex');expect(makerChatStore.getSnapshot(SESSION_ID).pendingPlanReview?.requestId).toBe('pr-cancel');makerChatStore.cancelPlanReview(SESSION_ID, 'pr-cancel');+ await new Promise((resolve) => setTimeout(resolve, 0));const snap = makerChatStore.getSnapshot(SESSION_ID);expect(snap.pendingPlanReview).toBeNull();diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.tsindex dc311b87f4..a9ba50c245 100644--- a/apps/desktop/src/renderer/lib/makerChatStore.ts+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts@@ -15125,50 +15125,80 @@ function updateSystemCardData(}}-/**- * F7.4/F7.5: Send all user answers for ask-user-question to the main process.- * Updates the corresponding ask_user message to 'answered' state.- */+// Only an accepted Host receipt may commit a question/plan decision. A rejected+// or lost receipt leaves the existing card and its draft available for retry.+const questionDecisionsInFlight = new Set<string>();++function submitQuestionDecision(+ sessionId: string,+ requestId: string,+ decision: Record<string, unknown>,+ onAccepted: () => void,+): void {+ const key = JSON.stringify([sessionId, requestId]);+ if (questionDecisionsInFlight.has(key)) return;+ questionDecisionsInFlight.add(key);+ const owner = getDataOwnerGeneration();+ const epoch = _messagesEpoch.get(sessionId) ?? 0;+ const authority = _inputProjectionAuthorityEpoch.get(sessionId) ?? 0;+ const origin = remoteProjectsStore.getSessionDeviceId(sessionId);+ const isCurrent = () => isDataOwnerGenerationCurrent(owner) &&+ (_messagesEpoch.get(sessionId) ?? 0) === epoch &&+ (_inputProjectionAuthorityEpoch.get(sessionId) ?? 0) === authority &&+ remoteProjectsStore.getSessionDeviceId(sessionId) === origin;+ bumpInteractionReconcileEpoch(sessionId);+ void (async () => {+ let timer: ReturnType<typeof setTimeout> | undefined;+ try {+ const receipt = await Promise.race([+ makerApiFor(sessionId).resolveInteraction(requestId, decision),+ new Promise<never>((_, reject) => {+ timer = setTimeout(() => reject(new Error('Interaction receipt timeout')), 15_000);+ }),+ ]);+ if (!isCurrent()) return;+ if (receipt?.accepted !== true) throw new Error('Interaction decision was not accepted');+ bumpInteractionReconcileEpoch(sessionId);+ onAccepted();+ } catch (error) {+ if (!isCurrent()) return;+ const state = sessions.get(sessionId);+ // A winning dismissal from another window/Stop remains authoritative.+ if (state?.pendingAskUser?.requestId !== requestId &&+ state?.pendingPlanReview?.requestId !== requestId) return;+ log.warn('Question decision receipt unavailable', error);+ toast.warning(i18n.t('newChat.permissionPrompt.submissionFailed'));+ } finally {+ if (timer) clearTimeout(timer);+ questionDecisionsInFlight.delete(key);+ }+ })();+}+function answerUserQuestion(sessionId: string,requestId: string,answers: Record<string, string>,): void {if (!sessionId) return;- const state = getOrCreateState(sessionId);- if (!state.pendingAskUser) return;- if (state.pendingAskUser.requestId !== requestId) return;- bumpInteractionReconcileEpoch(sessionId);-- // Build a human-readable reply summary- const replySummary = formatAskUserReply(answers);-- // Update message to answered + clear pendingAskUser- setState(sessionId, (s) => ({+ if (getOrCreateState(sessionId).pendingAskUser?.requestId !== requestId) return;+ const submittedAnswers = { ...answers };+ const replySummary = formatAskUserReply(submittedAnswers);+ submitQuestionDecision(sessionId, requestId, {+ kind: 'ask_user_question', answers: submittedAnswers,+ }, () => setState(sessionId, (s) => ({...s,- pendingAskUser: null,- // F-AUQ-MIN-5: question resolved — reset viewer for the next one.- askUserViewerState: 'expanded',- // F-AUQ-DRAFT: question resolved — drop the draft so a future question- // (potentially with the same questions[] payload) starts at step 1.- askUserDraft: null,+ pendingAskUser: s.pendingAskUser?.requestId === requestId ? null : s.pendingAskUser,+ askUserViewerState: s.pendingAskUser?.requestId === requestId ? 'expanded' : s.askUserViewerState,+ askUserDraft: s.pendingAskUser?.requestId === requestId ? null : s.askUserDraft,messages: s.messages.map((m) =>m.askUserRequestId === requestId && m.askUserStatus === 'pending'- ? {- ...m,- askUserStatus: 'answered' as const,- askUserReply: replySummary,- askUserAnswers: answers,- }+ ? { ...m, askUserStatus: 'answered' as const, askUserReply: replySummary, askUserAnswers: submittedAnswers }: m,),- }));-- // 落库只走 main 的 onInteractionResolved。renderer 先写会让多窗口输家/- // Stop-vs-answer 的迟到 updateContent 覆盖赢家或 cancelled。- makerApiFor(sessionId)- .resolveInteraction(requestId, { kind: 'ask_user_question', answers })- .catch((err) => log.error('Failed to answer user question:', err));+ })));+ // Persistence belongs exclusively to Main's onInteractionResolved, including+ // local sessions. A late renderer write must not overwrite a winning decision.}function respondToPluginSetup(@@ -15495,122 +15525,43 @@ function respondToPlanReview(feedback?: string,): void {if (!sessionId) return;- const state = getOrCreateState(sessionId);- if (!state.pendingPlanReview) return;- if (state.pendingPlanReview.requestId !== requestId) return;-- const nextStatus = approved ? 'approved' : 'revised';- const trimmedFeedback = feedback?.trim() ?? '';- bumpInteractionReconcileEpoch(sessionId);-- // Find the clientId for persistence update- const planMsg = state.messages.find(- (m) =>- m.role === 'plan_review' &&- m.planReviewRequestId === requestId &&- m.planReviewStatus === 'pending',- );-- setState(sessionId, (s) => ({- ...s,- pendingPlanReview: null,- // Reset viewer state so the next review starts fresh- planViewerState: 'expanded',- lastExpandedPlanViewerState: 'expanded',- messages: s.messages.map((m) =>- m.role === 'plan_review' &&- m.planReviewRequestId === requestId &&- m.planReviewStatus === 'pending'- ? {- ...m,- planReviewStatus: nextStatus as 'approved' | 'revised',- planReviewFeedback: approved ? undefined : trimmedFeedback || undefined,- }- : m,- ),- }));-- // Persist answered state via PATCH API。远程会话由被控端权威落库(见 answerUserQuestion 注释),- // 控制端跳过避免 dead write;本机会话保持原样。- if (planMsg && !isRemoteSession(sessionId)) {- messageService- .updateContent(sessionId, planMsg.clientId, {- requestId,- plan: planMsg.planReviewPlan ?? '',- planFilePath: planMsg.planReviewFilePath ?? '',- status: nextStatus,- feedback: approved ? null : trimmedFeedback || null,- })- .catch((err) => log.error('Failed to persist plan_review state:', err));- }-- // Send to maker (InteractionDecision kind: 'plan_review')- // approved → behavior='allow' + editedPlan = current pending.plan (用户改过的版本)- // 拒绝 → behavior='deny' + reason=feedback (模型读到 feedback 知道为什么被拒)- makerApiFor(sessionId)- .resolveInteraction(requestId, {- kind: 'plan_review',- behavior: approved ? 'allow' : 'deny',- editedPlan: approved ? state.pendingPlanReview.plan : undefined,- reason: approved ? undefined : trimmedFeedback || undefined,- })- .catch((err) => log.error('Failed to respond to plan review:', err));+ const pending = getOrCreateState(sessionId).pendingPlanReview;+ if (pending?.requestId !== requestId) return;+ const trimmedFeedback = feedback?.trim() || undefined;+ submitPlanReviewDecision(sessionId, requestId, {+ kind: 'plan_review',+ behavior: approved ? 'allow' : 'deny',+ editedPlan: approved ? pending.plan : undefined,+ reason: approved ? undefined : trimmedFeedback,+ }, approved ? 'approved' : 'revised', approved ? undefined : trimmedFeedback);}-/**- * 取消本次计划审阅(issue #475):与批准/反馈并列的第三条出路。- * 关闭卡片、气泡标 cancelled;决策发 deny + dismissed 标记 ——- * - Codex: 结束本轮计划循环,不发修订 turn(dismissed 语义,见 maker-core;下一条消息回常规模式);- * - Claude: ExitPlanMode 以默认理由被拒,模型收到后收尾等待,计划模式不变。- * 持久化与 respondToPlanReview 同款(远程会话由被控端权威落库,本机 PATCH)。- */function cancelPlanReview(sessionId: string, requestId: string): void {if (!sessionId) return;- const state = getOrCreateState(sessionId);- if (!state.pendingPlanReview) return;- if (state.pendingPlanReview.requestId !== requestId) return;- bumpInteractionReconcileEpoch(sessionId);-- const planMsg = state.messages.find(- (m) =>- m.role === 'plan_review' &&- m.planReviewRequestId === requestId &&- m.planReviewStatus === 'pending',- );+ if (getOrCreateState(sessionId).pendingPlanReview?.requestId !== requestId) return;+ submitPlanReviewDecision(sessionId, requestId, {+ kind: 'plan_review', behavior: 'deny', dismissed: true,+ }, 'cancelled');+}- setState(sessionId, (s) => ({+function submitPlanReviewDecision(+ sessionId: string,+ requestId: string,+ decision: Record<string, unknown>,+ status: 'approved' | 'revised' | 'cancelled',+ feedback?: string,+): void {+ submitQuestionDecision(sessionId, requestId, decision, () => setState(sessionId, (s) => ({...s,- pendingPlanReview: null,- planViewerState: 'expanded',- lastExpandedPlanViewerState: 'expanded',+ pendingPlanReview: s.pendingPlanReview?.requestId === requestId ? null : s.pendingPlanReview,+ planViewerState: s.pendingPlanReview?.requestId === requestId ? 'expanded' : s.planViewerState,+ lastExpandedPlanViewerState: s.pendingPlanReview?.requestId === requestId ? 'expanded' : s.lastExpandedPlanViewerState,messages: s.messages.map((m) =>- m.role === 'plan_review' &&- m.planReviewRequestId === requestId &&- m.planReviewStatus === 'pending'- ? { ...m, planReviewStatus: 'cancelled' as const, planReviewFeedback: undefined }+ m.role === 'plan_review' && m.planReviewRequestId === requestId && m.planReviewStatus === 'pending'+ ? { ...m, planReviewStatus: status, planReviewFeedback: feedback }: m,),- }));-- if (planMsg && !isRemoteSession(sessionId)) {- messageService- .updateContent(sessionId, planMsg.clientId, {- requestId,- plan: planMsg.planReviewPlan ?? '',- planFilePath: planMsg.planReviewFilePath ?? '',- status: 'cancelled',- feedback: null,- })- .catch((err) => log.error('Failed to persist cancelled plan_review state:', err));- }-- makerApiFor(sessionId)- .resolveInteraction(requestId, {- kind: 'plan_review',- behavior: 'deny',- dismissed: true,- })- .catch((err) => log.error('Failed to cancel plan review:', err));+ })));}/**diff --git a/apps/mobile/src/__tests__/InteractionPanelReceipt.test.tsx b/apps/mobile/src/__tests__/InteractionPanelReceipt.test.tsxnew file mode 100644index 0000000000..e4b89b0e29--- /dev/null+++ b/apps/mobile/src/__tests__/InteractionPanelReceipt.test.tsx@@ -0,0 +1,89 @@+// @vitest-environment jsdom+import { act, type ReactNode } from 'react';+import { createRoot, type Root } from 'react-dom/client';+import { afterEach, beforeEach, expect, it, vi } from 'vitest';+import { InteractionPanel } from '@/session/InteractionPanel';+import { remoteSessionStore, useSessionPendingInteractions } from '@/session/remoteSessionStore';+import { clearAllInteractionDrafts, readAskUserDraft } from '@/session/interactionDraftStore';++const { resolveInteraction } = vi.hoisted(() => ({ resolveInteraction: vi.fn() }));+vi.mock('@/device-link/useMobileMakerTransport', () => ({+ useMobileMakerTransport: () => ({ resolveInteraction }),+}));+vi.mock('react-native', async () => {+ const { createElement } = await import('react');+ const view = (tag: string) => ({ children, onPress, disabled, testID }: {+ children?: ReactNode; onPress?: () => void; disabled?: boolean; testID?: string;+ }) => createElement(tag, { onClick: onPress, disabled, 'data-testid': testID }, children);+ return { View: view('div'), Text: view('span'), Pressable: view('button'),+ ScrollView: view('div'), Image: () => null,+ useWindowDimensions: () => ({ width: 390, height: 844 }),+ StyleSheet: { create: (s: unknown) => s, hairlineWidth: 1 } };+});+vi.mock('@/components/AppText', async () => {+ const { createElement } = await import('react');+ return { Text: (await import('react-native')).Text,+ TextInput: ({ value, onChangeText, testID }: {+ value: string; onChangeText: (value: string) => void; testID: string;+ }) => createElement('input', { value, 'data-testid': testID,+ onInput: (event: { currentTarget: HTMLInputElement }) => onChangeText(event.currentTarget.value),+ readOnly: true }),+ };+});+vi.mock('lucide-react-native', () => ({ Check: () => null, CornerDownLeft: () => null,+ Maximize2: () => null, Minimize2: () => null, Minus: () => null, Pencil: () => null, Plus: () => null }));+vi.mock('react-i18next', async (importOriginal) => ({+ ...await importOriginal<typeof import('react-i18next')>(),+ useTranslation: () => ({ t: (key: string) => key, i18n: { language: 'en' } }),+}));+vi.mock('@/theme', async () => {+ const tokens = await import('@/theme/tokens');+ return { ...tokens, monoFont: 'monospace', useTheme: () => ({ colors: tokens.lightColors }),+ useThemedStyles: (make: (colors: typeof tokens.lightColors) => unknown) => make(tokens.lightColors) };+});++let root: Root;+let host: HTMLDivElement;+const requestId = 'codex:test:0';+const onError = vi.fn();+function Harness() {+ const interactions = useSessionPendingInteractions('s1');+ return <InteractionPanel deviceId="d1" sessionId="s1" interactions={interactions} onError={onError} />;+}+beforeEach(() => {+ Object.assign(globalThis, { IS_REACT_ACT_ENVIRONMENT: true });+ vi.resetAllMocks();+ remoteSessionStore.clear();+ clearAllInteractionDrafts();+ host = document.createElement('div');+ root = createRoot(host);+});+afterEach(() => act(() => root.unmount()));++it('restores the last answer after a rejected receipt and clears it only after an accepted retry', async () => {+ let reply!: (receipt: { accepted: boolean }) => void;+ resolveInteraction.mockImplementationOnce(() => new Promise((resolve) => { reply = resolve; }));+ remoteSessionStore.setPendingInteractions('s1', [{ request: {+ kind: 'ask_user_question', requestId, questions: [{ question: 'Your answer?' }],+ } }]);+ await act(async () => root.render(<Harness />));+ const input = () => host.querySelector<HTMLInputElement>('[data-testid="interaction.ask.textInput"]');+ const submit = () => host.querySelector<HTMLButtonElement>('[data-testid="interaction.ask.submitButton"]')!;+ await act(async () => {+ input()!.value = 'Keep the connection';+ input()!.dispatchEvent(new Event('input', { bubbles: true }));+ });+ await act(async () => submit().click());+ expect(input()).toBeNull();+ expect(readAskUserDraft(requestId)?.customInput).toBe('Keep the connection');+ await act(async () => reply({ accepted: false }));+ expect(input()?.value).toBe('Keep the connection');+ expect(onError).toHaveBeenLastCalledWith(expect.any(String));+ resolveInteraction.mockResolvedValueOnce({ accepted: true });+ await act(async () => submit().click());+ expect(resolveInteraction).toHaveBeenCalledTimes(2);+ expect(resolveInteraction.mock.calls[1]).toEqual(resolveInteraction.mock.calls[0]);+ expect(resolveInteraction.mock.calls[1][1]).toMatchObject({ answers: { 'Your answer?': 'Keep the connection' } });+ expect(input()).toBeNull();+ expect(readAskUserDraft(requestId)).toBeNull();+});diff --git a/apps/mobile/src/__tests__/interactionModel.test.ts b/apps/mobile/src/__tests__/interactionModel.test.tsindex a889176f15..91d5ebc91d 100644--- a/apps/mobile/src/__tests__/interactionModel.test.ts+++ b/apps/mobile/src/__tests__/interactionModel.test.ts@@ -967,6 +967,22 @@ describe('resolveInteractionResilient', () => {const noSleep = async () => undefined;const pendingItem = (requestId: string) => ({ request: { requestId } });+ it.each(['ask_user_question', 'plan_review'])('does not treat a rejected %s receipt as success even when the request is absent', async (kind) => {+ let queries = 0;+ await expect(mobileInteractionModel.resolveInteractionResilient({+ resolveInteraction: async () => ({ accepted: false }),+ getPendingInteractions: async () => { queries++; return []; },+ }, 's1', 'req-1', { kind }, { sleep: noSleep })).rejects.toThrow(i18n.t('interaction.panel.decisionNotAccepted'));+ expect(queries).toBe(0);+ });++ it.each([{ accepted: true }, undefined])('accepts a successful or legacy receipt %j', async (receipt) => {+ await expect(mobileInteractionModel.resolveInteractionResilient({+ resolveInteraction: async () => receipt,+ getPendingInteractions: async () => { throw new Error('should not reconcile'); },+ }, 's1', 'req-1', {}, { sleep: noSleep })).resolves.toBeUndefined();+ });+it('NOT_CONNECTED(请求未出本机)自动重试直到成功,不触发权威查询', async () => {let resolveCalls = 0;let pendingCalls = 0;diff --git a/apps/mobile/src/__tests__/remoteSessionStore.test.ts b/apps/mobile/src/__tests__/remoteSessionStore.test.tsindex d4b53d79c4..55c079954c 100644--- a/apps/mobile/src/__tests__/remoteSessionStore.test.ts+++ b/apps/mobile/src/__tests__/remoteSessionStore.test.ts@@ -3284,10 +3284,11 @@ describe('remoteSessionStore', () => {expect(remoteSessionStore.isSessionMakerTurnRunning('s1')).toBe(false);});- it('keeps the product turn running across claimed mobile continuation boundaries', () => {+ it.each(['ask_user_question', 'plan_review'])('keeps the product running while %s awaits confirmation across an SDK boundary', (kind) => {vi.useFakeTimers();try {pushMakerStatus('s1', { isRunning: true });+ remoteSessionStore.setPendingInteractions('s1', [{ request: { kind, requestId: 'human-1' } }]);pushMakerText('s1', 'persist-1', 'first segment', false);vi.runOnlyPendingTimers();@@ -3305,16 +3306,21 @@ describe('remoteSessionStore', () => {});expect(remoteSessionStore.isSessionRunning('s1')).toBe(true);+ expect(remoteSessionStore.getPendingInteractions('s1')).toHaveLength(1);expect(remoteSessionStore.isSessionMakerTurnRunning('s1')).toBe(true);expect(remoteSessionStore.getSessionRunStatus('s1').startedAt).not.toBeNull();expect(remoteSessionStore.getMessages('s1')[0]?.agentMeta?.isStreaming).toBe(true);+ remoteSessionStore.applyRemotePush('dev-1', 'maker:interaction-dismissed', {+ sessionId: 's1', requestId: 'human-1', resolvedAs: 'allow',+ });remoteSessionStore.applyRemotePush('dev-1', 'maker:event', {sessionId: 's1',event: { type: 'done', data: {} },});expect(remoteSessionStore.isSessionRunning('s1')).toBe(false);+ expect(remoteSessionStore.getPendingInteractions('s1')).toHaveLength(0);expect(remoteSessionStore.isSessionMakerTurnRunning('s1')).toBe(false);expect(remoteSessionStore.getMessages('s1')[0]?.agentMeta?.isStreaming).not.toBe(true);} finally {diff --git a/apps/mobile/src/device-link/mobileMakerTransport.ts b/apps/mobile/src/device-link/mobileMakerTransport.tsindex ec05244651..47a2771e0f 100644--- a/apps/mobile/src/device-link/mobileMakerTransport.ts+++ b/apps/mobile/src/device-link/mobileMakerTransport.ts@@ -542,7 +542,7 @@ export interface MobileMakerTransport {*/getVoiceDictionary(): Promise<MobileVoiceDictionarySnapshotResult>;getPendingInteractions(sessionId: string): Promise<PendingInteraction[]>;- resolveInteraction(requestId: string, decision: Record<string, unknown>): Promise<void>;+ resolveInteraction(requestId: string, decision: Record<string, unknown>): Promise<{ accepted: boolean } | void>;getContextUsage(sessionId: string, createOpts?: Record<string, unknown>): Promise<unknown>;fork(sourceSessionId: string, messageClientId: string): Promise<RemoteSession>;rewindPreview(sessionId: string, clientId: string): Promise<RewindPreviewPayload>;diff --git a/apps/mobile/src/i18n/locales/en/interaction.json b/apps/mobile/src/i18n/locales/en/interaction.jsonindex 1621b15f94..d074bac8fb 100644--- a/apps/mobile/src/i18n/locales/en/interaction.json+++ b/apps/mobile/src/i18n/locales/en/interaction.json@@ -57,6 +57,7 @@"collapsedHint": "Tap to answer","selectAnswer": "Select answer {{label}}","submittingHint": "Sending the decision to your computer. Don't submit again.",+ "decisionNotAccepted": "Your response was not accepted. Please try again.","customAnswerInputAccessibility": "Enter a custom answer","customAnswerPlaceholder": "Enter another answer","customAnswerButtonText": "Enter another answer…",diff --git a/apps/mobile/src/i18n/locales/ja/interaction.json b/apps/mobile/src/i18n/locales/ja/interaction.jsonindex 07cdb988a6..600a9fc699 100644--- a/apps/mobile/src/i18n/locales/ja/interaction.json+++ b/apps/mobile/src/i18n/locales/ja/interaction.json@@ -57,6 +57,7 @@"collapsedHint": "タップして回答","selectAnswer": "回答 {{label}} を選択","submittingHint": "決定をパソコンに送信中です。重複して送信しないでください。",+ "decisionNotAccepted": "回答を送信できませんでした。もう一度お試しください。","customAnswerInputAccessibility": "カスタム回答を入力","customAnswerPlaceholder": "その他の回答を入力","customAnswerButtonText": "その他の回答を入力…",diff --git a/apps/mobile/src/i18n/locales/ko/interaction.json b/apps/mobile/src/i18n/locales/ko/interaction.jsonindex 8f6accdd11..9b627d3cda 100644--- a/apps/mobile/src/i18n/locales/ko/interaction.json+++ b/apps/mobile/src/i18n/locales/ko/interaction.json@@ -57,6 +57,7 @@"collapsedHint": "탭하여 답변","selectAnswer": "답변 {{label}} 선택","submittingHint": "결정을 컴퓨터로 전송 중입니다. 중복 제출하지 마세요.",+ "decisionNotAccepted": "응답을 제출하지 못했습니다. 다시 시도하세요.","customAnswerInputAccessibility": "사용자 지정 답변 입력","customAnswerPlaceholder": "다른 답변 입력","customAnswerButtonText": "다른 답변 입력…",diff --git a/apps/mobile/src/i18n/locales/zh-CN/interaction.json b/apps/mobile/src/i18n/locales/zh-CN/interaction.jsonindex a6a50c41aa..51ed50729e 100644--- a/apps/mobile/src/i18n/locales/zh-CN/interaction.json+++ b/apps/mobile/src/i18n/locales/zh-CN/interaction.json@@ -57,6 +57,7 @@"collapsedHint": "点开回答","selectAnswer": "选择回答 {{label}}","submittingHint": "正在把决定回传到电脑端,请不要重复提交。",+ "decisionNotAccepted": "未能提交,请重试。","customAnswerInputAccessibility": "输入自定义回答","customAnswerPlaceholder": "输入其他回答","customAnswerButtonText": "输入其他回答…",diff --git a/apps/mobile/src/i18n/locales/zh-TW/interaction.json b/apps/mobile/src/i18n/locales/zh-TW/interaction.jsonindex 144a931edf..3d700d5e81 100644--- a/apps/mobile/src/i18n/locales/zh-TW/interaction.json+++ b/apps/mobile/src/i18n/locales/zh-TW/interaction.json@@ -57,6 +57,7 @@"collapsedHint": "點開回答","selectAnswer": "選擇回答 {{label}}","submittingHint": "正在把決定回傳到電腦端,請不要重複提交。",+ "decisionNotAccepted": "未能提交,請重試。","customAnswerInputAccessibility": "輸入自定義回答","customAnswerPlaceholder": "輸入其他回答","customAnswerButtonText": "輸入其他回答…",diff --git a/apps/mobile/src/session/InteractionPanel.tsx b/apps/mobile/src/session/InteractionPanel.tsxindex 890cf0b00a..e8137dc891 100644--- a/apps/mobile/src/session/InteractionPanel.tsx+++ b/apps/mobile/src/session/InteractionPanel.tsx@@ -466,6 +466,7 @@ function InteractionItem({if (optimisticDismiss) remoteSessionStore.beginOptimisticInteractionDismiss(sessionId, currentRequestId);try {await resolveInteractionResilient(maker, sessionId, currentRequestId, decision);+ if (kind === 'ask_user_question') clearAskUserDraft(currentRequestId);if (kind === 'plan_review') clearPlanReviewDraft(currentRequestId);if (optimisticDismiss) {remoteSessionStore.settleOptimisticInteractionDismiss(sessionId, currentRequestId, { kind: 'confirmed' });@@ -808,7 +809,6 @@ function AskUserQuestionCard({label={t('interaction.panel.continue')}onPress={() => {draftCompletedRef.current = true;- clearAskUserDraft(requestId);onDecision(buildAskUserQuestionDecision({}));}}requestId={requestId}@@ -845,7 +845,15 @@ function AskUserQuestionCard({setAnswers(nextAnswers);if (isLast) {draftCompletedRef.current = true;- clearAskUserDraft(requestId);+ // Optimistic dismissal unmounts this form immediately. Save the final+ // choice now so a refused/lost receipt can restore exactly this draft.+ const finalSelection = selectionFromAnswer(current, answer);+ saveAskUserDraft(requestId, {+ answers: nextAnswers, currentIndex,+ customInput: finalSelection.customInput,+ selectedLabels: [...finalSelection.selectedLabels],+ showCustomInput: finalSelection.showCustomInput,+ });onDecision(buildAskUserQuestionDecision(nextAnswers));} else {setCurrentIndex((idx) => Math.min(idx + 1, questions.length - 1));diff --git a/apps/mobile/src/session/interactionModel.ts b/apps/mobile/src/session/interactionModel.tsindex 072bec0816..6322d09727 100644--- a/apps/mobile/src/session/interactionModel.ts+++ b/apps/mobile/src/session/interactionModel.ts@@ -259,7 +259,7 @@ export function isPlanReviewResolveBusy(input: { busy: boolean }): boolean {/** resolveInteraction 依赖的最小 transport 面(便于单测注入 fake)。 */export interface InteractionResolveTransport {- resolveInteraction(requestId: string, decision: Record<string, unknown>): Promise<void>;+ resolveInteraction(requestId: string, decision: Record<string, unknown>): Promise<{ accepted: boolean } | void>;getPendingInteractions(sessionId: string): Promise<readonly PendingInteractionLike[]>;}@@ -283,10 +283,11 @@ function isRetryableResolveTransportError(err: unknown): boolean {* - NOT_CONNECTED / BACKPRESSURE 自动带退避重试。注意 NOT_CONNECTED 不保证未送达(断连时* in-flight invoke 会被批量 reject 成 NOT_CONNECTED),但 resolve 重发是安全的:* 交互请求在被控端是一次性的,已解决的 requestId 再收到 resolve 只会被拒,- * 不会重复执行决定,被拒后走下方权威查证按成功收敛——与 enqueue(追加语义,+ * 不会重复执行决定——与 enqueue(追加语义,* 盲重会双入队)有本质区别。BACKPRESSURE 要么在本地发送前拒绝,要么由被控端* admission 明确拒绝执行,同样可安全重试。- * - 其余失败(超时 / ack 丢失 / 对已解决请求的重复提交被拒)以被控端 pending+ * - 明确的 accepted:false 不视为成功,交由调用方恢复卡片与草稿。+ * - 传输异常(超时 / ack 丢失 / 老端抛错)以被控端 pending* 列表为权威分辨:该 requestId 已不在列表 → 决定已生效,按成功收敛(面板正常* 关闭,而不是留给用户一个会诱发二次提交的错误态);仍在列表或查询失败 →* 抛原始错误,面板保持可重试。@@ -301,9 +302,9 @@ export async function resolveInteractionResilient(const sleep = opts.sleep ?? ((ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms)));let lastErr: unknown;for (let attempt = 0; attempt <= RESOLVE_TRANSIENT_SEND_RETRIES; attempt++) {+ let receipt: { accepted: boolean } | void;try {- await transport.resolveInteraction(requestId, decision);- return;+ receipt = await transport.resolveInteraction(requestId, decision);} catch (err) {lastErr = err;if (attempt < RESOLVE_TRANSIENT_SEND_RETRIES && isRetryableResolveTransportError(err)) {@@ -312,6 +313,11 @@ export async function resolveInteractionResilient(}break;}+ // An explicit refusal is not a lost acknowledgement: absence from the+ // pending list cannot prove that this answer won. Restore the card/draft+ // through the caller's existing error path. Older Hosts returned void.+ if (receipt?.accepted === false) throw new Error(i18n.t('interaction.panel.decisionNotAccepted'));+ return;}try {const pending = await transport.getPendingInteractions(sessionId);diff --git a/docs/dev-rules/maker-core-and-agent-behavior.md b/docs/dev-rules/maker-core-and-agent-behavior.mdindex ac6bdf0e2e..d7a90cd70f 100644--- a/docs/dev-rules/maker-core-and-agent-behavior.md+++ b/docs/dev-rules/maker-core-and-agent-behavior.md@@ -162,6 +162,13 @@ Codex 的 120 秒 reconnect watchdog 只是 fallback 收口,不是根因诊断交给模型自由发挥,会引入不可复现的行为漂移,属于本规则明确禁止的做法。- **产品 turn 未结算不得结束。** provider `turn/completed` 可以立刻给 SDK turn 落墓碑并结算 usage;只有原子挂在该终态边界上的显式 continuation claim 才能挡住产品结束。+ Codex 提问/计划审阅尚待用户确认时同样保留产品边界:底层可继续独立工作并结束+ SDK turn,但不能触发完成通知、队列收口或协作任务完成。人工等待使用独立 claim,+ 复用 `turnContinuationId`,不能塞进 yield claim 造成回答续跑等待自身。计划审阅必须+ 在发布边界前登记;回答/批准后沿原意图续跑,取消/Stop 单次结束且不重复结算 usage。+ 起跑回执之前到达的终态先缓冲再核对归属;失败只能走失败终态,不能先以取消回调+ 触发定时任务的成功收口。回归见 `agents/codex/index.test.ts` 的 pending confirmation+ 与 human continuation 用例,以及 Desktop `sessionEventPipeline.test.ts`。Codex `functions.exec` yield 没有协议级 execution handle(cell / wait 活在`codex-rs` daemon),近期检测只能是 adapter 内、用真实 rollout fixture 锁死的启发式,用来铸造有界 claim,再由宿主确定性开续段让模型 wait 同一 cell。@@ -173,7 +180,7 @@ Codex 的 120 秒 reconnect watchdog 只是 fallback 收口,不是根因诊断无 yield marker 的 nameless 完成不得清匿名桶;匿名 `wait` 若按 `cell_id` 结算了其中一个cell,只从匿名桶拿掉该 cell,不得清空仍在跑的其它匿名 cell。同 turn 或续段里后续 `wait` 输出 `Script completed` / `Script terminated` 后视为该 cell 已结算,不得- 再铸 claim,也不得报 lost-handle。Plan Mode 审批只在产品终态跑:存在 awaiting+ 再铸 claim,也不得报 lost-handle。Plan Mode 审批只在执行段结算后跑:存在 awaitingyield claim 时不得把空计划当循环结束,也不得在 SDK `turn/completed` 上提前挂审批;origin 已产出的计划挂在 claim 上,续段结算后再审。禁止把 `last_agent_message == null` 或开场白当结算判据;空续段或重试耗尽只证明未取回结果,统一报 `yield-continuation-incomplete`,diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.tsindex 3501e29fe2..dfda9ea5ee 100644--- a/packages/maker-core/src/agents/codex/index.test.ts+++ b/packages/maker-core/src/agents/codex/index.test.ts@@ -684,6 +684,7 @@ function installFakeHost(agent: CodexAgent,requestImpl?: (method: string, params: unknown) => Promise<unknown> | unknown,opts: {+ connectionId?: string;codexProxyActive?: boolean;codexBrowserUseAvailable?: boolean;codexBrowserUseVersion?: string;@@ -840,7 +841,7 @@ function installFakeHost(getSubagentRoute,getObservedSubagentIdentity,getOpenAiWebSocketsEnabled,- getConnectionId: () => 'test-connection',+ getConnectionId: () => opts.connectionId ?? 'test-connection',getThreadHandlers: () => threadHandlers,// 0.145 不给 spawn 子线程发 thread/started,session 层改为从 spawn item 主动// 登记血缘;fake 里只记录调用,路由行为由 host.test.ts 的真 transport 覆盖。@@ -16565,7 +16566,7 @@ describe('CodexAgent MCP thread context hooks', () => {seen(req);expect(req).toMatchObject({kind: 'ask_user_question',- requestId: 'req-user-input',+ requestId: 'codex:test-connection:req-user-input',questions: [{question: 'Which mode should Codex use?',@@ -16653,7 +16654,7 @@ describe('CodexAgent MCP thread context hooks', () => {handle.setInteractionResolver(async (req) => {expect(req).toMatchObject({kind: 'permission',- requestId: 'req-tool-input',+ requestId: 'codex:test-connection:req-tool-input',toolName: 'mcp:third_party:block_contacts',metadata: { userInputKind: 'tool_side_effect' },});@@ -18824,7 +18825,7 @@ describe('CodexAgent MCP thread context hooks', () => {requestCount += 1;expect(req).toMatchObject({kind: 'ask_user_question',- requestId: 'req-dynamic',+ requestId: 'codex:test-connection:req-dynamic',toolUseId: 'dynamic-call-1',});return pendingDecision.promise;@@ -19054,8 +19055,8 @@ describe('CodexAgent MCP thread context hooks', () => {handle.setInteractionResolver(async (req) => {if (req.kind !== 'ask_user_question') throw new Error('expected ask_user_question');requestCount += 1;- if (req.requestId === 'req-first') return firstDecision.promise;- if (req.requestId === 'req-second') return secondDecision.promise;+ if (req.requestId === 'codex:test-connection:req-first') return firstDecision.promise;+ if (req.requestId === 'codex:test-connection:req-second') return secondDecision.promise;return {kind: 'ask_user_question',answers: { [req.questions[0]?.question ?? '']: 'Unexpected repeat' },@@ -19106,6 +19107,58 @@ describe('CodexAgent MCP thread context hooks', () => {await handle.close();});+ it.each(['native', 'dynamic'] as const)('isolates two %s questions with RPC id 0 across connections', async (kind) => {+ // Model Desktop's shared request registry. Each Host may independently+ // start numbering at zero; answering B must leave A available after done.+ const registry = new Map<string, (decision: InteractionDecision) => void>();+ const fixtures = await Promise.all(['first', 'second'].map(async (connectionId) => {+ const agent = new CodexAgent(createDeps());+ const host = installFakeHost(agent, undefined, { connectionId });+ const handle = await agent.startSession({+ sessionId: `collision-${connectionId}`, model: 'gpt-5.4', workingDir: '/repo',+ });+ handle.setInteractionResolver((request) => new Promise((resolve) => {+ registry.set(request.requestId, resolve);+ }));+ const handlers = host.getThreadHandlers()!;+ const response = kind === 'native'+ ? handlers.requestUserInput!({+ threadId: 'start-thread-id', turnId: 'turn-1', itemId: 'question',+ questions: [{ id: 'q', header: 'Choose', question: 'Choose?', isOther: false, isSecret: false, options: null }],+ }, { requestId: 0 })+ : handlers.dynamicToolCall!({+ threadId: 'start-thread-id', turnId: 'turn-1', callId: 'question',+ namespace: 'cindy', tool: 'ask_user_question',+ arguments: { questions: [{ id: 'q', header: 'Choose', question: 'Choose?' }] },+ }, { requestId: 0 });+ return { handle, host, handlers, response };+ }));+ try {+ await waitForExpectation(() => expect(registry.size).toBe(2));+ const keys = [...registry.keys()];+ const firstKey = keys.find((key) => key.includes('first'))!;+ const secondKey = keys.find((key) => key.includes('second'))!;+ expect(firstKey).not.toBe(secondKey);+ const events = await collectAgentEvents(fixtures[0].handle);+ fixtures[0].handlers.turnCompleted?.({+ threadId: 'start-thread-id', turn: { id: 'turn-1', status: 'completed' },+ });+ await fixtures[0].response;+ await waitForExpectation(() => expect(events.some((event) => event.type === 'done')).toBe(true));+ expect(events.filter((event) => event.type === 'interaction_dismissed')).toEqual([]);+ registry.get(secondKey)!({ kind: 'ask_user_question', answers: { 'Choose?': 'B' } });+ registry.delete(secondKey);+ await expect(fixtures[1].response).resolves.toEqual(kind === 'native'+ ? { answers: { q: { answers: ['B'] } } }+ : { success: true, contentItems: [{ type: 'inputText', text: JSON.stringify({ q: { answers: ['B'] } }) }] });+ expect(registry.has(firstKey)).toBe(true);+ registry.get(firstKey)!({ kind: 'ask_user_question', answers: { 'Choose?': 'A' } });+ await waitForExpectation(() => expect(askUserTurnStartCalls(fixtures[0].host)).toHaveLength(1));+ } finally {+ await Promise.all(fixtures.map(({ handle }) => handle.close()));+ }+ });+it('cancels pending user input when serverRequest/resolved arrives', async () => {const agent = new CodexAgent(createDeps());const host = installFakeHost(agent);@@ -19122,7 +19175,7 @@ describe('CodexAgent MCP thread context hooks', () => {let requestCount = 0;handle.setInteractionResolver(async (req) => {requestCount += 1;- return req.requestId === 'req-resolved'+ return req.requestId === 'codex:test-connection:req-resolved'? cancelledDecision.promise: retryDecision.promise;});@@ -19148,7 +19201,7 @@ describe('CodexAgent MCP thread context hooks', () => {await expect(nextEvent(iterator)).resolves.toMatchObject({type: 'interaction_dismissed',data: {- requestId: 'req-resolved',+ requestId: 'codex:test-connection:req-resolved',reason: 'server_request_resolved',resolvedAs: 'deny',},@@ -19277,7 +19330,7 @@ describe('CodexAgent MCP thread context hooks', () => {let requestCount = 0;handle.setInteractionResolver(async (req) => {requestCount += 1;- return req.requestId === 'req-owner'+ return req.requestId === 'codex:test-connection:req-owner'? ownerDecision.promise: joinedDecision.promise;});@@ -19319,7 +19372,7 @@ describe('CodexAgent MCP thread context hooks', () => {await expect(nextEvent(iterator)).resolves.toMatchObject({type: 'interaction_dismissed',data: {- requestId: 'req-owner',+ requestId: 'codex:test-connection:req-owner',reason: 'server_request_resolved',resolvedAs: 'deny',},@@ -19459,7 +19512,7 @@ describe('CodexAgent MCP thread context hooks', () => {await waitForExpectation(() => {expect(debug).toHaveBeenCalledWith('joined duplicate same-turn user input request cancelled',- { requestId: 'req-joined', turnId: 'turn-1' },+ { requestId: 'codex:test-connection:req-joined', turnId: 'turn-1' },);});}@@ -19480,6 +19533,132 @@ describe('CodexAgent MCP thread context hooks', () => {return events;}+ async function pendingHumanProduct(kind: 'native' | 'dynamic' | 'plan', followupStart?: () => Promise<unknown>) {+ const agent = new CodexAgent(createDeps());+ let turnSeq = 0;+ const host = installFakeHost(agent, (method) => {+ if (method !== Method.TurnStart) return undefined;+ turnSeq += 1;+ if (turnSeq === 2 && followupStart) return followupStart();+ return { turn: { id: `human-turn-${turnSeq}` } };+ });+ const handle = await agent.startSession({ sessionId: `human-${kind}`, model: 'gpt-5.4',+ workingDir: '/repo', planMode: kind === 'plan' });+ const decision = deferred<InteractionDecision>();+ handle.setInteractionResolver(async () => decision.promise);+ const events = await collectAgentEvents(handle);+ await handle.send({ type: 'user', content: 'Do the work after confirmation' });+ const handlers = host.getThreadHandlers()!;+ const base = { threadId: 'start-thread-id', turnId: 'human-turn-1' };+ if (kind === 'plan') {+ handlers.itemCompleted?.({ ...base, item: { type: 'plan', id: 'plan-1', text: '1. Make the change' } });+ } else if (kind === 'native') {+ void handlers.requestUserInput?.({ ...base, itemId: 'ask-1',+ questions: [{ id: 'choice', header: 'Scope', question: 'Proceed?', options: [{ label: 'Yes' }] }] },+ { requestId: 0 });+ } else {+ void handlers.dynamicToolCall?.({ ...base, callId: 'ask-1', namespace: 'cindy', tool: 'ask_user_question',+ arguments: { questions: [{ question: 'Proceed?', options: [{ label: 'Yes' }] }] } }, { requestId: 0 });+ }+ // Independent progress remains visible while the answer is pending.+ handlers.itemCompleted?.({ ...base,+ item: { type: 'agentMessage', id: 'progress-1', text: 'Existing tests checked.', phase: 'commentary' } });+ handlers.turnCompleted?.({ threadId: base.threadId, turn: { id: base.turnId, status: 'completed' } });+ await waitForExpectation(() => expect(events.some((event) => event.type === 'done')).toBe(true));+ const boundary = events.find((event) => event.type === 'done')!;+ expect(boundary.turnContinuationId).toEqual(expect.any(Number));+ expect(handle.beginTurnContinuationWait?.(boundary.turnContinuationId)).toBe('awaiting');+ expect(handle.isTurnRunning?.()).toBe(true);+ expect(events.some((event) => event.type === 'text' && JSON.stringify(event.data).includes('Existing tests checked.'))).toBe(true);+ return { handle, host, handlers, decision, events };+ }++ it.each(['native', 'dynamic', 'plan'] as const)('%s pending confirmation retains the product until its follow-up finishes', async (kind) => {+ const { handle, host, handlers, decision, events } = await pendingHumanProduct(kind);+ expect(events.filter((event) => event.type === 'done' && event.turnContinuationId === undefined)).toHaveLength(0);+ decision.resolve(kind === 'plan' ? { kind: 'plan_review', behavior: 'allow' }+ : { kind: 'ask_user_question', answers: { 'Proceed?': 'Yes' } });+ await vi.waitFor(() => expect(askUserTurnStartCalls(host)).toHaveLength(2));+ expect(handle.isTurnRunning?.()).toBe(true);+ handlers.turnCompleted?.({ threadId: 'start-thread-id', turn: { id: 'human-turn-2', status: 'completed' } });+ await waitForExpectation(() => expect(events.filter((event) => event.type === 'done' && event.turnContinuationId === undefined)).toHaveLength(1));+ expect(handle.isTurnRunning?.()).toBe(false);+ // Duplicate provider completion cannot generate a second product terminal.+ handlers.turnCompleted?.({ threadId: 'start-thread-id', turn: { id: 'human-turn-2', status: 'completed' } });+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(events.filter((event) => event.type === 'done' && event.turnContinuationId === undefined)).toHaveLength(1);+ await handle.close();+ });++ it.each(['native', 'dynamic', 'plan'] as const)('%s cancellation ends the product once without replaying SDK usage', async (kind) => {+ const { handle, host, decision, events } = await pendingHumanProduct(kind);+ decision.resolve(kind === 'plan' ? { kind: 'plan_review', behavior: 'deny', dismissed: true }+ : { kind: 'ask_user_question', answers: {}, dismissed: true });+ await waitForExpectation(() => expect(handle.isTurnRunning?.()).toBe(false));+ await waitForExpectation(() => expect(events.filter((event) => event.type === 'done' && event.turnContinuationId === undefined)).toHaveLength(1));+ expect(events.filter((event) => event.type === 'done' && event.data.usage)).toHaveLength(1);+ expect(askUserTurnStartCalls(host)).toHaveLength(1);+ await handle.close();+ });++ it.each(['abort', 'graceful', 'close'] as const)('supports %s while only a confirmation remains and ignores late approval', async (action) => {+ const { handle, host, decision, events } = await pendingHumanProduct('plan');+ if (action === 'abort') await handle.abort();+ else if (action === 'graceful') await handle.requestGracefulStop?.();+ else await handle.close();+ expect(handle.isTurnRunning?.()).toBe(false);+ decision.resolve({ kind: 'plan_review', behavior: 'allow' });+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(askUserTurnStartCalls(host)).toHaveLength(1);+ expect(events.filter((event) => event.type === 'done' && event.turnContinuationId === undefined)).toHaveLength(action === 'close' ? 0 : 1);+ await handle.close();+ });++ it('keeps a human continuation result that completes before its start acknowledgement', async () => {+ const start = deferred<unknown>();+ const { handle, host, handlers, decision, events } = await pendingHumanProduct('dynamic', () => start.promise);+ decision.resolve({ kind: 'ask_user_question', answers: { 'Proceed?': 'Yes' } });+ await vi.waitFor(() => expect(askUserTurnStartCalls(host)).toHaveLength(2));+ handlers.tokenUsageUpdated?.({ threadId: 'start-thread-id', turnId: 'human-turn-2', tokenUsage: {+ total: { totalTokens: 100, inputTokens: 80, outputTokens: 20, cachedInputTokens: 0 },+ last: { totalTokens: 100, inputTokens: 80, outputTokens: 20, cachedInputTokens: 0 },+ } });+ handlers.turnCompleted?.({ threadId: 'start-thread-id', turn: { id: 'human-turn-2', status: 'completed' } });+ start.resolve({ turn: { id: 'human-turn-2' } });+ await waitForExpectation(() => expect(events.filter((event) => event.type === 'done' && event.turnContinuationId === undefined)).toHaveLength(1));+ expect(events.find((event) => event.type === 'done' && event.data.raw?.id === 'human-turn-2')?.data.usage)+ .toMatchObject({ promptTokens: 80, completionTokens: 20 });+ expect(handle.isTurnRunning?.()).toBe(false);+ await handle.close();+ });++ it('does not signal successful cancellation before a human continuation start failure', async () => {+ const { handle, decision, events } = await pendingHumanProduct('plan', async () => { throw new Error('stale host'); });+ const changed = vi.fn();+ handle.onTurnContinuationChange?.(changed);+ decision.resolve({ kind: 'plan_review', behavior: 'allow' });+ await waitForExpectation(() => expect(events.some((event) => event.type === 'error')).toBe(true));+ expect(changed.mock.calls.some(([, state]) => state === 'cancelled')).toBe(false);+ expect(handle.isTurnRunning?.()).toBe(false);+ expect(events.filter((event) => event.type === 'error')).toHaveLength(1);+ await handle.close();+ });++ it('stops a human continuation whose start acknowledgement is still pending', async () => {+ const start = deferred<unknown>();+ const { handle, host, handlers, decision, events } = await pendingHumanProduct('plan', () => start.promise);+ decision.resolve({ kind: 'plan_review', behavior: 'allow' });+ await vi.waitFor(() => expect(askUserTurnStartCalls(host)).toHaveLength(2));+ await handle.abort();+ start.resolve({ turn: { id: 'human-turn-2' } });+ await waitForExpectation(() => expect(handle.isTurnRunning?.()).toBe(false));+ handlers.turnCompleted?.({ threadId: 'start-thread-id', turn: { id: 'human-turn-2', status: 'interrupted' } });+ await new Promise((resolve) => setTimeout(resolve, 0));+ expect(events.filter((event) => event.type === 'done' && event.turnContinuationId === undefined)).toHaveLength(1);+ expect(events.filter((event) => event.type === 'error')).toHaveLength(0);+ await handle.close();+ });+it('does not dismiss a pending ask_user on successful turn completion and continues once after the answer', async () => {const agent = new CodexAgent(createDeps());const host = installFakeHost(agent);@@ -19563,8 +19742,8 @@ describe('CodexAgent MCP thread context hooks', () => {const lastDecision = deferred<InteractionDecision>();handle.setInteractionResolver(async (req) => {if (req.kind !== 'ask_user_question') throw new Error('expected ask_user_question');- if (req.requestId === 'req-ask-first') return firstDecision.promise;- if (req.requestId === 'req-ask-last') return lastDecision.promise;+ if (req.requestId === 'codex:test-connection:req-ask-first') return firstDecision.promise;+ if (req.requestId === 'codex:test-connection:req-ask-last') return lastDecision.promise;throw new Error(`unexpected request ${req.requestId}`);});const events = await collectAgentEvents(handle);@@ -19593,13 +19772,13 @@ describe('CodexAgent MCP thread context hooks', () => {await waitForExpectation(() => {expect(events.some((event) => (event.type === 'interaction_dismissed'- && (event.data as { requestId?: string }).requestId === 'req-ask-first'+ && (event.data as { requestId?: string }).requestId === 'codex:test-connection:req-ask-first'&& (event.data as { reason?: string }).reason === 'superseded'))).toBe(true);});expect(events.filter((event) => (event.type === 'interaction_dismissed'- && (event.data as { requestId?: string }).requestId === 'req-ask-last'+ && (event.data as { requestId?: string }).requestId === 'codex:test-connection:req-ask-last'))).toEqual([]);firstDecision.resolve({@@ -19706,7 +19885,7 @@ describe('CodexAgent MCP thread context hooks', () => {await waitForExpectation(() => {expect(events.some((event) => (event.type === 'interaction_dismissed'- && (event.data as { requestId?: string }).requestId === 'req-ask-fail'+ && (event.data as { requestId?: string }).requestId === 'codex:test-connection:req-ask-fail'))).toBe(true);});@@ -22217,7 +22396,7 @@ describe('CodexAgent yield continuation', () => {});expect(events.some((event) => (event.type === 'interaction_dismissed'- && (event.data as { requestId?: string }).requestId === 'req-ask-late'+ && (event.data as { requestId?: string }).requestId === 'codex:test-connection:req-ask-late'))).toBe(true);ownerDecision.resolve({kind: 'ask_user_question',diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.tsindex 2233be6203..e6eabbda0b 100644--- a/packages/maker-core/src/agents/codex/index.ts+++ b/packages/maker-core/src/agents/codex/index.ts@@ -1220,12 +1220,25 @@ const CODEX_INHERITED_CAPABILITY_SELECTION = Symbol('codexInheritedCapabilitySelconst CODEX_AUTO_REVIEW_INTENT = Symbol('codexAutoReviewIntent');const CODEX_YIELD_CONTINUATION = Symbol('codexYieldContinuation');const CODEX_INTERNAL_CONTINUATION = Symbol('codexInternalContinuation');+const CODEX_INTERACTION_CONTINUATION = Symbol('codexInteractionContinuation');const YIELD_CONTINUATION_MAX_ATTEMPTS = 2;type CodexInternalSendOptions = SendOptions & {[CODEX_INHERITED_CAPABILITY_SELECTION]?: string;[CODEX_AUTO_REVIEW_INTENT]?: string;[CODEX_YIELD_CONTINUATION]?: number;[CODEX_INTERNAL_CONTINUATION]?: true;+ [CODEX_INTERACTION_CONTINUATION]?: true;+};+type InteractionContinuationClaim = {+ id: number;+ state: 'awaiting' | 'active' | 'cancelled';+ settled: boolean;+ pendingBoundaryEvents: number;+ turnIds: Set<string>;+ requestIds: Set<string>;+ pendingSends: number;+ sendTail: Promise<void>;+ abort: AbortController;};type YieldContinuationClaim = {id: number;@@ -3420,6 +3433,9 @@ export class CodexAgent extends BaseAgent {let isTurnInFlight = false;const yieldedExecCellsByTurnId = new Map<string, Map<string, YieldedExecCell[]>>();const yieldContinuationClaims = new Map<number, YieldContinuationClaim>();+ const interactionContinuationClaims = new Map<number, InteractionContinuationClaim>();+ let interactionContinuation: InteractionContinuationClaim | null = null;+ const interactionIdleWaiters = new Set<() => void>();const yieldContinuationListeners = new Set<(continuationId: number,state: 'awaiting' | 'active' | 'cancelled',@@ -3450,6 +3466,104 @@ export class CodexAgent extends BaseAgent {if (!claim.settled || claim.pendingBoundaryEvents > 0) return;yieldContinuationClaims.delete(claim.id);};+ // Human replies use the existing product-boundary contract, but never the+ // yield claim itself: an answer may have to wait for a yielded cell first.+ const retainInteractionContinuation = (turnId: string, requestId: string): InteractionContinuationClaim => {+ const claim = interactionContinuation ?? {+ id: nextYieldContinuationId++, state: 'awaiting' as const, settled: false,+ pendingBoundaryEvents: 0, turnIds: new Set<string>(), requestIds: new Set<string>(),+ pendingSends: 0, sendTail: Promise.resolve(), abort: new AbortController(),+ };+ interactionContinuation = claim;+ interactionContinuationClaims.set(claim.id, claim);+ claim.turnIds.add(turnId);+ claim.requestIds.add(requestId);+ claim.state = 'awaiting';+ return claim;+ };+ const releaseInteractionClaim = (claim: InteractionContinuationClaim): void => {+ if (claim.settled && claim.pendingBoundaryEvents === 0) interactionContinuationClaims.delete(claim.id);+ };+ const retireInteractionClaim = (claim: InteractionContinuationClaim, cancelled: boolean, notifyCancellation = cancelled): void => {+ claim.settled = true;+ if (interactionContinuation === claim) interactionContinuation = null;+ if (cancelled) {+ // Failure must be delivered as an error, not as a cancellation callback:+ // scheduled consumers treat that callback as successful teardown.+ claim.state = notifyCancellation ? 'cancelled' : 'active';+ claim.abort.abort();+ if (notifyCancellation) emitYieldContinuationState(claim.id, 'cancelled');+ }+ releaseInteractionClaim(claim);+ };+ const cancelInteractionContinuation = (reason: string, notifyCancellation = false): InteractionContinuationClaim | null => {+ const claim = interactionContinuation;+ if (!claim) return null;+ retireInteractionClaim(claim, true, notifyCancellation);+ for (const requestId of claim.requestIds) {+ eventQueue.push({ type: 'interaction_dismissed',+ data: { requestId, reason, resolvedAs: 'deny' }, source: 'codex' });+ }+ claim.requestIds.clear();+ return claim;+ };+ const interactionCanFinish = (claim: InteractionContinuationClaim): boolean =>+ !claim.settled && claim.requestIds.size === 0 && claim.pendingSends === 0 &&+ !isTurnInFlight && !isTurnStartPending && !activeYieldContinuationClaim() && !yieldContinuationInFlight;+ const finishIdleInteraction = (claim: InteractionContinuationClaim, cancelled = false): void => {+ if (!interactionCanFinish(claim)) return;+ retireInteractionClaim(claim, cancelled);+ // SDK usage was already delivered on its claimed boundary. Never replay it.+ eventQueue.push({ type: 'done', data: { type: 'codex/event/task_complete', cancelled }, source: 'codex' });+ eventQueue.push({ type: 'status', data: { status: 'Done', ...usageTracker.snapshot(), isRunning: false }, source: 'codex' });+ };+ const finishInteractionWithoutFollowUp = (requestId: string): void => {+ const claim = interactionContinuation;+ if (!claim?.requestIds.delete(requestId)) return;+ finishIdleInteraction(claim, true);+ };+ const flushInteractionIdleWaiters = (): void => {+ for (const resolve of [...interactionIdleWaiters]) resolve();+ };+ async function sendInteractionContinuation(+ requestId: string, message: UserMessage, options: CodexInternalSendOptions,+ failureContext: string,+ ): Promise<void> {+ const claim = interactionContinuation;+ if (!claim || !claim.requestIds.delete(requestId) || claim.settled) return;+ claim.pendingSends += 1;+ claim.sendTail = claim.sendTail.then(async () => {+ if (claim.settled || closed || await waitForYieldContinuationIdle()) return;+ while (!claim.settled && (isTurnInFlight || isTurnStartPending)) {+ await new Promise<void>((resolve) => {+ const wake = () => {+ interactionIdleWaiters.delete(wake);+ claim.abort.signal.removeEventListener('abort', wake);+ resolve();+ };+ interactionIdleWaiters.add(wake);+ claim.abort.signal.addEventListener('abort', wake, { once: true });+ });+ }+ if (claim.settled || closed) return;+ claim.state = 'active';+ emitYieldContinuationState(claim.id, 'active');+ await handle.send(message, { ...options, signal: claim.abort.signal,+ throwOnStartFailure: true, [CODEX_INTERACTION_CONTINUATION]: true } as CodexInternalSendOptions);+ }).catch((error: unknown) => {+ if (claim.settled || closed) return;+ cancelInteractionContinuation('interaction_continuation_failed');+ eventQueue.push({ type: 'error', data: {+ message: `${failureContext}: ${String(error)}`, isTerminal: true,+ }, source: 'codex' });+ eventQueue.push({ type: 'status', data: { status: 'Done', ...usageTracker.snapshot(), isRunning: false }, source: 'codex' });+ eventQueue.push({ type: 'done', data: { type: 'codex/event/task_complete' }, source: 'codex' });+ }).finally(() => {+ claim.pendingSends -= 1;+ finishIdleInteraction(claim);+ });+ await claim.sendTail;+ }const yieldItemLedgerKey = (record: Record<string, unknown> | null): string => {if (!record) return '';for (const key of ['id', 'call_id', 'callId'] as const) {@@ -3641,6 +3755,12 @@ export class CodexAgent extends BaseAgent {};const releaseYieldContinuationEvent = (event: AgentEvent): void => {if (event.turnContinuationId === undefined) return;+ const interactionClaim = interactionContinuationClaims.get(event.turnContinuationId);+ if (interactionClaim) {+ interactionClaim.pendingBoundaryEvents = Math.max(0, interactionClaim.pendingBoundaryEvents - 1);+ releaseInteractionClaim(interactionClaim);+ return;+ }const claim = yieldContinuationClaims.get(event.turnContinuationId);if (!claim) return;claim.pendingBoundaryEvents = Math.max(0, claim.pendingBoundaryEvents - 1);@@ -3652,6 +3772,7 @@ export class CodexAgent extends BaseAgent {cells: YieldedExecCell[];detail?: string;}): void => {+ cancelInteractionContinuation(opts.reason);log.warn(opts.reason === 'yield-continuation-start-failed'? 'yield continuation turn failed to start'@@ -4612,6 +4733,10 @@ export class CodexAgent extends BaseAgent {});}const connectionId = host.getConnectionId();+ // JSON-RPC IDs are connection-local (often 0). Desktop indexes interaction+ // requests across sessions, so never expose a raw server ID as a UI ID.+ const serverInteractionId = (requestId: string | number): string =>+ `codex:${connectionId}:${String(requestId)}`;const isCurrentHost = (): boolean => {if (sessionHostForceRetired) return false;const currentHost = this.hosts.get(currentHostKey);@@ -5556,6 +5681,7 @@ export class CodexAgent extends BaseAgent {const terminateHandleAfterThreadCleanupFailure = (reason: string): void => {if (closed) return;closed = true;+ cancelInteractionContinuation(reason);resetCodexGenerationTiming(translatorRt);resetUpstreamIdleForTurnEnd();unregisterCodexMcpContext(threadId);@@ -6834,6 +6960,7 @@ export class CodexAgent extends BaseAgent {): Promise<void> {planReviewSeq += 1;const requestId = `codex-plan-review:${turnId}:${planReviewSeq}`;+ const continuationClaim = retainInteractionContinuation(turnId, requestId);// 计划审批期间用户可能继续发消息(currentAutoReviewIntent 会被覆盖):实施/修订 turn 的审查// 意图必须锚在**发起计划时**的原始请求上(codex 报)。const planRequestAutoReviewIntent = currentAutoReviewIntent;@@ -6872,9 +6999,10 @@ export class CodexAgent extends BaseAgent {};log.debug('plan review ▶ dispatch', { turnId, planChars: plan.length });const decision = await dispatchInteraction({ kind: 'plan_review', requestId, plan });- if (closed) return;+ if (closed || continuationClaim.settled) return;if (decision.kind !== 'plan_review') {log.warn('plan review got mismatched decision', { decKind: decision.kind });+ finishInteractionWithoutFollowUp(requestId);return;}if (decision.behavior === 'allow') {@@ -6903,12 +7031,13 @@ export class CodexAgent extends BaseAgent {try {if (await waitForYieldContinuationIdle()) return;if (closed) return;- await handle.send(+ await sendInteractionContinuation(requestId,{ type: 'user', content: message },planFollowUpSendOptions(addedCapabilitySelection,implementationAutoReviewIntent,),+ 'plan implementation turn failed to start',);} catch (e) {emitPlanFollowUpStartFailure('implementation', e);@@ -6927,17 +7056,19 @@ export class CodexAgent extends BaseAgent {dismissed: decision.dismissed === true,reason: decision.reason ?? null,});+ finishInteractionWithoutFollowUp(requestId);return;}log.debug('plan review ◀ revision requested — starting plan revision turn', { turnId });try {if (await waitForYieldContinuationIdle()) return;if (closed) return;- await handle.send(+ await sendInteractionContinuation(requestId,{ type: 'user', content: feedback },// 修订轮同样带上原始审查意图快照:否则 send 会把 auto-review intent 覆盖成这条修改意见,// 下一次计划获批后 implementation reviewer 拿到的是"修改意见+计划"而非原始用户请求(codex 报)。planFollowUpSendOptions(feedback, planRequestAutoReviewIntent),+ 'plan revision turn failed to start',);} catch (e) {planCycleActive = false;@@ -7200,7 +7331,7 @@ export class CodexAgent extends BaseAgent {cancelledDynamicToolResponse(reason),);for (const meta of [...cancelledUserInput, ...cancelledDynamicTools]) {- const requestId = String(meta.requestId);+ const requestId = serverInteractionId(meta.requestId);if (dismissed.has(requestId)) continue;dismissed.add(requestId);liveAskUserByRequestId.delete(requestId);@@ -7242,7 +7373,10 @@ export class CodexAgent extends BaseAgent {// 否则被盖住的 resolver 会一直占着 hasPendingAgentInteraction。const lives = [...liveAskUserByRequestId.values()].filter((live) => live.turnId === turnId);const keep = lives.at(-1) ?? null;- if (keep) keep.detached = true;+ if (keep) {+ keep.detached = true;+ retainInteractionContinuation(turnId, keep.requestId);+ }const keepUiRequestIds = new Set(keep ? [keep.requestId] : []);const dismissed = new Set<string>();const dismiss = (requestId: string, reason: string): void => {@@ -7261,7 +7395,7 @@ export class CodexAgent extends BaseAgent {dismiss(live.requestId, 'superseded');}for (const meta of [...cancelledUserInput, ...cancelledDynamicTools]) {- dismiss(String(meta.requestId), 'turn_completed');+ dismiss(serverInteractionId(meta.requestId), 'turn_completed');}}@@ -7300,7 +7434,8 @@ export class CodexAgent extends BaseAgent {[CODEX_INTERNAL_CONTINUATION]: true,};try {- await handle.send({ type: 'user', content: message }, sendOptions);+ await sendInteractionContinuation(live.requestId, { type: 'user', content: message }, sendOptions,+ 'ask_user continuation turn failed to start');} catch (error) {emitAskUserContinuationStartFailure(error);}@@ -7488,6 +7623,7 @@ export class CodexAgent extends BaseAgent {currentTurnId = turnId;isTurnInFlight = true;bindYieldContinuationTurn(turnId);+ interactionContinuation?.turnIds.add(turnId);if (!isNewTurn) return;if (!hasActivatedRootTurn) {// Resume replays the previous run's usage window before this run starts.@@ -8070,6 +8206,9 @@ export class CodexAgent extends BaseAgent {// 装探针:此处仍远早于 handlers 注册(事件开始流动),不会漏掉任何一条。const rawEventQueuePush = eventQueue.push;eventQueue.push = (ev: AgentEvent): boolean => {+ if (ev.type === 'error' && (ev.data as { isTerminal?: boolean }).isTerminal === true) {+ cancelInteractionContinuation('terminal_error');+ }// 子代理卡帧只是"子线程有进展",不代表主 turn 还活着 —— 不参与静默计时与// reconnect 恢复判定,否则主 turn 哑火时会被子代理的心跳一直掩盖(review)。if (!emittingDescendantUpdate && ev.turnScope !== 'background') {@@ -8763,6 +8902,7 @@ export class CodexAgent extends BaseAgent {});if (decision.kind !== 'ask_user_question') {log.warn('requestUserInput got mismatched ask decision', { requestId, decKind: decision.kind });+ finishInteractionWithoutFollowUp(requestId);return questions.map(() => []);}const live = liveAskUserByRequestId.get(requestId);@@ -8785,6 +8925,8 @@ export class CodexAgent extends BaseAgent {) {live.continuationStarted = true;void startAskUserContinuation(live, decision.answers ?? {}, continuationAutoReviewIntent);+ } else if (live?.detached && decision.dismissed === true) {+ finishInteractionWithoutFollowUp(requestId);}return answersByPosition;})();@@ -8898,11 +9040,11 @@ export class CodexAgent extends BaseAgent {const turnGate = gateServerRequestTurn(params.turnId, params.threadId);if (turnGate === false) return { answers: {} };if (turnGate instanceof Promise && !(await turnGate)) return { answers: {} };- const requestId = String(meta.requestId);+ const requestId = serverInteractionId(meta.requestId);// 挂起期间服务端已取消本请求 (greptile R13 P1): 直接回空响应, 不注册// broker 不上 UI — 否则 UI 会等一个服务端已结束的交互, 用户提交后向// 已结束请求发迟到响应。- if (resolvedWhileBufferedRequestIds.delete(requestId)) return { answers: {} };+ if (resolvedWhileBufferedRequestIds.delete(String(meta.requestId))) return { answers: {} };const questions = normalizeRequestUserInputQuestions(params.questions);if (questions.length === 0) return { answers: {} };// Codex 0.145 emits an MCP tool's item/started notification before it@@ -9009,10 +9151,10 @@ export class CodexAgent extends BaseAgent {success: false,};}- const requestId = String(meta.requestId);+ const requestId = serverInteractionId(meta.requestId);// 挂起期间服务端已取消本请求 (greptile R13 P1): 直接回失败响应, 不注册// broker 不上 UI (与 resolved 的 cancel 响应同款文案)。- if (resolvedWhileBufferedRequestIds.delete(requestId)) {+ if (resolvedWhileBufferedRequestIds.delete(String(meta.requestId))) {return {contentItems: [{ type: 'inputText', text: 'Request was resolved before user input was submitted.' }],success: false,@@ -9123,6 +9265,7 @@ export class CodexAgent extends BaseAgent {function handleServerRequestResolved(params: ServerRequestResolvedNotification['params']): void {const requestId = String(params.requestId);+ const uiRequestId = serverInteractionId(params.requestId);const pendingApproval = pendingApprovals.get(requestId);let approvalCancelled = false;if (pendingApproval && !pendingApproval.settled) {@@ -9138,7 +9281,7 @@ export class CodexAgent extends BaseAgent {// Wake joined duplicates before settling the owner's outer broker// response. This keeps them on the cancellation/reassignment path even// if a resolver starts mirroring broker settlement in the future.- forgetPendingUserInputRequest(requestId);+ forgetPendingUserInputRequest(uiRequestId);}const userInputCancelled = userInputBroker.cancel(brokerKey,@@ -9151,13 +9294,21 @@ export class CodexAgent extends BaseAgent {success: false,},);- if (approvalCancelled || userInputCancelled || dynamicCancelled) {+ if (approvalCancelled) {eventQueue.push({type: 'interaction_dismissed',data: { requestId, reason: 'server_request_resolved', resolvedAs: 'deny' },source: 'codex',});- } else if (bufferedOrphanTurnIds.size > 0) {+ }+ if (userInputCancelled || dynamicCancelled) {+ eventQueue.push({+ type: 'interaction_dismissed',+ data: { requestId: uiRequestId, reason: 'server_request_resolved', resolvedAs: 'deny' },+ source: 'codex',+ });+ }+ if (!approvalCancelled && !userInputCancelled && !dynamicCancelled && bufferedOrphanTurnIds.size > 0) {// cancel 未命中且有 buffered turn: 可能是挂起中的请求 (尚未注册到// broker) 被服务端取消 (greptile R13 P1) — 记下 requestId, 对账放行// 后 handler 自查回空响应, 不上 UI。requestId 是一次性的 (消费即删),@@ -9597,8 +9748,10 @@ export class CodexAgent extends BaseAgent {};const flushDeferredTerminalTurnCompletionsIfIdle = (): void => {- if (isTurnStartPending || currentTurnId !== null) return;+ if (isTurnStartPending) return;for (const [turnId, params] of Array.from(deferredTerminalTurnCompletions.entries())) {+ if (currentTurnId !== null &&+ (currentTurnId !== turnId || !interactionContinuation?.turnIds.has(turnId))) continue;if (!deferredTerminalTurnCompletions.has(turnId)) continue;deferredTerminalTurnCompletions.delete(turnId);handleTurnCompleted(params);@@ -9984,6 +10137,12 @@ export class CodexAgent extends BaseAgent {recoveryState.pendingAutomaticRecovery = null;terminalErroredTurnIds.delete(turn.id);}+ if (interactionContinuation && !interactionContinuation.turnIds.has(turn.id) && isTurnStartPending) {+ // A continuation may complete before started/start response identifies+ // it. Reuse the terminal buffer; do not tombstone an unowned result.+ deferredTerminalTurnCompletions.set(turn.id, params);+ return;+ }// turn/start RPC 响应未回时就收到终态 → 记墓碑, 阻止稍后到达的// handleTurnStartResp / 乱序 turnStarted 把已终结的 turn 重新置活。if (isTurnStartPending) turnsCompletedBeforeStartResp.add(turn.id);@@ -10014,9 +10173,15 @@ export class CodexAgent extends BaseAgent {if (currentTurnId === turn.id || currentTurnId === null) {stopActiveRolloutPlanFallback();}+ if (interactionContinuation && !interactionContinuation.turnIds.has(turn.id)) {+ latestPlanByTurn.delete(turn.id);+ flushDeferredTerminalTurnCompletionsIfIdle();+ return;+ }if (turn.status === 'completed') {detachPendingAskUserForSuccessfulTurn(turn.id);} else {+ cancelInteractionContinuation(`turn_${turn.status}`);dismissPendingUserInputForTurn(turn.id, `turn_${turn.status}`);yieldedExecCellsByTurnId.delete(turn.id);const claim = activeYieldContinuationClaim();@@ -10272,7 +10437,28 @@ export class CodexAgent extends BaseAgent {yieldClaim.capabilitySelectionText = completedCapabilitySelectionText;yieldClaim.autoReviewIntent = currentAutoReviewIntent;}+ if (!suppressSuccessfulYieldBoundary && yieldClaim?.state !== 'awaiting') {+ // Register the review before publishing the SDK boundary. Consumers+ // must never observe an unclaimed Done followed by a necessary review.+ const livePlan = proposedPlanText?.trim() || null;+ proposedPlanText = null;+ const deferredPlan = existingYieldClaim?.deferredPlanText?.trim() || null;+ const planForReview = livePlan ?? deferredPlan;+ const planReviewTurnId = livePlan ? turn.id : (existingYieldClaim?.deferredPlanTurnId ?? turn.id);+ const planCapabilitySelection = livePlan ? completedCapabilitySelectionText+ : (existingYieldClaim?.deferredPlanCapabilitySelectionText || completedCapabilitySelectionText);+ if (planCycleActive && (completedTurnWasPlanMode || deferredPlan)) {+ if (planForReview) {+ void runPlanReviewFlow(planForReview, planReviewTurnId, planCapabilitySelection);+ } else {+ planCycleActive = false;+ }+ }+ }if (!suppressSuccessfulYieldBoundary) {+ if (interactionContinuation && interactionCanFinish(interactionContinuation)) {+ retireInteractionClaim(interactionContinuation, false);+ }const idleStatusEvent: AgentEvent = {type: 'status',data: {@@ -10302,6 +10488,10 @@ export class CodexAgent extends BaseAgent {if (yieldClaim?.state === 'awaiting') {attachYieldContinuationClaim(idleStatusEvent, yieldClaim);attachYieldContinuationClaim(doneEvent, yieldClaim);+ } else if (interactionContinuation) {+ idleStatusEvent.turnContinuationId = interactionContinuation.id;+ doneEvent.turnContinuationId = interactionContinuation.id;+ interactionContinuation.pendingBoundaryEvents += 2;}eventQueue.push(idleStatusEvent);// 真实 per-turn 用量 (host 的 today chip / daily_model_usage 记账消费):@@ -10332,36 +10522,8 @@ export class CodexAgent extends BaseAgent {}proposedPlanText = null;void startYieldContinuation(yieldClaim);- } else {- // 计划模式: 只在产品终态审批。awaiting yield claim 时 SDK turn 边界不是- // 产品结束 —— 空跑不得把 planCycleActive 关掉,已有计划也等续段结算后再挂卡。- // 放在 done 之后 (AsyncQueue FIFO), renderer 先做完 turn 收尾再挂 plan 卡片。- // 空跑(模型没产出 <proposed_plan>, 例如直接回答了问题) → 循环结束,- // 下一 turn 经 threadTouchedPlanMode 复位 default。- const livePlan = proposedPlanText?.trim() || null;- proposedPlanText = null;- const deferredPlan = existingYieldClaim?.deferredPlanText?.trim() || null;- const planForReview = livePlan ?? deferredPlan;- const planReviewTurnId = livePlan- ? turn.id- : (existingYieldClaim?.deferredPlanTurnId ?? turn.id);- const planCapabilitySelection = livePlan- ? completedCapabilitySelectionText- : (existingYieldClaim?.deferredPlanCapabilitySelectionText- || completedCapabilitySelectionText);- if (planCycleActive && (completedTurnWasPlanMode || deferredPlan)) {- if (planForReview) {- void runPlanReviewFlow(- planForReview,- planReviewTurnId,- planCapabilitySelection,- );- } else {- log.debug('plan turn produced no proposed plan — plan cycle ends', { turnId: turn.id });- planCycleActive = false;- }- }}+ flushInteractionIdleWaiters();flushDeferredTerminalTurnCompletionsIfIdle();}@@ -12059,7 +12221,8 @@ export class CodexAgent extends BaseAgent {isTurnInFlight|| targetsPendingTurn|| yieldContinuationInFlight- || activeYieldContinuationClaim() != null;+ || activeYieldContinuationClaim() != null+ || interactionContinuation != null;if (isTerminalError && targetsCurrentTurn && !isTransportError) {const recoveryTurnId = effectiveParams.turnId || currentTurnId || '';// error notification 只登记恢复意图并保持 logical turn 运行;@@ -12171,6 +12334,7 @@ export class CodexAgent extends BaseAgent {): Promise<void> {if (closed) return;closed = true;+ cancelInteractionContinuation('session_closed', true);resetCodexGenerationTiming(translatorRt);clearReconnectStall();resetUpstreamIdleForTurnEnd();@@ -12336,7 +12500,7 @@ export class CodexAgent extends BaseAgent {log.error('workspace permission profile refresh failed', { error: String(e), threadId });// Yield continuation owns its product terminal. Emitting here would// duplicate the later yield-continuation-start-failed events.- if (yieldAttempt == null) {+ if (yieldAttempt == null && !internalOpts?.[CODEX_INTERACTION_CONTINUATION]) {eventQueue.push({type: 'error',data: { message, isTerminal: true },@@ -12962,7 +13126,7 @@ export class CodexAgent extends BaseAgent {log.info('turn/start failure suppressed — this send was already settled by cancel', {threadId,});- } else if (yieldAttempt == null) {+ } else if (yieldAttempt == null && !internalOpts?.[CODEX_INTERACTION_CONTINUATION]) {eventQueue.push({type: 'error',data: { message: `turn/start failed: ${String(finalErr)}`, isTerminal: true },@@ -12981,6 +13145,7 @@ export class CodexAgent extends BaseAgent {if (rejectClosedOrCancelledSend(sendOpts, 'before resolving send')) {return;}+ flushInteractionIdleWaiters();},async steer(message: UserMessage, sendOpts?: SendOptions) {@@ -13147,6 +13312,10 @@ export class CodexAgent extends BaseAgent {},async requestGracefulStop(stopOpts) {+ if (!currentTurnId && interactionContinuation) {+ await handle.abort();+ return;+ }const retryState = overloadRetry;if (retryState &&@@ -13245,6 +13414,8 @@ export class CodexAgent extends BaseAgent {},async abort() {+ const cancelledInteraction = cancelInteractionContinuation('turn_interrupted', true);+ if (cancelledInteraction) dismissAllPendingUserInput('turn_interrupted');const cancelledYield = cancelActiveYieldContinuation('aborted');// isolateCancelledTurnStart tombstones an accepted turn whose TurnStart// RPC is still pending, and that tombstone swallows interrupted@@ -13252,7 +13423,8 @@ export class CodexAgent extends BaseAgent {// releases currentTurnAttemptToken. After the RPC has returned,// provider interrupted already emits one product Done — synthesizing// another here would settle the next attempt.- if (cancelledYield && isTurnStartPending) {+ if ((cancelledYield && isTurnStartPending) ||+ (cancelledInteraction && (!currentTurnId || isTurnStartPending))) {emitCancelledYieldProductDone();}clearReconnectStall();@@ -13698,12 +13870,14 @@ export class CodexAgent extends BaseAgent {return isTurnInFlight|| overloadRetryPending()|| yieldContinuationInFlight- || activeYieldContinuationClaim() != null;+ || activeYieldContinuationClaim() != null+ || interactionContinuation != null;},beginTurnContinuationWait(continuationId?: number) {if (continuationId === undefined) return null;- return yieldContinuationClaims.get(continuationId)?.state ?? null;+ return yieldContinuationClaims.get(continuationId)?.state+ ?? interactionContinuationClaims.get(continuationId)?.state ?? null;},onTurnContinuationChange(listener) {