Skip to content

Commit cb34773

Browse files
committed
feat: render model-authored collapsible details in web UI and flatten for plain channels
1 parent 97d3d60 commit cb34773

15 files changed

Lines changed: 1003 additions & 45 deletions

‎extensions/telegram/src/outbound-adapter.sanitize.test.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -36,6 +36,7 @@ describe("telegramOutbound.sanitizeText", () => {
3636
accountId: "default",
3737
});
3838
expect(sanitized).not.toContain("<details>");
39+
expect(sanitized).toContain("**More**\n\nbody");
3940
expect(sanitized).toContain("• done");
4041
});
4142

@@ -62,5 +63,21 @@ describe("telegramOutbound.sanitizeText", () => {
6263
payload: { text: islandText },
6364
});
6465
expect(sanitized).not.toContain("<details>");
66+
expect(sanitized).toContain("**More**\n\nbody");
67+
});
68+
69+
it("advertises native details preservation only for rich accounts", () => {
70+
expect(
71+
telegramOutbound.preserveMarkdownDetails?.({
72+
cfg: { channels: { telegram: { richMessages: true } } } as never,
73+
accountId: "default",
74+
}),
75+
).toBe(true);
76+
expect(
77+
telegramOutbound.preserveMarkdownDetails?.({
78+
cfg: { channels: { telegram: {} } } as never,
79+
accountId: "default",
80+
}),
81+
).toBe(false);
6582
});
6683
});

