Skip to content

Commit 2a87667

Browse files
fix(ui): keep one agent run in one transcript response (#126278)
* fix(ui): compose agent run transcript responses * fix(ui): preserve explicit run transcript boundaries * fix(ui): preserve run transcript status * fix(ui): preserve live agent run content * fix(ui): preserve semantic agent run frames * fix(ui): complete agent run transcript ownership * fix(ui): stabilize agent run transcript lifecycle * fix(ui): complete agent run frame ownership * fix(ui): close transcript ownership races * test(gateway-client): drop non-regressing projection case --------- Co-authored-by: RoboClaw <[email protected]>
1 parent 32bb08d commit 2a87667

47 files changed

Lines changed: 2580 additions & 479 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎extensions/codex/src/app-server/context-compaction-activity.test.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ describe("persistCodexContextCompactionActivity", () => {
5555
display: true,
5656
excludeFromContext: true,
5757
idempotencyKey: "codex-context-compaction:thread-1:turn-1:compact-1",
58+
__openclaw: { runId: "run-1" },
5859
},
5960
});
6061
expect(publishUpdate).toHaveBeenCalledOnce();

‎extensions/codex/src/app-server/context-compaction-activity.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ export async function persistCodexContextCompactionActivity(params: {
3939
itemId: params.itemId,
4040
...(params.runId ? { runId: params.runId } : {}),
4141
},
42+
...(params.runId ? { __openclaw: { runId: params.runId } } : {}),
4243
timestamp: params.timestamp,
4344
idempotencyKey: activityId,
4445
};

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

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -245,6 +245,8 @@ export async function activateCodexAttemptTurn(
245245
cwd: effectiveCwd,
246246
messages,
247247
idempotencyScope: `codex-app-server:${resourceState.thread.threadId}`,
248+
runId: params.runId,
249+
runMirrorIdentityPrefix: `${activeTurnId}:`,
248250
config: params.config,
249251
});
250252
}

‎extensions/codex/src/app-server/settled-turn-finalizer.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -114,6 +114,8 @@ export async function runCodexSettledTurnFinalization(
114114
cwd: attempt.workspaceDir,
115115
messages: [assistant],
116116
idempotencyScope: `codex-settled-finalizer:${attempt.runId}`,
117+
runId: attempt.runId,
118+
terminalAssistantOwner: { mirrorIdentity, runId: attempt.runId },
117119
config: attempt.config,
118120
skipBeforeMessageWriteHooks: true,
119121
});

‎extensions/codex/src/app-server/transcript-mirror-attestation.ts‎

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import { createHash } from "node:crypto";
22
import type { AgentMessage } from "openclaw/plugin-sdk/agent-harness-runtime";
3+
import { asOptionalRecord } from "openclaw/plugin-sdk/string-coerce-runtime";
34
import { readUpstreamUserText } from "./upstream-prompt-provenance.js";
45

56
type MirroredAgentMessage = Extract<AgentMessage, { role: "user" | "assistant" | "toolResult" }>;
@@ -29,6 +30,24 @@ export function attachCodexMirrorAttestation(
2930
return attested;
3031
}
3132

