Skip to content

Commit b54fafa

Browse files
authored
fix(codex): preserve operator input request ownership (#121171)
1 parent 019bd9a commit b54fafa

11 files changed

Lines changed: 241 additions & 41 deletions

‎extensions/codex/src/app-server/attempt-steering.test.ts‎

Lines changed: 55 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -387,7 +387,7 @@ describe("Codex app-server steering queue", () => {
387387
await vi.advanceTimersByTimeAsync(0);
388388
});
389389

390-
it("answers pending user input without steering", async () => {
390+
it("answers pending user input only for an inbound user message", async () => {
391391
const request = vi.fn(async () => ({ turnId: "turn-1" }));
392392
const answerPendingUserInput = vi.fn(() => true);
393393
const queue = createQueue(request, {
@@ -398,12 +398,62 @@ describe("Codex app-server steering queue", () => {
398398
});
399399
const onQueueAccepted = vi.fn();
400400

401-
await queue.queue("answer locally", { debounceMs: 0, onQueueAccepted });
401+
await queue.queue("answer locally", {
402+
debounceMs: 0,
403+
isInboundUserMessage: true,
404+
onQueueAccepted,
405+
});
402406
expect(answerPendingUserInput).toHaveBeenCalledWith("answer locally");
403407
expect(onQueueAccepted).toHaveBeenCalledWith(true);
404408
expect(request).not.toHaveBeenCalled();
405409
});
406410

411+
it("steers internal completion messages without claiming pending user input", async () => {
412+
const request = vi.fn(async () => ({ turnId: "turn-1" }));
413+
const claimPendingUserInput = vi.fn(() => ({
414+
answer: vi.fn(() => true),
415+
cancel: vi.fn(() => true),
416+
}));
417+
const queue = createQueue(request, { claimPendingUserInput });
418+
419+
const queued = queue.queue("subagent completed", { debounceMs: 0 });
420+
await vi.advanceTimersByTimeAsync(0);
421+
422+
expect(claimPendingUserInput).not.toHaveBeenCalled();
423+
expect(request).toHaveBeenCalledWith(
424+
"turn/steer",
425+
expect.objectContaining({
426+
input: [{ type: "text", text: "subagent completed", text_elements: [] }],
427+
}),
428+
steerRequestOptions,
429+
);
430+
expect(queue.confirmConsumed("openclaw:turn-1:steer:1")).toBe(true);
431+
await queued;
432+
});
433+
434+
it("rejects sealed inbound admission before claiming pending user input", async () => {
435+
const request = vi.fn(async () => ({ turnId: "turn-1" }));
436+
const claimPendingUserInput = vi.fn(() => ({
437+
answer: vi.fn(() => true),
438+
cancel: vi.fn(() => true),
439+
}));
440+
const queue = createQueue(request, { claimPendingUserInput });
441+
const onQueueAccepted = vi.fn();
442+
443+
queue.sealAdmission();
444+
await expect(
445+
queue.queue("too late", {
446+
debounceMs: 0,
447+
isInboundUserMessage: true,
448+
onQueueAccepted,
449+
}),
450+
).rejects.toThrow("queue admission sealed");
451+
452+
expect(claimPendingUserInput).not.toHaveBeenCalled();
453+
expect(onQueueAccepted).toHaveBeenCalledWith(false);
454+
expect(request).not.toHaveBeenCalled();
455+
});
456+
407457
it("steers a complete image reply before releasing pending input", async () => {
408458
const request = vi.fn(async () => ({ turnId: "turn-1" }));
409459
const answerPendingUserInput = vi.fn(() => true);
@@ -416,6 +466,7 @@ describe("Codex app-server steering queue", () => {
416466
});
417467

418468
const queued = queue.queue("compare these", {
469+
isInboundUserMessage: true,
419470
images: [
420471
{ type: "image", data: PNG_1X1, mimeType: "image/png" },
421472
{ type: "image", data: PNG_1X1, mimeType: "image/png" },
@@ -470,6 +521,7 @@ describe("Codex app-server steering queue", () => {
470521
});
471522

472523
const imageQueued = queue.queue("image reply", {
524+
isInboundUserMessage: true,
473525
images: [{ type: "image", data: PNG_1X1, mimeType: "image/png" }],
474526
});
475527
await vi.advanceTimersByTimeAsync(0);
@@ -509,6 +561,7 @@ describe("Codex app-server steering queue", () => {
509561
});
510562

511563
const queued = queue.queue("compare this", {
564+
isInboundUserMessage: true,
512565
images: [{ type: "image", data: PNG_1X1, mimeType: "image/png" }],
513566
});
514567
const rejected = expect(queued).rejects.toThrow("cannot steer this turn");

‎extensions/codex/src/app-server/attempt-steering.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -272,7 +272,9 @@ export function createCodexSteeringQueue(params: {
272272
options?.onQueueAccepted?.(false);
273273
throw unavailableError;
274274
}
275-
const pendingUserInput = params.claimPendingUserInput();
275+
// Only operator ingress can answer a pending prompt; internal steering stays transcript input.
276+
const pendingUserInput =
277+
options?.isInboundUserMessage === true ? params.claimPendingUserInput() : undefined;
276278
if (pendingUserInput) {
277279
if (!options?.images?.length) {
278280
const answered = pendingUserInput.answer(text);

‎extensions/codex/src/app-server/run-attempt-server-requests.ts‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -114,7 +114,7 @@ export function createCodexAttemptServerRequestController(
114114
armCompletionWatchOnResponse = true;
115115
markCurrentTurnRequestProgress();
116116
}
117-
return userInputBridgeRef.current?.handleRequest({
117+
return await userInputBridgeRef.current?.handleRequest({
118118
id: request.id,
119119
params: request.params,
120120
});
@@ -125,7 +125,7 @@ export function createCodexAttemptServerRequestController(
125125
armCompletionWatchOnResponse = true;
126126
markCurrentTurnRequestProgress();
127127
}
128-
return handleCodexAppServerApprovalRequest({
128+
return await handleCodexAppServerApprovalRequest({
129129
method: request.method,
130130
requestParams: request.params,
131131
paramsForRun: params,

‎extensions/codex/src/app-server/run-attempt.steering.test.ts‎

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -495,7 +495,10 @@ describe("runCodexAppServerAttempt steering", () => {
495495
expect(onLateAccepted).toHaveBeenCalledWith(false);
496496
});
497497

498-
it("routes request_user_input prompts through the active run follow-up queue", async () => {
498+
it.each([
499+
{ name: "gateway-backed", isSecret: false },
500+
{ name: "secret", isSecret: true },
501+
])("routes $name user prompts without consuming internal steering", async ({ isSecret }) => {
499502
let notify: (notification: CodexServerNotification) => Promise<void> = async () => undefined;
500503
let handleRequest:
501504
| ((request: { id: string; method: string; params?: unknown }) => Promise<unknown>)
@@ -533,6 +536,8 @@ describe("runCodexAppServerAttempt steering", () => {
533536

534537
const params = createSteeringParams();
535538
params.onBlockReply = vi.fn();
539+
const onRunProgress = vi.fn();
540+
params.onRunProgress = onRunProgress;
536541
const run = runCodexAppServerAttempt(params);
537542
await vi.waitFor(
538543
() => expect(request.mock.calls.map(([method]) => method)).toContain("turn/start"),
@@ -547,13 +552,14 @@ describe("runCodexAppServerAttempt steering", () => {
547552
threadId: "thread-1",
548553
turnId: "turn-1",
549554
itemId: "ask-1",
555+
isBlocking: true,
550556
questions: [
551557
{
552558
id: "mode",
553559
header: "Mode",
554560
question: "Pick a mode",
555561
isOther: false,
556-
isSecret: false,
562+
isSecret,
557563
options: [
558564
{ label: "Fast", description: "Use less reasoning" },
559565
{ label: "Deep", description: "Use more reasoning" },
@@ -583,6 +589,12 @@ describe("runCodexAppServerAttempt steering", () => {
583589
item: { id: "source-message", type: "userMessage", clientId: sourceMessageId },
584590
},
585591
});
592+
expect(
593+
onRunProgress.mock.calls.some(
594+
([event]) =>
595+
(event as { reason?: string }).reason === "request:item/tool/requestUserInput:response",
596+
),
597+
).toBe(false);
586598
const onQuestionAccepted = vi.fn();
587599
await waitAndQueueActiveRunMessage(params.sessionId, "2", {
588600
isInboundUserMessage: true,
@@ -591,6 +603,9 @@ describe("runCodexAppServerAttempt steering", () => {
591603
await expect(response).resolves.toEqual({
592604
answers: { mode: { answers: ["Deep"] } },
593605
});
606+
expect(onRunProgress).toHaveBeenCalledWith(
607+
expect.objectContaining({ reason: "request:item/tool/requestUserInput:response" }),
608+
);
594609
expect(onQuestionAccepted).toHaveBeenCalledWith(true);
595610
expect(request.mock.calls.filter(([method]) => method === "turn/steer")).toHaveLength(1);
596611

‎extensions/codex/src/app-server/run-attempt.turn-watches.test.ts‎

Lines changed: 81 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import {
1212
} from "openclaw/plugin-sdk/diagnostic-runtime";
1313
import * as mediaStore from "openclaw/plugin-sdk/media-store";
1414
import { describe, expect, it, vi } from "vitest";
15+
import * as approvalBridge from "./approval-bridge.js";
1516
import { buildCodexAppServerPromptTimeoutOutcome } from "./attempt-results.js";
1617
import type { EmbeddedRunAttemptResult } from "./attempt-terminal.js";
1718
import { readAttemptTerminal } from "./attempt-terminal.test-helper.js";
@@ -1146,6 +1147,71 @@ describe("runCodexAppServerAttempt turn watches", () => {
11461147
});
11471148
});
11481149

1150+
it("keeps turn request activity active until command approval resolves", async () => {
1151+
const harness = createStartedThreadHarness();
1152+
const approvalResponse = { decision: "accept" } as const;
1153+
let resolveApproval!: (value: typeof approvalResponse) => void;
1154+
const approval = new Promise<typeof approvalResponse>((resolve) => {
1155+
resolveApproval = resolve;
1156+
});
1157+
vi.spyOn(approvalBridge, "handleCodexAppServerApprovalRequest").mockImplementation(
1158+
async () => await approval,
1159+
);
1160+
const params = makeTestParams({ timeoutMs: 500 });
1161+
const onRunProgress = vi.fn();
1162+
params.onRunProgress = onRunProgress;
1163+
1164+
const run = runCodexAppServerAttempt(params, {
1165+
turnCompletionIdleTimeoutMs: 1_000,
1166+
turnAssistantCompletionIdleTimeoutMs: 1_000,
1167+
turnTerminalIdleTimeoutMs: 1_000,
1168+
});
1169+
await harness.waitForMethod("turn/start");
1170+
1171+
const response = harness.handleServerRequest({
1172+
id: "request-pending-approval",
1173+
method: "item/commandExecution/requestApproval",
1174+
params: {
1175+
threadId: "thread-1",
1176+
turnId: "turn-1",
1177+
itemId: "command-1",
1178+
command: "echo approved",
1179+
cwd: "/workspace",
1180+
},
1181+
});
1182+
await vi.waitFor(
1183+
() =>
1184+
expect(onRunProgress).toHaveBeenCalledWith(
1185+
expect.objectContaining({
1186+
reason: "request:item/commandExecution/requestApproval:start",
1187+
}),
1188+
),
1189+
fastWait,
1190+
);
1191+
expect(
1192+
onRunProgress.mock.calls.some(
1193+
([event]) =>
1194+
(event as { reason?: string }).reason ===
1195+
"request:item/commandExecution/requestApproval:response",
1196+
),
1197+
).toBe(false);
1198+
1199+
resolveApproval(approvalResponse);
1200+
await expect(response).resolves.toEqual(approvalResponse);
1201+
expect(onRunProgress).toHaveBeenCalledWith(
1202+
expect.objectContaining({
1203+
reason: "request:item/commandExecution/requestApproval:response",
1204+
}),
1205+
);
1206+
await harness.completeTurn({ threadId: "thread-1", turnId: "turn-1" });
1207+
1208+
expect(readAttemptTerminal(await run)).toMatchObject({
1209+
aborted: false,
1210+
timedOut: false,
1211+
promptError: null,
1212+
});
1213+
});
1214+
11491215
it("keeps an eliciting MCP tool active past the completion timeout", async () => {
11501216
const harness = createStartedThreadHarness();
11511217
const bridgedResponse = {
@@ -1225,16 +1291,11 @@ describe("runCodexAppServerAttempt turn watches", () => {
12251291
});
12261292
});
12271293

1228-
it("counts pending secret user input requests as turn attempt progress", async () => {
1229-
// `item/tool/requestUserInput` records attempt progress but never suppresses
1230-
// the attempt watch while pending, so this proves the turn outlives the
1294+
it("keeps secret user input request activity active until the answer arrives", async () => {
1295+
// Pending user input must keep the active request open and outlive the
12311296
// deadline `turn:start` alone would have set. That needs
12321297
// preRequestIdleMs + pendingHoldMs > attemptIdleTimeoutMs > pendingHoldMs;
12331298
// both bounds are asserted below so load can never make it vacuous.
1234-
// The two request resets in run-attempt-server-requests.ts land ~20ms apart
1235-
// (`finally` runs at `return`, not when the bridge promise settles), so this
1236-
// cannot attribute survival to `:start` over `:response` — it guards the
1237-
// pair. Mutating either one alone still passes; mutating both fails.
12381299
const attemptIdleTimeoutMs = 1_000;
12391300
const preRequestIdleMs = 500;
12401301
const pendingHoldMs = 700;
@@ -1271,6 +1332,7 @@ describe("runCodexAppServerAttempt turn watches", () => {
12711332
threadId: "thread-1",
12721333
turnId: "turn-1",
12731334
itemId: "input-1",
1335+
isBlocking: true,
12741336
questions: [
12751337
{
12761338
id: "mode",
@@ -1300,10 +1362,21 @@ describe("runCodexAppServerAttempt turn watches", () => {
13001362
// Lower bound: the turn has now outlived the deadline turn:start alone set,
13011363
// so surviving proves the pending request moved it.
13021364
expect(Date.now() - turnObservedAt).toBeGreaterThan(attemptIdleTimeoutMs);
1303-
expect(queueActiveRunMessageForTest("session-1", "2")).toBe(true);
1365+
expect(
1366+
onRunProgress.mock.calls.some(
1367+
([event]) =>
1368+
(event as { reason?: string }).reason === "request:item/tool/requestUserInput:response",
1369+
),
1370+
).toBe(false);
1371+
expect(queueActiveRunMessageForTest("session-1", "2", { isInboundUserMessage: true })).toBe(
1372+
true,
1373+
);
13041374
await expect(response).resolves.toEqual({
13051375
answers: { mode: { answers: ["Deep"] } },
13061376
});
1377+
expect(onRunProgress).toHaveBeenCalledWith(
1378+
expect.objectContaining({ reason: "request:item/tool/requestUserInput:response" }),
1379+
);
13071380
await harness.completeTurn({ threadId: "thread-1", turnId: "turn-1" });
13081381

13091382
const result = await run;

0 commit comments

Comments
 (0)