‎extensions/telegram/src/outbound-adapter.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -413,6 +413,9 @@ export function createTelegramOutboundAdapter(
413413
chunkerMode: "markdown",
414414
extractMarkdownImages: true,
415415
textChunkLimit: TELEGRAM_TEXT_CHUNK_LIMIT,
416+
preserveMarkdownDetails: ({ cfg, accountId }) =>
417+
mergeTelegramAccountConfig(cfg, accountId ?? resolveDefaultTelegramAccountId(cfg))
418+
.richMessages === true,
416419
// Default Telegram delivery reparses this result as Markdown; use its bold
417420
// and strike delimiters. Rich accounts must keep the agent's HTML islands
418421
// (<details>, <tg-math-block>, checkbox lists) intact — the blocks emitter

‎src/channels/plugins/outbound.types.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -173,6 +173,8 @@ export type ChannelOutboundAdapter = {
173173
chunkedTextFormatting?: OutboundDeliveryFormattingOptions;
174174
/** Lift remote Markdown image syntax in text into outbound media attachments. */
175175
extractMarkdownImages?: boolean;
176+
/** Preserve model-authored Markdown details blocks for a native channel renderer. */
177+
preserveMarkdownDetails?: (params: { cfg: OpenClawConfig; accountId?: string | null }) => boolean;
176178
textChunkLimit?: number;
177179
/**
178180
* Reserve the exact provider id used by the next single-message send.

‎src/infra/outbound/deliver-channel.ts‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -249,6 +249,11 @@ function createPluginHandler(
249249
chunkerMode,
250250
chunkedTextFormatting: outbound?.chunkedTextFormatting,
251251
textChunkLimit: outbound?.textChunkLimit,
252+
preserveMarkdownDetails:
253+
outbound?.preserveMarkdownDetails?.({
254+
cfg: params.cfg,
255+
accountId: params.accountId,
256+
}) === true,
252257
supportsMedia: Boolean(messageMedia ?? sendMedia),
253258
sanitizeText: outbound?.sanitizeText
254259
? (payload) =>

‎src/infra/outbound/deliver-contracts.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ export type ChannelHandler = {
6161
chunkerMode?: "text" | "markdown";
6262
chunkedTextFormatting?: OutboundDeliveryFormattingOptions;
6363
textChunkLimit?: number;
64+
preserveMarkdownDetails?: boolean;
6465
supportsMedia: boolean;
6566
sanitizeText?: (payload: ReplyPayload) => string;
6667
normalizePayload?: (payload: ReplyPayload) => ReplyPayload | null;

‎src/infra/outbound/deliver-payload.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,6 +23,7 @@ import type {
2323
NormalizedPayloadForChannelDelivery,
2424
} from "./deliver-contracts.js";
2525
import type { OutboundDeliveryResult, OutboundPayloadDeliveryKind } from "./deliver-types.js";
26+
import { flattenMarkdownDetails } from "./markdown-details.js";
2627
import type { DeliveryMirror } from "./mirror.js";
2728
import {
2829
summarizeOutboundPayloadForTransport,
@@ -125,6 +126,12 @@ export function normalizePayloadsForChannelDelivery(
125126
const normalizedPayloads: NormalizedPayloadForChannelDelivery[] = [];
126127
for (const entry of plan) {
127128
let sanitizedPayload = stripInternalRuntimeScaffoldingFromPayload(entry.payload);
129+
if (!handler.preserveMarkdownDetails && sanitizedPayload.text) {
130+
sanitizedPayload = {
131+
...sanitizedPayload,
132+
text: flattenMarkdownDetails(sanitizedPayload.text),
133+
};
134+
}
128135
if (handler.sanitizeText && sanitizedPayload.text) {
129136
if (!handler.shouldSkipPlainTextSanitization?.(sanitizedPayload)) {
130137
sanitizedPayload = {
Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
import { describe, expect, it } from "vitest";
2+
import { flattenMarkdownDetails } from "./markdown-details.js";
3+
4+
describe("flattenMarkdownDetails", () => {
5+
it("flattens details blocks into portable markdown", () => {
6+
expect(
7+
flattenMarkdownDetails(
8+
"<details open><summary>Why this works</summary>**Bold** body\n\n- one\n- two</details>",
9+
),
10+
).toBe("**Why this works**\n\n**Bold** body\n\n- one\n- two");
11+
});
12+
13+
it("uses the default label when summary is missing or empty", () => {
14+
expect(flattenMarkdownDetails("<details>body</details>")).toBe("**Details**\n\nbody");
15+
expect(flattenMarkdownDetails("<details><summary> </summary>body</details>")).toBe(
16+
"**Details**\n\nbody",
17+
);
18+
});
19+
20+
it("flattens nested details recursively", () => {
21+
expect(
22+
flattenMarkdownDetails(
23+
"<details><summary>Outer</summary>before\n\n<details><summary>Inner</summary>deep</details>\n\nafter</details>",
24+
),
25+
).toBe("**Outer**\n\nbefore\n\n**Inner**\n\ndeep\n\nafter");
26+
});
27+
28+
it("preserves indentation in the first body block", () => {
29+
expect(
30+
flattenMarkdownDetails("<details><summary>Example</summary>\n const x = 1;\n</details>"),
31+
).toBe("**Example**\n\n const x = 1;");
32+
});
33+
34+
it("preserves block boundaries around flattened details", () => {
35+
expect(flattenMarkdownDetails("before<details>inside</details>after")).toBe(
36+
"before\n\n**Details**\n\ninside\n\nafter",
37+
);
38+
expect(flattenMarkdownDetails("<details>inside</details>\nafter")).toBe(
39+
"**Details**\n\ninside\n\nafter",
40+
);
41+
});
42+
43+
it("preserves list and blockquote containers around flattened details", () => {
44+
expect(flattenMarkdownDetails("- <details><summary>A</summary>body</details>")).toBe(
45+
"- **A**\n\n body",
46+
);
47+
expect(flattenMarkdownDetails("> <details><summary>A</summary>body</details>")).toBe(
48+
"> **A**\n>\n> body",
49+
);
50+
});
51+
52+
it("keeps a two-space-indented details block in its list item", () => {
53+
expect(flattenMarkdownDetails(" - <details><summary>A</summary>body</details>")).toBe(
54+
" - **A**\n\n body",
55+
);
56+
expect(flattenMarkdownDetails("> - <details><summary>A</summary>body</details>")).toBe(
57+
"> - **A**\n>\n> body",
58+
);
59+
});
60+
61+
it("does not duplicate multiline container prefixes", () => {
62+
expect(
63+
flattenMarkdownDetails("> <details>\n> <summary>A</summary>\n>\n> body\n> </details>"),
64+
).toBe("> **A**\n>\n> body");
65+
expect(
66+
flattenMarkdownDetails("10. <details>\n <summary>A</summary>\n\n body\n </details>"),
67+
).toBe("10. **A**\n\n body");
68+
});
69+
70+
it("bounds rendering of deeply nested details", () => {
71+
let markdown = "deep body";
72+
for (let index = 0; index < 128; index += 1) {
73+
markdown = `<details><summary>Level ${index}</summary>${markdown}</details>`;
74+
}
75+
76+
const flattened = flattenMarkdownDetails(markdown);
77+
78+
expect(flattened).toContain("deep body");
79+
expect(flattened).not.toContain("<details>");
80+
});
81+
82+
it("flattens unterminated details without leaking structural tags", () => {
83+
expect(flattenMarkdownDetails("<details><summary>More</summary>partial")).toBe(
84+
"**More**\n\npartial",
85+
);
86+
});
87+
88+
it("closes an unterminated summary with its containing details", () => {
89+
expect(flattenMarkdownDetails("<details><summary>More</details>after")).toBe(
90+
"**More**\n\nafter",
91+
);
92+
});
93+
94+
it("leaves literal details examples inside code unchanged", () => {
95+
const markdown = "`<details>inline</details>`\n\n```html\n<details>block</details>\n```";
96+
expect(flattenMarkdownDetails(markdown)).toBe(markdown);
97+
});
98+
99+
it("does not flatten custom elements with details-like names", () => {
100+
const markdown = "<details-widget>body</details-widget>";
101+
expect(flattenMarkdownDetails(markdown)).toBe(markdown);
102+
});
103+
});
Lines changed: 191 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,191 @@
1+
import { findCodeRegions, isInsideCode } from "../../shared/text/code-regions.js";
2+
3+
const MAX_DETAILS_RENDER_DEPTH = 32;
4+
5+
type DetailsNode =
6+
| string
7+
| {
8+
type: "details" | "summary";
9+
children: DetailsNode[];
10+
};
11+
12+
const DETAILS_TAG_RE = /<\s*(\/?)\s*(details|summary)(?=\s|>)[^>]*>/gi;
13+
14+
function appendNode(target: DetailsNode[], node: DetailsNode): void {
15+
const previous = target.at(-1);
16+
if (typeof previous === "string" && typeof node === "string") {
17+
target[target.length - 1] = previous + node;
18+
return;
19+
}
20+
target.push(node);
21+
}
22+
23+
function trimMarkdownBlankLines(value: string): string {
24+
return value.replace(/^(?:[ \t]*\r?\n)+/, "").replace(/(?:\r?\n[ \t]*)+$/, "");
25+
}
26+
27+
type MarkdownContainerLayout = { blankPrefix: string; continuationPrefix: string };
28+
29+
function resolveMarkdownContainerLayout(rendered: string): MarkdownContainerLayout | null {
30+
const currentLine = rendered.slice(rendered.lastIndexOf("\n") + 1);
31+
if (/^[ \t]+$/.test(currentLine)) {
32+
return { blankPrefix: "", continuationPrefix: currentLine };
33+
}
34+
const quotePrefix = /^[ \t]{0,3}(?:>\s?)+/.exec(currentLine)?.[0] ?? "";
35+
const remainder = currentLine.slice(quotePrefix.length);
36+
if (quotePrefix && !remainder) {
37+
return { blankPrefix: quotePrefix.trimEnd(), continuationPrefix: quotePrefix };
38+
}
39+
const listMarker = /^ {0,3}(?:[-+*]|\d{1,9}[.)])[ \t]+$/.exec(remainder)?.[0];
40+
if (listMarker) {
41+
return {
42+
blankPrefix: quotePrefix.trimEnd(),
43+
continuationPrefix: quotePrefix + " ".repeat(listMarker.length),
44+
};
45+
}
46+
return null;
47+
}
48+
49+
function renderInMarkdownContainer(block: string, layout: MarkdownContainerLayout): string {
50+
return block
51+
.split("\n")
52+
.map((line, index) => {
53+
if (index === 0) {
54+
return line;
55+
}
56+
return line ? layout.continuationPrefix + line : layout.blankPrefix;
57+
})
58+
.join("\n");
59+
}
60+
61+
function stripMarkdownContainerLayout(block: string, layout: MarkdownContainerLayout): string {
62+
return block
63+
.split("\n")
64+
.map((line) => {
65+
if (line === layout.blankPrefix) {
66+
return "";
67+
}
68+
return line.startsWith(layout.continuationPrefix)
69+
? line.slice(layout.continuationPrefix.length)
70+
: line;
71+
})
72+
.join("\n");
73+
}
74+
75+
function collectDetailsText(nodes: readonly DetailsNode[]): string {
76+
let text = "";
77+
const pending = [...nodes].toReversed();
78+
while (pending.length > 0) {
79+
const node = pending.pop();
80+
if (typeof node === "string") {
81+
text += node;
82+
} else if (node) {
83+
pending.push(...node.children.toReversed());
84+
}
85+
}
86+
return text;
87+
}
88+
89+
function renderDetailsNodes(nodes: readonly DetailsNode[], depth = 0): string {
90+
let rendered = "";
91+
for (const [index, node] of nodes.entries()) {
92+
if (typeof node === "string") {
93+
rendered += node;
94+
continue;
95+
}
96+
if (node.type === "summary") {
97+
rendered +=
98+
depth >= MAX_DETAILS_RENDER_DEPTH
99+
? collectDetailsText(node.children)
100+
: renderDetailsNodes(node.children, depth + 1);
101+
continue;
102+
}
103+
104+
const summary = node.children.find(
105+
(child): child is Exclude<DetailsNode, string> =>
106+
typeof child !== "string" && child.type === "summary",
107+
);
108+
const bodyNodes = node.children.filter((child) => child !== summary);
109+
const container = resolveMarkdownContainerLayout(rendered);
110+
const renderedBody =
111+
depth >= MAX_DETAILS_RENDER_DEPTH
112+
? collectDetailsText(bodyNodes)
113+
: renderDetailsNodes(bodyNodes, depth + 1);
114+
const body = trimMarkdownBlankLines(
115+
container ? stripMarkdownContainerLayout(renderedBody, container) : renderedBody,
116+
);
117+
const label = summary
118+
? (depth >= MAX_DETAILS_RENDER_DEPTH
119+
? collectDetailsText(summary.children)
120+
: renderDetailsNodes(summary.children, depth + 1)
121+
).trim()
122+
: "Details";
123+
const heading = `**${label || "Details"}**`;
124+
const block = body ? `${heading}\n\n${body}` : heading;
125+
if (container) {
126+
rendered += renderInMarkdownContainer(block, container);
127+
} else {
128+
if (rendered && !rendered.endsWith("\n\n")) {
129+
rendered += rendered.endsWith("\n") ? "\n" : "\n\n";
130+
}
131+
rendered += block;
132+
}
133+
const next = nodes[index + 1];
134+
if (
135+
next !== undefined &&
136+
next !== "" &&
137+
(typeof next !== "string" || !next.startsWith("\n\n"))
138+
) {
139+
rendered += typeof next === "string" && next.startsWith("\n") ? "\n" : "\n\n";
140+
}
141+
}
142+
return rendered;
143+
}
144+
145+
/** Flattens model-authored details blocks for transports without native disclosure widgets. */
146+
export function flattenMarkdownDetails(text: string): string {
147+
if (!/<\s*\/?\s*(?:details|summary)(?=\s|>)/i.test(text)) {
148+
return text;
149+
}
150+
151+
const root: DetailsNode[] = [];
152+
const stack: Array<Extract<DetailsNode, { type: "details" | "summary" }>> = [];
153+
// Accepted tradeoff: four-space-indented literal tags may flatten as details.
154+
// Fenced and inline code stay protected; models normally author code fences.
155+
const codeRegions = findCodeRegions(text);
156+
let cursor = 0;
157+
for (const match of text.matchAll(DETAILS_TAG_RE)) {
158+
const start = match.index ?? 0;
159+
if (isInsideCode(start, codeRegions)) {
160+
continue;
161+
}
162+
163+
const target = stack.at(-1)?.children ?? root;
164+
appendNode(target, text.slice(cursor, start));
165+
cursor = start + match[0].length;
166+
167+
const type = match[2]?.toLowerCase();
168+
if (type !== "details" && type !== "summary") {
169+
continue;
170+
}
171+
if (match[1]) {
172+
if (
173+
type === "details" &&
174+
stack.at(-1)?.type === "summary" &&
175+
stack.at(-2)?.type === "details"
176+
) {
177+
stack.pop();
178+
}
179+
if (stack.at(-1)?.type === type) {
180+
stack.pop();
181+
}
182+
continue;
183+
}
184+
185+
const node = { type, children: [] } satisfies Exclude<DetailsNode, string>;
186+
appendNode(target, node);
187+
stack.push(node);
188+
}
189+
appendNode(stack.at(-1)?.children ?? root, text.slice(cursor));
190+
return renderDetailsNodes(root);
191+
}

‎src/infra/outbound/sanitize-text.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { flattenMarkdownDetails } from "./markdown-details.js";
12
// Plain-text sanitization strips internal runtime scaffolding and converts a
23
// conservative subset of model-produced HTML into channel-friendly text.
34
import { stripInternalRuntimeScaffolding } from "./protocol-scaffolding.js";
@@ -32,7 +33,7 @@ function stripRemainingHtmlTags(text: string): string {
3233
export function sanitizeForPlainText(text: string, options: { style?: "markdown" } = {}): string {
3334
const boldMarker = options.style === "markdown" ? "**" : "*";
3435
const strikeMarker = options.style === "markdown" ? "~~" : "~";
35-
const converted = stripInternalRuntimeScaffolding(text)
36+
const converted = flattenMarkdownDetails(stripInternalRuntimeScaffolding(text))
3637
// Preserve angle-bracket autolinks as plain URLs before tag stripping.
3738
.replace(/<((?:https?:\/\/|mailto:)[^<>\s]+)>/gi, "$1")
3839
// Normalize attributes once; conversions below only need exact bare tag names.

0 commit comments

Comments
 (0)