Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): Codex 提问卡在 turn 结束后继续等待选择 (#3290)

Dash67afe4914362
diff --git a/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts b/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts
index db300790e4..cf8b5d279a 100644
--- a/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts
+++ b/apps/desktop/src/main/__tests__/messagePersistBroadcaster.test.ts
@@ -83,6 +83,7 @@ import {
prepareSyntheticToolEventForBroadcast,
onAssistantTextEvent,
onInteractionMessage,
+ onInteractionResolved,
onThinkingEvent,
flushAssistantBlock,
flushOrphanToolResults,
@@ -2718,3 +2719,37 @@ describe('媒体 echo 兜底:flushOrphanToolResults 从 fallback 池认领', ()
expect(createMessage).not.toHaveBeenCalled();
});
});
+
+describe('ask_user persist first-write-wins', () => {
+ it('ignores a later cancelled write after the winner already answered', async () => {
+ const persistId = onInteractionMessage(SESSION, {
+ kind: 'ask_user_question',
+ requestId: 'ask-winner',
+ questions: [{ question: 'Pick one' }],
+ });
+ onInteractionResolved(
+ SESSION,
+ persistId,
+ 'ask_user_question',
+ { requestId: 'ask-winner', questions: [{ question: 'Pick one' }] },
+ { answers: { 'Pick one': 'Keep going' } },
+ );
+ onInteractionResolved(
+ SESSION,
+ persistId,
+ 'ask_user_question',
+ { requestId: 'ask-winner', questions: [{ question: 'Pick one' }] },
+ { answers: {}, dismissed: true },
+ );
+ await flushWrites();
+ expect(updateMessageContent).toHaveBeenCalledTimes(1);
+ expect(updateMessageContent).toHaveBeenCalledWith(
+ SESSION,
+ persistId,
+ expect.objectContaining({
+ status: 'answered',
+ answers: { 'Pick one': 'Keep going' },
+ }),
+ );
+ });
+});
diff --git a/apps/desktop/src/main/agent-island/__tests__/state.test.ts b/apps/desktop/src/main/agent-island/__tests__/state.test.ts
index 95481bffdd..7f5eee8a31 100644
--- a/apps/desktop/src/main/agent-island/__tests__/state.test.ts
+++ b/apps/desktop/src/main/agent-island/__tests__/state.test.ts
@@ -1165,6 +1165,35 @@ describe('Agent Island display state', () => {
});
});
+ it('keeps ask_user waiting after a successful done instead of completing', () => {
+ const state = createAgentIslandState();
+ applyAgentIslandEvent(state, { sessionId: 'ask', title: 'Ask' }, statusEvent(true, 'Running'), 1_000);
+ applyAgentIslandInteractionRequest(state, { sessionId: 'ask', title: 'Ask' }, askUserQuestionRequest('r1'), 1_100);
+ applyAgentIslandEvent(state, { sessionId: 'ask', title: 'Ask' }, doneEvent(), 1_200);
+
+ const display = buildAgentIslandDisplayState(state, 1_300);
+ expect(display.sessions[0]).toMatchObject({
+ sessionId: 'ask',
+ phase: 'needs-interaction',
+ interactionKind: 'ask_user_question',
+ });
+ expect(display.pillSnapshot.pendingInteractionCount).toBe(1);
+ });
+
+ it('still completes the island on done when only a permission card was pending', () => {
+ const state = createAgentIslandState();
+ applyAgentIslandEvent(state, { sessionId: 'ask', title: 'Ask' }, statusEvent(true, 'Running'), 1_000);
+ applyAgentIslandInteractionRequest(state, { sessionId: 'ask', title: 'Ask' }, permissionRequest('r1'), 1_100);
+ applyAgentIslandEvent(state, { sessionId: 'ask', title: 'Ask' }, doneEvent(), 1_200);
+
+ const display = buildAgentIslandDisplayState(state, 1_300);
+ expect(display.sessions[0]).toMatchObject({
+ sessionId: 'ask',
+ phase: 'completed',
+ });
+ expect(display.pillSnapshot.pendingInteractionCount).toBe(0);
+ });
+
it('expands visible-session permission prompts so users can approve in the island', () => {
const state = createAgentIslandState();
setAgentIslandVisibleSession(state, 'ask', 900);
diff --git a/apps/desktop/src/main/agent-island/state.ts b/apps/desktop/src/main/agent-island/state.ts
index 46407ca2e9..27e7a77e57 100644
--- a/apps/desktop/src/main/agent-island/state.ts
+++ b/apps/desktop/src/main/agent-island/state.ts
@@ -665,12 +665,32 @@ export function applyAgentIslandEvent(
if (event.type === 'done') {
clearAssistantStream(session);
session.running = false;
- session.pendingInteractionIds.clear();
- clearPendingInteractionMetadata(session);
- session.permissionRequestId = null;
- session.permissionCanAllowForSession = false;
session.currentToolUseId = null;
session.toolDetailUntil = null;
+ // Codex ask_user / plan_review can outlive a successful turn. Permission
+ // cards belong to the dead turn and must not keep the island waiting.
+ for (const [requestId, kind] of [...session.pendingInteractionKinds.entries()]) {
+ if (kind === 'ask_user_question' || kind === 'plan_review') continue;
+ dismissPendingInteraction(state, session, requestId, now, {
+ requirePending: true,
+ pruneIfIdle: false,
+ });
+ }
+ if (session.pendingInteractionIds.size > 0) {
+ session.phase = 'needs-interaction';
+ restorePendingInteractionKind(session);
+ session.detail = session.interactionKind
+ ? (session.pendingInteractionDetails.get(
+ [...session.pendingInteractionIds][0] ?? '',
+ ) ?? session.detail)
+ : session.detail;
+ session.detailSource = 'interaction';
+ session.completedUntil = null;
+ session.lastActivityAt = now;
+ return true;
+ }
+ session.permissionRequestId = null;
+ session.permissionCanAllowForSession = false;
session.detailSource = null;
completeAgentIslandSession(state, session, now, {
suppressAttention: options.suppressCompletionAttention === true,
@@ -796,7 +816,7 @@ function dismissPendingInteraction(
session: AgentIslandSessionState,
requestId: string,
now: number,
- options: { requirePending?: boolean } = {},
+ options: { requirePending?: boolean; pruneIfIdle?: boolean } = {},
): void {
if (options.requirePending === true && !session.pendingInteractionIds.has(requestId)) return;
session.pendingInteractionIds.delete(requestId);
@@ -845,6 +865,9 @@ function dismissPendingInteraction(
}
// errorUntil 已过期但未读的 error 账本仍在,不能删 —— 岛面 TTL 只影响展示。
if (preserveErrorUnread) return;
+ // done 会先清死 turn 的 permission,再记 completed。这里若立刻 prune,
+ // 后续 complete 只能改到已脱离 state.sessions 的孤儿对象,岛面丢完成态。
+ if (options.pruneIfIdle === false) return;
state.sessions.delete(session.sessionId);
}
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index fd982d1e77..06cb5a2d07 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -2287,6 +2287,28 @@ function dismissRendererInteraction(
});
}
+function persistInteractionDecision(
+ sessionId: string,
+ persistId: string | undefined,
+ kind: PendingInteractionEntry['kind'],
+ request: RecoverableInteractionSnapshot,
+ decision: InteractionDecision | Record<string, unknown>,
+): void {
+ if (kind !== 'ask_user_question' && kind !== 'plan_review') return;
+ onInteractionResolved(
+ sessionId,
+ persistId,
+ kind,
+ request as {
+ requestId?: unknown;
+ questions?: unknown;
+ plan?: unknown;
+ planFilePath?: unknown;
+ },
+ decision as Record<string, unknown>,
+ );
+}
+
function resolvePendingInteraction(requestId: string, decision: InteractionDecision): boolean {
const resolver = pendingInteractionResolvers.get(requestId);
if (!resolver) return false;
@@ -2311,24 +2333,19 @@ function resolvePendingInteraction(requestId: string, decision: InteractionDecis
decision.behavior === 'deny' &&
(decision.dismissed === true ||
!(typeof decision.reason === 'string' && decision.reason.trim().length > 0));
- if (plannedNoFollowUpTurn) {
+ const askUserNoFollowUpTurn =
+ resolver.kind === 'ask_user_question' &&
+ (decision.kind !== 'ask_user_question' || decision.dismissed === true);
+ if (plannedNoFollowUpTurn || askUserNoFollowUpTurn) {
agentInputCoordinatorHolder?.onInteractionResolved(resolver.sessionId);
}
- // 被控端权威落库 ask/plan 的 answered/approved/revised 状态(含答案/编辑后 plan/feedback)。
- if (resolver.kind === 'ask_user_question' || resolver.kind === 'plan_review') {
- onInteractionResolved(
- resolver.sessionId,
- resolver.persistId,
- resolver.kind,
- resolver.request as {
- requestId?: unknown;
- questions?: unknown;
- plan?: unknown;
- planFilePath?: unknown;
- },
- (decision ?? {}) as Record<string, unknown>,
- );
- }
+ persistInteractionDecision(
+ resolver.sessionId,
+ resolver.persistId,
+ resolver.kind,
+ resolver.request,
+ decision,
+ );
// (Option B)ask_user_question 答完 → 即时改写该会话的 goal 目标(仅首轮澄清,controller 内 guard)。
// 连同本次问题(含选项)一并交出,让 controller 用确定性标记甄别这是不是"目标澄清问题"。
if (
@@ -2368,7 +2385,7 @@ function defaultDecisionForPending(
reason: string,
): InteractionDecision {
if (kind === 'ask_user_question') {
- return { kind: 'ask_user_question', answers: {} };
+ return { kind: 'ask_user_question', answers: {}, dismissed: true };
}
if (kind === 'plan_review') {
// dismissed: 系统性 deny(session_closed / session_aborted / 超时清理等),
@@ -2385,7 +2402,9 @@ function cleanupPendingAgentInteractionsForSession(sessionId: string, reason: st
for (const [requestId, entry] of entries) {
clearPendingInteraction(requestId);
handleAgentIslandInteractionDismissed(sessionId, requestId);
- entry.resolve(defaultDecisionForPending(entry.kind, reason));
+ const decision = defaultDecisionForPending(entry.kind, reason);
+ entry.resolve(decision);
+ persistInteractionDecision(sessionId, entry.persistId, entry.kind, entry.request, decision);
dismissRendererInteraction(entry, requestId, reason, 'deny');
}
ghostSetupInteractionBridge.cleanupForSession(
@@ -3852,11 +3871,17 @@ export function wireSessionToIpc(session: ReturnType<Maker['getSession']>): void
handleAgentIslandInteractionDismissed(session.id, data.requestId);
const entry = clearPendingInteraction(data.requestId);
if (entry) {
- entry.resolve(
- defaultDecisionForPending(
- entry.kind,
- typeof data.reason === 'string' ? data.reason : 'dismissed',
- ),
+ const decision = defaultDecisionForPending(
+ entry.kind,
+ typeof data.reason === 'string' ? data.reason : 'dismissed',
+ );
+ entry.resolve(decision);
+ persistInteractionDecision(
+ session.id,
+ entry.persistId,
+ entry.kind,
+ entry.request,
+ decision,
);
}
}
@@ -13898,31 +13923,33 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
pluginSetupResponseTarget = event.sender;
}
}
- if (!resolvePendingInteraction(requestId, decision as InteractionDecision)) {
- if (isPermissionInteractionDecision(decision)) {
- handleAgentIslandInteractionDismissedByRequestId(requestId);
- }
- // agent interaction 没命中 → 可能是 issue 确认卡(kind='issue_confirm',
- // pending 在 issueConfirmBridge 自己的 map 里)或批量改名确认卡。
- // 三边都 miss 才告警。
- if (issueConfirmBridge.resolve(requestId, decision)) return;
- if (renameSessionsConfirmBridge.resolve(requestId, decision)) return;
- if (
- orcaWorkerPermissionConfirmBridge.resolveFromIpc(requestId, decision, {
- isDeviceLink: isDeviceLinkInvoke(),
- assertTrustedSender: () => assertTrustedAppRendererEvent(event),
- })
- ) {
- return;
- }
- if (ghostGrantConfirmBridge.resolve(requestId, decision)) return;
- if (ghostSetupInteractionBridge.resolve(requestId, decision, pluginSetupResponseTarget)) {
- return;
- }
- log.warn('resolve-interaction: no pending resolver (likely already dismissed/timed out)', {
- requestId,
- });
+ if (resolvePendingInteraction(requestId, decision as InteractionDecision)) {
+ return { accepted: true };
+ }
+ if (isPermissionInteractionDecision(decision)) {
+ handleAgentIslandInteractionDismissedByRequestId(requestId);
+ }
+ // agent interaction 没命中 → 可能是 issue 确认卡(kind='issue_confirm',
+ // pending 在 issueConfirmBridge 自己的 map 里)或批量改名确认卡。
+ // 三边都 miss 才告警。
+ if (issueConfirmBridge.resolve(requestId, decision)) return { accepted: true };
+ if (renameSessionsConfirmBridge.resolve(requestId, decision)) return { accepted: true };
+ if (
+ orcaWorkerPermissionConfirmBridge.resolveFromIpc(requestId, decision, {
+ isDeviceLink: isDeviceLinkInvoke(),
+ assertTrustedSender: () => assertTrustedAppRendererEvent(event),
+ })
+ ) {
+ return { accepted: true };
}
+ if (ghostGrantConfirmBridge.resolve(requestId, decision)) return { accepted: true };
+ if (ghostSetupInteractionBridge.resolve(requestId, decision, pluginSetupResponseTarget)) {
+ return { accepted: true };
+ }
+ log.warn('resolve-interaction: no pending resolver (likely already dismissed/timed out)', {
+ requestId,
+ });
+ return { accepted: false };
},
);
diff --git a/apps/desktop/src/main/messagePersistBroadcaster.ts b/apps/desktop/src/main/messagePersistBroadcaster.ts
index 6373634402..17569e9448 100644
--- a/apps/desktop/src/main/messagePersistBroadcaster.ts
+++ b/apps/desktop/src/main/messagePersistBroadcaster.ts
@@ -1498,6 +1498,19 @@ export function onInteractionMessage(
*
* 仅 ask_user_question / plan_review 落库(permission 无 chat 消息,persistId 为空时直接跳过)。
*/
+const finalizedInteractionPersistIdsBySession = new Map<string, Set<string>>();
+
+function claimInteractionPersistId(sessionId: string, persistId: string): boolean {
+ let claimed = finalizedInteractionPersistIdsBySession.get(sessionId);
+ if (!claimed) {
+ claimed = new Set<string>();
+ finalizedInteractionPersistIdsBySession.set(sessionId, claimed);
+ }
+ if (claimed.has(persistId)) return false;
+ claimed.add(persistId);
+ return true;
+}
+
export function onInteractionResolved(
sessionId: string,
persistId: string | undefined,
@@ -1508,14 +1521,16 @@ export function onInteractionResolved(
if (!persistId) return;
const requestId = typeof request.requestId === 'string' ? request.requestId : '';
if (!requestId) return;
+ if (!claimInteractionPersistId(sessionId, persistId)) return;
if (kind === 'ask_user_question') {
const answers = (decision.answers as Record<string, string> | undefined) ?? {};
+ const cancelled = decision.dismissed === true;
enqueueWrite(`ask_user_resolved:${sessionId}:${persistId}`, () =>
updateDbMessageContent(sessionId, persistId, {
requestId,
questions: request.questions ?? [],
- status: 'answered',
+ status: cancelled ? 'cancelled' : 'answered',
answers,
}),
);
@@ -1946,6 +1961,7 @@ export function clearSessionPersistState(sessionId: string): void {
lastAssistantPersistIdBySession.delete(sessionId);
lastTopLevelAssistantPersistIdBySession.delete(sessionId);
lastAssistantTranscriptUuidBySession.delete(sessionId);
+ finalizedInteractionPersistIdsBySession.delete(sessionId);
dbAgentKindBySession.delete(sessionId);
_turnStartedAtBySession.delete(sessionId);
_turnAttemptTokenBySession.delete(sessionId);
diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.ts
index 9923baa0b4..c59a755973 100644
--- a/apps/desktop/src/preload/preload.ts
+++ b/apps/desktop/src/preload/preload.ts
@@ -5890,7 +5890,8 @@ contextBridge.exposeInMainWorld('electronAPI', {
requestId: string,
// InteractionDecision union (permission/ask_user_question/plan_review,按 kind 分支)
decision: Record<string, unknown>,
- ): Promise<void> => ipcRenderer.invoke('maker:resolve-interaction', requestId, decision),
+ ): Promise<{ accepted: boolean }> =>
+ ipcRenderer.invoke('maker:resolve-interaction', requestId, decision),
/** Local-only Secret handoff; Main verifies this is Cindy's trusted top-level frame. */
submitPluginSetupInline: (request: {
diff --git a/apps/desktop/src/renderer/__tests__/askUserDoneRace.test.ts b/apps/desktop/src/renderer/__tests__/askUserDoneRace.test.ts
new file mode 100644
index 0000000000..9632c71029
--- /dev/null
+++ b/apps/desktop/src/renderer/__tests__/askUserDoneRace.test.ts
@@ -0,0 +1,267 @@
+/**
+ * Codex ask_user 是 turn 间可存活交互:code-mode 可能在提问未答时就
+ * turn/completed。done 不得把卡片标 expired;真正放弃仍走 dismissal。
+ */
+
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('@/lib/messageService', () => ({
+ list: vi.fn(async () => []),
+ create: vi.fn(async () => ({}) as unknown),
+ updateContent: vi.fn(async () => ({}) as unknown),
+}));
+
+vi.mock('@/lib/sessionService', () => ({
+ get: vi.fn(async () => ({
+ agentKind: 'codex',
+ remoteHostId: null,
+ sdkSessionId: null,
+ fastMode: false,
+ contextTokens: 0,
+ contextWindow: 0,
+ totalCostUsd: 0,
+ })),
+ update: vi.fn(async () => ({})),
+ touchUserSend: vi.fn(async () => ({})),
+}));
+
+vi.mock('@/lib/sessionsBus', () => ({
+ emitPatch: vi.fn(),
+}));
+
+vi.mock('@/lib/userPromptStore', () => ({
+ getUserPrompt: () => '',
+}));
+
+vi.mock('@/lib/memorySettingsStore', () => ({
+ getMakerMemoryEnabled: () => true,
+}));
+
+vi.mock('@/lib/logger', () => ({
+ createLogger: () => ({
+ debug: vi.fn(),
+ info: vi.fn(),
+ warn: vi.fn(),
+ error: vi.fn(),
+ }),
+}));
+
+vi.mock('@/lib/imageRef', () => ({
+ parseUserContent: vi.fn((c: string) => ({ text: c, images: [], files: [] })),
+ stringifyUserContent: vi.fn((text: string, images = [], files = []) =>
+ JSON.stringify({ text, images, files }),
+ ),
+}));
+
+vi.mock('@/lib/composerDraftStore', () => ({
+ saveDraft: vi.fn(),
+ setRemoteOptimisticAttachmentUrls: vi.fn(),
+ plainTextToTiptapDoc: (s: string) => ({
+ type: 'doc',
+ content: [{ type: 'paragraph', content: [{ type: 'text', text: s }] }],
+ }),
+}));
+
+import { updateContent as updateMessageContent } from '@/lib/messageService';
+import { makerChatStore } from '@/lib/makerChatStore';
+
+const SESSION_ID = 'ask-user-done-race';
+
+function emptyProjection(sessionId: string) {
+ return {
+ sessionId,
+ pendingQueue: [],
+ steeringQueueClientIds: [],
+ queuePaused: false,
+ queueExpanded: false,
+ queueInteractionLocks: [],
+ queueEditLocks: [],
+ queueAbortPending: false,
+ error: null,
+ recovery: null,
+ errorRetryText: null,
+ };
+}
+
+let onEvent: ((data: unknown) => void) | undefined;
+let onInteractionRequest: ((data: unknown) => void) | undefined;
+let onInteractionDismissed: ((data: unknown) => void) | undefined;
+
+function installElectronBridge(): void {
+ onEvent = undefined;
+ onInteractionRequest = undefined;
+ onInteractionDismissed = undefined;
+ const w = globalThis as unknown as { window: Record<string, unknown> };
+ w.window = {
+ electronAPI: {
+ maker: {
+ input: {
+ getProjection: vi.fn(async (sessionId: string) => emptyProjection(sessionId)),
+ enqueue: vi.fn(async (sessionId: string) => emptyProjection(sessionId)),
+ },
+ onInputProjection: vi.fn(() => vi.fn()),
+ onEvent: (cb: (data: unknown) => void) => {
+ onEvent = cb;
+ return vi.fn();
+ },
+ onStatusChanged: vi.fn(() => vi.fn()),
+ onInteractionRequest: (cb: (data: unknown) => void) => {
+ onInteractionRequest = cb;
+ return vi.fn();
+ },
+ onInteractionDismissed: (cb: (data: unknown) => void) => {
+ onInteractionDismissed = cb;
+ return vi.fn();
+ },
+ send: vi.fn(async () => ({ accepted: true })),
+ generateTitle: vi.fn(async () => ({ title: 't' })),
+ getPendingInteractions: vi.fn(async () => []),
+ setPlanMode: vi.fn(async () => {}),
+ resolveInteraction: vi.fn(async () => ({ accepted: true })),
+ abortSession: vi.fn(async () => {}),
+ closeSession: vi.fn(async () => {}),
+ listActive: vi.fn(async () => []),
+ },
+ localDb: {
+ messages: {
+ onCreated: vi.fn(() => vi.fn()),
+ },
+ },
+ },
+ };
+}
+
+function emitAskUserRequest(requestId: string): void {
+ onInteractionRequest?.({
+ sessionId: SESSION_ID,
+ request: {
+ kind: 'ask_user_question',
+ requestId,
+ questions: [{ question: '桌面版这次要采用哪种范围?', header: '词典编辑' }],
+ },
+ persistId: `persist-${requestId}`,
+ });
+}
+
+function emitDone(source: 'codex' | 'claude-code'): void {
+ onEvent?.({
+ sessionId: SESSION_ID,
+ event: {
+ type: 'done',
+ source,
+ data: { type: 'task_complete', raw: { id: 'turn-1', status: 'completed' } },
+ },
+ });
+}
+
+function pendingAskStatuses(): string[] {
+ return makerChatStore
+ .getSnapshot(SESSION_ID)
+ .messages.filter((m) => m.role === 'ask_user')
+ .map((m) => m.askUserStatus ?? 'unknown');
+}
+
+describe('ask_user 与 done 的时序', () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ installElectronBridge();
+ makerChatStore.__teardownGlobalListeners();
+ makerChatStore.purgeSession(SESSION_ID);
+ makerChatStore.initGlobalListeners();
+ });
+
+ afterEach(() => {
+ makerChatStore.__teardownGlobalListeners();
+ makerChatStore.purgeSession(SESSION_ID);
+ vi.restoreAllMocks();
+ });
+
+ it('codex:done 不吞掉未答提问卡', () => {
+ makerChatStore.setSessionRuntime(SESSION_ID, { agentKind: 'codex' });
+ emitAskUserRequest('ask-1');
+ expect(makerChatStore.getSnapshot(SESSION_ID).pendingAskUser?.requestId).toBe('ask-1');
+
+ emitDone('codex');
+
+ const snap = makerChatStore.getSnapshot(SESSION_ID);
+ expect(snap.pendingAskUser?.requestId).toBe('ask-1');
+ expect(pendingAskStatuses()).toEqual(['pending']);
+ });
+
+ it('claude:turn 结束仍将 pending 提问卡标过期', () => {
+ makerChatStore.setSessionRuntime(SESSION_ID, { agentKind: 'claude-code' });
+ emitAskUserRequest('ask-2');
+ emitDone('claude-code');
+
+ const snap = makerChatStore.getSnapshot(SESSION_ID);
+ expect(snap.pendingAskUser).toBeNull();
+ expect(pendingAskStatuses()).toEqual(['expired']);
+ });
+
+ it('codex:main 的 dismissal 仍能把存活提问卡标过期', () => {
+ makerChatStore.setSessionRuntime(SESSION_ID, { agentKind: 'codex' });
+ emitAskUserRequest('ask-3');
+ emitDone('codex');
+ expect(makerChatStore.getSnapshot(SESSION_ID).pendingAskUser?.requestId).toBe('ask-3');
+
+ onInteractionDismissed?.({
+ sessionId: SESSION_ID,
+ requestId: 'ask-3',
+ reason: 'session_aborted',
+ resolvedAs: 'deny',
+ });
+
+ const snap = makerChatStore.getSnapshot(SESSION_ID);
+ expect(snap.pendingAskUser).toBeNull();
+ expect(pendingAskStatuses()).toEqual(['expired']);
+ });
+
+ it('codex:答题只走 resolveInteraction,不本地落库', async () => {
+ makerChatStore.setSessionRuntime(SESSION_ID, { agentKind: 'codex' });
+ emitAskUserRequest('ask-4');
+ emitDone('codex');
+ makerChatStore.answerUserQuestion(SESSION_ID, 'ask-4', {
+ '桌面版这次要采用哪种范围?': '完整编辑(推荐)',
+ });
+ await Promise.resolve();
+ expect(updateMessageContent).not.toHaveBeenCalled();
+ const resolveInteraction = (globalThis as unknown as {
+ window: { electronAPI: { maker: { resolveInteraction: ReturnType<typeof vi.fn> } } };
+ }).window.electronAPI.maker.resolveInteraction;
+ expect(resolveInteraction).toHaveBeenCalledWith('ask-4', {
+ kind: 'ask_user_question',
+ answers: { '桌面版这次要采用哪种范围?': '完整编辑(推荐)' },
+ });
+ });
+
+ it('codex:输家乐观答案会被赢家 dismissal 覆盖', () => {
+ makerChatStore.setSessionRuntime(SESSION_ID, { agentKind: 'codex' });
+ emitAskUserRequest('ask-5');
+ emitDone('codex');
+ makerChatStore.answerUserQuestion(SESSION_ID, 'ask-5', {
+ '桌面版这次要采用哪种范围?': '只展示和搜索',
+ });
+ expect(makerChatStore.getSnapshot(SESSION_ID).messages.find((m) => m.role === 'ask_user'))
+ .toMatchObject({
+ askUserStatus: 'answered',
+ askUserAnswers: { '桌面版这次要采用哪种范围?': '只展示和搜索' },
+ });
+
+ onInteractionDismissed?.({
+ sessionId: SESSION_ID,
+ requestId: 'ask-5',
+ reason: 'resolved',
+ resolvedAs: 'deny',
+ decision: {
+ kind: 'ask_user_question',
+ answers: { '桌面版这次要采用哪种范围?': '完整编辑(推荐)' },
+ },
+ });
+
+ expect(makerChatStore.getSnapshot(SESSION_ID).messages.find((m) => m.role === 'ask_user'))
+ .toMatchObject({
+ askUserStatus: 'answered',
+ askUserAnswers: { '桌面版这次要采用哪种范围?': '完整编辑(推荐)' },
+ });
+ });
+});
diff --git a/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts b/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts
index 9cd2c9d087..0571dcf8ee 100644
--- a/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts
+++ b/apps/desktop/src/renderer/__tests__/deviceLinkInteractionScenarios.test.ts
@@ -1325,16 +1325,26 @@ describe('远程交互接线不变式', () => {
expect(body).toContain('resolver.resolve(');
expect(body).toContain('dismissRendererInteraction(');
// F1:resolve 后被控端权威落库 ask/plan answered 状态。
- expect(body).toContain('onInteractionResolved(');
+ expect(body).toContain('persistInteractionDecision(');
+ const persistStart = src.indexOf('function persistInteractionDecision');
+ expect(persistStart).toBeGreaterThan(-1);
+ const persistEnd = src.indexOf('\n}', persistStart);
+ expect(persistEnd).toBeGreaterThan(-1);
+ expect(src.slice(persistStart, persistEnd)).toContain('onInteractionResolved(');
});
// ── 全面审查批量修复(F1–F7)接线不变式:每条都是真机踩过 / 审查确认的「会话级直连未路由 /
// 状态变更未广播收敛」家族残留,锁住防回归 ──────────────────────────────────────────
const mainSrc = (rel: string) => readFileSync(resolve(__dirname, '../../main', rel), 'utf8');
- it('F1: makerChatStore 的 ask/plan answered 写库远程跳过(被控端权威落库,避免 dead write)', () => {
+ it('F1: ask 本地远程都只由 main 落库;plan answered 写库仍远程跳过', () => {
const src = read('lib/makerChatStore.ts');
- expect(src).toContain('if (askMsg && !isRemoteSession(sessionId))');
+ 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))');
});
diff --git a/apps/desktop/src/renderer/lib/makerChatStore.ts b/apps/desktop/src/renderer/lib/makerChatStore.ts
index 6bc40d3c96..e3051bc4af 100644
--- a/apps/desktop/src/renderer/lib/makerChatStore.ts
+++ b/apps/desktop/src/renderer/lib/makerChatStore.ts
@@ -5305,11 +5305,19 @@ export function handleStreamEvent(
// Claude 的 plan_review 发生在 turn 内(ExitPlanMode 阻塞中),done 必然晚于决策,
// 清扫语义不变。真正的放弃路径(abort/close)由 main 的 interaction dismissal
// (permission_dismissed 事件)负责标 expired,不依赖这里。
+ //
+ // Codex ask_user 同款:code-mode 可能在提问 RPC 未决时就 turn/completed。
+ // 卡片必须跨 done 存活,等用户回答后走 detached continuation。
const keepPlanReviewAcrossDone = state.agentKind === 'codex';
+ const keepAskUserAcrossDone = state.agentKind === 'codex';
const cleanedMessages = finalized.messages.map((m) => {
let next = m;
if (m.isStreaming) next = { ...next, isStreaming: false };
- if (m.role === 'ask_user' && m.askUserStatus === 'pending') {
+ if (
+ !keepAskUserAcrossDone &&
+ m.role === 'ask_user' &&
+ m.askUserStatus === 'pending'
+ ) {
next = { ...next, askUserStatus: 'expired' as const };
}
if (
@@ -5359,14 +5367,14 @@ export function handleStreamEvent(
activeTurnRetryText: null,
errorRetryText: finalized.error ? finalized.errorRetryText : null,
pendingPermission: null,
- pendingAskUser: null,
+ pendingAskUser: keepAskUserAcrossDone ? state.pendingAskUser : null,
continuationTurnClientId: null,
// F-AUQ-MIN-5: viewerState lives with pendingAskUser — when the
// pending question is gone, reset so the next one starts expanded.
- askUserViewerState: 'expanded',
+ askUserViewerState: keepAskUserAcrossDone ? state.askUserViewerState : 'expanded',
// F-AUQ-DRAFT: pending question gone → in-progress wizard draft is
// meaningless, drop it so the next question starts clean.
- askUserDraft: null,
+ askUserDraft: keepAskUserAcrossDone ? state.askUserDraft : null,
pendingPlanReview: keepPlanReviewAcrossDone ? state.pendingPlanReview : null,
pendingIssueConfirm: null,
pendingRenameSessionsConfirm: null,
@@ -5690,22 +5698,27 @@ export function handleStreamEvent(
),
};
}
- if (state.pendingAskUser?.requestId === data.requestId) {
+ if (
+ state.pendingAskUser?.requestId === data.requestId ||
+ state.messages.some((m) => m.role === 'ask_user' && m.askUserRequestId === data.requestId)
+ ) {
// resolved + answers → 翻成 answered 并填答案(与答题端 answerUserQuestion 同款 reply / answers,
// 卡片据此渲染 ✓ 选项);否则(真·放弃)标 expired。
+ // 多窗口输家可能已经乐观写成 answered;仍要用赢家决策覆盖,不能只认 pending。
const answers = resolved?.answers as Record<string, string> | undefined;
- const askUserReply = answers ? formatAskUserReply(answers) : '';
+ const dismissed = resolved?.dismissed === true;
+ const askUserReply = answers && !dismissed ? formatAskUserReply(answers) : '';
return {
...state,
- pendingAskUser: null,
- askUserViewerState: 'expanded',
- // F-AUQ-DRAFT: question dismissed → drop draft.
- askUserDraft: null,
+ pendingAskUser:
+ state.pendingAskUser?.requestId === data.requestId ? null : state.pendingAskUser,
+ askUserViewerState:
+ state.pendingAskUser?.requestId === data.requestId ? 'expanded' : state.askUserViewerState,
+ askUserDraft:
+ state.pendingAskUser?.requestId === data.requestId ? null : state.askUserDraft,
messages: state.messages.map((m) =>
- m.role === 'ask_user' &&
- m.askUserRequestId === data.requestId &&
- m.askUserStatus === 'pending'
- ? answers
+ m.role === 'ask_user' && m.askUserRequestId === data.requestId
+ ? answers && !dismissed
? {
...m,
askUserStatus: 'answered' as const,
@@ -13871,11 +13884,6 @@ function answerUserQuestion(
// Build a human-readable reply summary
const replySummary = formatAskUserReply(answers);
- // Find the clientId for persistence update
- const askMsg = state.messages.find(
- (m) => m.askUserRequestId === requestId && m.askUserStatus === 'pending',
- );
-
// Update message to answered + clear pendingAskUser
setState(sessionId, (s) => ({
...s,
@@ -13897,21 +13905,8 @@ function answerUserQuestion(
),
}));
- // F7.6: Persist answered state via PATCH API。
- // device-link 远程会话:被控端在 RESOLVE_INTERACTION 里权威落库(onInteractionResolved),
- // 控制端再写就是写自己的空库(dead write + 错误日志)→ 远程跳过,只本机会话走这条。
- if (askMsg && !isRemoteSession(sessionId)) {
- messageService
- .updateContent(sessionId, askMsg.clientId, {
- requestId,
- questions: askMsg.askUserQuestions ?? null,
- status: 'answered',
- answers,
- })
- .catch((err) => log.error('Failed to persist ask_user answered state:', err));
- }
-
- // Send to maker (InteractionDecision kind: 'ask_user_question')
+ // 落库只走 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));
diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.ts
index b3ef948712..cc25cb2b68 100644
--- a/apps/desktop/src/renderer/vite-env.d.ts
+++ b/apps/desktop/src/renderer/vite-env.d.ts
@@ -5419,7 +5419,10 @@ interface ElectronAPI {
};
/** Resolve a pending interaction (permission / ask_user_question / plan_review). */
- resolveInteraction: (requestId: string, decision: Record<string, unknown>) => Promise<void>;
+ resolveInteraction: (
+ requestId: string,
+ decision: Record<string, unknown>,
+ ) => Promise<{ accepted: boolean }>;
/** Submit one inline plugin Secret through the local trusted-frame-only IPC. */
submitPluginSetupInline: (request: {
diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.ts
index fbba0c5cee..868adcee1a 100644
--- a/packages/maker-core/src/agents/codex/index.test.ts
+++ b/packages/maker-core/src/agents/codex/index.test.ts
@@ -16835,13 +16835,472 @@ describe('CodexAgent MCP thread context hooks', () => {
success: false,
contentItems: [{ type: 'inputText', text: `Request cancelled: ${reason}` }],
});
+ if (lifecycle !== 'turn completion') {
+ await waitForExpectation(() => {
+ expect(debug).toHaveBeenCalledWith(
+ 'joined duplicate same-turn user input request cancelled',
+ { requestId: 'req-joined', turnId: 'turn-1' },
+ );
+ });
+ }
+ if (lifecycle !== 'session close') await handle.close();
+ });
+
+ function askUserTurnStartCalls(host: ReturnType<typeof installFakeHost>) {
+ return host.request.mock.calls.filter(([method]) => method === Method.TurnStart);
+ }
+
+ async function collectAgentEvents(handle: AgentSessionHandle): Promise<AgentEvent[]> {
+ const events: AgentEvent[] = [];
+ void (async () => {
+ for await (const event of handle.events()) {
+ events.push(event);
+ }
+ })();
+ return events;
+ }
+
+ 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);
+ const handle = await agent.startSession({
+ sessionId: 'session-ask-user-detached-continue',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ });
+ const handlers = host.getThreadHandlers();
+ if (!handlers?.dynamicToolCall) throw new Error('expected dynamicToolCall');
+ const ownerDecision = deferred<InteractionDecision>();
+ handle.setInteractionResolver(async () => ownerDecision.promise);
+ const events = await collectAgentEvents(handle);
+
+ const resultPromise = handlers.dynamicToolCall({
+ threadId: 'start-thread-id',
+ turnId: 'turn-1',
+ callId: 'item-ask',
+ namespace: 'cindy',
+ tool: 'ask_user_question',
+ arguments: {
+ questions: [{
+ id: 'q1',
+ header: '词典编辑',
+ question: '桌面版这次要采用哪种范围?',
+ options: [{ label: '完整编辑(推荐)' }],
+ }],
+ },
+ }, { requestId: 'req-ask' });
+
+ handlers.turnCompleted?.({
+ threadId: 'start-thread-id',
+ turn: { id: 'turn-1', status: 'completed' },
+ });
+
+ await expect(resultPromise).resolves.toEqual({
+ success: false,
+ contentItems: [{ type: 'inputText', text: 'Request cancelled: turn_completed' }],
+ });
await waitForExpectation(() => {
- expect(debug).toHaveBeenCalledWith(
- 'joined duplicate same-turn user input request cancelled',
- { requestId: 'req-joined', turnId: 'turn-1' },
- );
+ expect(events.some((event) => event.type === 'done')).toBe(true);
});
- if (lifecycle !== 'session close') await handle.close();
+ expect(events.filter((event) => event.type === 'interaction_dismissed')).toEqual([]);
+ expect(askUserTurnStartCalls(host)).toHaveLength(0);
+
+ ownerDecision.resolve({
+ kind: 'ask_user_question',
+ answers: { '桌面版这次要采用哪种范围?': '完整编辑(推荐)' },
+ });
+
+ await vi.waitFor(() => {
+ expect(askUserTurnStartCalls(host)).toHaveLength(1);
+ });
+ const [, params] = askUserTurnStartCalls(host)[0] as [string, {
+ input: Array<{ type: string; text?: string }>;
+ }];
+ expect(params.input[0]?.text).toContain('The user answered the pending question.');
+ expect(params.input[0]?.text).toContain('完整编辑(推荐)');
+ expect(params.input[0]?.text).toContain('Continue from the previous turn.');
+
+ ownerDecision.resolve({
+ kind: 'ask_user_question',
+ answers: { '桌面版这次要采用哪种范围?': '只展示和搜索' },
+ });
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ expect(askUserTurnStartCalls(host)).toHaveLength(1);
+ await handle.close();
+ });
+
+ it('dismisses superseded same-turn ask_user requests and continues only the last card', async () => {
+ const agent = new CodexAgent(createDeps());
+ const host = installFakeHost(agent);
+ const handle = await agent.startSession({
+ sessionId: 'session-ask-user-supersede',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ });
+ const handlers = host.getThreadHandlers();
+ if (!handlers?.dynamicToolCall) throw new Error('expected dynamicToolCall');
+ const firstDecision = deferred<InteractionDecision>();
+ 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;
+ throw new Error(`unexpected request ${req.requestId}`);
+ });
+ const events = await collectAgentEvents(handle);
+
+ void handlers.dynamicToolCall({
+ threadId: 'start-thread-id',
+ turnId: 'turn-1',
+ callId: 'item-ask-first',
+ namespace: 'cindy',
+ tool: 'ask_user_question',
+ arguments: { questions: [{ question: 'First question?' }] },
+ }, { requestId: 'req-ask-first' });
+ void handlers.dynamicToolCall({
+ threadId: 'start-thread-id',
+ turnId: 'turn-1',
+ callId: 'item-ask-last',
+ namespace: 'cindy',
+ tool: 'ask_user_question',
+ arguments: { questions: [{ question: 'Last question?' }] },
+ }, { requestId: 'req-ask-last' });
+
+ handlers.turnCompleted?.({
+ threadId: 'start-thread-id',
+ turn: { id: 'turn-1', status: 'completed' },
+ });
+ await waitForExpectation(() => {
+ expect(events.some((event) => (
+ event.type === 'interaction_dismissed'
+ && (event.data as { requestId?: string }).requestId === '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'
+ ))).toEqual([]);
+
+ firstDecision.resolve({
+ kind: 'ask_user_question',
+ answers: { 'First question?': 'stale' },
+ });
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ expect(askUserTurnStartCalls(host)).toHaveLength(0);
+
+ lastDecision.resolve({
+ kind: 'ask_user_question',
+ answers: { 'Last question?': 'visible' },
+ });
+ await vi.waitFor(() => {
+ expect(askUserTurnStartCalls(host)).toHaveLength(1);
+ });
+ const [, params] = askUserTurnStartCalls(host)[0] as [string, {
+ input: Array<{ type: string; text?: string }>;
+ }];
+ expect(params.input[0]?.text).toContain('Last question?');
+ expect(params.input[0]?.text).toContain('visible');
+ expect(params.input[0]?.text).not.toContain('First question?');
+ await handle.close();
+ });
+
+ it('does not start a continuation when the user answers before turn completion', async () => {
+ const agent = new CodexAgent(createDeps());
+ const host = installFakeHost(agent);
+ const handle = await agent.startSession({
+ sessionId: 'session-ask-user-answer-before-complete',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ });
+ const handlers = host.getThreadHandlers();
+ if (!handlers?.requestUserInput) throw new Error('expected requestUserInput');
+ const ownerDecision = deferred<InteractionDecision>();
+ handle.setInteractionResolver(async () => ownerDecision.promise);
+
+ const resultPromise = handlers.requestUserInput({
+ threadId: 'start-thread-id',
+ turnId: 'turn-1',
+ itemId: 'item-native',
+ questions: [{
+ id: 'native-q1',
+ header: 'Question',
+ question: 'Pick one',
+ isOther: false,
+ isSecret: false,
+ options: [{ label: 'A', description: null }],
+ }],
+ }, { requestId: 'req-native' });
+
+ ownerDecision.resolve({
+ kind: 'ask_user_question',
+ answers: { 'Pick one': 'A' },
+ });
+ await expect(resultPromise).resolves.toEqual({
+ answers: { 'native-q1': { answers: ['A'] } },
+ });
+
+ handlers.turnCompleted?.({
+ threadId: 'start-thread-id',
+ turn: { id: 'turn-1', status: 'completed' },
+ });
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ expect(askUserTurnStartCalls(host)).toHaveLength(0);
+ await handle.close();
+ });
+
+ it('still dismisses ask_user and does not continue after a failed turn', async () => {
+ const agent = new CodexAgent(createDeps());
+ const host = installFakeHost(agent);
+ const handle = await agent.startSession({
+ sessionId: 'session-ask-user-failed-turn',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ });
+ const handlers = host.getThreadHandlers();
+ if (!handlers?.dynamicToolCall) throw new Error('expected dynamicToolCall');
+ const ownerDecision = deferred<InteractionDecision>();
+ handle.setInteractionResolver(async () => ownerDecision.promise);
+ const events = await collectAgentEvents(handle);
+
+ const resultPromise = handlers.dynamicToolCall({
+ threadId: 'start-thread-id',
+ turnId: 'turn-1',
+ callId: 'item-ask-fail',
+ namespace: 'cindy',
+ tool: 'ask_user_question',
+ arguments: {
+ questions: [{ question: 'Pick one' }],
+ },
+ }, { requestId: 'req-ask-fail' });
+
+ handlers.turnCompleted?.({
+ threadId: 'start-thread-id',
+ turn: { id: 'turn-1', status: 'failed' },
+ });
+
+ await expect(resultPromise).resolves.toEqual({
+ success: false,
+ contentItems: [{ type: 'inputText', text: 'Request cancelled: turn_failed' }],
+ });
+ await waitForExpectation(() => {
+ expect(events.some((event) => (
+ event.type === 'interaction_dismissed'
+ && (event.data as { requestId?: string }).requestId === 'req-ask-fail'
+ ))).toBe(true);
+ });
+
+ ownerDecision.resolve({
+ kind: 'ask_user_question',
+ answers: { 'Pick one': 'A' },
+ });
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ expect(askUserTurnStartCalls(host)).toHaveLength(0);
+ await handle.close();
+ });
+
+ it('emits a terminal event when the detached ask_user continuation cannot start', async () => {
+ const agent = new CodexAgent(createDeps());
+ const host = installFakeHost(agent, (method) => {
+ if (method === Method.TurnStart) {
+ throw new Error('Codex send cannot be accepted: stale host before turn/start');
+ }
+ return undefined;
+ });
+ const handle = await agent.startSession({
+ sessionId: 'session-ask-user-continue-start-fails',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ });
+ const handlers = host.getThreadHandlers();
+ if (!handlers?.dynamicToolCall) throw new Error('expected dynamicToolCall');
+ const ownerDecision = deferred<InteractionDecision>();
+ handle.setInteractionResolver(async () => ownerDecision.promise);
+ const events = await collectAgentEvents(handle);
+
+ void handlers.dynamicToolCall({
+ threadId: 'start-thread-id',
+ turnId: 'turn-1',
+ callId: 'item-ask-fail-start',
+ namespace: 'cindy',
+ tool: 'ask_user_question',
+ arguments: { questions: [{ question: 'Pick one' }] },
+ }, { requestId: 'req-ask-fail-start' });
+
+ handlers.turnCompleted?.({
+ threadId: 'start-thread-id',
+ turn: { id: 'turn-1', status: 'completed' },
+ });
+ await waitForExpectation(() => {
+ expect(events.some((event) => event.type === 'done')).toBe(true);
+ });
+
+ ownerDecision.resolve({
+ kind: 'ask_user_question',
+ answers: { 'Pick one': 'A' },
+ });
+
+ await waitForExpectation(() => {
+ expect(events.some((event) => (
+ event.type === 'error'
+ && String((event.data as { message?: string }).message ?? '').includes(
+ 'ask_user continuation turn failed to start',
+ )
+ ))).toBe(true);
+ });
+ await handle.close();
+ });
+
+ it('starts a continuation when every detached question is skipped', async () => {
+ const agent = new CodexAgent(createDeps());
+ const host = installFakeHost(agent);
+ const handle = await agent.startSession({
+ sessionId: 'session-ask-user-skip-continue',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ });
+ const handlers = host.getThreadHandlers();
+ if (!handlers?.dynamicToolCall) throw new Error('expected dynamicToolCall');
+ const ownerDecision = deferred<InteractionDecision>();
+ handle.setInteractionResolver(async () => ownerDecision.promise);
+
+ void handlers.dynamicToolCall({
+ threadId: 'start-thread-id',
+ turnId: 'turn-1',
+ callId: 'item-ask-skip',
+ namespace: 'cindy',
+ tool: 'ask_user_question',
+ arguments: { questions: [{ question: 'Pick one' }] },
+ }, { requestId: 'req-ask-skip' });
+
+ handlers.turnCompleted?.({
+ threadId: 'start-thread-id',
+ turn: { id: 'turn-1', status: 'completed' },
+ });
+ await waitForExpectation(() => {
+ expect(askUserTurnStartCalls(host)).toHaveLength(0);
+ });
+
+ ownerDecision.resolve({
+ kind: 'ask_user_question',
+ answers: { 'Pick one': '' },
+ });
+
+ await vi.waitFor(() => {
+ expect(askUserTurnStartCalls(host)).toHaveLength(1);
+ });
+ const [, params] = askUserTurnStartCalls(host)[0] as [string, {
+ input: Array<{ type: string; text?: string }>;
+ }];
+ expect(params.input[0]?.text).toContain('The user answered the pending question.');
+ expect(params.input[0]?.text).toContain('(no answer)');
+ await handle.close();
+ });
+
+ it('does not start a continuation when a detached resolver fails', async () => {
+ const agent = new CodexAgent(createDeps());
+ const host = installFakeHost(agent);
+ const handle = await agent.startSession({
+ sessionId: 'session-ask-user-resolver-error',
+ model: 'gpt-5.4',
+ workingDir: '/repo',
+ });
+ const handlers = host.getThreadHandlers();
+ if (!handlers?.dynamicToolCall) throw new Error('expected dynamicToolCall');
+ const ownerDecision = deferred<InteractionDecision>();
+ handle.setInteractionResolver(async () => ownerDecision.promise);
+
+ void handlers.dynamicToolCall({
+ threadId: 'start-thread-id',
+ turnId: 'turn-1',
+ callId: 'item-ask-resolver-error',
+ namespace: 'cindy',
+ tool: 'ask_user_question',
+ arguments: { questions: [{ question: 'Pick one' }] },
+ }, { requestId: 'req-ask-resolver-error' });
+
+ handlers.turnCompleted?.({
+ threadId: 'start-thread-id',
+ turn: { id: 'turn-1', status: 'completed' },
+ });
+ await waitForExpectation(() => {
+ expect(askUserTurnStartCalls(host)).toHaveLength(0);
+ });
+
+ ownerDecision.reject(new Error('interaction resolver failed'));
+ await new Promise((resolve) => setTimeout(resolve, 20));
+ expect(askUserTurnStartCalls(host)).toHaveLength(0);
+ await handle.close();
+ });
+
+ it('keeps the originating turn auto-review intent on detached continuation', async () => {
+ const seenIntents: string[] = [];
+ const reviewAutoPermissionAction = vi.fn<AutoReviewDelegate>(async (request) => {
+ seenIntents.push(request.userIntent);
+ return { verdict: 'allow' as const };
+ });
+ const agent = new CodexAgent(createDeps({}, { reviewAutoPermissionAction }));
+ 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-ask-user-intent-snapshot',
+ model: 'gpt-5.5',
+ providerId: 'openai',
+ workingDir: '/repo',
+ permissionMode: 'auto',
+ });
+ const handlers = host.getThreadHandlers();
+ if (!handlers?.dynamicToolCall || !handlers.commandExecutionApproval) {
+ throw new Error('expected ask and approval handlers');
+ }
+ const ownerDecision = deferred<InteractionDecision>();
+ handle.setInteractionResolver(async () => ownerDecision.promise);
+
+ await handle.send({ type: 'user', content: 'ORIGINAL_INTENT_MARKER' });
+ void handlers.dynamicToolCall({
+ threadId: 'start-thread-id',
+ turnId: 'turn-1',
+ callId: 'item-ask-intent',
+ namespace: 'cindy',
+ tool: 'ask_user_question',
+ arguments: { questions: [{ question: 'Pick one' }] },
+ }, { requestId: 'req-ask-intent' });
+ handlers.turnCompleted?.({
+ threadId: 'start-thread-id',
+ turn: { id: 'turn-1', status: 'completed' },
+ });
+
+ await handle.send({ type: 'user', content: 'DRIFT_INTENT_MARKER' });
+ handlers.turnCompleted?.({
+ threadId: 'start-thread-id',
+ turn: { id: 'turn-2', status: 'completed' },
+ });
+
+ ownerDecision.resolve({
+ kind: 'ask_user_question',
+ answers: { 'Pick one': 'Keep going' },
+ });
+ await vi.waitFor(() => {
+ expect(askUserTurnStartCalls(host)).toHaveLength(3);
+ });
+
+ await handlers.commandExecutionApproval({
+ threadId: 'start-thread-id',
+ turnId: 'turn-3',
+ itemId: 'cmd-intent',
+ approvalId: 'approval-intent',
+ command: 'npm install express',
+ cwd: '/repo',
+ });
+ expect(seenIntents.at(-1)).toContain('ORIGINAL_INTENT_MARKER');
+ expect(seenIntents.at(-1)).not.toContain('DRIFT_INTENT_MARKER');
+ await handle.close();
});
it('updates the registered vendorOptions object by reference on setVendorOptions', async () => {
diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.ts
index cf88201891..06df5ba3b9 100644
--- a/packages/maker-core/src/agents/codex/index.ts
+++ b/packages/maker-core/src/agents/codex/index.ts
@@ -960,6 +960,32 @@ function hasSubmittedUserInput(answersByPosition: readonly (readonly string[])[]
);
}
+function formatAskUserContinuationMessage(
+ questions: readonly ToolRequestUserInputQuestion[],
+ answers: Record<string, string>,
+): string {
+ const lines = [ASK_USER_CONTINUATION_INTRO, ''];
+ for (const question of questions) {
+ const raw = answers[question.question] ?? answers[question.header] ?? answers[question.id] ?? '';
+ lines.push(`Q: ${question.question}`);
+ lines.push(`A: ${raw.trim() || '(no answer)'}`);
+ lines.push('');
+ }
+ lines.push(ASK_USER_CONTINUATION_OUTRO);
+ return lines.join('\n');
+}
+
+interface LiveAskUserRequest {
+ requestId: string;
+ turnId: string | null;
+ questions: ToolRequestUserInputQuestion[];
+ detached: boolean;
+ continuationStarted: boolean;
+ permissionPolicy: TurnPermissionPolicy | null;
+ capabilitySelectionText: string;
+ autoReviewIntent: string;
+}
+
function normalizeServiceTier(serviceTier: ServiceTier | null | undefined): ServiceTier | null | undefined {
return serviceTier === 'priority' ? 'fast' : serviceTier;
}
@@ -1124,6 +1150,8 @@ function codexPermissionStrictnessRank(mode: PermissionMode): number {
// (codex-rs/tui/src/chatwidget/plan_implementation.rs 的
// PLAN_IMPLEMENTATION_CODING_MESSAGE), 模型对这句有训练分布上的既有理解。
const PLAN_IMPLEMENTATION_MESSAGE = 'Implement the plan.';
+const ASK_USER_CONTINUATION_INTRO = 'The user answered the pending question.';
+const ASK_USER_CONTINUATION_OUTRO = 'Continue from the previous turn. Do not ask the same question again.';
const CODEX_INHERITED_CAPABILITY_SELECTION = Symbol('codexInheritedCapabilitySelection');
// 计划实施/修订 turn 的**审查意图**:这些 turn 的 message 是固定内部串('Implement the plan.'),
// 直接拿它当 review intent 会让灰区 reviewer 完全看不到用户原始请求与获批计划(codex 报)。
@@ -5503,6 +5531,7 @@ export class CodexAgent extends BaseAgent {
pendingForTurn: Map<string, PendingUserInputInteraction>;
pendingInteraction: PendingUserInputInteraction;
}>();
+ const liveAskUserByRequestId = new Map<string, LiveAskUserRequest>();
registerRootCodexMcpContext();
let mcpElicitationSeq = 0;
@@ -5520,7 +5549,9 @@ export class CodexAgent extends BaseAgent {
function defaultInteractionDecision(req: InteractionRequest, reason: string): InteractionDecision {
if (req.kind === 'ask_user_question') {
- return { kind: 'ask_user_question', answers: {} };
+ // dismissed: 系统性取消(无 resolver / resolver 抛错)。空 answers 是用户 Skip,
+ // 不能和系统兜底长得一样,否则 detach 后会误开 continuation。
+ return { kind: 'ask_user_question', answers: {}, dismissed: true };
}
if (req.kind === 'plan_review') {
// dismissed: 系统性 deny(无 resolver / resolver 抛错), reason 是系统代码,
@@ -5904,6 +5935,19 @@ export class CodexAgent extends BaseAgent {
const requestId = String(meta.requestId);
if (dismissed.has(requestId)) continue;
dismissed.add(requestId);
+ liveAskUserByRequestId.delete(requestId);
+ forgetPendingUserInputRequest(requestId);
+ eventQueue.push({
+ type: 'interaction_dismissed',
+ data: { requestId, reason, resolvedAs: 'deny' },
+ source: 'codex',
+ });
+ }
+ for (const [requestId, live] of liveAskUserByRequestId) {
+ if (!predicate({ threadId, turnId: live.turnId })) continue;
+ liveAskUserByRequestId.delete(requestId);
+ if (dismissed.has(requestId)) continue;
+ dismissed.add(requestId);
forgetPendingUserInputRequest(requestId);
eventQueue.push({
type: 'interaction_dismissed',
@@ -5917,6 +5961,80 @@ export class CodexAgent extends BaseAgent {
dismissPendingUserInput(reason, (meta) => meta.turnId === turnId);
}
+ function detachPendingAskUserForSuccessfulTurn(turnId: string): void {
+ const cancelledUserInput = userInputBroker.cancelWhere(
+ (meta) => meta.turnId === turnId,
+ { answers: {} },
+ );
+ const cancelledDynamicTools = dynamicToolBroker.cancelWhere(
+ (meta) => meta.turnId === turnId,
+ cancelledDynamicToolResponse('turn_completed'),
+ );
+ // Desktop 只有一个 pendingAskUser。同 turn 多个提问只留最后一张,
+ // 否则被盖住的 resolver 会一直占着 hasPendingAgentInteraction。
+ const lives = [...liveAskUserByRequestId.values()].filter((live) => live.turnId === turnId);
+ const keep = lives.at(-1) ?? null;
+ if (keep) keep.detached = true;
+ const keepUiRequestIds = new Set(keep ? [keep.requestId] : []);
+ const dismissed = new Set<string>();
+ const dismiss = (requestId: string, reason: string): void => {
+ if (keepUiRequestIds.has(requestId) || dismissed.has(requestId)) return;
+ dismissed.add(requestId);
+ liveAskUserByRequestId.delete(requestId);
+ forgetPendingUserInputRequest(requestId);
+ eventQueue.push({
+ type: 'interaction_dismissed',
+ data: { requestId, reason, resolvedAs: 'deny' },
+ source: 'codex',
+ });
+ };
+ for (const live of lives) {
+ if (keep && live.requestId === keep.requestId) continue;
+ dismiss(live.requestId, 'superseded');
+ }
+ for (const meta of [...cancelledUserInput, ...cancelledDynamicTools]) {
+ dismiss(String(meta.requestId), 'turn_completed');
+ }
+ }
+
+ const emitAskUserContinuationStartFailure = (error: unknown): void => {
+ log.warn('ask_user continuation turn failed to start', { error: String(error) });
+ eventQueue.push({
+ type: 'error',
+ data: {
+ message: `ask_user continuation turn failed to start: ${String(error)}`,
+ isTerminal: true,
+ },
+ source: 'codex',
+ });
+ eventQueue.push({
+ type: 'status',
+ data: { status: 'Done', ...usageTracker.snapshot(), isRunning: false },
+ source: 'codex',
+ });
+ };
+
+ async function startAskUserContinuation(
+ live: LiveAskUserRequest,
+ answers: Record<string, string>,
+ autoReviewIntent?: string,
+ ): Promise<void> {
+ if (closed) return;
+ const message = formatAskUserContinuationMessage(live.questions, answers);
+ const sendOptions: CodexInternalSendOptions = {
+ ...(live.permissionPolicy ? { turnPermissionPolicy: live.permissionPolicy } : {}),
+ ...(live.capabilitySelectionText
+ ? { [CODEX_INHERITED_CAPABILITY_SELECTION]: live.capabilitySelectionText }
+ : {}),
+ ...(autoReviewIntent ? { [CODEX_AUTO_REVIEW_INTENT]: autoReviewIntent } : {}),
+ };
+ try {
+ await handle.send({ type: 'user', content: message }, sendOptions);
+ } catch (error) {
+ emitAskUserContinuationStartFailure(error);
+ }
+ }
+
function dismissAllPendingUserInput(reason: string): void {
dismissPendingUserInput(reason, (meta) => meta.threadId === threadId);
}
@@ -7211,6 +7329,20 @@ export class CodexAgent extends BaseAgent {
}
const interactionPromise = (async (): Promise<UserInputAnswersByPosition> => {
+ liveAskUserByRequestId.set(requestId, {
+ requestId,
+ turnId: turnId ?? null,
+ questions,
+ detached: false,
+ continuationStarted: false,
+ permissionPolicy: activeTurnPermissionPolicy,
+ capabilitySelectionText: (
+ (turnId ? capabilitySelectionTextByTurnId.get(turnId) : undefined)
+ ?? capabilitySelectionTextByThreadId.get(threadId)
+ ?? ''
+ ),
+ autoReviewIntent: currentAutoReviewIntent,
+ });
const decision = await dispatchInteraction({
kind: 'ask_user_question',
requestId,
@@ -7221,16 +7353,28 @@ export class CodexAgent extends BaseAgent {
log.warn('requestUserInput got mismatched ask decision', { requestId, decKind: decision.kind });
return questions.map(() => []);
}
- // 澄清答案改变本轮授权范围(把范围从 src/ 收窄到 build/ 后,后续 `rm -rf src` 必须按澄清后的
- // 意图裁决)→ 并入有界 review intent 并清缓存,与 Claude 侧 AskUserQuestion 对称(codex 报)。
- setAutoReviewIntent(composeAutoReviewIntentWithClarification(
- currentAutoReviewIntent,
+ const live = liveAskUserByRequestId.get(requestId);
+ // 澄清必须锚在发起提问那一轮的审查意图上。卡片挂起期间后续 turn 可能改写
+ // currentAutoReviewIntent;plan_review 已用 planRequestAutoReviewIntent 防漂。
+ const continuationAutoReviewIntent = composeAutoReviewIntentWithClarification(
+ live?.autoReviewIntent ?? currentAutoReviewIntent,
Object.entries(decision.answers ?? {}).map(([question, answer]) => ({ question, answer })),
- ));
- return userInputAnswersByPosition(
+ );
+ setAutoReviewIntent(continuationAutoReviewIntent);
+ const answersByPosition = userInputAnswersByPosition(
questions,
responseFromAskUserAnswers(questions, decision.answers),
);
+ if (
+ live
+ && live.detached
+ && !live.continuationStarted
+ && decision.dismissed !== true
+ ) {
+ live.continuationStarted = true;
+ void startAskUserContinuation(live, decision.answers ?? {}, continuationAutoReviewIntent);
+ }
+ return answersByPosition;
})();
let cancelPendingInteraction!: () => void;
@@ -7275,6 +7419,7 @@ export class CodexAgent extends BaseAgent {
}
return responseFromUserInputAnswersByPosition(questions, answersByPosition);
} finally {
+ liveAskUserByRequestId.delete(requestId);
const ownedPending = pendingUserInputOwnerByRequestId.get(requestId);
if (ownedPending?.pendingInteraction === pendingInteraction) {
pendingUserInputOwnerByRequestId.delete(requestId);
@@ -8333,7 +8478,11 @@ export class CodexAgent extends BaseAgent {
if (currentTurnId === turn.id || currentTurnId === null) {
stopActiveRolloutPlanFallback();
}
- dismissPendingUserInputForTurn(turn.id, `turn_${turn.status}`);
+ if (turn.status === 'completed') {
+ detachPendingAskUserForSuccessfulTurn(turn.id);
+ } else {
+ dismissPendingUserInputForTurn(turn.id, `turn_${turn.status}`);
+ }
clearActiveToolContextsForTurn(turn.id);
const overlapsActiveTurn = suppressTerminalUi && currentTurnId !== null && currentTurnId !== turn.id;
if (overlapsActiveTurn) return;
diff --git a/packages/maker-core/src/types/events.ts b/packages/maker-core/src/types/events.ts
index 72817a7c71..3d10bafb07 100644
--- a/packages/maker-core/src/types/events.ts
+++ b/packages/maker-core/src/types/events.ts
@@ -294,6 +294,11 @@ export type InteractionDecision =
kind: 'ask_user_question';
/** 用户对每道问题的回答, key=question(或 header), value=用户回答 */
answers: Record<string, string>;
+ /**
+ * true = 系统性 dismissal(会话 abort/close、turn 失败等自动空答),
+ * 不是用户 Skip。Codex detached continuation 据此不发起续跑 turn。
+ */
+ dismissed?: boolean;
}
| {
kind: 'plan_review';