Skip to content

Commit 69fa1a8

Browse files
committed
fix(codex): preserve steering transcript order
1 parent 72c8bf9 commit 69fa1a8

5 files changed

Lines changed: 171 additions & 14 deletions

File tree

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

Lines changed: 31 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,11 @@ export type CodexSteeringQueueOptions = {
3333
userTurnTranscriptRecorder?: AgentHarnessQueueMessageOptions["userTurnTranscriptRecorder"];
3434
};
3535

36+
type CodexSteeringCommitItem = Pick<
37+
CodexSteeringQueueOptions,
38+
"isInboundUserMessage" | "userTurnTranscriptRecorder"
39+
>;
40+
3641
/**
3742
* Creates a queue that batches steer messages while still serializing
3843
* app-server `turn/steer` requests.
@@ -43,15 +48,18 @@ export function createCodexSteeringQueue(params: {
4348
turnId: string;
4449
requestTimeoutMs: number;
4550
signal: AbortSignal;
51+
beforeConfirmConsumed?: (items: readonly CodexSteeringCommitItem[]) => Promise<void>;
4652
}) {
4753
type PendingSteerMessage = {
4854
acceptance: "open" | "accepted" | "rejected";
4955
text: string;
5056
images?: EmbeddedRunAttemptParams["images"];
57+
isInboundUserMessage?: boolean;
5158
onQueueAccepted?: (accepted: boolean) => void;
5259
resolve: () => void;
5360
reject: (error: unknown) => void;
5461
settled: boolean;
62+
userTurnTranscriptRecorder?: CodexSteeringQueueOptions["userTurnTranscriptRecorder"];
5563
};
5664
type PendingSteerBatch = {
5765
items: PendingSteerMessage[];
@@ -245,10 +253,12 @@ export function createCodexSteeringQueue(params: {
245253
acceptance: "open" as const,
246254
text,
247255
images: options?.images,
256+
isInboundUserMessage: options?.isInboundUserMessage,
248257
onQueueAccepted: options?.onQueueAccepted,
249258
resolve: resolveDelivery,
250259
reject: rejectDelivery,
251260
settled: false,
261+
userTurnTranscriptRecorder: options?.userTurnTranscriptRecorder,
252262
};
253263
pendingMessages.add(item);
254264
return { item, delivery };
@@ -290,9 +300,28 @@ export function createCodexSteeringQueue(params: {
290300
}
291301
dispatchedBatches.delete(clientUserMessageId);
292302
for (const item of batch.items) {
293-
resolveItem(item);
303+
reportItemAcceptance(item, true);
304+
}
305+
const resolveBatch = () => {
306+
for (const item of batch.items) {
307+
resolveItem(item);
308+
}
309+
return true;
310+
};
311+
const rejectBatch = (error: unknown) => {
312+
for (const item of batch.items) {
313+
rejectItem(item, error);
314+
}
315+
return true;
316+
};
317+
if (!params.beforeConfirmConsumed) {
318+
return resolveBatch();
319+
}
320+
try {
321+
return params.beforeConfirmConsumed(batch.items).then(resolveBatch, rejectBatch);
322+
} catch (error) {
323+
return rejectBatch(error);
294324
}
295-
return true;
296325
},
297326
sealAdmission: sealQueueAdmission,
298327
cancel: cancelQueue,

‎extensions/codex/src/app-server/event-projector.ts‎

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import {
44
emitAgentEvent as emitGlobalAgentEvent,
55
runAgentHarnessAfterCompactionHook,
66
runAgentHarnessBeforeCompactionHook,
7+
type AgentMessage,
78
type BeforeToolCallFailureDisposition,
89
type EmbeddedRunAttemptParamsV2 as EmbeddedRunAttemptParams,
910
} from "openclaw/plugin-sdk/agent-harness-runtime";
@@ -26,6 +27,7 @@ import {
2627
buildCodexAttemptResult,
2728
type CodexAppServerToolTelemetry,
2829
} from "./event-projector-result.js";
30+
import { buildCodexMessagesSnapshot } from "./event-projector-snapshot.js";
2931
import { CodexToolProgressProjection } from "./event-projector-tool-progress.js";
3032
import { CodexToolTranscriptProjection } from "./event-projector-tool-transcript.js";
3133
import {
@@ -157,6 +159,24 @@ export class CodexAppServerEventProjector {
157159
return this.completedTurn?.status;
158160
}
159161

162+
buildSteeringTranscriptPrefix(): AgentMessage[] {
163+
const commentaryMessages = this.assistantProjection
164+
.collectCommentaryMessages()
165+
.filter(({ itemId }) => this.completedItemIds.has(itemId));
166+
return buildCodexMessagesSnapshot({
167+
runParams: this.params,
168+
turnId: this.turnId,
169+
upstreamUserText: this.options.upstreamUserText,
170+
reasoningText: undefined,
171+
planText: undefined,
172+
commentaryMessages,
173+
toolMessages: this.toolTranscriptProjection.transcriptMessages,
174+
lastAssistant: undefined,
175+
createAssistantMirrorMessage: (title, text) =>
176+
this.assistantProjection.createAssistantMirrorMessage(title, text),
177+
}).filter((message) => message.role !== "user");
178+
}
179+
160180
hasCompletedTerminalAssistantText(): boolean {
161181
return this.assistantProjection.hasCompletedTerminalAssistantText(this.completedItemIds);
162182
}

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

Lines changed: 43 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import type { CodexAttemptNotificationController } from "./run-attempt-notificat
2323
import type { CodexAttemptResources } from "./run-attempt-resources.js";
2424
import type { CodexAttemptTurnState } from "./run-attempt-turn-state.js";
2525
import {
26+
codexTranscriptMirrorRuntime,
2627
createCodexAppServerUserMessagePersistenceNotifier,
2728
mirrorPromptAtTurnStartBestEffort,
2829
} from "./transcript-mirror.js";
@@ -55,6 +56,7 @@ export async function activateCodexAttemptTurn(
5556
bindingIdentity,
5657
sessionAgentId,
5758
sandboxSessionKey,
59+
contextSessionKey,
5860
effectiveCwd,
5961
} = connection;
6062
const { dynamicToolParams, compactionPlanState, computerContextEpoch, toolBridge } = attemptTools;
@@ -210,12 +212,53 @@ export async function activateCodexAttemptTurn(
210212
{ threadId: resourceState.thread.threadId, turnId: activeTurnId },
211213
);
212214
}
215+
const notifyUserMessagePersisted = createCodexAppServerUserMessagePersistenceNotifier(params);
216+
const promptMirrorPromise = mirrorPromptAtTurnStartBestEffort({
217+
params,
218+
agentId: sessionAgentId,
219+
notifyUserMessagePersisted,
220+
sessionKey: sandboxSessionKey,
221+
cwd: effectiveCwd,
222+
threadId: resourceState.thread.threadId,
223+
turnId: activeTurnId,
224+
upstreamUserText: turnState.codexTurnPromptText,
225+
});
213226
const activeSteeringQueue = createCodexSteeringQueue({
214227
client: resourceState.client,
215228
threadId: resourceState.thread.threadId,
216229
turnId: activeTurnId,
217230
requestTimeoutMs: connection.appServer.requestTimeoutMs,
218231
signal: runAbortController.signal,
232+
beforeConfirmConsumed: async (items) => {
233+
const inboundItems = items.filter((item) => item.isInboundUserMessage === true);
234+
if (inboundItems.length === 0) {
235+
return;
236+
}
237+
await promptMirrorPromise;
238+
const messages = activeProjector.buildSteeringTranscriptPrefix();
239+
if (params.sessionTarget && messages.length > 0) {
240+
await codexTranscriptMirrorRuntime.mirror({
241+
agentId: sessionAgentId,
242+
sessionKey: contextSessionKey,
243+
sessionId: params.sessionId,
244+
storePath: params.sessionTarget.storePath,
245+
cwd: effectiveCwd,
246+
messages,
247+
idempotencyScope: `codex-app-server:${resourceState.thread.threadId}`,
248+
config: params.config,
249+
});
250+
}
251+
for (const item of inboundItems) {
252+
const recorder = item.userTurnTranscriptRecorder;
253+
if (!recorder) {
254+
continue;
255+
}
256+
await recorder.persistApproved();
257+
if (!recorder.hasPersisted()) {
258+
throw new Error("Codex consumed steering before its user turn was persisted");
259+
}
260+
}
261+
},
219262
});
220263
steeringQueueRef.current = activeSteeringQueue;
221264
const claimPendingUserInputAnswer = async (
@@ -308,17 +351,6 @@ export async function activateCodexAttemptTurn(
308351
terminalState.terminalOutcomeFrozen = true;
309352
params.abortSignal?.removeEventListener("abort", abortFromUpstream);
310353
};
311-
const notifyUserMessagePersisted = createCodexAppServerUserMessagePersistenceNotifier(params);
312-
void mirrorPromptAtTurnStartBestEffort({
313-
params,
314-
agentId: sessionAgentId,
315-
notifyUserMessagePersisted,
316-
sessionKey: sandboxSessionKey,
317-
cwd: effectiveCwd,
318-
threadId: resourceState.thread.threadId,
319-
turnId: activeTurnId,
320-
upstreamUserText: turnState.codexTurnPromptText,
321-
});
322354
const abortListener = () => {
323355
if (state.timedOut) {
324356
void (async () => {

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ export function createCodexAttemptNotificationController(
9898
if (notificationState.isCurrentTurnNotification && notification.method === "item/completed") {
9999
const item = readCodexNotificationItem(notification.params);
100100
if (item?.type === "userMessage" && typeof item.clientId === "string") {
101-
steeringQueue?.confirmConsumed(item.clientId);
101+
await steeringQueue?.confirmConsumed(item.clientId);
102102
}
103103
}
104104
if (notificationState.isTurnAbortMarker) {

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

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,13 @@
11
// Codex tests cover run attempt.steering plugin behavior.
22
import path from "node:path";
33
import { GPT5_BEHAVIOR_CONTRACT as CODEX_GPT5_BEHAVIOR_CONTRACT } from "openclaw/plugin-sdk/provider-model-shared";
4+
import { upsertSessionEntry } from "openclaw/plugin-sdk/session-store-runtime";
5+
import {
6+
appendSessionTranscriptMessageByIdentity,
7+
readSessionTranscriptEvents,
8+
} from "openclaw/plugin-sdk/session-transcript-runtime";
49
import { describe, expect, it, vi } from "vitest";
10+
import type { CodexSteeringQueueOptions } from "./attempt-steering.js";
511
import { readAttemptTerminal } from "./attempt-terminal.test-helper.js";
612
import type { CodexServerNotification } from "./protocol.js";
713
import {
@@ -173,13 +179,63 @@ describe("runCodexAppServerAttempt steering", () => {
173179
it("accepts Gateway transcript-backed steering for the active Codex turn", async () => {
174180
const { requests, waitForMethod, completeTurn, notify } = createStartedThreadHarness();
175181
const params = createSteeringParams();
182+
const storePath = path.join(tempDir, `${params.sessionId}.sqlite`);
183+
const sessionTarget = {
184+
agentId: "main",
185+
sessionId: params.sessionId,
186+
sessionKey: params.sessionKey!,
187+
storePath,
188+
};
176189
params.taskSuggestionDeliveryMode = "gateway";
190+
params.sessionTarget = sessionTarget;
191+
await upsertSessionEntry({
192+
agentId: "main",
193+
sessionKey: params.sessionKey!,
194+
storePath,
195+
entry: {
196+
sessionFile: params.sessionFile,
197+
sessionId: params.sessionId,
198+
updatedAt: Date.now(),
199+
},
200+
});
201+
let steerPersisted = false;
202+
const userTurnTranscriptRecorder = {
203+
persistApproved: vi.fn(async () => {
204+
if (steerPersisted) {
205+
return undefined;
206+
}
207+
steerPersisted = true;
208+
return await appendSessionTranscriptMessageByIdentity({
209+
...sessionTarget,
210+
message: {
211+
role: "user",
212+
content: "steer this active turn",
213+
timestamp: Date.now(),
214+
idempotencyKey: `${params.runId}:steer:user`,
215+
},
216+
});
217+
}),
218+
hasPersisted: () => steerPersisted,
219+
} as unknown as NonNullable<CodexSteeringQueueOptions["userTurnTranscriptRecorder"]>;
177220

178221
const run = runCodexAppServerAttempt(params, {
179222
pluginConfig: { appServer: { mode: "yolo" } },
180223
});
181224
await waitForMethod("turn/start");
182225
const onQueueAccepted = vi.fn();
226+
await notify({
227+
method: "item/completed",
228+
params: {
229+
threadId: "thread-1",
230+
turnId: "turn-1",
231+
item: {
232+
type: "agentMessage",
233+
id: "pre-steer-commentary",
234+
phase: "commentary",
235+
text: "PRE-STEER-COMMENTARY",
236+
},
237+
},
238+
});
183239

184240
await vi.waitFor(() => {
185241
expect(
@@ -198,6 +254,7 @@ describe("runCodexAppServerAttempt steering", () => {
198254
taskSuggestionDeliveryMode: "gateway",
199255
waitForTranscriptCommit: true,
200256
onQueueAccepted,
257+
userTurnTranscriptRecorder,
201258
});
202259
await vi.waitFor(
203260
() => expect(requests.map((entry) => entry.method)).toContain("turn/steer"),
@@ -219,6 +276,20 @@ describe("runCodexAppServerAttempt steering", () => {
219276
item: { id: "steered-user-message", type: "userMessage", clientId: clientUserMessageId },
220277
},
221278
});
279+
await userTurnTranscriptRecorder.persistApproved();
280+
await notify({
281+
method: "item/completed",
282+
params: {
283+
threadId: "thread-1",
284+
turnId: "turn-1",
285+
item: {
286+
type: "agentMessage",
287+
id: "final-answer",
288+
phase: "final_answer",
289+
text: "Steering completed.",
290+
},
291+
},
292+
});
222293
await completeTurn({ threadId: "thread-1", turnId: "turn-1" });
223294
await run;
224295

@@ -227,6 +298,11 @@ describe("runCodexAppServerAttempt steering", () => {
227298
expectedTurnId: "turn-1",
228299
input: [{ type: "text", text: "steer this active turn" }],
229300
});
301+
const roles = (await readSessionTranscriptEvents(sessionTarget)).flatMap((event) => {
302+
const message = (event as { message?: { role?: string } }).message;
303+
return message?.role ? [message.role] : [];
304+
});
305+
expect(roles).toEqual(["user", "assistant", "user", "assistant"]);
230306
});
231307

232308
it("forwards queued text and images to the active app-server turn", async () => {

0 commit comments

Comments
 (0)