Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
43 changes: 40 additions & 3 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,9 @@
"dompurify": "3.4.17",
"highlight.js": "11.12.0",
"jsonc-parser": "3.3.1",
"katex": "0.18.10",
"marked": "18.1.1",
"marked-katex-extension": "5.1.13",
"mermaid": "^12.2.0",
"solid-js": "^1.9.17"
},
Expand Down
11 changes: 11 additions & 0 deletions src/extension/webview-html.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -220,6 +220,17 @@ describe('renderWebviewHtml', () => {
expect(imgSrc).toBe('vscode-webview-resource: data:');
});

it('allows bundled KaTeX fonts from the webview resource source', () => {
const html = renderWebviewHtml('vscode-webview-resource:', initialState, {
scriptUri: 'webview.js',
cssUri: 'webview.css',
version: 'fixed-cache-key',
});
const fontSrc = html.match(/font-src ([^;]+);/)?.[1];

expect(fontSrc).toBe('vscode-webview-resource: data:');
});

it('allows module chunks only from the webview resource source', () => {
const html = renderWebviewHtml('vscode-webview-resource:', initialState, {
scriptUri: 'webview.js',
Expand Down
2 changes: 1 addition & 1 deletion src/extension/webview-html.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,7 +146,7 @@ export function renderWebviewHtml(
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="Content-Security-Policy"
content="default-src 'none'; img-src ${cspSource} data:; script-src 'nonce-${nonce}' ${cspSource}; worker-src blob:; connect-src ${cspSource}; style-src 'unsafe-inline' ${cspSource}; font-src data:;" />
content="default-src 'none'; img-src ${cspSource} data:; script-src 'nonce-${nonce}' ${cspSource}; worker-src blob:; connect-src ${cspSource}; style-src 'unsafe-inline' ${cspSource}; font-src ${cspSource} data:;" />
<title>Varro</title>
<style>${LOADING_STYLES}${editorLoadingStyles}</style>${logoPreload}
<link rel="stylesheet" href="${escapeHtmlAttribute(cssUri)}" />${modulePreloads}
Expand Down
74 changes: 74 additions & 0 deletions src/webview/components/MarkdownRenderer.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -481,6 +481,80 @@ describe('MarkdownRenderer', () => {
expect(mounted).not.toHaveBeenCalled();
});

it('renders inline and display LaTeX with KaTeX', () => {
const html = __parseMarkdownForTests(
[
'Inline: $\\mathcal{N}(\\mu_t^{(p)},\\Sigma_t^{(p)})$',
'',
'$$',
'\\hat\\mu_t^{(p)}=A_t^{(p)}\\mu_t^{(p)}+b_t^{(p)},\\qquad',
'\\hat\\Sigma_t^{(p)}=A_t^{(p)}\\Sigma_t^{(p)}(A_t^{(p)})^\\top',
'$$',
].join('\n'),
{ cacheByContent: false }
);
const root = document.createElement('div');
root.innerHTML = html;

expect(root.querySelectorAll('.katex')).toHaveLength(2);
expect(root.querySelector('.katex-display')).not.toBeNull();
expect(root.querySelector('.katex-html [style]')).not.toBeNull();
expect(root.querySelector('.katex-error')).toBeNull();
});

it('renders display math when delimiters share lines with the formula', () => {
const html = __parseMarkdownForTests(
[
'然后按逆协方差加权融合:',
'',
'$$\\mu_t=\\Sigma_t\\sum_{p}',
'(\\hat\\Sigma_t^{(p)})^{-1}\\hat\\mu_t^{(p)},\\qquad',
'\\Sigma_t=\\Big(\\sum_{p}(\\hat\\Sigma_t^{(p)})^{-1}\\Big)^{-1}$$',
].join('\n'),
{ cacheByContent: false }
);
const root = document.createElement('div');
root.innerHTML = html;

expect(root.querySelector('.katex-display')).not.toBeNull();
expect(root.querySelector('.katex-html [style]')).not.toBeNull();
expect(root.querySelector('.katex-error')).toBeNull();
});

it('keeps LaTeX literal inside code spans and fenced code blocks', () => {
const html = __parseMarkdownForTests(
['Inline code: `$x^2$`', '', '```text', '$y^2$', '```'].join('\n'),
{ cacheByContent: false }
);
const root = document.createElement('div');
root.innerHTML = html;

expect(root.querySelector('.katex')).toBeNull();
expect(root.querySelector('code')?.textContent).toBe('$x^2$');
expect(root.querySelector('pre')?.textContent).toContain('$y^2$');
});

it('does not treat currency amounts as math', () => {
const html = __parseMarkdownForTests('It costs $5 and $10.', { cacheByContent: false });
const root = document.createElement('div');
root.innerHTML = html;

expect(root.querySelector('.katex')).toBeNull();
expect(root.textContent?.trim()).toBe('It costs $5 and $10.');
});

it('renders math followed by CJK punctuation', () => {
const html = __parseMarkdownForTests(
'查询出 $\\mathcal{N}(\\mu_t^{(p)},\\Sigma_t^{(p)})$,再变换回全局:',
{ cacheByContent: false }
);
const root = document.createElement('div');
root.innerHTML = html;

expect(root.querySelector('.katex')).not.toBeNull();
expect(root.querySelector('.katex-error')).toBeNull();
});

it('renders indented text as prose while preserving fenced code blocks', () => {
const indentedHtml = __parseMarkdownForTests(
'Failure details\n\n Error: expected 37\n Received: 36.71875',
Expand Down
145 changes: 141 additions & 4 deletions src/webview/components/MarkdownRenderer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,9 @@ import { Show, createSignal, createEffect, createMemo, onMount, onCleanup } from
import type { JSX } from 'solid-js';
import { Portal, render } from 'solid-js/web';
import DOMPurify from 'dompurify';
import { renderToString as renderKatex } from 'katex';
import { marked, Tokenizer } from 'marked';
import markedKatex from 'marked-katex-extension';
import type { Token, Tokens } from 'marked';
import type { Mermaid, MermaidConfig } from 'mermaid';
import { writeClipboard } from '../lib/write-clipboard';
Expand Down Expand Up @@ -188,6 +190,84 @@ const ALLOWED_HTML_ATTRIBUTES = [
'y1',
'y2',
];
const KATEX_HTML_TAGS = [
'annotation',
'annotation-xml',
'math',
'menclose',
'merror',
'mfrac',
'mi',
'mmultiscripts',
'mn',
'mo',
'mover',
'mpadded',
'mphantom',
'mprescripts',
'mrow',
'mroot',
'ms',
'mspace',
'msqrt',
'mstyle',
'msub',
'msubsup',
'msup',
'mtable',
'mtd',
'mtext',
'mtr',
'munder',
'munderover',
'none',
'semantics',
];
const KATEX_HTML_ATTRIBUTES = [
'accent',
'accentunder',
'align',
'bevelled',
'columnlines',
'columnalign',
'columnspacing',
'columnspan',
'display',
'displaystyle',
'encoding',
'equalcolumns',
'equalrows',
'frame',
'framespacing',
'linethickness',
'lspace',
'mathvariant',
'maxsize',
'minsize',
'movablelimits',
'notation',
'preserveAspectRatio',
'rowalign',
'rowlines',
'rowspacing',
'rowspan',
'rspace',
'scriptlevel',
'separator',
'stretchy',
'symmetric',
'voffset',
'xmlns',
];
const KATEX_RENDER_OPTIONS = {
throwOnError: false,
strict: 'ignore',
trust: false,
output: 'htmlAndMathml',
} as const;
// Models commonly emit display math as "$$first line\nlast line$$" instead of
// placing the delimiters on their own lines. Match that form at block level.
const DISPLAY_MATH_BLOCK_RE = /^\$\$[ \t]*\n?([\s\S]+?)\$\$(?=\n|$)/;
const MAX_COPY_TEXT_LENGTH = 20_000;
const MAX_MERMAID_SOURCE_LENGTH = 100_000;
const MERMAID_SVG_CACHE_LIMIT = 20;
Expand Down Expand Up @@ -572,6 +652,30 @@ marked.setOptions({
gfm: true,
breaks: false,
});
marked.use(markedKatex(KATEX_RENDER_OPTIONS));
marked.use({
extensions: [
{
name: 'displayKatexBlock',
level: 'block',
tokenizer(src) {
const match = DISPLAY_MATH_BLOCK_RE.exec(src);
if (!match) return undefined;
const text = match[1]?.trim();
if (!text) return undefined;
return {
type: 'displayKatexBlock',
raw: match[0],
text,
};
},
renderer(token) {
const text = getString(token.text);
return text ? `${renderKatex(text, { ...KATEX_RENDER_OPTIONS, displayMode: true })}\n` : '';
},
},
],
});

const PATH_SEPARATOR_SOURCE = String.raw`[\\/]`;
const PATH_SEGMENT_CHARS_SOURCE = String.raw`[\w.@+-]`;
Expand Down Expand Up @@ -746,7 +850,7 @@ function linkifySessionReferences(fragment: DocumentFragment) {
// SAFETY: The surrounding shape or discriminator check establishes the Text contract used below.
const node = walker.currentNode as Text;
const parent = node.parentElement;
if (!parent || parent.closest('a, button, code, pre')) continue;
if (!parent || parent.closest('a, button, code, pre, .katex')) continue;
textNodes.push(node);
}

Expand Down Expand Up @@ -793,6 +897,33 @@ function linkifySessionReferences(fragment: DocumentFragment) {
}
}

function rehydrateKatexMath(fragment: DocumentFragment) {
for (const element of Array.from(fragment.querySelectorAll<HTMLElement>('.katex'))) {
const annotation = element.querySelector('annotation[encoding="application/x-tex"]');
const tex = annotation?.textContent;
if (!tex) continue;

const displayMode =
element.closest('.katex-display') !== null ||
element.querySelector('math[display="block"]') !== null;
const rendered = renderKatex(tex, {
displayMode,
throwOnError: false,
strict: 'ignore',
trust: false,
output: 'htmlAndMathml',
});
const template = document.createElement('template');
template.innerHTML = rendered;
const wrapper = template.content.firstElementChild;
const replacement =
displayMode && wrapper?.classList.contains('katex-display')
? wrapper.querySelector('.katex')
: wrapper;
if (replacement) element.replaceWith(replacement);
}
}

function sanitizeHtml(
html: string,
disableCache: boolean,
Expand All @@ -810,13 +941,19 @@ function sanitizeHtml(
// second time, which is where mutation-XSS lives. Mutating the fragment
// DOMPurify vetted keeps a single parse/serialize round trip.
const fragment = DOMPurify.sanitize(html, {
ALLOWED_TAGS: ALLOWED_HTML_TAGS,
ALLOWED_ATTR: ALLOWED_HTML_ATTRIBUTES,
ALLOWED_TAGS: [...ALLOWED_HTML_TAGS, ...KATEX_HTML_TAGS],
ALLOWED_ATTR: [...ALLOWED_HTML_ATTRIBUTES, ...KATEX_HTML_ATTRIBUTES],
ALLOW_DATA_ATTR: false,
FORBID_ATTR: ['style'],
RETURN_DOM_FRAGMENT: true,
});

// DOMPurify removes the inline styles KaTeX needs for layout. Re-render each
// formula from its (sanitized) TeX annotation after sanitization so the
// trusted KaTeX markup keeps its positioning without allowing model-authored
// style attributes through the general Markdown sanitizer.
rehydrateKatexMath(fragment);

const privateSelector = PRIVATE_RENDERER_ATTRIBUTES.map((name) => `[${name}]`).join(',');
for (const element of Array.from(fragment.querySelectorAll<HTMLElement>(privateSelector))) {
if (element.hasAttribute(TRUSTED_RENDERER_ATTRIBUTE)) continue;
Expand Down Expand Up @@ -1518,7 +1655,7 @@ function linkifyPaths(fragment: DocumentFragment) {
if (
!parent ||
parent.closest(
'a, button, code, pre, svg, .interactive-result-code-block, .mermaid-diagram, .markdown-task-checkbox, .markdown-inline-slot'
'a, button, code, pre, svg, .katex, .interactive-result-code-block, .mermaid-diagram, .markdown-task-checkbox, .markdown-inline-slot'
)
) {
continue;
Expand Down
1 change: 1 addition & 0 deletions src/webview/index.css
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
@import './styles/base.css';
@import './styles/chat-shell.css' layer(components);
@import './styles/messages.css' layer(components);
@import './styles/math.css' layer(components);
@import './styles/composer.css' layer(components);
@import './styles/tool-calls.css' layer(components);
@import './styles/menus.css' layer(components);
Expand Down
Loading