๐คฏ LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
๐ fix: ๆฅ้ Codex ๅ็ๆ้ฎไธ็ญๆกๅไผ (#22287)
Mochaea476720f0f2
diff --git a/.agents/acceptance/probe-mock-patterns.md b/.agents/acceptance/probe-mock-patterns.mdindex 3623dbfd34a..f5eed6b3691 100644--- a/.agents/acceptance/probe-mock-patterns.md+++ b/.agents/acceptance/probe-mock-patterns.md@@ -41,7 +41,7 @@ drive / probe / capture / publish. Skip a row only when its surface AND runtime| P17 | web | any | drive | Goals live at `/agent/:aid/goals` behind the Labs toggle `enableGoals` || P18 | electron | hetero | fixture | Local-execution CC agent plus a four-table ledger fixture keyed to the live CLI identity || P19 | web | any | auth | Seed a second user and sign in from inside a run-specific session; a signed-out context hits `/signin` |-| P20 | cli | any | fixture | Strip ambient topic/agent/operation ids for a LOCAL ingest; keep them for the production publish |+| P20 | cli | any | fixture | Strip ambient conversation ids and set the local credential's workspace for LOCAL API/ingest; retain production scope for publishing || P21 | web | any | drive | Upload through the Add-menu input, poll `dockUploadFileList`, A/B the hashing worker with `window.Worker = undefined` || P22 | web, electron | any | drive | `keyboard type` emits no keydown; fire `/` (and any menu trigger) with `press` || P23 | web, electron | any | drive | Tag `svg.lucide-<rendered-name>` and click through agent-browser; `el.click()` on the wrapper does nothing |@@ -665,6 +665,14 @@ assistant, so every batch fails with `Seeded assistantMessageId msg_โฆ was nottopic <t>`. Set it to the fixture's seeded assistant id and unset`LOBEHUB_HETERO_EXEC_INHERIT_PROCESS_GROUP` together with the ids above.+`LOBEHUB_WORKSPACE_ID` is also inherited. A personal local seed API key with a+production workspace header returns HTTP 401 even when its hash, enabled flag,+and user are valid. For local API creation and native CLI replay, explicitly set+`LOBEHUB_WORKSPACE_ID=personal` (or the verified workspace owned by the test+credential) in that subprocess. Verify a real authenticated API call on the local+server before creating the operation. Do not change persistent CLI workspace+scope, and restore the production context for report publication.+### Driving the UI#### P21ใปDriving a ่ตๆบๅบ upload with agent-browser: use the Add-menu input, and a same-build A/B for the hashing threaddiff --git a/.agents/skills/heterogeneous-agent/references/debug-workflow.md b/.agents/skills/heterogeneous-agent/references/debug-workflow.mdindex 953f1b52c2f..1573aa29cef 100644--- a/.agents/skills/heterogeneous-agent/references/debug-workflow.md+++ b/.agents/skills/heterogeneous-agent/references/debug-workflow.md@@ -259,6 +259,15 @@ If subagent events leak to the main handler, the main bubble can inherit the wroRun the smallest useful test set first.+For shared Codex modules consumed by Desktop, also check the Desktop consumer with+`bun check --cwd=<repo>/apps/desktop -p tsconfig.json` from outside the repo. The+root type-check excludes Desktop, whose `strict: false` makes Zod nullable output+properties optional in type inference. A `satisfies z.ZodType<ProtocolType>`+assertion can therefore fail only in Desktop despite unchanged runtime validation;+remove a redundant assertion rather than changing global compiler settings. Pass+affected `__tests__/*.test.ts` files explicitly to `bun run check --test` when+updating adjacent action entries: automatic related-test discovery may miss them.+```bashbunx vitest run --silent='passed-only' 'packages/heterogeneous-agents/src/adapters/codex.test.ts'bunx vitest run --silent='passed-only' 'packages/heterogeneous-agents/src/adapters/claudeCode.test.ts'diff --git a/apps/cli/src/commands/hetero.ts b/apps/cli/src/commands/hetero.tsindex 22c507926a3..1f61425a190 100644--- a/apps/cli/src/commands/hetero.ts+++ b/apps/cli/src/commands/hetero.ts@@ -138,6 +138,7 @@ const spawnAgentOrRuntime = (): Promise<Awaited<ReturnType<typeof spawnAgent>>> => {if (nativeCodex)return createCodexAgentHandle({+ askUserBridge: spawnOpts.askUserBridge,clientVersion: cliVersion,args: spawnOpts.extraArgs ?? [],commandPath: spawnOpts.command!,@@ -743,15 +744,10 @@ const exec = async (options: ExecOptions): Promise<void> => {// โโโ AskUserQuestion MCP โ remote Human-in-the-loop โโโโโโโโโโโโโโโโโโโโโโโโ//- // Mount the same `lobe_cc` MCP server the desktop app uses, but resolve the- // bridge over the server's Redis stream instead of Electron IPC:- // - request out: `bridge.events()` ride the normal ingest sink โ server- // `heteroIngest` โ Redis stream โ renderer shows the AskUserQuestion card.- // - response back: the sandbox can't read Redis, so a long-poll pulls the- // `agent_intervention_response` off the stream (published by the browser's- // `submitHeteroIntervention`) and resolves the pending bridge call.- // The bridge's own 5-min timeout is the backstop, so a dropped poll or an- // absent user never strands CC.+ // MCP and native Codex share the desktop's AskUserBridge. Requests flow+ // through durable ingest to the question card; long-poll returns browser+ // answers from the server's Redis stream to the blocked native callback.+ // The bridge timeout bounds the wait, including native Codex requests.const sleep = (ms: number) => new Promise<void>((resolve) => setTimeout(resolve, ms));let askServer: LobeBuiltinMcpServer | undefined;let askBridge: AskUserBridge | undefined;@@ -760,6 +756,7 @@ const exec = async (options: ExecOptions): Promise<void> => {if (serverIngest &&(agentType === 'claude-code' ||+ (agentType === 'codex' && options.codexAppServer) ||agentType === 'copilot' ||agentType === 'cursor' ||agentType === 'droid' ||@@ -768,6 +765,7 @@ const exec = async (options: ExecOptions): Promise<void> => {serverIngester) {if (+ agentType === 'codex' ||agentType === 'copilot' ||agentType === 'cursor' ||agentType === 'devin' ||diff --git a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.tsindex 12efb78cff2..2b0a5aa8346 100644--- a/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts+++ b/apps/desktop/src/main/controllers/HeterogeneousAgentImpl.ts@@ -1185,7 +1185,7 @@ export default class HeterogeneousAgentCtr {// โโโ AskUserQuestion MCP server () โโโ- /** Register and broadcast a native ACP intervention without starting an MCP server. */+ /** Register a native intervention (ACP or Codex) without starting an MCP server. */private setupAcpInterventionForOp(operationId: string,sessionId: string,@@ -1194,8 +1194,7 @@ export default class HeterogeneousAgentCtr {bridge: AskUserBridge;cleanup: () => Promise<void>;} {- // Cursor keeps its legacy Claude Code renderer identifier. Droid has a- // first-class identifier, while provider remains explicit for both.+ // Cursor keeps its legacy renderer identifier; every provider stays explicit.const bridge = new AskUserBridge(operationId, {identifier: provider === 'cursor' ? 'claude-code' : provider,provider,@@ -2071,6 +2070,7 @@ export default class HeterogeneousAgentCtr {needsSessionIntroduction: this.needsSessionIntroduction.bind(this),recordInflightRun: this.recordInflightRun.bind(this),resolveSessionCommand: this.resolveSessionCommand.bind(this),+ setupAcpInterventionForOp: this.setupAcpInterventionForOp.bind(this),writeCliTraceFile: this.writeCliTraceFile.bind(this),writeCliTraceJson: this.writeCliTraceJson.bind(this),},diff --git a/apps/desktop/src/main/controllers/codexAppServer.ts b/apps/desktop/src/main/controllers/codexAppServer.tsindex 6597a499010..e65b71faf2d 100644--- a/apps/desktop/src/main/controllers/codexAppServer.ts+++ b/apps/desktop/src/main/controllers/codexAppServer.ts@@ -1,4 +1,5 @@import type { HeterogeneousAgentSessionError } from '@lobechat/electron-client-ipc';+import type { AskUserBridge, AskUserBridgeOptions } from '@lobechat/heterogeneous-agents/askUser';import { buildHeterogeneousPrompt } from '@lobechat/heterogeneous-agents/protocol';import type { AgentStreamEvent } from '@lobechat/heterogeneous-agents/spawn';import {@@ -59,6 +60,11 @@ interface CodexAppServerHost {startedAt: string;}) => void;resolveSessionCommand: (session: AgentSession) => string;+ setupAcpInterventionForOp: (+ operationId: string,+ sessionId: string,+ provider: NonNullable<AskUserBridgeOptions['provider']>,+ ) => { bridge: AskUserBridge; cleanup: () => Promise<void> };writeCliTraceFile: (trace: CliTraceSession | undefined,name: string,@@ -216,8 +222,14 @@ export async function sendPromptWithCodexAppServer(sessionId: session.sessionId,});+ const intervention = host.setupAcpInterventionForOp(+ params.operationId,+ session.sessionId,+ 'codex',+ );try {await appServerSession.run({+ askUserBridge: intervention.bridge,input,onRawMessage: (line) => host.appendCliTraceFile(traceSession, 'stdout.jsonl', line),operationId: params.operationId,@@ -290,5 +302,7 @@ export async function sendPromptWithCodexAppServer(throw new Error(typeof sessionError === 'string' ? sessionError : sessionError.message, {cause: error,});+ } finally {+ await intervention.cleanup();}}diff --git a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/codex.test.ts b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/codex.test.tsindex c7acf7a82d7..9309358080a 100644--- a/apps/desktop/src/main/modules/heterogeneousAgent/drivers/codex.test.ts+++ b/apps/desktop/src/main/modules/heterogeneousAgent/drivers/codex.test.ts@@ -268,6 +268,7 @@ describe('withCodexContextArgs', () => {it('reaches the app-server thread config as plain strings', () => {const params = buildCodexAppServerThreadParams(withCodexContextArgs('codex', env), '/work');expect(params.config).toEqual({+ 'features.default_mode_request_user_input': true,'shell_environment_policy.set.LOBEHUB_AGENT_ID': 'agt_1','shell_environment_policy.set.LOBEHUB_CLI': cliPath,'shell_environment_policy.set.LOBEHUB_OPERATION_ID': 'op "1"',diff --git a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/intervention.ts b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/intervention.tsindex 9e308a30dda..0556e554107 100644--- a/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/intervention.ts+++ b/apps/server/src/services/heterogeneousAgent/HeterogeneousPersistenceHandler/intervention.ts@@ -142,6 +142,7 @@ export const INTERVENTION_KINDS = new Set<AgentInterventionInteractionKind>([export const INTERVENTION_PROVIDERS = new Set<AgentInterventionProvider>(['claude-code',+ 'codex','copilot','cursor','devin',diff --git a/packages/agent-gateway-client/src/intervention.test.ts b/packages/agent-gateway-client/src/intervention.test.tsindex dd191e008e0..2c29969a8c9 100644--- a/packages/agent-gateway-client/src/intervention.test.ts+++ b/packages/agent-gateway-client/src/intervention.test.ts@@ -28,6 +28,25 @@ const request = (overrides: Partial<AgentInterventionRequestData> = {}) => ({});describe('sanitizeAgentInterventionRequestForReview', () => {+ it('preserves a native Codex free-text question for durable Review', () => {+ const sanitized = sanitizeAgentInterventionRequestForReview(+ request({+ arguments: JSON.stringify({+ questions: [{ header: 'Database', options: [], question: 'Database name?' }],+ }),+ identifier: 'codex',+ interactionKind: 'question',+ provider: 'codex',+ }),+ );+ expect(sanitized).toMatchObject({ identifier: 'codex', provider: 'codex' });+ expect(JSON.parse(sanitized!.arguments).questions[0]).toEqual({+ header: 'Database',+ multiSelect: false,+ options: [],+ question: 'Database name?',+ });+ });it('accepts an OpenCode question while retaining its producer identity', () => {expect(sanitizeAgentInterventionRequestForReview(diff --git a/packages/agent-gateway-client/src/intervention.ts b/packages/agent-gateway-client/src/intervention.tsindex 2a9c87bebb4..a7d0e4bcbda 100644--- a/packages/agent-gateway-client/src/intervention.ts+++ b/packages/agent-gateway-client/src/intervention.ts@@ -13,6 +13,7 @@ const INTERACTION_KINDS = new Set<AgentInterventionInteractionKind>([]);const PROVIDERS = new Set<AgentInterventionProvider>(['claude-code',+ 'codex','copilot','cursor','devin',@@ -77,7 +78,7 @@ export const sanitizeAgentInterventionRequestForReview = (typeof questionRecord.multiSelect !== 'boolean') ||(request.interactionKind !== 'question' && questionRecord.multiSelect === true) ||!Array.isArray(rawOptions) ||- rawOptions.length < 1 ||+ (rawOptions.length < 1 && request.interactionKind !== 'question') ||rawOptions.length > 16) {return;diff --git a/packages/agent-gateway-client/src/types.ts b/packages/agent-gateway-client/src/types.tsindex 62192983926..283fc230cb2 100644--- a/packages/agent-gateway-client/src/types.ts+++ b/packages/agent-gateway-client/src/types.ts@@ -278,7 +278,7 @@ export type AgentInterventionInteractionKind = 'permission' | 'plan' | 'question/** Producer that owns the blocked interaction. */export type AgentInterventionProvider =- 'claude-code' | 'copilot' | 'cursor' | 'devin' | 'droid' | 'opencode' | 'qoder';+ 'claude-code' | 'codex' | 'copilot' | 'cursor' | 'devin' | 'droid' | 'opencode' | 'qoder';/** Whitelisted option surface that may be persisted for cold-start review. */export interface AgentInterventionRenderOption {diff --git a/packages/builtin-tools/src/register.ts b/packages/builtin-tools/src/register.tsindex 923d94b2a08..2ed61bf2426 100644--- a/packages/builtin-tools/src/register.ts+++ b/packages/builtin-tools/src/register.ts@@ -325,6 +325,7 @@ export const registerBuiltinToolSurfaces = (): void => {[KIMI_CODE_IDENTIFIER]: KimiCodeRenders as Record<string, BuiltinRender>,codex: {...CodexRenders,+ [ClaudeCodeApiName.AskUserQuestion]: ClaudeCodeRenders[ClaudeCodeApiName.AskUserQuestion],command_execution: RunCommandRender as BuiltinRender,},[GithubIdentifier]: GithubRenders,@@ -411,7 +412,10 @@ export const registerBuiltinToolSurfaces = (): void => {},[PI_IDENTIFIER]: heterogeneousCliInspectors,[KIMI_CODE_IDENTIFIER]: KimiCodeInspectors,- 'codex': CodexInspectors,+ 'codex': {+ ...CodexInspectors,+ [ClaudeCodeApiName.AskUserQuestion]: ClaudeCodeInspectors[ClaudeCodeApiName.AskUserQuestion],+ },[GithubIdentifier]: GithubInspectors,[LinearIdentifier]: LinearInspectors,[TwitterIdentifier]: TwitterInspectors,@@ -458,6 +462,10 @@ export const registerBuiltinToolSurfaces = (): void => {BuiltinIntervention>,[ClaudeCodeIdentifier]: ClaudeCodeInterventions as Record<string, BuiltinIntervention>,+ codex: {+ [ClaudeCodeApiName.AskUserQuestion]:+ ClaudeCodeInterventions[ClaudeCodeApiName.AskUserQuestion],+ },[COPILOT_IDENTIFIER]: {[ClaudeCodeApiName.AskUserQuestion]:ClaudeCodeInterventions[ClaudeCodeApiName.AskUserQuestion],diff --git a/packages/heterogeneous-agents/src/adapters/codexAppServer.ts b/packages/heterogeneous-agents/src/adapters/codexAppServer.tsindex 8b8eede94a5..6778486fa59 100644--- a/packages/heterogeneous-agents/src/adapters/codexAppServer.ts+++ b/packages/heterogeneous-agents/src/adapters/codexAppServer.ts@@ -1,5 +1,6 @@import { formatPatch, structuredPatch } from 'diff';+import type { InterventionAnswer } from '../askUser';import type {AgentMessageDeltaNotification,CodexErrorInfo,@@ -404,6 +405,32 @@ export class CodexAppServerAdapter {return this.latestCumulativeUsage ?? this.lastCumulativeUsage;}+ startUserInput(toolCallId: string, args: unknown): HeterogeneousAgentEvent[] {+ const payload: ToolCallPayload = {+ apiName: 'askUserQuestion',+ arguments: JSON.stringify(args),+ id: toolCallId,+ identifier: CODEX_IDENTIFIER,+ type: 'default',+ };+ this.hasToolActivity = true;+ this.pendingTools.set(toolCallId, payload);+ return this.startLateTool(payload);+ }++ completeUserInput(toolCallId: string, answer: InterventionAnswer): HeterogeneousAgentEvent[] {+ if (!this.pendingTools.delete(toolCallId)) return [];+ return [+ this.makeEvent('tool_result', {+ content: JSON.stringify(answer.cancelled ? { cancelled: true } : (answer.result ?? {})),+ isError: false,+ pluginState: answer.cancelled ? undefined : { askUserAnswers: answer.result },+ toolCallId,+ } satisfies ToolResultData),+ this.makeEvent('tool_end', { isSuccess: true, toolCallId }),+ ];+ }+configureModel(model: string): HeterogeneousAgentEvent[] {if (model === this.currentModel) return [];this.currentModel = model;diff --git a/packages/heterogeneous-agents/src/codex/CodexAppServerClient.ts b/packages/heterogeneous-agents/src/codex/CodexAppServerClient.tsindex 71299fb93b6..5e651a5bb34 100644--- a/packages/heterogeneous-agents/src/codex/CodexAppServerClient.ts+++ b/packages/heterogeneous-agents/src/codex/CodexAppServerClient.ts@@ -319,7 +319,7 @@ export class CodexAppServerClient {await this.startProcess(generation);const params: InitializeParams = {capabilities: {- experimentalApi: false,+ experimentalApi: true,requestAttestation: false,},clientInfo: {diff --git a/packages/heterogeneous-agents/src/codex/CodexThreadSession.test.ts b/packages/heterogeneous-agents/src/codex/CodexThreadSession.test.tsindex 3ad5ae859bb..c91d7f0644d 100644--- a/packages/heterogeneous-agents/src/codex/CodexThreadSession.test.ts+++ b/packages/heterogeneous-agents/src/codex/CodexThreadSession.test.ts@@ -1,5 +1,6 @@-import { describe, expect, it, vi } from 'vitest';+import { afterEach, describe, expect, it, vi } from 'vitest';+import { AskUserBridge } from '../askUser';import {CodexAppServerConnectionError,CodexAppServerRpcError,@@ -28,6 +29,7 @@ interface ClientHarness {resolveThreadStart: () => void;resolveTurnStart: () => void;resume: (model?: string) => Promise<void> | void;+ serverRequest: (method: string, params: unknown) => Promise<unknown>;}const createClientHarness = (@@ -48,6 +50,7 @@ const createClientHarness = (): ClientHarness => {let disconnectHandler: (() => void) | undefined;let notificationHandler: ((method: string, params: unknown) => Promise<void>) | undefined;+ let serverRequestHandler: ((method: string, params: unknown) => unknown) | undefined;let registration:| {onResume: (response: unknown) => Promise<void> | void;@@ -152,7 +155,10 @@ const createClientHarness = (notificationHandler = handler;return vi.fn();}),- subscribeServerRequests: vi.fn(() => vi.fn()),+ subscribeServerRequests: vi.fn((_threadId, handler) => {+ serverRequestHandler = handler;+ return vi.fn();+ }),};return {@@ -166,6 +172,7 @@ const createClientHarness = (resolveTurnStart,resume: (model = 'gpt-5.5-codex') =>registration?.onResume({ model, thread: { id: options.initialThreadId ?? 'thread-1' } }),+ serverRequest: async (method, params) => serverRequestHandler?.(method, params),};};@@ -209,6 +216,226 @@ const createSession = (};describe('CodexThreadSession', () => {+ describe('native user input', () => {+ const contexts: Array<{ bridge: AskUserBridge; session: CodexThreadSession }> = [];+ afterEach(() => {+ for (const { bridge, session } of contexts.splice(0)) {+ bridge.cancelAll();+ session.close();+ }+ });+ const question = {+ header: 'Database',+ id: 'database',+ isOther: true,+ isSecret: false,+ options: [{ description: 'Preserve existing data', label: 'Keep' }],+ question: 'Keep the database?',+ };+ const request = (questions = [question]) => ({+ autoResolutionMs: null,+ isBlocking: true,+ itemId: 'question-1',+ questions,+ threadId: 'thread-1',+ turnId: 'turn-1',+ });+ const start = async () => {+ const harness = createClientHarness({ autoComplete: false });+ const { events, session } = createSession(harness);+ const bridge = new AskUserBridge('op-question', { identifier: 'codex', provider: 'codex' });+ contexts.push({ bridge, session });+ const running = session.run({+ askUserBridge: bridge,+ input: [{ text: 'Ask me', text_elements: [], type: 'text' }],+ onRawMessage: vi.fn(),+ operationId: 'op-question',+ });+ await vi.waitFor(() =>+ expect(harness.requests.some((r) => r.method === 'turn/start')).toBe(true),+ );+ return { bridge, events, harness, running, session };+ };+ const finish = async (ctx: Awaited<ReturnType<typeof start>>) => {+ await ctx.harness.notify('turn/completed', {+ threadId: 'thread-1',+ turn: turn('turn-1', 'completed'),+ });+ await ctx.running;+ ctx.session.close();+ };++ it('presents native questions and returns selected/custom answers by their original ids', async () => {+ const ctx = await start();+ const reply = ctx.harness.serverRequest(+ 'item/tool/requestUserInput',+ request([question, { ...question, id: 'name', options: null, question: 'Database name?' }]),+ );+ await vi.waitFor(() => expect(ctx.bridge.pendingCount).toBe(1));+ const intervention = await ctx.bridge.events()[Symbol.asyncIterator]().next();+ expect(intervention.value).toMatchObject({+ data: {+ apiName: 'askUserQuestion',+ identifier: 'codex',+ provider: 'codex',+ toolCallId: 'question-1',+ },+ operationId: 'op-question',+ type: 'agent_intervention_request',+ });+ ctx.bridge.resolve('question-1', {+ result: { 'Keep the database?': 'Keep', 'Database name?': 'archive' },+ });+ await expect(reply).resolves.toEqual({+ answers: { database: { answers: ['Keep'] }, name: { answers: ['archive'] } },+ });+ expect(ctx.events).toContainEqual(+ expect.objectContaining({+ type: 'tool_result',+ data: expect.objectContaining({+ pluginState: {+ askUserAnswers: { 'Keep the database?': 'Keep', 'Database name?': 'archive' },+ },+ toolCallId: 'question-1',+ }),+ }),+ );+ await finish(ctx);+ });++ it.each(['user_cancelled', 'timeout'] as const)(+ 'resolves %s without inventing an answer',+ async (cancelReason) => {+ const ctx = await start();+ const reply = ctx.harness.serverRequest('item/tool/requestUserInput', request());+ await vi.waitFor(() => expect(ctx.bridge.pendingCount).toBe(1));+ ctx.bridge.resolve('question-1', { cancelled: true, cancelReason });+ await expect(reply).resolves.toEqual({ answers: {} });+ await finish(ctx);+ },+ );++ it('maps whole-form free text and supplementary notes without losing them', async () => {+ const ctx = await start();+ const reply = ctx.harness.serverRequest('item/tool/requestUserInput', request());+ await vi.waitFor(() => expect(ctx.bridge.pendingCount).toBe(1));+ ctx.bridge.resolve('question-1', {+ result: { __freeform__: 'Use a snapshot', __supplement__: 'Read only' },+ });+ await expect(reply).resolves.toEqual({+ answers: { database: { answers: ['Use a snapshot', 'Read only'] } },+ });+ await finish(ctx);+ });++ it('releases a pending question on interruption', async () => {+ const ctx = await start();+ const reply = ctx.harness.serverRequest('item/tool/requestUserInput', request());+ await vi.waitFor(() => expect(ctx.bridge.pendingCount).toBe(1));+ await ctx.session.interrupt();+ await expect(reply).resolves.toEqual({ answers: {} });+ await ctx.running;+ expect(ctx.bridge.pendingCount).toBe(0);+ ctx.session.close();+ });++ it('uses the native deadline and clears a timed-out question', async () => {+ const ctx = await start();+ vi.useFakeTimers();+ try {+ const reply = ctx.harness.serverRequest('item/tool/requestUserInput', {+ ...request(),+ autoResolutionMs: 100,+ });+ await vi.advanceTimersByTimeAsync(0);+ expect(ctx.bridge.pendingCount).toBe(1);+ await vi.advanceTimersByTimeAsync(100);+ await expect(reply).resolves.toEqual({ answers: {} });+ expect(ctx.bridge.pendingCount).toBe(0);+ const stream = ctx.bridge.events()[Symbol.asyncIterator]();+ await stream.next();+ expect((await stream.next()).value).toMatchObject({+ data: { cancelled: true, cancelReason: 'timeout' },+ type: 'agent_intervention_response',+ });+ await finish(ctx);+ } finally {+ vi.useRealTimers();+ ctx.session.close();+ }+ });++ it.each(['disconnect', 'close', 'complete'] as const)(+ 'clears questions when the turn ends via %s',+ async (end) => {+ const ctx = await start();+ const reply = ctx.harness.serverRequest('item/tool/requestUserInput', request());+ await vi.waitFor(() => expect(ctx.bridge.pendingCount).toBe(1));+ if (end === 'disconnect') ctx.harness.disconnect();+ else if (end === 'close') ctx.session.close();+ else+ await ctx.harness.notify('turn/completed', {+ threadId: 'thread-1',+ turn: turn('turn-1', 'completed'),+ });+ await expect(reply).resolves.toEqual({ answers: {} });+ await ctx.running;+ expect(ctx.bridge.pendingCount).toBe(0);+ ctx.session.close();+ },+ );++ it('rejects secret or ambiguous questions before persisting them', async () => {+ const ctx = await start();+ await expect(+ ctx.harness.serverRequest(+ 'item/tool/requestUserInput',+ request([{ ...question, isSecret: true }]),+ ),+ ).rejects.toThrow();+ await expect(+ ctx.harness.serverRequest('item/tool/requestUserInput', request([question, question])),+ ).rejects.toThrow();+ expect(ctx.bridge.pendingCount).toBe(0);+ expect(ctx.events.some((event) => event.type === 'tool_start')).toBe(false);+ await finish(ctx);+ });++ it('rejects a request from another turn without displaying a question', async () => {+ const ctx = await start();+ await expect(+ ctx.harness.serverRequest('item/tool/requestUserInput', {+ ...request(),+ turnId: 'old-turn',+ }),+ ).rejects.toThrow();+ expect(ctx.bridge.pendingCount).toBe(0);+ await finish(ctx);+ });++ it('leaves the operation bridge usable when startup fails before a turn begins', async () => {+ const harness = createClientHarness({ connectError: new Error('unavailable') });+ const { session } = createSession(harness);+ const bridge = new AskUserBridge('retry-operation', {+ identifier: 'codex',+ provider: 'codex',+ });+ await expect(+ session.run({+ askUserBridge: bridge,+ input: [],+ onRawMessage: vi.fn(),+ operationId: 'retry-operation',+ }),+ ).rejects.toThrow('unavailable');+ const answer = bridge.pending({ arguments: {}, toolCallId: 'retry-question' });+ expect(bridge.pendingCount).toBe(1);+ bridge.cancelAll();+ await expect(answer).resolves.toMatchObject({ cancelled: true });+ session.close();+ });+ });+const provenance = (operationId: string) => ({LOBEHUB_AGENT_ID: 'agent',LOBEHUB_OPERATION_ID: operationId,diff --git a/packages/heterogeneous-agents/src/codex/CodexThreadSession.ts b/packages/heterogeneous-agents/src/codex/CodexThreadSession.tsindex 417ddc92142..2aa0d0232fb 100644--- a/packages/heterogeneous-agents/src/codex/CodexThreadSession.ts+++ b/packages/heterogeneous-agents/src/codex/CodexThreadSession.ts@@ -2,6 +2,7 @@ import type { AgentStreamEvent } from '@lobechat/agent-gateway-client';import { isRecord, pickString } from '@lobechat/utils/object';import { CodexAppServerAdapter } from '../adapters/codexAppServer';+import type { AskUserBridge } from '../askUser';import type { HeterogeneousAgentRuntimeStatus } from '../spawn/claudeAgentSdkSession';import { toStreamEvent } from '../spawn/streamEvent';import type { UsageData } from '../types';@@ -22,6 +23,11 @@ import type {TurnStartResponse,UserInput,} from './protocol';+import {+ codexUserInputArguments,+ codexUserInputResponse,+ parseCodexUserInput,+} from './requestUserInput';const CODEX_APP_SERVER_TRANSPORT = 'codex-app-server' as const;/** An interrupted turn settled within 250 ms in probes; this bounds slow tool teardown. */@@ -39,6 +45,7 @@ const toThreadResumeParams = (threadId: string, params: ThreadStartParams): Threinterface ActiveTurn {adapter: CodexAppServerAdapter;+ askUserBridge?: AskUserBridge;completion: Promise<void>;interruptRequest?: Promise<void>;interruptRequested: boolean;@@ -57,6 +64,7 @@ interface ThreadNameSetParams {}export interface CodexThreadTurnOptions {+ askUserBridge?: AskUserBridge;input: UserInput[];onRawMessage: (line: string) => Promise<void> | void;operationId: string;@@ -151,6 +159,7 @@ export class CodexThreadSession {});const activeTurn: ActiveTurn = {adapter,+ askUserBridge: options.askUserBridge,completion,interruptRequested: this.interruptRequested,notificationQueue: Promise.resolve(),@@ -198,6 +207,7 @@ export class CodexThreadSession {this.emitStatus('error', options.operationId);throw error;} finally {+ this.activeTurn?.askUserBridge?.cancelAll('session_ended');for (const unsubscribe of traceUnsubscribers) unsubscribe();this.activeTurn = undefined;this.interruptRequested = false;@@ -212,6 +222,7 @@ export class CodexThreadSession {if (!activeTurn) return;activeTurn.interruptRequested = true;+ activeTurn.askUserBridge?.cancelAll('session_ended');if (!activeTurn.turnId) return;try {await this.requestInterrupt(activeTurn);@@ -344,13 +355,14 @@ export class CodexThreadSession {this.options.client.subscribe(threadId, (method, params) =>this.enqueueNotification(method, params),),- this.options.client.subscribeServerRequests(threadId, (method) => {+ this.options.client.subscribeServerRequests(threadId, (method, params) => {if (method === 'item/commandExecution/requestApproval' ||method === 'item/fileChange/requestApproval') {return { decision: 'cancel' };}+ if (method === 'item/tool/requestUserInput') return this.requestUserInput(params);throw new Error(`Unsupported Codex app-server request: ${method}`);}),this.options.client.registerThread(@@ -372,6 +384,51 @@ export class CodexThreadSession {if (response.model) this.updateModel(response.model);}+ private async requestUserInput(params: unknown) {+ const request = parseCodexUserInput(params);+ const activeTurn = this.activeTurn;+ const bridge = activeTurn?.askUserBridge;+ if (+ !activeTurn ||+ !bridge ||+ bridge.operationId !== activeTurn.operationId ||+ request.threadId !== this.threadId ||+ request.turnId !== activeTurn.turnId ||+ activeTurn.terminalNotificationReceived ||+ activeTurn.interruptRequested+ )+ throw new Error('Codex user input has no matching active operation');++ const args = codexUserInputArguments(request);+ // Serialize visible tool events with native notifications, but never put+ // the human wait on that queue: interrupts and nonblocking turns must flow.+ activeTurn.notificationQueue = activeTurn.notificationQueue.then(() =>+ this.emitEvents(+ activeTurn.adapter.startUserInput(request.itemId, args),+ activeTurn.operationId,+ ),+ );+ await activeTurn.notificationQueue;+ if (+ activeTurn.interruptRequested ||+ activeTurn.terminalNotificationReceived ||+ activeTurn.transportInterrupted+ )+ return { answers: {} };+ const answer = await bridge.pending(+ { arguments: args, toolCallId: request.itemId },+ request.autoResolutionMs ? { timeoutMs: request.autoResolutionMs } : {},+ );+ activeTurn.notificationQueue = activeTurn.notificationQueue.then(() =>+ this.emitEvents(+ activeTurn.adapter.completeUserInput(request.itemId, answer),+ activeTurn.operationId,+ ),+ );+ await activeTurn.notificationQueue;+ return codexUserInputResponse(request, answer);+ }+private handleDisconnect(): void {if (this.closedByHost) return;this.attached = false;@@ -395,6 +452,7 @@ export class CodexThreadSession {const activeTurn = this.activeTurn;if (!activeTurn || activeTurn.transportInterrupted) return;activeTurn.transportInterrupted = true;+ activeTurn.askUserBridge?.cancelAll('session_ended');activeTurn.notificationQueue = activeTurn.notificationQueue.then(() =>this.emitEvents(activeTurn.adapter.interruptForTransportFailure(), activeTurn.operationId),@@ -412,6 +470,7 @@ export class CodexThreadSession {const notification = params as TurnCompletedNotification;if (notification.turn.status !== 'inProgress') {activeTurn.terminalNotificationReceived = true;+ activeTurn.askUserBridge?.cancelAll('session_ended');}}diff --git a/packages/heterogeneous-agents/src/codex/appServerParams.test.ts b/packages/heterogeneous-agents/src/codex/appServerParams.test.tsindex 101337b90c5..4af38039742 100644--- a/packages/heterogeneous-agents/src/codex/appServerParams.test.ts+++ b/packages/heterogeneous-agents/src/codex/appServerParams.test.ts@@ -42,9 +42,10 @@ describe('Codex app-server payload builders', () => {).toEqual({approvalPolicy: 'never',config: {- model_provider: 'openai',- model_reasoning_effort: 'high',- service_tier: 'fast',+ 'features.default_mode_request_user_input': true,+ 'model_provider': 'openai',+ 'model_reasoning_effort': 'high',+ 'service_tier': 'fast',},cwd: '/workspace/nested',ephemeral: true,diff --git a/packages/heterogeneous-agents/src/codex/appServerParams.ts b/packages/heterogeneous-agents/src/codex/appServerParams.tsindex d84041c6c6b..bc6f2387662 100644--- a/packages/heterogeneous-agents/src/codex/appServerParams.ts+++ b/packages/heterogeneous-agents/src/codex/appServerParams.ts@@ -151,7 +151,9 @@ export const buildCodexAppServerThreadParams = (cwd: string,initialModel?: string,): ThreadStartParams => {- const config: Record<string, JsonValue> = {};+ const config: Record<string, JsonValue> = {+ 'features.default_mode_request_user_input': true,+ };let effectiveCwd = cwd;let ephemeral = false;let model = initialModel;diff --git a/packages/heterogeneous-agents/src/codex/codexAgentHandle.ts b/packages/heterogeneous-agents/src/codex/codexAgentHandle.tsindex 2c3af4f1714..8dde81683a6 100644--- a/packages/heterogeneous-agents/src/codex/codexAgentHandle.ts+++ b/packages/heterogeneous-agents/src/codex/codexAgentHandle.ts@@ -1,5 +1,6 @@import { PassThrough } from 'node:stream';+import type { AskUserBridge } from '../askUser';import type { AgentPromptInput } from '../protocol';import { createEventQueue } from '../spawn/agentEventQueue';import { buildCodexLobeHubContextArgs, createCodexJwtFile } from '../spawn/codexShellEnv';@@ -18,6 +19,7 @@ import { pickCodexRunProvenance } from './environment';export interface CodexAgentHandleOptions {/** Existing provider arguments; unsupported policies are rejected, never weakened. */args: string[];+ askUserBridge?: AskUserBridge;/** Caller version sent in the native initialize handshake. */clientVersion: string;/** Resolved, validated Codex executable path. */@@ -145,6 +147,7 @@ export const createCodexAgentHandle = async (};options.onStartupControl?.({ cancel });const turnOptions = {+ askUserBridge: options.askUserBridge,// Keep the already materialized user input and attachment paths unchanged.input: buildCodexAppServerInput(input),onRawMessage: (line: string) => options.onRawStdout?.(Buffer.from(line)),diff --git a/packages/heterogeneous-agents/src/codex/protocol/README.md b/packages/heterogeneous-agents/src/codex/protocol/README.mdindex b4542517287..1e72e4fa537 100644--- a/packages/heterogeneous-agents/src/codex/protocol/README.md+++ b/packages/heterogeneous-agents/src/codex/protocol/README.md@@ -14,3 +14,8 @@ The `ThreadUnsubscribe*` types come from the same command run by Codex CLI 0.160The vendored file is the transitive stable subset used by LobeHub's native app-server client. Keepwire names and nullability identical to the generated files; do not hand-edit protocol types.++`experimental/ToolRequestUserInput*.ts` are generated by Codex CLI 0.166.0's+`codex app-server generate-ts --experimental --out <directory>` output. They describe the+native `item/tool/requestUserInput` request and its question-id-keyed answer contract;+only repository formatting is applied after generation.diff --git a/packages/heterogeneous-agents/src/codex/protocol/experimental/ToolRequestUserInputAnswer.ts b/packages/heterogeneous-agents/src/codex/protocol/experimental/ToolRequestUserInputAnswer.tsnew file mode 100644index 00000000000..87e581b7cac--- /dev/null+++ b/packages/heterogeneous-agents/src/codex/protocol/experimental/ToolRequestUserInputAnswer.ts@@ -0,0 +1,8 @@+// GENERATED CODE! DO NOT MODIFY BY HAND!++// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.++/**+ * EXPERIMENTAL. Captures a user's answer to a request_user_input question.+ */+export type ToolRequestUserInputAnswer = { answers: Array<string> };diff --git a/packages/heterogeneous-agents/src/codex/protocol/experimental/ToolRequestUserInputOption.ts b/packages/heterogeneous-agents/src/codex/protocol/experimental/ToolRequestUserInputOption.tsnew file mode 100644index 00000000000..6a92bc048da--- /dev/null+++ b/packages/heterogeneous-agents/src/codex/protocol/experimental/ToolRequestUserInputOption.ts@@ -0,0 +1,8 @@+// GENERATED CODE! DO NOT MODIFY BY HAND!++// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.++/**+ * EXPERIMENTAL. Defines a single selectable option for request_user_input.+ */+export type ToolRequestUserInputOption = { label: string; description: string };diff --git a/packages/heterogeneous-agents/src/codex/protocol/experimental/ToolRequestUserInputParams.ts b/packages/heterogeneous-agents/src/codex/protocol/experimental/ToolRequestUserInputParams.tsnew file mode 100644index 00000000000..717ad511410--- /dev/null+++ b/packages/heterogeneous-agents/src/codex/protocol/experimental/ToolRequestUserInputParams.ts@@ -0,0 +1,19 @@+// GENERATED CODE! DO NOT MODIFY BY HAND!++// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.+import type { ToolRequestUserInputQuestion } from './ToolRequestUserInputQuestion';++/**+ * EXPERIMENTAL. Params sent with a request_user_input event.+ */+export type ToolRequestUserInputParams = {+ threadId: string;+ turnId: string;+ itemId: string;+ questions: Array<ToolRequestUserInputQuestion>;+ isBlocking: boolean;+ /**+ * @deprecated Use `isBlocking` to decide whether the request should block.+ */+ autoResolutionMs: number | null;+};diff --git a/packages/heterogeneous-agents/src/codex/protocol/experimental/ToolRequestUserInputQuestion.ts b/packages/heterogeneous-agents/src/codex/protocol/experimental/ToolRequestUserInputQuestion.tsnew file mode 100644index 00000000000..e030f4d4ef2--- /dev/null+++ b/packages/heterogeneous-agents/src/codex/protocol/experimental/ToolRequestUserInputQuestion.ts@@ -0,0 +1,16 @@+// GENERATED CODE! DO NOT MODIFY BY HAND!++// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.+import type { ToolRequestUserInputOption } from './ToolRequestUserInputOption';++/**+ * EXPERIMENTAL. Represents one request_user_input question and its required options.+ */+export type ToolRequestUserInputQuestion = {+ id: string;+ header: string;+ question: string;+ isOther: boolean;+ isSecret: boolean;+ options: Array<ToolRequestUserInputOption> | null;+};diff --git a/packages/heterogeneous-agents/src/codex/protocol/experimental/ToolRequestUserInputResponse.ts b/packages/heterogeneous-agents/src/codex/protocol/experimental/ToolRequestUserInputResponse.tsnew file mode 100644index 00000000000..1618b643cbd--- /dev/null+++ b/packages/heterogeneous-agents/src/codex/protocol/experimental/ToolRequestUserInputResponse.ts@@ -0,0 +1,11 @@+// GENERATED CODE! DO NOT MODIFY BY HAND!++// This file was generated by [ts-rs](https://github.com/Aleph-Alpha/ts-rs). Do not edit this file manually.+import type { ToolRequestUserInputAnswer } from './ToolRequestUserInputAnswer';++/**+ * EXPERIMENTAL. Response payload mapping question ids to answers.+ */+export type ToolRequestUserInputResponse = {+ answers: { [key in string]?: ToolRequestUserInputAnswer };+};diff --git a/packages/heterogeneous-agents/src/codex/requestUserInput.ts b/packages/heterogeneous-agents/src/codex/requestUserInput.tsnew file mode 100644index 00000000000..2b85f619201--- /dev/null+++ b/packages/heterogeneous-agents/src/codex/requestUserInput.ts@@ -0,0 +1,71 @@+import { isRecord } from '@lobechat/utils/object';+import { z } from 'zod';++import type { InterventionAnswer } from '../askUser';+import type { ToolRequestUserInputResponse } from './protocol/experimental/ToolRequestUserInputResponse';++const questionSchema = z.object({+ header: z.string().max(200),+ id: z.string().min(1),+ // Secret collection needs its own secure input surface, not a persisted chat form.+ isSecret: z.literal(false),+ options: z+ .array(z.object({ description: z.string().max(1000), label: z.string().min(1).max(200) }))+ .max(16)+ .nullable(),+ question: z.string().min(1).max(4000),+});++export const parseCodexUserInput = (params: unknown) => {+ const request = z+ .object({+ autoResolutionMs: z.number().int().positive().nullish(),+ itemId: z.string().min(1),+ questions: z.array(questionSchema).min(1).max(4),+ threadId: z.string(),+ turnId: z.string(),+ })+ .parse(params);+ if (+ new Set(request.questions.map((q) => q.id)).size !== request.questions.length ||+ new Set(request.questions.map((q) => q.question)).size !== request.questions.length+ )+ throw new Error('Codex user input questions must have unique ids and text');+ return request;+};++export const codexUserInputArguments = (request: ReturnType<typeof parseCodexUserInput>) => ({+ questions: request.questions.map((question) => ({+ header: question.header,+ multiSelect: false,+ options: (question.options ?? []).map(({ description, label }) => ({+ ...(description ? { description } : {}),+ id: label,+ label,+ })),+ question: question.question,+ })),+});++export const codexUserInputResponse = (+ request: ReturnType<typeof parseCodexUserInput>,+ answer: InterventionAnswer,+): ToolRequestUserInputResponse => {+ if (answer.cancelled || !isRecord(answer.result)) return { answers: {} };+ const result = answer.result;+ const entries = request.questions.flatMap<[string, { answers: string[] }]>((question, index) => {+ const value = result[question.question];+ const selected =+ typeof value === 'string'+ ? [value]+ : Array.isArray(value)+ ? value.filter((entry): entry is string => typeof entry === 'string')+ : [];+ if (index === 0) {+ if (typeof result.__freeform__ === 'string') selected.push(result.__freeform__);+ if (typeof result.__supplement__ === 'string') selected.push(result.__supplement__);+ }+ return selected.length > 0 ? [[question.id, { answers: selected }]] : [];+ });+ return { answers: Object.fromEntries(entries) };+};diff --git a/packages/types/src/agent/heterogeneousIntervention.ts b/packages/types/src/agent/heterogeneousIntervention.tsindex 5fa5ba111e6..8c27a3cd50b 100644--- a/packages/types/src/agent/heterogeneousIntervention.ts+++ b/packages/types/src/agent/heterogeneousIntervention.ts@@ -5,6 +5,7 @@ export type HeterogeneousAgentInterventionKind =export const HETEROGENEOUS_AGENT_INTERVENTION_PROVIDERS = ['claude-code',+ 'codex','copilot','cursor','devin',diff --git a/packages/types/src/tool/intervention.test.ts b/packages/types/src/tool/intervention.test.tsindex 97948a0b4a3..9200776e5e5 100644--- a/packages/types/src/tool/intervention.test.ts+++ b/packages/types/src/tool/intervention.test.ts@@ -3,6 +3,12 @@ import { describe, expect, it } from 'vitest';import { classifyToolInterventionPresentation } from './intervention';describe('classifyToolInterventionPresentation', () => {+ it('renders native Codex questions as a form', () => {+ expect(classifyToolInterventionPresentation('codex', 'askUserQuestion')).toEqual({+ interactionKind: 'question',+ surface: 'form',+ });+ });it('renders Devin questions and provider-specific interactions as forms', () => {expect(classifyToolInterventionPresentation('copilot', 'askUserQuestion')).toEqual({interactionKind: 'question',diff --git a/packages/types/src/tool/intervention.ts b/packages/types/src/tool/intervention.tsindex fac1123c397..1515b10f0ed 100644--- a/packages/types/src/tool/intervention.ts+++ b/packages/types/src/tool/intervention.ts@@ -164,6 +164,7 @@ export type ToolInterventionPresentation = {const ASK_USER_QUESTION_IDENTIFIERS = new Set(['claude-code',+ 'codex','copilot','cursor','devin',@@ -175,6 +176,7 @@ const ASK_USER_QUESTION_IDENTIFIERS = new Set([const HETEROGENEOUS_CUSTOM_INTERACTION_IDENTIFIERS = new Set(['claude-code',+ 'codex','copilot','cursor','devin',diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/customInteractionHandlers.test.ts b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/customInteractionHandlers.test.tsindex 447c478813d..c71f2bc3a53 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/customInteractionHandlers.test.ts+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/customInteractionHandlers.test.ts@@ -108,7 +108,7 @@ describe('customInteractionHandlers', () => {});});- it.each(['devin', 'droid', 'opencode', 'qoder'])(+ it.each(['codex', 'devin', 'droid', 'opencode', 'qoder'])('routes %s tools through the heterogeneous custom flow',(type) => {expect(isCustomInteractionIdentifier(type, 'askUserQuestion')).toBe(true);diff --git a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/customInteractionHandlers.ts b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/customInteractionHandlers.tsindex b100ed7c1fa..a2152dc8576 100644--- a/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/customInteractionHandlers.ts+++ b/src/features/Conversation/Messages/AssistantGroup/Tool/Detail/Intervention/customInteractionHandlers.ts@@ -171,6 +171,7 @@ const findCustomInteractionSubmitHandler = (identifier: string, apiName?: string*/const HETERO_CUSTOM_INTERACTION_IDENTIFIERS = new Set<string>([ClaudeCodeIdentifier,+ 'codex',COPILOT_IDENTIFIER,CURSOR_IDENTIFIER,DEVIN_IDENTIFIER,diff --git a/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts b/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.tsindex 7b88e27d5f1..349d3359b77 100644--- a/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts+++ b/src/store/chat/slices/agentRun/actions/__tests__/conversationControl.test.ts@@ -3391,7 +3391,7 @@ describe('ConversationControl actions', () => {expect(persistAnswersSpy).not.toHaveBeenCalled();});- it('fails closed after an unavailable durable source when operation memory is empty', async () => {+ it('uses the persisted operation after an unavailable durable source on cold start', async () => {const { result } = renderHook(() => useChatStore());const agentId = 'remote-agent';const topicId = 'remote-topic';@@ -3422,23 +3422,24 @@ describe('ConversationControl actions', () => {const sourceMutation = vi.mocked(lambdaClient.aiAgent.resolveAgentInterventionBySource.mutate,);- const pluginSpy = vi- .spyOn(result.current, 'optimisticUpdateMessagePlugin')- .mockResolvedValue(undefined);const legacyRemoteSubmit = vi.mocked(lambdaClient.aiAgent.submitHeteroIntervention.mutate);const localSubmit = vi.spyOn(heterogeneousAgentService, 'submitIntervention').mockResolvedValue(undefined as any);await act(async () => {- await expect(- result.current.submitHeteroIntervention(toolMessage.id, 'submit', { Question: 'Answer' }),- ).rejects.toThrow('Question runtime is unavailable');+ await result.current.submitHeteroIntervention(toolMessage.id, 'submit', {+ Question: 'Answer',+ });});expect(sourceMutation).toHaveBeenCalledOnce();- expect(pluginSpy).not.toHaveBeenCalled();- expect(legacyRemoteSubmit).not.toHaveBeenCalled();+ expect(legacyRemoteSubmit).toHaveBeenCalledWith({+ operationId: 'server-operation-source-unavailable',+ resolutionRequestId: expect.any(String),+ result: { Question: 'Answer' },+ toolCallId: 'call-source-unavailable',+ });expect(localSubmit).not.toHaveBeenCalled();});@@ -3479,9 +3480,7 @@ describe('ConversationControl actions', () => {});});- const pluginSpy = vi- .spyOn(result.current, 'optimisticUpdateMessagePlugin')- .mockResolvedValue(undefined);+ vi.spyOn(result.current, 'optimisticUpdateMessagePlugin').mockResolvedValue(undefined);vi.spyOn(result.current, 'optimisticUpdateMessageContent').mockResolvedValue(undefined);vi.spyOn(messageService, 'updateMessagePluginState').mockResolvedValue({messages: [],diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationControl.questionLifecycle.test.ts b/src/store/chat/slices/agentRun/actions/entries/conversationControl.questionLifecycle.test.tsindex 080a4c80066..40c85933bbb 100644--- a/src/store/chat/slices/agentRun/actions/entries/conversationControl.questionLifecycle.test.ts+++ b/src/store/chat/slices/agentRun/actions/entries/conversationControl.questionLifecycle.test.ts@@ -64,6 +64,55 @@ const makeState = (ended: boolean) => {beforeEach(() => vi.resetAllMocks());describe('question actions racing tool completion', () => {+ it('refuses delivery when neither runtime memory nor the card identifies an operation', async () => {+ const { control, state } = makeState(false);+ state.operations = {};+ state.dbMessagesMap[key][0].pluginIntervention = { status: 'pending' };+ state.checkQuestionSubmission = vi.fn().mockResolvedValue(false);++ await expect(+ control.submitHeteroIntervention('question', 'skip', undefined, context),+ ).rejects.toThrow('Question runtime is unavailable');++ expect(lambdaClient.aiAgent.submitHeteroIntervention.mutate).not.toHaveBeenCalled();+ expect(heterogeneousAgentService.submitIntervention).not.toHaveBeenCalled();+ });++ it.each(['submit', 'skip', 'cancel'] as const)(+ 'delivers a cold-loaded %s using the persisted operation when OSS has no generic claim store',+ async (action) => {+ const { control, state } = makeState(false);+ state.operations = {};+ state.internal_getConversationContext = () => context;+ state.checkQuestionSubmission = vi.fn().mockResolvedValue(false);+ vi.mocked(aiAgentService.resolveAgentInterventionBySource).mockResolvedValue({+ handled: false,+ });+ vi.mocked(lambdaClient.aiAgent.submitHeteroIntervention.mutate).mockResolvedValue(undefined);+ const answers = { 'Which drink?': 'Tea' };++ await control.submitHeteroIntervention(+ 'question',+ action,+ action === 'submit' ? answers : undefined,+ context,+ );++ expect(lambdaClient.aiAgent.submitHeteroIntervention.mutate).toHaveBeenCalledWith(+ expect.objectContaining({+ operationId: 'operation',+ toolCallId: 'call',+ ...(action === 'submit' ? { result: answers } : { cancelled: true }),+ }),+ );+ expect(heterogeneousAgentService.submitIntervention).not.toHaveBeenCalled();+ expect(state.dbMessagesMap[key][0].pluginIntervention).toMatchObject({+ status: 'pending',+ resolving: true,+ });+ },+ );+it.each(['desktop', 'remote', 'source'] as const)('preserves skip intent until the %s ACK and clears it for a later cancel',async (transport) => {diff --git a/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts b/src/store/chat/slices/agentRun/actions/entries/conversationControl.tsindex daf66097eff..dbdedf8c3d8 100644--- a/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts+++ b/src/store/chat/slices/agentRun/actions/entries/conversationControl.ts@@ -1686,14 +1686,14 @@ export class ConversationControlActionImpl {// Walk up to the assistant that owns this tool. `messageOperationMap` is a// most-granular pointer, so it may reference a transient child op- // (`reasoning`, `toolCalling`, ...), not the runtime execution that owns- // the AskUser bridge. This memory-only lookup is deliberately deferred- // until the durable path is unavailable or reports `handled: false`; it is- // provenance for local desktop IPC / legacy fallback, never server auth.+ // (`reasoning`, `toolCalling`, ...), not the runtime owning the AskUser bridge.+ // Prefer live IPC provenance; on OSS reload, the persisted op locates the+ // remote callback. The server still authorizes the operation independently.const { messageOperationMap } = this.#get();const candidateOperationId =(toolMessage.parentId && messageOperationMap?.[toolMessage.parentId]) ??- messageOperationMap?.[toolMessageId];+ messageOperationMap?.[toolMessageId] ??+ originalIntervention?.operationId;if (!candidateOperationId) {if (await this.#get().checkQuestionSubmission(toolMessageId, effectiveContext)) {