Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(maker-core): 避免同轮重复询问已回答问题 (#947)
DavidShenXD52e5f8f4e798
diff --git a/packages/maker-core/src/agents/codex/index.test.ts b/packages/maker-core/src/agents/codex/index.test.tsindex 2ef2671860..641245f356 100644--- a/packages/maker-core/src/agents/codex/index.test.ts+++ b/packages/maker-core/src/agents/codex/index.test.ts@@ -9959,18 +9959,21 @@ describe('CodexAgent MCP thread context hooks', () => {workingDir: '/repo',});const handlers = host.getThreadHandlers();- if (!handlers?.dynamicToolCall) throw new Error('expected dynamicToolCall handler');+ if (!handlers?.dynamicToolCall || !handlers.requestUserInput) {+ throw new Error('expected user input handlers');+ }let requestCount = 0;+ const pendingDecision = deferred<InteractionDecision>();handle.setInteractionResolver(async (req) => {requestCount += 1;expect(req).toMatchObject({kind: 'ask_user_question',- requestId: requestCount === 1 ? 'req-dynamic' : 'req-dynamic-legacy',+ requestId: 'req-dynamic',});- return { kind: 'ask_user_question', answers: { 'What next?': 'Keep going' } };+ return pendingDecision.promise;});- const result = await handlers.dynamicToolCall({+ const resultPromise = handlers.dynamicToolCall({threadId: 'start-thread-id',turnId: 'turn-1',callId: 'dynamic-call-1',@@ -9978,18 +9981,46 @@ describe('CodexAgent MCP thread context hooks', () => {tool: 'ask_user_question',arguments: {questions: [{- id: 'q1',header: 'Direction',question: 'What next?',- options: [{ label: 'Keep going', description: 'Continue current work' }],}],},}, { requestId: 'req-dynamic' });+ const nativeDuplicateResultPromise = handlers.requestUserInput({+ threadId: 'start-thread-id',+ turnId: 'turn-1',+ itemId: 'native-call-duplicate',+ questions: [{+ id: 'native-q1',+ header: 'Direction',+ question: 'What next?',+ isOther: false,+ isSecret: false,+ options: [],+ }],+ }, { requestId: 'req-native-duplicate' });++ expect(requestCount).toBe(1);+ pendingDecision.resolve({+ kind: 'ask_user_question',+ answers: { 'What next?': 'Keep going' },+ });++ const [result, nativeDuplicateResult] = await Promise.all([+ resultPromise,+ nativeDuplicateResultPromise,+ ]);expect(result.success).toBe(true);expect(result.contentItems).toEqual([- { type: 'inputText', text: JSON.stringify({ q1: { answers: ['Keep going'] } }) },+ {+ type: 'inputText',+ text: JSON.stringify({ 'question-1': { answers: ['Keep going'] } }),+ },]);+ expect(nativeDuplicateResult).toEqual({+ answers: { 'native-q1': { answers: ['Keep going'] } },+ });const legacyResult = await handlers.dynamicToolCall({threadId: 'start-thread-id',@@ -9999,14 +10030,88 @@ describe('CodexAgent MCP thread context hooks', () => {tool: 'ask_user_question',arguments: {questions: [{- id: 'q1',+ id: 'legacy-q1',header: 'Direction',question: 'What next?',- options: [{ label: 'Keep going', description: 'Continue current work' }],+ options: null,}],},}, { requestId: 'req-dynamic-legacy' });- expect(legacyResult).toEqual(result);+ expect(legacyResult.contentItems).toEqual([+ {+ type: 'inputText',+ text: JSON.stringify({ 'legacy-q1': { answers: ['Keep going'] } }),+ },+ ]);+ expect(requestCount).toBe(1);+ await handle.close();+ });++ it('preserves submitted answers from different concurrent user input prompts', async () => {+ const agent = new CodexAgent(createDeps());+ const host = installFakeHost(agent);+ const handle = await agent.startSession({+ sessionId: 'session-concurrent-user-input',+ model: 'gpt-5.4',+ workingDir: '/repo',+ });+ const handlers = host.getThreadHandlers();+ if (!handlers?.dynamicToolCall) throw new Error('expected dynamicToolCall handler');++ const firstDecision = deferred<InteractionDecision>();+ const secondDecision = deferred<InteractionDecision>();+ let requestCount = 0;+ 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;+ return {+ kind: 'ask_user_question',+ answers: { [req.questions[0]?.question ?? '']: 'Unexpected repeat' },+ };+ });++ const callQuestion = (+ requestId: string,+ callId: string,+ questionId: string,+ question: string,+ ) => handlers.dynamicToolCall?.({+ threadId: 'start-thread-id',+ turnId: 'turn-1',+ callId,+ namespace: 'cindy',+ tool: 'ask_user_question',+ arguments: {+ questions: [{ id: questionId, header: 'Direction', question }],+ },+ }, { requestId });++ const firstResultPromise = callQuestion('req-first', 'call-first', 'first', 'First question?');+ const secondResultPromise = callQuestion('req-second', 'call-second', 'second', 'Second question?');+ if (!firstResultPromise || !secondResultPromise) throw new Error('expected dynamic tool results');+ expect(requestCount).toBe(2);++ secondDecision.resolve({+ kind: 'ask_user_question',+ answers: { 'Second question?': 'Second answer' },+ });+ await secondResultPromise;+ firstDecision.resolve({+ kind: 'ask_user_question',+ answers: { 'First question?': 'First answer' },+ });+ await firstResultPromise;++ const firstReplay = await callQuestion('req-first-replay', 'call-first-replay', 'first', 'First question?');+ const secondReplay = await callQuestion('req-second-replay', 'call-second-replay', 'second', 'Second question?');+ expect(firstReplay?.contentItems).toEqual([+ { type: 'inputText', text: JSON.stringify({ first: { answers: ['First answer'] } }) },+ ]);+ expect(secondReplay?.contentItems).toEqual([+ { type: 'inputText', text: JSON.stringify({ second: { answers: ['Second answer'] } }) },+ ]);expect(requestCount).toBe(2);await handle.close();});@@ -10022,38 +10127,353 @@ describe('CodexAgent MCP thread context hooks', () => {const iterator = handle.events()[Symbol.asyncIterator]();const handlers = host.getThreadHandlers();if (!handlers?.requestUserInput || !handlers.serverRequestResolved) throw new Error('expected handlers');- const pendingDecision = deferred<InteractionDecision>();- handle.setInteractionResolver(async () => pendingDecision.promise);-+ const cancelledDecision = deferred<InteractionDecision>();+ const retryDecision = deferred<InteractionDecision>();+ let requestCount = 0;+ handle.setInteractionResolver(async (req) => {+ requestCount += 1;+ return req.requestId === 'req-resolved'+ ? cancelledDecision.promise+ : retryDecision.promise;+ });++ const question = {+ id: 'q1',+ header: 'Question',+ question: 'Pick one',+ isOther: false,+ isSecret: false,+ options: null,+ };const responsePromise = handlers.requestUserInput({threadId: 'start-thread-id',turnId: 'turn-1',itemId: 'item-1',+ questions: [question],+ }, { requestId: 'req-resolved' });++ handlers.serverRequestResolved({ threadId: 'start-thread-id', requestId: 'req-resolved' });++ await expect(responsePromise).resolves.toEqual({ answers: {} });+ await expect(nextEvent(iterator)).resolves.toMatchObject({+ type: 'interaction_dismissed',+ data: {+ requestId: 'req-resolved',+ reason: 'server_request_resolved',+ resolvedAs: 'deny',+ },+ });++ const retryResponsePromise = handlers.requestUserInput({+ threadId: 'start-thread-id',+ turnId: 'turn-1',+ itemId: 'item-2',+ questions: [question],+ }, { requestId: 'req-retry' });+ expect(requestCount).toBe(2);+ retryDecision.resolve({+ kind: 'ask_user_question',+ answers: { 'Pick one': 'fresh' },+ });+ await expect(retryResponsePromise).resolves.toEqual({+ answers: { q1: { answers: ['fresh'] } },+ });++ cancelledDecision.resolve({+ kind: 'ask_user_question',+ answers: { 'Pick one': 'late' },+ });+ await Promise.resolve();+ await Promise.resolve();+ await expect(handlers.requestUserInput({+ threadId: 'start-thread-id',+ turnId: 'turn-1',+ itemId: 'item-3',+ questions: [question],+ }, { requestId: 'req-replay' })).resolves.toEqual({+ answers: { q1: { answers: ['fresh'] } },+ });+ expect(requestCount).toBe(2);+ await handle.close();+ });++ it('does not cache a late user-input answer after local turn interruption', async () => {+ const agent = new CodexAgent(createDeps());+ const host = installFakeHost(agent, (method) => {+ if (method === Method.TurnStart) return { turn: { id: 'turn-1' } };+ if (method === Method.TurnInterrupt) return {};+ return undefined;+ });+ const handle = await agent.startSession({+ sessionId: 'session-user-input-local-interrupt',+ model: 'gpt-5.4',+ workingDir: '/repo',+ });+ await handle.send({ type: 'user', content: 'ask me a question' });+ const handlers = host.getThreadHandlers();+ if (!handlers?.requestUserInput) throw new Error('expected requestUserInput handler');+ const interruptedDecision = deferred<InteractionDecision>();+ const replacementDecision = deferred<InteractionDecision>();+ let requestCount = 0;+ handle.setInteractionResolver(async () => {+ requestCount += 1;+ return requestCount === 1+ ? interruptedDecision.promise+ : replacementDecision.promise;+ });++ const question = {+ id: 'q1',+ header: 'Question',+ question: 'Pick one',+ isOther: false,+ isSecret: false,+ options: null,+ };+ const interruptedResponsePromise = handlers.requestUserInput({+ threadId: 'start-thread-id',+ turnId: 'turn-1',+ itemId: 'item-interrupted',+ questions: [question],+ }, { requestId: 'req-interrupted' });++ await handle.abort();+ await expect(interruptedResponsePromise).resolves.toEqual({ answers: {} });++ interruptedDecision.resolve({+ kind: 'ask_user_question',+ answers: { 'Pick one': 'late' },+ });+ await Promise.resolve();+ await Promise.resolve();++ const replacementResponsePromise = handlers.requestUserInput({+ threadId: 'start-thread-id',+ turnId: 'turn-1',+ itemId: 'item-replacement',+ questions: [question],+ }, { requestId: 'req-replacement' });+ expect(requestCount).toBe(2);+ replacementDecision.resolve({+ kind: 'ask_user_question',+ answers: { 'Pick one': 'fresh' },+ });+ await expect(replacementResponsePromise).resolves.toEqual({+ answers: { q1: { answers: ['fresh'] } },+ });++ handlers.turnCompleted?.({+ threadId: 'start-thread-id',+ turn: { id: 'turn-1', status: 'interrupted' },+ });+ await handle.close();+ });++ it('reassigns a joined duplicate when the interaction owner is cancelled', async () => {+ const agent = new CodexAgent(createDeps());+ const host = installFakeHost(agent);+ const handle = await agent.startSession({+ sessionId: 'session-user-input-owner-cancelled',+ model: 'gpt-5.4',+ workingDir: '/repo',+ });+ const iterator = handle.events()[Symbol.asyncIterator]();+ const handlers = host.getThreadHandlers();+ if (!handlers?.requestUserInput || !handlers.dynamicToolCall || !handlers.serverRequestResolved) {+ throw new Error('expected handlers');+ }+ const ownerDecision = deferred<InteractionDecision>();+ const joinedDecision = deferred<InteractionDecision>();+ let requestCount = 0;+ handle.setInteractionResolver(async (req) => {+ requestCount += 1;+ return req.requestId === 'req-owner'+ ? ownerDecision.promise+ : joinedDecision.promise;+ });++ const ownerResponsePromise = handlers.requestUserInput({+ threadId: 'start-thread-id',+ turnId: 'turn-1',+ itemId: 'item-owner',questions: [{- id: 'q1',+ id: 'native-q1',header: 'Question',question: 'Pick one',isOther: false,isSecret: false,options: null,}],- }, { requestId: 'req-resolved' });+ }, { requestId: 'req-owner' });+ const joinedResponsePromise = handlers.dynamicToolCall({+ threadId: 'start-thread-id',+ turnId: 'turn-1',+ callId: 'item-joined',+ namespace: 'cindy',+ tool: 'ask_user_question',+ arguments: {+ questions: [{+ id: 'dynamic-q1',+ header: 'Question',+ question: 'Pick one',+ isOther: false,+ options: null,+ }],+ },+ }, { requestId: 'req-joined' });+ expect(requestCount).toBe(1);- handlers.serverRequestResolved({ threadId: 'start-thread-id', requestId: 'req-resolved' });+ handlers.serverRequestResolved({ threadId: 'start-thread-id', requestId: 'req-owner' });- await expect(responsePromise).resolves.toEqual({ answers: {} });+ await expect(ownerResponsePromise).resolves.toEqual({ answers: {} });await expect(nextEvent(iterator)).resolves.toMatchObject({type: 'interaction_dismissed',data: {- requestId: 'req-resolved',+ requestId: 'req-owner',reason: 'server_request_resolved',resolvedAs: 'deny',},});- pendingDecision.resolve({ kind: 'ask_user_question', answers: { q1: 'late' } });+ await waitForExpectation(() => {+ expect(requestCount).toBe(2);+ });++ joinedDecision.resolve({+ kind: 'ask_user_question',+ answers: { 'Pick one': 'fresh' },+ });+ await expect(joinedResponsePromise).resolves.toEqual({+ success: true,+ contentItems: [{+ type: 'inputText',+ text: JSON.stringify({ 'dynamic-q1': { answers: ['fresh'] } }),+ }],+ });++ ownerDecision.resolve({+ kind: 'ask_user_question',+ answers: { 'Pick one': 'late' },+ });+ await Promise.resolve();+ await Promise.resolve();+ await expect(handlers.requestUserInput({+ threadId: 'start-thread-id',+ turnId: 'turn-1',+ itemId: 'item-replay',+ questions: [{+ id: 'replay-q1',+ header: 'Question',+ question: 'Pick one',+ isOther: false,+ isSecret: false,+ options: null,+ }],+ }, { requestId: 'req-replay' })).resolves.toEqual({+ answers: { 'replay-q1': { answers: ['fresh'] } },+ });+ expect(requestCount).toBe(2);await handle.close();});+ it.each([+ {+ lifecycle: 'turn completion',+ reason: 'turn_completed',+ trigger: (_handle: AgentSessionHandle, handlers: ThreadEventHandlers) => {+ handlers.turnCompleted?.({+ threadId: 'start-thread-id',+ turn: { id: 'turn-1', status: 'completed' },+ });+ },+ },+ {+ lifecycle: 'transport failure',+ reason: 'transport_error',+ trigger: (_handle: AgentSessionHandle, handlers: ThreadEventHandlers) => {+ handlers.error?.({+ threadId: 'start-thread-id',+ turnId: '',+ willRetry: false,+ scope: 'transport',+ error: { message: 'transport closed' },+ });+ },+ },+ {+ lifecycle: 'session close',+ reason: 'session_closed',+ trigger: async (handle: AgentSessionHandle) => {+ await handle.close();+ },+ },+ ])('wakes joined user-input requests during $lifecycle cleanup', async ({ lifecycle, reason, trigger }) => {+ const logger = createNoopLogger();+ const debug = vi.spyOn(logger, 'debug');+ const agent = new CodexAgent(createDeps({}, { logger }));+ const host = installFakeHost(agent);+ const handle = await agent.startSession({+ sessionId: `session-user-input-cleanup-${lifecycle.replaceAll(' ', '-')}`,+ model: 'gpt-5.4',+ workingDir: '/repo',+ });+ const handlers = host.getThreadHandlers();+ if (!handlers?.requestUserInput || !handlers.dynamicToolCall) {+ throw new Error('expected user input handlers');+ }+ const ownerDecision = deferred<InteractionDecision>();+ let requestCount = 0;+ handle.setInteractionResolver(async () => {+ requestCount += 1;+ return ownerDecision.promise;+ });++ const ownerResponsePromise = handlers.requestUserInput({+ threadId: 'start-thread-id',+ turnId: 'turn-1',+ itemId: 'item-owner',+ questions: [{+ id: 'native-q1',+ header: 'Question',+ question: 'Pick one',+ isOther: false,+ isSecret: false,+ options: null,+ }],+ }, { requestId: 'req-owner' });+ const joinedResponsePromise = handlers.dynamicToolCall({+ threadId: 'start-thread-id',+ turnId: 'turn-1',+ callId: 'item-joined',+ namespace: 'cindy',+ tool: 'ask_user_question',+ arguments: {+ questions: [{+ id: 'dynamic-q1',+ header: 'Question',+ question: 'Pick one',+ isOther: false,+ options: null,+ }],+ },+ }, { requestId: 'req-joined' });+ expect(requestCount).toBe(1);++ await trigger(handle, handlers);++ await expect(ownerResponsePromise).resolves.toEqual({ answers: {} });+ await expect(joinedResponsePromise).resolves.toEqual({+ success: false,+ contentItems: [{ type: 'inputText', text: `Request cancelled: ${reason}` }],+ });+ 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();+ });+it('updates the registered vendorOptions object by reference on setVendorOptions', async () => {const registerCodexMcpThreadContext = vi.fn();const agent = new CodexAgent(createDeps({}, {diff --git a/packages/maker-core/src/agents/codex/index.ts b/packages/maker-core/src/agents/codex/index.tsindex f3dbc441ed..82071da094 100644--- a/packages/maker-core/src/agents/codex/index.ts+++ b/packages/maker-core/src/agents/codex/index.ts@@ -643,6 +643,54 @@ function dynamicToolResponseFromUserInput(response: ToolRequestUserInputResponse};}+function userInputQuestionsFingerprint(+ questions: readonly ToolRequestUserInputQuestion[],+): string {+ return JSON.stringify(questions.map((question) => ({+ header: question.header,+ question: question.question,+ isOther: question.isOther === true,+ options: (question.options ?? []).map((option) => ({+ label: option.label,+ description: option.description,+ })),+ })));+}++type UserInputAnswersByPosition = string[][];++interface PendingUserInputInteraction {+ interactionPromise: Promise<UserInputAnswersByPosition>;+ cancelledPromise: Promise<void>;+ cancel: () => void;+}++function userInputAnswersByPosition(+ questions: readonly ToolRequestUserInputQuestion[],+ response: ToolRequestUserInputResponse,+): UserInputAnswersByPosition {+ return questions.map((question) =>+ response.answers[question.id]?.answers.slice() ?? [],+ );+}++function responseFromUserInputAnswersByPosition(+ questions: readonly ToolRequestUserInputQuestion[],+ answersByPosition: readonly (readonly string[])[],+): ToolRequestUserInputResponse {+ const answers: ToolRequestUserInputResponse['answers'] = {};+ questions.forEach((question, index) => {+ answers[question.id] = { answers: [...(answersByPosition[index] ?? [])] };+ });+ return { answers };+}++function hasSubmittedUserInput(answersByPosition: readonly (readonly string[])[]): boolean {+ return answersByPosition.some((answers) =>+ answers.some((value) => value.trim().length > 0),+ );+}+function normalizeServiceTier(serviceTier: ServiceTier | null | undefined): ServiceTier | null | undefined {return serviceTier === 'priority' ? 'fast' : serviceTier;}@@ -3502,6 +3550,24 @@ export class CodexAgent extends BaseAgent {const userInputBroker = new CodexInteractionBroker<ToolRequestUserInputResponse>();const dynamicToolBroker = new CodexInteractionBroker<DynamicToolCallResponse>();const activeToolContexts = new Map<string, ActiveToolContext>();+ // A single model turn can surface the same visible question through both+ // the native requestUserInput request and the dynamic-tool compatibility+ // path. Join an in-flight interaction, then replay its submitted answers+ // by question position so protocol-specific ids can still differ.+ const submittedUserInputByTurn = new Map<+ string,+ Map<string, UserInputAnswersByPosition>+ >();+ const pendingUserInputByTurn = new Map<+ string,+ Map<string, PendingUserInputInteraction>+ >();+ const pendingUserInputOwnerByRequestId = new Map<string, {+ turnId: string;+ fingerprint: string;+ pendingForTurn: Map<string, PendingUserInputInteraction>;+ pendingInteraction: PendingUserInputInteraction;+ }>();registerCodexMcpContext(threadId);let mcpElicitationSeq = 0;@@ -3790,6 +3856,7 @@ export class CodexAgent extends BaseAgent {const requestId = String(meta.requestId);if (dismissed.has(requestId)) continue;dismissed.add(requestId);+ forgetPendingUserInputRequest(requestId);eventQueue.push({type: 'interaction_dismissed',data: { requestId, reason, resolvedAs: 'deny' },@@ -4429,6 +4496,46 @@ export class CodexAgent extends BaseAgent {for (const [itemId, ctx] of activeToolContexts) {if (ctx.turnId === turnId) activeToolContexts.delete(itemId);}+ // Lifecycle callers dismiss the broker entries first. Wake joined waiters+ // before dropping the lookup maps so they can observe that their request+ // is no longer pending instead of reopening the interaction.+ const pendingForTurn = pendingUserInputByTurn.get(turnId);+ if (pendingForTurn) {+ for (const pendingInteraction of pendingForTurn.values()) {+ pendingInteraction.cancel();+ }+ }+ for (const [requestId, pending] of pendingUserInputOwnerByRequestId) {+ if (pending.turnId === turnId) pendingUserInputOwnerByRequestId.delete(requestId);+ }+ submittedUserInputByTurn.delete(turnId);+ pendingUserInputByTurn.delete(turnId);+ }++ function clearAllPendingUserInputInteractions(): void {+ // Keep the same broker-dismiss-before-wake ordering as the per-turn path.+ for (const pendingForTurn of pendingUserInputByTurn.values()) {+ for (const pendingInteraction of pendingForTurn.values()) {+ pendingInteraction.cancel();+ }+ }+ pendingUserInputByTurn.clear();+ pendingUserInputOwnerByRequestId.clear();+ }++ function forgetPendingUserInputRequest(requestId: string): void {+ const pending = pendingUserInputOwnerByRequestId.get(requestId);+ if (!pending) return;+ pendingUserInputOwnerByRequestId.delete(requestId);+ pending.pendingInteraction.cancel();+ if (pending.pendingForTurn.get(pending.fingerprint) !== pending.pendingInteraction) return;+ pending.pendingForTurn.delete(pending.fingerprint);+ if (+ pending.pendingForTurn.size === 0+ && pendingUserInputByTurn.get(pending.turnId) === pending.pendingForTurn+ ) {+ pendingUserInputByTurn.delete(pending.turnId);+ }}function classifyUserInputRequest(params: ToolRequestUserInputParams): 'ask_user_question' | 'permission' {@@ -4446,6 +4553,8 @@ export class CodexAgent extends BaseAgent {async function askUserViaInteraction(requestId: string,questions: ToolRequestUserInputQuestion[],+ turnId?: string | null,+ isRequestPending: () => boolean = () => true,): Promise<ToolRequestUserInputResponse> {if (questions.some((q) => q.isSecret)) {log.warn('requestUserInput secret question refused', {@@ -4454,16 +4563,117 @@ export class CodexAgent extends BaseAgent {});return emptyUserInputResponse(questions);}- const decision = await dispatchInteraction({- kind: 'ask_user_question',- requestId,- questions: questionsToAskUserItems(questions),+ const fingerprint = turnId ? userInputQuestionsFingerprint(questions) : null;+ const submittedForTurn = turnId ? submittedUserInputByTurn.get(turnId) : undefined;+ const replay = fingerprint ? submittedForTurn?.get(fingerprint) : undefined;+ if (replay) {+ log.info('reusing submitted answer for duplicate same-turn user input request', {+ requestId,+ turnId,+ questionCount: questions.length,+ });+ return responseFromUserInputAnswersByPosition(questions, replay);+ }++ let pendingForTurn = turnId ? pendingUserInputByTurn.get(turnId) : undefined;+ const pendingReplay = fingerprint ? pendingForTurn?.get(fingerprint) : undefined;+ if (pendingReplay) {+ log.info('joining duplicate same-turn user input request', {+ requestId,+ turnId,+ questionCount: questions.length,+ });+ const joined = await Promise.race([+ pendingReplay.interactionPromise.then((answersByPosition) => ({+ kind: 'answered' as const,+ answersByPosition,+ })),+ pendingReplay.cancelledPromise.then(() => ({ kind: 'cancelled' as const })),+ ]);+ if (joined.kind === 'cancelled') {+ log.debug('joined duplicate same-turn user input request cancelled', {+ requestId,+ turnId,+ });+ return isRequestPending()+ ? askUserViaInteraction(requestId, questions, turnId, isRequestPending)+ : emptyUserInputResponse(questions);+ }+ return responseFromUserInputAnswersByPosition(questions, joined.answersByPosition);+ }++ const interactionPromise = (async (): Promise<UserInputAnswersByPosition> => {+ const decision = await dispatchInteraction({+ kind: 'ask_user_question',+ requestId,+ questions: questionsToAskUserItems(questions),+ });+ if (decision.kind !== 'ask_user_question') {+ log.warn('requestUserInput got mismatched ask decision', { requestId, decKind: decision.kind });+ return questions.map(() => []);+ }+ return userInputAnswersByPosition(+ questions,+ responseFromAskUserAnswers(questions, decision.answers),+ );+ })();++ let cancelPendingInteraction!: () => void;+ const cancelledPromise = new Promise<void>((resolve) => {+ cancelPendingInteraction = resolve;});- if (decision.kind !== 'ask_user_question') {- log.warn('requestUserInput got mismatched ask decision', { requestId, decKind: decision.kind });- return emptyUserInputResponse(questions);+ const pendingInteraction: PendingUserInputInteraction = {+ interactionPromise,+ cancelledPromise,+ cancel: cancelPendingInteraction,+ };++ if (turnId && fingerprint) {+ pendingForTurn ??= new Map<string, PendingUserInputInteraction>();+ pendingForTurn.set(fingerprint, pendingInteraction);+ if (!pendingUserInputByTurn.has(turnId)) {+ pendingUserInputByTurn.set(turnId, pendingForTurn);+ }+ pendingUserInputOwnerByRequestId.set(requestId, {+ turnId,+ fingerprint,+ pendingForTurn,+ pendingInteraction,+ });+ }++ try {+ const answersByPosition = await interactionPromise;+ if (+ turnId+ && fingerprint+ && pendingUserInputByTurn.get(turnId) === pendingForTurn+ && pendingForTurn?.get(fingerprint) === pendingInteraction+ && hasSubmittedUserInput(answersByPosition)+ ) {+ const nextSubmittedForTurn = submittedUserInputByTurn.get(turnId)+ ?? new Map<string, UserInputAnswersByPosition>();+ nextSubmittedForTurn.set(fingerprint, answersByPosition);+ if (!submittedUserInputByTurn.has(turnId)) {+ submittedUserInputByTurn.set(turnId, nextSubmittedForTurn);+ }+ }+ return responseFromUserInputAnswersByPosition(questions, answersByPosition);+ } finally {+ const ownedPending = pendingUserInputOwnerByRequestId.get(requestId);+ if (ownedPending?.pendingInteraction === pendingInteraction) {+ pendingUserInputOwnerByRequestId.delete(requestId);+ }+ if (turnId && fingerprint && pendingForTurn?.get(fingerprint) === pendingInteraction) {+ pendingForTurn.delete(fingerprint);+ if (+ pendingForTurn.size === 0+ && pendingUserInputByTurn.get(turnId) === pendingForTurn+ ) {+ pendingUserInputByTurn.delete(turnId);+ }+ }}- return responseFromAskUserAnswers(questions, decision.answers);}async function requestUserInputAsPermission(@@ -4542,7 +4752,12 @@ export class CodexAgent extends BaseAgent {async (settle) => {const response = kind === 'permission'? await requestUserInputAsPermission(requestId, params, questions)- : await askUserViaInteraction(requestId, questions);+ : await askUserViaInteraction(+ requestId,+ questions,+ params.turnId,+ () => userInputBroker.has({ connectionId, requestId: meta.requestId }),+ );settle(response);},);@@ -4602,7 +4817,12 @@ export class CodexAgent extends BaseAgent {itemId: params.callId,},async (settle) => {- const response = await askUserViaInteraction(requestId, questions);+ const response = await askUserViaInteraction(+ requestId,+ questions,+ params.turnId,+ () => dynamicToolBroker.has({ connectionId, requestId: meta.requestId }),+ );settle(dynamicToolResponseFromUserInput(response));},);@@ -4610,12 +4830,21 @@ export class CodexAgent extends BaseAgent {function handleServerRequestResolved(params: ServerRequestResolvedNotification['params']): void {const requestId = String(params.requestId);+ const brokerKey = { connectionId, requestId: params.requestId };+ const userInputPending = userInputBroker.has(brokerKey);+ const dynamicPending = dynamicToolBroker.has(brokerKey);+ if (userInputPending || dynamicPending) {+ // 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);+ }const userInputCancelled = userInputBroker.cancel(- { connectionId, requestId: params.requestId },+ brokerKey,{ answers: {} },);const dynamicCancelled = dynamicToolBroker.cancel(- { connectionId, requestId: params.requestId },+ brokerKey,{contentItems: [{ type: 'inputText', text: 'Request was resolved before user input was submitted.' }],success: false,@@ -6195,6 +6424,8 @@ export class CodexAgent extends BaseAgent {subscriptionInvalidatedByTransport = true;dismissAllPendingUserInput('transport_error');activeToolContexts.clear();+ submittedUserInputByTurn.clear();+ clearAllPendingUserInputInteractions();}const targetsPendingTurn = isTurnStartPending && currentTurnId === null && Boolean(params.turnId);// 空 turnId 的容量拒绝: 过载重投的 RPC 还在飞、而它的 turnStarted 尚未到达时,@@ -7277,6 +7508,7 @@ export class CodexAgent extends BaseAgent {// 否则 server 那边没回 response 会卡; UI 上的 PermissionPrompt 也会留尸try { dismissAllPending('session_closed', 'deny'); } catch (e) { log.warn('dismissAllPending threw', { error: String(e) }); }try { dismissAllPendingUserInput('session_closed'); } catch (e) { log.warn('dismissAllPendingUserInput threw', { error: String(e) }); }+ try { clearAllPendingUserInputInteractions(); } catch (e) { log.warn('clear pending user input threw', { error: String(e) }); }try { stopActiveRolloutPlanFallback(); } catch (e) { log.warn('stop rollout plan fallback threw', { error: String(e) }); }// 挂起的过载重投计时器必须清掉:否则会话已关,计时器到点仍会对已释放的// thread 发 turn/start(assertCurrentHost 会抛,但那是在无人接收的