Skip to content

Commit 54cf346

Browse files
committed
fix: preserve pending input across authority changes
1 parent 1bb20fb commit 54cf346

10 files changed

Lines changed: 263 additions & 44 deletions

File tree

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

Lines changed: 30 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -172,23 +172,37 @@ export async function activateCodexAttemptTurn(
172172
signal: runAbortController.signal,
173173
});
174174
steeringQueueRef.current = activeSteeringQueue;
175+
const claimPendingUserInputAnswer = async (
176+
text: string,
177+
optionsLocal?: CodexSteeringQueueOptions,
178+
) => {
179+
if (optionsLocal?.isInboundUserMessage !== true || optionsLocal.images?.length) {
180+
return false;
181+
}
182+
const claimed = await claimPendingAgentQuestionAnswer({
183+
sessionKey: params.sessionKey ?? params.sessionId,
184+
text,
185+
persist: optionsLocal.userTurnTranscriptRecorder
186+
? async () => {
187+
await optionsLocal.userTurnTranscriptRecorder?.persistApproved();
188+
}
189+
: undefined,
190+
});
191+
return claimed;
192+
};
193+
const cancelPendingUserInput = (resolvedBy: string) =>
194+
cancelPendingAgentQuestionForSession({
195+
sessionKey: params.sessionKey ?? params.sessionId,
196+
resolvedBy,
197+
});
175198
const queueMessage = async (text: string, optionsLocal?: CodexSteeringQueueOptions) => {
176199
const isInboundUserMessage = optionsLocal?.isInboundUserMessage === true;
177-
if (isInboundUserMessage && !optionsLocal?.images?.length) {
178-
const claimed = await claimPendingAgentQuestionAnswer({
179-
sessionKey: params.sessionKey ?? params.sessionId,
180-
text,
181-
});
182-
if (claimed) {
183-
optionsLocal?.onQueueAccepted?.(true);
184-
return undefined;
185-
}
186-
} else if (isInboundUserMessage) {
200+
if (await claimPendingUserInputAnswer(text, optionsLocal)) {
201+
optionsLocal?.onQueueAccepted?.(true);
202+
return undefined;
203+
} else if (isInboundUserMessage && optionsLocal?.images?.length) {
187204
try {
188-
await cancelPendingAgentQuestionForSession({
189-
sessionKey: params.sessionKey ?? params.sessionId,
190-
resolvedBy: "image-reply",
191-
});
205+
await cancelPendingUserInput("image-reply");
192206
} catch (error) {
193207
// Cleanup failure must not drop the user's image turn.
194208
embeddedAgentLog.warn("failed to cancel codex gateway question before image steering", {
@@ -213,6 +227,8 @@ export async function activateCodexAttemptTurn(
213227
kind: "embedded" as const,
214228
runId: params.runId,
215229
toolAuthorityFingerprint: params.toolAuthorityFingerprint,
230+
claimPendingUserInputAnswer,
231+
cancelPendingUserInput,
216232
queueMessage,
217233
messageInjection: {
218234
isAvailable: () =>

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

Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import {
1919
} from "./run-attempt-test-harness.js";
2020

2121
const activeRunRegistrationMocks = vi.hoisted(() => ({
22+
cancelPendingAgentQuestionForSession: vi.fn(),
2223
clearActiveEmbeddedRun: vi.fn(),
2324
setActiveEmbeddedRun: vi.fn(),
2425
questionWaiters: new Map<string, (value: unknown) => void>(),
@@ -32,6 +33,7 @@ vi.mock("openclaw/plugin-sdk/agent-harness-runtime", async (importOriginal) => {
3233
cancelPendingAgentQuestionForSession: async (
3334
...args: Parameters<typeof actual.cancelPendingAgentQuestionForSession>
3435
) => {
36+
activeRunRegistrationMocks.cancelPendingAgentQuestionForSession(...args);
3537
const error = activeRunRegistrationMocks.cancelQuestionError;
3638
activeRunRegistrationMocks.cancelQuestionError = undefined;
3739
if (error) {
@@ -143,6 +145,31 @@ describe("runCodexAppServerAttempt steering", () => {
143145
});
144146
});
145147

148+
it("exposes pending-question cancellation for queued image fallback", async () => {
149+
const harness = createStartedThreadHarness();
150+
const params = createSteeringParams();
151+
activeRunRegistrationMocks.cancelPendingAgentQuestionForSession.mockClear();
152+
const run = runCodexAppServerAttempt(params);
153+
await harness.waitForMethod("turn/start");
154+
155+
let handle: { cancelPendingUserInput?: (resolvedBy: string) => Promise<boolean> } | undefined;
156+
await vi.waitFor(() => {
157+
handle = activeRunRegistrationMocks.setActiveEmbeddedRun.mock.calls.findLast(
158+
(call) => call[0] === params.sessionId,
159+
)?.[1] as typeof handle;
160+
expect(handle?.cancelPendingUserInput).toBeTypeOf("function");
161+
}, fastWait);
162+
163+
await expect(handle?.cancelPendingUserInput?.("image-reply")).resolves.toBe(false);
164+
expect(activeRunRegistrationMocks.cancelPendingAgentQuestionForSession).toHaveBeenCalledWith({
165+
sessionKey: params.sessionKey,
166+
resolvedBy: "image-reply",
167+
});
168+
169+
await harness.completeTurn({ threadId: "thread-1", turnId: "turn-1" });
170+
await run;
171+
});
172+
146173
it("accepts Gateway transcript-backed steering for the active Codex turn", async () => {
147174
const { requests, waitForMethod, completeTurn, notify } = createStartedThreadHarness();
148175
const params = createSteeringParams();

‎extensions/copilot/src/attempt-active-run.test.ts‎

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -99,6 +99,17 @@ describe("registerCopilotActiveRun", () => {
9999
expect(send).not.toHaveBeenCalled();
100100
});
101101

102+
it("exposes pending-question cancellation for queued image fallback", async () => {
103+
const { handle } = registerTestRun();
104+
105+
await expect(handle.cancelPendingUserInput?.("image-reply")).resolves.toBe(false);
106+
107+
expect(harnessMocks.cancelPendingAgentQuestionForSession).toHaveBeenCalledWith({
108+
sessionKey: "session-1",
109+
resolvedBy: "image-reply",
110+
});
111+
});
112+
102113
it("reports pre-ownership validation failure as rejected", async () => {
103114
const onQueueAccepted = vi.fn();
104115
const { handle, send } = registerTestRun({ canAcceptSteering: () => false });

‎extensions/copilot/src/attempt-active-run.ts‎

Lines changed: 26 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -25,14 +25,34 @@ export function registerCopilotActiveRun(params: {
2525
transcriptJournal: AttemptTranscriptJournal;
2626
userInputBridge: CopilotUserInputBridge;
2727
}) {
28-
const cancelGatewayQuestionBestEffort = (resolvedBy: string) => {
29-
void cancelPendingAgentQuestionForSession({
28+
const cancelPendingUserInput = (resolvedBy: string) =>
29+
cancelPendingAgentQuestionForSession({
3030
sessionKey: params.input.sessionKey ?? params.input.sessionId,
3131
resolvedBy,
32-
}).catch((error: unknown) => {
32+
});
33+
const cancelGatewayQuestionBestEffort = (resolvedBy: string) => {
34+
void cancelPendingUserInput(resolvedBy).catch((error: unknown) => {
3335
embeddedAgentLog.warn("failed to cancel copilot gateway question during shutdown", { error });
3436
});
3537
};
38+
const claimPendingUserInputAnswer = async (
39+
text: string,
40+
options?: CopilotQueueMessageOptions,
41+
) => {
42+
if (options?.isInboundUserMessage !== true || options.images?.length) {
43+
return false;
44+
}
45+
const claimed = await claimPendingAgentQuestionAnswer({
46+
sessionKey: params.input.sessionKey ?? params.input.sessionId,
47+
text,
48+
persist: options.userTurnTranscriptRecorder
49+
? async () => {
50+
await options.userTurnTranscriptRecorder?.persistApproved();
51+
}
52+
: undefined,
53+
});
54+
return claimed;
55+
};
3656
const queueMessage = async (text: string, options?: CopilotQueueMessageOptions) => {
3757
let acceptanceReported = false;
3858
// Acceptance transfers fallback ownership irrevocably. A later transcript
@@ -46,18 +66,7 @@ export function registerCopilotActiveRun(params: {
4666
};
4767
let messageId: string;
4868
try {
49-
if (
50-
options?.isInboundUserMessage === true &&
51-
(await claimPendingAgentQuestionAnswer({
52-
sessionKey: params.input.sessionKey ?? params.input.sessionId,
53-
text,
54-
persist: options.userTurnTranscriptRecorder
55-
? async () => {
56-
await options.userTurnTranscriptRecorder?.persistApproved();
57-
}
58-
: undefined,
59-
}))
60-
) {
69+
if (await claimPendingUserInputAnswer(text, options)) {
6170
reportAcceptance(true);
6271
return undefined;
6372
}
@@ -95,6 +104,8 @@ export function registerCopilotActiveRun(params: {
95104
kind: "embedded" as const,
96105
runId: params.input.runId,
97106
toolAuthorityFingerprint: params.input.toolAuthorityFingerprint,
107+
claimPendingUserInputAnswer,
108+
cancelPendingUserInput,
98109
queueMessage,
99110
messageInjection: {
100111
isAvailable: () => params.canAcceptSteering() && !params.isSettled() && !params.isAborted(),

‎src/agents/embedded-agent-runner/run-state.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,13 @@ export type EmbeddedAgentQueueHandle = {
3131
runId?: string;
3232
/** Exact authority of the concrete provider/model attempt behind this handle. */
3333
toolAuthorityFingerprint?: string;
34+
/** Atomically consumes one plain-text answer for this run's pending user-input request. */
35+
claimPendingUserInputAnswer?: (
36+
text: string,
37+
options?: EmbeddedAgentQueueMessageOptions,
38+
) => Promise<boolean>;
39+
/** Cancels this run's pending user-input request before an image is queued as a later turn. */
40+
cancelPendingUserInput?: (resolvedBy: string) => Promise<boolean>;
3441
queueMessage: (
3542
text: string,
3643
options?: EmbeddedAgentQueueMessageOptions,

‎src/agents/embedded-agent-runner/run/attempt-queue-message.ts‎

Lines changed: 21 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -346,19 +346,7 @@ export async function steerActiveSessionWithOptionalDeliveryWait(
346346
log.warn(`failed to cancel ask_user before image steering: ${String(error)}`);
347347
}
348348
}
349-
if (
350-
isInboundUserMessage &&
351-
isPlainTextAnswer &&
352-
(await claimPendingAgentQuestionAnswer({
353-
sessionKey,
354-
text,
355-
persist: options.userTurnTranscriptRecorder
356-
? async () => {
357-
await options.userTurnTranscriptRecorder?.persistApproved();
358-
}
359-
: undefined,
360-
}))
361-
) {
349+
if (await claimEmbeddedPendingUserInputAnswer(text, options, sessionKey)) {
362350
options?.onQueueAccepted?.(true);
363351
return;
364352
}
@@ -402,3 +390,23 @@ export async function steerActiveSessionWithOptionalDeliveryWait(
402390
throw error;
403391
}
404392
}
393+
394+
export async function claimEmbeddedPendingUserInputAnswer(
395+
text: string,
396+
options: EmbeddedAgentQueueMessageOptions | undefined,
397+
sessionKey?: string,
398+
): Promise<boolean> {
399+
if (options?.isInboundUserMessage !== true || options.images?.length) {
400+
return false;
401+
}
402+
const claimed = await claimPendingAgentQuestionAnswer({
403+
sessionKey,
404+
text,
405+
persist: options.userTurnTranscriptRecorder
406+
? async () => {
407+
await options.userTurnTranscriptRecorder?.persistApproved();
408+
}
409+
: undefined,
410+
});
411+
return claimed;
412+
}

‎src/agents/embedded-agent-runner/run/attempt-stream-prepare.ts‎

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ import {
1717
import { getGlobalHookRunner } from "../../../plugins/hook-runner-global.js";
1818
import { recordStructuredReplayTrustForToolCall } from "../../agent-tools.before-tool-call.js";
1919
import { subscribeEmbeddedAgentSession } from "../../embedded-agent-subscribe.js";
20+
import { cancelPendingAgentQuestionForSession } from "../../harness/gateway-question.js";
2021
import { runAgentHarnessBeforeAgentFinalizeHook } from "../../harness/lifecycle-hook-helpers.js";
2122
import {
2223
AGENT_RUN_RESTART_ABORT_STOP_REASON,
@@ -43,7 +44,10 @@ import {
4344
requiresCompletionRequiredAsyncTaskWait,
4445
type AsyncStartedToolMeta,
4546
} from "./attempt-async-tasks.js";
46-
import { steerActiveSessionWithOptionalDeliveryWait } from "./attempt-queue-message.js";
47+
import {
48+
claimEmbeddedPendingUserInputAnswer,
49+
steerActiveSessionWithOptionalDeliveryWait,
50+
} from "./attempt-queue-message.js";
4751
import type { EmbeddedAttemptClientToolCallSlot } from "./attempt-result.js";
4852
import {
4953
resolveFinalAssistantRawText,
@@ -429,6 +433,10 @@ export function prepareEmbeddedAttemptStream(input: {
429433
...(attempt.toolAuthorityFingerprint
430434
? { toolAuthorityFingerprint: attempt.toolAuthorityFingerprint }
431435
: {}),
436+
claimPendingUserInputAnswer: (text, options) =>
437+
claimEmbeddedPendingUserInputAnswer(text, options, attempt.sessionKey),
438+
cancelPendingUserInput: (resolvedBy) =>
439+
cancelPendingAgentQuestionForSession({ sessionKey: attempt.sessionKey, resolvedBy }),
432440
queueMessage,
433441
messageInjection: {
434442
isAvailable: () =>

‎src/agents/embedded-agent-runner/runs.steering.test.ts‎

Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -380,6 +380,90 @@ describe("embedded-agent active-run steering", () => {
380380
);
381381
});
382382

383+
it("atomically claims pending plain-text input across an authority mismatch", async () => {
384+
const claimPendingUserInputAnswer = vi.fn(async () => true);
385+
const queueMessage = vi.fn(async () => {});
386+
setActiveEmbeddedRun("session-pending-question", {
387+
...createEmbeddedRunHandle(),
388+
toolAuthorityFingerprint: "fallback-authority",
389+
claimPendingUserInputAnswer,
390+
queueMessage,
391+
});
392+
393+
const options = {
394+
isInboundUserMessage: true,
395+
onQueueAccepted: vi.fn(),
396+
toolAuthorityFingerprint: "default-authority",
397+
} as const;
398+
const outcome = await queueEmbeddedAgentMessageWithOutcomeAsync(
399+
"session-pending-question",
400+
"2",
401+
options,
402+
);
403+
404+
expect(outcome).toMatchObject({ queued: true, target: "embedded_run" });
405+
expect(claimPendingUserInputAnswer).toHaveBeenCalledWith("2", options);
406+
expect(options.onQueueAccepted).toHaveBeenCalledWith(true);
407+
expect(queueMessage).not.toHaveBeenCalled();
408+
});
409+
410+
it.each([
411+
{ label: "no pending question", claimed: false, images: undefined },
412+
{
413+
label: "image input",
414+
claimed: true,
415+
images: [{ type: "image" as const, data: "png", mimeType: "image/png" as const }],
416+
},
417+
])("preserves authority mismatch for $label", async ({ claimed, images }) => {
418+
const claimPendingUserInputAnswer = vi.fn(async () => claimed);
419+
const cancelPendingUserInput = vi.fn(async () => true);
420+
const queueMessage = vi.fn(async () => {});
421+
setActiveEmbeddedRun("session-pending-question-rejected", {
422+
...createEmbeddedRunHandle(),
423+
toolAuthorityFingerprint: "fallback-authority",
424+
claimPendingUserInputAnswer,
425+
cancelPendingUserInput,
426+
queueMessage,
427+
});
428+
429+
const outcome = await queueEmbeddedAgentMessageWithOutcomeAsync(
430+
"session-pending-question-rejected",
431+
"continue",
432+
{
433+
isInboundUserMessage: true,
434+
toolAuthorityFingerprint: "default-authority",
435+
images,
436+
},
437+
);
438+
439+
expect(outcome).toMatchObject({ queued: false, reason: "tool_authority_mismatch" });
440+
expect(claimPendingUserInputAnswer).toHaveBeenCalledTimes(images ? 0 : 1);
441+
expect(cancelPendingUserInput).toHaveBeenCalledTimes(images ? 1 : 0);
442+
expect(queueMessage).not.toHaveBeenCalled();
443+
});
444+
445+
it("cancels pending input before rejecting an unsupported queued image", async () => {
446+
const cancelPendingUserInput = vi.fn(async () => true);
447+
setActiveEmbeddedRun("session-unsupported-question-image", {
448+
...createEmbeddedRunHandle(),
449+
toolAuthorityFingerprint: "same-authority",
450+
cancelPendingUserInput,
451+
});
452+
453+
const outcome = await queueEmbeddedAgentMessageWithOutcomeAsync(
454+
"session-unsupported-question-image",
455+
"inspect",
456+
{
457+
isInboundUserMessage: true,
458+
toolAuthorityFingerprint: "same-authority",
459+
images: [{ type: "image", data: "png", mimeType: "image/png" }],
460+
},
461+
);
462+
463+
expect(outcome).toMatchObject({ queued: false, reason: "image_input_unsupported" });
464+
expect(cancelPendingUserInput).toHaveBeenCalledWith("image-reply");
465+
});
466+
383467
it("reports accepted steering without transcript confirmation as non-replayable", async () => {
384468
setActiveEmbeddedRun("session-unconfirmed", {
385469
...createEmbeddedRunHandle(),

0 commit comments

Comments
 (0)