Skip to content

Commit 15d80d3

Browse files
fix(ui): close transcript ownership races
1 parent d681690 commit 15d80d3

8 files changed

Lines changed: 117 additions & 20 deletions

File tree

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

Lines changed: 4 additions & 1 deletion
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" }>;
@@ -35,10 +36,12 @@ export function attachCodexMirrorRunId<T extends AgentMessage>(
3536
terminal = false,
3637
): T {
3738
const existing = CODEX_META_KEY in message ? message[CODEX_META_KEY] : undefined;
39+
const metadata = asOptionalRecord(existing) ?? {};
40+
const { runTerminal: _staleTerminal, ...current } = metadata;
3841
return {
3942
...message,
4043
[CODEX_META_KEY]: {
41-
...(existing && typeof existing === "object" && !Array.isArray(existing) ? existing : {}),
44+
...current,
4245
runId,
4346
...(terminal ? { runTerminal: true } : {}),
4447
},

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

Lines changed: 12 additions & 0 deletions
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([

‎src/agents/tools/message-tool.internal-source-reply.integration.test.ts‎

Lines changed: 22 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -198,7 +198,24 @@ describe("WebChat message tool internal source reply", () => {
198198
mediaUrls: imagePaths,
199199
};
200200
const updates: SessionTranscriptUpdate[] = [];
201-
const unsubscribe = onSessionTranscriptUpdate((update) => updates.push(update));
201+
const publishedDownloads: Array<Promise<unknown>> = [];
202+
const unsubscribe = onSessionTranscriptUpdate((update) => {
203+
updates.push(update);
204+
const content =
205+
update.message && typeof update.message === "object"
206+
? (update.message as { content?: Array<Record<string, unknown>> }).content
207+
: undefined;
208+
for (const block of content?.filter((entry) => entry.type === "image") ?? []) {
209+
publishedDownloads.push(
210+
resolveManagedOutgoingMediaArtifactDownload({
211+
sessionKey,
212+
agentId: "main",
213+
artifactId: String(block.artifactId),
214+
stateDir,
215+
}),
216+
);
217+
}
218+
});
202219
const [toolResult, overlappingResult] = await Promise.all([
203220
tool.execute("restart-proof-call", sendParams),
204221
tool.execute("restart-proof-call", sendParams),
@@ -272,6 +289,10 @@ describe("WebChat message tool internal source reply", () => {
272289
published?.message as { content?: Array<Record<string, unknown>> }
273290
)?.content;
274291
expect(publishedContent?.filter((block) => block.type === "image")).toHaveLength(2);
292+
await expect(Promise.all(publishedDownloads)).resolves.toEqual([
293+
expect.objectContaining({ type: "image" }),
294+
expect.objectContaining({ type: "image" }),
295+
]);
275296
for (const block of content.filter((entry) => entry.type === "image")) {
276297
await expect(
277298
resolveManagedOutgoingMediaArtifactDownload({

‎src/config/sessions/transcript.ts‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -390,6 +390,7 @@ export async function appendAssistantMessageToSessionTranscript(params: {
390390
text?: string;
391391
mediaUrls?: string[];
392392
content?: SessionTranscriptAssistantMessage["content"];
393+
eventId?: string;
393394
idempotencyKey?: string;
394395
runId?: string;
395396
deliveryMirror?: InternalSessionTranscriptDeliveryMirror;
@@ -429,8 +430,9 @@ export async function appendAssistantMessageToSessionTranscript(params: {
429430
? { sessionLifecyclePatch: params.sessionLifecyclePatch }
430431
: {}),
431432
storePath: params.storePath,
432-
idempotencyKey: params.idempotencyKey,
433-
runId: params.runId,
433+
...(params.eventId ? { eventId: params.eventId } : {}),
434+
...(params.idempotencyKey ? { idempotencyKey: params.idempotencyKey } : {}),
435+
...(params.runId ? { runId: params.runId } : {}),
434436
updateMode: params.updateMode,
435437
config: params.config,
436438
...(params.beforeMessageWrite ? { beforeMessageWrite: params.beforeMessageWrite } : {}),
@@ -470,6 +472,7 @@ export async function appendExactAssistantMessageToSessionTranscript(params: {
470472
expectedSessionState?: SessionTranscriptTurnExpectedState;
471473
sessionLifecyclePatch?: SessionTranscriptTurnLifecyclePatch;
472474
message: SessionTranscriptAssistantMessage;
475+
eventId?: string;
473476
idempotencyKey?: string;
474477
runId?: string;
475478
storePath?: string;
@@ -598,6 +601,7 @@ export async function appendExactAssistantMessageToSessionTranscript(params: {
598601
messages: [
599602
{
600603
message: preparedUnkeyedMessage,
604+
...(params.eventId ? { eventId: params.eventId } : {}),
601605
...(explicitIdempotencyKey ? { idempotencyLookup: "scan" } : {}),
602606
...(explicitIdempotencyKey && params.beforeMessageWrite
603607
? {

‎src/gateway/internal-source-reply-persistence.ts‎

Lines changed: 8 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { randomUUID } from "node:crypto";
12
import type { ReplyPayload } from "../auto-reply/reply-payload.js";
23
import { appendAssistantMessageToSessionTranscript } from "../config/sessions.js";
34
import { resolveSessionStorePathCore } from "../config/sessions/paths.js";
@@ -11,8 +12,8 @@ import { getAgentScopedMediaLocalRootsForSources } from "../media/local-roots.js
1112
import { createKeyedFifoLeaseRegistry } from "../shared/keyed-fifo-lease.js";
1213
import { isOpenClawDeliveryMirrorAssistantMessage } from "../shared/transcript-only-openclaw-assistant.js";
1314
import {
14-
attachManagedOutgoingMediaToMessage,
1515
createManagedOutgoingMediaBlocks,
16+
removeManagedOutgoingMediaBlocks,
1617
} from "./managed-image-attachments.js";
1718
import { prepareGatewayInjectedAssistantContent } from "./server-methods/chat-transcript-inject.js";
1819

@@ -95,10 +96,12 @@ export async function persistInternalSourceReply(params: {
9596
return;
9697
}
9798
const mediaUrls = collectSourceReplyMediaUrls(params.payload);
99+
const messageId = randomUUID();
98100
const mediaBlocks = await createManagedOutgoingMediaBlocks({
99101
sessionKey: params.sessionKey,
100102
agentId: params.agentId,
101103
mediaUrls,
104+
messageId,
102105
localRoots: getAgentScopedMediaLocalRootsForSources({
103106
cfg: params.cfg,
104107
agentId: params.agentId,
@@ -119,6 +122,7 @@ export async function persistInternalSourceReply(params: {
119122
: {}),
120123
...(writerFence ? { expectedWriterRunId: writerFence.expectedWriterRunId } : {}),
121124
content: prepareGatewayInjectedAssistantContent(content),
125+
eventId: messageId,
122126
idempotencyKey: params.idempotencyKey,
123127
runId: params.runId,
124128
...(params.sourceReplyFinal !== undefined
@@ -134,16 +138,11 @@ export async function persistInternalSourceReply(params: {
134138
config: params.cfg,
135139
});
136140
if (!appended.ok) {
141+
await removeManagedOutgoingMediaBlocks({ blocks: mediaBlocks, messageId });
137142
throw new Error(`Internal source reply persistence failed: ${appended.reason}`);
138143
}
139-
if (
140-
mediaBlocks.length > 0 &&
141-
!attachManagedOutgoingMediaToMessage({
142-
messageId: appended.messageId,
143-
blocks: mediaBlocks,
144-
})
145-
) {
146-
throw new Error("Internal source reply media ownership could not be persisted");
144+
if (appended.messageId !== messageId) {
145+
await removeManagedOutgoingMediaBlocks({ blocks: mediaBlocks, messageId });
147146
}
148147
} finally {
149148
lease?.release();

‎src/gateway/managed-image-attachments.ts‎

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -787,6 +787,22 @@ export async function cleanupManagedOutgoingMediaRecords(params?: {
787787
return { deletedRecordCount, deletedFileCount, retainedCount };
788788
}
789789

790+
export async function removeManagedOutgoingMediaBlocks(params: {
791+
blocks: readonly Record<string, unknown>[];
792+
messageId: string;
793+
stateDir?: string;
794+
}): Promise<void> {
795+
const stateDir = params.stateDir ?? resolveStateDir();
796+
await Promise.all(
797+
collectManagedOutgoingAttachmentRefs(params.blocks).map(async ({ attachmentId }) => {
798+
const record = readManagedImageRecord(attachmentId, stateDir);
799+
if (record?.messageId === params.messageId) {
800+
await deleteManagedImageRecordArtifacts(record, stateDir);
801+
}
802+
}),
803+
);
804+
}
805+
790806
function resolveManagedSessionOwnerAgentId(
791807
sessionKey: string,
792808
explicitAgentId?: string,

‎ui/src/pages/chat/chat-view.test.ts‎

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1663,6 +1663,39 @@ describe("chat transcript rendering", () => {
16631663
"Latest streamed narration",
16641664
);
16651665

1666+
renderItems([
1667+
user,
1668+
{
1669+
kind: "group",
1670+
key: "group:assistant:persisted-announcement",
1671+
role: "assistant",
1672+
messages: [
1673+
{
1674+
key: "assistant:persisted-announcement",
1675+
message: {
1676+
role: "assistant",
1677+
content: "Persisted narration while the run continues",
1678+
runId: "run-announcement",
1679+
},
1680+
},
1681+
],
1682+
timestamp: 3,
1683+
isStreaming: false,
1684+
runId: "run-announcement",
1685+
},
1686+
{
1687+
kind: "reading-indicator",
1688+
key: "reading:persisted-announcement",
1689+
startedAt: 4,
1690+
runId: "run-announcement",
1691+
boundaryId: "send:run-announcement",
1692+
},
1693+
] as ReturnType<typeof chatThread.buildCachedChatItems>);
1694+
1695+
expect(container.querySelector(".chat-transcript-announcement")?.textContent).toBe(
1696+
"Persisted narration while the run continues",
1697+
);
1698+
16661699
renderItems([
16671700
user,
16681701
{ ...stream, isStreaming: false },

‎ui/src/pages/chat/components/chat-transcript-announcement.ts‎

Lines changed: 16 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -7,14 +7,17 @@ import type { TranscriptAnnouncement } from "./chat-transcript-controller.ts";
77
type ChatRenderItem = ReturnType<typeof coalesceAgentRunFrames>[number];
88
const ANNOUNCEMENT_MAX_CHARS = 500;
99

10-
function assistantGroupText(group: MessageGroup): string | null {
10+
function assistantGroupAnnouncementSource(
11+
group: MessageGroup,
12+
): { key: string; text: string } | null {
1113
if (group.role.toLowerCase() !== "assistant") {
1214
return null;
1315
}
1416
for (let index = group.messages.length - 1; index >= 0; index -= 1) {
15-
const text = extractTextCached(group.messages[index]?.message)?.trim();
17+
const source = group.messages[index];
18+
const text = extractTextCached(source?.message)?.trim();
1619
if (text) {
17-
return text;
20+
return { key: source?.key ?? group.key, text };
1821
}
1922
}
2023
return null;
@@ -58,6 +61,13 @@ export function latestTranscriptAnnouncement(
5861
}
5962
continue;
6063
}
64+
const groups = part.kind === "group" ? [part] : part.groups.toReversed();
65+
for (const group of groups) {
66+
const source = assistantGroupAnnouncementSource(group);
67+
if (source) {
68+
return announcement(source.key, source.text);
69+
}
70+
}
6171
}
6272
continue;
6373
}
@@ -68,10 +78,9 @@ export function latestTranscriptAnnouncement(
6878
? item.groups.toReversed()
6979
: [];
7080
for (const group of groups) {
71-
const text = assistantGroupText(group);
72-
if (text) {
73-
const owner = group.messages.findLast(({ message }) => Boolean(extractTextCached(message)));
74-
return announcement(owner?.key ?? item.key, text);
81+
const source = assistantGroupAnnouncementSource(group);
82+
if (source) {
83+
return announcement(source.key, source.text);
7584
}
7685
}
7786
}

0 commit comments

Comments
 (0)