Skip to content

Commit 6d2ba0d

Browse files
fix: steering reaches active runs across agent harnesses (#119594)
* fix steering delivery across harnesses * fix steering across moving transcript leaves * test: align steering queue expectations * fix: harden active steering ownership * fix: retain steering fallback admission * fix: reject late copilot steering * fix: prevent replay of accepted steering * fix: bind acquired chat work admission * fix: bind steering to active transcript branch
1 parent 97505b7 commit 6d2ba0d

33 files changed

Lines changed: 1072 additions & 94 deletions

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

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,9 @@
11
// Codex tests cover attempt steering plugin behavior.
22
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
3-
import { createCodexSteeringQueue } from "./attempt-steering.js";
3+
import {
4+
CodexSteeringAcceptedUnconfirmedError,
5+
createCodexSteeringQueue,
6+
} from "./attempt-steering.js";
47
import { createClientHarness } from "./test-support.js";
58

69
const PNG_1X1 =
@@ -78,10 +81,10 @@ describe("Codex app-server steering queue", () => {
7881
signal: new AbortController().signal,
7982
});
8083

81-
const outcomes: string[] = [];
84+
const outcomes: unknown[] = [];
8285
void queue.queue("steer me", { debounceMs: 0 }).then(
8386
() => outcomes.push("resolved"),
84-
(error: unknown) => outcomes.push(`rejected: ${(error as Error).message}`),
87+
(error: unknown) => outcomes.push(error),
8588
);
8689
await vi.advanceTimersByTimeAsync(0);
8790
expect((JSON.parse(harness.writes[0] ?? "{}") as { method?: string }).method).toBe(
@@ -91,7 +94,10 @@ describe("Codex app-server steering queue", () => {
9194
// Codex accepted the frame but never responds: the caller must not wait forever.
9295
await vi.advanceTimersByTimeAsync(5_000);
9396

94-
expect(outcomes).toEqual(["rejected: turn/steer timed out"]);
97+
expect(outcomes[0]).toBeInstanceOf(CodexSteeringAcceptedUnconfirmedError);
98+
expect((outcomes[0] as Error & { cause?: unknown }).cause).toMatchObject({
99+
message: "turn/steer timed out",
100+
});
95101
harness.client.close();
96102
});
97103

@@ -221,7 +227,7 @@ describe("Codex app-server steering queue", () => {
221227
const queue = createQueue(request);
222228

223229
const queued = queue.queue("completion wake", { debounceMs: 0 });
224-
const rejected = expect(queued).rejects.toThrow("steering queue cancelled");
230+
const rejected = expect(queued).rejects.toBeInstanceOf(CodexSteeringAcceptedUnconfirmedError);
225231
await vi.advanceTimersByTimeAsync(0);
226232
expect(request).toHaveBeenCalledTimes(1);
227233

@@ -239,7 +245,7 @@ describe("Codex app-server steering queue", () => {
239245
const queue = createQueue(request, { signal: controller.signal });
240246

241247
const queued = queue.queue("completion wake", { debounceMs: 0 });
242-
const rejected = expect(queued).rejects.toThrow("steering queue aborted");
248+
const rejected = expect(queued).rejects.toBeInstanceOf(CodexSteeringAcceptedUnconfirmedError);
243249
await vi.advanceTimersByTimeAsync(0);
244250
expect(request).toHaveBeenCalledTimes(1);
245251

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

Lines changed: 37 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -6,11 +6,22 @@ import {
66
embeddedAgentLog,
77
type EmbeddedRunAttemptParams,
88
} from "openclaw/plugin-sdk/agent-harness-runtime";
9-
import type { CodexAppServerClient } from "./client.js";
9+
import {
10+
isCodexAppServerIndeterminateRequestCancellationError,
11+
isCodexAppServerIndeterminateTransportError,
12+
type CodexAppServerClient,
13+
} from "./client.js";
1014
import { buildCodexUserInput } from "./user-input.js";
1115

1216
const CODEX_STEER_ALL_DEBOUNCE_MS = 500;
1317

18+
export class CodexSteeringAcceptedUnconfirmedError extends Error {
19+
constructor(message: string, options?: ErrorOptions) {
20+
super(message, options);
21+
this.name = "CodexSteeringAcceptedUnconfirmedError";
22+
}
23+
}
24+
1425
/** Per-message options for Codex steering queue behavior. */
1526
export type CodexSteeringQueueOptions = {
1627
debounceMs?: number;
@@ -36,6 +47,7 @@ export function createCodexSteeringQueue(params: {
3647
signal: AbortSignal;
3748
}) {
3849
type PendingSteerMessage = {
50+
accepted: boolean;
3951
text: string;
4052
images?: EmbeddedRunAttemptParams["images"];
4153
resolve: () => void;
@@ -75,7 +87,14 @@ export function createCodexSteeringQueue(params: {
7587
}
7688
item.settled = true;
7789
pendingMessages.delete(item);
78-
item.reject(error);
90+
item.reject(
91+
item.accepted
92+
? new CodexSteeringAcceptedUnconfirmedError(
93+
"Codex accepted steering but did not confirm transcript consumption",
94+
{ cause: error },
95+
)
96+
: error,
97+
);
7998
};
8099

81100
const closeQueue = (error: Error) => {
@@ -132,10 +151,24 @@ export function createCodexSteeringQueue(params: {
132151
},
133152
{ timeoutMs: params.requestTimeoutMs, signal: params.signal },
134153
);
154+
for (const item of liveItems) {
155+
item.accepted = true;
156+
}
135157
} catch (error) {
136158
dispatchedBatches.delete(clientUserMessageId);
159+
const acceptedUnconfirmed =
160+
isCodexAppServerIndeterminateRequestCancellationError(error) ||
161+
isCodexAppServerIndeterminateTransportError(error);
137162
for (const item of liveItems) {
138-
rejectItem(item, error);
163+
rejectItem(
164+
item,
165+
acceptedUnconfirmed
166+
? new CodexSteeringAcceptedUnconfirmedError(
167+
"Codex steering request may have been accepted before confirmation",
168+
{ cause: error },
169+
)
170+
: error,
171+
);
139172
}
140173
throw error;
141174
}
@@ -178,6 +211,7 @@ export function createCodexSteeringQueue(params: {
178211
rejectDelivery = reject;
179212
});
180213
const item = {
214+
accepted: false,
181215
text,
182216
images,
183217
resolve: resolveDelivery,

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

Lines changed: 19 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,11 +2,16 @@ import {
22
cancelPendingAgentQuestionForSession,
33
claimPendingAgentQuestionAnswer,
44
embeddedAgentLog,
5+
formatErrorMessage,
56
setActiveEmbeddedRun,
67
} from "openclaw/plugin-sdk/agent-harness-runtime";
78
import { retireCodexAppServerClientAfterTimedOutTurn } from "./attempt-client-cleanup.js";
89
import { isTerminalTurnStatus } from "./attempt-notifications.js";
9-
import { createCodexSteeringQueue, type CodexSteeringQueueOptions } from "./attempt-steering.js";
10+
import {
11+
CodexSteeringAcceptedUnconfirmedError,
12+
createCodexSteeringQueue,
13+
type CodexSteeringQueueOptions,
14+
} from "./attempt-steering.js";
1015
import { CodexAppServerEventProjector } from "./event-projector.js";
1116
import { createCodexNativeMcpAppResultDetailsPreparer } from "./native-mcp-app.js";
1217
import type { CodexTurnStartResponse, JsonObject } from "./protocol.js";
@@ -177,7 +182,7 @@ export async function activateCodexAttemptTurn(
177182
text,
178183
});
179184
if (claimed) {
180-
return;
185+
return undefined;
181186
}
182187
} else if (isInboundUserMessage) {
183188
try {
@@ -192,7 +197,18 @@ export async function activateCodexAttemptTurn(
192197
});
193198
}
194199
}
195-
await activeSteeringQueue.queue(text, optionsLocal);
200+
try {
201+
await activeSteeringQueue.queue(text, optionsLocal);
202+
} catch (error) {
203+
if (error instanceof CodexSteeringAcceptedUnconfirmedError) {
204+
return {
205+
transcriptCommit: "unconfirmed" as const,
206+
errorMessage: formatErrorMessage(error),
207+
};
208+
}
209+
throw error;
210+
}
211+
return undefined;
196212
},
197213
isStreaming: () => !state.completed && !runAbortController.signal.aborted,
198214
isAborted: () => runAbortController.signal.aborted,

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

Lines changed: 74 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,15 +4,25 @@ import {
44
embeddedAgentLog,
55
setActiveEmbeddedRun,
66
} from "openclaw/plugin-sdk/agent-harness-runtime";
7+
import type { queueAgentHarnessMessage } from "openclaw/plugin-sdk/agent-harness-runtime";
8+
import type { AttemptTranscriptJournal } from "./attempt-transcript-journal.js";
79
import type { AttemptParamsLike } from "./attempt-types.js";
810
import type { attachEventBridge } from "./event-bridge.js";
11+
import type { SessionLike } from "./event-bridge.js";
912
import type { CopilotUserInputBridge } from "./user-input-bridge.js";
13+
14+
const DEFAULT_STEERING_DELIVERY_TIMEOUT_MS = 120_000;
15+
type CopilotQueueMessageOptions = Parameters<typeof queueAgentHarnessMessage>[2];
16+
1017
export function registerCopilotActiveRun(params: {
1118
abortActiveSession: () => void;
1219
bridge: ReturnType<typeof attachEventBridge> | undefined;
20+
canAcceptSteering: () => boolean;
1321
input: AttemptParamsLike;
1422
isAborted: () => boolean;
1523
isSettled: () => boolean;
24+
session: SessionLike;
25+
transcriptJournal: AttemptTranscriptJournal;
1626
userInputBridge: CopilotUserInputBridge;
1727
}) {
1828
const cancelGatewayQuestionBestEffort = (resolvedBy: string) => {
@@ -25,21 +35,52 @@ export function registerCopilotActiveRun(params: {
2535
};
2636
const activeRunHandle = {
2737
kind: "embedded" as const,
28-
queueMessage: async (text: string, options?: { isInboundUserMessage?: boolean }) => {
38+
queueMessage: async (text: string, options?: CopilotQueueMessageOptions) => {
2939
if (
3040
options?.isInboundUserMessage === true &&
3141
(await claimPendingAgentQuestionAnswer({
3242
sessionKey: params.input.sessionKey ?? params.input.sessionId,
3343
text,
44+
persist: options.userTurnTranscriptRecorder
45+
? async () => {
46+
await options.userTurnTranscriptRecorder?.persistApproved();
47+
}
48+
: undefined,
3449
}))
3550
) {
36-
return;
51+
return undefined;
3752
}
38-
throw new Error("Copilot runtime is not waiting for user input.");
53+
if (params.isSettled() || params.isAborted()) {
54+
throw new Error("Copilot steering is unavailable after the active run ended");
55+
}
56+
if (!params.canAcceptSteering()) {
57+
throw new Error("Copilot steering is unavailable before initial user validation");
58+
}
59+
const messageId = await params.session.send({ prompt: text });
60+
if (options?.waitForTranscriptCommit === true) {
61+
try {
62+
await waitForPersistenceReceipt(
63+
params.transcriptJournal.waitForSdkUserPersisted(messageId),
64+
options.deliveryTimeoutMs,
65+
);
66+
} catch (error) {
67+
return {
68+
transcriptCommit: "unconfirmed" as const,
69+
errorMessage:
70+
error instanceof Error
71+
? error.message
72+
: "Copilot accepted steering but its transcript receipt was not confirmed",
73+
};
74+
}
75+
}
76+
return undefined;
3977
},
40-
isStreaming: () => !params.isSettled() && !params.isAborted(),
78+
isStreaming: () => params.canAcceptSteering() && !params.isSettled() && !params.isAborted(),
4179
isAborted: params.isAborted,
4280
isCompacting: () => params.bridge?.isCompacting() ?? false,
81+
// session.send resolves with the injected user-message id; the journal
82+
// receipt resolves only after that exact SDK event reaches canonical history.
83+
supportsTranscriptCommitWait: true,
4384
sourceReplyDeliveryMode: params.input.sourceReplyDeliveryMode,
4485
cancel: () => {
4586
cancelGatewayQuestionBestEffort("run-cancel");
@@ -60,3 +101,32 @@ export function registerCopilotActiveRun(params: {
60101
);
61102
return activeRunHandle;
62103
}
104+
105+
async function waitForPersistenceReceipt(
106+
receipt: Promise<void>,
107+
requestedTimeoutMs: number | undefined,
108+
): Promise<void> {
109+
const timeoutMs =
110+
typeof requestedTimeoutMs === "number" &&
111+
Number.isFinite(requestedTimeoutMs) &&
112+
requestedTimeoutMs > 0
113+
? requestedTimeoutMs
114+
: DEFAULT_STEERING_DELIVERY_TIMEOUT_MS;
115+
let timer: ReturnType<typeof setTimeout> | undefined;
116+
try {
117+
await Promise.race([
118+
receipt,
119+
new Promise<never>((_, reject) => {
120+
timer = setTimeout(
121+
() => reject(new Error("Copilot steering transcript receipt timed out")),
122+
timeoutMs,
123+
);
124+
timer.unref?.();
125+
}),
126+
]);
127+
} finally {
128+
if (timer) {
129+
clearTimeout(timer);
130+
}
131+
}
132+
}

‎extensions/copilot/src/attempt-execution.ts‎

Lines changed: 14 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -108,6 +108,7 @@ export async function runCopilotExecution(context: {
108108
let session: SessionLike | undefined;
109109
let bridge: ReturnType<typeof attachEventBridge> | undefined;
110110
let transcriptJournal: AttemptTranscriptJournal | undefined;
111+
let initialSdkUserValidated = false;
111112
const nativeSubagentTaskMirror = createCopilotNativeSubagentTaskMirror({
112113
agentId: sessionAgentId,
113114
now,
@@ -403,6 +404,15 @@ export async function runCopilotExecution(context: {
403404
});
404405
} catch {}
405406
}
407+
transcriptJournal = createAttemptTranscriptJournal({
408+
abortSession: () => session?.abort() ?? Promise.resolve(),
409+
attempt: input,
410+
messages,
411+
onInitialSdkUserValidated: () => {
412+
initialSdkUserValidated = true;
413+
},
414+
sdkSessionId,
415+
});
406416
bridge = attachEventBridge(session, {
407417
onAssistantDelta: settledToolFinalization ? undefined : input.onAssistantDelta,
408418
onAgentEvent: settledToolFinalization ? undefined : input.onAgentEvent,
@@ -442,12 +452,7 @@ export async function runCopilotExecution(context: {
442452
getSdkSessionId: () => sdkSessionId,
443453
isAborted: () => aborted || transcriptJournal?.hasFailed() === true,
444454
transcriptProjection: {
445-
journal: (transcriptJournal = createAttemptTranscriptJournal({
446-
abortSession: () => session?.abort() ?? Promise.resolve(),
447-
attempt: input,
448-
messages,
449-
sdkSessionId,
450-
})),
455+
journal: transcriptJournal,
451456
modelRef,
452457
now,
453458
resultContentSourceByToolName,
@@ -456,9 +461,12 @@ export async function runCopilotExecution(context: {
456461
activeRunHandleRef = registerCopilotActiveRun({
457462
abortActiveSession,
458463
bridge,
464+
canAcceptSteering: () => initialSdkUserValidated,
459465
input,
460466
isAborted: () => aborted,
461467
isSettled: () => settled,
468+
session,
469+
transcriptJournal,
462470
userInputBridge,
463471
});
464472
const messageOptions = await createMessageOptions(attemptInput, {

‎extensions/copilot/src/attempt-transcript-journal.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,7 @@ function createFakeSession(): FakeSession {
3838
on: vi.fn((eventType: string, handler: (event: SessionEvent) => void) => {
3939
listeners.set(eventType, [...(listeners.get(eventType) ?? []), handler]);
4040
}) as FakeSession["on"],
41+
send: vi.fn(async () => "sdk-user"),
4142
sendAndWait: vi.fn(async () => undefined),
4243
sessionId: "sdk-session",
4344
};

0 commit comments

Comments
 (0)