Skip to content

Commit 0bd5c6a

Browse files
authored
feat(ui): render cross-session messages as linked speech bubbles (#132054)
* feat(ui): render cross-session messages as linked speech bubbles Messages delivered by sessions_send now render in the Control UI as left-aligned speech bubbles with a forward glyph, a clickable titled source-session chip (existing session-link titler, hovercard, and navigation attach by selector), and a stable per-source-session tint. The gateway display projection emits a structured senderSession {sessionKey, agentId} from the same derivation that builds the legacy senderLabel, with a prompt-prefix fallback for legacy transcripts. Provenance repairs in the same change: - sessions_send active-run steering now persists the structured inter_session provenance via the user-turn transcript recorder (previously only the text envelope survived), and the Codex app-server steering path commits recorder-bearing internal items. - worker.sessions.send now records the source channel. - assistant replies after a forwarded turn no longer show a stale 'Replying to' attribution naming the last human participant. Forwarded groups split and cache by source session; dedup signatures include the source so distinct senders never collapse. * test: drop duplicate temp-dir tracker introduced by rebase * style: format merged class list * test: teach sibling projection and contrast suites the forwarded surface server-methods projection fixtures now expect the structured senderSession field, and the WCAG contrast reader follows the tint rule's :is(.user, .chat-group--forwarded) selector, covering the forwarded bubble surface. * fix(copilot): persist inter-session provenance through active steering Copilot's ordinary steering branch dropped the sessions_send transcript recorder: the SDK event bridge persisted its own user row without provenance, so steered cross-session messages could not render as forwarded bubbles. session.send now routes through the journal's sendSdkUser seam, which gates SDK user events behind the messageId binding (safe when the event beats the send response), stamps the recorder's provenance onto the SDK-built row, and satisfies the recorder via runtime-persisted marks instead of a duplicate write. Suppressed writes mark the recorder blocked so waitForTranscriptCommit receipts stay honest. Sibling sweep: Codex app-server already persists recorder-bearing items; no other runtime persists an SDK-built user row on an active-steering path. * perf(ui): keep forwarded-chip render inside the startup JS budget The keyed directive pulled lit/directives/keyed into the boot graph for a remount that cannot occur: messages are immutable and grouping splits on senderSession, so a changed source always produces a new group key and a fresh anchor. Render the chip directly and narrow the test to the real protected behavior (titled chip survives re-renders). Startup JS returns to 346,695 B, inside the committed baseline's growth allowance. * fix(ui): keep non-navigable legacy source keys as plain text The titler, hovercard, and click handlers all reject keys without the agent: prefix, so rendering one as a focusable session chip produced a link that cannot open, title, or hover anything. Only parseable agent session keys become chips; other persisted source keys stay readable plain text in the attribution row. * style: format merged dedup signature * refactor: split capacity-limit test files, duplicate collapse, and ui shards PR additions landed on surfaces parked exactly at their caps. Split the forwarded/tool-details projection suites and sender-label/sender-session normalizer suites out of their 1000-line test files, extract the sequential-duplicate-collapse concept from chat-thread-items (706>700) into chat-thread-duplicates, and give ui/src/e2e its own tsgo shard so ui-pages-e2e returns under the 720-root memory bound. Pure moves; no caps or baselines changed. * fix: drop duplicate ui-e2e shard after main landed the same split * refactor: split worker-session-tool executor suites and near-cap prod modules Cap sweep for the branch: worker-session-tool-executor.test.ts (1007>1000) splits into a send-delivery suite plus shared test-support scaffolding; the executor's send path and outcome-unknown error move to their concept owners; the Copilot transcript journal sheds its replay bookkeeping into attempt-transcript-replay. Pure moves, no caps or baselines changed. * perf(ui): fit forwarded styling into the boot CSS budget The boot CSS chunk sat at 99.94% of its flat 53.0 KiB cap on main, so the forwarded-bubble styles tripped it. Consolidate the attribution row onto the existing chat-reply-attribution class (the two rows never coexist in a group), drop redundant declarations the base bubble already carries, delete two verified-dead selectors, and keep the per-session tint dark-only. The exhausted cap moves to 53.5 KiB with operator approval (2026-08-29). * style: format dead-css deletion sites * test: drop projection tool-detail suite duplicated by main's tool-result split
1 parent 5bbd9f8 commit 0bd5c6a

40 files changed

Lines changed: 2223 additions & 1188 deletions

‎docs/web/control-ui.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -809,6 +809,8 @@ Absolute external `http(s)` embed URLs stay blocked by default. To let `[embed u
809809

810810
The chat transcript uses a centered readable frame aligned with the composer. Assistant and tool output stay left-aligned while your own messages stay right-aligned inside that frame. In multi-user sessions (for example a group chat relayed from a channel plugin), messages from other attributed participants render left-aligned with the author's avatar, name, and a stable per-identity color, so only the signed-in viewer's messages read as "mine". When two or more attributed participants are present, assistant replies carry a small "Replying to name" marker naming the participant whose message triggered the turn. System entries such as local slash-command output render as centered notice rows without an avatar.
811811

812+
Messages forwarded by `sessions_send` render as left-aligned speech bubbles with a forward icon and a source-session chip above the message. Select the chip to open the source session; hover it to see session progress. Each source session has a stable bubble tint. Forwarded messages without a known source session show the source agent when available, or a generic forwarded-message label. The receiving agent's own replies remain flat text.
813+
812814
## Chat message width
813815

814816
Wide-monitor users can override the transcript width under **Settings → Chat →

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

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -292,8 +292,13 @@ export async function activateCodexAttemptTurn(
292292
return buildCodexUserInput(text, result.images);
293293
},
294294
beforeConfirmConsumed: async (items) => {
295-
const inboundItems = items.filter((item) => item.isInboundUserMessage === true);
296-
if (inboundItems.length === 0) {
295+
// Internal steering can own a user turn too. Commit its recorder after the
296+
// preceding answers so source provenance and transcript ordering survive.
297+
const transcriptItems = items.filter(
298+
(item) =>
299+
item.isInboundUserMessage === true || item.userTurnTranscriptRecorder !== undefined,
300+
);
301+
if (transcriptItems.length === 0) {
297302
return;
298303
}
299304
await promptMirrorPromise;
@@ -313,7 +318,7 @@ export async function activateCodexAttemptTurn(
313318
});
314319
activeProjector.markSteeringTranscriptPersisted();
315320
}
316-
for (const item of inboundItems) {
321+
for (const item of transcriptItems) {
317322
const recorder = item.userTurnTranscriptRecorder;
318323
if (!recorder) {
319324
continue;

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

Lines changed: 37 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -198,9 +198,26 @@ describe("runCodexAppServerAttempt steering", () => {
198198
await run;
199199
});
200200

201-
it.each(["none", "sleep", "dynamicToolCall", "commandExecution"])(
202-
"persists every completed answer before Gateway steering across a %s barrier",
203-
async (barrierType) => {
201+
it.each([
202+
...["none", "sleep", "dynamicToolCall", "commandExecution"].map((barrierType) => ({
203+
name: `Gateway steering across a ${barrierType} barrier`,
204+
barrierType,
205+
isInboundUserMessage: true,
206+
provenance: undefined,
207+
})),
208+
{
209+
name: "inter-session steering with provenance",
210+
barrierType: "none",
211+
isInboundUserMessage: false,
212+
provenance: {
213+
kind: "inter_session",
214+
sourceSessionKey: "agent:sender:main",
215+
sourceTool: "sessions_send",
216+
},
217+
},
218+
])(
219+
"persists every completed answer before $name",
220+
async ({ barrierType, isInboundUserMessage, provenance }) => {
204221
const { requests, waitForMethod, completeTurn, notify } = createStartedThreadHarness();
205222
const params = createSteeringParams();
206223
const storePath = path.join(tempDir, `${params.sessionId}.sqlite`);
@@ -249,6 +266,7 @@ describe("runCodexAppServerAttempt steering", () => {
249266
content: "steer this active turn",
250267
timestamp: Date.now(),
251268
idempotencyKey: `${params.runId}:steer:user`,
269+
...(provenance ? { provenance } : {}),
252270
},
253271
});
254272
return undefined;
@@ -332,7 +350,7 @@ describe("runCodexAppServerAttempt steering", () => {
332350
// promise stays pending until the matching item/completed notification below.
333351
await waitAndQueueActiveRunMessage(params.sessionId, "steer this active turn", {
334352
debounceMs: 0,
335-
isInboundUserMessage: true,
353+
isInboundUserMessage,
336354
toolAuthorityFingerprint: params.toolAuthorityFingerprint,
337355
taskSuggestionDeliveryMode: "gateway",
338356
waitForTranscriptCommit: true,
@@ -367,6 +385,7 @@ describe("runCodexAppServerAttempt steering", () => {
367385
role: string;
368386
content: string | Array<{ type: string; text?: string }>;
369387
__openclaw?: { mirrorIdentity?: string };
388+
provenance?: JsonObject;
370389
};
371390
}
372391
).message;
@@ -380,7 +399,14 @@ describe("runCodexAppServerAttempt steering", () => {
380399
.flatMap((part) => (part.type === "text" ? [part.text] : []))
381400
.join("");
382401
return text
383-
? [{ role: message.role, text, mirrorIdentity: message["__openclaw"]?.mirrorIdentity }]
402+
? [
403+
{
404+
role: message.role,
405+
text,
406+
mirrorIdentity: message["__openclaw"]?.mirrorIdentity,
407+
...(message.provenance ? { provenance: message.provenance } : {}),
408+
},
409+
]
384410
: [];
385411
});
386412
const prefix = await readTextRows();
@@ -414,7 +440,12 @@ describe("runCodexAppServerAttempt steering", () => {
414440
},
415441
{ role: "assistant", text: "answer-a", mirrorIdentity: "turn-1:assistant:answer-a" },
416442
{ role: "assistant", text: "answer-b", mirrorIdentity: "turn-1:assistant:answer-b" },
417-
{ role: "user", text: "steer this active turn", mirrorIdentity: undefined },
443+
{
444+
role: "user",
445+
text: "steer this active turn",
446+
mirrorIdentity: undefined,
447+
...(provenance ? { provenance } : {}),
448+
},
418449
]);
419450
expect(await readTextRows()).toEqual([
420451
...prefix,

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

Lines changed: 203 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,19 @@
11
import { createDeferred } from "openclaw/plugin-sdk/extension-shared";
2-
import { beforeEach, describe, expect, it, vi } from "vitest";
2+
import {
3+
initializeGlobalHookRunner,
4+
resetGlobalHookRunner,
5+
} from "openclaw/plugin-sdk/hook-runtime";
6+
import { createMockPluginRegistry } from "openclaw/plugin-sdk/plugin-test-runtime";
7+
import { readSessionTranscriptEvents } from "openclaw/plugin-sdk/session-transcript-runtime";
8+
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
39
import { registerCopilotActiveRun } from "./attempt-active-run.js";
410
import type { AttemptTranscriptJournal } from "./attempt-transcript-journal.js";
11+
import {
12+
cleanupAttemptTranscriptJournalFixtures,
13+
createFixture,
14+
event,
15+
transcriptMessages,
16+
} from "./attempt-transcript-journal.test-helpers.js";
517
import type { AttemptParamsLike } from "./attempt-types.js";
618
import type { SessionLike } from "./event-bridge.js";
719
import type { CopilotUserInputBridge } from "./user-input-bridge.js";
@@ -27,10 +39,12 @@ function registerTestRun(params?: {
2739
startedAtMs?: number;
2840
receipt?: Promise<void>;
2941
send?: SessionLike["send"];
42+
session?: SessionLike;
43+
journal?: AttemptTranscriptJournal;
3044
}) {
3145
const send = params?.send ?? vi.fn(async () => "steer-1");
3246
const waitForSdkUserPersisted = vi.fn(() => params?.receipt ?? Promise.resolve());
33-
const session: SessionLike = {
47+
const session: SessionLike = params?.session ?? {
3448
abort: vi.fn(async () => undefined),
3549
disconnect: vi.fn(async () => undefined),
3650
on: vi.fn() as SessionLike["on"],
@@ -46,7 +60,12 @@ function registerTestRun(params?: {
4660
isAborted: () => false,
4761
isSettled: () => false,
4862
session,
49-
transcriptJournal: { waitForSdkUserPersisted } as unknown as AttemptTranscriptJournal,
63+
transcriptJournal:
64+
params?.journal ??
65+
({
66+
waitForSdkUserPersisted,
67+
sendSdkUser: (submit: () => Promise<string>) => submit(),
68+
} as unknown as AttemptTranscriptJournal),
5069
userInputBridge: {
5170
cancelPending: vi.fn(),
5271
onUserInputRequest: vi.fn(),
@@ -55,7 +74,28 @@ function registerTestRun(params?: {
5574
return { handle, send, waitForSdkUserPersisted };
5675
}
5776

77+
function createSteeringRecorder(
78+
recorder: NonNullable<AttemptParamsLike["userTurnTranscriptRecorder"]>,
79+
sourceSessionKey = "agent:other:source",
80+
) {
81+
const message = {
82+
role: "user" as const,
83+
content: "change course",
84+
timestamp: 1,
85+
provenance: { kind: "inter_session" as const, sourceSessionKey, sourceTool: "sessions_send" },
86+
};
87+
return {
88+
...recorder,
89+
message,
90+
resolveMessage: vi.fn(async () => message),
91+
markSentToProvider: vi.fn(),
92+
markRuntimePersisted: vi.fn(),
93+
};
94+
}
95+
5896
describe("registerCopilotActiveRun", () => {
97+
afterEach(cleanupAttemptTranscriptJournalFixtures);
98+
afterEach(resetGlobalHookRunner);
5999
beforeEach(() => {
60100
harnessMocks.cancelPendingAgentQuestionForSession.mockClear();
61101
harnessMocks.claimPendingAgentQuestionAnswer.mockReset();
@@ -87,6 +127,166 @@ describe("registerCopilotActiveRun", () => {
87127
expect(onQueueAccepted).toHaveBeenCalledOnce();
88128
});
89129

130+
it.each(["before response", "after response", "during tools", "hook replacement"])(
131+
"persists steering provenance once and confirms its SDK receipt: %s",
132+
async (timing) => {
133+
const { journal, recorder, session, target } = await createFixture();
134+
await journal.persistInitialUser();
135+
session.emit(event("user.message", "initial-user", { content: "inspect both files" }));
136+
const steeringRecorder = createSteeringRecorder(recorder);
137+
const { message } = steeringRecorder;
138+
const { provenance } = message;
139+
if (timing === "hook replacement") {
140+
initializeGlobalHookRunner(
141+
createMockPluginRegistry([
142+
{
143+
hookName: "before_message_write",
144+
handler: () => ({
145+
message: { role: "user", content: message.content, timestamp: 1 },
146+
}),
147+
},
148+
]),
149+
);
150+
}
151+
const sdkUser = event("user.message", "steer-1", { content: message.content });
152+
const response = createDeferred<string>();
153+
const send = vi.fn(() => {
154+
if (timing !== "after response") {
155+
session.emit(sdkUser);
156+
}
157+
return response.promise;
158+
});
159+
session.send = send;
160+
if (timing === "during tools") {
161+
session.emit(
162+
event("assistant.message", "assistant-tools", {
163+
content: "checking",
164+
messageId: "assistant-tools",
165+
toolRequests: [{ name: "read", arguments: {}, toolCallId: "read-1" }],
166+
}),
167+
);
168+
session.emit(
169+
event("tool.execution_start", "start-read", { toolCallId: "read-1", toolName: "read" }),
170+
);
171+
}
172+
const { handle } = registerTestRun({ journal, session });
173+
const onQueueAccepted = vi.fn();
174+
let confirmed = false;
175+
const delivery = handle
176+
.queueMessage(message.content, {
177+
userTurnTranscriptRecorder: steeringRecorder,
178+
onQueueAccepted,
179+
waitForTranscriptCommit: true,
180+
})
181+
.then((result) => {
182+
confirmed = true;
183+
return result;
184+
});
185+
await vi.waitFor(() => expect(send).toHaveBeenCalledOnce());
186+
expect(onQueueAccepted).not.toHaveBeenCalled();
187+
response.resolve("steer-1");
188+
await vi.waitFor(() => expect(onQueueAccepted).toHaveBeenCalledWith(true));
189+
if (timing === "after response" || timing === "during tools") {
190+
expect(confirmed).toBe(false);
191+
}
192+
if (timing === "after response") {
193+
session.emit(sdkUser);
194+
} else if (timing === "during tools") {
195+
session.emit(
196+
event("tool.execution_complete", "result-read", {
197+
toolCallId: "read-1",
198+
success: true,
199+
result: { content: "done" },
200+
}),
201+
);
202+
}
203+
await expect(delivery).resolves.toBeUndefined();
204+
session.emit(sdkUser);
205+
await journal.barrier("steering replay");
206+
const rows = transcriptMessages(await readSessionTranscriptEvents(target));
207+
const steered = rows.filter(
208+
(row) => row.message.role === "user" && row.message.content === message.content,
209+
);
210+
expect(steered).toHaveLength(1);
211+
expect(steered[0]?.message).toMatchObject({
212+
provenance,
213+
idempotencyKey: "copilot-sdk:sdk-session:steer-1",
214+
});
215+
expect(steeringRecorder.markRuntimePersisted).toHaveBeenCalledWith(
216+
expect.objectContaining({ provenance }),
217+
expect.objectContaining({ entryId: steered[0]?.id }),
218+
);
219+
expect(steeringRecorder.persistApproved).not.toHaveBeenCalled();
220+
expect(steeringRecorder.markSentToProvider).toHaveBeenCalledOnce();
221+
},
222+
);
223+
224+
it.each([false, true])(
225+
"correlates concurrent identical steering by SDK id and releases rejected sends: reject=%s",
226+
async (rejectFirst) => {
227+
const { journal, recorder, session, target } = await createFixture();
228+
await journal.persistInitialUser();
229+
session.emit(event("user.message", "initial-user", { content: "inspect both files" }));
230+
const first = createSteeringRecorder(recorder, "agent:first:source");
231+
const second = createSteeringRecorder(recorder, "agent:second:source");
232+
const response = createDeferred<string>();
233+
const send = vi
234+
.fn()
235+
.mockImplementationOnce(() => response.promise)
236+
.mockImplementationOnce(async () => {
237+
session.emit(event("user.message", "second", { content: second.message.content }));
238+
return "second";
239+
});
240+
session.send = send;
241+
const { handle } = registerTestRun({ journal, session });
242+
const firstDelivery = handle.queueMessage(first.message.content, {
243+
userTurnTranscriptRecorder: first,
244+
waitForTranscriptCommit: true,
245+
});
246+
const firstOutcome = firstDelivery.catch((error: unknown) => error);
247+
await vi.waitFor(() => expect(send).toHaveBeenCalledTimes(1));
248+
const secondAccepted = vi.fn();
249+
const secondDelivery = handle.queueMessage(second.message.content, {
250+
userTurnTranscriptRecorder: second,
251+
waitForTranscriptCommit: true,
252+
onQueueAccepted: secondAccepted,
253+
});
254+
await vi.waitFor(() => expect(secondAccepted).toHaveBeenCalledWith(true));
255+
if (rejectFirst) {
256+
response.reject(new Error("send rejected"));
257+
await expect(firstOutcome).resolves.toMatchObject({ message: "send rejected" });
258+
} else {
259+
session.emit(event("user.message", "first", { content: first.message.content }));
260+
response.resolve("first");
261+
await expect(firstOutcome).resolves.toBeUndefined();
262+
}
263+
await expect(secondDelivery).resolves.toBeUndefined();
264+
session.emit(event("user.message", "native", { content: first.message.content }));
265+
await journal.barrier("concurrent steering");
266+
const users = transcriptMessages(await readSessionTranscriptEvents(target))
267+
.filter((row) => row.message.role === "user")
268+
.slice(1);
269+
expect(users.map((row) => row.message)).toEqual([
270+
expect.objectContaining({
271+
idempotencyKey: "copilot-sdk:sdk-session:second",
272+
provenance: second.message.provenance,
273+
}),
274+
...(!rejectFirst
275+
? [
276+
expect.objectContaining({
277+
idempotencyKey: "copilot-sdk:sdk-session:first",
278+
provenance: first.message.provenance,
279+
}),
280+
]
281+
: []),
282+
expect.not.objectContaining({ provenance: expect.anything() }),
283+
]);
284+
expect(first.markRuntimePersisted).toHaveBeenCalledTimes(rejectFirst ? 0 : 1);
285+
expect(second.markRuntimePersisted).toHaveBeenCalledOnce();
286+
expect(recorder.persistApproved).not.toHaveBeenCalled();
287+
},
288+
);
289+
90290
it("reports a claimed pending question as accepted without sending steering", async () => {
91291
harnessMocks.claimPendingAgentQuestionAnswer.mockResolvedValueOnce(true);
92292
const onQueueAccepted = vi.fn();

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

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -76,7 +76,10 @@ export function registerCopilotActiveRun(params: {
7676
if (!params.canAcceptSteering()) {
7777
throw new Error("Copilot steering is unavailable before initial user validation");
7878
}
79-
messageId = await params.session.send({ prompt: text });
79+
messageId = await params.transcriptJournal.sendSdkUser(
80+
() => params.session.send({ prompt: text }),
81+
options?.userTurnTranscriptRecorder,
82+
);
8083
reportAcceptance(true);
8184
} catch (error) {
8285
reportAcceptance(false);

0 commit comments

Comments
 (0)