Skip to content

Commit d8488a9

Browse files
fix(ui): keep short JSON code blocks visible (#122313)
1 parent f30e672 commit d8488a9

4 files changed

Lines changed: 183 additions & 14 deletions

File tree

‎ui/src/components/markdown-code-blocks.ts‎

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@ import { escapeMarkdownHtml, isMarkdownBlockArtText } from "./markdown-text.ts";
2020

2121
const blockArtCopyPayloadPrefix = "openclaw:block-art-code:";
2222
const blockArtCodeBlockCopyPayloadEncoding = "block-art-json";
23+
// Keep typical replies visible; disclosure is reserved for JSON that dominates the transcript.
24+
const JSON_COLLAPSE_LINE_THRESHOLD = 40;
2325
const codeBlockCopyAttempts = new WeakMap<HTMLElement, number>();
2426
const codeBlockCopyResetTimers = new WeakMap<HTMLElement, ReturnType<typeof setTimeout>>();
2527

@@ -175,12 +177,11 @@ export function renderMarkdownCodeBlock(
175177
(trimmed.startsWith("[") && trimmed.endsWith("]"))));
176178

177179
if (isJson) {
178-
const lineCount = text.split("\n").length;
179-
const label =
180-
lineCount > 1
181-
? escapeMarkdownHtml(t("chat.codeBlock.jsonLines", { count: String(lineCount) }))
182-
: "JSON";
183-
return `<details class="json-collapse"><summary>${label}</summary><div class="code-block-wrapper">${header}${codeBlock}</div></details>`;
180+
const lineCount = markdownCodeBlockCopyText(text).split("\n").length;
181+
if (lineCount > JSON_COLLAPSE_LINE_THRESHOLD) {
182+
const label = escapeMarkdownHtml(t("chat.codeBlock.jsonLines", { count: String(lineCount) }));
183+
return `<details class="json-collapse code-block-wrapper"><summary class="code-block-header"><span>${label}</span>${copyButton}</summary>${codeBlock}</details>`;
184+
}
184185
}
185186

186187
return `<div class="code-block-wrapper">${header}${codeBlock}</div>`;

‎ui/src/components/markdown.test.ts‎

