Skip to content

Commit de0fa7c

Browse files
steipetePeter Steinberger
andauthored
feat(webchat): expand truncated assistant messages inline (#117936)
* feat(webchat): expand truncated assistant messages inline Replace the per-message Open in canvas button with an inline Show more / Show less disclosure on truncated assistant messages that fetches full content via chat.message.get on demand. * test(webchat): stabilize inline expansion e2e * fix(ui): satisfy lint and export gates for inline show-more * test(ui): update shared disclosure selector --------- Co-authored-by: Peter Steinberger <[email protected]>
1 parent 4d8fcf4 commit de0fa7c

22 files changed

Lines changed: 522 additions & 236 deletions

‎docs/web/control-ui.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -451,7 +451,7 @@ Capability toggles stay disabled until the Gateway, session, and runtime config
451451
- Chat uploads accept images plus non-video files. Images keep the native image path; other files are stored as managed media and shown in history as attachment links.
452452
- Re-sending with the same `idempotencyKey` returns `{ status: "in_flight" }` while running, and `{ status: "ok" }` after completion.
453453
- `chat.history` responses are size-bounded for UI safety. When transcript entries are too large, Gateway may truncate long text fields, omit heavy metadata blocks, and replace oversized messages with a placeholder (`[chat.history omitted: message too large]`).
454-
- When a visible assistant message was truncated in `chat.history`, the side reader can fetch the full display-normalized transcript entry on demand through `chat.message.get` by `sessionKey`, active `agentId` when needed, and transcript `messageId`. If the Gateway still cannot return more, the reader shows an explicit unavailable state instead of silently repeating the truncated preview.
454+
- When a visible assistant message was truncated in `chat.history`, **Show more** fetches the full display-normalized transcript entry inline through `chat.message.get` by `sessionKey`, active `agentId` when needed, and transcript `messageId`. **Show less** restores the preview without discarding the fetched content. If the Gateway cannot return more, the message shows an explicit retryable error instead of silently repeating the truncated preview.
455455
- Assistant/generated images are persisted as managed media references. New clients resolve their stable artifact ids through authenticated `artifacts.download` and receive short-lived, exact-resource media URLs, so reloads do not depend on raw base64 payloads or reusable credentials in image URLs.
456456
- When rendering `chat.history`, the Control UI strips display-only inline directive tags from visible assistant text (for example `[[reply_to_*]]` and `[[audio_as_voice]]`), plain-text tool-call XML payloads (including `<tool_call>...</tool_call>`, `<function_call>...</function_call>`, `<tool_calls>...</tool_calls>`, `<function_calls>...</function_calls>`, and truncated tool-call blocks), and leaked ASCII/full-width model control tokens. It omits assistant entries whose whole visible text is only the exact silent token `NO_REPLY` / `no_reply` or the heartbeat acknowledgement token `HEARTBEAT_OK`.
457457
- During an active send and the final history refresh, the chat view keeps local optimistic user/assistant messages visible if `chat.history` briefly returns an older snapshot; the canonical transcript replaces those local messages once the Gateway history catches up.

‎docs/web/webchat.md‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,7 @@ Status: the macOS/iOS SwiftUI chat UI talks directly to the Gateway WebSocket. N
2424

2525
- The UI connects to the Gateway WebSocket and uses the `chat.history`, `chat.send`, `chat.inject`, and `chat.message.get` RPC methods.
2626
- `chat.history` is bounded for stability: Gateway may truncate long text fields, omit heavy metadata, and replace oversized entries with `[chat.history omitted: message too large]`. API clients can send a per-request `maxChars` to override the default limit for one call.
27-
- When a visible assistant message was truncated in `chat.history`, Control UI can open a side reader and fetch the full display-normalized entry on demand through `chat.message.get`, without increasing the default history payload. `chat.message.get` uses the same transcript branch and display rules as `chat.history`, but targets one entry by `messageId` and returns an honest unavailable reason when the full content can no longer be returned.
27+
- When a visible assistant message was truncated in `chat.history`, **Show more** fetches the full display-normalized entry inline through `chat.message.get`, without increasing the default history payload. **Show less** restores the truncated preview and reuses the fetched content on the next expansion. `chat.message.get` uses the same transcript branch and display rules as `chat.history`, but targets one entry by `messageId` and returns an honest unavailable reason when the full content can no longer be returned.
2828
- `chat.history` follows the active transcript branch for append-only session files, so abandoned rewrite branches and superseded prompt copies are not rendered in WebChat.
2929
- Compaction entries render as a "Compacted history" divider explaining that the compacted transcript is preserved as a checkpoint, with an action to open session checkpoints (branch or restore, when permissions allow).
3030
- Control UI remembers the backing Gateway `sessionId` returned by `chat.history` and includes it on follow-up `chat.send` calls, so reconnects and page refreshes continue the same stored conversation unless the user starts or resets a session.

‎ui/src/e2e/chat-message-actions.e2e.test.ts‎

Lines changed: 51 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -135,7 +135,9 @@ describeControlUiE2e("Control UI chat message actions", () => {
135135
const messageText = "Reply and context menu action proof.";
136136
const privateThinking = "private reply reasoning";
137137
const visibleThinkingAnswer = "Visible reply context only.";
138-
await installMockGateway(page, {
138+
const truncatedPreview = "Truncated assistant preview\n...(truncated)...";
139+
const fullAssistantContent = "Complete assistant content loaded inline.";
140+
const gateway = await installMockGateway(page, {
139141
historyMessages: [
140142
{
141143
role: "assistant",
@@ -160,7 +162,25 @@ describeControlUiE2e("Control UI chat message actions", () => {
160162
timestamp: Date.now() + 2,
161163
__openclaw: { id: "assistant-thinking-proof", seq: 3 },
162164
},
165+
{
166+
role: "user",
167+
content: [{ type: "text", text: "Keep the truncated message separate." }],
168+
timestamp: Date.now() + 3,
169+
__openclaw: { id: "user-truncated-separator", seq: 4 },
170+
},
171+
{
172+
role: "assistant",
173+
content: [{ type: "text", text: truncatedPreview }],
174+
timestamp: Date.now() + 4,
175+
__openclaw: { id: "assistant-truncated-proof", seq: 5 },
176+
},
163177
],
178+
methodResponses: {
179+
"chat.message.get": {
180+
ok: true,
181+
message: { role: "assistant", content: fullAssistantContent },
182+
},
183+
},
164184
});
165185

166186
try {
@@ -234,7 +254,7 @@ describeControlUiE2e("Control UI chat message actions", () => {
234254
const inlineActions = group.locator(".chat-group-footer-actions button");
235255
expect(
236256
await inlineActions.evaluateAll((buttons) => buttons.map((button) => button.ariaLabel)),
237-
).toEqual(["Reply to message", "Hide message", "Open in canvas", "Copy as markdown"]);
257+
).toEqual(["Reply to message", "Hide message", "Copy as markdown"]);
238258
for (const button of await inlineActions.all()) {
239259
const label = await button.getAttribute("aria-label");
240260
await expectHoverColor(button, label === "Hide message" ? "--danger" : "--accent");
@@ -313,7 +333,6 @@ describeControlUiE2e("Control UI chat message actions", () => {
313333
"Copy",
314334
"Reply",
315335
"Hide message",
316-
"Open in canvas",
317336
"Copy as markdown",
318337
]);
319338
await screenshot(page, "04-selected-text-context-menu.png");
@@ -328,7 +347,6 @@ describeControlUiE2e("Control UI chat message actions", () => {
328347
expect(await menu.getByRole("menuitem").allTextContents()).toEqual([
329348
"Reply",
330349
"Hide message",
331-
"Open in canvas",
332350
"Copy as markdown",
333351
]);
334352
expect(
@@ -341,10 +359,35 @@ describeControlUiE2e("Control UI chat message actions", () => {
341359
.poll(() => page.evaluate(() => navigator.clipboard.readText()))
342360
.toBe(messageText);
343361

344-
await bubble.click({ button: "right" });
345-
await page.getByRole("menuitem", { name: "Open in canvas" }).click();
346-
const markdownSidebar = page.locator(".sidebar-markdown");
347-
await markdownSidebar.getByText(messageText, { exact: true }).waitFor({ state: "visible" });
362+
const expandableBubble = page.locator(
363+
'.chat-bubble[data-entry-id="assistant-truncated-proof"]',
364+
);
365+
await expandableBubble.getByRole("button", { name: "Show more" }).click();
366+
const fullMessageRequest = await gateway.waitForRequest("chat.message.get");
367+
expect(fullMessageRequest.params).toMatchObject({
368+
sessionKey: "main",
369+
messageId: "assistant-truncated-proof",
370+
maxChars: 500_000,
371+
});
372+
await expandableBubble.getByText(fullAssistantContent, { exact: true }).waitFor({
373+
state: "visible",
374+
});
375+
376+
await expandableBubble.getByRole("button", { name: "Show less" }).click();
377+
await expect
378+
.poll(async () =>
379+
(await expandableBubble.locator(".chat-message-disclosure__content").textContent())
380+
?.split("\n")
381+
.map((line) => line.trim())
382+
.filter(Boolean)
383+
.join("\n"),
384+
)
385+
.toBe(truncatedPreview);
386+
await expandableBubble.getByRole("button", { name: "Show more" }).click();
387+
await expandableBubble.getByText(fullAssistantContent, { exact: true }).waitFor({
388+
state: "visible",
389+
});
390+
expect(await gateway.getRequests("chat.message.get")).toHaveLength(1);
348391

349392
await bubble.click({ button: "right" });
350393
await page.getByRole("menuitem", { name: "Hide message" }).click();

‎ui/src/i18n/locales/en.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -4881,7 +4881,7 @@ export const en: TranslationMap = {
48814881
hideConfirm: "Hide this message in this browser? The agent still sees it.",
48824882
hideMessage: "Hide message",
48834883
hideTooltip: "Hide in this browser only",
4884-
openInCanvas: "Open in canvas",
4884+
fullContentLoadFailed: "Could not load the full message.",
48854885
reply: "Reply",
48864886
replyToMessage: "Reply to message",
48874887
replyingTo: "Replying to {name}",
Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
import { describe, expect, it, vi } from "vitest";
2+
import { resolveChatMessageAccess } from "./chat-message-access.ts";
3+
import type { ChatPageHost } from "./chat-state-host.ts";
4+
5+
describe("chat message access", () => {
6+
it("loads full messages with the session-scoped agent", async () => {
7+
const request = vi.fn().mockResolvedValue({ ok: true, message: { role: "assistant" } });
8+
const access = resolveChatMessageAccess({
9+
assistantAgentId: "alpha",
10+
agentsList: null,
11+
client: { request } as unknown as ChatPageHost["client"],
12+
connected: true,
13+
hello: null,
14+
sessionKey: "agent:alpha:main",
15+
});
16+
17+
expect(access.catalogKey).toBeNull();
18+
expect(access.chatProps.fullMessageAgentId).toBe("alpha");
19+
expect(access.chatProps.loadFullAssistantMessage).toBe(access.fullMessageLoader);
20+
await access.fullMessageLoader?.({
21+
sessionKey: "agent:alpha:main",
22+
agentId: "alpha",
23+
messageId: "message-1",
24+
kind: "assistant_message",
25+
});
26+
expect(request).toHaveBeenCalledWith("chat.message.get", {
27+
sessionKey: "agent:alpha:main",
28+
agentId: "alpha",
29+
messageId: "message-1",
30+
maxChars: 500_000,
31+
});
32+
});
33+
34+
it("disables full-message loading for catalog sessions", () => {
35+
const access = resolveChatMessageAccess({
36+
assistantAgentId: "alpha",
37+
agentsList: null,
38+
client: { request: vi.fn() } as unknown as ChatPageHost["client"],
39+
connected: true,
40+
hello: null,
41+
sessionKey: "catalog:catalog-1:host-1:thread-1",
42+
});
43+
44+
expect(access.catalogKey).toEqual({
45+
catalogId: "catalog-1",
46+
hostId: "host-1",
47+
threadId: "thread-1",
48+
});
49+
expect(access.fullMessageLoader).toBeNull();
50+
expect(access.chatProps.loadFullAssistantMessage).toBeNull();
51+
});
52+
});
Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,20 @@
1+
import { parseCatalogSessionKey } from "../../lib/sessions/catalog-key.ts";
2+
import { scopedAgentParamsForSession } from "../../lib/sessions/index.ts";
3+
import { createSidebarFullMessageLoader } from "./chat-pane-sidebar-layout.ts";
4+
import type { ChatPageHost } from "./chat-state-host.ts";
5+
import type { ChatProps } from "./chat-view.ts";
6+
7+
type ChatMessageAccessState = Pick<
8+
ChatPageHost,
9+
"assistantAgentId" | "agentsList" | "client" | "connected" | "hello" | "sessionKey"
10+
>;
11+
12+
export function resolveChatMessageAccess(state: ChatMessageAccessState) {
13+
const catalogKey = parseCatalogSessionKey(state.sessionKey);
14+
const fullMessageLoader = createSidebarFullMessageLoader(state, Boolean(catalogKey));
15+
const chatProps: Pick<ChatProps, "fullMessageAgentId" | "loadFullAssistantMessage"> = {
16+
fullMessageAgentId: scopedAgentParamsForSession(state, state.sessionKey).agentId,
17+
loadFullAssistantMessage: fullMessageLoader,
18+
};
19+
return { catalogKey, fullMessageLoader, chatProps };
20+
}

‎ui/src/pages/chat/chat-pane-render.ts‎

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,10 @@ import {
1616
projectSessionObserverDigest,
1717
resolveChatPaneObserverRunId,
1818
} from "../../lib/observer-digest.ts";
19-
import { parseCatalogSessionKey } from "../../lib/sessions/catalog-key.ts";
20-
import { scopedAgentParamsForSession } from "../../lib/sessions/index.ts";
2119
import { buildAgentMainSessionKey } from "../../lib/sessions/session-key.ts";
2220
import { renderBoardSessionSurface } from "./board-session-surface.ts";
2321
import { clearChatHistory } from "./chat-history.ts";
22+
import { resolveChatMessageAccess } from "./chat-message-access.ts";
2423
import { createChatModelSetupBanner, requiresChatModelSetup } from "./chat-model-setup.ts";
2524
import { ChatPaneHeader } from "./chat-pane-header.ts";
2625
import {
@@ -29,7 +28,6 @@ import {
2928
WORKSPACE_RAIL_SIDE_MIN_PANE_WIDTH,
3029
} from "./chat-pane-shared.ts";
3130
import {
32-
createSidebarFullMessageLoader,
3331
renderSidebarRegion,
3432
resolveSidebarLayoutForBoard,
3533
restoreHiddenSidebarChat,
@@ -122,7 +120,7 @@ export class ChatPane extends ChatPaneHeader {
122120
),
123121
);
124122
const currentAgentId = resolveChatAgentId(state);
125-
const catalogKey = parseCatalogSessionKey(state.sessionKey);
123+
const { catalogKey, fullMessageLoader, chatProps } = resolveChatMessageAccess(state);
126124
const overlays = this.context?.overlays;
127125
const approvalSnapshot = overlays?.snapshot;
128126
const inlineApproval = this.active
@@ -542,7 +540,7 @@ export class ChatPane extends ChatPaneHeader {
542540
onClearHistory: () => void clearChatHistory(state),
543541
agentsList: state.agentsList,
544542
currentAgentId,
545-
fullMessageAgentId: scopedAgentParamsForSession(state, state.sessionKey).agentId,
543+
...chatProps,
546544
onAgentChange: (agentId) => {
547545
const nextSessionKey = buildAgentMainSessionKey({ agentId });
548546
this.onPaneSessionChange?.(this.paneId, nextSessionKey);
@@ -615,7 +613,7 @@ export class ChatPane extends ChatPaneHeader {
615613
detail: html`<openclaw-chat-detail-panel
616614
class="chat-sidebar"
617615
.content=${state.sidebarContent}
618-
.loadFullMessage=${createSidebarFullMessageLoader(state, Boolean(catalogKey))}
616+
.loadFullMessage=${fullMessageLoader}
619617
.canvasPluginSurfaceUrl=${state.canvasPluginSurfaceUrl}
620618
.embedSandboxMode=${state.embedSandboxMode}
621619
.allowExternalEmbedUrls=${state.allowExternalEmbedUrls}

‎ui/src/pages/chat/chat-pane-sidebar-layout.ts‎

Lines changed: 4 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -5,10 +5,7 @@ import type {
55
SidebarPanelTemplates,
66
SidebarRegionCallbacks,
77
} from "./components/chat-sidebar-region-types.ts";
8-
import type {
9-
DetailFullMessageResult,
10-
SidebarFullMessageRequest,
11-
} from "./components/chat-sidebar.ts";
8+
import type { SidebarFullMessageLoader } from "./components/chat-sidebar.ts";
129
import {
1310
closeSlot,
1411
detachPanelToColumn,
@@ -195,15 +192,15 @@ export function restoreHiddenSidebarChat(params: {
195192
export function createSidebarFullMessageLoader(
196193
state: { client: GatewayBrowserClient | null; connected: boolean },
197194
disabled: boolean,
198-
): ((request: SidebarFullMessageRequest) => Promise<DetailFullMessageResult | null>) | null {
199-
if (disabled) {
195+
): SidebarFullMessageLoader | null {
196+
if (disabled || !state.client || !state.connected) {
200197
return null;
201198
}
202199
return async (request) => {
203200
if (!state.client || !state.connected) {
204201
return null;
205202
}
206-
return state.client.request<DetailFullMessageResult>("chat.message.get", {
203+
return state.client.request("chat.message.get", {
207204
sessionKey: request.sessionKey,
208205
...(request.agentId ? { agentId: request.agentId } : {}),
209206
messageId: request.messageId,

‎ui/src/pages/chat/chat-responsive.browser.test.ts‎

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -160,9 +160,6 @@ function activityAlignmentHtml() {
160160
function chatFooterActionsHtml() {
161161
return `
162162
<div class="chat-group-footer-actions">
163-
<button class="chat-expand-btn" type="button" aria-label="Open in canvas">
164-
<span class="chat-expand-btn__icon" aria-hidden="true">${iconSvg()}</span>
165-
</button>
166163
<button class="chat-copy-btn" type="button" aria-label="Copy as markdown">
167164
<span class="chat-copy-btn__icon" aria-hidden="true">${iconSvg()}</span>
168165
</button>

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

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3899,7 +3899,9 @@ describe("expansion-state render dependencies", () => {
38993899
expect(getExpansionStateVersion(currentUsers)).toBe(previousUserVersion);
39003900
const toolCardId = expectDefined(currentTools.keys().next().value, "retained tool card");
39013901
expectDefined(
3902-
retainedPane.querySelector<HTMLButtonElement>(".chat-user-message-disclosure__toggle"),
3902+
retainedPane.querySelector<HTMLButtonElement>(
3903+
".chat-group.user .chat-message-disclosure__toggle",
3904+
),
39033905
"mounted user disclosure",
39043906
).click();
39053907
expectDefined(

0 commit comments

Comments
 (0)