Skip to content

Local-first AI coding agent desktop: Electron + Rust host core + pi Agent Harness + user-installable plugins

Merge branch 'main' into fix/katex-copy-tex-source

vastsa00d7abfcd4a7
diff --cc apps/desktop/src/hooks/use-copy-tex.ts
index db52be07e,000000000..123fa0fb2
mode 100644,000000..100644
--- a/apps/desktop/src/hooks/use-copy-tex.ts
+++ b/apps/desktop/src/hooks/use-copy-tex.ts
@@@ -1,56 -1,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).
++ * (issue #414, D619).
+ *
+ * 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 --cc apps/desktop/src/lib/selection-tex.ts
index 8f349f2fc,000000000..df091e387
mode 100644,000000..100644
--- a/apps/desktop/src/lib/selection-tex.ts
+++ b/apps/desktop/src/lib/selection-tex.ts
@@@ -1,518 -1,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
++ // Markdown source, on the same ground D619 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
++ * is the hand-written structural walk this module exists to avoid. D619 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 --cc docs/spec/04-ux/08-component-spec.md
index 1a48aae19,be8f0490e..bb32ab221
--- a/docs/spec/04-ux/08-component-spec.md
+++ b/docs/spec/04-ux/08-component-spec.md
@@@ -1904,48 -1899,6 +1904,48 @@@ Renderer: `apps/desktop/src/components/
additions and the `math-inline`/`math-display` classes on `code` (which keep
TeX `\[…\]` in display layout) are admitted. KaTeX's Vite-inlined WOFF2 fonts
are allowed by the renderer's `font-src 'self' data:` CSP directive.
- - **Copying a formula (D618)**: a selection that covers rendered math reaches
++- **Copying a formula (D619)**: 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 assistant
answer prose renders through the official Mermaid package. The dependency is
dynamically imported only when a diagram approaches the viewport; Mermaid's
diff --cc docs/spec/06-delivery/04-e2e-test-plan.md
index 06a93502c,9d95e4860..2d5e71f51
--- a/docs/spec/06-delivery/04-e2e-test-plan.md
+++ b/docs/spec/06-delivery/04-e2e-test-plan.md
@@@ -3684,101 -3684,6 +3684,101 @@@ identify the platform validation still
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
++ decisions-log D619, 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 a
diff --cc docs/spec/08-meta/decisions-log.md
index b7a078516,72cdb22e8..d5f29b48b
--- a/docs/spec/08-meta/decisions-log.md
+++ b/docs/spec/08-meta/decisions-log.md
@@@ -304,7 -304,6 +304,7 @@@ Gold source: local Codex electron captu
| 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. |
++| D619 | 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
@@@ -6703,142 -6729,19 +6730,158 @@@ that was sitting at the bottom — incl
empty range, or one past that request bound, still falls back on budget
grounds. 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)
++## 2026-09-20 — A copied formula is its TeX source (D619, 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
++- Splitting a message into independently parsed blocks, which predates D619 and
++ which D619 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
++- D619 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.
+ ## 2026-09-22 — pi's file-op collector is fed the names it reads (D618, issue #827)
+
+ - A checkpoint's `readFiles` / `modifiedFiles`, and the `<read-files>` section a
+ summary appends, come from pi's own `extractFileOpsFromMessage`, which switches
+ on the lowercase names `read` / `write` / `edit` — the names pi's tools carry.
+ PI-Desktop registers `Read` / `Write` / `Edit`, so the collector matched
+ nothing and every checkpoint reported an empty file list; issue #827 turned
+ this up while reading a compaction report.
+ - The conversion stays on our side of the boundary. `withPiFileOpToolNames`
+ copies the entries handed to pi's `prepareCompaction` with exactly those three
+ names respelled; no stored byte changes — a transcript, a checkpoint and a
+ rebuilt context keep our names — and the input array comes back untouched when
+ no such call is present, so the common path allocates nothing.
+ - Only those three are converted. pi's collector reads nothing else, so `Grep`,
+ `Glob`, `Bash`, plugin and MCP names keep the spelling we register, and the
+ summarized text changes only where pi consumes the name.
diff --cc docs/zh-CN/spec/04-ux/08-component-spec.md
index 4652cfa97,023a9d62e..3d7c53042
--- a/docs/zh-CN/spec/04-ux/08-component-spec.md
+++ b/docs/zh-CN/spec/04-ux/08-component-spec.md
@@@ -1365,36 -1363,6 +1365,36 @@@ Renderer: `apps/desktop/src/component
`code` 上的 `math-inline`/`math-display` 类(保证 TeX `\[…\]` 使用块级布局)
允许添加。 KaTeX 的 Vite 内联 WOFF2 字体被允许
渲染器的 `font-src 'self' data:` CSP 指令。
- - **复制公式(D618)**:覆盖到渲染公式的选区,以公式被写下时的 TeX 进入剪贴板
++- **复制公式(D619)**:覆盖到渲染公式的选区,以公式被写下时的 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 --cc docs/zh-CN/spec/06-delivery/04-e2e-test-plan.md
index ce20c8220,a52de6b78..d2c4c2ea3
--- 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,33 -2278,6 +2278,33 @@@ MainChat 弥补了缺口。 Maximized/f
- **完整历史回归**:打开包含 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
++ 决策日志 D619,issue #414
+- **验收**:C(聊天流),质量
+- **里程碑**:M5
+- **状态**:已自动化(`pnpm test:e2e:copy-tex`,真实 Chromium),另有
+ `selection-tex.test.mjs`
+
#### E2E-060b:镀铬中性灰色调
- **先决条件**:应用程序在深色和浅色主题中运行;插件页面和
diff --cc docs/zh-CN/spec/08-meta/decisions-log.md
index d3b3fac1f,b0eb74014..6f00131a5
--- a/docs/zh-CN/spec/08-meta/decisions-log.md
+++ b/docs/zh-CN/spec/08-meta/decisions-log.md
@@@ -308,7 -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 剪贴板可以替代,那剪贴板就得真的装着源码。 |
-
++| D619 | 复制公式得到的是它的 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. 模型目录决策
@@@ -4755,92 -4774,14 +4774,103 @@@ that amendment are retired by ADR 0268
请求,每次携带上一片的摘要,检查点报告这些请求的用量总和。只有空范围或超过该请求上限
的范围才因预算原因回退。见 ADR 0302、`03-runtime/02-agent-runtime.md`、ADR 0049、ADR 0282。
- ## 2026-09-20 —— 复制公式得到的是它的 TeX 源码(D618,issue #414)
++## 2026-09-20 —— 复制公式得到的是它的 TeX 源码(D619,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 当年据以移除「引用」
++- 把消息切成互相独立解析的块——这早于 D619,D619 只是把它换到了渲染语法上——仅当某一片不依赖其他片的解析上下文时才成立。链接与脚注定义恰是反例:它在整条消息范围内解析,脚注还要跨消息编号、复用和回链,于是脱离定义单独解析的引用会以字面 `[^1]` 留在正文里,脚注本身消失。因此只要消息中任意位置声明了定义,该消息就整体不切分。把定义注入每一片的做法被否决:那会让脚注按片各自重新编号,并把回链指向错误的引用。被接受的代价是这类消息在流式期间失去按块记忆——这正是渲染器在引入分块之前一直承担的成本,而它在聊天回答中的罕见程度把这个代价限住了。
++- D619 不新增任何界面、store 状态或操作行条目:它把 ADR 0268 当年据以移除「引用」
+ 的那个 OS 剪贴板,变成名副其实的替代品。仅渲染层——未改动任何 IPC 通道、宿主协议、
+ 存储 schema、权限、Plugin SDK 或 i18n 键。见 `04-ux/08-component-spec.md` §8.7
+ 与 E2E-CHAT-copy-formula-as-tex。
+ ## 2026-09-22 —— 交给 pi 的文件操作收集器使用它认识的拼写(D618,issue #827)
+
+ - 检查点的 `readFiles` / `modifiedFiles` 以及摘要追加的 `<read-files>` 段来自 pi 自己的
+ `extractFileOpsFromMessage`,它只匹配小写名字 `read` / `write` / `edit`——即 pi 自己
+ 工具的名字。PI-Desktop 注册的是 `Read` / `Write` / `Edit`,因此该收集器什么都匹配不到,
+ 每个检查点都报出空文件清单;issue #827 在排查压缩报告时发现了这一点。
+ - 转换只发生在边界这一侧:`withPiFileOpToolNames` 把交给 pi `prepareCompaction` 的条目
+ 复制一份,并改写这三个名字的拼写。存储字节不变——transcript、检查点与重建后的上下文都
+ 保留我们的拼写——而且当历史里没有这类调用时原样返回入参数组,常见路径不产生任何分配。
+ - 只转换这三个名字。pi 的收集器不读其它名字,因此 `Grep`、`Glob`、`Bash`、插件与 MCP 名字
+ 保持我们注册的拼写,被摘要的文本只在 pi 真正消费该名字的地方发生变化。