33+
export function attachCodexMirrorRunId<T extends AgentMessage>(
34+
message: T,
35+
runId: string,
36+
terminal = false,
37+
): T {
38+
const existing = CODEX_META_KEY in message ? message[CODEX_META_KEY] : undefined;
39+
const metadata = asOptionalRecord(existing) ?? {};
40+
const { runTerminal: _staleTerminal, ...current } = metadata;
41+
return {
42+
...message,
43+
[CODEX_META_KEY]: {
44+
...current,
45+
runId,
46+
...(terminal ? { runTerminal: true } : {}),
47+
},
48+
} as T; // SAFETY: AgentMessage variants permit provider metadata at runtime; preserve T.
49+
}
50+
3251
export function readCodexMirrorSourceFingerprint(message: AgentMessage): string | undefined {
3352
const meta = CODEX_META_KEY in message ? message[CODEX_META_KEY] : undefined;
3453
if (!meta || typeof meta !== "object" || Array.isArray(meta)) {

‎extensions/codex/src/app-server/transcript-mirror.test.ts‎

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@ import {
2020
import { afterEach, describe, expect, it, vi } from "vitest";
2121
import type { CodexThread } from "./protocol.js";
2222
import { readCodexMirroredSessionHistoryMessages } from "./session-history.js";
23+
import { attachCodexMirrorRunId } from "./transcript-mirror-attestation.js";
2324
import {
2425
buildCodexUserPromptMessage,
2526
codexTranscriptMirrorRuntime,
@@ -793,6 +794,17 @@ describe("projectBoundedCodexThreadHistory", () => {
793794
});
794795

795796
describe("mirrorCodexAppServerTranscript", () => {
797+
it("clears terminal ownership when a mirrored message becomes non-terminal", () => {
798+
const message = makeAgentAssistantMessage({
799+
content: [{ type: "text", text: "intermediate narration" }],
800+
timestamp: Date.now(),
801+
});
802+
const terminal = attachCodexMirrorRunId(message, "run-1", true);
803+
const intermediate = attachCodexMirrorRunId(terminal, "run-1");
804+
805+
expect(intermediate).toMatchObject({ __openclaw: { runId: "run-1" } });
806+
expect(intermediate).not.toHaveProperty("__openclaw.runTerminal");
807+
});
796808
it("hides current memory-maintenance messages without hiding replayed turns", async () => {
797809
initializeGlobalHookRunner(
798810
createMockPluginRegistry([
@@ -1061,6 +1073,8 @@ describe("mirrorCodexAppServerTranscript", () => {
10611073
),
10621074
],
10631075
idempotencyScope: "codex-app-server:thread-1",
1076+
runId: "openclaw-run-1",
1077+
runMirrorIdentityPrefix: "turn-1:",
10641078
terminalAssistantOwner: {
10651079
mirrorIdentity: "turn-1:assistant",
10661080
runId: "openclaw-run-1",
@@ -1072,6 +1086,22 @@ describe("mirrorCodexAppServerTranscript", () => {
10721086
);
10731087
expect(updates.map((update) => update.update?.messageSeq)).toEqual([1, 2]);
10741088
expect(updates.map((update) => update.update?.runId)).toEqual([undefined, "openclaw-run-1"]);
1089+
expect(
1090+
updates.map(
1091+
(update) =>
1092+
(update.update?.message as { __openclaw?: { runId?: string } } | undefined)?.[
1093+
"__openclaw"
1094+
]?.runId,
1095+
),
1096+
).toEqual(["openclaw-run-1", "openclaw-run-1"]);
1097+
expect(
1098+
updates.map(
1099+
(update) =>
1100+
(update.update?.message as { __openclaw?: { runTerminal?: boolean } } | undefined)?.[
1101+
"__openclaw"
1102+
]?.runTerminal,
1103+
),
1104+
).toEqual([undefined, true]);
10751105
expect(
10761106
updates.map((update) => {
10771107
const message = update.update?.message as { role?: string } | undefined;
@@ -1483,7 +1513,7 @@ describe("mirrorCodexAppServerTranscript", () => {
14831513
turnId: "turn-1",
14841514
});
14851515

1486-
expect(mirrorOutcome.assistantTranscriptOwned).toBe(true);
1516+
expect(mirrorOutcome.assistantTranscriptOwned).toBe(false);
14871517
expect(mirrorOutcome.mirroredMessages).toEqual([]);
14881518
});
14891519

‎extensions/codex/src/app-server/transcript-mirror.ts‎

Lines changed: 32 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import {
2323
} from "./transcript-history-projection.js";
2424
import {
2525
attachCodexMirrorAttestation,
26+
attachCodexMirrorRunId,
2627
fingerprintCodexMirrorSourceMessage,
2728
readCodexMirrorSourceFingerprint,
2829
} from "./transcript-mirror-attestation.js";
@@ -134,6 +135,8 @@ async function mirrorBestEffort(params: {
134135
// identity (not via the scope). Dropping `turnId` from the scope here is
135136
// what lets a re-emitted prior-turn entry collide with its existing key.
136137
idempotencyScope: `codex-app-server:${params.threadId}`,
138+
runId: params.params.runId,
139+
runMirrorIdentityPrefix: `${params.turnId}:`,
137140
terminalAssistantOwner: {
138141
mirrorIdentity: `${params.turnId}:assistant`,
139142
runId: params.params.runId,
@@ -166,11 +169,13 @@ async function mirrorBestEffort(params: {
166169
);
167170
});
168171
const assistantMirrorIdentity = `${params.turnId}:assistant`;
169-
const assistantTranscriptOwned =
170-
mirrorResult.assistantMirrorIdentitiesOwned.includes(assistantMirrorIdentity);
171-
const assistantTranscriptMessage = assistantTranscriptOwned
172-
? mirroredMessages.find((message) => readMirrorIdentity(message) === assistantMirrorIdentity)
173-
: undefined;
172+
const assistantTranscriptMessage = mirroredMessages.find(
173+
(message) => readMirrorIdentity(message) === assistantMirrorIdentity,
174+
);
175+
const assistantTranscriptOwned = Boolean(
176+
assistantTranscriptMessage &&
177+
mirrorResult.assistantMirrorIdentitiesOwned.includes(assistantMirrorIdentity),
178+
);
174179
const assistantTranscriptIdempotencyKey = normalizeOptionalString(
175180
(assistantTranscriptMessage as { idempotencyKey?: unknown } | undefined)?.idempotencyKey,
176181
);
@@ -283,6 +288,8 @@ export async function mirrorPromptAtTurnStartBestEffort(params: {
283288
cwd: params.cwd,
284289
messages: [userPromptMessage],
285290
idempotencyScope: `codex-app-server:${params.threadId}`,
291+
runId: params.params.runId,
292+
runMirrorIdentityPrefix: `${params.turnId}:`,
286293
config: params.params.config,
287294
});
288295
for (const receipt of mirrorResult.userMessageReceipts) {
@@ -327,6 +334,8 @@ async function mirror(params: {
327334
storePath?: string;
328335
messages: AgentMessage[];
329336
idempotencyScope?: string;
337+
runId?: string;
338+
runMirrorIdentityPrefix?: string;
330339
terminalAssistantOwner?: { mirrorIdentity: string; runId: string };
331340
config?: SessionTranscriptWriteLockParams["config"];
332341
skipBeforeMessageWriteHooks?: boolean;
@@ -377,8 +386,22 @@ async function mirror(params: {
377386
idempotencyKeys: candidateIdempotencyKeys,
378387
});
379388
for (const { dedupeIdentity, idempotencyKey, message, sourceFingerprint } of candidates) {
389+
const mirrorIdentity = readMirrorIdentity(message);
390+
const ownsRun = Boolean(
391+
params.runId &&
392+
(!params.runMirrorIdentityPrefix ||
393+
mirrorIdentity?.startsWith(params.runMirrorIdentityPrefix)),
394+
);
395+
const terminalOwner = params.terminalAssistantOwner;
396+
const ownsTerminal = Boolean(
397+
ownsRun && terminalOwner && mirrorIdentity === terminalOwner.mirrorIdentity,
398+
);
399+
const ownedMessage =
400+
ownsRun && params.runId
401+
? attachCodexMirrorRunId(message, params.runId, ownsTerminal)
402+
: message;
380403
const transcriptMessage = {
381-
...attachCodexMirrorAttestation(message, sourceFingerprint),
404+
...attachCodexMirrorAttestation(ownedMessage, sourceFingerprint),
382405
...(idempotencyKey ? { idempotencyKey } : {}),
383406
} as AgentMessage;
384407
if (idempotencyKey && mirrorFacts.existingIdempotencyKeys.has(idempotencyKey)) {
@@ -428,12 +451,14 @@ async function mirror(params: {
428451
}
429452
: attachCodexMirrorAttestation(nextMessage, sourceFingerprint)
430453
) as AgentMessage;
431-
const mirrorIdentity = readMirrorIdentity(message);
432454
if (mirrorIdentity) {
433455
// Hooks may replace the whole message. Restore the provider-owned
434456
// identity so retries cannot turn a stale idempotency hit into evidence.
435457
messageToAppend = attachCodexMirrorIdentity(messageToAppend, mirrorIdentity);
436458
}
459+
if (ownsRun && params.runId) {
460+
messageToAppend = attachCodexMirrorRunId(messageToAppend, params.runId, ownsTerminal);
461+
}
437462
messageToAppend = projectAgentHarnessTranscriptMessageForDisplay({
438463
hidden: (message as { display?: boolean }).display === false,
439464
message: messageToAppend,
Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,99 @@
1+
import { asNullableRecord as readRecord } from "@openclaw/normalization-core/record-coerce";
2+
3+
export type SessionMessageEnvelope = {
4+
messageId?: unknown;
5+
messageSeq?: unknown;
6+
clientRunId?: unknown;
7+
runId?: unknown;
8+
idempotencyKey?: unknown;
9+
};
10+
11+
export type SessionMessageIdentity = {
12+
role: string;
13+
id: string | null;
14+
sequence: number | null;
15+
idempotencyKey: string | null;
16+
runId: string | null;
17+
isImported: boolean;
18+
externalSource: string | null;
19+
};
20+
21+
export function readSessionProjectionString(value: unknown): string | null {
22+
return typeof value === "string" ? value.trim() || null : null;
23+
}
24+
25+
function readPositiveSafeInteger(value: unknown): number | null {
26+
return typeof value === "number" && Number.isSafeInteger(value) && value > 0 ? value : null;
27+
}
28+
29+
/** History and status markers carry transcript order even when they have no chat role. */
30+
export function readSessionMessageSequence(
31+
message: unknown,
32+
envelope?: SessionMessageEnvelope,
33+
): number | null {
34+
const metadata = readRecord(readRecord(message)?.["__openclaw"]);
35+
return readPositiveSafeInteger(metadata?.seq) ?? readPositiveSafeInteger(envelope?.messageSeq);
36+
}
37+
38+
/** Run ownership normalizes a user-turn suffix without changing its persisted send key. */
39+
export function normalizeSessionProjectionRunId(value: unknown): string | null {
40+
const runId = readSessionProjectionString(value);
41+
return runId?.endsWith(":user") ? runId.slice(0, -":user".length) || null : runId;
42+
}
43+
44+
/** Persisted row facts win; assistant run ownership comes from its authoritative producer. */
45+
export function readSessionMessageIdentity(
46+
message: unknown,
47+
envelope?: SessionMessageEnvelope,
48+
): SessionMessageIdentity | null {
49+
const record = readRecord(message);
50+
const role = readSessionProjectionString(record?.role)?.toLowerCase();
51+
if (!record || !role) {
52+
return null;
53+
}
54+
const metadata = readRecord(record["__openclaw"]);
55+
const importedFrom = readSessionProjectionString(metadata?.importedFrom);
56+
const cliSessionId = readSessionProjectionString(metadata?.cliSessionId);
57+
const externalId = readSessionProjectionString(metadata?.externalId);
58+
const idempotencyKey =
59+
readSessionProjectionString(metadata?.idempotencyKey) ??
60+
readSessionProjectionString(record.idempotencyKey) ??
61+
readSessionProjectionString(envelope?.idempotencyKey) ??
62+
readSessionProjectionString(envelope?.clientRunId);
63+
const persistedRunId = normalizeSessionProjectionRunId(idempotencyKey);
64+
const envelopeRunId = normalizeSessionProjectionRunId(envelope?.runId);
65+
const metadataRunId = normalizeSessionProjectionRunId(metadata?.runId);
66+
const mirroredMessage = readSessionProjectionString(metadata?.mirrorOrigin) !== null;
67+
// CLI persistence namespaces assistant send keys; the suffix is the
68+
// originating Gateway run identity consumed by every projection layer.
69+
const isCliAssistant =
70+
role === "assistant" && readSessionProjectionString(record.api)?.toLowerCase() === "cli";
71+
const canonicalPersistedRunId =
72+
isCliAssistant && persistedRunId?.startsWith("cli-assistant:")
73+
? readSessionProjectionString(persistedRunId.slice("cli-assistant:".length))
74+
: persistedRunId;
75+
const optimisticRunId =
76+
metadata && Object.keys(metadata).every((key) => key === "idempotencyKey")
77+
? canonicalPersistedRunId
78+
: null;
79+
return {
80+
role,
81+
id:
82+
readSessionProjectionString(metadata?.id) ?? readSessionProjectionString(envelope?.messageId),
83+
sequence: readSessionMessageSequence(message, envelope),
84+
idempotencyKey,
85+
runId:
86+
role === "assistant"
87+
? (metadataRunId ??
88+
envelopeRunId ??
89+
(isCliAssistant || !mirroredMessage ? canonicalPersistedRunId : null) ??
90+
optimisticRunId)
91+
: (metadataRunId ?? canonicalPersistedRunId ?? envelopeRunId),
92+
isImported: Boolean(importedFrom || cliSessionId || externalId),
93+
// Imported IDs belong to their provider and CLI session, never the native ID namespace.
94+
externalSource:
95+
importedFrom && cliSessionId && externalId
96+
? JSON.stringify([importedFrom, cliSessionId, externalId])
97+
: null,
98+
};
99+
}

‎packages/gateway-client/src/session-projection.test.ts‎

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -106,6 +106,42 @@ describe("readSessionMessageIdentity", () => {
106106
expect(normalizeSessionProjectionRunId(input)).toBe(expected);
107107
});
108108

109+
it("recovers the originating run from a persisted CLI assistant send key", () => {
110+
expect(
111+
readSessionMessageIdentity({
112+
role: "assistant",
113+
api: "cli",
114+
content: "Done",
115+
idempotencyKey: "cli-assistant:run-cli-1",
116+
}),
117+
).toMatchObject({
118+
idempotencyKey: "cli-assistant:run-cli-1",
119+
runId: "run-cli-1",
120+
});
121+
});
122+
123+
it("keeps assistant dedupe identity separate from producer-owned run identity", () => {
124+
expect(
125+
readSessionMessageIdentity({
126+
role: "assistant",
127+
content: "Commentary",
128+
idempotencyKey: "codex-app-server:thread-1:turn-1:commentary:item-1",
129+
__openclaw: { mirrorOrigin: "codex-app-server", runId: "run-1" },
130+
}),
131+
).toMatchObject({
132+
idempotencyKey: "codex-app-server:thread-1:turn-1:commentary:item-1",
133+
runId: "run-1",
134+
});
135+
expect(
136+
readSessionMessageIdentity({
137+
role: "assistant",
138+
content: "Imported history",
139+
idempotencyKey: "codex-app-server:thread-1:history:turn-1:assistant",
140+
__openclaw: { mirrorOrigin: "codex-app-server" },
141+
}),
142+
).toHaveProperty("runId", null);
143+
});
144+
109145
it("requires every imported source component before claiming provider identity", () => {
110146
const identity = readSessionMessageIdentity(
111147
createMessage("user", "imported", {
@@ -202,6 +238,22 @@ describe("session transcript projection", () => {
202238
expect(state.messages).toEqual([persisted]);
203239
});
204240

241+
it("does not promote a provisional final into same-run Codex commentary", () => {
242+
const commentary = createMessage("assistant", "commentary", {
243+
id: "commentary-1",
244+
mirrorOrigin: "codex-app-server",
245+
runId: "run-1",
246+
});
247+
const final = createMessage("assistant", "final answer");
248+
let state = projectLiveSessionMessage(createSessionProjection(primaryScope), commentary, {
249+
runId: "run-1",
250+
});
251+
252+
state = projectLiveSessionMessage(state, final, { runId: "run-1" });
253+
254+
expect(state.messages).toEqual([commentary, final]);
255+
});
256+
205257
it("keeps the durable assistant identity when its run's terminal projection replays", () => {
206258
const persisted = createMessage("assistant", "persisted final", {
207259
id: "assistant-final",

0 commit comments

Comments
 (0)