AI, fully local on your computer.
TypeScript aiai-toolskiwixllama-cpplocal-ailocal-llmofflineoffline-aioffline-firstprivacy-firstragwikipediazim
import { cloneElement, isValidElement, memo, type ReactElement, type ReactNode } from 'react'
import { Streamdown, defaultRehypePlugins, useIsCodeFenceIncomplete } from 'streamdown'
import { math } from '@streamdown/math'
import { codeBlockExtension } from '@shared/code-block-export'
import { useCodeBlockActions, type CodeBlockActions } from './CodeBlockActionsContext'
import { useT } from '../i18n'
// rehype-katex renders the math; this import resolves the same katex install (one copy in the
// bundle since #698) and is used only to VALIDATE partially-streamed TeX before typesetting it
// (completePartialTex below). The CSS comes from that install too.
import katex from 'katex'
import 'katex/dist/katex.min.css'
// Streamdown + KaTeX markdown renderer for assistant replies. Split out of Transcript.tsx into
// its own module (perf: renderer code-split) so the streamdown/katex/@streamdown/math weight
// (~2 MB pre-split) loads as a separate async chunk via AssistantMarkdownLazy — the app shell and
// non-chat screens no longer carry it in the initial bundle. Consumers import the lazy wrapper
// (barrel `AssistantMarkdown`), never this module directly.
// The math plugin (KaTeX) is module-level so its reference is stable across renders — a fresh
// object each render would defeat Streamdown's block memoization. remark-math parses ONLY
// $$…$$ — NOT single `$` (`singleDollarTextMath` stays off: it claims EVERY `$` pair, mangling
// prose like "$5 and $10" into math) and NOT the LaTeX-style \(…\)/\[…\] delimiters. Both of
// those forms are normalized to $$ by `normalizeMathDelimiters` below — brackets always, single
// `$…$` only when the span really looks like math (#501) — before the text reaches Streamdown.
const mdPlugins = { math }
// Local models emit LaTeX-style `\[ … \]` / `\( … \)` math at least as often as the `$$` form,
// but remark-math parses only `$`-delimiters — bracket math silently degraded to literal
// "[ … ]" text (commonmark eats the backslashes as escapes). Normalize brackets → `$$…$$`
// before Streamdown, SKIPPING fenced blocks and inline code spans so a code sample mentioning
// `\[x\]` stays verbatim. `\[ … \]` on its own lines becomes flow math (display); `\( … \)`
// becomes `$$…$$` inline math text (single-`$` stays off, so dollar prose is still safe).
// One O(n) pass per text change — the same whole-buffer class as parseIncompleteMarkdown; an
// unclosed `\[ …` mid-stream stays literal until its `\]` arrives, then converts on that flush.
// ponytail: regex-over-segments, not a markdown AST walk — revisit only if a real transcript
// shows a false positive (e.g. prose containing a literal backslash-bracket pair).
// Capturing split: even indices are prose, odd indices are code (fences first, then spans).
// With one capture group split always returns an odd number of parts, so the LAST part is always
// prose — '' when an UNCLOSED trailing fence swallows to end-of-text as a code part; the
// completions below find nothing in that ''.
const CODE_SPLIT_RE = /(```[\s\S]*?(?:```|$)|~~~[\s\S]*?(?:~~~|$)|`[^`\n]+`)/
function normalizeMathDelimiters(text: string): string {
if (!text.includes('\\[') && !text.includes('\\(') && !text.includes('$')) return text
const parts = text.split(CODE_SPLIT_RE)
for (let i = 0; i < parts.length; i += 2) {
parts[i] = promoteSingleDollarMath(
// The model's own `$$` pairs first, before the bracket rules below emit any of theirs.
canonicalizeDisplayDollars(parts[i]!)
// Line-anchored \[ … \] next: micromark's DISPLAY (flow) math needs `$$` on its own
// lines, so a block-shaped bracket pair becomes the fence form, at the line's indentation
// when a fence may keep it (#701: dropping it took a formula in a list item out of the
// list)… A delimiter's backslash must not be escaped itself: `\\[2pt]` is a TeX row break.
.replace(
/^([ \t]*)\\\[([\s\S]+?)(?<!\\)\\\][ \t]*$/gm,
(_m, indent: string, inner: string) => displayFence(fenceIndent(indent) ?? '', inner.trim())
)
// …and anything left (mid-sentence brackets, \( … \)) becomes inline math text.
.replace(/(?<!\\)\\\[([\s\S]+?)(?<!\\)\\\]/g, (_m, inner: string) => `$$${inner}$$`)
.replace(/(?<!\\)\\\(([\s\S]+?)(?<!\\)\\\)/g, (_m, inner: string) => `$$${inner}$$`)
)
}
parts[parts.length - 1] = openDanglingDisplayDollar(parts)
return parts.join('')
}
/** A display formula in micromark's fence form: `$$` alone on the lines around its TeX. */
function displayFence(indent: string, tex: string): string {
return `${indent}$$\n${indent}${tex}\n${indent}$$`
}
/**
* The indentation a display fence may keep, or null. Under four columns it is a list item's
* content line (or none). Four or more, or a tab, is an indented code block outside a list, so
* a fence kept there would turn the formula into code; such lines keep their earlier reading.
*/
function fenceIndent(indent: string): string | null {
return /^ {0,3}$/.test(indent) ? indent : null
}
// #701 — models write display math as `$$ … $$` in shapes micromark's flow construct does not
// read the way LaTeX (or Pandoc, or GitHub) does: it takes `$$` only ALONE on a fence line. TeX
// on the opening line became the fence's "meta" and vanished (`$$ x = 1⏎$$` rendered an empty
// block); TeX glued to the closer left the block open to the end of the answer (`\end{aligned}$$`
// → one KaTeX error box over everything after it); and a one-line `$$ x $$` paragraph became
// INLINE math. A `$$ … $$` pair that occupies whole lines is therefore rewritten into the fence
// form, as the line-anchored `\[ … \]` rule already is, keeping the line's indentation so a formula
// in a list item stays in it (`fenceIndent`: four columns or more stay as they were). The pair
// never spans a blank line or another `$$`: a line holding `$$a$$ and $$b$$` is two inline
// formulas and does not match, nor does a `$$$` run.
const BLOCK_DOLLAR_RE = /^( {0,3})\$\$(?!\$)((?:(?!\$\$|\n[ \t]*\n)[\s\S])+?)(?<!\$)\$\$(?!\$)[ \t]*$/gm
function canonicalizeDisplayDollars(prose: string): string {
if (!prose.includes('$$')) return prose
return prose.replace(BLOCK_DOLLAR_RE, (m, indent: string, inner: string) =>
inner.trim() === '' ? m : displayFence(indent, inner.trim())
)
}
/** A `$$` delimiter: exactly two dollars, not a backslash-escaped `\$` (micromark's reading). */
const DISPLAY_DOLLAR_RE = /(?<![\\$])\$\$(?!\$)/g
/**
* The `$$` left without a partner, when it is the trailing prose segment's own last one: its
* index there, and the indentation its display fence keeps (null mid-line, or where a fence may
* not keep it). Null when every `$$` has its partner, when the buffer ends inside code (the
* trailing prose part is then ''), or when the unpaired one lies before a code span: which `$$`
* that is cannot be told from here.
*/
function danglingDisplayDollar(parts: string[]): { open: number; fence: string | null } | null {
const last = parts.length - 1
const inTail = [...parts[last]!.matchAll(DISPLAY_DOLLAR_RE)]
let before = 0
for (let i = 0; i < last; i += 2) before += parts[i]!.match(DISPLAY_DOLLAR_RE)?.length ?? 0
if (inTail.length % 2 === 0 || before % 2 === 1) return null
const open = inTail[inTail.length - 1]!.index
const head = parts[last]!.slice(0, open)
return { open, fence: fenceIndent(head.slice(head.lastIndexOf('\n') + 1)) }
}
// #701 — the one `$$` left without a partner (a turn stopped or cut off mid-formula, or the live
// tail before its closer streams in) is, at the start of a line with TeX after it and no `$`, the
// same flow fence whose "meta" micromark drops: the persisted turn showed an empty block where the
// formula had been. Move that TeX to its own line so it is kept: typeset when it parses, otherwise
// KaTeX's error text, which is the raw TeX. Mid-line, or with a `$` after it, micromark reads the
// line as paragraph text and an unclosed `$$` stays literal; that needs nothing.
function openDanglingDisplayDollar(parts: string[]): string {
const tail = parts[parts.length - 1]!
const dangling = danglingDisplayDollar(parts)
if (dangling === null || dangling.fence === null) return tail
const { open, fence } = dangling
const newline = tail.indexOf('\n', open)
const lineEnd = newline === -1 ? tail.length : newline
const rest = tail.slice(open + 2, lineEnd)
if (rest.trim() === '' || rest.includes('$')) return tail
return `${tail.slice(0, open + 2)}\n${fence}${rest.trimStart()}${tail.slice(lineEnd)}`
}
// #501 — models write inline math as `$ … $` at least as often as `$$ … $$`, and remark-math's
// own single-dollar mode is not an option: it claims EVERY `$` pair, so "owes $5 and $10" turns
// into math. Promote only spans that genuinely look like math. Two filters, both on the
// code-free prose segments: Pandoc's shape rule (no whitespace just inside the delimiters, no
// digit immediately after the closer, never across a line break) AND a content rule — a TeX
// signal character, or a one/two-character symbol like `$m$`, `$x$`, `$π$`. Everything else
// stays literal, which is why `$HOME/$USER` survives (`/` is deliberately NOT a signal) as do
// currency runs and escaped `\$`. The promoted form is the GLUED `$$…$$`, which micromark reads
// as INLINE (text) math: its flow/display construct rejects a `$` on the opening fence line.
const TEX_SIGNAL = /[\\^_{}=+<>|]/
function looksLikeMath(inner: string): boolean {
if (TEX_SIGNAL.test(inner)) return true
// A bare symbol: `$x$`, `$xy$`. Digits are excluded so `$5` can never qualify.
return inner.length <= 2 && !/[\d\s]/.test(inner)
}
/** `$` at `i` opens a span only if it is unescaped and the next character starts an expression. */
function isDollarOpener(prose: string, i: number): boolean {
const prev = i > 0 ? prose[i - 1]! : ''
const next = prose[i + 1]
return prev !== '\\' && prev !== '$' && next !== undefined && next !== '$' && !/\s/.test(next)
}
/** The closing `$` for the opener at `open`, or -1 (Pandoc's spacing/digit rule; same line only). */
function closingDollar(prose: string, open: number): number {
for (let j = open + 1; j < prose.length; j++) {
const c = prose[j]!
if (c === '\n') return -1 // inline math never spans lines
if (c !== '$') continue
const before = prose[j - 1]!
const after = prose[j + 1] ?? ''
if (before === '\\' || /\s/.test(before)) continue
if (after === '$' || /[0-9]/.test(after)) continue
return j
}
return -1
}
/** One promotable `$…$` span: the index of its opening `$` and of its closing `$`. */
type DollarSpan = { open: number; close: number }
/**
* One left-to-right pass over a prose segment: the `$…$` spans worth promoting, plus `tailOpen`
* — the last opener still waiting for its closer, which is what the streaming pass completes.
* `$$…$$` is opaque (remark-math owns it); an UNCLOSED `$$` owns everything after it, so the
* scan stops there and reports no tail.
*/
function scanDollarMath(prose: string): { spans: DollarSpan[]; tailOpen: number } {
const spans: DollarSpan[] = []
let tailOpen = -1
let i = 0
while (i < prose.length) {
if (prose[i] !== '$') {
i++
} else if (prose[i + 1] === '$') {
const end = prose.indexOf('$$', i + 2)
if (end === -1) return { spans, tailOpen: -1 }
i = end + 2
} else if (!isDollarOpener(prose, i)) {
i++
} else {
const close = closingDollar(prose, i)
if (close === -1) {
tailOpen = i
i++
} else if (looksLikeMath(prose.slice(i + 1, close))) {
spans.push({ open: i, close })
i = close + 1
} else {
i++
}
}
}
return { spans, tailOpen }
}
function promoteSingleDollarMath(prose: string): string {
if (!prose.includes('$')) return prose
const { spans } = scanDollarMath(prose)
if (spans.length === 0) return prose
let out = ''
let copied = 0
for (const { open, close } of spans) {
out += `${prose.slice(copied, open)}$$${prose.slice(open + 1, close)}$$`
copied = close + 1
}
return out + prose.slice(copied)
}
// A partially-streamed TeX expression usually is NOT valid TeX (a `\frac{…` cut mid-group
// throws, and rehype-katex then falls back to raw error text — worse than showing nothing).
// Complete it: cut a half-streamed macro name / dangling `^`/`_`, close unbalanced brace
// groups, and if the result still lacks a pending argument group (e.g. `\frac{X}` awaiting
// its denominator) try an appended `{}` — then VALIDATE with KaTeX itself (the install
// rehype-katex renders with) and only emit TeX that actually parses. Returns null when the
// partial is unsalvageable this flush (e.g. `\left(` before its `\right` arrives) — the
// caller then hides the math tail instead of flashing raw TeX; it appears once parseable.
function completePartialTex(tex: string): string | null {
let t = tex
.replace(/\\[a-zA-Z]*$/, '') // half-streamed macro name (`\fra`) or lone trailing `\`
.replace(/[\^_]\s*$/, '') // trailing sub/superscript operator awaiting its argument
.trimEnd()
let depth = 0
for (let i = 0; i < t.length; i++) {
const c = t[i]
if (c === '\\') {
i++ // skip the escaped char — `\{` is not a group open
} else if (c === '{') {
depth++
} else if (c === '}' && depth > 0) {
depth--
}
}
t += '}'.repeat(depth)
if (t.trim() === '') return null
for (const candidate of [t, `${t}{}`]) {
try {
katex.renderToString(candidate, { throwOnError: true })
return candidate
} catch {
// try the next candidate / fall through to null
}
}
return null
}
// Streaming companion to `normalizeMathDelimiters`: mid-stream, a trailing `\[ …` / `\( …`
// whose CLOSING delimiter hasn't arrived yet can't be claimed by the whole-text pass, so the
// raw TeX would flash until the close streamed in. Streamdown's `remend` hook runs custom
// handlers over the buffer on every flush (streaming mode only, before block-splitting) —
// complete the dangling opener to a CLOSED `$$…$$` there (via `completePartialTex`, so only
// TeX that actually parses is typeset; an unsalvageable partial is held back this flush).
// A prose `\[` that never closes shows as math only WHILE streaming; the persisted turn
// re-renders static (no remend) through the whole-text pass and is literal again.
function completeTrailingBracketMath(text: string): string {
if (!text.includes('\\[') && !text.includes('\\(')) return text
const parts = text.split(CODE_SPLIT_RE)
const last = parts.length - 1
const tail = parts[last]!
// The LAST opener in the trailing prose segment; a closed pair was already converted to $$
// by normalizeMathDelimiters, so anything still bracket-form here is the dangling tail.
const b = lastUnescaped(tail, '\\[')
const p = lastUnescaped(tail, '\\(')
const open = Math.max(b, p)
if (open === -1) return text
const isBlock = open === b
if (tail.indexOf(isBlock ? '\\]' : '\\)', open) !== -1) return text // actually closed
const inner = tail.slice(open + 2)
if (inner.trim() === '') return text // just the opener so far — nothing to typeset yet
const fixed = completePartialTex(inner)
// Not (yet) parseable even after completion → hide the math tail this flush rather than
// flash raw TeX / a KaTeX error box; a later flush with more tokens will pick it up.
if (fixed === null) {
parts[last] = tail.slice(0, open)
return parts.join('')
}
const before = tail.slice(0, open)
const indent = before.slice(before.lastIndexOf('\n') + 1)
const blockShaped = isBlock && /^[ \t]*$/.test(indent)
parts[last] = blockShaped
? before.slice(0, before.length - indent.length) + displayTail(fenceIndent(indent) ?? '', fixed.trim())
: `${before}$$${fixed}$$`
return parts.join('')
}
/**
* The last `opener` (`\[` or `\(`) whose backslash is not itself escaped, or -1. In TeX `\\[2pt]`
* is a row break with extra space, not a bracket opener (#701: taken for one, it hid the formula
* and everything streamed after it).
*/
function lastUnescaped(s: string, opener: string): number {
for (let i = s.lastIndexOf(opener); i !== -1; i = i === 0 ? -1 : s.lastIndexOf(opener, i - 1)) {
let k = i
while (k > 0 && s[k - 1] === '\\') k--
if ((i - k) % 2 === 0) return i
}
return -1
}
/**
* A completed DISPLAY tail: the fence form, then a newline that keeps the closing `$$` a fence
* line of its own. remend's later handlers append their closers to the buffer (an unmatched `[`
* in the prose above gets `](streamdown:incomplete-link)`), and glued to the fence that text left
* the formula open, a KaTeX error box (#701).
*/
function displayTail(indent: string, tex: string): string {
return `${displayFence(indent, tex)}\n`
}
// Streaming companion to `promoteSingleDollarMath` (#501): a trailing `$ E = mc^` has no closer
// yet, so the whole-text pass cannot claim it. Complete the LAST dangling opener in the trailing
// prose segment — but only when the partial already carries a TeX signal. A tail like "$5 and
// the" or a bare "$m" is still ambiguous (the next token could make it prose or currency), and
// unlike the static pass there is no closer to judge it by, so the short-symbol rule does NOT
// apply here: an ambiguous tail simply stays literal for this flush.
function completeTrailingDollarMath(text: string): string {
if (!text.includes('$')) return text
const parts = text.split(CODE_SPLIT_RE)
const last = parts.length - 1
const tail = parts[last]!
const { tailOpen } = scanDollarMath(tail)
// A newline after the opener means the buffer moved on: it was a literal `$`, not math.
if (tailOpen === -1 || tail.indexOf('\n', tailOpen) !== -1) return text
const inner = tail.slice(tailOpen + 1)
if (!TEX_SIGNAL.test(inner)) return text
const fixed = completePartialTex(inner)
// Unparseable even after completion → hide the tail this flush (same as the bracket path).
parts[last] = fixed === null ? tail.slice(0, tailOpen) : `${tail.slice(0, tailOpen)}$$${fixed}$$`
return parts.join('')
}
// #701 — streaming companion for a dangling `$$`. Without it, remend's built-in katex handler
// closed the tail by appending `$$` and nothing more, so a partial like `$$ x = \frac{-b \pm \sqrt`
// reached rehype-katex as TeX that cannot parse and showed KaTeX's error box until it did. Same
// treatment as the other tails: complete through `completePartialTex`, typeset what parses, hide
// the tail this flush when nothing does. A dangling `$$` at the start of a line is display math,
// as the pair will be once its closer ends the line (`canonicalizeDisplayDollars`); mid-line it is
// inline. Prose after the closer on the same line turns it inline then, as for `\[ … \]`.
function completeTrailingDisplayDollarMath(text: string): string {
if (!text.includes('$$')) return text
const parts = text.split(CODE_SPLIT_RE)
// Null also when the unpaired `$$` lies before a code span: remend's katex handler closes that
// one, as it did before.
const dangling = danglingDisplayDollar(parts)
if (dangling === null) return text
const { open, fence } = dangling
const last = parts.length - 1
const tail = parts[last]!
const before = tail.slice(0, open)
// A lone `$` at the very end is the closer's first half: without this cut the formula would
// vanish for the one flush between the two dollars.
const inner = tail.slice(open + 2).replace(/(?<![\\$])\$[ \t]*$/, '')
// Inline math never crosses a blank line, so a mid-line `$$` followed by one was a literal `$$`
// (the persisted turn shows it so). Escape it rather than complete it: completed, everything
// after it stayed hidden while it did not parse as TeX (`&` does not), and left as it is,
// remend's katex handler would close it at the end of the buffer instead.
if (fence === null && /\n[ \t]*\n/.test(inner)) {
parts[last] = `${before}\\$\\$${tail.slice(open + 2)}`
return parts.join('')
}
const fixed = inner.trim() === '' ? null : completePartialTex(inner)
// Just the opener so far, or not (yet) parseable even after completion: hide the tail this
// flush rather than flash a stray `$$`, raw TeX or a KaTeX error box.
if (fixed === null) {
parts[last] = before
} else if (fence === null) {
parts[last] = `${before}$$${fixed}$$`
} else {
parts[last] = before.slice(0, before.length - fence.length) + displayTail(fence, fixed.trim())
}
return parts.join('')
}
// #701 — remend's links completion (priority 20, after us) reads every `[` with no matching `]`
// outside code as an unfinished link, math included, and appends `](streamdown:incomplete-link)`
// to the buffer. A half-open interval in a formula already closed (`$$ x \in [0, 1) $$`) left
// that text at the end of the live bubble for the rest of the stream; inside the formula still
// streaming (`x \in [a, b`) it landed after the closing `$$` and broke the formula into a KaTeX
// error box. Such a `[` becomes `\lbrack ` (the space ends the control word and adds nothing),
// which KaTeX draws as the same glyph with the same spacing; `\lbrack{}` would not: its empty
// group is an atom of its own, and a `-` after it became a binary minus. Streaming only: the
// persisted turn renders statically, with no remend and its own TeX.
const MATH_SPAN_RE = /(?<![\\$])\$\$(?!\$)([\s\S]*?)(?<![\\$])\$\$(?!\$)/g
function shieldMathBrackets(text: string): string {
if (!text.includes('[')) return text
const parts = text.split(CODE_SPLIT_RE)
for (let i = 0; i < parts.length; i += 2) {
if (!parts[i]!.includes('[')) continue
parts[i] = parts[i]!.replace(MATH_SPAN_RE, (span, tex: string) => {
const open: number[] = []
for (let j = 0; j < tex.length; j++) {
if (tex[j] === '\\') j++ // a control symbol: `\{`, `\\` (so `\\[2pt]` stays a pair)
else if (tex[j] === '[') open.push(j)
else if (tex[j] === ']') open.pop()
}
if (open.length === 0) return span
let out = tex
for (const j of open.reverse()) out = `${out.slice(0, j)}\\lbrack ${out.slice(j + 1)}`
return `$$${out}$$`
})
}
return parts.join('')
}
/**
* All three streaming completions in one handler. Brackets first (they may emit `$$` the others
* read), then a dangling `$$` (it owns the rest of the buffer, so the single-`$` scan then finds
* no tail after it), then a dangling `$`; last, the `[` shield over every formula they left.
*/
function completeTrailingMath(text: string): string {
return shieldMathBrackets(
completeTrailingDollarMath(completeTrailingDisplayDollarMath(completeTrailingBracketMath(text)))
)
}
// Module-level (stable reference for Streamdown's memoization). Priority 10 puts the handler
// BEFORE remend's built-in links completion (20) — that handler treats a dangling `\[ …` tail
// as an incomplete LINK, completes it to `](streamdown:incomplete-link)`, and EARLY-RETURNS
// the whole pipeline, so at any later priority we would never run. Converting first also means
// links sees no unclosed `[` and the katex built-ins (70/75) see our `$$` already balanced: the
// `$$` one only acts on a dangling `$$` this handler leaves alone, one that began before a code
// span in the tail.
const mdRemend = {
handlers: [{ name: 'trailing-math', priority: 10, handle: completeTrailingMath }]
}
// Pare Streamdown's default rehype chain (raw → sanitize → harden) down to just `sanitize`:
// • drop `rehype-raw` so model-emitted HTML is NEVER parsed into live elements — it renders as
// literal text instead (the app's long-standing no-injection posture: `<img onerror=…>` and
// `<script>` show as text, not as a stripped-but-present <img>/<script> node).
// • drop `rehype-harden` (link/image-origin rewriting): redundant here — the CSP already blocks
// remote images (`img-src 'self' data:`) and the `a` override below is the link gate; harden only
// muddied output with "[blocked]" rewrites and trailing-slash href normalization.
// `sanitize` stays as defence-in-depth. KaTeX's rehype plugin rides in via `plugins`, independent of
// this list, so math is unaffected. Streamdown appends it AFTER this list, so KaTeX's own output is
// never sanitized: KaTeX's `trust` option is that path's gate, and nothing may set it (DEP-7; the
// `trust` pin in assistant-markdown.test.tsx). Module-level for a stable reference (memoization).
const mdRehypePlugins = [defaultRehypePlugins.sanitize]
// ---------------------------------------------------------------------------------------------
// #286 — the per-code-block Copy / Save toolbar.
//
// WHY `pre` AND NOT `code`: Streamdown's default `pre` is literally
// `({children}) => isValidElement(children) ? cloneElement(children, {'data-block':'true'}) : children`
// — it exists only to STAMP the child <code> as a block; the default `code` component then reads
// that stamp and renders the whole `<div data-streamdown="code-block">` (header row with the
// language + `<pre><code>` body), and renders `<code data-streamdown="inline-code">` without it.
// Overriding `code` would therefore mean re-implementing Streamdown's block chrome (and would have
// to re-handle inline code); overriding `pre` lets us keep every pixel of it and merely wrap.
//
// `controls={false}` STAYS (owner decision D4): Streamdown's own download control is a
// blob + `<a download>` in the renderer, which bypasses the main-process write boundary (the
// native save dialog IS the consent). Ours goes through `window.api.saveCodeBlock`.
/** The block's exact code value + its fence language token, read off the child <code> element. */
function readCodeChild(child: ReactElement): { content: string; language: string } {
const props = child.props as { className?: string; children?: unknown }
// Mirror Streamdown's own extraction: the highlighted body may be a string or a single
// element wrapping one.
const inner = props.children
let raw = ''
if (typeof inner === 'string') {
raw = inner
} else if (isValidElement(inner)) {
const nested = (inner.props as { children?: unknown }).children
if (typeof nested === 'string') raw = nested
}
// mdast-util-to-hast appends ONE '\n' to every code node's value (`value ? value + '\n' : ''`).
// D1 says "verbatim" = the code value AS PARSED, so strip exactly that one newline — otherwise
// every saved file would gain a byte the markdown never contained.
const content = raw.endsWith('\n') ? raw.slice(0, -1) : raw
const language = /language-([^\s]+)/.exec(props.className ?? '')?.[1] ?? ''
return { content, language }
}
/**
* The hover/focus toolbar over one fenced block. Mounted ONLY when the transcript provided
* CodeBlockActions — which is also why it may use the i18n hook: AssistantMarkdown itself renders
* in contexts with no I18nProvider (unit tests, other screens) and the bare `pre` path below must
* stay hook-free for them.
*/
function CodeBlockToolbar({
actions,
content,
language
}: {
actions: CodeBlockActions
content: string
language: string
}): JSX.Element | null {
const { t } = useT()
// Mid-stream the closing fence may not have arrived, so the "code" so far is a partial the user
// should not be saving. (Belt-and-braces: the live bubble is never given a provider at all.)
const incomplete = useIsCodeFenceIncomplete()
if (incomplete) return null
// Distinct accessible names per block: the extension comes from the SHARED allowlist, so the
// label can never promise an extension main would not use.
const saveTitle = t('chat.code.saveTitle', { ext: codeBlockExtension(language) })
const copyTitle = t('chat.code.copyTitle')
return (
<div className="code-block-actions">
<button
type="button"
className="msg-action"
title={copyTitle}
aria-label={copyTitle}
onClick={() => actions.onCopy(content)}
>
{t('chat.code.copy')}
</button>
<button
type="button"
className="msg-action"
title={saveTitle}
aria-label={saveTitle}
onClick={() => actions.onSave(content, language)}
>
{t('chat.code.save')}
</button>
</div>
)
}
/**
* `pre` override. With NO CodeBlockActions in context this is byte-for-byte Streamdown's default
* (clone the child with the `data-block` stamp) — so every non-transcript consumer, inline code,
* and the live streaming bubble keep the exact DOM they had before #286.
*/
function CodeBlockPre({ children }: { children?: ReactNode }): JSX.Element {
const actions = useCodeBlockActions()
if (!isValidElement(children)) return <>{children}</>
const child = cloneElement(children as ReactElement<Record<string, unknown>>, {
'data-block': 'true'
})
if (actions === null) return <>{child}</>
const { content, language } = readCodeChild(children)
return (
<div className="code-block">
{child}
<CodeBlockToolbar actions={actions} content={content} language={language} />
</div>
)
}
// Streamdown's link-safety modal is off (see the `a` override). Module-level for the same reason as
// `mdComponents`: Streamdown puts this object in the context its code blocks, tables and images
// read, so a fresh `{ enabled: false }` per render re-rendered those inside blocks already closed on
// every flush (#685; scripts/bench-markdown-flush.mjs streams 80 blocks in ~750 ms, not 1,160).
const mdLinkSafety = { enabled: false }
// Module-level so the reference is stable across every render — defining this inline in JSX would
// hand Streamdown a fresh `components` object on each ~40 ms flush, busting the block memoization
// that makes the live bubble O(n) instead of O(n²) (the whole point of FE-1 revisited).
const mdComponents = {
// #286: the Copy/Save toolbar wrapper (a no-op passthrough without the transcript's context).
pre: CodeBlockPre,
// Streamdown renders `**bold**` as a Tailwind-classed <span> (font-semibold). This app ships
// no Tailwind, so that span would be UNSTYLED — map it back to a semantic <strong> the
// existing `.md strong` CSS styles (and screen readers announce as emphasis). Every other
// markdown element already comes out semantic (<em>, <code>, <h1>, <li>, <table>, …).
strong: ({ children }: { children?: ReactNode }) => <strong>{children}</strong>,
// Whitelist http(s) only (audit L1): a model could emit a `javascript:`/`data:` href.
// rehype-sanitize strips those two, and the CSP + window-open handler block execution and
// navigation, but streamdown's schema lets `mailto:`, `tel:`, `streamdown:`, relative and
// fragment hrefs through, so for those this override is the only gate (#743). A disallowed
// href renders as inert text, not a link.
a: ({ href, children }: { href?: string; children?: ReactNode }) =>
isSafeHttpUrl(href) ? (
<a href={href} target="_blank" rel="noreferrer">
{children}
</a>
) : (
<span>{children}</span>
)
}
/**
* Assistant replies render as Markdown (GFM + KaTeX math) via Streamdown, a streaming-aware
* drop-in for react-markdown — local models emit Markdown and showing raw `**asterisks**` reads as
* broken output. Streamdown splits the text into blocks and memoizes each, and (when `streaming`)
* `parseIncompleteMarkdown` closes dangling syntax so the live bubble formats cleanly instead of
* flashing raw markers. It builds React elements (no innerHTML) and runs rehype-sanitize, so scripts
* and event handlers are stripped; with the strict CSP the no-injection posture holds. KaTeX's math
* output comes after sanitize, gated by KaTeX's `trust`, which stays off (DEP-7). Streamdown's
* own link-safety modal is disabled in favour of the existing posture: links are whitelisted to
* http(s) and open in the OS browser via the main process's window-open handler. Code-block controls
* are disabled (they ship Tailwind-styled chrome this app doesn't load). User turns stay plain text.
*/
export const AssistantMarkdown = memo(function AssistantMarkdown({
text,
streaming = false
}: {
text: string
/** Live bubble: parse incomplete markdown so partial syntax renders without flicker. */
streaming?: boolean
}): JSX.Element {
return (
<Streamdown
// Its own class on Streamdown's root, so styles.css can style every surface that renders
// this component, whatever wrapper the call site uses (#685, list item paragraphs).
className="assistant-md"
mode={streaming ? 'streaming' : 'static'}
parseIncompleteMarkdown={streaming}
remend={mdRemend}
plugins={mdPlugins}
rehypePlugins={mdRehypePlugins}
controls={false}
linkSafety={mdLinkSafety}
// streamdown 2.6 caps code blocks at 400 px and tables at 300 px, and relies on Tailwind's
// overflow utilities (not loaded here) to scroll the rest: a tall table drew over everything
// below it. 0 turns the caps off, so both grow with their content as before (#550).
codeBlockMaxHeight={0}
tableMaxHeight={0}
components={mdComponents}
>
{normalizeMathDelimiters(text)}
</Streamdown>
)
})
/** True only for absolute http(s) URLs — the one scheme allowed in rendered model links. */
function isSafeHttpUrl(href: string | undefined): boolean {
if (!href) return false
try {
const proto = new URL(href).protocol
return proto === 'http:' || proto === 'https:'
} catch {
// Not an absolute URL (relative/anchor/malformed) → not a safe external link.
return false
}
}