Skip to content

Open-source AI browser agent for Chrome and Firefox (monorepo) 🧠

Fix nested Markdown code fence rendering

Emre Sokullu9d626b052d34
diff --git a/package.json b/package.json
index 25511df7e..062324ebf 100644
--- a/package.json
+++ b/package.json
@@ -5,8 +5,9 @@
"private": true,
"type": "module",
"scripts": {
- "test": "npm run test:systemone && npm run test:systemone:fast && node --test test/browser-dialogs.mjs && npm run test:firefox-bidi && npm run test:runtime-lifecycle && npm run test:provider-limits && npm run test:accessibility-tree-benchmark && npm run test:toolbar-guard && npm run test:pdf-read && npm run test:pdf-selection && npm run test:social-contract && npm run test:safesocial && npm run test:build-unpacked && npm run test:attachment-drop && node test/run.js && node test/selection-scope-restoration.mjs && node scripts/benchmark-offline-relevance.mjs && npm run test:security",
+ "test": "npm run test:markdown && npm run test:systemone && npm run test:systemone:fast && node --test test/browser-dialogs.mjs && npm run test:firefox-bidi && npm run test:runtime-lifecycle && npm run test:provider-limits && npm run test:accessibility-tree-benchmark && npm run test:toolbar-guard && npm run test:pdf-read && npm run test:pdf-selection && npm run test:social-contract && npm run test:safesocial && npm run test:build-unpacked && npm run test:attachment-drop && node test/run.js && node test/selection-scope-restoration.mjs && node scripts/benchmark-offline-relevance.mjs && npm run test:security",
"test:provider-limits": "node test/provider-model-limits.mjs",
+ "test:markdown": "node --test test/markdown-render.mjs",
"test:accessibility-tree-benchmark": "node --test test/llm/lib/accessibility-tree-formats.test.mjs && node test/llm/accessibility-tree-benchmark.mjs --no-exact-tokenizer --check",
"test:attachment-drop": "node test/attachment-drop.mjs",
"test:security": "node test/security/injection-corpus.mjs",
diff --git a/src/chrome/src/ui/history-text.js b/src/chrome/src/ui/history-text.js
index 074daadec..b80a24369 100644
--- a/src/chrome/src/ui/history-text.js
+++ b/src/chrome/src/ui/history-text.js
@@ -125,10 +125,17 @@ export function historyTextFromElement(root, { markdown = true } = {}) {
if (markdown && tagName === 'PRE') {
const language = String(node.parentElement?.querySelector?.('.code-lang')?.textContent || '').trim();
ensureBreak();
- output += `\`\`\`${language}\n`;
+ const beforeCode = output;
+ output = '';
for (const child of Array.from(node.childNodes || [])) visit(child, false, true);
ensureBreak();
- output += '```';
+ const code = output;
+ // History must not reintroduce ambiguous fences around a Markdown
+ // document (or any code sample containing literal backtick runs).
+ let fenceLength = 3;
+ for (const match of code.matchAll(/`{3,}/g)) fenceLength = Math.max(fenceLength, match[0].length + 1);
+ const fence = '`'.repeat(fenceLength);
+ output = `${beforeCode}${fence}${language}\n${code}${fence}`;
return;
}
if (markdown && tagName === 'CODE' && !inPre) {
diff --git a/src/chrome/src/ui/markdown-render.js b/src/chrome/src/ui/markdown-render.js
index f8aa7a878..f1d55e26f 100644
--- a/src/chrome/src/ui/markdown-render.js
+++ b/src/chrome/src/ui/markdown-render.js
@@ -57,6 +57,55 @@ export function codeFenceLanguage(infoString) {
return String(infoString || '').trim().split(/\s+/, 1)[0] || '';
}
+/** Replace whole fenced blocks, including an unfinished block during streaming. */
+export function replaceMarkdownCodeFences(value, renderBlock) {
+ const source = String(value ?? '');
+ // Accept fences at the document root and inside the simple containers this
+ // renderer preserves (lists and blockquotes). The old unanchored matcher
+ // accepted these forms, while a root-only matcher mistakes their closer for
+ // a new opener and consumes the rest of the message as code.
+ const fenceLines = /^(?:(?: {0,3}>[ \t]?)*(?:(?:[ \t]*(?:[-+*]|\d+[.)])[ \t]+)?)[ \t]{0,3})(`{3,}|~{3,})([^\r\n]*)(?:\r?\n|$)/gm;
+ const output = [];
+ let cursor = 0;
+ let block = null;
+ const stack = [];
+
+ for (const match of source.matchAll(fenceLines)) {
+ const [, fence, info] = match;
+ const validOpening = fence[0] !== '`' || !info.includes('`');
+ const markdown = /^(?:md|markdown)$/i.test(codeFenceLanguage(info));
+ if (!block) {
+ if (!validOpening) continue;
+ output.push(source.slice(cursor, match.index));
+ block = { info, start: match.index + match[0].length };
+ stack.push({ fence, markdown });
+ continue;
+ }
+
+ const active = stack[stack.length - 1];
+ // A closing fence occupies its own line, has no info string, and is at
+ // least as long as its opener. Backticks inside source code are literal.
+ if (!info.trim() && fence[0] === active.fence[0] && fence.length >= active.fence.length) {
+ stack.pop();
+ if (!stack.length) {
+ output.push(renderBlock(block.info, source.slice(block.start, match.index)));
+ // Leave the closing line's newline for the surrounding Markdown.
+ cursor = match.index + match[0].replace(/\r?\n$/, '').length;
+ block = null;
+ }
+ } else if (active.markdown && validOpening && info.trim() && fence === active.fence) {
+ // Models sometimes wrap a README in ```markdown and reuse ```lang
+ // inside it. Recover only this named Markdown nesting; ordinary code
+ // and correctly longer outer fences retain their literal contents.
+ stack.push({ fence, markdown });
+ }
+ }
+
+ if (block) output.push(renderBlock(block.info, source.slice(block.start)));
+ else output.push(source.slice(cursor));
+ return output.join('');
+}
+
function tokenSpan(type, value) {
const escaped = escapeCodeHtml(value);
return type ? `<span class="syntax-${type}">${escaped}</span>` : escaped;
diff --git a/src/chrome/src/ui/sidepanel.js b/src/chrome/src/ui/sidepanel.js
index bc6e8126d..5964754db 100644
--- a/src/chrome/src/ui/sidepanel.js
+++ b/src/chrome/src/ui/sidepanel.js
@@ -7,7 +7,7 @@
import { t, getLocale, setLocale, LANGUAGES, applyDOMTranslations, translationsForKey } from './i18n.js';
import { CAPABILITY_LABEL } from '../agent/permission-gate.js';
import { sanitizeMarkdownLinks } from './markdown-link.js';
-import { codeFenceLanguage, highlightCode, renderMarkdownHeadings, renderMarkdownTables } from './markdown-render.js';
+import { codeFenceLanguage, highlightCode, renderMarkdownHeadings, renderMarkdownTables, replaceMarkdownCodeFences } from './markdown-render.js';
import { applyMode, loadMode, watch } from './theme.js';
import {
UI_SCALE_LEVELS,
@@ -12829,7 +12829,7 @@ function formatMarkdown(text, options = {}) {
// 1. Extract fenced code blocks BEFORE escaping HTML
const codeBlocks = [];
- text = text.replace(/```[ \t]*([^`\r\n]*)\r?\n([\s\S]*?)```/g, (_match, info, code) => {
+ text = replaceMarkdownCodeFences(text, (info, code) => {
const lang = codeFenceLanguage(info);
const id = `__CODEBLOCK_${codeBlocks.length}__`;
codeBlocks.push({ lang: lang || '', code });
diff --git a/src/chrome/src/ui/skill-markdown.js b/src/chrome/src/ui/skill-markdown.js
index 5e65cb0cf..2dd0f4ac6 100644
--- a/src/chrome/src/ui/skill-markdown.js
+++ b/src/chrome/src/ui/skill-markdown.js
@@ -5,7 +5,7 @@
import { escapeHtml } from './utils.js';
import { sanitizeMarkdownLinks } from './markdown-link.js';
-import { renderMarkdownHeadings, renderMarkdownTables } from './markdown-render.js';
+import { renderMarkdownHeadings, renderMarkdownTables, replaceMarkdownCodeFences } from './markdown-render.js';
function renderEmphasis(text) {
return text
@@ -38,7 +38,7 @@ function renderInlineMarkdown(value) {
export function renderSkillMarkdown(content) {
let text = String(content || '');
const codeBlocks = [];
- text = text.replace(/```[ \t]*([^`\r\n]*)\r?\n([\s\S]*?)```/g, (_match, _info, code) => {
+ text = replaceMarkdownCodeFences(text, (_info, code) => {
const placeholder = `__SKILL_CODE_BLOCK_${codeBlocks.length}__`;
codeBlocks.push(code);
return placeholder;
diff --git a/src/firefox/src/ui/history-text.js b/src/firefox/src/ui/history-text.js
index 074daadec..b80a24369 100644
--- a/src/firefox/src/ui/history-text.js
+++ b/src/firefox/src/ui/history-text.js
@@ -125,10 +125,17 @@ export function historyTextFromElement(root, { markdown = true } = {}) {
if (markdown && tagName === 'PRE') {
const language = String(node.parentElement?.querySelector?.('.code-lang')?.textContent || '').trim();
ensureBreak();
- output += `\`\`\`${language}\n`;
+ const beforeCode = output;
+ output = '';
for (const child of Array.from(node.childNodes || [])) visit(child, false, true);
ensureBreak();
- output += '```';
+ const code = output;
+ // History must not reintroduce ambiguous fences around a Markdown
+ // document (or any code sample containing literal backtick runs).
+ let fenceLength = 3;
+ for (const match of code.matchAll(/`{3,}/g)) fenceLength = Math.max(fenceLength, match[0].length + 1);
+ const fence = '`'.repeat(fenceLength);
+ output = `${beforeCode}${fence}${language}\n${code}${fence}`;
return;
}
if (markdown && tagName === 'CODE' && !inPre) {
diff --git a/src/firefox/src/ui/markdown-render.js b/src/firefox/src/ui/markdown-render.js
index f8aa7a878..f1d55e26f 100644
--- a/src/firefox/src/ui/markdown-render.js
+++ b/src/firefox/src/ui/markdown-render.js
@@ -57,6 +57,55 @@ export function codeFenceLanguage(infoString) {
return String(infoString || '').trim().split(/\s+/, 1)[0] || '';
}
+/** Replace whole fenced blocks, including an unfinished block during streaming. */
+export function replaceMarkdownCodeFences(value, renderBlock) {
+ const source = String(value ?? '');
+ // Accept fences at the document root and inside the simple containers this
+ // renderer preserves (lists and blockquotes). The old unanchored matcher
+ // accepted these forms, while a root-only matcher mistakes their closer for
+ // a new opener and consumes the rest of the message as code.
+ const fenceLines = /^(?:(?: {0,3}>[ \t]?)*(?:(?:[ \t]*(?:[-+*]|\d+[.)])[ \t]+)?)[ \t]{0,3})(`{3,}|~{3,})([^\r\n]*)(?:\r?\n|$)/gm;
+ const output = [];
+ let cursor = 0;
+ let block = null;
+ const stack = [];
+
+ for (const match of source.matchAll(fenceLines)) {
+ const [, fence, info] = match;
+ const validOpening = fence[0] !== '`' || !info.includes('`');
+ const markdown = /^(?:md|markdown)$/i.test(codeFenceLanguage(info));
+ if (!block) {
+ if (!validOpening) continue;
+ output.push(source.slice(cursor, match.index));
+ block = { info, start: match.index + match[0].length };
+ stack.push({ fence, markdown });
+ continue;
+ }
+
+ const active = stack[stack.length - 1];
+ // A closing fence occupies its own line, has no info string, and is at
+ // least as long as its opener. Backticks inside source code are literal.
+ if (!info.trim() && fence[0] === active.fence[0] && fence.length >= active.fence.length) {
+ stack.pop();
+ if (!stack.length) {
+ output.push(renderBlock(block.info, source.slice(block.start, match.index)));
+ // Leave the closing line's newline for the surrounding Markdown.
+ cursor = match.index + match[0].replace(/\r?\n$/, '').length;
+ block = null;
+ }
+ } else if (active.markdown && validOpening && info.trim() && fence === active.fence) {
+ // Models sometimes wrap a README in ```markdown and reuse ```lang
+ // inside it. Recover only this named Markdown nesting; ordinary code
+ // and correctly longer outer fences retain their literal contents.
+ stack.push({ fence, markdown });
+ }
+ }
+
+ if (block) output.push(renderBlock(block.info, source.slice(block.start)));
+ else output.push(source.slice(cursor));
+ return output.join('');
+}
+
function tokenSpan(type, value) {
const escaped = escapeCodeHtml(value);
return type ? `<span class="syntax-${type}">${escaped}</span>` : escaped;
diff --git a/src/firefox/src/ui/sidepanel.js b/src/firefox/src/ui/sidepanel.js
index 12c8ec3e6..c6ed35f98 100644
--- a/src/firefox/src/ui/sidepanel.js
+++ b/src/firefox/src/ui/sidepanel.js
@@ -7,7 +7,7 @@
import { t, getLocale, setLocale, LANGUAGES, applyDOMTranslations, translationsForKey } from './i18n.js';
import { CAPABILITY_LABEL } from '../agent/permission-gate.js';
import { sanitizeMarkdownLinks } from './markdown-link.js';
-import { codeFenceLanguage, highlightCode, renderMarkdownHeadings, renderMarkdownTables } from './markdown-render.js';
+import { codeFenceLanguage, highlightCode, renderMarkdownHeadings, renderMarkdownTables, replaceMarkdownCodeFences } from './markdown-render.js';
import { applyMode, loadMode, watch } from './theme.js';
import {
UI_SCALE_LEVELS,
@@ -12416,7 +12416,7 @@ function formatMarkdown(text, options = {}) {
// 1. Extract fenced code blocks BEFORE escaping HTML
const codeBlocks = [];
- text = text.replace(/```[ \t]*([^`\r\n]*)\r?\n([\s\S]*?)```/g, (_match, info, code) => {
+ text = replaceMarkdownCodeFences(text, (info, code) => {
const lang = codeFenceLanguage(info);
const id = `__CODEBLOCK_${codeBlocks.length}__`;
codeBlocks.push({ lang: lang || '', code });
diff --git a/src/firefox/src/ui/skill-markdown.js b/src/firefox/src/ui/skill-markdown.js
index 5e65cb0cf..2dd0f4ac6 100644
--- a/src/firefox/src/ui/skill-markdown.js
+++ b/src/firefox/src/ui/skill-markdown.js
@@ -5,7 +5,7 @@
import { escapeHtml } from './utils.js';
import { sanitizeMarkdownLinks } from './markdown-link.js';
-import { renderMarkdownHeadings, renderMarkdownTables } from './markdown-render.js';
+import { renderMarkdownHeadings, renderMarkdownTables, replaceMarkdownCodeFences } from './markdown-render.js';
function renderEmphasis(text) {
return text
@@ -38,7 +38,7 @@ function renderInlineMarkdown(value) {
export function renderSkillMarkdown(content) {
let text = String(content || '');
const codeBlocks = [];
- text = text.replace(/```[ \t]*([^`\r\n]*)\r?\n([\s\S]*?)```/g, (_match, _info, code) => {
+ text = replaceMarkdownCodeFences(text, (_info, code) => {
const placeholder = `__SKILL_CODE_BLOCK_${codeBlocks.length}__`;
codeBlocks.push(code);
return placeholder;
diff --git a/test/markdown-render.mjs b/test/markdown-render.mjs
new file mode 100644
index 000000000..bf366ecfa
--- /dev/null
+++ b/test/markdown-render.mjs
@@ -0,0 +1,197 @@
+import assert from 'node:assert/strict';
+import fs from 'node:fs';
+import vm from 'node:vm';
+import { test } from 'node:test';
+
+const readUi = (build, name) => fs.readFileSync(new URL(`../src/${build}/src/ui/${name}`, import.meta.url), 'utf8');
+const panelFormatter = (build) => {
+ const source = readUi(build, 'sidepanel.js');
+ const start = source.indexOf('function formatMarkdown(');
+ assert.ok(start >= 0);
+ return source.slice(start, source.indexOf('\n}', start) + 2);
+};
+// Reduced reproduction of a model-authored README with same-length nested
+// fences. Keep user traces and their private page content out of the fixture.
+const readme = [
+ '# Example README', '', '## Role',
+ '```text', 'User request', ' |', ' v', 'Browser tools', '```', '',
+ '## Usage', '```javascript', 'const marker = "```";',
+ 'const html = "<script>alert(1)</script>";', '```', '',
+ '### Parser notes', '```bash', 'node --test parser.test.mjs', '```', '',
+ '## License', 'See `LICENSE`.', '',
+].join('\n');
+const draft = `Here is the draft:\n\n\`\`\`markdown\n${readme}\`\`\`\n\n## Next steps\nReview it.`;
+const preContents = (html) => [...html.matchAll(/<pre><code>([\s\S]*?)<\/code><\/pre>/g)].map(match => match[1]);
+
+for (const build of ['chrome', 'firefox']) {
+ const helpers = await import(`../src/${build}/src/ui/markdown-render.js`);
+ const { sanitizeMarkdownLinks } = await import(`../src/${build}/src/ui/markdown-link.js`);
+ const { escapeHtml } = await import(`../src/${build}/src/ui/utils.js`);
+ const { renderSkillMarkdown } = await import(`../src/${build}/src/ui/skill-markdown.js`);
+ const { historyTextFromElement } = await import(`../src/${build}/src/ui/history-text.js`);
+ const formatMarkdown = vm.runInNewContext(`(${panelFormatter(build)})`, {
+ ...helpers, sanitizeMarkdownLinks, escapeHtml, t: key => key,
+ scheduleMathRender() {}, setTimeout() {},
+ });
+
+ test(`${build}: nested README remains one complete, copyable Markdown block`, () => {
+ for (const language of ['markdown', 'md', 'MARKDOWN']) {
+ const source = draft.replace('```markdown', `\`\`\`${language}`);
+ for (const enhance of [true, false]) {
+ const html = formatMarkdown(source, { enhance });
+ assert.deepEqual(preContents(html), [helpers.escapeCodeHtml(readme)]);
+ assert.equal((html.match(/class="code-copy-btn"/g) || []).length, enhance ? 1 : 0);
+ assert.match(html, /<h2>Next steps<\/h2>Review it\./);
+ assert.doesNotMatch(html, /<script>|<h[1-6]>Role|<br>text<br>|<br>bash<br>/);
+ }
+ assert.deepEqual(preContents(renderSkillMarkdown(source)), [escapeHtml(readme)]);
+ }
+ });
+
+ test(`${build}: fence length, marker and whole-line closers protect literal code`, () => {
+ const cases = [
+ ['````markdown', '```js\nconst x = 1;\n```\n', '````'],
+ ['~~~~text', '~~~\n```\n~~~~ trailing text\n', '~~~~~'],
+ ['```javascript title="sample.js"', 'const s = "```";\n~~~\n``\n``` trailing text\n', '```'],
+ [' ```text', 'literal **bold** and [link](javascript:alert(1))\n', ' ``` '],
+ ['```text', '````js\n## Literal heading\n', '```'],
+ ['~~~markdown', '~~~bash\necho ok\n~~~\n## Still inside\n', '~~~'],
+ ];
+ for (const [open, code, close] of cases) {
+ for (const newline of ['\n', '\r\n']) {
+ const source = `${open}\n${code}${close}\n## Outside`.replaceAll('\n', newline);
+ const blocks = [];
+ const remaining = helpers.replaceMarkdownCodeFences(source, (info, value) => {
+ blocks.push({ info: info.trim(), code: value });
+ return 'BLOCK';
+ });
+ assert.deepEqual(blocks, [{ info: open.trim().replace(/^[`~]+/, ''), code: code.replaceAll('\n', newline) }]);
+ assert.equal(remaining, `BLOCK${newline}## Outside`);
+ assert.match(formatMarkdown(source), /<h2>Outside<\/h2>/);
+ }
+ }
+ });
+
+ test(`${build}: streamed open fences keep headings, HTML and nested examples literal`, () => {
+ for (const content of [readme, '## Heading\n<img src=x onerror=alert(1)>\n', '']) {
+ const source = `\`\`\`markdown\n${content}`;
+ const html = formatMarkdown(source, { enhance: false });
+ assert.deepEqual(preContents(html), [escapeHtml(content)]);
+ assert.deepEqual(preContents(renderSkillMarkdown(source)), [escapeHtml(content)]);
+ assert.doesNotMatch(html, /<h[1-6]>|<img |code-copy-btn/);
+ }
+ const start = '```markdown\n';
+ for (let length = start.length; length <= start.length + readme.length; length += 1) {
+ const prefix = (start + readme).slice(0, length);
+ const blocks = preContents(formatMarkdown(prefix, { enhance: false }));
+ assert.equal(blocks.length, 1, `stream prefix ${length} split the document`);
+ }
+ });
+
+ test(`${build}: independent code blocks retain their surrounding Markdown`, () => {
+ const source = '## Start\n```js\nconst x = 1;\n```\n**Between**\n~~~bash\necho ok\n~~~\n## End';
+ const html = formatMarkdown(source);
+ assert.equal(preContents(html).length, 2);
+ assert.match(html, /syntax-keyword/);
+ assert.match(html, /<strong>Between<\/strong>/);
+ assert.match(html, /<h2>End<\/h2>/);
+ assert.match(renderSkillMarkdown(source), /<strong>Between<\/strong>/);
+ const prose = 'Use ``` inline; this is not a block.\n ```js\nIndented example.';
+ assert.equal(helpers.replaceMarkdownCodeFences(prose, () => 'BLOCK'), prose);
+ });
+
+ test(`${build}: fences inside list and quote containers do not consume following prose`, () => {
+ const cases = [
+ [
+ 'numbered list',
+ '1. ```python\nvalue = "**literal**"\n```\n\n2. Start the server.',
+ /2\. Start the server\./,
+ ],
+ [
+ 'list marker',
+ '- ```python\n value = "**literal**"\n ```\n\n## Next steps\nCheck the result.',
+ /<h2>Next steps<\/h2>Check the result\./,
+ ],
+ [
+ 'blockquote',
+ '> ```text\n> **literal**\n> ```\n\n## Next steps\nCheck the result.',
+ /<h2>Next steps<\/h2>Check the result\./,
+ ],
+ ];
+ for (const [label, source, followingProse] of cases) {
+ const html = formatMarkdown(source);
+ assert.equal(preContents(html).length, 1, `${label}: fence did not render as one code block`);
+ assert.doesNotMatch(html, /<strong>literal<\/strong>/, `${label}: code formatting leaked into prose`);
+ assert.match(html, followingProse, `${label}: closing fence consumed following prose`);
+ }
+ });
+
+ test(`${build}: saved history uses an outer fence longer than all literal backticks`, () => {
+ const text = value => ({ nodeType: 3, nodeValue: value });
+ const element = (tagName, ...childNodes) => ({ nodeType: 1, tagName, childNodes });
+ for (const code of [readme, '````markdown\n```js\nconst x = 1;\n```\n````\n']) {
+ const pre = element('PRE', element('CODE', text(code)));
+ pre.parentElement = { querySelector: () => ({ textContent: 'markdown' }) };
+ const saved = historyTextFromElement(element('DIV', pre));
+ const firstFence = saved.match(/^(`+)markdown/)[1];
+ assert.ok([...code.matchAll(/`+/g)].every(match => match[0].length < firstFence.length));
+ assert.deepEqual(preContents(renderSkillMarkdown(saved)), [escapeHtml(code)]);
+ assert.deepEqual(preContents(formatMarkdown(saved)), [helpers.escapeCodeHtml(code)]);
+ }
+ });
+
+ // Opt-in native DOM checks: WEBBRAIN_MARKDOWN_DOM=1 npm run test:markdown.
+ if (process.env.WEBBRAIN_MARKDOWN_DOM === '1') test(`${build}: browser render, Copy and history round trip`, async () => {
+ const { chromium, firefox } = await import('playwright');
+ const browser = await (build === 'chrome' ? chromium : firefox).launch({ headless: true });
+ try {
+ const page = await browser.newPage({ viewport: { width: 480, height: 1000 } });
+ await page.route('http://markdown.test/**', async route => {
+ const name = new URL(route.request().url()).pathname.slice(1);
+ if (/^[\w-]+\.js$/.test(name)) {
+ await route.fulfill({ contentType: 'text/javascript', body: readUi(build, name) });
+ } else {
+ await route.fulfill({ contentType: 'text/html', body: '<html data-theme="light"><body><div class="message assistant"><div class="message-content" id="message"></div></div><div id="history"></div></body></html>' });
+ }
+ });
+ await page.goto('http://markdown.test/');
+ await page.addStyleTag({ content: fs.readFileSync(new URL(`../src/${build}/styles/sidepanel.css`, import.meta.url), 'utf8') });
+ const result = await page.evaluate(async ({ formatter, source, expected }) => {
+ const helpers = await import('/markdown-render.js');
+ const { sanitizeMarkdownLinks } = await import('/markdown-link.js');
+ const { escapeHtml } = await import('/utils.js');
+ const { historyTextFromElement } = await import('/history-text.js');
+ const { renderSkillMarkdown } = await import('/skill-markdown.js');
+ const dependencies = { ...helpers, sanitizeMarkdownLinks, escapeHtml, t: key => key, scheduleMathRender() {} };
+ const format = new Function(...Object.keys(dependencies), `return (${formatter})`)(...Object.values(dependencies));
+ let copied = null;
+ Object.defineProperty(navigator, 'clipboard', { value: { writeText: async text => { copied = text; } } });
+ const message = document.querySelector('#message');
+ message.innerHTML = format(source, { enhance: false });
+ const streamed = message.querySelector('pre code').textContent;
+ message.innerHTML = format(source);
+ await new Promise(resolve => setTimeout(resolve, 20));
+ message.querySelector('.code-copy-btn').click();
+ await Promise.resolve();
+ const saved = historyTextFromElement(message);
+ const history = document.querySelector('#history');
+ history.innerHTML = renderSkillMarkdown(saved);
+ return {
+ blocks: message.querySelectorAll('pre').length,
+ streamedMatches: streamed === expected,
+ copiedMatches: copied === expected,
+ historyMatches: history.querySelector('pre code').textContent === expected,
+ historyBlocks: history.querySelectorAll('pre').length,
+ nextHeading: message.querySelector('h2').textContent,
+ unsafeElements: message.querySelectorAll('script, img').length,
+ };
+ }, { formatter: panelFormatter(build), source: draft, expected: readme });
+ assert.deepEqual(result, { blocks: 1, streamedMatches: true, copiedMatches: true, historyMatches: true, historyBlocks: 1, nextHeading: 'Next steps', unsafeElements: 0 });
+ if (process.env.WEBBRAIN_MARKDOWN_SCREENSHOT_DIR) {
+ await page.screenshot({ path: `${process.env.WEBBRAIN_MARKDOWN_SCREENSHOT_DIR}/${build}-markdown.png`, fullPage: true });
+ }
+ } finally {
+ await browser.close();
+ }
+ });
+}
diff --git a/test/run.js b/test/run.js
index 4faa4ce7b..14cf64a86 100644
--- a/test/run.js
+++ b/test/run.js
@@ -21917,7 +21917,7 @@ test('sidepanels wire highlighting and heading rendering into fenced Markdown',
]) {
const panel = fs.readFileSync(path.join(ROOT, panelRel), 'utf8');
const css = fs.readFileSync(path.join(ROOT, cssRel), 'utf8');
- assert.match(panel, /import \{ codeFenceLanguage, highlightCode, renderMarkdownHeadings, renderMarkdownTables \} from '\.\/markdown-render\.js';/, `${label}: renderer helpers should be imported`);
+ assert.match(panel, /import \{ codeFenceLanguage, highlightCode, renderMarkdownHeadings, renderMarkdownTables, replaceMarkdownCodeFences \} from '\.\/markdown-render\.js';/, `${label}: renderer helpers should be imported`);
assert.match(panel, /const lang = codeFenceLanguage\(info\);/, `${label}: fenced code should tolerate metadata after its language token`);
assert.match(panel, /const highlighted = enhance \? highlightCode\(block\.code, block\.lang\) : escapeHtml\(block\.code\);/, `${label}: completed fenced code should be highlighted by its language while live code stays lightweight`);
assert.match(panel, /text = renderMarkdownTables\(text\);\s*text = renderMarkdownHeadings\(text\);/, `${label}: pipe tables must render before headings swallow the following newline`);