Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins
TypeScript ai-agentcoding-agentdesktop-appelectronglobali18nlocal-firstmcppipi-agentpi-desktoppluginsreactrusttypescript
fix(chat): copy rendered formulas as round-trippable TeX
KtzeAbyss5a74d3a8588e
diff --git a/apps/desktop/package.json b/apps/desktop/package.jsonindex 6b0089a05..176e7e057 100644--- a/apps/desktop/package.json+++ b/apps/desktop/package.json@@ -55,7 +55,6 @@"i18next": "^26.3.6","katex": "^0.16.47","lucide-react": "^1.31.0",- "marked": "^18.0.9","mermaid": "^11.16.1","pinyin-pro": "3.29.1","react": "^19.2.8",@@ -67,9 +66,11 @@"rehype-sanitize": "^6.0.0","remark-gfm": "^4.0.1","remark-math": "^6.0.0",+ "remark-parse": "^11.0.0","shiki": "^4.4.3","tailwindcss": "^4.3.3","typescript": "^5.9.3",+ "unified": "^11.0.5","vite": "^7.3.6","ws": "8.21.1","zustand": "^5.0.15"diff --git a/apps/desktop/src/components/ContextMenu.tsx b/apps/desktop/src/components/ContextMenu.tsxindex 748d9abd3..85f546c0f 100644--- a/apps/desktop/src/components/ContextMenu.tsx+++ b/apps/desktop/src/components/ContextMenu.tsx@@ -33,6 +33,7 @@ import {type ContextMenuPlacement,type ContextMenuPoint,} from "../lib/context-menu";+import { texClipboardPayload } from "../lib/selection-tex";export type ContextMenuItem = {/** Stable identity for React keys and for tests naming a row. */@@ -83,6 +84,13 @@ function pointForEvent(event: ReactMouseEvent<HTMLElement>): ContextMenuPoint {* A selection in the composer or another row is not "this turn's excerpt".* Anchor or focus inside the right-clicked node is enough: a range that* starts in this row still belongs to Copy here.+ *+ * `useCopyTex` has no counterpart to this check, and the asymmetry is the+ * point: `root` is where the *user* aimed the pointer, which really can be a+ * row the selection never entered, while a `copy` event's target is derived+ * by the platform from the selection itself and so is always inside it. Do+ * not mirror this gate onto the copy listener — it rejects every range built+ * with `selectNodeContents`, this row's Copy item included.*/function snapshotSelection(root: EventTarget): string {// Textarea ranges are not represented by the document Selection.@@ -96,16 +104,51 @@ function snapshotSelection(root: EventTarget): string {}const live = window.getSelection();if (!live || live.rangeCount === 0 || live.isCollapsed) return "";- const text = live.toString();- if (!text || !(root instanceof Node)) return "";+ if (!(root instanceof Node)) return "";const { anchorNode, focusNode } = live;- if (+ const inside =(anchorNode && root.contains(anchorNode)) ||- (focusNode && root.contains(focusNode))- ) {- return text;- }- return "";+ (focusNode && root.contains(focusNode));+ if (!inside) return "";+ /*+ A formula reads as its TeX source here too: Copy and Ctrl+C must not put+ two different readings of the same selection on the clipboard (issue #414).+ Read after the row check, so a selection this row does not own is never+ serialized at all.++ Read *here*, while the menu is opening, and not from the Copy item's own+ `onSelect`, even though that would reduce only when the user asks for it.+ The menu focuses its first item a frame after it opens (the+ `requestAnimationFrame` in `ContextMenu` below) and that collapses the+ range, so by the time an item runs there is no selection left to read.+ Deferring would mean carrying a cloned `Range` across the gap, where it+ goes stale while a turn is still streaming — a new failure mode traded for+ one clone. That clone is bounded by `mayContainKatex`, so only a row that+ actually renders math pays for it, and it is paid inside the frame the+ menu already spends before it can take focus. Menus whose items ignore the+ selection (a link's, in `Markdown.tsx`) pay it too; an opt-in flag on+ `ContextMenuRequest` would spare them and is not worth the public field.++ Read without a `try`/`catch`, deliberately. The only fallback a catch+ could reach for is the `live.toString()` below, which is the duplicated+ glyph reading issue #414 exists about — so swallowing here would turn a+ defect in the reduction into a silently wrong clipboard, the one outcome+ this module was written to remove. `markdown-blocks.ts` degrades rather+ than throwing for the opposite reason, not the same one: it runs in a+ render memo under the app's single root `ErrorBoundary`, where a throw+ replaces the whole window.++ The price here is smaller but it is not nothing, and naming it is the+ point: `openContextMenu` has already called `preventDefault` by the time+ this runs and has not called `setState` yet, so a throw costs the user+ this one right-click — no menu of ours, and no platform menu behind it+ either, since nothing registers `webContents.on("context-menu")`. Paid+ knowingly. A silently wrong clipboard is the failure that outlives the+ gesture; a menu that has to be opened twice is not. Reordering the+ snapshot above `preventDefault` would not buy a fallback back, only move+ which nothing happens.+ */+ return texClipboardPayload(live) ?? live.toString();}export function useContextMenu() {diff --git a/apps/desktop/src/components/Markdown.tsx b/apps/desktop/src/components/Markdown.tsxindex 253829c8c..e725a46b4 100644--- a/apps/desktop/src/components/Markdown.tsx+++ b/apps/desktop/src/components/Markdown.tsx@@ -17,12 +17,14 @@ import {type ReactNode,} from "react";import ReactMarkdown, { type Components, type Options } from "react-markdown";-import remarkGfm from "remark-gfm";-import remarkMath from "remark-math";import rehypeKatex from "rehype-katex";import rehypeRaw from "rehype-raw";import rehypeSanitize, { defaultSchema } from "rehype-sanitize";-import { lexer } from "marked";+import {+ advanceMarkdownBlocks,+ emptyMarkdownBlockCache,+ markdownRemarkPlugins,+} from "../lib/markdown-blocks";import { useTranslation } from "react-i18next";import type { ThemedToken } from "shiki";import "katex/dist/katex.min.css";@@ -79,10 +81,12 @@ import {/** Streaming-optimized chat markdown renderer.*- * The source is split into top-level markdown blocks with marked's lexer and- * each block renders through a memoized <ReactMarkdown>. While streaming only- * the tail block's raw text changes, so every settled block skips re-parsing- * entirely — total work stays linear in message length instead of quadratic.+ * The source is split with the rendering grammar, and each block renders+ * through a memoized <ReactMarkdown>. Streaming re-parses the growing tail+ * while retaining the completed prefix; a long unclosed block still has to+ * be parsed in full until its boundary is known. A source carrying link or+ * footnote definitions opts out of splitting altogether — `markdown-blocks`+ * states why, and why that trade is the right one.*/export function useCopy() {@@ -717,7 +721,10 @@ const markdownComponents: Components = {table: Table,};-const staticRemarkPlugins = [remarkGfm, remarkMath, remarkLocalImagePaths];+// The grammar the block splitter parses with, plus the renderer-only rewrite+// of local image paths. `remarkLocalImagePaths` transforms URLs and moves no+// block boundary, so the splitter has no reason to run it.+const staticRemarkPlugins = [...markdownRemarkPlugins, remarkLocalImagePaths];// Extend the default schema only for the media elements rendered above, plus// `remark-math`'s math classes on `<code>`: the default `language-*` allow list@@ -745,58 +752,15 @@ const rehypePlugins = [rehypeRaw, [rehypeSanitize, sanitizeSchema], rehypeKatex]/* ---------- block splitting ---------- */-function parseBlocks(source: string): string[] {- const blocks: string[] = [];- let sourceOffset = 0;- const hasWindowsLines = source.includes("\r\n");- for (const token of lexer(source)) {- if (!token.raw) continue;- const start = sourceOffset;- // Marked normalizes CRLF before tokenizing. Preserve original slices so- // parser offsets and incremental block lengths still refer to stored text.- if (hasWindowsLines) {- for (let i = 0; i < token.raw.length; i++, sourceOffset++) {- if (source[sourceOffset] === "\r" && source[sourceOffset + 1] === "\n") sourceOffset++;- }- } else {- sourceOffset += token.raw.length;- }- const raw = source.slice(start, sourceOffset);- // Fold blank-line runs into the previous block so joining blocks- // reconstructs the source and block boundaries stay append-stable.- if (token.type === "space" && blocks.length > 0) {- blocks[blocks.length - 1] += raw;- } else {- blocks.push(raw);- }- }- return blocks;-}-/*- * Incremental re-lex: while streaming appends text, all blocks before the- * last are settled (markdown blocks never merge backwards across a completed- * boundary), so only the tail block is re-lexed each frame.+ * Splitting and its streaming reuse live in `markdown-blocks`, which owns the+ * rules a slice has to satisfy before it can be parsed on its own.*/function useBlocks(source: string): string[] {- const cacheRef = useRef({ consumed: "", blocks: [] as string[] });+ const cacheRef = useRef(emptyMarkdownBlockCache);return useMemo(() => {- const cache = cacheRef.current;- let stable: string[] = [];- let tail = source;- if (- cache.blocks.length > 0 &&- source.length >= cache.consumed.length &&- source.startsWith(cache.consumed)- ) {- stable = cache.blocks.slice(0, -1);- const lastStart =- cache.consumed.length - cache.blocks[cache.blocks.length - 1].length;- tail = source.slice(lastStart);- }- const blocks = tail ? [...stable, ...parseBlocks(tail)] : stable;- cacheRef.current = { consumed: source, blocks };- return blocks;+ cacheRef.current = advanceMarkdownBlocks(cacheRef.current, source);+ return cacheRef.current.blocks;}, [source]);}@@ -861,15 +825,9 @@ export const Markdown = memo(function Markdown({baseDir?: string;}) {const workspaceRoot = useAppStore((s) => s.workspace?.path);- // Normalize once at the source level: marked's block lexer runs on the raw- // text and would otherwise split `\[ … \]` display math whose body puts a- // lone `=`/`-` (setext underline) or `+`/`*` (list marker) on its own line,- // stranding `\[` and `\]` in different blocks so the delimiters escape as- // literal `[`/`]`. The normalizer both rewrites the delimiters to `$$` and- // flattens newlines inside every paired region, keeping the whole formula- // inside a single markdown block. The rewrite is length-preserving, so we- // can still slice the original text at the same offsets for downstream- // plugins that need the pre-normalized delimiters.+ // Keep normalization length-preserving so source anchors and the bracket+ // display plugin still address the original text. Block splitting uses the+ // same math grammar as rendering, including unclosed streaming math blocks.const normalizedSource = useMemo(() => normalizeLatexMathDelimiters(source),[source],diff --git a/apps/desktop/src/features/app/AppShell.tsx b/apps/desktop/src/features/app/AppShell.tsxindex 54ba0aaee..20f203454 100644--- a/apps/desktop/src/features/app/AppShell.tsx+++ b/apps/desktop/src/features/app/AppShell.tsx@@ -16,6 +16,7 @@ import { cx, TooltipButton } from "../../components/ui";import { StartupRecovery } from "../../components/StartupRecovery";import { WindowControls } from "../../components/WindowControls";import { WorkPanel } from "../../components/workpanel/WorkPanel";+import { useCopyTex } from "../../hooks/use-copy-tex";import { api } from "../../lib/api";import { CollapsedTitlebarActions, RoutePending } from "./chrome";import { useAppShellRuntime } from "./useAppShellRuntime";@@ -87,6 +88,7 @@ export function AppShell() {sidebarToggleShortcut,workPanelToggleTooltip,} = useAppShellRuntime();+ useCopyTex();// A boot that never reaches the shell gets a surface it can act on instead of// a window that only knows how to wait (issue #831). Rendered as a direct childdiff --git a/apps/desktop/src/hooks/use-copy-tex.ts b/apps/desktop/src/hooks/use-copy-tex.tsnew file mode 100644index 000000000..db52be07e--- /dev/null+++ b/apps/desktop/src/hooks/use-copy-tex.ts@@ -0,0 +1,56 @@+import { useEffect } from "react";+import { texClipboardPayload } from "../lib/selection-tex";++/**+ * Ctrl/Cmd+C over a rendered formula puts its TeX source on the clipboard+ * (issue #414, D618).+ *+ * The listener is on the document because `Markdown` renders no wrapper of its+ * own — answers, a work-panel file preview, and a plugin readme all reach the+ * same formulas through different parents — and because a copy is a document+ * gesture: it is raised wherever the selection is, not where a component+ * happens to be mounted. One listener for the window, installed by the shell+ * and removed with it.+ *+ * It declines exactly one thing — a selection with no formula in it — and+ * deliberately does not ask whether the copy "belongs to" that selection.+ * Chromium derives the event target *from* the selection: it walks the+ * canonicalized start position up to its element, so a non-collapsed+ * selection always raises its copy somewhere inside itself and there is+ * nothing left to check. A `target.contains(anchorNode)` gate only ever+ * misfires, because a `Range` built with `selectNodeContents` leaves+ * `anchorNode` on the element the range was built from while the event lands+ * on a descendant — and that is precisely the range the transcript's own+ * "Select text" item creates, so the gate rejected the app's own copy path+ * and handed the user KaTeX's glyphs back.+ *+ * The case such a gate looks like it is for — a copy raised in the composer+ * while an earlier transcript selection is still on the page — cannot occur:+ * a frame carries one selection, so focusing any field collapses the document+ * selection, and `texClipboardPayload` already declines a collapsed one.+ * `ContextMenu`'s `snapshotSelection` keeps its own row check and is not the+ * same question; see the note there before mirroring either way.+ *+ * `copy` only, and no `cut`: a cut is raised over editable content, and no+ * editable surface here renders math — the composer paints draft text and+ * file chips, never a formula.+ */+export function useCopyTex(): void {+ useEffect(() => {+ const onCopy = (event: ClipboardEvent) => {+ const clipboard = event.clipboardData;+ if (!clipboard) return;+ const text = texClipboardPayload(window.getSelection());+ if (!text) return;+ /*+ `text/plain` alone, on purpose: taking the event over drops the+ platform's `text/html` as well, and `texClipboardPayload` explains why+ none is written back. A rich paste target falls back to this string.+ */+ clipboard.setData("text/plain", text);+ event.preventDefault();+ };+ document.addEventListener("copy", onCopy);+ return () => document.removeEventListener("copy", onCopy);+ }, []);+}diff --git a/apps/desktop/src/lib/latex-math.ts b/apps/desktop/src/lib/latex-math.tsindex 5eece851c..2c179897e 100644--- a/apps/desktop/src/lib/latex-math.ts+++ b/apps/desktop/src/lib/latex-math.ts@@ -56,13 +56,10 @@ export function normalizeLatexMathDelimiters(source: string): string {if (isDelimiter(index, math.close)) {output[math.open] = output[math.open + 1] = "$";output[index] = output[index + 1] = "$";- // Marked lexes the raw source before remark-math sees it, so any- // newline inside a `\[ … \]` block that is followed by a lone `=`,- // `-`, `+` or `*` line collapses the display math into a setext- // heading or a list item and splits `\[` from `\]` across blocks.- // KaTeX treats intra-formula whitespace the same, so replacing the- // paired region's newlines with spaces keeps the math in one block- // without changing what KaTeX renders.+ // Retain the historical single-line bracket representation and+ // source offsets. Dollar-fenced math bypasses this normalization+ // and preserves its newlines; block splitting must use the math+ // grammar rather than relying on flattened input.for (let j = math.open + 2; j < index; j++) {if (output[j] === "\n") output[j] = " ";}diff --git a/apps/desktop/src/lib/markdown-blocks.ts b/apps/desktop/src/lib/markdown-blocks.tsnew file mode 100644index 000000000..a46668839--- /dev/null+++ b/apps/desktop/src/lib/markdown-blocks.ts@@ -0,0 +1,193 @@+import { unified } from "unified";+import remarkParse from "remark-parse";+import remarkGfm from "remark-gfm";+import remarkMath from "remark-math";++// Share the grammar with ReactMarkdown. A different block lexer can split a+// valid math node at a list, quote, heading, or blank line inside its TeX.+//+// "Share" is literal and rests on deduplication: `react-markdown` depends on+// `remark-parse`/`unified` itself, and the ranges in `package.json` are kept+// wide enough to overlap its own so the installer resolves one copy for both.+// Pinning either exactly is the one way to break that — the renderer's range+// still floats, and the two would then parse blocks by different grammars+// while every test keeps passing, which is the defect this module exists to+// remove. If `react-markdown` ever moves to a new major of either, follow it+// rather than holding this one back.+//+// The parse costs more per byte than the `marked` lexer it replaces, and the+// cost lands on the render path. It is not the frame's dominant term: normal+// multi-block streaming re-parses only a short tail (~0.1 ms/frame), and the+// one shape whose tail is the whole message — a single long unclosed fence —+// measures ~2.4 ms/frame at 46 KB, on top of the full parse ReactMarkdown+// already runs over that same tail each frame. The quadratic shape belongs to+// incremental splitting itself and predates this parser.+//+// Guarding the tail parse behind a cheap "could this append have opened a+// boundary?" test is refused rather than merely unwritten: such a test is a+// second block grammar, and a second block grammar disagreeing with the+// renderer's is the defect this module exists to remove. Throttling streaming+// renders, or reading boundaries from micromark's own events, would cut the+// cost without buying it back.+export const markdownRemarkPlugins = [remarkGfm, remarkMath];+const parser = unified().use(remarkParse).use(markdownRemarkPlugins);++export type MarkdownBlockSplit = {+ /** Source slices that concatenate back to the input. */+ blocks: string[];+ /**+ * The source declares a link or footnote definition, so its slices cannot+ * be parsed independently of each other. See `advanceMarkdownBlocks`.+ */+ hasDocumentScopedDefinition: boolean;+};++/*+ * A definition resolves across the whole document rather than inside its own+ * container: `> [ref]: /url` in a quote still defines `[ref]` for a later+ * paragraph. The search descends for that reason instead of reading the top+ * level, where such a definition never appears as a child.+ */+function declaresDefinition(node: unknown): boolean {+ if (node === null || typeof node !== "object") return false;+ const { type, children } = node as { type?: unknown; children?: unknown };+ if (type === "definition" || type === "footnoteDefinition") return true;+ return Array.isArray(children) && children.some(declaresDefinition);+}++export function parseMarkdownBlocks(source: string): MarkdownBlockSplit {+ if (!source) return { blocks: [], hasDocumentScopedDefinition: false };+ const root = parser.parse(source);+ const blocks: string[] = [];+ let start = 0;+ for (const node of root.children.slice(1)) {+ const nodeStart = node.position?.start.offset;+ if (nodeStart === undefined) {+ // `remark-parse` positions everything it produces, and only a plugin+ // that synthesizes a node can leave the offset out — which is why mdast+ // keeps `position` optional at all. Unreachable for the parser-level+ // plugins above, and handled anyway for what it would cost: this runs+ // in `Markdown`'s render memo, under the app's single root+ // `ErrorBoundary`, so a throw here replaces the whole window. An+ // undivided source renders identically and only gives up per-block+ // memoization — the same cost `advanceMarkdownBlocks` already accepts+ // for a definition — so degrading is strictly better than failing.+ console.warn("Markdown block has no source offset; rendering undivided");+ return {+ blocks: [source],+ hasDocumentScopedDefinition: declaresDefinition(root),+ };+ }+ // Slice the original bytes, including CRLF and inter-block whitespace.+ // Attaching whitespace to the preceding block keeps source anchors and+ // the streaming tail's start aligned without serializing the AST again.+ //+ // Cut at the line start rather than at `nodeStart`: the grammar is+ // line-based, so a block owns the indentation before its first character+ // while `position.start` points past it. A slice that loses those columns+ // re-parses as a different block — two items indented by two spaces become+ // a nested list, and an indented fence keeps the indent inside its code. No+ // two top-level blocks begin on the same line, so the span skipped here is+ // whitespace and the slices still concatenate back to the source.+ const end = source.lastIndexOf("\n", nodeStart - 1) + 1;+ blocks.push(source.slice(start, end));+ start = end;+ }+ blocks.push(source.slice(start));+ return { blocks, hasDocumentScopedDefinition: declaresDefinition(root) };+}++export type MarkdownBlockCache = {+ /** Source the cached blocks were produced from. */+ consumed: string;+ blocks: string[];+ /** The cached blocks are the whole source, kept undivided on purpose. */+ singleUnit: boolean;+};++export const emptyMarkdownBlockCache: MarkdownBlockCache = {+ consumed: "",+ blocks: [],+ singleUnit: false,+};++/*+ * Split `source` for rendering, reusing what `cache` already settled.+ *+ * A slice may be handed to its own parser only when it needs no other slice's+ * parse context. Definitions break that: they resolve document-wide, and+ * footnotes additionally carry document-wide numbering, reuse and back-links.+ * A source that declares one therefore stays undivided. Copying definitions+ * into every slice is no substitute — it renumbers footnotes per slice and+ * aims the back-links at the wrong reference, and even for a plain link+ * definition, where no numbering is at stake, it breaks the property every+ * caller relies on: the slices concatenate back to the source, which is what+ * keeps each block's `data-source-*` offsets pointing at real bytes.+ *+ * The cost is accepted, not overlooked, and it is a cost rather than a+ * limitation carried over: marked's lexer did split these sources, so this+ * gives that split up on purpose. Such a source loses per-slice memoization+ * and re-parses in full on every streaming frame, the way the renderer did+ * before it split blocks at all, and the frame that collapses N slices into+ * one remounts them, re-rendering Mermaid, Shiki and KaTeX. What the old+ * split bought was speed on a wrong rendering: definitions are rare in chat+ * answers, and a reference that survives as a literal `[^1]` is wrong at any+ * frequency.+ *+ * Rare is measured against the grammar rather than against the shape of the+ * line, which is most of the answer to "but surely ordinary prose trips+ * this". A definition needs its destination to end the line bar an optional+ * quoted or parenthesised title, so a glossary line reading+ * `[API]: Application Programming Interface` is a paragraph — those trailing+ * words are not a valid title. What reaches this branch is a real+ * reference-style link or footnote, which is the case the branch is for.+ *+ * Streaming keeps the settled prefix and re-parses only the tail, which still+ * observes every definition: a block only ever comes into existence through a+ * tail parse, so a definition anywhere in the source was seen by the parse+ * that first produced its block, and `singleUnit` latches that observation for+ * the rest of the append run. The latch is one-way by choice, not because a+ * definition is permanent: appending to a definition's own line can take it+ * back — `[spec]: /url` continued into `[spec]: /url is the reference.` is a+ * plain paragraph — and such a source stays undivided for the rest of the run+ * anyway. Undivided is always a correct rendering, so a stale latch costs+ * speed and never output, while re-deciding would parse the whole source on+ * every frame to win a split back for a message that read like a definition+ * once. A source that stops extending the cached one is an edit rather than an+ * append, and decides again from a full parse.+ *+ * Splitting an undivided source is still wrong for raw HTML that wraps+ * blank-line-separated Markdown (`<div>` … `</div>`), whose tags land in+ * different slices unbalanced. That is not a definition problem, it predates+ * this splitter — marked's lexer separated those tags the same way — and it+ * is deliberately left alone here.+ */+export function advanceMarkdownBlocks(+ cache: MarkdownBlockCache,+ source: string,+): MarkdownBlockCache {+ const appended =+ cache.blocks.length > 0 &&+ source.length >= cache.consumed.length &&+ source.startsWith(cache.consumed);+ // Latched one-way; see above for why a stale latch costs speed, not output.+ if (appended && cache.singleUnit) {+ return { consumed: source, blocks: [source], singleUnit: true };+ }+ let stable: string[] = [];+ let tail = source;+ if (appended) {+ stable = cache.blocks.slice(0, -1);+ const lastStart =+ cache.consumed.length - cache.blocks[cache.blocks.length - 1].length;+ tail = source.slice(lastStart);+ }+ // An unclosed math fence owns its entire body, including blank lines, so no+ // interior list or quote is mistaken for a completed streaming boundary.+ const split = tail+ ? parseMarkdownBlocks(tail)+ : { blocks: [], hasDocumentScopedDefinition: false };+ const singleUnit = split.hasDocumentScopedDefinition;+ const blocks = singleUnit ? [source] : [...stable, ...split.blocks];+ return { consumed: source, blocks, singleUnit };+}diff --git a/apps/desktop/src/lib/selection-tex.ts b/apps/desktop/src/lib/selection-tex.tsnew file mode 100644index 000000000..8f349f2fc--- /dev/null+++ b/apps/desktop/src/lib/selection-tex.ts@@ -0,0 +1,518 @@+/**+ * The clipboard reading of a rendered selection that contains math.+ *+ * KaTeX paints one formula twice — a MathML tree for assistive technology and+ * a visual tree of positioned spans — and both are real text in the document.+ * The platform's own copy therefore writes a formula out as its glyphs, twice+ * over, and never as the source the answer was written in (issue #414). The+ * TeX the formula was built from is already in the document, in the MathML+ * `annotation`, so a selection that covers a formula is read from the+ * annotation instead of from the rendering.+ *+ * Only the formulas are rewritten. The prose, lists, tables and code blocks+ * around them are serialized by the platform itself — the reduced clone is+ * selected and read back through `Selection.toString()`, which is the+ * serializer a copy runs — so the rest of a selection that happens to contain+ * a formula keeps its browser reading except for the one syntax this module+ * makes load-bearing: touching fences are separated, and every dollar outside+ * a formula is escaped so it cannot pair with a fence written here — code+ * blocks included, because the serializer has already dropped their fences+ * and what reaches the clipboard from one is prose (see `renderedText`).+ * A hand-written walk of the tree+ * could only approximate those rules, and everywhere it fell short it would+ * silently rewrite content the platform already got right.+ *+ * ADR 0268 removed the selection overlay and the Quote action and rested that+ * removal on the OS clipboard being the substitute for quoting. This is that+ * substitute made honest, and nothing more: no surface, no store state, no+ * action-row item, and no new way to reach the clipboard. The copy the user+ * already performs writes different bytes when, and only when, the selection+ * contains a formula.+ *+ * The delimiters are the renderer's own: `lib/latex-math.ts` normalizes+ * `\(…\)` and `\[…\]` to `$…$` / `$$…$$` before `remark-math` runs, so a+ * formula copied out of an answer renders as that same formula when it is+ * pasted back into the composer.+ */++/** KaTeX keeps the TeX it rendered in this MathML annotation. */+export const KATEX_TEX_SELECTOR = 'annotation[encoding="application/x-tex"]';+/** One rendered formula, whichever of its two trees a node sits in. */+export const KATEX_SELECTOR = ".katex";+/** The wrapper KaTeX puts around a display formula. */+export const KATEX_DISPLAY_SELECTOR = ".katex-display";+/** The MathML tree, hidden by KaTeX's own stylesheet and by nothing else. */+const KATEX_MATHML_SELECTOR = ".katex-mathml";+/** The outermost element of a formula a range boundary landed inside. */+const KATEX_BOUNDARY_SELECTOR = `${KATEX_DISPLAY_SELECTOR}, ${KATEX_SELECTOR}`;++/* ---------- pure helpers ---------- */++/**+ * Inline math stays inside its line; display math takes a line of its own,+ * because a `$$` line is what opens a flow math block.+ *+ * Inline is the *narrow* run, `$…$`, even though `normalizeLatexMathDelimiters`+ * rewrites `\(…\)` to `$$…$$` — that form is forced on it by being+ * length-preserving, not chosen. The reason is not that a pasted sentence might+ * start a line with the formula: a single-line `$$…$$` never opens a display+ * block, because math flow forbids `$` in the meta that follows its opening+ * fence, so `$$x^2$$ here.` and even a bare `$$x^2$$` line both parse as text+ * math. The reason is that an inline formula's TeX can carry a newline —+ * `$a +\nb$` parses, and only the `\(…\)` path has its newlines flattened by+ * the normalization — and a `$$` run then lands at the start of a line with the+ * rest of the formula behind it, which *is* a flow opening and swallows the+ * paragraph. `$…$` spans the line ending instead, which is also why `texSlot`+ * needs `white-space: pre` for inline math and not only for display.+ *+ * The run is widened past any run inside the formula, which is the escalation+ * rule markdown already uses for code spans: `$\$5 + x$` closes at the escaped+ * dollar and pastes back as prose, while `$$\$5 + x$$` reads whole. Display+ * keeps a floor of two. The measure is the longest run anywhere in the formula+ * rather than a line-initial one, which over-widens a display fence that could+ * not have been closed early — cheaper than restating where a flow fence may+ * appear, and invisible to every formula that carries no `$` at all, which is+ * written exactly as it was before this rule existed.+ */+export function texSource(tex: string, display: boolean): string {+ const inner = Math.max(+ 0,+ ...Array.from(tex.matchAll(/\$+/g), (run) => run[0].length),+ );+ const fence = "$".repeat(Math.max(display ? 2 : 1, inner + 1));+ if (display) return `${fence}\n${tex}\n${fence}`;+ // remark-math drops one space *or line ending* from each end of a run that+ // has data between them. Pad wherever it would, so the drop lands on padding+ // written here instead of on the formula. A dollar at either edge takes the+ // same padding for a different reason: without it that dollar lengthens the+ // fence. "Data" is the grammar's own test — anything that is neither a space+ // nor a line ending — and not `trim()`, which reads a tab as whitespace+ // where the grammar reads it as data.+ const padded =+ /^[ \r\n]/.test(tex) && /[ \r\n]$/.test(tex) && /[^ \r\n]/.test(tex);+ const pad = padded || tex.startsWith("$") || tex.endsWith("$");+ const source = `${fence}${pad ? ` ${tex} ` : tex}${fence}`;+ // Copying just the formula can move a widened fence to column zero, where+ // a newline makes it a flow opener. Keep an explicit inline context rather+ // than flattening TeX: a newline can terminate a % comment. This is literal+ // Markdown source, not a rich-clipboard HTML flavour.+ //+ // The test is formula-local, so it also wraps a formula the payload puts+ // mid-sentence, where that fence never reaches column zero and the tag is+ // pure noise — in a non-Markdown paste target, and in this app's own+ // composer, where it survives the round trip into the message the model is+ // sent. Deliberate: only `renderedText`+ // knows where a slot lands once the parts are joined, and reaching back into+ // this decision from there would couple the two for a shape that has to be+ // authored to exist at all — inline math carrying *both* a literal `$` and a+ // newline, which means a hand-written `$$…$$` run, since a single-dollar run+ // closes at the first inner dollar and the `\(…\)` path has its newlines+ // flattened by the normalization.+ //+ // The closing run is left unguarded, and not because it cannot reach column+ // zero: it does, whenever that same TeX also *ends* with a newline. Such a+ // formula cannot be written down on its own. Its source closed the same way,+ // on a line opening with `$$`, and only stayed inline because a later dollar+ // on that line spoiled the flow fence's meta — copying the formula alone+ // takes that neighbour away, and no padding brings it back, since a fence+ // still opens under three spaces of indent and a fourth would fall inside+ // the math. A bound on the round trip, not a repair this module can make.+ return fence.length > 1 && /[\r\n]/.test(tex)+ ? `<span>${source}</span>`+ : source;+}++/* ---------- DOM reduction ---------- */++/**+ * What a formula becomes before the platform serializes the clone.+ *+ * `white-space: pre` because a bare text node would have the newlines inside+ * `$$ … $$` collapsed away like any other source whitespace, and a block slot+ * for display math because that is how it earns its own lines — both out of+ * the same rules that give the surrounding prose its breaks, rather than out+ * of newlines written into the text by hand.+ *+ * A paragraph, not a bare block: the serializer gives `p` a blank line on each+ * side and a `div` only a single break, so a `div` slot pastes back as+ * `$$ … $$\nLast paragraph.`, which reads as one run-on block.+ *+ * Display math is not always block-level here, and the slot is deliberately+ * left alone when it is not. `\[ … \]` is rewritten to `$$ … $$` in place —+ * the normalization is length-preserving — so `remarkLatexBracketDisplay`+ * promotes an *inline* math node and KaTeX paints `.katex-display` inside the+ * sentence's own `<p>`; the slot is then a `p` nested in a `p`, which is+ * invalid as markup and harmless here, because the clone is never serialized+ * as HTML (see `texClipboardPayload`) and only ever read through the text+ * serializer. That reading treats the nested block as one boundary and yields+ * `The result\n$$\nE = mc^2\n$$\n\ncloses the proof.` — a single newline above+ * `$$` is enough for `remark-math` to open the display block, so the formula+ * pastes back as the display formula it came from. Both `\[ … \]` shapes are+ * covered by E2E-CHAT-copy-formula-as-tex; do not "fix" the nesting without+ * re-running it.+ *+ * The block slot survives a table cell, which the grammar argues it should not+ * and which is therefore measured rather than reasoned about. The same+ * promotion puts `.katex-display` inside a `<td>`, and the table serializer+ * joins cells with tabs, so a `$$` fence there looks like it would be closed+ * by the tab after it and swallow the rest of the row —+ * `a\tb\n$$\nE = mc^2\n$$\t2` is one math node whose value runs to the end of+ * the line. Chromium writes no such string: a block box is a block boundary in+ * a cell too, the row breaks around it, and the fence closes on its own line.+ * Nor is the slot inventing that boundary, which is the half that decides it —+ * the platform's own reading of the same row carries no tab either, because+ * `.katex-display` breaks the row for it as well. Narrowing to the inline run+ * inside a cell would pay display math to repair a shape the serializer does+ * not produce, and would write a tab back that the platform does not. Both the+ * reading and the platform's parity are asserted by the `tableDisplay` case in+ * `scripts/e2e/copy-tex.tsx`, so a serializer that started tab-joining a cell+ * holding a block fails there rather than in a clipboard.+ */+function texSlot(tex: string, display: boolean, doc: Document): HTMLElement {+ const slot = doc.createElement(display ? "p" : "span");+ slot.style.whiteSpace = "pre";+ slot.textContent = texSource(tex, display);+ return slot;+}++/**+ * A formula is one unit: its MathML tree and its visual tree are two+ * renderings of the same source, and keeping both duplicates the expression.+ *+ * KaTeX paints one `.katex` per formula and never nests them, so the static+ * list this walks cannot hold an element an earlier replacement detached.+ */+function replaceKatex(wrapper: Element, doc: Document): HTMLElement[] {+ const slots: HTMLElement[] = [];+ for (const katex of Array.from(wrapper.querySelectorAll(KATEX_SELECTOR))) {+ const tex = katex.querySelector(KATEX_TEX_SELECTOR)?.textContent;+ if (!tex?.trim()) {+ // Valid KaTeX always carries the annotation. Without it the formula+ // degrades to its visual tree alone rather than to the same expression+ // twice over: the MathML tree is hidden by a stylesheet, and no+ // stylesheet travels on the clipboard.+ katex.querySelector(KATEX_MATHML_SELECTOR)?.remove();+ continue;+ }+ const display = katex.closest(KATEX_DISPLAY_SELECTOR);+ // Preserve annotation whitespace: it may separate a literal dollar from+ // the closing fence. The emptiness check above must not normalize it.+ const slot = texSlot(tex, Boolean(display), doc);+ (display ?? katex).replaceWith(slot);+ slots.push(slot);+ }+ return slots;+}++/**+ * Expand a range that starts or ends inside a formula to the whole formula:+ * half a TeX expression is not a formula, and a cut between KaTeX's two trees+ * would take the source from one and the glyphs from the other. A display+ * formula carries its wrapper out with it, because that wrapper is what tells+ * the reduction it is a display one. Both boundaries only ever move outwards,+ * never inwards, so the expansion cannot drop content the range covered.+ *+ * Only the boundary containers are consulted, not the offsets, and that is a+ * decision rather than an oversight. A boundary that names a node inside a+ * formula while pointing at its very edge — `(firstGlyphTextNode, 0)` for a+ * range that stopped just short of the formula — does grow over that formula,+ * so such a copy carries one formula the selection did not cover. It is left+ * that way because the result is still a whole formula, which is the unit this+ * function exists to keep intact, and because Chromium canonicalizes selection+ * boundaries into text positions: pointer drags, keyboard extension and+ * `selectNodeContents` on a row all land inside a text node or on the row+ * itself. Reading the offsets would add a branch only a hand-built `Range`+ * reaches, to trade an over-inclusive copy for a half-formula one.+ */+function expandRangeToWholeKatex(range: Range): Range {+ const expanded = range.cloneRange();+ const boundaryFor = (node: Node | null): Element | null => {+ const element =+ node?.nodeType === 1 ? (node as Element) : (node?.parentElement ?? null);+ const katex = element?.closest?.(KATEX_BOUNDARY_SELECTOR) ?? null;+ return katex?.closest?.(KATEX_DISPLAY_SELECTOR) ?? katex;+ };+ const start = boundaryFor(expanded.startContainer);+ const end = boundaryFor(expanded.endContainer);+ if (start) expanded.setStartBefore(start);+ if (end) expanded.setEndAfter(end);+ return expanded;+}++/**+ * The platform's own reading of the reduced clone.+ *+ * The clone is selected and read back through `Selection.toString()` because+ * that is the serializer a copy actually runs, so the reduced selection is+ * read by the same code that read the original one: source line breaks+ * collapsed to spaces, `pre` kept byte for byte, one line per list item, tabs+ * between cells — and chrome the app marked `user-select: none` dropped.+ * `innerText` looks like the same reading and is not: it has no notion of+ * `user-select`, so it writes out the code block's language rail and the+ * action rows that `base.css` marks inert precisely so a copy leaves them+ * behind. Restating that rule here instead would be the hand-written walk this+ * module exists to avoid; running the platform's own serializer costs one+ * range and makes the parity exact rather than approximate.+ *+ * The reading needs layout, so the clone is attached off screen rather than+ * hidden — and attached inside the element the selection already lived in,+ * because for this serializer the cascade *is* the reading. `cloneContents`+ * keeps every ancestor below the range's common ancestor; mounting there+ * supplies the rest, so each ancestor-scoped rule resolves exactly as it did+ * live. That matters most for the one rule this module leans on: `base.css`+ * makes `html, body, #root` unselectable and has document-like surfaces opt+ * back in, so a clone parked on `body` reads back as the code blocks alone,+ * with every paragraph dropped. Restating the opt-in on the clone instead —+ * an inline `user-select: text` — looks like the cure and inverts the+ * contract: the default flips to selectable, and chrome that is inert only by+ * inheritance (a tool row's section head, a compact thinking row) arrives in+ * the clipboard. Borrowing the real ancestors settles both directions at once,+ * and does it without a second, duplicate-`id` copy of the chain under `body`.+ *+ * The wrapper is one element level the live tree does not have, so a rule+ * reaching the clone's top level through `>` or `:nth-child` misses it. Left+ * alone rather than engineered around, and on a fact rather than a law: the+ * reading turns on `display`, `white-space`, `visibility` and `user-select`,+ * and no rule in the app selects a direct child of a selection's common+ * ancestor to set one of them — the app's child combinators sit on chrome,+ * menus, settings and the composer, none of which renders a formula or reaches+ * this path. A rule that changed that would move one of the paragraph, list,+ * table or code readings in E2E-CHAT-copy-formula-as-tex, which is the guard;+ * rebuilding the ancestor chain to close the gap would trade it for a+ * duplicate-`id` clone and is not worth it. Mounting inside a React-rendered+ * parent is safe for the+ * same reason the swap below is: the node is added and removed inside one+ * synchronous task, so no render and no frame observes it, React does not+ * watch the DOM, and a `MutationObserver` sees the addition and the removal+ * together. `position: fixed` under a `transform`/`filter` ancestor only+ * changes which box it is fixed to, and an `overflow` ancestor only clips;+ * neither reaches the text serializer.+ *+ * The live selection is restored before returning, anchor and focus each to+ * the end it came from; the one `selectionchange` listener in the app+ * (`useComposerDraft`) ignores anchors outside the composer, and the event is+ * queued rather than dispatched mid-swap, so nothing observes the intermediate+ * state.+ */+function renderedText(+ wrapper: HTMLElement,+ host: Element,+ slots: HTMLElement[],+): string {+ const doc = host.ownerDocument;+ wrapper.style.cssText = "position:fixed;left:-99999px;top:0";+ host.append(wrapper);+ const selection = doc.defaultView?.getSelection() ?? null;+ /*+ Anchor and focus, not `getRangeAt(0)`: a range remembers where a selection+ starts and ends but not which end the user is holding, so restoring one+ through `addRange` turns every backward selection forward and sends the+ next Shift+Arrow off the opposite edge.+ */+ const restore =+ selection?.anchorNode && selection.focusNode+ ? ([+ selection.anchorNode,+ selection.anchorOffset,+ selection.focusNode,+ selection.focusOffset,+ ] as const)+ : null;+ try {+ // No view means no layout, and a reading taken without layout is the+ // whitespace-collapsing one this module must not produce. Returning ""+ // leaves the copy to the platform instead of writing a worse one.+ if (!selection) return "";+ // Preserve formula identity until after the browser has serialized the+ // selection. DOM siblings are not text neighbours: formatting vanishes,+ // inert chrome is omitted, and block boundaries contribute whitespace.+ // A fresh opaque marker avoids confusing formula slots with user text,+ // even when hidden nodes disappear between pieces of that text.+ const marker = `copy-tex:${crypto.randomUUID()}:`;+ const sources = slots.map((slot, index) => {+ const source = slot.textContent ?? "";+ slot.textContent = `${marker}${index}${marker}`;+ return source;+ });+ const range = doc.createRange();+ range.selectNodeContents(wrapper);+ selection.removeAllRanges();+ selection.addRange(range);+ const escape = (run: string) => run.replace(/[\\$]/g, "\\$&");+ const parts = selection.toString().split(new RegExp(`${marker}(\\d+)${marker}`));+ if (parts.length === 1) return parts[0];+ return parts.map((part, index) => {+ if (index % 2) {+ const source = sources[Number(part)];+ // Two inline fences need one separator after formatting is removed.+ const touchesFence =+ index > 1 && !parts[index - 1] &&+ sources[Number(parts[index - 2])].endsWith("$") &&+ source.startsWith("$");+ return (touchesFence ? " " : "") + source;+ }+ // A prose dollar must stay prose, wherever in the part it sits, and not+ // only where it touches a fence. This module is what makes `$`+ // load-bearing in the payload, so a lone prose dollar now has something+ // to pair with: `Use $HOME then $x$ here.` reads `HOME then ` as the+ // formula and drops `x`, and a second prose dollar pairs with the first+ // to make a formula out of the sentence between them. Escaping is+ // lossless because the math here is Markdown source already and `\$`+ // renders as a dollar — a positional rule would only be narrower, not+ // cheaper. Adding a space instead is not enough ("$ $x$" parses an empty+ // formula).+ //+ // A code block's text is not exempt, and exempting it would be a+ // regression rather than a repair. The serializer above writes a code+ // block out without its fences, so what lands in the payload is prose+ // and reads as prose: `echo $HOME and $PATH` on its own pairs its two+ // dollars and turns `HOME and ` into a formula. That corruption+ // predates this module — the platform's own copy produced it — and the+ // escape is what removes it. Exempting code would hand it back.+ //+ // Nor is a working paste being traded away, which is the part that does+ // not read off the code. Only a selection that holds a rendered formula+ // reaches this function at all (`texClipboardPayload` re-checks the+ // clone, not just the host), and that is exactly the selection whose+ // clipboard text was already unusable: every formula in it arrived+ // twice, as glyphs — issue #414. The cost is narrower than nothing at+ // all, and saying so is the honest version: a code block's own lines did+ // paste cleanly out of that ruined selection and now carry `\$`. It+ // stays the right trade, because the payload is one Markdown document+ // and because the selection copied for the sake of its code alone holds+ // no formula and never arrives here.+ //+ // Exempting code would also have to write its fences back to be sound,+ // since unfenced code is what lets its dollars pair in the first place.+ // That turns this module into one that reconstructs code blocks as well+ // as formulas — the structural walk the file header declines — and+ // moves the `code copy` reading E2E pins in scripts/e2e/copy-tex.tsx.+ //+ // The cost is the visible one and it is accepted: a payload pasted into+ // a terminal or another non-Markdown target shows `\$`. This flavour is+ // Markdown source, on the same ground D618 drops `text/html` on, and a+ // code block still carries its own copy button, which never reaches this+ // path and writes the literal text.+ const escaped = part.replace(/\\*\$/g, escape);+ // A trailing backslash run needs the same treatment with no dollar of+ // its own: what follows it in the text is a fence for it to escape.+ return index === parts.length - 1 ? escaped : escaped.replace(/\\+$/, escape);+ }).join("");+ } finally {+ // Unmount before restoring, so the clone cannot outlive the call through a+ // throwing restore. No such throw is reachable today — `setBaseAndExtent`+ // raises only `IndexSizeError`, nothing shrinks a boundary node between+ // the capture above and this line, and `expandRangeToWholeKatex` clones+ // the range rather than moving the live one — but the invariant the header+ // rests on is that no frame observes the clone, and the order is what+ // makes that structural instead of conditional on the restore.+ //+ // Free to take in this order: removing the wrapper only collapses the+ // range this function put inside it, which the restore then overwrites,+ // and `selectionchange` is queued and coalesced within the task, so the+ // app's one listener (`useComposerDraft`) sees the same end state either+ // way.+ wrapper.remove();+ if (restore) selection?.setBaseAndExtent(...restore);+ else selection?.removeAllRanges();+ }+}++/* ---------- live selection ---------- */++/**+ * The element the range's content already sits in: the ancestor context the+ * clone is read in, and the cheapest place to look for a formula. Null only+ * for a range whose common ancestor is the document itself, which no selection+ * the user can make produces — and which has nothing to borrow a cascade from+ * anyway, so the copy stays the platform's.+ *+ * For a selection that lies wholly inside one formula — a double-click on a+ * glyph, a drag across half a rendering — this is an element *inside* the+ * `.katex` the reduction replaces, so the clone is mounted within the live+ * formula and KaTeX's own stylesheet is what the wrapper inherits from. That+ * is intended, and it holds structurally rather than on any fact about that+ * stylesheet, which does set two of the four properties the text serializer+ * turns on (`.katex .base` is `display: inline-block; white-space: nowrap`).+ * A common ancestor inside a `.katex` means both range boundaries are inside+ * it, so `expandRangeToWholeKatex` widens to exactly that one formula and+ * `replaceKatex` leaves the clone holding exactly one slot — and the slot sets+ * its own `white-space`, the only one of the four that could move its reading.+ * There is no prose under that cascade for an inherited property to reach, and+ * the live tree is only ever read. E2E-CHAT-copy-formula-as-tex drags this+ * selection under the real KaTeX stylesheet, so a future rule that did reach+ * the reading surfaces there rather than in the user's clipboard.+ */+function hostElementOf(range: Range): Element | null {+ const container = range.commonAncestorContainer;+ return container.nodeType === 1+ ? (container as Element)+ : (container.parentElement ?? null);+}++function selectionRange(selection: Selection | null): Range | null {+ if (!selection || selection.rangeCount === 0 || selection.isCollapsed) {+ return null;+ }+ return selection.getRangeAt(0);+}++/**+ * Whether a selection hosted by `host` is worth cloning at all. Cheap, and+ * allowed to say yes too often because the clone is checked for a formula+ * anyway — so that the common copy, the one with no math anywhere near it,+ * does not deep-clone a whole transcript inside the event before finding that+ * out.+ *+ * This is the only gate, on purpose. A selection that does hold math is cloned+ * and laid out whole, however large, inside the event — because the platform+ * serializing that same selection is the cost being matched, and because a+ * size threshold above which the copy silently reverted to glyphs would make+ * one gesture return two different things depending on how long the+ * conversation had grown. The synchronous layout is the accepted price of that+ * parity, not an oversight to be bounded later.+ */+function mayContainKatex(host: Element): boolean {+ return Boolean(+ host.closest(KATEX_SELECTOR) ?? host.querySelector(KATEX_SELECTOR),+ );+}++/**+ * The `text/plain` a copy should carry for `selection`, or null when this+ * module has nothing to add — no selection, or a selection with no rendered+ * formula in it. Returning null is how every caller keeps the platform's own+ * copy: rewriting a selection that holds no math could only make it worse.+ *+ * One flavour, and only one. Taking the copy over drops the platform's+ * `text/html` too, and none is written back. The clone is the app's own+ * markup, so serializing it would carry the chrome `base.css` marks+ * `user-select: none` — a code block's `js` rail and its copy button — which+ * the text reading drops, plus `data-source-*` bookkeeping and the nested+ * display slot `texSlot` describes: a second, worse reading of one selection.+ * Leaving it out is also what keeps a formula from pasting twice over, since+ * KaTeX's stylesheet is the only thing hiding the MathML tree and no+ * stylesheet travels on the clipboard. A rich paste target falls back to the+ * plain text, which is the source the user asked for.+ *+ * That fallback is the known cost, not an oversight: a selection holding a+ * formula now pastes into a rich target without the tag-level formatting the+ * platform's own `text/html` carried. Keeping the formatting would mean+ * reconstructing that flavour here — stripping the inert chrome, stripping the+ * bookkeeping, and splitting the paragraph the display slot nests in — which+ * is the hand-written structural walk this module exists to avoid. D618 weighs+ * the trade and takes the deletion; reopen it there, not here.+ */+export function texClipboardPayload(selection: Selection | null): string | null {+ const live = selectionRange(selection);+ const host = live ? hostElementOf(live) : null;+ if (!live || !host || !mayContainKatex(host)) return null;+ const doc = host.ownerDocument;++ const wrapper = doc.createElement("div");+ wrapper.append(expandRangeToWholeKatex(live).cloneContents());+ if (!wrapper.querySelector(KATEX_SELECTOR)) return null;++ const slots = replaceKatex(wrapper, doc);+ return renderedText(wrapper, host, slots) || null;+}diff --git a/apps/desktop/test/markdown-blocks.test.mjs b/apps/desktop/test/markdown-blocks.test.mjsnew file mode 100644index 000000000..59ebfe0bc--- /dev/null+++ b/apps/desktop/test/markdown-blocks.test.mjs@@ -0,0 +1,122 @@+import assert from "node:assert/strict";+import test from "node:test";+import {+ advanceMarkdownBlocks,+ emptyMarkdownBlockCache,+ parseMarkdownBlocks,+} from "../src/lib/markdown-blocks.ts";++const blocksOf = (source) => parseMarkdownBlocks(source).blocks;++/** Feed `source` one appended chunk at a time, as streaming does. */+function stream(...chunks) {+ let cache = emptyMarkdownBlockCache;+ let source = "";+ for (const chunk of chunks) {+ source += chunk;+ cache = advanceMarkdownBlocks(cache, source);+ }+ return cache;+}++test("math bodies are indivisible blocks, including Markdown-looking lines", () => {+ for (const body of ["- x", "+ x", "* x", "> x", "x\n=\ny", "x\n\n+ y"]) {+ const math = `$$\n${body}\n$$\n\n`;+ assert.deepEqual(blocksOf(`Before.\n\n${math}After.`), [+ "Before.\n\n", math, "After.",+ ]);+ }+});++test("source slices preserve CRLF, leading whitespace and ordinary block boundaries", () => {+ const blocks = [+ "\r\nBefore.\r\n\r\n",+ "$$\r\n- x\r\n\r\n+ y\r\n$$\r\n\r\n",+ "- first\r\n- second\r\n\r\n",+ "> quote\r\n\r\n",+ "```text\r\n$$\r\n- literal\r\n$$\r\n```\r\n\r\n",+ "| a | b |\r\n| --- | --- |\r\n| 1 | 2 |\r\n\r\n",+ "After.",+ ];+ assert.deepEqual(blocksOf(blocks.join("")), blocks);+ assert.deepEqual(blocksOf(" \r\n\r\n"), [" \r\n\r\n"]);+ assert.deepEqual(blocksOf(""), []);+});++test("an indented block keeps its own indentation in its own slice", () => {+ // Cutting at the node's first character instead of at its line start leaves+ // the indentation on the previous slice, and the block then re-parses as a+ // different one on its own: a nested list, or a fence that keeps the indent+ // inside its code.+ assert.deepEqual(blocksOf("Before.\n\n - first\n - second\n\nAfter."), [+ "Before.\n\n",+ " - first\n - second\n\n",+ "After.",+ ]);+ assert.deepEqual(blocksOf("Before.\n\n 1. one\n 1. two\n"), [+ "Before.\n\n",+ " 1. one\n 1. two\n",+ ]);+ assert.deepEqual(+ blocksOf("Before.\r\n\r\n ```js\r\n code\r\n ```\r\n\r\nAfter."),+ ["Before.\r\n\r\n", " ```js\r\n code\r\n ```\r\n\r\n", "After."],+ );+});++test("an unclosed math fence retains its whole body in the streaming tail", () => {+ for (const tail of ["$$\n- x", "$$\n- x\n\n+ y", "$$\n- x\n\n+ y\n$$"]) {+ assert.deepEqual(blocksOf(`Before.\n\n${tail}`), ["Before.\n\n", tail]);+ }+});++test("a definition anywhere makes the source one parse context", () => {+ for (const source of [+ "Text[^1].\n[^1]: footnote\n",+ "Text[^1].\n\n[^1]: footnote\n",+ "A[^1] and B[^1] reuse one note.\n\n[^1]: footnote\n",+ "[^1]: footnote\n\nText[^1].\n",+ "See [spec].\n\n[spec]: https://example.com\n",+ "> [spec]: https://example.com\n\nSee [spec].\n",+ "- [spec]: https://example.com\n\nSee [spec].\n",+ ]) {+ assert.equal(parseMarkdownBlocks(source).hasDocumentScopedDefinition, true, source);+ assert.deepEqual(advanceMarkdownBlocks(emptyMarkdownBlockCache, source).blocks, [source]);+ }+});++test("sources without definitions keep splitting into independent blocks", () => {+ for (const source of [+ "Before.\n\n$$\nx\n$$\n\nAfter.",+ "Text[^1] whose note never arrives.\n\nNext paragraph.\n",+ "See [spec] with no target.\n\nNext paragraph.\n",+ "```text\n[^1]: fenced, not a definition\n```\n\nAfter.\n",+ ]) {+ assert.equal(parseMarkdownBlocks(source).hasDocumentScopedDefinition, false, source);+ assert.ok(advanceMarkdownBlocks(emptyMarkdownBlockCache, source).blocks.length > 1, source);+ }+});++test("a definition streamed in after its reference still collapses the prefix", () => {+ const cache = stream("Text[^1].\n", "\nMore prose.\n", "\n[^1]: footnote\n");+ assert.equal(cache.singleUnit, true);+ assert.deepEqual(cache.blocks, ["Text[^1].\n\nMore prose.\n\n[^1]: footnote\n"]);+ // The latch holds without re-parsing once later text arrives.+ const later = advanceMarkdownBlocks(cache, `${cache.consumed}\nTail.\n`);+ assert.deepEqual(later.blocks, [later.consumed]);+});++test("streaming an appended source splits it exactly like one full parse", () => {+ const source = "Before.\n\n$$\n- x\n$$\n\n- first\n- second\n\nAfter.";+ for (let cut = 1; cut < source.length; cut++) {+ const cache = stream(source.slice(0, cut), source.slice(cut));+ assert.deepEqual(cache.blocks, blocksOf(source), `cut at ${cut}`);+ }+});++test("a source that stops extending the cached one is re-decided from scratch", () => {+ const withDefinition = stream("See [spec].\n\n[spec]: https://example.com\n");+ assert.equal(withDefinition.singleUnit, true);+ const replaced = advanceMarkdownBlocks(withDefinition, "Before.\n\nAfter.\n");+ assert.equal(replaced.singleUnit, false);+ assert.deepEqual(replaced.blocks, ["Before.\n\n", "After.\n"]);+});diff --git a/apps/desktop/test/selection-tex.test.mjs b/apps/desktop/test/selection-tex.test.mjsnew file mode 100644index 000000000..6ad613a83--- /dev/null+++ b/apps/desktop/test/selection-tex.test.mjs@@ -0,0 +1,167 @@+import assert from "node:assert/strict";+import { readFile } from "node:fs/promises";+import test from "node:test";+import { createElement } from "react";+import { renderToStaticMarkup } from "react-dom/server";+import { createInstance } from "i18next";+import { I18nextProvider } from "react-i18next";+import { catalogs } from "@pi-desktop/i18n";+import { createServer } from "vite";+import { fileURLToPath } from "node:url";+import {+ KATEX_DISPLAY_SELECTOR,+ KATEX_SELECTOR,+ KATEX_TEX_SELECTOR,+ texSource,+} from "../src/lib/selection-tex.ts";++/*+ * Issue #414: a formula copied out of an answer pasted as the glyphs KaTeX+ * painted, not as the TeX it was written in. What the reduction does to a real+ * selection is proven against a real Chromium in `pnpm test:e2e:copy-tex`,+ * which drags real `Range`s across real KaTeX output; the reading of ordinary+ * prose, lists, tables and code blocks around a formula is checked there too,+ * because that reading belongs to the platform and only a real one can answer+ * for it.+ *+ * What stays here answers questions that suite cannot: the pure delimiter+ * contract, the shape the markdown pipeline actually paints a formula in, and+ * the one wiring fact a fixture that mounts the hook itself would miss. It+ * asserts on behaviour, never on the text of the modules under test — a suite+ * that matches source against regexes fails on a rename and passes on an+ * inverted condition.+ */++const shell = await readFile(+ new URL("../src/features/app/AppShell.tsx", import.meta.url),+ "utf8",+);++test("inline math stays in its line and display math takes the lines around it", () => {+ assert.equal(texSource("a^2+b^2", false), "$a^2+b^2$");+ assert.equal(texSource("\\int_0^1 x^2\\,dx", true), "$$\n\\int_0^1 x^2\\,dx\n$$");+ /*+ A run that outgrows anything inside the formula, as a code span's does:+ `$\$5 + x$` would close at the escaped dollar and paste back as prose. The+ display fence already clears a single `$`, so it only widens past a run of+ two or more. What the widened form still *means* is answered by the round+ trip in `pnpm test:e2e:copy-tex`, not here.+ */+ assert.equal(texSource("\\$5 + x", false), "$$\\$5 + x$$");+ assert.equal(texSource("\\$5 + x", true), "$$\n\\$5 + x\n$$");+ assert.equal(texSource("a$$b", false), "$$$a$$b$$$");+ assert.equal(texSource("5\\$ ", false), "$$5\\$ $$");+ assert.equal(texSource("5\\$", false), "$$ 5\\$ $$");+ assert.equal(texSource(" x ", false), "$ x $");+ /*+ Padding answers a line ending at the edges as it answers a space, because+ the grammar drops either one. `$\nx\n$` would read back as `x`.+ */+ assert.equal(texSource("\nx\n", false), "$ \nx\n $");+ assert.equal(texSource("\n\tx\t\n", false), "$ \n\tx\t\n $");+ assert.equal(texSource("\nx", false), "$\nx$");+ assert.equal(+ texSource("a % note\nb + \\text{\\$5}", false),+ "<span>$$a % note\nb + \\text{\\$5}$$</span>",+ );+});++test("a copied formula uses the delimiters the renderer itself accepts", async () => {+ // `normalizeLatexMathDelimiters` rewrites `\(…\)` / `\[…\]` to these before+ // `remark-math` runs, so a pasted formula renders as the one it came from.+ const { normalizeLatexMathDelimiters } = await import("../src/lib/latex-math.ts");+ assert.equal(normalizeLatexMathDelimiters(texSource("x^2", false)), "$x^2$");+ assert.equal(+ normalizeLatexMathDelimiters(texSource("x^2", true)),+ "$$\nx^2\n$$",+ );+ /*+ The rewrite is length-preserving, which is why a `\[ … \]` formula stays+ *inline* in its paragraph and why the display slot can land in an inline+ context at all. `texSlot` documents what the reduction makes of that, and+ `pnpm test:e2e:copy-tex` pins the reading; this is the premise both rest on.+ */+ assert.equal(+ normalizeLatexMathDelimiters("The result \\[E = mc^2\\] closes the proof."),+ "The result $$E = mc^2$$ closes the proof.",+ );+ assert.equal(normalizeLatexMathDelimiters("Inline \\(x^2\\) here."), "Inline $$x^2$$ here.");+ // A widened run is already dollar syntax; the normalization leaves it alone.+ assert.equal(+ normalizeLatexMathDelimiters(texSource("\\$5 + x", false)),+ "$$\\$5 + x$$",+ );+});++test("the shell mounts the one document copy listener", () => {+ /*+ The only fact the Chromium suite cannot see: it mounts `useCopyTex` itself,+ so a hook nobody installs would still pass there. Everything else about the+ listener — which copies it claims, which it declines, and what it writes —+ is behaviour, and behaviour is asserted against a real selection in+ `pnpm test:e2e:copy-tex` rather than against the text of the module.+ */+ assert.match(shell, /import \{ useCopyTex \} from "\.\.\/\.\.\/hooks\/use-copy-tex";/);+ assert.match(shell, /^ {2}useCopyTex\(\);$/m);+});++test("KaTeX still emits the trees and the annotation the reduction reads", async () => {+ const server = await createServer({+ root: fileURLToPath(new URL("..", import.meta.url)),+ configFile: false,+ server: { middlewareMode: true, hmr: false, ws: false },+ esbuild: { jsx: "automatic" },+ appType: "custom",+ optimizeDeps: { noDiscovery: true, include: [] },+ });+ const originalDocument = globalThis.document;+ try {+ // `useThemeMode` reads the theme off the document during render.+ globalThis.document = { documentElement: { dataset: {} } };+ const { Markdown } = await server.ssrLoadModule("/src/components/Markdown.tsx");+ const i18n = createInstance();+ await i18n.init({ lng: "en", resources: { en: { translation: catalogs.en } } });+ const render = (text) =>+ renderToStaticMarkup(+ createElement(I18nextProvider, { i18n }, createElement(Markdown, { source: text })),+ );++ // The selectors are read straight off the module, so a rename here has to+ // agree with what the pipeline actually paints.+ const className = (selector) => selector.replace(/^\./, "");+ const inline = render("The identity $a^2+b^2=c^2$ closes the proof.");+ assert.match(inline, new RegExp(`class="${className(KATEX_SELECTOR)}"`));+ assert.doesNotMatch(inline, new RegExp(className(KATEX_DISPLAY_SELECTOR)));+ // Both trees are painted, which is why copying the rendering duplicates it.+ assert.match(inline, /class="katex-mathml"/);+ assert.match(inline, /class="katex-html"/);+ assert.match(inline, /<annotation encoding="application\/x-tex">a\^2\+b\^2=c\^2<\/annotation>/);+ assert.equal(KATEX_TEX_SELECTOR, 'annotation[encoding="application/x-tex"]');++ const display = render("$$\n\\int_0^1 x^2\\,dx\n$$");+ assert.match(display, new RegExp(className(KATEX_DISPLAY_SELECTOR)));+ assert.match(display, /<annotation encoding="application\/x-tex">/);+ // The annotation carries the source, not the glyphs: this is the string the+ // clipboard gets back.+ assert.match(display, /\\int_0\^1 x\^2\\,dx/);++ /*+ `\[ … \]` is display math painted *inside* a paragraph, because the+ normalization is length-preserving and `remarkLatexBracketDisplay`+ promotes an inline node. This is the only shape in which the reduction+ nests its display slot in a paragraph, so `texSlot` reasons about it+ explicitly; pin it here so a pipeline change surfaces as this assertion+ rather than as a wrong clipboard string.+ */+ const bracket = render("The result \\[E = mc^2\\] closes the proof.");+ assert.match(bracket, /<p[^>]*>(?:(?!<\/p>).)*katex-display/s);+ // `\( … \)` normalizes to `$$ … $$` as well but is never promoted.+ assert.doesNotMatch(+ render("Inline \\(x^2\\) here."),+ new RegExp(className(KATEX_DISPLAY_SELECTOR)),+ );+ } finally {+ globalThis.document = originalDocument;+ await server.close();+ }+});diff --git a/docs/spec/04-ux/08-component-spec.md b/docs/spec/04-ux/08-component-spec.mdindex e01aac822..1a48aae19 100644--- a/docs/spec/04-ux/08-component-spec.md+++ b/docs/spec/04-ux/08-component-spec.md@@ -1885,12 +1885,17 @@ Renderer: `apps/desktop/src/components/Markdown.tsx` + `apps/desktop/src/lib/shi- **Streaming without jank**: runtime content chunks render directly, without asecond renderer-side typewriter or animation-frame state loop. Source splits- into top-level blocks via `marked`'s lexer; each block renders through a+ into top-level blocks via the same remark/GFM/math grammar used for rendering;+ raw source slices preserve CRLF and offsets. Each block renders through amemoized `<ReactMarkdown>`. While streaming only the tail block re-parses- (incremental re-lex from the last block boundary), so cost stays linear in- message length. A Mermaid fence stays in the normal source-code presentation+ (incremental parsing from the last block boundary); an unclosed math fence+ retains its entire body in that tail, including blank lines. A Mermaid fence stays in the normal source-code presentationuntil its matching closing fence arrives; partial streamed diagrams never- enter the diagram parser.+ enter the diagram parser. Splitting is skipped entirely for a message that+ declares a link or footnote definition, wherever it sits: definitions resolve+ across the whole message, and footnotes also number, reuse and back-link+ across it, so the message renders as one parse context and gives up per-block+ memoization for as long as it streams.- **Plugins**: `remark-gfm` (tables, task lists, strikethrough, autolinks),`remark-math` + `rehype-katex` (inline `$…$` or `\(…\)`, display `$$…$$`or `\[…\]`). Raw HTML is@@ -1899,6 +1904,48 @@ Renderer: `apps/desktop/src/components/Markdown.tsx` + `apps/desktop/src/lib/shiadditions and the `math-inline`/`math-display` classes on `code` (which keepTeX `\[…\]` in display layout) are admitted. KaTeX's Vite-inlined WOFF2 fontsare allowed by the renderer's `font-src 'self' data:` CSP directive.+- **Copying a formula (D618)**: a selection that covers rendered math reaches+ the clipboard as the TeX it was written in — `$…$` inline, `$$…$$` on its own+ lines, each run widened past any run inside the formula the way a code span's+ fence is, so a formula carrying a literal `$` still reads whole. Inline stays+ the narrow run because an inline formula's TeX can carry a newline, and a+ `$$` run at the start of a line opens a flow block and swallows the+ paragraph. KaTeX paints every formula twice (a MathML tree and a visual one), so+ the platform's own copy wrote both renderings and never the source+ (issue #414). `lib/selection-tex.ts` reads the TeX back out of the MathML+ `annotation` and grows a cut that lands inside a formula to the whole formula;+ `hooks/use-copy-tex.ts` is the single document `copy` listener the shell owns,+ and the transcript's right-click Copy reads the same selection through the+ same module. Only the formulas are rewritten: the reduced clone is read back+ through `Selection.toString()`, the serializer a copy itself runs, and read+ inside the element the selection came from, so the cascade deciding that+ reading is the live one. The prose, lists, tables and code blocks that share+ the selection therefore read exactly as the platform already read them — the+ chrome a copy leaves behind included, whether `base.css` marks it+ `user-select: none` by selector or it is inert only by inheriting the shell's+ default. A selection with no formula in it is left to the platform entirely;+ nothing else is tested, because Chromium raises a copy inside the selection+ it derived the event from, so a whole selection reaches the clipboard as its+ source however deep in it the event was raised. The copy writes one flavour,+ `text/plain`: taking+ the event over drops the platform's `text/html` too, and none is written back+ — the reduced clone is app markup, so it would carry the `user-select: none`+ chrome the text reading drops, and carrying the rendering instead would paste+ every formula twice, KaTeX's stylesheet being the only thing that hides the+ MathML tree. A rich paste target falls back to the plain text.++ Math boundaries remain parseable after copying: touching inline fences get+ one separator, and every prose dollar in the copied text is escaped, together+ with backslash runs that would otherwise escape a fence.+ Annotation whitespace is preserved; widened multiline inline math uses a+ literal `<span>` wrapper to prevent a flow opener when pasted at column zero.+ TeX newlines are not flattened because they can terminate `%` comments.+ The wrapper is Markdown source in `text/plain`, not a `text/html` payload;+ compatibility with external editors that disallow inline HTML is not promised.+ Regression coverage checks both copy entry points and Markdown round trips+ for adjacent formulas, prose dollars on either side, formatting wrappers,+ line/block boundaries, padding, and multiline math including TeX comments.+- **Mermaid diagrams (D165)**: a completed `mermaid` fenced block in assistantanswer prose renders through the official Mermaid package. The dependency isdynamically imported only when a diagram approaches the viewport; Mermaid'sdiff --git a/docs/spec/06-delivery/04-e2e-test-plan.md b/docs/spec/06-delivery/04-e2e-test-plan.mdindex ba3dbb65d..06a93502c 100644--- a/docs/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/spec/06-delivery/04-e2e-test-plan.md@@ -3684,6 +3684,101 @@ identify the platform validation still needed.Copy must not load history until selected or change the reading position.Run `node scripts/e2e-copy-conversation.mjs`.+#### E2E-CHAT-copy-formula-as-tex: Copying rendered math yields its source++Math boundaries remain parseable after copying: touching inline fences get+one separator, and every prose dollar in the copied text is escaped, together+with backslash runs that would otherwise escape a fence.+Annotation whitespace is preserved; widened multiline inline math uses a+literal `<span>` wrapper to prevent a flow opener when pasted at column zero.+TeX newlines are not flattened because they can terminate `%` comments.+The wrapper is Markdown source in `text/plain`, not a `text/html` payload;+compatibility with external editors that disallow inline HTML is not promised.+Regression coverage checks both copy entry points and Markdown round trips+for adjacent formulas, prose dollars on either side, formatting wrappers,+line/block boundaries, padding, and multiline math including TeX comments.+Display math containing `- x`, `+ x`, `* x`, `> x`, or internal blank lines+must remain a single math node after copying. The shared remark grammar+keeps unclosed math in the streaming tail until its fence closes; subsequent+prose and its source offsets remain intact. A footnote whose definition+follows its reference — adjacently or streamed in later — renders as a real+reference and note section rather than a literal `[^1]`, which is what block+splitting costs when a slice is parsed without the rest of the message.+CRLF, ordinary lists, quotes, GFM tables, fenced code and the sources that+must keep splitting are covered by `markdown-blocks.test.mjs`.+++- **Preconditions**: An assistant answer contains inline math inside a+ sentence, a display formula on its own lines, a `\[ … \]` formula inside a+ sentence and another on its own lines, a `\( … \)` formula, a formula+ carrying a literal `$`, an inline formula whose value carries a newline and+ another whose value carries one at each edge, a paragraph with+ no math, and — each sharing a selection with a formula — a paragraph whose+ source wrapped across several lines, a bulleted list, a table, a second+ table whose cell holds a `\[ … \]` formula, a fenced+ code block that contains blank lines, and a turn whose prose is interrupted+ by chrome that is unselectable only because it inherits the shell's+ `user-select: none` (a tool row's section head).+- **Steps**: 1) Select the sentence holding the inline formula and press+ Ctrl/Cmd+C. 2) Select the display formula and copy it. 3) Select from the+ middle of a formula to the end of its sentence and copy. 4) Select a+ paragraph, a formula, and another paragraph together and copy. 5) Select+ prose with no formula in it and copy. 6) Copy each of the wrapped paragraph,+ the list, both tables, and the code block. 7) Copy each `\[ … \]` formula, the+ `\( … \)` one, the formula carrying a literal `$`, and the two whose values+ carry newlines. 8) Select a formula backwards — from the end of the+ sentence to its start — and copy. 9) With a formula selected, right-click+ that turn and choose Copy, then right-click a different turn and choose Copy.+ 10) Select a turn's whole contents the way the Select text item does, so the+ range is anchored on the turn while the copy is raised on a paragraph inside+ it, and copy. 11) Select without ever leaving one formula — a drag inside its+ rendering — and copy. 12) Render each result back through the same answer+ renderer — what pasting it into the composer and sending it produces — and+ compare the formulas it paints with the ones the selection covered.+- **Expected**: Every formula reaches the clipboard as the TeX it was written+ in — `$…$` inline, `$$…$$` on its own lines — instead of the glyphs KaTeX+ painted, or the same expression twice over from its two trees. A formula+ carrying a literal `$` widens its delimiter run past it, as a code span's+ fence does, and pastes back as the formula rather than as prose; an inline+ formula whose value carries a newline keeps the narrow run, because a `$$`+ run at the start of a line would open a flow block and swallow the+ paragraph; one whose value carries a newline at each edge is written with+ padding of its own, because the grammar drops a line ending there as it+ drops a space. A cut that+ starts inside a formula copies the whole formula, and a selection that never+ leaves one copies that formula alone. Everything else in the+ selection is byte for byte what the platform already copied: a wrapped+ paragraph stays one line, a list keeps one line per item, a table keeps tabs+ between cells and one line per row including the newline the platform closes+ the last row with, and a code block keeps its blank lines. Chrome the copy+ leaves behind stays out of the clipboard whether `base.css` marks it+ `user-select: none` by selector (a code block's language rail) or it is inert+ only by inheriting the shell's default (a tool row's section head, a compact+ thinking row). A selection with no formula in it is written by the platform+ unchanged; a selection that holds one reaches the clipboard as its source+ however deep inside it the copy was raised, so a range anchored on a turn —+ what Select text produces — copies as TeX even though Chromium raises the+ event on a paragraph within it. Right-click Copy and Ctrl/Cmd+C produce the+ same string for one selection, and a right-click on a turn that does not own+ the selection reads no excerpt from it, so Copy falls back to that turn's own+ source. A pasted formula renders as+ the one it came from — same TeX, and display math still display math —+ `\[ … \]` included: it is painted inside its sentence's paragraph, and copies+ with `$$` on a line of its own, which is enough to open a display block when+ it is pasted back. `\( … \)` stays+ inline. A table cell reaches it too, measured rather than assumed: the+ `.katex-display` box breaks the row for the platform's own reading as well,+ so no tab lands beside the fence and the formula copies as display math with+ the neighbouring cell intact on its own line. A backward selection is still+ backward after the copy. The copy+ writes `text/plain` only — no `text/html` flavour is put on the clipboard.+- **Specs linked**: `04-ux/08-component-spec.md` §8.7, ADR 0268,+ decisions-log D618, issue #414+- **Acceptance**: C (chat stream), Quality+- **Milestone**: M5+- **Status**: Automated (`pnpm test:e2e:copy-tex`, real Chromium) plus+ `selection-tex.test.mjs`+#### E2E-060b: Neutral gray accent across chrome- **Preconditions**: App running in dark and light themes; plugins page and adiff --git a/docs/spec/08-meta/decisions-log.md b/docs/spec/08-meta/decisions-log.mdindex d6f203ca2..b7a078516 100644--- a/docs/spec/08-meta/decisions-log.md+++ b/docs/spec/08-meta/decisions-log.md@@ -304,6 +304,7 @@ Gold source: local Codex electron captures; latest row wins where rows conflict.| D365 | Named quiet intervals on the live activity row | **Amend D338 / ADR 0175: `AgentActivity` adds `preparing`, `compacting`, and `recovering`; `starting` shows its own label; `waiting-subagents` carries a live running snapshot (`name`, `lastPhase`, `lastToolName`) that updates on child tool/thinking changes, not on every token. The row stays one compact inline status and does not restore an activity-group capsule.** | Compaction, silent-turn recovery, the post-tool gap, and startup all looked like a stuck generic wait, and a parent wait hid what its delegates were doing (ADR 0198, E2E-008c / E2E-094) || D599 | A development build is its own installation | **Narrow D236 / amend ADR 0094: a development build (unpackaged, or `PI_DESKTOP_DEV=1`) takes `PI-Desktop Dev` as its Electron `userData` — and with it the single-instance lock, renderer `localStorage`, the plugin panel partitions, and browser pane cookies — and reads `~/.pi-desktop-dev`. An explicit `--user-data-dir` still wins, which is how the E2E harnesses point a build at a throwaway profile. A packaged installation keeps `PI-Desktop` and `~/.pi-desktop`, so no existing profile is relocated. `PI_DESKTOP_DATA_DIR` still overrides either profile and is made absolute before it reaches host-core as a child-process environment variable; Electron main publishes the resolved directory back to that variable so the plugin runtime reads one root. No IPC, protocol, schema, or packaged-installation path change. See `03-runtime/07-process-model.md` and E2E-150.** | A packaged app that was already running held the lock, so `pnpm dev` quit on arrival; a development host that won the race instead put a second host-core over the same single-writer `pi.sqlite`, the outbox, and the log tree. || D602 | Crash dumps stay in the data directory | **Electron's Crashpad reporter starts local-only (`uploadToServer: false`) before `ready`. Dumps live under `<data_dir>/crash-dumps`, not the default Electron `userData` crashDumps path, so a `PI_DESKTOP_DATA_DIR` profile does not share dumps. The next lock-holding launch writes one `diagnostics` line for dumps newer than `crash-dumps.json`, classified by Crashpad `ptype`: `error` if any new dump is the browser/main process, `warn` for recovered renderer/GPU/utility crashes. Host-core and sidecar crashes stay on the supervisor path. No upload, no IPC, no schema change.** | A crash left a minidump nobody read. Crashpad also records recovered renderer crashes, so a next-launch `error` that said the previous run died was a lie; and dumps outside the data directory escaped `PI_DESKTOP_DATA_DIR` isolation. |+| D618 | A copied formula is its TeX source | **Renderer only: a copy whose selection covers rendered math writes `text/plain` from the MathML `annotation` — `$…$` inline, `$$…$$` on its own lines, the delimiters `lib/latex-math.ts` normalizes `\(…\)` and `\[…\]` to, each run widened past any run inside the formula as a code span's fence is — instead of the two trees KaTeX paints. A cut that lands inside a formula grows to the whole formula. Only the formulas are rewritten: the reduced clone is read back through `Selection.toString()`, the serializer a copy itself runs, so prose, lists, tables and code blocks sharing the selection keep the platform's own reading — `user-select: none` chrome left behind included, which `innerText` would have written out. A selection with no formula in it, and a copy raised where the selection does not live, are left to the platform entirely. One flavour is written, `text/plain`: taking the event over drops the platform's `text/html` too and none is written back, because the reduced clone is app markup that would carry the `user-select: none` chrome the text reading drops, and because carrying the rendering instead would paste every formula twice — KaTeX's stylesheet is the only thing hiding the MathML tree and no stylesheet travels on the clipboard. One document `copy` listener owned by the shell, and the transcript's right-click Copy reads the same selection through the same module.** | A formula pasted as its glyphs, once per rendered tree, so it could not be carried into a LaTeX document or another Markdown editor (issue #414). ADR 0268 removed quoting on the grounds that the OS clipboard was the substitute; the clipboard had to actually carry the source. |## M0. Model catalog decisions@@ -6701,3 +6702,143 @@ that was sitting at the bottom — including after the turn had finished.checkpoint reports the summed usage of the requests that produced it. Only anempty range, or one past that request bound, still falls back on budgetgrounds. See ADR 0302, `03-runtime/02-agent-runtime.md`, ADR 0049, ADR 0282.++## 2026-09-20 — A copied formula is its TeX source (D618, issue #414)++Math boundaries remain parseable after copying: touching inline fences get+one separator, and every prose dollar in the copied text is escaped, together+with backslash runs that would otherwise escape a fence.+Annotation whitespace is preserved; widened multiline inline math uses a+literal `<span>` wrapper to prevent a flow opener when pasted at column zero.+TeX newlines are not flattened because they can terminate `%` comments.+The wrapper is Markdown source in `text/plain`, not a `text/html` payload;+compatibility with external editors that disallow inline HTML is not promised.+Regression coverage checks both copy entry points and Markdown round trips+for adjacent formulas, prose dollars on either side, formatting wrappers,+line/block boundaries, padding, and multiline math including TeX comments.+Display math containing `- x`, `+ x`, `* x`, `> x`, or internal blank lines+must remain a single math node after copying. The shared remark grammar+keeps unclosed math in the streaming tail until its fence closes; subsequent+prose and its source offsets remain intact. A footnote whose definition+follows its reference — adjacently or streamed in later — renders as a real+reference and note section rather than a literal `[^1]`, which is what block+splitting costs when a slice is parsed without the rest of the message.+CRLF, ordinary lists, quotes, GFM tables, fenced code and the sources that+must keep splitting are covered by `markdown-blocks.test.mjs`.+++- KaTeX paints one formula twice — a MathML tree for assistive technology and a+ visual tree of positioned spans — and both are real text in the document. The+ platform's own copy therefore wrote a formula out as its glyphs, twice over,+ and never as the source the answer was written in.+- A copy whose selection covers rendered math now reads the TeX back out of the+ MathML `annotation`: `$…$` inline, `$$…$$` on its own lines. Those are the+ delimiters `lib/latex-math.ts` normalizes `\(…\)` and `\[…\]` to before+ `remark-math` runs, so a pasted formula renders as the one it came from. A cut+ that lands inside a formula grows to the whole formula, because half a TeX+ expression is not one and a cut between the two trees would take the source+ from one and the glyphs from the other.+- Each delimiter run is widened past any run inside the formula, the way a code+ span's fence is, because `$\$5 + x$` closes at the escaped dollar and pastes+ back as prose. Inline stays the narrow run otherwise, and not for the reason+ it first looks like: a single-line `$$…$$` never opens a display block, since+ math flow forbids `$` in the meta after its opening fence. It stays narrow+ because an inline formula's TeX can carry a newline — only the `\(…\)` path+ has its newlines flattened by the normalization — and a `$$` run would then+ land at the start of a line with the rest of the formula behind it, which is a+ flow opening and swallows the paragraph.+- Display math is not always a block here. `normalizeLatexMathDelimiters`+ rewrites `\[ … \]` in place — the rewrite is length-preserving — so the math+ node stays inline and `remarkLatexBracketDisplay` promotes it, leaving KaTeX+ to paint `.katex-display` inside the sentence's own paragraph. The reduction+ puts its paragraph slot there unchanged; a `p` nested in a `p` is invalid as+ markup and harmless here, because the clone is only ever read through the+ text serializer, which treats the nested block as one boundary. One newline+ above `$$` is enough for `remark-math` to open the display block, so the+ formula pastes back as the display formula it came from. Both `\[ … \]`+ shapes are pinned by E2E-CHAT-copy-formula-as-tex.+- A table cell is the one place the block slot had to be measured rather than+ reasoned about, and the measurement is recorded because the reasoning points+ the wrong way. `remarkLatexBracketDisplay` promotes a `\[ … \]` node wherever+ it sits, cells included, so `.katex-display` really does land inside a `<td>`+ — and the table serializer joins cells with tabs, which makes it look as+ though the `$$` fence there would be closed by a tab and swallow the rest of+ the row (`a\tb\n$$\nE = mc^2\n$$\t2` is one math node whose value runs to+ the end of the line). Chromium writes no such string: a block box is a block+ boundary inside a cell too, so the row breaks around it, the fence closes on+ its own line, and the neighbouring cell arrives on one of its own. The slot+ is not inventing that boundary either — the platform's own reading of the+ same row has no tab in it, because `.katex-display` breaks the row for it as+ well — so keeping the display form here is the parity the rest of this+ decision rests on rather than an exception to it. Narrowing to the inline run+ in a cell was considered and rejected: it would pay display math to repair a+ shape the serializer does not produce, and it would put a tab back that the+ platform itself does not write. E2E-CHAT-copy-formula-as-tex asserts both+ halves, so a Chromium that started tab-joining a cell holding a block would+ fail there rather than in a user's clipboard.+- Only the formulas are rewritten. Everything else in the selection — prose,+ lists, tables, code blocks — is serialized by the platform itself: the+ reduced clone is selected and read back through `Selection.toString()`, the+ serializer a copy actually runs. A hand-written walk of the tree could only+ approximate those whitespace rules, and everywhere it fell short it would+ silently rewrite content the platform already got right: source line wrapping+ put back into a paragraph, blank lines between list items, a code block's own+ blank lines collapsed.+- The serializer has to be the copy's own, not a near neighbour. `innerText`+ reads almost identically and has no notion of `user-select`, so it writes out+ the chrome `base.css` marks inert — a code block's language rail reaching the+ clipboard as a stray `js` line. Restating that rule inside the reduction+ would be the hand-written walk this decision rejects; running the platform's+ own serializer makes the parity exact instead of approximate. The clone is+ read inside the element the selection came from rather than parked on `body`,+ so the cascade deciding that reading is the live one; restating the selection+ contract on the clone instead (an inline `user-select: text`) inverts it,+ because the shell is unselectable by default and document-like surfaces opt+ back in — chrome that is inert only by inheritance would arrive in the+ clipboard.+- Every other selection is left alone: a selection with no formula in it is the+ platform's business. There is no second test of whether the copy "belongs to"+ the selection, because Chromium derives the event target from the selection+ itself, so a non-collapsed selection always raises its copy inside itself;+ a target check only rejects ranges built with `selectNodeContents`, the+ transcript's own Select text among them. A copy raised in the composer cannot+ carry a stale transcript selection either — a frame holds one selection, so+ focusing a field collapses it, and a collapsed selection is already declined.+- One clipboard flavour, `text/plain`. Taking the copy over drops the+ platform's `text/html` as well, and none is written back. The reduced clone+ is the app's own markup: serializing it would carry the chrome `base.css`+ marks `user-select: none` — a code block's `js` rail and its copy button —+ that the text reading drops, plus `data-source-*` bookkeeping and a display+ slot nested in a paragraph, which is a second and worse reading of one+ selection. Writing the rendering back instead is not an option either:+ KaTeX's stylesheet is the only thing that hides the MathML tree, and no+ stylesheet travels on the clipboard, so a rich paste target would show every+ formula twice — the very duplication this decision removes. Leaving the+ flavour out settles both: a rich paste target falls back to the plain text,+ which is the source. The cost is that a selection holding a formula pastes+ into a rich target without the tag-level formatting the platform's own+ `text/html` would have carried; the source is what the copy is for.+- One document `copy` listener, installed and removed by the shell+ (`hooks/use-copy-tex.ts`), because `Markdown` renders no wrapper of its own —+ answers, a work-panel file preview and a plugin readme reach the same+ formulas through different parents — and because a copy is a document+ gesture. The transcript's right-click Copy reads the same selection through+ the same module, so the two entry points cannot put two readings of one+ selection on the clipboard.+- Splitting a message into independently parsed blocks, which predates D618 and+ which D618 moved onto the rendering grammar, is only sound for a slice that+ needs no other slice's parse context. A link or footnote definition is+ exactly the counterexample: it resolves across the whole message, and a+ footnote also numbers, reuses and back-links across it, so a reference parsed+ without its definition survives as the literal `[^1]` and the note is+ dropped. A message declaring a definition anywhere therefore renders+ undivided. Injecting definitions into every slice was rejected: it renumbers+ footnotes per slice and aims the back-links at the wrong reference. The+ accepted cost is that such a message loses per-block memoization while it+ streams, which is the cost the renderer carried before it split blocks at all+ and which its rarity in chat answers keeps bounded.+- D618 adds no surface, no store state, and no action-row item: it is the OS+ clipboard that ADR 0268 already rested the removal of quotes on, made honest.+ Renderer only — no IPC channel, host protocol, storage schema, permission,+ Plugin SDK, or i18n key changed. See `04-ux/08-component-spec.md` §8.7 and+ E2E-CHAT-copy-formula-as-tex.diff --git a/docs/zh-CN/spec/04-ux/08-component-spec.md b/docs/zh-CN/spec/04-ux/08-component-spec.mdindex 023a9d62e..4652cfa97 100644--- a/docs/zh-CN/spec/04-ux/08-component-spec.md+++ b/docs/zh-CN/spec/04-ux/08-component-spec.md@@ -1349,12 +1349,14 @@ Renderer: `apps/desktop/src/components/Markdown.tsx` + `apps/desktop/src/lib/s- **无卡顿流式传输**:运行时内容块直接渲染,无需第二个渲染器端打字机或动画帧状态循环。源分裂- 通过 `marked` 的词法分析器进入顶级块;每个块都通过一个渲染+ 通过与渲染一致的 remark/GFM/math 语法切分顶级块;每个块都通过一个渲染已记住 `<ReactMarkdown>`。当仅流式传输尾部块时重新解析(从最后一个块边界开始增量 re-lex),因此成本在消息长度。美人鱼栅栏保留在正常的源代码演示中直到其匹配的关闭栅栏到达;部分流图永远不会- 输入图表解析器。+ 输入图表解析器。若消息中任意位置声明了链接或脚注定义,则完全跳过切分:+ 定义在整条消息范围内解析,脚注还要跨消息编号、复用和回链,+ 因此该消息作为单一解析上下文渲染,并在其流式期间放弃按块记忆。- **插件**:`remark-gfm`(表格、任务列表、删除线、自动链接),`remark-math` + `rehype-katex`(内联 `$…$` 或 `\(…\)`,显示 `$$…$$`或 `\[…\]`)。原始 HTML 是@@ -1363,6 +1365,36 @@ Renderer: `apps/desktop/src/components/Markdown.tsx` + `apps/desktop/src/lib/s`code` 上的 `math-inline`/`math-display` 类(保证 TeX `\[…\]` 使用块级布局)允许添加。 KaTeX 的 Vite 内联 WOFF2 字体被允许渲染器的 `font-src 'self' data:` CSP 指令。+- **复制公式(D618)**:覆盖到渲染公式的选区,以公式被写下时的 TeX 进入剪贴板+ ——行内 `$…$`,块级 `$$…$$` 独占行;两者的定界符长度都像代码段的围栏那样,+ 比公式内部出现的最长同字符串再长一位,因此含字面 `$` 的公式仍能被完整读回。+ 行内保持窄形式,是因为行内公式的 TeX 可能带换行,而 `$$` 一旦落在行首就会+ 开出块级公式并吞掉整段。KaTeX 每个公式都画两遍(一棵 MathML 树和+ 一棵可视树),因此平台自带的复制写出的是这两份渲染,而不是源码(issue #414)。+ `lib/selection-tex.ts` 从 MathML `annotation` 里把 TeX 读回来,并把落在公式+ 内部的切口扩展成整个公式;`hooks/use-copy-tex.ts` 是外壳持有的那一个文档级+ `copy` 监听器,记录区的右键复制经由同一个模块读取同一个选区。只有公式被改写:+ 归约后的克隆经由 `Selection.toString()`——复制自己跑的那个序列化器——读回,且在+ 选区原本所处的那个元素里读,因此决定这份读法的层叠就是实时文档的层叠。于是+ 同处一个选区的正文、列表、表格和代码块,读法与平台原本给出的完全一致,包括+ 复制本就会略过的那些界面零件——无论 `base.css` 是按选择器把它标为+ `user-select: none`,还是它仅因继承外壳默认值而不可选。不含公式的选区整份交回+ 平台处理;除此之外不再做第二重判断,因为 Chromium 的复制事件目标本就是从选区+ 推导出来的,事件必定落在选区内部——所以无论事件落在选区里多深的位置,整个选区+ 都会以源码进入剪贴板。复制只写一种 flavour:`text/plain`。接管事件同时也+ 丢掉了平台的 `text/html`,而且不再写回——归约后的克隆是应用自己的标记,写回去+ 会带上文本读法已经略过的那些 `user-select: none` 界面零件;若改为携带渲染结果,+ 则每个公式会被粘贴两遍,因为隐藏 MathML 树的只有 KaTeX 自己的样式表。富文本+ 粘贴目标会回退到这份纯文本。++ 复制之后公式的边界仍然可解析:相邻的行内围栏之间补一个分隔符;正文里的每个+ 美元符号都会被转义,本会把围栏转义掉的反斜杠串同理。annotation 里的空白原样+ 保留;加宽过的多行行内公式用一个字面的 `<span>` 包住,以免它粘在行首时开出+ 块级公式。TeX 里的换行不做压平,因为它可能用来终止 `%` 注释。这个包裹是+ `text/plain` 里的 Markdown 源码,不是 `text/html` 负载;对禁用行内 HTML 的+ 外部编辑器不作兼容承诺。回归覆盖两个复制入口,以及相邻公式、围栏两侧的正文+ 美元符号、格式化包装、行与块的边界、补白,以及含 TeX 注释的多行公式各自的+ Markdown 往返。- **美人鱼图(D165)**:助手中完成的 `mermaid` 围栏块答案散文通过官方美人鱼包呈现。依赖关系是仅当图表接近视口时才动态导入;美人鱼的diff --git a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.mdindex aa612a8be..ce20c8220 100644--- a/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md+++ b/docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md@@ -2278,6 +2278,33 @@ MainChat 弥补了缺口。 Maximized/fullscreen 调用保留最新的- **完整历史回归**:打开包含 140 条消息的会话,不向上翻页,选择复制整个对话;剪贴板必须包含第 1–140 条消息。从搜索上下文窗口和长消息截断预览重复验证。保留当前可见的生成中文字;读取失败时提示错误,剪贴板保持不变。仅在选择复制后读取完整历史,不改变阅读位置。运行 `node scripts/e2e-copy-conversation.mjs`。- 编辑时复制应使用草稿选区,无选区时复制整份草稿;选中消息文本应选中草稿。菜单不提供编辑、删除或版本切换;取消后原消息及其菜单保持不变。自动化验证:`node scripts/e2e-message-edit-copy.mjs`。+#### E2E-CHAT-copy-formula-as-tex:复制渲染后的公式得到源码++复制之后公式的边界仍然可解析:相邻的行内围栏之间补一个分隔符;正文里的每个美元+符号都会被转义,本会把围栏转义掉的反斜杠串同理。annotation 里的空白原样保留;+加宽过的多行行内公式用一个字面的 `<span>` 包住,以免它粘在行首时开出块级公式。+TeX 里的换行不做压平,因为它可能用来终止 `%` 注释。这个包裹是 `text/plain` 里的+Markdown 源码,不是 `text/html` 负载;对禁用行内 HTML 的外部编辑器不作兼容承诺。+回归覆盖两个复制入口,以及相邻公式、围栏两侧的正文美元符号、格式化包装、行与块+的边界、补白,以及含 TeX 注释的多行公式各自的 Markdown 往返。+含 `- x`、`+ x`、`* x`、`> x` 或内部空行的块级公式,复制之后必须仍是同一个公式+节点。共享的 remark 语法把尚未闭合的公式留在流式尾块里直到围栏闭合,其后的正文+及其源码偏移保持不变。脚注定义出现在引用之后——紧随其后,或稍后才流式到达——会+渲染成真正的引用与脚注区,而不是字面的 `[^1]`;这正是把切片脱离整条消息单独解析+时,按块切分要付的代价。CRLF、普通列表、引用块、GFM 表格、围栏代码,以及那些+必须继续切分的源文,由 `markdown-blocks.test.mjs` 覆盖。+++- **前提条件**:助手回答里既有句中的行内公式,也有独占若干行的块级公式,还有句中的 `\[ … \]` 公式与独占若干行的 `\[ … \]` 公式、一个 `\( … \)` 公式、一个含字面 `$` 的公式、一个值里带换行的行内公式与另一个值的两端各带一个换行的行内公式,以及一段不含公式的正文;另有与公式同处一个选区的:源码跨多行折行的段落、无序列表、表格、一个单元格里放着 `\[ … \]` 公式的表格、内含空行的围栏代码块,以及一个正文被 chrome 打断的回合,该 chrome 仅因继承外壳的 `user-select: none` 而不可选(工具行的分节标题)。+- **步骤**:1)选中含行内公式的整句并按 Ctrl/Cmd+C。2)选中块级公式并复制。3)从公式中间选到该句末尾并复制。4)把一段正文、一个公式和另一段正文一起选中并复制。5)选中不含公式的正文并复制。6)分别复制折行段落、列表、两个表格和代码块。7)分别复制两个 `\[ … \]` 公式、那个 `\( … \)` 公式、含字面 `$` 的公式,以及值里带换行的那两个公式。8)从句末反向选到句首选中一个公式并复制。9)在公式处于选中状态时右键该回合并选择复制,再右键另一个回合并选择复制。10)按「选中文本」菜单项的方式选中整个回合的内容——选区锚在回合上,而复制事件落在回合内部的某个段落上——并复制。11)选中一个始终不越出该公式的范围——在它的渲染内部拖选——并复制。12)把每次结果重新交给同一个回答渲染器渲染一遍——即粘回输入框并发送后得到的东西——再把它画出的公式与选区覆盖的公式逐一比对。+- **预期**:每个公式都以它被写下时的 TeX 进入剪贴板——行内 `$…$`,块级 `$$…$$` 独占行——而不是 KaTeX 画出的字形,也不是两棵树带来的同一个表达式的两份。含字面 `$` 的公式会像代码段的围栏那样把定界符加长到盖过它,粘回去仍是公式而不是普通文字;值里带换行的行内公式则保持窄形式,因为 `$$` 落在行首会开出块级公式并吞掉整段;值的两端各带一个换行的那个,复制时会自己补上一对空白,因为语法在这里吃掉一个换行就像吃掉一个空格。从公式中间开始的选区会复制整个公式,而始终不越出某个公式的选区只复制出该公式本身。选区里其余内容与平台原本复制到的逐字节一致:折行段落仍是一整行,列表每项一行,表格单元格之间是制表符、每行一行并保留平台为末行补上的换行,代码块保留自己的空行。复制本就会略过的 chrome 不会进入剪贴板:无论 `base.css` 是按选择器把它标为 `user-select: none`(代码块的语言标签),还是它仅因继承外壳默认值而不可选(工具行的分节标题、紧凑思考行)。不含公式的选区交回平台原样写入;含公式的选区则无论复制事件落在它内部多深的位置,都以源码进入剪贴板——所以锚在整个回合上的选区(即「选中文本」产生的那种)也会复制成 TeX,哪怕 Chromium 把事件抬在了回合内部的某个段落上。右键复制与 Ctrl/Cmd+C 对同一个选区得到同一个字符串,而右键一个并不持有该选区的回合读不到任何摘录,因此复制退回该回合自己的源码。粘回的公式渲染回它来处的那个公式——TeX 相同,块级仍是块级——`\[ … \]` 也不例外:它被画在所属句子的段落里,复制出来时 `$$` 独占一行,足以在粘回去时开出块级公式;`\( … \)` 保持行内。表格单元格同样适用,且这一条是实测而非推断:`.katex-display` 盒子对平台自己的读法同样会断开该行,因此围栏旁边不会出现制表符,公式仍以块级形式复制,相邻单元格完整地落在自己的行上。反向选区在复制之后仍然是反向的。复制只写 `text/plain`——不会把 `text/html` flavour 放上剪贴板。+- **链接规格**:`04-ux/08-component-spec.md` §8.7,ADR 0268,+ 决策日志 D618,issue #414+- **验收**:C(聊天流),质量+- **里程碑**:M5+- **状态**:已自动化(`pnpm test:e2e:copy-tex`,真实 Chromium),另有+ `selection-tex.test.mjs`+#### E2E-060b:镀铬中性灰色调- **先决条件**:应用程序在深色和浅色主题中运行;插件页面和diff --git a/docs/zh-CN/spec/08-meta/decisions-log.md b/docs/zh-CN/spec/08-meta/decisions-log.mdindex 2b3cd5c68..d3b3fac1f 100644--- a/docs/zh-CN/spec/08-meta/decisions-log.md+++ b/docs/zh-CN/spec/08-meta/decisions-log.md@@ -308,7 +308,7 @@| D365 | 为实时活动行的每个安静间隔命名 | **修订 D338 / ADR 0175:`AgentActivity` 增加 `preparing`、`compacting`、`recovering`;`starting` 显示独立标签;`waiting-subagents` 携带实时运行快照(`name`、`lastPhase`、`lastToolName`),随子级工具/思考变化更新而非逐 token 更新。该行保持为一条紧凑的内联状态,不恢复活动分组胶囊。** | 压缩、静默回合恢复、工具后间隙与启动都像卡住的通用等待,父级等待也隐藏了委托在做什么(ADR 0198,E2E-008c / E2E-094) || D599 | 开发构建是一个独立安装 | **收窄 D236 / 修订 ADR 0094:开发构建(未打包,或 `PI_DESKTOP_DEV=1`)以 `PI-Desktop Dev` 作为 Electron `userData`(随之独立的单实例锁、渲染层 `localStorage`、插件面板 partition 与浏览器面板 Cookie),数据目录为 `~/.pi-desktop-dev`。显式 `--user-data-dir` 仍然优先,E2E 装置正是用它把构建指向临时 profile。正式安装仍保持 `PI-Desktop` 与 `~/.pi-desktop`,既有 profile 不会被搬迁。`PI_DESKTOP_DATA_DIR` 仍优先于两种 profile,并在作为子进程环境变量传给 host-core 之前被绝对化;Electron 主进程把解析结果回写到该变量,使插件运行时读到同一个根目录。不改 IPC、协议、schema 或正式安装路径。见 `03-runtime/07-process-model.md` 与 E2E-150。** | 已在运行的正式版持有锁,`pnpm dev` 一启动就退出;而抢到锁的开发 host 会把第二个 host-core 压到同一个单写者 `pi.sqlite`、outbox 与日志树上。 || D602 | 崩溃转储留在数据目录 | **Electron 的 Crashpad 报告器在 `ready` 之前以本地模式启动(`uploadToServer: false`)。转储放在 `<data_dir>/crash-dumps`,而不是 Electron 默认的 `userData` crashDumps 路径,因此 `PI_DESKTOP_DATA_DIR` profile 不会与其它安装共用转储。下一次持有单实例锁的启动会为新于 `crash-dumps.json` 的转储写一条 `diagnostics` 记录,按 Crashpad `ptype` 分类:任一新转储属于 browser/main 进程则为 `error`,已恢复的 renderer/GPU/utility 崩溃为 `warn`。host-core 与 sidecar 崩溃仍走监督器路径。不上传,不改 IPC,不改 schema。** | 崩溃留下的 minidump 无人读取。Crashpad 也会记录已恢复的渲染进程崩溃,因此下次启动用 `error` 声称上次运行已死是错的;而数据目录之外的转储会逃出 `PI_DESKTOP_DATA_DIR` 隔离。 |-+| D618 | 复制公式得到的是它的 TeX 源码 | **仅渲染层:当选区覆盖到渲染出来的公式时,`text/plain` 从 MathML `annotation` 写出——行内 `$…$`,块级 `$$…$$` 独占行,也就是 `lib/latex-math.ts` 把 `\(…\)` 和 `\[…\]` 归一到的那组定界符,且每组定界符都像代码段的围栏那样加长到盖过公式内部出现的最长同字符串——而不是 KaTeX 画的那两棵树。落在公式内部的切口会扩展成整个公式。只有公式被改写:归约后的克隆经由 `Selection.toString()`——复制自己跑的那个序列化器——读回,因此同处一个选区的正文、列表、表格和代码块保留平台自己的读法,包括 `innerText` 会写出、而复制本就会略过的 `user-select: none` 界面零件。不含公式的选区,以及在选区所在位置之外触发的复制,整份交回平台。只写一种 flavour:`text/plain`。接管事件同时丢掉了平台的 `text/html`,且不再写回——归约后的克隆是应用自己的标记,写回去会带上文本读法已略过的 `user-select: none` 界面零件;而改为携带渲染结果则会把每个公式粘贴两遍,因为隐藏 MathML 树的只有 KaTeX 自己的样式表,样式表不会随剪贴板一起走。只有一个由外壳持有的文档级 `copy` 监听器,记录区的右键复制经由同一个模块读取同一个选区。** | 公式粘出来是它的字形,而且每棵渲染树各一份,无法带进 LaTeX 文档或别的 Markdown 编辑器(issue #414)。ADR 0268 当年移除「引用」的理由正是 OS 剪贴板可以替代,那剪贴板就得真的装着源码。 |## M0. 模型目录决策@@ -4754,3 +4754,93 @@ that amendment are retired by ADR 0268; the upstream work-panel lifecycle stays.- 单次缩减后仍过大的摘要提示不再被跳过:范围会被切成每片都能放下的连续分片,最多 16 次请求,每次携带上一片的摘要,检查点报告这些请求的用量总和。只有空范围或超过该请求上限的范围才因预算原因回退。见 ADR 0302、`03-runtime/02-agent-runtime.md`、ADR 0049、ADR 0282。++## 2026-09-20 —— 复制公式得到的是它的 TeX 源码(D618,issue #414)++复制之后公式的边界仍然可解析:相邻的行内围栏之间补一个分隔符;正文里的每个美元+符号都会被转义,本会把围栏转义掉的反斜杠串同理。annotation 里的空白原样保留;+加宽过的多行行内公式用一个字面的 `<span>` 包住,以免它粘在行首时开出块级公式。+TeX 里的换行不做压平,因为它可能用来终止 `%` 注释。这个包裹是 `text/plain` 里的+Markdown 源码,不是 `text/html` 负载;对禁用行内 HTML 的外部编辑器不作兼容承诺。+回归覆盖两个复制入口,以及相邻公式、围栏两侧的正文美元符号、格式化包装、行与块+的边界、补白,以及含 TeX 注释的多行公式各自的 Markdown 往返。+含 `- x`、`+ x`、`* x`、`> x` 或内部空行的块级公式,复制之后必须仍是同一个公式+节点。共享的 remark 语法把尚未闭合的公式留在流式尾块里直到围栏闭合,其后的正文+及其源码偏移保持不变。脚注定义出现在引用之后——紧随其后,或稍后才流式到达——会+渲染成真正的引用与脚注区,而不是字面的 `[^1]`;这正是把切片脱离整条消息单独解析+时,按块切分要付的代价。CRLF、普通列表、引用块、GFM 表格、围栏代码,以及那些+必须继续切分的源文,由 `markdown-blocks.test.mjs` 覆盖。+++- KaTeX 每个公式都画两遍:一棵给无障碍技术读的 MathML 树,一棵由定位 span 组成的+ 可视树,两者都是文档里真实的文本。于是平台自带的复制把公式写成了它的字形,而且+ 写了两份,从来不是这条回答被写下时的源码。+- 现在,当选区覆盖到渲染出来的公式时,复制会从 MathML `annotation` 里把 TeX 读回来:+ 行内 `$…$`,块级 `$$…$$` 独占行。这正是 `lib/latex-math.ts` 在 `remark-math`+ 运行前把 `\(…\)` 和 `\[…\]` 归一到的那组定界符,因此粘回去的公式会渲染回它+ 来处的那个公式。落在公式内部的切口会扩展成整个公式——半个 TeX 表达式不成其为+ 公式,而横在两棵树之间的切口会从一棵里取到源码、从另一棵里取到字形。+- 每组定界符都像代码段的围栏那样,加长到盖过公式内部出现的最长同字符串,因为+ `$\$5 + x$` 会在那个转义美元处收口,粘回去变成普通文字。除此之外行内保持窄+ 形式,而理由并不是它乍看上去的那个:单行的 `$$…$$` 永远开不出块级公式,因为+ math flow 不允许开栅栏之后的 meta 段里出现 `$`。它保持窄形式,是因为行内公式+ 的 TeX 可能带换行——只有 `\(…\)` 那条路径的换行被归一化抹平了——此时 `$$` 会+ 落在行首、公式其余部分跟在它后面,那才是一个 flow 开栅栏,会把整段吞掉。+- 块级公式在这里并不总是一个块。`normalizeLatexMathDelimiters` 对 `\[ … \]` 是+ 等宽原地改写,因此数学节点仍是行内的,再由 `remarkLatexBracketDisplay` 提升,+ 于是 KaTeX 把 `.katex-display` 画在句子自己的段落里。归约照原样放入段落插槽:+ `p` 套 `p` 作为标记是非法的,但在这里无害——克隆只会经由文本序列化器读取,+ 而它把嵌套块当成一个边界。`$$` 上方有一个换行就足以让 `remark-math` 开出块级+ 公式,所以粘回去的仍是它来处的那个块级公式。两种 `\[ … \]` 形态都由+ E2E-CHAT-copy-formula-as-tex 钉住。+- 表格单元格是唯一一处块级插槽必须实测、而不能靠推理定论的地方;这里记下实测结果,+ 因为推理恰好指向了相反的方向。`remarkLatexBracketDisplay` 会提升任意位置的+ `\[ … \]` 节点,单元格也不例外,所以 `.katex-display` 确实会落进 `<td>`;+ 而表格序列化器用制表符拼接单元格,于是看上去那里的 `$$` 围栏会被制表符封死、+ 把该行其余内容吞掉(`a\tb\n$$\nE = mc^2\n$$\t2` 是一个值一直延伸到行尾的+ 公式节点)。Chromium 并不会写出这种字符串:块级盒子在单元格里同样是块级边界,+ 因此该行在它周围断开,围栏在自己的行上闭合,相邻单元格也落在自己的行上。这个+ 边界也不是插槽凭空造出来的——平台自己对同一行的读法里同样没有制表符,因为+ `.katex-display` 对它也会断行——所以在这里保留块级形式,正是这条决策其余部分+ 所依赖的那种一致性,而不是它的例外。「在单元格里收窄成行内形式」被考虑过并否决:+ 那会拿块级语义去修一个序列化器根本不产生的形态,还会把平台自己都不写的制表符+ 塞回去。E2E-CHAT-copy-formula-as-tex 同时钉住了这两半,因此哪天 Chromium 开始对+ 含块级盒子的单元格做制表符拼接,会在那里失败,而不是在用户的剪贴板里。+- 只有公式被改写。选区里其余的一切——正文、列表、表格、代码块——由平台自己序列化:+ 归约后的克隆被选中,经由 `Selection.toString()`——复制真正跑的那个序列化器——读回。+ 手写一遍树的遍历只能近似那套空白规则,而它每差一点,就会悄悄改写平台本来+ 已经做对的内容:段落里被放回源码的折行、列表项之间多出的空行、代码块里被压掉的+ 空行。+- 序列化器必须是复制自己那一个,而不是它的近邻。`innerText` 读出来几乎一样,却完全+ 不认识 `user-select`,于是会把 `base.css` 标为惰性的界面零件一起写出去——代码块的+ 语言标签会变成剪贴板里多出来的一行 `js`。把那条规则在归约里重述一遍,正是这条决策+ 所拒绝的手写遍历;跑平台自己的序列化器,让一致性从"近似"变成"精确"。克隆在选区+ 原本所处的那个元素里读,而不是挂到 `body` 上,因此决定这份读法的层叠就是实时+ 文档的层叠;反过来在克隆上重述选择契约(内联一条 `user-select: text`)会把它+ 倒置——外壳默认不可选、由文档型表面 opt-in,于是仅因继承而不可选的界面零件会进+ 入剪贴板。+- 其余选区一律不碰:不含公式的选区归平台管。除此之外不再判断这次复制"属不属于"+ 该选区,因为 Chromium 的事件目标本就是从选区推导出来的,非塌陷选区必定在自己+ 内部抬起复制;加一道目标检查只会误伤用 `selectNodeContents` 构造的选区,记录区+ 自己的「选中文本」就是其中之一。输入框里抬起的复制也带不走残留的记录区选区——+ 一个 frame 只有一个选区,聚焦任何字段都会让文档选区塌陷,而塌陷的选区本就会被+ 拒绝。+- 只有一种剪贴板 flavour:`text/plain`。接管复制的同时也丢掉了平台的 `text/html`,+ 而且不再写回。归约后的克隆是应用自己的标记:把它序列化会带上 `base.css` 标为+ `user-select: none`、文本读法已经略过的界面零件——代码块的 `js` 标签和它的复制+ 按钮——还有 `data-source-*` 记账信息,以及一个嵌在段落里的块级插槽,那是同一个+ 选区的第二份、也更差的读法。改为写回渲染结果同样不行:隐藏 MathML 树的只有+ KaTeX 自己的样式表,而样式表不会随剪贴板一起走,于是富文本粘贴目标会看到每个+ 公式出现两遍——正是这条决策要消除的那种重复。索性不写这个 flavour,两头都解决:+ 富文本目标回退到纯文本,而那正是源码。代价是含公式的选区粘进富文本目标时,会+ 失去平台 `text/html` 本来会携带的标签级格式;复制要的就是源码。+- 只有一个文档级 `copy` 监听器,由外壳装上、也由外壳摘掉(`hooks/use-copy-tex.ts`)。+ 因为 `Markdown` 自己不渲染任何包裹元素——回答、工作面板的文件预览、插件 readme+ 通过不同的父节点抵达同一批公式——也因为复制本来就是一个文档级手势。记录区的+ 右键复制经由同一个模块读取同一个选区,两个入口不会把同一个选区的两种读法送进+ 剪贴板。+- 把消息切成互相独立解析的块——这早于 D618,D618 只是把它换到了渲染语法上——仅当某一片不依赖其他片的解析上下文时才成立。链接与脚注定义恰是反例:它在整条消息范围内解析,脚注还要跨消息编号、复用和回链,于是脱离定义单独解析的引用会以字面 `[^1]` 留在正文里,脚注本身消失。因此只要消息中任意位置声明了定义,该消息就整体不切分。把定义注入每一片的做法被否决:那会让脚注按片各自重新编号,并把回链指向错误的引用。被接受的代价是这类消息在流式期间失去按块记忆——这正是渲染器在引入分块之前一直承担的成本,而它在聊天回答中的罕见程度把这个代价限住了。+- D618 不新增任何界面、store 状态或操作行条目:它把 ADR 0268 当年据以移除「引用」+ 的那个 OS 剪贴板,变成名副其实的替代品。仅渲染层——未改动任何 IPC 通道、宿主协议、+ 存储 schema、权限、Plugin SDK 或 i18n 键。见 `04-ux/08-component-spec.md` §8.7+ 与 E2E-CHAT-copy-formula-as-tex。diff --git a/package.json b/package.jsonindex 84fd27edf..a1918ad8d 100644--- a/package.json+++ b/package.json@@ -30,6 +30,7 @@"test:e2e:composer-autocomplete": "node scripts/e2e-composer-autocomplete.mjs","test:e2e:composer-paste": "node scripts/e2e-composer-paste.mjs","test:e2e:transcript": "node scripts/e2e-transcript-render.mjs",+ "test:e2e:copy-tex": "node scripts/e2e-copy-tex.mjs","test:e2e:transcript-disclosure": "node scripts/e2e-transcript-disclosure-anchor.mjs","test:e2e:images": "node scripts/e2e-image-generation.mjs && node scripts/e2e-image-generation-ui.mjs && node scripts/e2e-image-chat.mjs","test:e2e:provider-order": "node scripts/e2e-provider-order.mjs",diff --git a/pnpm-lock.yaml b/pnpm-lock.yamlindex 8ca258983..624bfb0af 100644--- a/pnpm-lock.yaml+++ b/pnpm-lock.yaml@@ -106,9 +106,6 @@ importers:lucide-react:specifier: ^1.31.0version: 1.31.0([email protected])- marked:- specifier: ^18.0.9- version: 18.0.9mermaid:specifier: ^11.16.1version: 11.16.1@@ -142,6 +139,9 @@ importers:remark-math:specifier: ^6.0.0version: 6.0.0+ remark-parse:+ specifier: ^11.0.0+ version: 11.0.0shiki:specifier: ^4.4.3version: 4.4.3@@ -151,6 +151,9 @@ importers:typescript:specifier: ^5.9.3version: 5.9.3+ unified:+ specifier: ^11.0.5+ version: 11.0.5vite:specifier: ^7.3.6@@ -3210,11 +3213,6 @@ packages:engines: {node: '>= 20'}hasBin: true- resolution: {integrity: sha512-/Sa4qiiHZxf0/FQdBBowr9q4r10krCwMvpK48FUBdXdUXScDxiQGR9zCPrFgRVR5LU3iySOiIjy09ZQvADir1w==}- engines: {node: '>= 20'}- hasBin: true-resolution: {integrity: sha512-OkeDaAZ/bQCxeFAozM55PKcKU0yJMPGifLwV4Qgjitu+5MoAfSQN4lsLJeXZ1b8w0x+/Emda6MZgXS1jvsapng==}engines: {node: '>=10'}@@ -7408,8 +7406,6 @@ snapshots:- [email protected]: {}-dependencies:escape-string-regexp: 4.0.0diff --git a/scripts/e2e-copy-tex.mjs b/scripts/e2e-copy-tex.mjsnew file mode 100644index 000000000..fb421fa1c--- /dev/null+++ b/scripts/e2e-copy-tex.mjs@@ -0,0 +1,120 @@+#!/usr/bin/env node+/**+ * Real KaTeX/Chromium regression for issue #414: a formula copied out of an+ * answer has to paste as the TeX it was written in.+ *+ * The reduction only exists at all because a rendered formula is two DOM trees,+ * so a fixture that fakes the DOM would prove nothing. This one mounts the real+ * `Markdown` renderer and the real `useCopyTex` hook in a real renderer+ * process, drags a real `Range` across a real KaTeX rendering, and reads back+ * what the `copy` event carried.+ */+import assert from "node:assert/strict";+import { spawn } from "node:child_process";+import { createRequire } from "node:module";+import { mkdtemp, rm, writeFile } from "node:fs/promises";+import { tmpdir } from "node:os";+import { dirname, join } from "node:path";+import { fileURLToPath } from "node:url";+import { resolveElectronBinary } from "./e2e/boot.mjs";++const root = join(dirname(fileURLToPath(import.meta.url)), "..");+const require = createRequire(join(root, "packages/agent-runtime/package.json"));+const { build } = require("esbuild");+const { electronBinary } = resolveElectronBinary(root);+const temp = await mkdtemp(join(tmpdir(), "pi-copy-tex-"));+try {+ await build({+ entryPoints: [join(root, "scripts/e2e/copy-tex.tsx")],+ outfile: join(temp, "renderer.js"),+ bundle: true,+ platform: "browser",+ format: "iife",+ jsx: "automatic",+ define: { "process.env.NODE_ENV": '"production"' },+ /*+ The reduction hands its clone to the platform's text serializer, so the+ cascade *is* the reading and this fixture has to carry the real one.+ Stylesheets arrive as text and the fixture injects them itself (see+ `STYLESHEETS` there), rather than through esbuild's CSS pipeline: as text+ nothing resolves KaTeX's `@font-face` URLs, so no font asset has to be+ bundled — and glyph metrics reach neither `Selection.toString()` nor any+ assertion in this suite.+ */+ loader: { ".css": "text" },+ alias: {+ "@pi-desktop/i18n": join(root, "packages/i18n/src/index.ts"),+ // The fixture lives outside the desktop package; use its React instance.+ react: join(root, "apps/desktop/node_modules/react"),+ "react-dom": join(root, "apps/desktop/node_modules/react-dom"),+ },+ nodePaths: [join(root, "apps/desktop/node_modules")],+ });+ await writeFile(+ join(temp, "index.html"),+ '<!doctype html><meta charset="utf-8"><title>Copy formula as TeX regression</title><script src="renderer.js"></script>',+ );+ await writeFile(+ join(temp, "main.cjs"),+ `+const { app, BrowserWindow } = require("electron");+const path = require("node:path");+app.setPath("userData", path.join(__dirname, "profile"));+app.whenReady().then(async () => {+ const window = new BrowserWindow({+ show: false,+ webPreferences: {+ sandbox: true,+ contextIsolation: true,+ nodeIntegration: false,+ backgroundThrottling: false,+ },+ });+ window.webContents.on("console-message", (event) => console.error(event.message));+ try {+ await window.loadFile(path.join(__dirname, "index.html"));+ const result = await window.webContents.executeJavaScript("globalThis.copyTexProbe()");+ console.log("COPY_TEX_PROBE " + JSON.stringify(result));+ app.quit();+ } catch (error) {+ console.error("COPY_TEX_PROBE " + JSON.stringify({ ok: false, error: String(error) }));+ app.exit(1);+ }+});+`,+ );+ const env = { ...process.env };+ delete env.ELECTRON_RUN_AS_NODE;+ const child = spawn(electronBinary, [join(temp, "main.cjs")], {+ env,+ stdio: ["ignore", "pipe", "pipe"],+ });+ let output = "";+ for (const stream of [child.stdout, child.stderr])+ stream.on("data", (data) => {+ output += data;+ });+ const timeout = setTimeout(() => child.kill("SIGKILL"), 60_000);+ let code;+ try {+ code = await new Promise((resolve, reject) => {+ child.once("error", reject);+ child.once("close", resolve);+ });+ } finally {+ clearTimeout(timeout);+ }+ const line = output+ .split(/\r?\n/)+ .find((line) => line.startsWith("COPY_TEX_PROBE "));+ assert(+ line,+ `renderer returned no probe result (exit=${code}): ${output.slice(-2000)}`,+ );+ const result = JSON.parse(line.slice("COPY_TEX_PROBE ".length));+ console.log("COPY_TEX_PROBE " + JSON.stringify(result));+ assert.equal(code, 0, output.slice(-6000));+ assert.equal(result.ok, true);+} finally {+ await rm(temp, { recursive: true, force: true });+}diff --git a/scripts/e2e/copy-tex.tsx b/scripts/e2e/copy-tex.tsxnew file mode 100644index 000000000..88d3332c0--- /dev/null+++ b/scripts/e2e/copy-tex.tsx@@ -0,0 +1,789 @@+import { createRoot } from "react-dom/client";+import { flushSync } from "react-dom";+import { createInstance } from "i18next";+import { I18nextProvider } from "react-i18next";+import { en } from "@pi-desktop/i18n";+import baseCss from "../../apps/desktop/src/styles/base.css";+import katexCss from "katex/dist/katex.min.css";+import {+ ContextMenu,+ useContextMenu,+} from "../../apps/desktop/src/components/ContextMenu";+import { Markdown } from "../../apps/desktop/src/components/Markdown";+import { useCopyTex } from "../../apps/desktop/src/hooks/use-copy-tex";+import {+ KATEX_DISPLAY_SELECTOR,+ KATEX_SELECTOR,+ KATEX_TEX_SELECTOR,+} from "../../apps/desktop/src/lib/selection-tex";++declare global {+ var copyTexProbe: () => Promise<unknown>;+}++function assert(value: unknown, message: string): asserts value {+ if (!value) throw new Error(message);+}++function assertEqual(actual: string, expected: string, what: string): void {+ assert(+ actual === expected,+ `${what} was ${JSON.stringify(actual)}, expected ${JSON.stringify(expected)}`,+ );+}++/**+ * The real `Markdown` renderer under the real shell hook and the real+ * transcript menu: KaTeX paints both of its trees into a real document, a real+ * `Range` is dragged across them, and a real `copy` event carries whatever the+ * hook decided to write.+ */+function Fixture({+ cases,+ onMenuCopy,+}: {+ cases: Record<string, string>;+ onMenuCopy: (selection: string) => void;+}) {+ useCopyTex();+ const { contextMenu, openContextMenu, closeContextMenu } = useContextMenu();+ return (+ <>+ {Object.entries(cases).map(([name, source]) => (+ <div+ className="prose-chat"+ data-case={name}+ key={name}+ onContextMenu={(event) =>+ openContextMenu(event, {+ label: "Message actions",+ items: [{ id: "copy", label: "Copy", onSelect: onMenuCopy }],+ })+ }+ >+ <Markdown source={source} />+ </div>+ ))}+ {/*+ A turn the way the transcript builds one: prose that opts into+ selection, with chrome between it that is inert only because it+ inherits the shell's `user-select: none`. `.tool-row-section-head` is+ one of the real ones; a `button` in its place would prove nothing,+ because `base.css` marks those inert by selector and they stay inert in+ any ancestor context.+ */}+ <div data-case="chrome">+ <div className="prose-chat">+ <Markdown source="Before $x^2$ here." />+ </div>+ <div className="tool-row-section-head">+ <span>Output</span>+ </div>+ <div className="prose-chat">+ <Markdown source="After the tool row." />+ </div>+ </div>+ <ContextMenu state={contextMenu} onClose={closeContextMenu} />+ </>+ );+}++type Copied = { prevented: boolean; text: string; html: string };++/**+ * A copy raised on `target`, which the listener must not read.+ *+ * Chromium picks the target itself, by walking the selection's canonicalized+ * start position up to its element — for every `selectContents` below that is+ * a descendant of the node the range was built on, never the node itself. The+ * cases pass both shapes in so a listener that started consulting the target+ * again would fail here rather than in the user's clipboard.+ */+function rawCopy(target: Element): Copied {+ const clipboardData = new DataTransfer();+ const event = new ClipboardEvent("copy", {+ bubbles: true,+ cancelable: true,+ clipboardData,+ });+ target.dispatchEvent(event);+ return {+ prevented: event.defaultPrevented,+ text: clipboardData.getData("text/plain"),+ html: clipboardData.getData("text/html"),+ };+}++const WRAPPED = [+ "A long sentence about $x$ that the model",+ "wrapped across two source lines and",+ "continues here.",+].join("\n");++const CASES = {+ displayBlank: "$$\n- x\n\n+ y\n$$",+ displayCrlf: "$$\r\n- x\r\n$$",+ displayMinus: "\\[ - x \\]",+ displayPlus: "\\[ + x \\]",+ displayStar: "\\[ * x \\]",+ displayQuote: "\\[ > x \\]",++ multilineDollar: "Value $$a +\n\\text{\\$5}$$ here.",+ multilineComment: "Value $$a % note\nb + \\text{\\$5}$$ here.",+ markerText: "\uE0000\uE000 $x$",+ multilineBoundary: "\\$**$$a +\n\\text{\\$5}$$**\\$",+ proseDollarAfter: "\\(x\\)\\$",+ proseDollarBefore: "\\$\\(x\\)",+ proseDollarsBoth: "\\$\\(x\\)\\$",+ proseDollarWrapped: "\\$**$x$**\\$",+ proseDollarBetween: "$x$\\$**$y$**",+ /*+ A prose dollar the escaping cannot see from a fence: one on each side of+ the formula and neither touching it. Left alone they pair across the+ formula's own fences — `Run $HOME then $x$ costs $5.` paints `HOME then `+ and ` costs ` and loses `x` entirely — so the round trip below, not the+ expected string, is what this case is here for.+ */+ proseDollarDistant: "Run \\$HOME then $x$ costs \\$5.",++ adjacent: "The identity $a$**$b$**$c$ closes the proof.",+ inertGap: "$a$**$b$**",+ separated: "$a$ **$b$**",+ lineBreak: "$a$ \n**$b$**",+ paragraphs: "$a$\n\n$b$",+ dollarAtEdge: "\\( 5\\$ \\)",+ padded: "$$ x $$",+ trailingDollar: "\\(5\\$ \\)",+ inline: "The identity $a^2+b^2=c^2$ closes the proof.",+ display: "$$\n\\int_0^1 x^2\\,dx\n$$",+ mixed: "First paragraph.\n\n$$\nE = mc^2\n$$\n\nLast paragraph.",+ prose: "Nothing but prose here.",+ /*+ The shapes a model actually emits. `normalizeLatexMathDelimiters` rewrites+ `\[ … \]` in place — the rewrite is length-preserving — so the math node+ stays *inline* and `remarkLatexBracketDisplay` promotes it, which paints+ `.katex-display` inside the sentence's own paragraph. That is the only+ place the display slot lands in an inline context, and the only place the+ reduction nests a `p` in a `p`; both readings below pin what it produces.+ */+ bracketMid: "The result \\[E = mc^2\\] closes the proof.",+ bracketOwnLine: "\\[\nE = mc^2\n\\]",+ parenInline: "Inline \\(x^2\\) here.",+ /*+ The two shapes that decide the delimiter run in `texSource`, and the only+ cases here whose point is invisible in the clipboard string: a formula+ carrying a literal `$` needs a run that outgrows it, and a formula whose+ value carries a newline needs the run to stay narrow. The round trip below+ is what fails when either half of that rule is wrong.+ */+ dollar: "Cost \\(\\$5 + x\\) today.",+ multiline: "The value $a +\nb$ here.",+ /*+ The same narrow run, with the padding the grammar eats. The space on each+ side of the formula is load-bearing rather than stray: it is what leaves+ the annotation a line ending at either edge, which is the padding the copy+ then has to write back. Drop either space and this is `multiline` again.+ */+ paddedMultiline: "The value $ \na +\nb\n $ here.",+ // Everything below is prose the platform already serialized correctly: a+ // formula in the same selection must not rewrite any of it.+ wrapped: WRAPPED,+ list: "- first item with $x^2$\n- second item\n- third item",+ table: "| a | b |\n| --- | --- |\n| $x$ | 2 |\n| 3 | 4 |",+ /*+ A display slot inside a table cell — the one place a `$$` fence could be+ closed by a tab instead of a line ending. `remarkLatexBracketDisplay`+ promotes a `\[ … \]` node wherever it sits, cells included, so this is the+ shape that puts `.katex-display` inside a `<td>`. What the reading does+ there is measured below, not argued from the grammar.+ */+ tableDisplay: "| a | b |\n| --- | --- |\n| \\[E = mc^2\\] | 2 |",+ code: "Formula $x$ here.\n\n```js\nconst a = 1;\n\n\n\nconst b = 2;\n```",+};++/*+ The real stylesheets, not a restatement of them. The reduction reads its+ clone through the platform's text serializer, so the reading turns on+ `display`, `white-space`, `visibility` and `user-select` as the live cascade+ resolves them; a fixture that paraphrased those rules would drift from the+ app and could not tell the copy's own serializer apart from `innerText`,+ which ignores `user-select` and writes a code block's language rail into the+ clipboard.++ `base.css` carries the selection contract in its real shape — the shell is+ unselectable at `html, body, #root` and document-like surfaces opt back in,+ which is what the `chrome` case turns on: the default has to be *none* with+ surfaces opting in, not merely a few selectors saying `none`. KaTeX's own+ stylesheet is here because the wrapper is mounted inside the live formula+ whenever a selection never leaves one, so that cascade is the one the clone+ inherits (see `hostElementOf`).++ Two sheets, not the whole `styles/` directory, and the omission was checked+ rather than assumed: a sheet earns a place here only by deciding one of the+ four properties for content a formula can be selected with. `prose.css` does+ set `display`, `white-space` and `user-select` under `.prose-chat`, and every+ one of those either restates a UA default the fixture already gets+ (`.prose-chat .code-block pre code` re-declaring `pre`'s own+ `white-space: pre`) or sits inside an element `base.css` already marks inert+ (`.code-block-lang` under `.code-block-head`, which is what the `code` case's+ missing `js` rail proves). `messages.css` keeps its own `white-space` and+ `user-select` rules on surfaces that never render a formula — the user+ bubble, the edit textarea, tool-row gutters — so none of them moves a reading+ asserted below. The rest of what both sheets carry, `overflow` and+ `font-size` and spacing and colour, never reaches the text serializer. Add a+ sheet the moment that stops being true, not on principle: an unread rule here+ costs layout on every case and blurs which rule a reading rests on.++ Injected by hand rather than left to `Markdown`'s own+ `import "katex/dist/katex.min.css"`: that is a bare import of a file the+ package marks side-effect free, so the bundler drops it and nothing would+ reach the document. Keep both here even if the app's import starts surviving+ — the fixture has to name the cascade it tests.+*/+const STYLESHEETS = `${baseCss}\n${katexCss}`;++globalThis.copyTexProbe = async () => {+ const i18n = createInstance();+ await i18n.init({+ lng: "en",+ resources: { en: { translation: en } },+ interpolation: { escapeValue: false },+ });+ const style = document.createElement("style");+ style.textContent = STYLESHEETS;+ document.head.append(style);+ const host = document.createElement("div");+ host.style.width = "700px";+ document.body.append(host);+ const root = createRoot(host);+ // Where a clipboard string is rendered back, to answer the only question the+ // strings below cannot: whether what the copy wrote still paints the formula+ // it came from. See `copy`.+ const echo = document.createElement("div");+ echo.className = "prose-chat";+ document.body.append(echo);+ const echoRoot = createRoot(echo);+ let menuCopy: string | null = null;+ try {+ flushSync(() =>+ root.render(+ <I18nextProvider i18n={i18n}>+ <Fixture+ cases={CASES}+ onMenuCopy={(selection) => {+ menuCopy = selection;+ }}+ />+ </I18nextProvider>,+ ),+ );+ const selection = window.getSelection();+ assert(selection, "the document has no selection");+ const block = (name: string) => {+ const element = host.querySelector<HTMLElement>(`[data-case="${name}"]`);+ assert(element, `case ${name} did not render`);+ return element;+ };+ const select = (range: Range) => {+ selection.removeAllRanges();+ selection.addRange(range);+ };+ const selectContents = (node: Node) => {+ const range = document.createRange();+ range.selectNodeContents(node);+ select(range);+ };+ const rightClickCopy = async (row: Element): Promise<string> => {+ menuCopy = null;+ row.dispatchEvent(+ new MouseEvent("contextmenu", { bubbles: true, cancelable: true }),+ );+ await Promise.resolve();+ const item = document.querySelector<HTMLElement>(+ '[data-context-menu-item="copy"]',+ );+ assert(item, "the context menu did not open");+ item.click();+ await Promise.resolve();+ return menuCopy ?? "";+ };++ /** Every formula in `element`, as the pair a round trip has to preserve. */+ const formulas = (element: Element) =>+ Array.from(element.querySelectorAll(KATEX_SELECTOR)).map((katex) => ({+ tex: katex.querySelector(KATEX_TEX_SELECTOR)?.textContent ?? "",+ display: Boolean(katex.closest(KATEX_DISPLAY_SELECTOR)),+ }));++ /*+ A copy, and the round trip that is the point of copying TeX at all.++ The strings the cases below assert say what reached the clipboard; they+ cannot say whether it still *means* the formula it came from. So every+ copy is rendered back through the same `Markdown` that painted the+ original — which is the paste path, `normalizeLatexMathDelimiters` and+ `remarkLatexBracketDisplay` included — and the formulas it paints are+ compared with the ones the selection covered, by TeX and by whether they+ are display math. That pins the delimiter choice (`$…$` inline so a+ pasted sentence cannot open a display block, `$$…$$` on their own lines+ so it does) and the one reading no expected string explains: a `\[ … \]`+ formula copies with a single newline above `$$`, which is enough for+ `remark-math` to open the display block it came from. Comparing against+ the live formulas rather than a literal keeps the expectation in one+ place — the fixture cannot pass by agreeing with itself.+ */+ const copy = (target: Element): Copied => {+ const copied = rawCopy(target);+ if (!copied.text) return copied;+ flushSync(() =>+ echoRoot.render(+ <I18nextProvider i18n={i18n}>+ <Markdown source={copied.text} />+ </I18nextProvider>,+ ),+ );+ assertEqual(+ JSON.stringify(formulas(echo)),+ JSON.stringify(formulas(target)),+ `formulas surviving ${JSON.stringify(copied.text)}`,+ );+ return copied;+ };++ // Exercise copy -> Markdown, including boundaries across formatting wrappers.+ for (const [name, expected] of [+ ["displayBlank", "$$\n- x\n\n+ y\n$$"],+ ["displayCrlf", "$$\n- x\n$$"],+ ["displayMinus", "$$\n- x\n$$"],+ ["displayPlus", "$$\n+ x\n$$"],+ ["displayStar", "$$\n* x\n$$"],+ ["displayQuote", "$$\n> x\n$$"],+ ["markerText", "\uE0000\uE000 $x$"],+ ["multilineBoundary", "\\$<span>$$a +\n\\text{\\$5}$$</span>\\$"],+ ["proseDollarAfter", "$x$\\$"],+ ["proseDollarBefore", "\\$$x$"],+ ["proseDollarsBoth", "\\$$x$\\$"],+ ["proseDollarWrapped", "\\$$x$\\$"],+ ["proseDollarBetween", "$x$\\$$y$"],+ ["proseDollarDistant", "Run \\$HOME then $x$ costs \\$5."],+ ["adjacent", "The identity $a$ $b$ $c$ closes the proof."],+ ["inertGap", "$a$ $b$"],+ ["separated", "$a$ $b$"],+ ["lineBreak", "$a$\n$b$"],+ ["paragraphs", "$a$\n\n$b$"],+ ["dollarAtEdge", "$$ 5\\$ $$"],+ ["padded", "$ x $"],+ ["trailingDollar", "$$5\\$ $$"],+ ]) {+ const element = block(name);+ if (name === "inertGap") {+ const chrome = document.createElement("span");+ chrome.style.userSelect = "none";+ chrome.textContent = "Unselectable chrome";+ element.querySelector("strong")!.before(chrome);+ }+ selectContents(element);+ assertEqual(copy(element).text, expected, `${name} copy`);+ selectContents(element);+ assertEqual(await rightClickCopy(element), expected, `${name} menu copy`);+ }++ for (const name of ["multilineDollar", "multilineComment"]) {+ const element = block(name);+ const formula = element.querySelector(KATEX_SELECTOR)!;+ selectContents(element);+ copy(element);+ selectContents(formula);+ const copied = copy(element);+ selectContents(formula);+ assertEqual(await rightClickCopy(element), copied.text, `${name} menu copy`);+ }++ // Reuse the same mounted Markdown while a math fence streams across+ // blank lines. Its body must remain the tail until the fence closes.+ for (const suffix of ["", "\n\n+ y", "\n\n+ y\n$$", "\n\n+ y\n$$\n\nAfter."]) {+ const source = "Before.\n\n$$\n- x" + suffix;+ flushSync(() => echoRoot.render(+ <I18nextProvider i18n={i18n}><Markdown source={source} /></I18nextProvider>,+ ));+ assertEqual(JSON.stringify(formulas(echo)), JSON.stringify([+ { tex: suffix ? "- x\n\n+ y" : "- x", display: true },+ ]), "streaming display math");+ assert(!echo.querySelector("ul, ol, blockquote"), "math became a prose block");+ if (source.endsWith("After.")) {+ const after = Array.from(echo.querySelectorAll("p")).find(p => p.textContent === "After.");+ assert(after, "closed math swallowed the following paragraph");+ assertEqual(after.getAttribute("data-source-start") ?? "", String(source.indexOf("After.")), "following paragraph offset");+ }+ }++ /*+ Same mounted Markdown, streaming a footnote. The definition arrives after+ the paragraph that references it, so this is the one place the renderer+ has to give up block splitting: a reference resolved against its own+ slice alone survives as the literal `[^1]` and the note disappears.+ */+ for (const [source, resolved] of [+ ["Text[^1].\n", false],+ ["Text[^1].\n[^1]: adjacent note\n", true],+ ["Text[^1].\n[^1]: adjacent note\n\nAnd more[^2].\n\n[^2]: later note\n", true],+ ] as const) {+ flushSync(() => echoRoot.render(+ <I18nextProvider i18n={i18n}><Markdown source={source} /></I18nextProvider>,+ ));+ const notes = echo.querySelector("section[data-footnotes]");+ assert(resolved === Boolean(notes), `footnote section for ${JSON.stringify(source)}`);+ if (!notes) continue;+ assertEqual(+ echo.querySelectorAll("a[data-footnote-ref]").length.toString(),+ (source.match(/\[\^\d\]\./g) ?? []).length.toString(),+ "footnote references",+ );+ assert(!echo.textContent?.includes("[^"), "a footnote reference stayed literal");+ assert(notes.textContent?.includes("adjacent note"), "the note text is missing");+ }++ const inline = block("inline");+ assert(inline.querySelector(".katex"), "the inline formula did not render");+ assert(+ inline.querySelector('annotation[encoding="application/x-tex"]'),+ "KaTeX rendered no TeX annotation",+ );+ selectContents(inline);+ const rendered = selection.toString();+ const inlineCopy = copy(inline);+ assert(inlineCopy.prevented, "the inline copy was left to the platform");+ assertEqual(inlineCopy.text, CASES.inline, "inline copy");+ // The bug this fixes: the platform's own reading of the same selection.+ assert(+ rendered !== CASES.inline,+ "the rendering already reads as its source; this fixture proves nothing",+ );+ /*+ One flavour. Taking the copy over drops the platform's `text/html` too,+ and none is written back: the clone is the app's own markup, so it would+ carry the `user-select: none` chrome the text reading drops and paste the+ formula twice over, KaTeX's stylesheet being the only thing that hides+ the MathML tree. A rich paste target falls back to the plain text.+ */+ assertEqual(inlineCopy.html, "", "inline copy HTML flavour");++ const display = block("display");+ const wrapper = display.querySelector(".katex-display");+ assert(wrapper, "the display formula did not render in display layout");+ selectContents(display);+ assertEqual(copy(display).text, "$$\n\\int_0^1 x^2\\,dx\n$$", "display copy");+ // A range that stops at the display wrapper's own edges, rather than+ // inside the formula, still knows this is display math.+ selectContents(wrapper);+ assertEqual(+ copy(display).text,+ "$$\n\\int_0^1 x^2\\,dx\n$$",+ "display copy bounded by the wrapper",+ );++ const mixed = block("mixed");+ selectContents(mixed);+ assertEqual(copy(mixed).text, CASES.mixed, "mixed copy");++ /*+ `\[ … \]` display math sits inside the sentence's own paragraph, so the+ display slot lands in an inline context and the reduction nests a `p` in+ a `p`. The reading is still the one that matters: a single newline above+ `$$` is enough for `remark-math` to open the display block, so the+ formula pastes back as the display formula it came from. `\( … \)` is+ normalized to `$$ … $$` too but is never promoted, so it stays inline.+ */+ const bracketMid = block("bracketMid");+ assert(+ bracketMid.querySelector("p .katex-display"),+ "`\\[ … \\]` no longer renders as display math inside a paragraph",+ );+ selectContents(bracketMid);+ assertEqual(+ copy(bracketMid).text,+ "The result\n$$\nE = mc^2\n$$\n\ncloses the proof.",+ "bracket display copy",+ );++ const bracketOwnLine = block("bracketOwnLine");+ selectContents(bracketOwnLine);+ assertEqual(+ copy(bracketOwnLine).text,+ "$$\nE = mc^2\n$$",+ "bracket display copy on its own lines",+ );++ const parenInline = block("parenInline");+ assert(+ !parenInline.querySelector(".katex-display"),+ "`\\( … \\)` was promoted to display math",+ );+ selectContents(parenInline);+ assertEqual(copy(parenInline).text, "Inline $x^2$ here.", "paren inline copy");++ /*+ The delimiter run, in the two directions that pin it. A formula carrying+ a literal `$` needs a run wider than the one inside it — `$\$5 + x$`+ closes at the escaped dollar, and the round trip inside `copy` is what+ catches that, because the clipboard string looks right either way. A+ formula whose value carries a newline needs the run to stay narrow: `$$`+ would land at the start of a line with the rest of the formula behind it,+ which opens a flow block and swallows the paragraph. Only the `\( … \)`+ path has its newlines flattened by `normalizeLatexMathDelimiters`, so a+ `$ … $` formula really can reach the reduction with one in it.+ */+ const dollar = block("dollar");+ selectContents(dollar);+ assertEqual(copy(dollar).text, "Cost $$\\$5 + x$$ today.", "dollar copy");++ const multiline = block("multiline");+ assertEqual(+ multiline.querySelector(KATEX_TEX_SELECTOR)?.textContent ?? "",+ "a +\nb",+ "the inline formula lost the newline its source carried",+ );+ selectContents(multiline);+ assertEqual(+ copy(multiline).text,+ "The value $a +\nb$ here.",+ "multiline inline copy",+ );++ /*+ A line ending at either edge of the annotation is padding to the grammar,+ exactly as a space is, so the copy has to write padding of its own for+ the round trip inside `copy` to see the formula it started from.+ */+ const padded = block("paddedMultiline");+ assertEqual(+ padded.querySelector(KATEX_TEX_SELECTOR)?.textContent ?? "",+ "\na +\nb\n",+ "the inline formula lost the padding its source carried",+ );+ selectContents(padded);+ assertEqual(+ copy(padded).text,+ "The value $ \na +\nb\n $ here.",+ "padded multiline inline copy",+ );++ // A cut through the middle of a formula: half a TeX expression is not a+ // formula, so the range grows to the whole one before it is read.+ const glyphs = inline.querySelector(".katex-html");+ assert(glyphs, "KaTeX rendered no visual tree");+ const walker = document.createTreeWalker(glyphs, NodeFilter.SHOW_TEXT);+ const insideFormula = walker.nextNode();+ assert(insideFormula, "the visual tree carries no text");+ const paragraph = inline.querySelector("p");+ assert(paragraph, "the inline case rendered no paragraph");+ const partial = document.createRange();+ partial.setStart(insideFormula, 0);+ partial.setEnd(paragraph, paragraph.childNodes.length);+ select(partial);+ assertEqual(+ copy(inline).text,+ "$a^2+b^2=c^2$ closes the proof.",+ "partial copy",+ );++ /*+ A selection that never leaves the formula — a double-click on a glyph, a+ drag across half a rendering. Its common ancestor is inside the `.katex`+ the reduction replaces, so the clone is read mounted within the live+ formula; this is the case `hostElementOf` reasons about, and the reading+ it has to keep is one whole formula and nothing else.+ */+ const whole = document.createRange();+ whole.setStart(insideFormula, 0);+ whole.setEnd(insideFormula, (insideFormula as Text).length);+ select(whole);+ assertEqual(copy(inline).text, "$a^2+b^2=c^2$", "copy from inside one formula");++ /*+ Only the formulas are rewritten. The rest of the selection is the+ platform's own serialization, so a formula must not put the source's line+ wrapping back into a paragraph, and must not reflow a list, a table, or a+ code block that happens to share the selection with it.+ */+ const wrapped = block("wrapped");+ selectContents(wrapped);+ assertEqual(+ copy(wrapped).text,+ "A long sentence about $x$ that the model wrapped across two source" ++ " lines and continues here.",+ "wrapped-paragraph copy",+ );++ const list = block("list");+ selectContents(list);+ assertEqual(+ copy(list).text,+ "first item with $x^2$\nsecond item\nthird item",+ "list copy",+ );++ /*+ The trailing newline is the platform's: its own reading of this selection+ ends with one, formula or no formula, because that is how it closes a+ table's last row. It is asserted rather than trimmed for the same reason+ nothing else here is — the reduction answers for the formulas and for+ nothing around them. A clone read outside the context it came from loses+ it, which is how this line found the mount that keeps it.+ */+ const table = block("table");+ selectContents(table);+ assert(+ selection.toString().endsWith("\n"),+ "the platform stopped closing a table row with a newline",+ );+ assertEqual(copy(table).text, "a\tb\n$x$\t2\n3\t4\n", "table copy");++ /*+ Display math inside a table cell, which is the one shape whose reading+ cannot be predicted from the grammar and was measured instead.+ `remarkLatexBracketDisplay` promotes a `\[ … \]` node wherever it sits, so+ KaTeX paints `.katex-display` inside a `<td>` while the table serializer+ joins cells with tabs — which reads like a trap, since a `$$` fence+ closed by a tab would swallow the rest of the row into the formula+ (`a\tb\n$$\nE = mc^2\n$$\t2` is one math node whose value runs to the end+ of the line). It is not one: a block slot is a block boundary in a cell+ too, so the row breaks around it and the fence closes on its own line.+ The expected string below is what Chromium actually writes.++ The parity assertion is what makes that a guard rather than a snapshot.+ The platform's own reading of this row has no tab in it either — the+ `.katex-display` box breaks the row for the platform exactly as the slot+ does for the reduction — so the slot is not inventing a boundary, it is+ keeping the one that was already there. A reading that grew a tab would+ mean the block boundary had gone away, which is the case where the fence+ would have to narrow to the inline run; assert it here rather than+ narrowing pre-emptively and paying display math for a shape Chromium+ does not produce.+ */+ const tableDisplay = block("tableDisplay");+ assert(+ tableDisplay.querySelector(KATEX_DISPLAY_SELECTOR),+ "`\\[ … \\]` no longer renders as display math inside a table cell",+ );+ selectContents(tableDisplay);+ assert(+ !selection.toString().slice("a\tb".length).includes("\t"),+ `the platform started tab-joining a cell that holds a block: ${JSON.stringify(selection.toString())}`,+ );+ assertEqual(+ copy(tableDisplay).text,+ "a\tb\n$$\nE = mc^2\n$$\n\n2\n",+ "table display copy",+ );++ /*+ Asserted whole, not by fragments: the prose, the block's own bytes with+ its blank lines, and — the part fragments cannot see — the absence of the+ `js` language rail. `.code-block-head` is `user-select: none`, so the+ platform's copy leaves it behind and the reduction has to as well; a+ reading taken with `innerText` passes every `includes` here and still+ pastes a stray `js` line into the user's document.+ */+ const code = block("code");+ selectContents(code);+ const platformCode = selection.toString();+ assertEqual(+ copy(code).text,+ "Formula $x$ here.\n\nconst a = 1;\n\n\n\nconst b = 2;",+ "code copy",+ );+ assert(+ !platformCode.includes("js"),+ `the fixture lost its selection rules: ${JSON.stringify(platformCode)}`,+ );++ /*+ The clone is read in the ancestor context the selection came from, so+ the cascade that decides the reading is the live one — chrome that is+ inert only by inheriting the shell's `user-select: none` stays out of+ the clipboard, exactly as it does for the platform's own copy. A clone+ parked on `body` has to restate that contract to be readable at all, and+ restating it inverts it: the default turns selectable and this label+ arrives in the copy.+ */+ const chrome = block("chrome");+ selectContents(chrome);+ const platformChrome = selection.toString();+ assert(+ !platformChrome.includes("Output"),+ `the fixture lost its selection rules: ${JSON.stringify(platformChrome)}`,+ );+ assertEqual(+ copy(chrome).text,+ "Before $x^2$ here.\n\nAfter the tool row.",+ "copy across inert chrome",+ );++ // Prose without a formula stays the platform's business.+ const prose = block("prose");+ selectContents(prose);+ const proseCopy = copy(prose);+ assert(!proseCopy.prevented, "a formula-free copy was taken over");+ assert(proseCopy.text === "", "a formula-free copy wrote to the clipboard");++ /*+ The target Chromium really raises a copy on, which is not the node the+ range was built from. `selectNodeContents` — the shape the transcript's+ own "Select text" item produces — leaves anchor and focus on that node,+ while the event lands on the paragraph inside it. A listener that gated+ on `target.contains(anchorNode)` read this as a copy belonging to some+ other selection and handed the glyphs back; the whole selection has to+ reach the clipboard as its source however deep the event was raised.+ */+ selectContents(inline);+ assert(+ selection.anchorNode === inline && selection.focusNode === inline,+ "selectNodeContents stopped anchoring on the node it was given",+ );+ const raisedDeep = copy(inline.querySelector("p")!);+ assert(raisedDeep.prevented, "a copy raised inside the selection was declined");+ assertEqual(raisedDeep.text, CASES.inline, "copy raised on a descendant");++ /*+ The reduction borrows the live selection to read the clone back, so it+ has to hand it over unchanged — including which end the user is holding.+ A range does not carry that, which is why anchor and focus are restored+ rather than a cloned range: otherwise a backward selection comes back+ forward and the next Shift+Arrow grows it off the opposite edge.+ */+ const backwards = inline.querySelector("p");+ assert(backwards?.firstChild && backwards.lastChild, "the sentence is empty");+ const tail = backwards.lastChild as Text;+ selection.setBaseAndExtent(tail, tail.length, backwards.firstChild, 0);+ assert(selection.anchorNode === tail, "the fixture built a forward selection");+ const backwardCopy = copy(inline);+ assertEqual(backwardCopy.text, CASES.inline, "backward selection copy");+ assert(+ selection.anchorNode === tail && selection.focusNode === backwards.firstChild,+ "the copy turned a backward selection forward",+ );++ /*+ The transcript's right-click Copy reads the same selection through the+ same module, so the two entry points cannot put two readings of one+ selection on the clipboard — and a selection another row owns is still+ not this row's excerpt.+ */+ selectContents(inline);+ assertEqual(await rightClickCopy(inline), CASES.inline, "right-click Copy");+ selectContents(inline);+ assertEqual(+ await rightClickCopy(prose),+ "",+ "right-click Copy in another row",+ );++ return { ok: true, rendered, inline: inlineCopy.text };+ } finally {+ flushSync(() => root.unmount());+ host.remove();+ flushSync(() => echoRoot.unmount());+ echo.remove();+ }+};