Lines changed: 26 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -241,6 +241,11 @@ describe("toSanitizedMarkdownHtml", () => {
241241

242242
describe("code blocks", () => {
243243
const blockArt = " ▀▀▀▀ \n ▄▄▄▄ \n ████ ";
244+
const jsonBlock = (lineCount: number) => {
245+
const values = Array.from({ length: lineCount - 2 }, (_, index) => ` ${index},`);
246+
values[values.length - 1] = values.at(-1)?.slice(0, -1) ?? "";
247+
return `\`\`\`json\n[\n${values.join("\n")}\n]\n\`\`\``;
248+
};
244249

245250
it("renders raw block art as a whitespace-preserving code block", () => {
246251
const html = toSanitizedMarkdownHtml(blockArt);
@@ -343,17 +348,30 @@ PY
343348
);
344349
});
345350

346-
it("highlights collapsed JSON code blocks", () => {
347-
const html = toSanitizedMarkdownHtml('```json\n{"ok": true}\n```');
351+
it("keeps short JSON code blocks visible and highlighted", () => {
352+
const html = toSanitizedMarkdownHtml(jsonBlock(6));
348353
const fragment = htmlFragment(html);
349-
const details = fragment.querySelector("details.json-collapse");
350-
const code = details?.querySelector("pre code");
354+
const code = fragment.querySelector(".code-block-wrapper pre code");
351355

352-
expect(details?.querySelector("summary")?.textContent).toBe("JSON · 2 lines");
353-
expect(code?.textContent).toBe('{"ok": true}\n');
356+
expect(fragment.querySelector("details.json-collapse")).toBeNull();
357+
expect(code?.textContent?.split("\n")).toHaveLength(7);
354358
expect(code?.innerHTML).toContain("hljs-");
355359
});
356360

361+
it("collapses JSON only above 40 lines and uses one copyable header", () => {
362+
const atLimit = htmlFragment(toSanitizedMarkdownHtml(jsonBlock(40)));
363+
const overLimit = htmlFragment(toSanitizedMarkdownHtml(jsonBlock(41)));
364+
const details = overLimit.querySelector("details.json-collapse");
365+
const summary = details?.querySelector("summary");
366+
367+
expect(atLimit.querySelector("details.json-collapse")).toBeNull();
368+
expect(summary?.textContent).toContain("JSON · 41 lines");
369+
expect(summary?.querySelector(".code-block-copy")).toBeInstanceOf(HTMLButtonElement);
370+
expect(details?.querySelectorAll(".code-block-header")).toHaveLength(1);
371+
expect(summary?.classList.contains("code-block-header")).toBe(true);
372+
expect(details?.querySelector("pre code")?.innerHTML).toContain("hljs-");
373+
});
374+
357375
it("localizes collapsed JSON line counts", async () => {
358376
i18n.registerTranslation("pt-BR", {
359377
chat: {
@@ -364,8 +382,8 @@ PY
364382
});
365383
await i18n.setLocale("pt-BR");
366384
try {
367-
const fragment = htmlFragment(toSanitizedMarkdownHtml('```json\n{"ok": true}\n```'));
368-
expect(fragment.querySelector("summary")?.textContent).toBe("JSON · 2 linhas");
385+
const fragment = htmlFragment(toSanitizedMarkdownHtml(jsonBlock(41)));
386+
expect(fragment.querySelector("summary")?.textContent).toContain("JSON · 41 linhas");
369387
} finally {
370388
await i18n.setLocale("en");
371389
}
Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,140 @@
1+
import { mkdir } from "node:fs/promises";
2+
import path from "node:path";
3+
import { chromium, type Browser, type Page } from "playwright";
4+
import { afterAll, beforeAll, describe, expect, it } from "vitest";
5+
import {
6+
canRunPlaywrightChromium,
7+
installMockGateway,
8+
resolvePlaywrightChromiumExecutablePath,
9+
startControlUiE2eServer,
10+
type ControlUiE2eServer,
11+
} from "../test-helpers/control-ui-e2e.ts";
12+
13+
const chromiumExecutablePath = resolvePlaywrightChromiumExecutablePath(chromium.executablePath());
14+
const chromiumAvailable = canRunPlaywrightChromium(chromiumExecutablePath);
15+
const allowMissingChromium = process.env.OPENCLAW_UI_E2E_ALLOW_MISSING_CHROMIUM === "1";
16+
const describeControlUiE2e = chromiumAvailable || !allowMissingChromium ? describe : describe.skip;
17+
const captureProof = process.env.OPENCLAW_CAPTURE_UI_PROOF === "1";
18+
const proofStage = process.env.OPENCLAW_JSON_CODE_PROOF_STAGE ?? "after";
19+
const artifactDir = path.resolve(process.cwd(), ".artifacts/control-ui-e2e/chat-json-code-block");
20+
21+
function fencedJson(lineCount: number): string {
22+
const values = Array.from({ length: lineCount - 2 }, (_, index) => ` ${index},`);
23+
values[values.length - 1] = values.at(-1)?.slice(0, -1) ?? "";
24+
return `\`\`\`json\n[\n${values.join("\n")}\n]\n\`\`\``;
25+
}
26+
27+
const shortJson = `\`\`\`json
28+
{
29+
"status": "ok",
30+
"items": [
31+
"alpha"
32+
]
33+
}
34+
\`\`\``;
35+
36+
async function setThemeMode(page: Page, mode: "dark" | "light"): Promise<void> {
37+
await page.emulateMedia({ colorScheme: mode });
38+
await page.evaluate((nextMode) => {
39+
const root = document.documentElement;
40+
root.dataset.themeMode = nextMode;
41+
root.dataset.themeResolved = nextMode;
42+
root.classList.toggle("wa-light", nextMode === "light");
43+
root.classList.toggle("wa-dark", nextMode === "dark");
44+
root.style.colorScheme = nextMode;
45+
}, mode);
46+
}
47+
48+
let browser: Browser;
49+
let server: ControlUiE2eServer;
50+
51+
describeControlUiE2e("Control UI JSON code blocks", () => {
52+
beforeAll(async () => {
53+
if (!chromiumAvailable) {
54+
throw new Error(`Playwright Chromium is unavailable at ${chromiumExecutablePath}`);
55+
}
56+
if (captureProof) {
57+
await mkdir(artifactDir, { recursive: true });
58+
}
59+
server = await startControlUiE2eServer(undefined, { source: true });
60+
browser = await chromium.launch({ executablePath: chromiumExecutablePath });
61+
});
62+
63+
afterAll(async () => {
64+
await browser?.close();
65+
await server?.close();
66+
});
67+
68+
it.each(["dark", "light"] as const)(
69+
"keeps short JSON visible and reserves one disclosure header for long JSON in %s mode",
70+
async (theme) => {
71+
const context = await browser.newContext({
72+
colorScheme: theme,
73+
locale: "en-US",
74+
serviceWorkers: "block",
75+
viewport: { height: 900, width: 1440 },
76+
});
77+
await context.grantPermissions(["clipboard-read", "clipboard-write"], {
78+
origin: new URL(server.baseUrl).origin,
79+
});
80+
const page = await context.newPage();
81+
await installMockGateway(page, {
82+
historyMessages: [
83+
{
84+
role: "user",
85+
content: [{ type: "text", text: "Show the full diagnostic payload." }],
86+
timestamp: Date.now(),
87+
__openclaw: { id: "user-json-long", seq: 1 },
88+
},
89+
{
90+
role: "assistant",
91+
content: [{ type: "text", text: fencedJson(41) }],
92+
timestamp: Date.now() + 1,
93+
__openclaw: { id: "assistant-json-long", seq: 2 },
94+
},
95+
{
96+
role: "user",
97+
content: [{ type: "text", text: "Return the deployment receipt as JSON." }],
98+
timestamp: Date.now() + 2,
99+
__openclaw: { id: "user-json-short", seq: 3 },
100+
},
101+
{
102+
role: "assistant",
103+
content: [{ type: "text", text: shortJson }],
104+
timestamp: Date.now() + 3,
105+
__openclaw: { id: "assistant-json-short", seq: 4 },
106+
},
107+
],
108+
});
109+
110+
try {
111+
await page.goto(`${server.baseUrl}chat`);
112+
await setThemeMode(page, theme);
113+
const shortBubble = page.locator('[data-entry-id="assistant-json-short"]');
114+
const longBubble = page.locator('[data-entry-id="assistant-json-long"]');
115+
await shortBubble.waitFor({ state: "visible" });
116+
if (captureProof) {
117+
await page.screenshot({
118+
animations: "disabled",
119+
path: path.join(artifactDir, `${proofStage}-${theme}.png`),
120+
});
121+
}
122+
123+
expect(await shortBubble.locator("details.json-collapse").count()).toBe(0);
124+
expect(await shortBubble.locator("pre code").isVisible()).toBe(true);
125+
126+
const details = longBubble.locator("details.json-collapse");
127+
const summary = details.locator("summary");
128+
expect(await summary.textContent()).toContain("JSON · 41 lines");
129+
expect(await summary.locator(".code-block-copy").count()).toBe(1);
130+
expect(await details.locator(".code-block-header").count()).toBe(1);
131+
await summary.click();
132+
await expect.poll(() => details.getAttribute("open")).toBe("");
133+
await summary.locator(".code-block-copy").click();
134+
await expect.poll(() => details.getAttribute("open")).toBe("");
135+
} finally {
136+
await context.close();
137+
}
138+
},
139+
);
140+
});

‎ui/src/styles/components.css‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2335,12 +2335,22 @@ openclaw-chat-session-rail {
23352335
}
23362336

23372337
.json-collapse summary {
2338+
display: list-item;
23382339
font-size: 12px;
23392340
color: var(--muted);
23402341
padding: 4px 8px;
2342+
border-radius: var(--radius-sm);
23412343
user-select: none;
23422344
}
23432345

2346+
.json-collapse summary .code-block-copy {
2347+
float: right;
2348+
}
2349+
2350+
.json-collapse[open] summary {
2351+
border-radius: var(--radius-sm) var(--radius-sm) 0 0;
2352+
}
2353+
23442354
.json-collapse summary:hover {
23452355
color: var(--text);
23462356
}

0 commit comments

Comments
 (0)