Local UI to run and train LLMs and diffusion models. Supports GGUF, MLX, Qwen3.8, DeepSeek-V4.1, MiniMax-H3, Gemma 4, FLUX and more.
Python agentaichatgptdeepseekfine-tuninggemmaimage-generationllamallmllmsopenaipythonqwenreinforcement-learningself-hostedstable-diffusiontext-to-speechttsuiunsloth
Studio: copy a thread selection without building the styled clipboard flavour (#9457)
Daniel Han984402b9a83f
diff --git a/studio/frontend/scripts/build-fast-copy-bundle.mjs b/studio/frontend/scripts/build-fast-copy-bundle.mjsnew file mode 100644index 00000000000..dc2f8977417--- /dev/null+++ b/studio/frontend/scripts/build-fast-copy-bundle.mjs@@ -0,0 +1,50 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// Compile the SHIPPED module into a browser script, so the byte-for-byte proof runs against the+// TypeScript that is actually in the tree rather than against a hand-kept copy of it. Proving a+// reference implementation proves the reference implementation; what reaches a user is+// studio/frontend/src/components/assistant-ui/thread-fast-copy.ts, so that is what is built.+//+// Usage: node scripts/build-fast-copy-bundle.mjs <out-dir>, from studio/frontend.+// It lives here rather than beside its caller in tests/studio because node resolves a bare+// `import ... from "vite"` against the IMPORTING FILE's directory, and vite is installed+// under studio/frontend/node_modules.+// Writes <out-dir>/fastcopy.js, an IIFE bundle exposing the module's exports as `SBFastCopy`.+//+// `configFile: false` so studio/frontend/vite.config.ts (the app build: react plugin, chunking,+// asset pipeline) is not applied to a one-module library build. `copyPublicDir: false` because+// the app's public/ is tens of megabytes of images the proof never loads.++import path from "node:path";+import { fileURLToPath } from "node:url";+import { build } from "vite";++const here = path.dirname(fileURLToPath(import.meta.url));+const root = path.resolve(here, "..");++const outDir = process.argv[2];+if (!outDir) {+ console.error("usage: node scripts/build-fast-copy-bundle.mjs <out-dir>");+ process.exit(2);+}++await build({+ root,+ configFile: false,+ logLevel: "error",+ build: {+ outDir: path.resolve(outDir),+ // The caller owns the directory and hands over a fresh one; emptying a path outside the+ // vite root is a footgun this has no need of.+ emptyOutDir: false,+ copyPublicDir: false,+ minify: false,+ lib: {+ entry: path.join(root, "src/components/assistant-ui/thread-fast-copy.ts"),+ name: "SBFastCopy",+ formats: ["iife"],+ fileName: () => "fastcopy.js",+ },+ },+});diff --git a/studio/frontend/src/components/assistant-ui/thread-fast-copy.ts b/studio/frontend/src/components/assistant-ui/thread-fast-copy.tsnew file mode 100644index 00000000000..487bcdae681--- /dev/null+++ b/studio/frontend/src/components/assistant-ui/thread-fast-copy.ts@@ -0,0 +1,557 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++/**+ * Copying a selection out of the thread, without paying for the styled clipboard flavour.+ *+ * WHERE THE TIME GOES. Almost all of the cost of a copy on a long thread is the browser building+ * the annotated `text/html` flavour, not extracting text. Measured on smoke-heavy-thread.html at+ * the 100K rung -- the real Thread, 14,137 elements in the viewport, Chromium, five repetitions+ * with the selection re-established before each -- a 40,626-character selection costs 347.0ms to+ * copy, and producing the identical string ourselves costs 11.9ms. So: take the event, write the+ * plain text ourselves, and the styled flavour is never built.+ *+ * `Selection.toString()` IS NOT THE SAME STRING AS THE CLIPBOARD'S `text/plain`, and this file+ * exists because of that. Blink builds the two with different `TextIteratorBehavior` flags:+ *+ * DOMSelection::toString() ForSelectionToString, SkipsUnselectableContent+ * FrameSelection::SelectedTextForClipboard() SkipsUnselectableContent, EntersTextControls,+ * IgnoresCssTextTransforms, EmitsImageAltText+ *+ * and `WebViewImpl::ApplyWebPreferences` turns `SetSelectionIncludesAltImageText(true)` on for+ * every web view, so the alt-text one is not conditional in practice. The thirty-one constructs+ * in tests/studio/_thread_fast_copy_constructs.py were copied one at a time on Playwright's+ * Chromium and WebKit and pasted back, and the clipboard differs from `toString()` in exactly+ * four places:+ *+ * construct chromium webkit what is done here+ * img[alt] emits the alt text emits the alt text REPRODUCED+ * U+00A0 becomes a space becomes a space REPRODUCED+ * text-transform ignored (source text) applied (rendered) REPRODUCED (chromium)+ * input/textarea/ value emitted, as its value omitted REFUSED+ * select own block+ *+ * Everything else -- block boundaries, whitespace collapsing, `user-select: none`, generated+ * content, tables, lists, `<pre>`, `<br>`, entities, emoji -- is identical, because it is the+ * same iterator. So this does NOT reimplement the iterator. It patches the enumerated deltas+ * into the live DOM inside one synchronous turn of the copy event, asks the engine for its own+ * `toString()`, and puts everything back. Every semantic not on that list stays right by+ * construction, which a hand-written walker could not promise.+ *+ * WHY THIS RUNS ON ONE ENGINE FAMILY. WebKit's `toString()` appends trailing block breaks its+ * clipboard does not carry, and the count depends on what the selection ends with: +2 after a+ * paragraph or a heading, +1 after a div, list, `<pre>` or blockquote, +0 after a table or an+ * inline. That is the iterator's block-boundary emission, which is exactly the open-ended part+ * this avoids. Chromium's delta is +0 in all eleven endings measured. A clipboard that is+ * silently wrong is worse than a clipboard that is slow, so an engine whose mapping has not been+ * proven gets the browser's own copy. The check is a BEHAVIOURAL probe of `toString()`, not a+ * version test; the user agent narrows it further and is never allowed to decide what bytes are+ * produced.+ *+ * WHY A FORM CONTROL IS REFUSED rather than reproduced. Chromium emits a control's value AND+ * treats it as its own block, and the break depends on the control: a text input lands as+ * "value\n", a select as "\nvalue\n". That is the same block-boundary problem. Measured on the+ * real thread at the 100K rung, the viewport contains ZERO form controls, so the refusal costs+ * nothing that exists -- and a password field would copy as its mask, where guessing the glyph+ * wrong would put a real password on the clipboard.+ *+ * WHAT THIS DOES NOT COVER. A document-wide Ctrl+A does not route through here, and moving the+ * listener to the document would not change that. The copy event targets the node the selection+ * starts in, which for a whole-document selection is the first row of the sidebar, so a viewport+ * listener never sees it (measured in both engines) -- but a document listener that did see it+ * would refuse anyway, because that selection spans the composer's textarea. What is fixed here+ * is the case that dominates a session: dragging a selection across a long stretch of the+ * conversation.+ *+ * WHY NOT SERIALISE THE MESSAGE STORE. Building the text from the store is faster still, because+ * nothing is read out of the DOM at all. It also changes what lands on the clipboard: role+ * headings, thinking markers and tool lines the DOM selection never contained. That trade is+ * worth making on a virtualized list, where the DOM physically cannot select an unmounted+ * message. On the shipped, fully mounted list it buys only speed, at the cost of handing the+ * user a different document than the one they highlighted.+ */++/** Why a copy was left to the browser. Named so a test can assert the reason, not just the miss. */+export type NativeCopyReason =+ | "already-handled"+ | "no-clipboard-data"+ | "editable-origin"+ | "empty-selection"+ | "selection-leaves-thread"+ | "form-control"+ | "unmapped-engine";++export type ThreadCopyDecision =+ | { readonly kind: "fast" }+ | { readonly kind: "native"; readonly reason: NativeCopyReason };++/**+ * A copy event, structurally. The GATE needs no DOM, so its branches can be unit tested against+ * plain objects. The SERIALISER below is the part that must be proven in a browser against a+ * real clipboard, and is, by tests/studio/playwright_thread_fast_copy.py, which builds THIS+ * module and, per construct, sets what it produces against what the engine's own copy puts on+ * the clipboard: Chromium must match byte for byte, WebKit must refuse, and its refusal must be+ * backed by a divergence the same run measures.+ */+export type CopyEventLike = {+ readonly defaultPrevented: boolean;+ readonly target: unknown;+ readonly clipboardData: {+ setData(format: string, data: string): void;+ } | null;+};++export type SelectionLike = {+ readonly isCollapsed: boolean;+ readonly rangeCount: number;+ getRangeAt(index: number): { readonly commonAncestorContainer: unknown };+ toString(): string;+};++export type ThreadViewportLike = {+ contains(node: unknown): boolean;+ querySelector(selectors: string): unknown;+};++/**+ * A form control anywhere in the selected subtree. Chromium's clipboard reads its value and+ * wraps it in block breaks whose shape depends on the control, so the copy is handed back.+ */+const FORM_CONTROL = "input, textarea, select";++/** Where a copy must be left alone because the selection is not the document's. */+const EDITABLE_ORIGIN =+ 'input, textarea, select, [contenteditable=""], [contenteditable="true"], [contenteditable="plaintext-only"]';++const TRANSFORMED = new Set(["uppercase", "lowercase", "capitalize"]);++function matchesAncestor(target: unknown, selectors: string): boolean {+ const closest = (+ target as { closest?: (selectors: string) => unknown } | null+ )?.closest;+ if (typeof closest !== "function") return false;+ return closest.call(target, selectors) != null;+}++/**+ * The smallest subtree the checks have to be right about.+ *+ * The range's common ancestor, not the viewport, and the difference is what makes this worth+ * shipping: a thread with one `<textarea>` open anywhere would otherwise never take the fast+ * path again, however far from it the user selected. The common ancestor is by definition a+ * superset of the selected content, so scanning it is an over-approximation -- it can only ever+ * refuse a copy the fast path could have taken, never accept one it could not.+ *+ * A range that ends in a text node has no `querySelector` of its own, hence the parent. Anything+ * unrecognisable falls back to the viewport, which is the conservative direction.+ */+function scopeOf(+ selection: SelectionLike,+ viewport: ThreadViewportLike,+): Pick<ThreadViewportLike, "querySelector"> {+ // Several disjoint ranges have no single ancestor short of the viewport.+ if (selection.rangeCount !== 1) return viewport;++ const container = selection.getRangeAt(0).commonAncestorContainer as {+ querySelector?: unknown;+ parentElement?: { querySelector?: unknown } | null;+ } | null;++ if (typeof container?.querySelector === "function") {+ return container as Pick<ThreadViewportLike, "querySelector">;+ }+ const parent = container?.parentElement;+ if (typeof parent?.querySelector === "function") {+ return parent as Pick<ThreadViewportLike, "querySelector">;+ }+ return viewport;+}++/**+ * Does this engine's clipboard agree with its own `toString()` about trailing block breaks?+ *+ * A hidden paragraph is selected and `toString()` asked whether it appends one. Chromium says+ * "a"; WebKit says "a\n\n". Cached, because the answer cannot change within a document, and run+ * with the user's own selection saved and restored around it.+ *+ * The restore goes through `restoreSelection`, the serialiser's, and for the same reason: this+ * path also takes the selection away and rebuilds it, so rebuilding from ranges alone would flip+ * a selection the user dragged upwards. The text copied would still be right and their highlight+ * would silently reverse, which is the more annoying half of the bug -- the next Shift+Arrow then+ * moves the far end. Reached on a plain drag right-to-left, and on the FIRST copy of a document,+ * since the answer is cached afterwards.+ */+export function engineClipboardIsMapped(+ view: Window & typeof globalThis,+): boolean {+ const cache = view as { __sbFastCopyMapped?: boolean };+ if (typeof cache.__sbFastCopyMapped === "boolean") {+ return cache.__sbFastCopyMapped;+ }+ let mapped = false;+ try {+ const ua = view.navigator?.userAgent ?? "";+ if (+ /Chrome\/|Chromium\/|Edg\//.test(ua) &&+ !/\bAppleWebKit\b(?!.*Chrome)/.test(ua)+ ) {+ const doc = view.document;+ const probe = doc.createElement("div");+ probe.setAttribute("aria-hidden", "true");+ probe.style.cssText =+ "position:fixed;left:-9999px;top:0;width:1px;height:1px;overflow:hidden";+ probe.innerHTML = "<p>a</p>";+ doc.body.appendChild(probe);+ const selection = view.getSelection();+ const saved: Range[] = [];+ if (selection) {+ for (let index = 0; index < selection.rangeCount; index += 1) {+ saved.push(selection.getRangeAt(index).cloneRange());+ }+ // Before the probe replaces it, because that is the only moment the direction exists.+ const direction = captureDirection(selection);+ selection.selectAllChildren(probe);+ mapped = selection.toString() === "a";+ restoreSelection(selection, saved, direction);+ }+ probe.remove();+ }+ } catch {+ mapped = false;+ }+ cache.__sbFastCopyMapped = mapped;+ return mapped;+}++/**+ * The two deltas that are reproduced, patched into the live DOM and taken straight back out.+ *+ * Returns the undo list rather than doing its own cleanup, so the caller can guarantee the+ * restore runs even if `toString()` throws. Nothing here paints: the whole sequence is one+ * synchronous turn of the copy event, so the user never sees the patched document.+ */+/**+ * Put an element's `style` attribute back exactly as it was found, including not being there.+ *+ * `style.removeProperty` is not the inverse of `style.setProperty` at the serialisation level,+ * which is the level a DOM comparison works at.+ */+/**+ * Would the clipboard's own iterator emit this image's alt text?+ *+ * `SkipsUnselectableContent` and ordinary rendering rules mean an image that is not displayed,+ * not visible or not selectable contributes nothing. `visibility` and `user-select` inherit, so+ * the computed style already answers for an ancestor that set them.+ */+function nativeWouldEmitAlt(image: HTMLImageElement): boolean {+ const computed = getComputedStyle(image);+ if (computed.display === "none") return false;+ if (computed.visibility !== "visible") return false;+ const selectable = computed.userSelect ?? computed.webkitUserSelect;+ if (selectable === "none") return false;+ return true;+}++function restoreStyleAttribute(element: Element, had: string | null): void {+ if (had !== null) {+ element.setAttribute("style", had);+ return;+ }+ // `removeAttribute("style")` DOES NOT REMOVE IT once the inline declaration has been touched.+ // Measured in Chromium: setProperty then removeAttribute leaves `style=""` on the element and+ // in its serialisation, and calling removeAttribute twice does not help, nor does clearing+ // `cssText` first. Removing the attribute NODE does work. The residue is invisible to a user+ // and visible to every DOM comparison, and it is permanent: it survives the copy that caused+ // it, so a thread accumulates one per element the fast path ever touched.+ try {+ element.attributes.removeNamedItem("style");+ } catch {+ element.removeAttribute("style");+ }+}++function patchClipboardDeltas(root: Element): Array<() => void> {+ const undo: Array<() => void> = [];++ // IgnoresCssTextTransforms: the clipboard carries the SOURCE text.+ //+ // ROOT ITSELF, not only its descendants. A selection lying entirely inside+ // `<span class="uppercase">text</span>` has that span as its common ancestor, and+ // `querySelectorAll("*")` does not include the element it is called on, so the transform was+ // missed and the TRANSFORMED text was written where the clipboard carries the source text.+ // Raised in review and reproduced against the real clipboard before it was fixed: the three+ // cases now in tests/studio/_thread_fast_copy_constructs.py under INSIDE_SCOPE all failed.+ // `text-transform` inherits, so `getComputedStyle(root)` already reports a transform set on+ // any ancestor above the scope, and no walk upwards is needed.+ const scoped: HTMLElement[] = [];+ if (root instanceof HTMLElement) scoped.push(root);+ scoped.push(...Array.from(root.querySelectorAll<HTMLElement>("*")));+ for (const element of scoped) {+ const transform = getComputedStyle(element).textTransform;+ if (!TRANSFORMED.has(transform)) continue;+ // THE RAW ATTRIBUTE, not the property. Going through `style.removeProperty` restores the+ // computed value and does NOT restore the serialisation: an element that had no `style`+ // attribute is left carrying `style=""`, and one that had `style="text-transform:uppercase"`+ // gets it rewritten as `style="text-transform: uppercase;"`. Neither is visible to a user+ // and both are visible to any DOM comparison, so every copy silently rewrote the document.+ // Caught by the structural parity digest, which reported six actions differing against a+ // null that matched fifteen of sixteen.+ const had = element.getAttribute("style");+ element.style.setProperty("text-transform", "none", "important");+ undo.push(() => restoreStyleAttribute(element, had));+ }++ // EmitsImageAltText: the clipboard carries the alt text, which is not in the DOM as text.+ //+ // THE HOLDER MUST NOT HAVE A BOX. Studio's message images are display:block, so an inline+ // holder placed beside one sits between two blocks, the engine wraps it in an anonymous block,+ // and the alt text arrives with a leading newline the real clipboard does not have. That was+ // measured on the real thread as 40,650 characters against the clipboard's 40,648, two images+ // each contributing one extra break. Taking the image out of the flow removes the box the+ // break came from, and an image contributes no text of its own, so hiding it changes nothing+ // else.+ for (const image of Array.from(+ root.querySelectorAll<HTMLImageElement>("img[alt]"),+ )) {+ const alt = image.getAttribute("alt");+ if (!alt) continue;+ // ONLY AN IMAGE THE NATIVE ITERATOR WOULD EMIT. Chromium skips an image that is not+ // rendered or not selectable, so inserting its alt text unconditionally ADDS text the+ // clipboard never carried. Measured against the real clipboard: `display: none`,+ // `visibility: hidden` and `user-select: none` all diverge, and so does Studio's own+ // `ImagePreview`, which carries an `invisible` class until the image loads -- so copying+ // across a message whose image had not finished loading gained an alt string.+ if (!nativeWouldEmitAlt(image)) continue;+ const had = image.getAttribute("style");+ image.style.setProperty("display", "none", "important");+ const holder = image.ownerDocument.createElement("span");+ holder.textContent = alt;+ image.parentNode?.insertBefore(holder, image);+ undo.push(() => {+ holder.remove();+ restoreStyleAttribute(image, had);+ });+ }++ return undo;+}++/**+ * The string the browser would have put on the clipboard, produced without building the styled+ * flavour. Proven byte-for-byte against Chromium's real clipboard over 31 selections -- the 23+ * of the 31 constructs it answers, the other 8 being refused or copying nothing, plus two+ * element-offset endpoints, three selections scoped to a transformed element and three partials+ * -- and on the real thread at 40,648 characters.+ *+ * The selection is restored whatever happens, because a copy that quietly moved the user's+ * highlight would be a worse bug than the one being fixed.+ */+/**+ * A selection's DIRECTION, and only its direction.+ *+ * Deliberately not the endpoints. Capturing raw offsets and restoring them was wrong: the alt+ * holders are inserted BEFORE their images, so an endpoint expressed as an element/child offset+ * in the same parent points at a different child afterwards. Measured, with two images and a+ * trailing text node selected by parent offsets 0..3: the clipboard carried+ * `first catsecond cattail text` and we produced `first catsecond cat`, silently dropping the+ * tail -- and because that is non-empty, the listener took the copy rather than handing it back.+ *+ * A cloned `Range` is live and its boundaries move with the DOM, so the ranges already hold the+ * correct positions. All that is missing from them is which end the user dragged from.+ */+type SelectionDirection = { readonly backward: boolean };++function captureDirection(selection: Selection): SelectionDirection {+ const { anchorNode, anchorOffset, focusNode, focusOffset } = selection;+ if (!anchorNode || !focusNode) return { backward: false };+ try {+ const probe = anchorNode.ownerDocument?.createRange();+ if (!probe) return { backward: false };+ probe.setStart(anchorNode, anchorOffset);+ probe.setEnd(anchorNode, anchorOffset);+ // -1 means the focus lies before the anchor, which is a selection dragged upwards.+ return { backward: probe.comparePoint(focusNode, focusOffset) < 0 };+ } catch {+ // Different trees, or a detached node. Forward is the safe assumption.+ return { backward: false };+ }+}++/**+ * Put the selection back the way it was, INCLUDING ITS DIRECTION.+ *+ * A `Range` carries ordered boundaries and nothing else, so rebuilding with `addRange` always+ * produces a forward selection. Measured: a selection dragged upwards came back with its anchor+ * and focus swapped, so the user's next Shift+Arrow would move the opposite edge of it. Only the+ * patched path ever rebuilds the selection, which is why this never showed on ordinary prose.+ *+ * `setBaseAndExtent` preserves direction and takes one anchor/focus pair, so a multi-range+ * selection still falls back to `addRange`. Firefox is the only engine that produces those, and+ * it is not an engine this fast path runs on.+ */+function restoreSelection(+ selection: Selection,+ saved: readonly Range[],+ direction: SelectionDirection,+): void {+ selection.removeAllRanges();+ if (saved.length === 1) {+ // The LIVE range's boundaries, which the holder insertions have already adjusted, ordered+ // by the direction the user dragged in.+ const range = saved[0];+ try {+ if (direction.backward) {+ selection.setBaseAndExtent(+ range.endContainer,+ range.endOffset,+ range.startContainer,+ range.startOffset,+ );+ } else {+ selection.setBaseAndExtent(+ range.startContainer,+ range.startOffset,+ range.endContainer,+ range.endOffset,+ );+ }+ return;+ } catch {+ // A detached node is better answered with the range than with nothing at all.+ }+ }+ for (const range of saved) selection.addRange(range);+}++export function faithfulSelectionText(+ selection: Selection,+ root: Element,+): string {+ const saved: Range[] = [];+ for (let index = 0; index < selection.rangeCount; index += 1) {+ saved.push(selection.getRangeAt(index).cloneRange());+ }+ const direction = captureDirection(selection);+ const undo = patchClipboardDeltas(root);+ let raw: string;+ try {+ if (undo.length > 0) restoreSelection(selection, saved, direction);+ raw = selection.toString();+ } finally {+ for (let index = undo.length - 1; index >= 0; index -= 1) undo[index]();+ if (undo.length > 0) restoreSelection(selection, saved, direction);+ }+ // Both engines' clipboards fold a no-break space to a plain one; neither `toString()` does.+ return raw.replace(/\u00a0/g, " ");+}++/**+ * Should this copy be answered by us instead of the browser, and if not, why not?+ *+ * Pure, and every rejection carries its reason, because each branch is a distinct way of getting+ * somebody's copy wrong and "the fast path did not run" is not enough to tell them apart.+ */+export function decideThreadCopy(+ event: CopyEventLike,+ selection: SelectionLike | null,+ viewport: ThreadViewportLike,+ engineIsMapped = true,+): ThreadCopyDecision {+ // Somebody upstream already produced this clipboard payload. Do not overwrite it.+ if (event.defaultPrevented) {+ return { kind: "native", reason: "already-handled" };+ }++ // No transfer to write into, so preventing the default would copy nothing at all.+ if (!event.clipboardData) {+ return { kind: "native", reason: "no-clipboard-data" };+ }++ // A copy out of a text control is that control's own selection, and `window.getSelection()` is+ // not it: the document selection is usually collapsed or stale while a textarea has focus, so+ // substituting it would replace the copied field with unrelated text. The thread viewport+ // contains these -- a message being edited mounts a textarea -- so this cannot be left to the+ // listener's placement.+ if (matchesAncestor(event.target, EDITABLE_ORIGIN)) {+ return { kind: "native", reason: "editable-origin" };+ }++ // A caret rather than a selection. The browser copies nothing; so should we.+ if (!selection || selection.isCollapsed || selection.rangeCount === 0) {+ return { kind: "native", reason: "empty-selection" };+ }++ // A selection that starts inside the thread and runs out of it -- into the composer, the+ // sidebar, the header -- has a common ancestor above the viewport. Its text is no longer+ // something this file has proven, so it is not something this file should be rewriting.+ for (let index = 0; index < selection.rangeCount; index += 1) {+ if (+ !viewport.contains(selection.getRangeAt(index).commonAncestorContainer)+ ) {+ return { kind: "native", reason: "selection-leaves-thread" };+ }+ }++ if (scopeOf(selection, viewport).querySelector(FORM_CONTROL) != null) {+ return { kind: "native", reason: "form-control" };+ }++ // Last, because it is the only branch that touches the document, and every cheaper refusal+ // above should have run first.+ if (!engineIsMapped) {+ return { kind: "native", reason: "unmapped-engine" };+ }++ return { kind: "fast" };+}++/**+ * Wire the decision to a live viewport. Returns the detach function.+ *+ * Only `copy` is listened for. A `cut` also has to mutate the document it cut from, and the+ * thread is not editable, so a cut inside it is already a no-op and one inside a message being+ * edited belongs to that textarea.+ */+export function attachThreadFastCopy(viewport: HTMLElement): () => void {+ const onCopy = (event: ClipboardEvent) => {+ const view = viewport.ownerDocument.defaultView;+ if (!view) return;+ const selection = view.getSelection();+ const decision = decideThreadCopy(+ event,+ selection,+ viewport,+ engineClipboardIsMapped(view as Window & typeof globalThis),+ );+ if (decision.kind !== "fast") return;++ let text: string;+ try {+ text = faithfulSelectionText(+ selection as Selection,+ scopeElement(selection as Selection, viewport),+ );+ } catch {+ // The patch could not be applied or undone cleanly. Let the browser copy: slow and right+ // beats fast and silently different.+ return;+ }+ // A selection can be non-collapsed and still serialise to nothing (an image with an empty+ // alt on its own). Writing "" would clear a clipboard the browser would have left alone.+ if (text === "") return;++ event.preventDefault();+ event.clipboardData?.setData("text/plain", text);+ };++ viewport.addEventListener("copy", onCopy);+ return () => viewport.removeEventListener("copy", onCopy);+}++/** The element form of `scopeOf`, for the patching path, which needs a real `Element`. */+function scopeElement(selection: Selection, viewport: HTMLElement): Element {+ if (selection.rangeCount !== 1) return viewport;+ const container = selection.getRangeAt(0).commonAncestorContainer;+ if (container.nodeType === 1) return container as Element;+ return container.parentElement ?? viewport;+}diff --git a/studio/frontend/src/components/assistant-ui/thread.tsx b/studio/frontend/src/components/assistant-ui/thread.tsxindex 9f49fcd1ead..b096b86289a 100644--- a/studio/frontend/src/components/assistant-ui/thread.tsx+++ b/studio/frontend/src/components/assistant-ui/thread.tsx@@ -22,6 +22,7 @@ import {MessageResponseModelBadge,} from "@/components/assistant-ui/message-response-details-sheet";import { MessageTiming } from "@/components/assistant-ui/message-timing";+import { attachThreadFastCopy } from "@/components/assistant-ui/thread-fast-copy";import { threadHasResearchMessage } from "@/components/assistant-ui/thread-research-presence";import { Reasoning, ReasoningGroup } from "@/components/assistant-ui/reasoning";import { RagSourcesGroup } from "@/components/assistant-ui/rag-sources";@@ -1544,6 +1545,15 @@ export const Thread: FC<{[viewportRef],);+ // Copying a selection out of the thread writes the plain text itself rather than letting the+ // browser serialise the selection, which spends over 99% of a long thread's copy building the+ // styled clipboard flavour. thread-fast-copy.ts holds the rule for when that substitution is+ // provably invisible, and hands the event back to the browser whenever it is not.+ useEffect(() => {+ if (!viewportEl) return;+ return attachThreadFastCopy(viewportEl);+ }, [viewportEl]);+// Bottom spacer sizing. Invariant: chat never moves on its own on composer// resize.// - Grow (attachment added, multiline): grow at once; growth below thediff --git a/studio/frontend/tests/thread-fast-copy.test.ts b/studio/frontend/tests/thread-fast-copy.test.tsnew file mode 100644index 00000000000..5f634d9a7f3--- /dev/null+++ b/studio/frontend/tests/thread-fast-copy.test.ts@@ -0,0 +1,1798 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++// A copy inside the thread writes its own `text/plain` so the browser never builds the styled+// clipboard flavour. Measured on smoke-heavy-thread.html at the 100K rung, a 40,626-character+// selection costs 347.0ms to copy and 11.9ms to produce ourselves, so essentially all of it.+//+// What is tested here is the DECISION and the SERIALISER, not the timing. A unit test cannot time+// a clipboard, and one that tried would be measuring the test runner. What it can do is pin the+// two things that decide whether a user gets the right bytes:+//+// * the gate, whose every branch is a distinct way of handing somebody the wrong text -- a copy+// that started in a textarea, where `window.getSelection()` is not the selection being copied+// at all; a selection that runs out of the thread, whose text has not been checked; a form+// control, whose value the clipboard emits as its own block; an engine whose `toString()` has+// not been proven to agree with its clipboard+// * the serialiser, which reproduces the enumerated deltas by PATCHING THE LIVE DOM and taking+// the engine's own `toString()` back out. What has to be true of it is that the patch is+// complete and that the document and the user's selection are exactly as they were found.+//+// There is no DOM library in this project -- no jsdom, no happy-dom, no vitest environment; the+// runner is `node --test` and every sibling test that needs a document hand-rolls one (see+// tests/overlay-scrollbar-gutter.test.ts). So the gate runs against plain objects, which is what+// its structural types are for, and the serialiser runs against the small DOM below. That DOM is+// honest about its limits: its `querySelectorAll` throws on any selector it does not really+// implement, and its `toString()` is computed from the tree at the moment it is asked, so an alt+// text only appears in the output if the module actually put a holder in the document.++import assert from "node:assert/strict";+import test from "node:test";++import {+ type CopyEventLike,+ type SelectionLike,+ type ThreadViewportLike,+ attachThreadFastCopy,+ decideThreadCopy,+ engineClipboardIsMapped,+ faithfulSelectionText,+} from "../src/components/assistant-ui/thread-fast-copy.ts";++// --- the gate ----------------------------------------------------------------------------------++/** A viewport holding no form control, containing everything. */+function plainViewport(+ options: {+ contains?: boolean;+ matches?: string[];+ } = {},+): ThreadViewportLike & { queried: string[] } {+ const { contains = true, matches = [] } = options;+ const queried: string[] = [];+ return {+ queried,+ contains: () => contains,+ querySelector(selectors: string) {+ queried.push(selectors);+ // Stand in for a real matcher: report a hit if any of the named constructs is in the list+ // the module asked about.+ const hit = matches.find((selector) => selectors.includes(selector));+ return hit === undefined ? null : { selector: hit };+ },+ };+}++function selectionOf(text: string): SelectionLike {+ return {+ isCollapsed: false,+ rangeCount: 1,+ getRangeAt: () => ({ commonAncestorContainer: { node: "message" } }),+ toString: () => text,+ };+}++function copyEvent(overrides: Partial<CopyEventLike> = {}): CopyEventLike {+ return {+ defaultPrevented: false,+ target: { closest: () => null },+ clipboardData: { setData: () => undefined },+ ...overrides,+ };+}++test("an ordinary selection inside the thread is answered by the fast path", () => {+ // The decision no longer carries the text: the string is produced separately, from the live+ // DOM, because reproducing the clipboard's deltas needs a document and the gate does not.+ const decision = decideThreadCopy(+ copyEvent(),+ selectionOf("first message\n\nsecond message"),+ plainViewport(),+ );++ assert.deepEqual(decision, { kind: "fast" });+});++test("a copy another handler already answered is left alone", () => {+ const decision = decideThreadCopy(+ copyEvent({ defaultPrevented: true }),+ selectionOf("anything"),+ plainViewport(),+ );++ assert.deepEqual(decision, { kind: "native", reason: "already-handled" });+});++test("a copy with no clipboardData is left alone rather than prevented into nothing", () => {+ // preventDefault() with nowhere to write the replacement copies NOTHING, which is strictly+ // worse than a slow copy.+ const decision = decideThreadCopy(+ copyEvent({ clipboardData: null }),+ selectionOf("anything"),+ plainViewport(),+ );++ assert.deepEqual(decision, { kind: "native", reason: "no-clipboard-data" });+});++test("a copy out of a text control keeps the browser's own copy", () => {+ // The edit composer and the queued-prompt editor both mount a textarea INSIDE the viewport, so+ // this is reachable, and `window.getSelection()` there is the document's selection rather than+ // the field's: substituting it would replace the copied field with unrelated text.+ for (const tag of ["input", "textarea", "select"]) {+ const decision = decideThreadCopy(+ copyEvent({+ target: {+ closest: (selectors: string) =>+ selectors.includes(tag) ? { tag } : null,+ },+ }),+ selectionOf("some text elsewhere in the document"),+ plainViewport(),+ );++ assert.deepEqual(+ decision,+ { kind: "native", reason: "editable-origin" },+ `copy originating in <${tag}>`,+ );+ }+});++test("a copy out of a contenteditable keeps the browser's own copy", () => {+ const decision = decideThreadCopy(+ copyEvent({+ target: {+ closest: (selectors: string) =>+ selectors.includes("contenteditable") ? { tag: "div" } : null,+ },+ }),+ selectionOf("text"),+ plainViewport(),+ );++ assert.deepEqual(decision, { kind: "native", reason: "editable-origin" });+});++test("a caret rather than a selection is left alone", () => {+ const collapsed: SelectionLike = { ...selectionOf("x"), isCollapsed: true };+ assert.deepEqual(decideThreadCopy(copyEvent(), collapsed, plainViewport()), {+ kind: "native",+ reason: "empty-selection",+ });++ const empty: SelectionLike = { ...selectionOf("x"), rangeCount: 0 };+ assert.deepEqual(decideThreadCopy(copyEvent(), empty, plainViewport()), {+ kind: "native",+ reason: "empty-selection",+ });++ assert.deepEqual(decideThreadCopy(copyEvent(), null, plainViewport()), {+ kind: "native",+ reason: "empty-selection",+ });+});++test("a selection running out of the thread is left alone", () => {+ // Dragging from the last message down into the composer, or up into the sidebar, puts the+ // common ancestor above the viewport. The text past the boundary is not text this file has+ // checked, so it is not text this file rewrites.+ const decision = decideThreadCopy(+ copyEvent(),+ selectionOf("thread text plus composer draft"),+ plainViewport({ contains: false }),+ );++ assert.deepEqual(decision, {+ kind: "native",+ reason: "selection-leaves-thread",+ });+});++test("every range of a multi-range selection has to be inside the thread", () => {+ // Firefox builds a multi-range selection from ctrl-click. One range inside the thread does not+ // make the rest of them so.+ let range = 0;+ const selection: SelectionLike = {+ isCollapsed: false,+ rangeCount: 2,+ getRangeAt: () => ({ commonAncestorContainer: { index: range++ } }),+ toString: () => "two disjoint runs",+ };+ const viewport: ThreadViewportLike = {+ // First range inside, second outside.+ contains: (node) => (node as { index: number }).index === 0,+ querySelector: () => null,+ };++ assert.deepEqual(decideThreadCopy(copyEvent(), selection, viewport), {+ kind: "native",+ reason: "selection-leaves-thread",+ });+});++test("a form control in the selected subtree hands the copy back", () => {+ // The one construct that is REFUSED rather than reproduced. Chromium's clipboard emits the+ // control's value AND treats it as its own block, and the break depends on the control: a text+ // input lands as "value\n", a select as "\nvalue\n". Guessing that wrong is the same+ // block-boundary problem the whole file exists to avoid -- and a password field would copy as+ // its mask, where guessing the glyph wrong puts a real password on the clipboard.+ for (const control of ["input", "textarea", "select"]) {+ const decision = decideThreadCopy(+ copyEvent(),+ selectionOf("some prose and then the field"),+ plainViewport({ matches: [control] }),+ );++ assert.deepEqual(+ decision,+ { kind: "native", reason: "form-control" },+ `<${control}> inside the selection`,+ );+ }+});++test("an image with alt text no longer refuses the fast path", () => {+ // It used to. The clipboard emits an image's alt text and `toString()` does not, but that delta+ // is now REPRODUCED by faithfulSelectionText rather than being a reason to give up: the images+ // in a thread are message attachments, and refusing on them turned the fast path off for+ // exactly the messages most worth copying.+ const viewport = plainViewport();+ const decision = decideThreadCopy(+ copyEvent(),+ selectionOf("prose next to an image of a cat"),+ viewport,+ );++ assert.deepEqual(decision, { kind: "fast" });+ // And the gate no longer even asks about images.+ assert.deepEqual(viewport.queried, ["input, textarea, select"]);+});++test("text under a css text-transform no longer refuses the fast path", () => {+ // Also used to. Chromium's clipboard ignores text-transform and carries the source text while+ // `toString()` carries the rendered text; faithfulSelectionText neutralises the transform for+ // the length of the copy instead of handing the copy back.+ const viewport = plainViewport({ matches: [".uppercase"] });++ assert.deepEqual(+ decideThreadCopy(copyEvent(), selectionOf("STDOUT"), viewport),+ { kind: "fast" },+ );+});++test("an engine whose clipboard mapping is unproven hands the copy back", () => {+ // WebKit's `toString()` appends trailing block breaks its clipboard does not carry, and the+ // count depends on what the selection ends with: +2 after a paragraph or heading, +1 after a+ // div, list, <pre> or blockquote, +0 after a table or an inline. A clipboard that is silently+ // wrong is worse than one that is slow.+ const decision = decideThreadCopy(+ copyEvent(),+ selectionOf("a paragraph"),+ plainViewport(),+ false,+ );++ assert.deepEqual(decision, { kind: "native", reason: "unmapped-engine" });+});++test("the engine check runs after every cheaper refusal", () => {+ // It is the branch the module documents as last, and the one whose answer costs a probe of the+ // document. Anything that refuses for a cheaper reason has to say so instead.+ const cheaper: ReadonlyArray<readonly [string, () => unknown]> = [+ [+ "already-handled",+ () =>+ decideThreadCopy(+ copyEvent({ defaultPrevented: true }),+ selectionOf("text"),+ plainViewport(),+ false,+ ),+ ],+ [+ "no-clipboard-data",+ () =>+ decideThreadCopy(+ copyEvent({ clipboardData: null }),+ selectionOf("text"),+ plainViewport(),+ false,+ ),+ ],+ [+ "editable-origin",+ () =>+ decideThreadCopy(+ copyEvent({ target: { closest: () => ({}) } }),+ selectionOf("text"),+ plainViewport(),+ false,+ ),+ ],+ [+ "empty-selection",+ () => decideThreadCopy(copyEvent(), null, plainViewport(), false),+ ],+ [+ "selection-leaves-thread",+ () =>+ decideThreadCopy(+ copyEvent(),+ selectionOf("text"),+ plainViewport({ contains: false }),+ false,+ ),+ ],+ [+ "form-control",+ () =>+ decideThreadCopy(+ copyEvent(),+ selectionOf("text"),+ plainViewport({ matches: ["textarea"] }),+ false,+ ),+ ],+ ];++ for (const [reason, run] of cheaper) {+ assert.deepEqual(run(), { kind: "native", reason }, reason);+ }+});++test("the checks run cheapest-first, so a rejected copy never walks the thread", () => {+ // The form control check is the only branch of the gate that queries the DOM. Anything that+ // rejects for another reason has to reject before paying for it.+ for (const event of [+ copyEvent({ defaultPrevented: true }),+ copyEvent({ clipboardData: null }),+ copyEvent({ target: { closest: () => ({}) } }),+ ]) {+ const viewport = plainViewport();+ const decision = decideThreadCopy(event, selectionOf("text"), viewport);++ assert.equal(decision.kind, "native");+ assert.deepEqual(viewport.queried, []);+ }+});++test("the button copy path is untouched", () => {+ // lib/copy-to-clipboard.ts falls back to a hidden <textarea> appended to document.body. It is+ // outside the viewport, so the listener never sees it; and if the tree ever moves, the+ // editable-origin guard rejects it anyway. Both, because either one alone is a silent+ // dependency on the other.+ const decision = decideThreadCopy(+ copyEvent({+ target: {+ closest: (selectors: string) =>+ selectors.includes("textarea") ? { tag: "textarea" } : null,+ },+ }),+ selectionOf("whatever the thread happens to have selected"),+ plainViewport(),+ );++ assert.deepEqual(decision, { kind: "native", reason: "editable-origin" });+});++// --- how far the form control check looks ------------------------------------------------------+// Scoping it to the whole viewport would be correct and nearly useless: one textarea anywhere in+// the conversation would turn the fast path off for every later copy, however far from it the user+// selected.++/** A range whose common ancestor is an element that answers querySelector itself. */+function selectionInside(+ element: { querySelector(selectors: string): unknown },+ text = "selected prose",+): SelectionLike {+ return {+ isCollapsed: false,+ rangeCount: 1,+ getRangeAt: () => ({ commonAncestorContainer: element }),+ toString: () => text,+ };+}++test("the form control check looks at the selection's ancestor, not at the whole thread", () => {+ const message = {+ // This message holds no form control.+ querySelector: () => null,+ };+ // The viewport does, elsewhere in the conversation. It must not be consulted.+ const viewport: ThreadViewportLike = {+ contains: () => true,+ querySelector: () => ({ tag: "textarea" }),+ };++ const decision = decideThreadCopy(+ copyEvent(),+ selectionInside(message),+ viewport,+ );++ assert.deepEqual(decision, { kind: "fast" });+});++test("a form control inside the selected subtree still refuses the fast path", () => {+ const message = { querySelector: () => ({ tag: "textarea" }) };+ const viewport: ThreadViewportLike = {+ contains: () => true,+ querySelector: () => null,+ };++ assert.deepEqual(+ decideThreadCopy(copyEvent(), selectionInside(message), viewport),+ { kind: "native", reason: "form-control" },+ );+});++test("a range ending in a text node is checked against that node's element", () => {+ // Range.commonAncestorContainer is very often a text node, which has no querySelector.+ const paragraph = { querySelector: () => ({ tag: "textarea" }) };+ const textNode = { parentElement: paragraph };+ const selection: SelectionLike = {+ isCollapsed: false,+ rangeCount: 1,+ getRangeAt: () => ({ commonAncestorContainer: textNode }),+ toString: () => "half a sentence",+ };+ const viewport: ThreadViewportLike = {+ contains: () => true,+ querySelector: () => null,+ };++ assert.deepEqual(decideThreadCopy(copyEvent(), selection, viewport), {+ kind: "native",+ reason: "form-control",+ });+});++test("a multi-range selection is checked against the whole viewport", () => {+ // Disjoint ranges have no common ancestor short of the viewport, so the wide check is the only+ // sound one.+ const viewport: ThreadViewportLike = {+ contains: () => true,+ querySelector: () => ({ tag: "input" }),+ };+ const selection: SelectionLike = {+ isCollapsed: false,+ rangeCount: 2,+ getRangeAt: () => ({+ commonAncestorContainer: { querySelector: () => null },+ }),+ toString: () => "two disjoint runs",+ };++ assert.deepEqual(decideThreadCopy(copyEvent(), selection, viewport), {+ kind: "native",+ reason: "form-control",+ });+});++// --- a document, hand-rolled ------------------------------------------------------------------+// Enough of one for the serialiser and the probe, and no more. Three properties make it worth+// trusting: `querySelectorAll` throws on any selector it does not really implement, so the module+// cannot quietly ask for something the fake glosses over; `toString()` is computed from the tree+// at the instant it is asked, so alt text reaches the output only if a holder was really inserted;+// and inline style is a property map with priorities, so a restore that loses `!important` shows.+//+// What it does NOT prove is the thing only a browser can: that `toString()` under these patches+// equals the clipboard's `text/plain`. That was measured, over 27 constructs, and is what the doc+// comment records.++type StyleEntry = { value: string; priority: string };++type FakeText = {+ readonly nodeType: 3;+ readonly data: string;+ parentNode: FakeElement | null;+ readonly ownerDocument: typeof fakeDocument;+};++type FakeNode = FakeText | FakeElement;++type FakeElement = {+ readonly nodeType: 1;+ readonly tagName: string;+ readonly attrs: Map<string, string>;+ readonly childNodes: FakeNode[];+ parentNode: FakeElement | null;+ readonly parentElement: FakeElement | null;+ /** What a class rule gives this element. Inherited by descendants, the way CSS does it. */+ readonly ruleTextTransform: string | null;+ readonly ruleVisibility: string | null;+ readonly styleEntries: Map<string, StyleEntry>;+ readonly style: {+ getPropertyValue(name: string): string;+ getPropertyPriority(name: string): string;+ setProperty(name: string, value: string, priority?: string): void;+ removeProperty(name: string): void;+ };+ readonly ownerDocument: typeof fakeDocument;+ textContent: string;+ getAttribute(name: string): string | null;+ setAttribute(name: string, value: string): void;+ removeAttribute(name: string): void;+ readonly attributes: { removeNamedItem(name: string): void };+ querySelector(selectors: string): FakeElement | null;+ querySelectorAll(selectors: string): FakeElement[];+ insertBefore(node: FakeNode, ref: FakeNode | null): FakeNode;+ remove(): void;+};++/**+ * `patchClipboardDeltas` narrows the root with `root instanceof HTMLElement`, so a fake element+ * has to be one. The constructor is never called: elements are built as object literals and given+ * this prototype, which is all `instanceof` looks at.+ */+class FakeHtmlElement {}++Object.defineProperty(globalThis, "HTMLElement", {+ configurable: true,+ writable: true,+ value: FakeHtmlElement,+});++function text(data: string): FakeText {+ // Text nodes carry an ownerDocument too, because a selection endpoint is usually one of+ // these and that is where `captureDirection` reaches for `createRange`.+ return { nodeType: 3, data, parentNode: null, ownerDocument: fakeDocument };+}++/** Only the selectors this module actually uses. Anything else is a hole in the fake, not a pass. */+function matchesSelector(node: FakeElement, selectors: string): boolean {+ return selectors.split(",").some((part) => {+ const one = part.trim();+ if (one === "*") return true;+ if (one === "img[alt]") {+ return node.tagName === "img" && node.attrs.has("alt");+ }+ if (one === "input" || one === "textarea" || one === "select") {+ return node.tagName === one;+ }+ throw new Error(`the fake DOM does not implement the selector ${one}`);+ });+}++/**+ * Removing or inserting a node inside a live range COLLAPSES that range in Chromium, which is the+ * whole reason faithfulSelectionText re-establishes the selection twice: once after patching and+ * once after undoing. Without modelling it, the second restore looks like dead code.+ *+ * One listener per fake selection, and they outlive their test, which is why each of them checks+ * that the mutation was inside its own root before reacting.+ */+const mutationListeners: Array<(parent: FakeElement) => void> = [];++function notifyMutation(parent: FakeElement): void {+ for (const listener of mutationListeners) listener(parent);+}++function isWithin(node: FakeElement | null, root: FakeElement): boolean {+ for (let at = node; at !== null; at = at.parentNode) {+ if (at === root) return true;+ }+ return false;+}++function descendants(node: FakeElement): FakeElement[] {+ const found: FakeElement[] = [];+ for (const child of node.childNodes) {+ if (child.nodeType !== 1) continue;+ found.push(child, ...descendants(child));+ }+ return found;+}++function el(+ tagName: string,+ options: {+ alt?: string;+ /** What a class rule gives this element's visibility, e.g. Studio's `invisible`. */+ ruleVisibility?: string;+ /** [property, value, priority] triples, as an inline style attribute. */+ inline?: ReadonlyArray<readonly [string, string, string?]>;+ /** A stylesheet rule on this element, e.g. Tailwind's `uppercase`. */+ rule?: string;+ children?: ReadonlyArray<FakeNode | string>;+ } = {},+): FakeElement {+ const attrs = new Map<string, string>();+ if (options.alt !== undefined) attrs.set("alt", options.alt);+ const styleEntries = new Map<string, StyleEntry>();+ for (const [name, value, priority] of options.inline ?? []) {+ styleEntries.set(name, { value, priority: priority ?? "" });+ }+ const childNodes: FakeNode[] = [];+ // THE COUPLING THE STUB WAS MISSING. On a real element the inline declaration and the `style`+ // attribute are two views of one thing: touching a property writes the attribute, and emptying+ // the declaration leaves `style=""` rather than removing it. Keeping them in separate maps is+ // why "the dom is left exactly as it was found" stayed green while every copy was leaving+ // residue in the document.+ const syncStyleAttribute = () => {+ attrs.set(+ "style",+ [...styleEntries]+ .map(+ ([name, entry]) =>+ `${name}: ${entry.value}${entry.priority ? ` !${entry.priority}` : ""};`,+ )+ .join(" "),+ );+ };+ const readStyleAttribute = (value: string) => {+ styleEntries.clear();+ for (const part of value.split(";")) {+ const [rawName, ...rest] = part.split(":");+ if (rest.length === 0) continue;+ const name = rawName.trim();+ if (!name) continue;+ const raw = rest.join(":").trim();+ const important = raw.endsWith("!important");+ styleEntries.set(name, {+ value: important ? raw.slice(0, -"!important".length).trim() : raw,+ priority: important ? "important" : "",+ });+ }+ };++ // An element built WITH inline styles must carry the matching `style` attribute from the+ // start, exactly as parsed markup would. Seeding the declaration alone left `getAttribute`+ // returning null, so a restore saw "there was no style attribute" and removed the element's+ // own styling.+ if (styleEntries.size > 0) syncStyleAttribute();++ const node: FakeElement = {+ nodeType: 1,+ tagName,+ attrs,+ childNodes,+ parentNode: null,+ get parentElement() {+ return node.parentNode;+ },+ ruleTextTransform: options.rule ?? null,+ ruleVisibility: options.ruleVisibility ?? null,+ styleEntries,+ style: {+ getPropertyValue: (name) => styleEntries.get(name)?.value ?? "",+ getPropertyPriority: (name) => styleEntries.get(name)?.priority ?? "",+ setProperty: (name, value, priority = "") => {+ styleEntries.set(name, { value, priority });+ syncStyleAttribute();+ },+ removeProperty: (name) => {+ styleEntries.delete(name);+ syncStyleAttribute();+ },+ },+ ownerDocument: fakeDocument,+ get textContent() {+ return childNodes.map(renderSource).join("");+ },+ set textContent(value: string) {+ childNodes.length = 0;+ node.insertBefore(text(value), null);+ },+ getAttribute: (name) => attrs.get(name) ?? null,+ setAttribute: (name, value) => {+ attrs.set(name, value);+ if (name === "style") readStyleAttribute(value);+ },+ // `removeAttribute` and the attribute NODE removal are different operations on a real+ // element, and the difference is the bug this stub failed to catch. Both are modelled.+ removeAttribute: (name) => {+ attrs.delete(name);+ if (name === "style") styleEntries.clear();+ },+ attributes: {+ removeNamedItem: (name: string) => {+ if (!attrs.has(name)) {+ // The real DOM throws NotFoundError, which the module relies on catching.+ throw new Error(`NotFoundError: no attribute named ${name}`);+ }+ attrs.delete(name);+ if (name === "style") styleEntries.clear();+ },+ },+ querySelector: (selectors) =>+ descendants(node).find((child) => matchesSelector(child, selectors)) ??+ null,+ querySelectorAll: (selectors) =>+ descendants(node).filter((child) => matchesSelector(child, selectors)),+ insertBefore(child, ref) {+ const at = ref === null ? -1 : childNodes.indexOf(ref);+ childNodes.splice(at < 0 ? childNodes.length : at, 0, child);+ child.parentNode = node;+ notifyMutation(node);+ return child;+ },+ remove() {+ const parent = node.parentNode;+ if (!parent) return;+ parent.childNodes.splice(parent.childNodes.indexOf(node), 1);+ node.parentNode = null;+ notifyMutation(parent);+ },+ };+ Object.setPrototypeOf(node, FakeHtmlElement.prototype);+ for (const child of options.children ?? []) {+ node.insertBefore(typeof child === "string" ? text(child) : child, null);+ }+ return node;+}++/** Untransformed text, which is what `textContent` reports and what the clipboard carries. */+function renderSource(node: FakeNode): string {+ return node.nodeType === 3+ ? node.data+ : node.childNodes.map(renderSource).join("");+}++/** The cascade, as far as this module can see it: own inline, own rule, then inherited. */+function computedTextTransform(node: FakeElement | null): string {+ for (let at = node; at !== null; at = at.parentNode) {+ const inline = at.styleEntries.get("text-transform");+ if (inline) return inline.value;+ if (at.ruleTextTransform) return at.ruleTextTransform;+ }+ return "none";+}++function isDisplayNone(node: FakeElement | null): boolean {+ for (let at = node; at !== null; at = at.parentNode) {+ if (at.styleEntries.get("display")?.value === "none") return true;+ }+ return false;+}++function applyTransform(value: string, transform: string): string {+ if (transform === "uppercase") return value.toUpperCase();+ if (transform === "lowercase") return value.toLowerCase();+ if (transform === "capitalize") {+ return value.replace(/\b\w/g, (letter) => letter.toUpperCase());+ }+ return value;+}++/**+ * What `Selection.toString()` would give for everything under `node`.+ *+ * The two behaviours that matter are the ones the module patches around: text is emitted as it is+ * RENDERED, so a text-transform shows up; and an image emits nothing of its own, which is why the+ * alt text has to arrive as a real inserted node or not at all.+ */+function renderSelected(node: FakeNode): string {+ if (node.nodeType === 3) {+ if (isDisplayNone(node.parentNode)) return "";+ return applyTransform(node.data, computedTextTransform(node.parentNode));+ }+ if (isDisplayNone(node)) return "";+ if (node.tagName === "img") return "";+ return node.childNodes.map(renderSelected).join("");+}++/**+ * A structural snapshot, for asserting the document was put back.+ *+ * Inline style is compared as a SET of (property, value, priority): declaration order inside a+ * style attribute is not observable to anything the app reads, and a real CSSStyleDeclaration+ * reorders on removeProperty/setProperty anyway, so ordering here would fail a correct restore.+ */+function snapshot(node: FakeNode): unknown {+ if (node.nodeType === 3) return { text: node.data };+ return {+ tag: node.tagName,+ attrs: [...node.attrs].sort(),+ style: [...node.styleEntries]+ .map(+ ([name, entry]) =>+ `${name}: ${entry.value}${entry.priority ? ` !${entry.priority}` : ""}`,+ )+ .sort(),+ children: node.childNodes.map(snapshot),+ };+}++type FakeRange = {+ readonly id: number;+ readonly commonAncestorContainer: FakeElement | null;+ readonly startContainer: FakeNode | null;+ readonly startOffset: number;+ readonly endContainer: FakeNode | null;+ readonly endOffset: number;+ cloneRange(): FakeRange;+};++function fakeRange(+ id: number,+ container: FakeElement | null = null,+ bounds: {+ startContainer?: FakeNode | null;+ startOffset?: number;+ endContainer?: FakeNode | null;+ endOffset?: number;+ } = {},+): FakeRange {+ // A real Range is LIVE: its boundaries move as the DOM around them changes, which is why the+ // restore reads them instead of the raw offsets captured before the patch ran.+ return {+ id,+ commonAncestorContainer: container,+ startContainer: bounds.startContainer ?? container,+ startOffset: bounds.startOffset ?? 0,+ endContainer: bounds.endContainer ?? container,+ endOffset: bounds.endOffset ?? 0,+ cloneRange: () => fakeRange(id, container, bounds),+ };+}++/**+ * A selection over `root`, plus the probe behaviour engineClipboardIsMapped needs.+ *+ * `selectAllChildren` switches what `toString()` answers, and `removeAllRanges` switches it back,+ * which is exactly the sequence the probe performs.+ */+function fakeSelection(+ root: FakeElement,+ options: {+ ids?: number[];+ probeText?: string;+ anchorNode?: FakeNode;+ anchorOffset?: number;+ focusNode?: FakeNode;+ focusOffset?: number;+ /** The LIVE range boundaries, which the restore reads instead of the raw offsets. */+ bounds?: {+ startContainer?: FakeNode | null;+ startOffset?: number;+ endContainer?: FakeNode | null;+ endOffset?: number;+ };+ } = {},+) {+ const { ids = [1], probeText = "a" } = options;+ const bounds = options.bounds ?? {};+ // A selection's DIRECTION lives in its anchor/focus pair and nowhere else. A cloned Range+ // carries ordered boundaries only, so a restore that rebuilds from ranges silently flips a+ // backward selection forward. Recording the calls is how a test can tell which API was used.+ const calls: {+ setBaseAndExtent: Array<{+ anchorNode: FakeNode | null;+ anchorOffset: number;+ focusNode: FakeNode | null;+ focusOffset: number;+ }>;+ } = { setBaseAndExtent: [] };+ let anchorNode: FakeNode | null = options.anchorNode ?? null;+ let anchorOffset = options.anchorOffset ?? 0;+ let focusNode: FakeNode | null = options.focusNode ?? null;+ let focusOffset = options.focusOffset ?? 0;+ let ranges = ids.map((id) => fakeRange(id, root, bounds));+ let probing = false;+ let collapsedByMutation = false;+ mutationListeners.push((parent) => {+ if (isWithin(parent, root)) collapsedByMutation = true;+ });+ /** Take the collapse the last mutation inside the selection would really have caused. */+ const sync = () => {+ if (!collapsedByMutation) return;+ collapsedByMutation = false;+ ranges = [];+ };+ const selection = {+ get rangeCount() {+ sync();+ return ranges.length;+ },+ getRangeAt: (index: number) => {+ sync();+ return ranges[index];+ },+ // ANCHOR AND FOCUS MOVE WITH THE RANGES, as they do in a real engine. A stub that left+ // them where the test set them would report the ORIGINAL direction no matter what the code+ // did to the selection, so a restore that flips a backward selection forward would pass.+ removeAllRanges() {+ sync();+ ranges = [];+ probing = false;+ anchorNode = null;+ anchorOffset = 0;+ focusNode = null;+ focusOffset = 0;+ },+ addRange(range: FakeRange) {+ sync();+ ranges.push(range);+ // Per the spec: the anchor is the range's START and the focus its END, which is exactly+ // why rebuilding this way can only ever produce a forward selection.+ anchorNode = range.startContainer;+ anchorOffset = range.startOffset;+ focusNode = range.endContainer;+ focusOffset = range.endOffset;+ },+ selectAllChildren() {+ sync();+ ranges = [];+ probing = true;+ // Whatever the engine puts here, it is the probe's node and not the user's selection.+ anchorNode = null;+ anchorOffset = 0;+ focusNode = null;+ focusOffset = 0;+ },+ toString: () => {+ sync();+ if (probing) return probeText;+ return ranges.length === 0 ? "" : renderSelected(root);+ },+ get anchorNode() {+ return anchorNode;+ },+ get anchorOffset() {+ return anchorOffset;+ },+ get focusNode() {+ return focusNode;+ },+ get focusOffset() {+ return focusOffset;+ },+ setBaseAndExtent(+ newAnchor: FakeNode,+ newAnchorOffset: number,+ newFocus: FakeNode,+ newFocusOffset: number,+ ) {+ sync();+ anchorNode = newAnchor;+ anchorOffset = newAnchorOffset;+ focusNode = newFocus;+ focusOffset = newFocusOffset;+ // The boundaries are restored too, so the selection is usable afterwards.+ ranges = ids.map((id) => fakeRange(id, root, bounds));+ calls.setBaseAndExtent.push({+ anchorNode: newAnchor,+ anchorOffset: newAnchorOffset,+ focusNode: newFocus,+ focusOffset: newFocusOffset,+ });+ },+ };+ return {+ selection,+ calls,+ currentIds: () => {+ sync();+ return ranges.map((range) => range.id);+ },+ };+}++/**+ * `captureDirection` asks a throwaway Range whether the focus lies before the anchor, so the+ * stub needs `ownerDocument.createRange()` on every node. Document order is computed from the+ * parent chains, which is what `comparePoint` reports and needs no knowledge of a root.+ */+function chain(node: FakeNode): FakeNode[] {+ const path: FakeNode[] = [];+ for (let at: FakeNode | null = node; at !== null; at = at.parentNode)+ path.unshift(at);+ return path;+}++/** -1 if `b` precedes `a` in document order, 1 if it follows, 0 if they are the same point. */+function documentOrder(+ a: FakeNode,+ aOffset: number,+ b: FakeNode,+ bOffset: number,+): number {+ const pa = chain(a);+ const pb = chain(b);+ let depth = 0;+ while (depth < pa.length && depth < pb.length && pa[depth] === pb[depth]) {+ depth += 1;+ }+ if (depth === pa.length && depth === pb.length) {+ return bOffset === aOffset ? 0 : bOffset < aOffset ? -1 : 1;+ }+ const parent = pa[depth - 1];+ if (!parent || parent.nodeType !== 1) return 0;+ const kids = parent.childNodes;+ const ia = depth < pa.length ? kids.indexOf(pa[depth]) : aOffset;+ const ib = depth < pb.length ? kids.indexOf(pb[depth]) : bOffset;+ if (ib === ia) return 0;+ return ib < ia ? -1 : 1;+}++const fakeDocument = {+ createElement: (tag: string) => el(tag),+ createRange: () => {+ let anchor: FakeNode | null = null;+ let anchorAt = 0;+ return {+ setStart(node: FakeNode, offset: number) {+ anchor = node;+ anchorAt = offset;+ },+ setEnd() {},+ comparePoint: (node: FakeNode, offset: number) =>+ anchor === null ? 0 : documentOrder(anchor, anchorAt, node, offset),+ };+ },+};++/** The module reads the bare global, not `view.getComputedStyle`. */+Object.defineProperty(globalThis, "getComputedStyle", {+ configurable: true,+ writable: true,+ value: (node: FakeElement) => ({+ textTransform: computedTextTransform(node),+ // `display` is not inherited; `visibility` and `user-select` are, which is why the module+ // can read the computed value and not walk ancestors itself. An image the native iterator+ // skips must not get an alt-text holder, so these three decide whether it does.+ display: node.styleEntries.get("display")?.value ?? "inline",+ visibility: inheritedStyle(node, "visibility", "visible"),+ userSelect: inheritedStyle(node, "user-select", "auto"),+ webkitUserSelect: inheritedStyle(node, "-webkit-user-select", "auto"),+ }),+});++/** An inherited property, resolved the way the cascade does: own inline, own rule, ancestors. */+function inheritedStyle(+ node: FakeElement | null,+ name: string,+ fallback: string,+): string {+ for (let at = node; at !== null; at = at.parentNode) {+ const inline = at.styleEntries.get(name);+ if (inline) return inline.value;+ if (name === "visibility" && at.ruleVisibility) return at.ruleVisibility;+ }+ return fallback;+}++// --- the behavioural probe ---------------------------------------------------------------------++const CHROMIUM_UA =+ "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36";+const WEBKIT_UA =+ "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.4 Safari/605.1.15";++function fakeView(options: {+ userAgent: string;+ probeText?: string;+ root?: FakeElement;+ selectionIds?: number[];+ /** The user's own selection, when a test cares which way round it is. */+ anchorNode?: FakeNode;+ anchorOffset?: number;+ focusNode?: FakeNode;+ focusOffset?: number;+ bounds?: {+ startContainer?: FakeNode | null;+ startOffset?: number;+ endContainer?: FakeNode | null;+ endOffset?: number;+ };+}) {+ const root = options.root ?? el("div", { children: ["thread text"] });+ const { selection, currentIds, calls } = fakeSelection(root, {+ ids: options.selectionIds ?? [1],+ probeText: options.probeText ?? "a",+ anchorNode: options.anchorNode,+ anchorOffset: options.anchorOffset,+ focusNode: options.focusNode,+ focusOffset: options.focusOffset,+ bounds: options.bounds,+ });+ const body = el("body");+ // A counter rather than a throwing getter: engineClipboardIsMapped swallows everything it+ // catches, so a throw would be indistinguishable from an honest `false`.+ let documentReads = 0;+ const document = {+ createElement: (tag: string) => el(tag),+ body: {+ appendChild: (child: FakeElement) => body.insertBefore(child, null),+ },+ };+ const view = {+ navigator: { userAgent: options.userAgent },+ get document() {+ documentReads += 1;+ return document;+ },+ getSelection: () => selection,+ };+ return {+ view,+ root,+ selection,+ currentIds,+ calls,+ body,+ documentReads: () => documentReads,+ };+}++/** The probe assigns `style.cssText` and `innerHTML`, which the fake element does not model. */+function asWindow(view: unknown): Window & typeof globalThis {+ return view as Window & typeof globalThis;+}++test("a non-chromium user agent is unmapped without the document being touched", () => {+ // WebKit's `toString()` appends block breaks its clipboard does not carry, so the answer is+ // known before any probe runs, and running one would cost a style recalc for nothing.+ const world = fakeView({ userAgent: WEBKIT_UA, probeText: "a" });++ assert.equal(engineClipboardIsMapped(asWindow(world.view)), false);+ assert.equal(world.documentReads(), 0);+ assert.equal(world.body.childNodes.length, 0);+});++test("a chromium engine whose toString appends a block break is unmapped", () => {+ // The probe is a hidden <p>a</p>. An engine that answers "a\n\n" to that is the WebKit+ // behaviour under a Chromium-looking user agent, and the user agent is never allowed to decide+ // what bytes are produced.+ const world = fakeView({ userAgent: CHROMIUM_UA, probeText: "a\n\n" });++ assert.equal(engineClipboardIsMapped(asWindow(world.view)), false);+ assert.equal(world.documentReads(), 1);+});++test("a chromium engine whose toString matches its clipboard is mapped", () => {+ const world = fakeView({ userAgent: CHROMIUM_UA, probeText: "a" });++ assert.equal(engineClipboardIsMapped(asWindow(world.view)), true);+ // And the probe took its own node back out of the body.+ assert.equal(world.body.childNodes.length, 0);+});++test("the probe's answer is cached on the view", () => {+ // It cannot change within a document, and it costs a node insertion, a style recalc and a round+ // trip through the user's selection.+ const world = fakeView({ userAgent: CHROMIUM_UA, probeText: "a" });++ assert.equal(engineClipboardIsMapped(asWindow(world.view)), true);+ assert.equal(world.documentReads(), 1);+ assert.equal(engineClipboardIsMapped(asWindow(world.view)), true);+ assert.equal(world.documentReads(), 1);+ assert.equal(+ (world.view as { __sbFastCopyMapped?: boolean }).__sbFastCopyMapped,+ true,+ );+});++test("the probe puts a backward selection back backward", () => {+ // The probe takes the selection away and rebuilds it, so it has the serialiser's problem and+ // needs the serialiser's answer. Rebuilding from the saved ranges alone always produces a+ // forward selection, so a user who dragged right to left had their highlight silently reversed+ // by the first copy in the document, and their next Shift+Arrow moved the opposite end.+ //+ // Asserted on the anchor/focus PAIR, not on the copied text, which is identical either way.+ const first = text("first paragraph");+ const second = text("second paragraph");+ const root = el("div", {+ children: [+ el("p", { children: [first] }),+ el("p", { children: [second] }),+ ],+ });+ const world = fakeView({+ userAgent: CHROMIUM_UA,+ probeText: "a",+ root,+ anchorNode: second,+ anchorOffset: 16,+ focusNode: first,+ focusOffset: 0,+ bounds: {+ startContainer: first,+ startOffset: 0,+ endContainer: second,+ endOffset: 16,+ },+ });++ engineClipboardIsMapped(asWindow(world.view));++ assert.equal(world.selection.anchorNode, second);+ assert.equal(world.selection.anchorOffset, 16);+ assert.equal(world.selection.focusNode, first);+ assert.equal(world.selection.focusOffset, 0);+});++test("the probe leaves a forward selection forward", () => {+ // The other half of the rule, so the fix cannot be "always swap".+ const first = text("first paragraph");+ const second = text("second paragraph");+ const root = el("div", {+ children: [+ el("p", { children: [first] }),+ el("p", { children: [second] }),+ ],+ });+ const world = fakeView({+ userAgent: CHROMIUM_UA,+ probeText: "a",+ root,+ anchorNode: first,+ anchorOffset: 0,+ focusNode: second,+ focusOffset: 16,+ bounds: {+ startContainer: first,+ startOffset: 0,+ endContainer: second,+ endOffset: 16,+ },+ });++ engineClipboardIsMapped(asWindow(world.view));++ assert.equal(world.selection.anchorNode, first);+ assert.equal(world.selection.anchorOffset, 0);+ assert.equal(world.selection.focusNode, second);+ assert.equal(world.selection.focusOffset, 16);+});++test("the probe puts the user's selection back", () => {+ const world = fakeView({+ userAgent: CHROMIUM_UA,+ probeText: "a",+ selectionIds: [7, 8],+ });++ engineClipboardIsMapped(asWindow(world.view));++ assert.deepEqual(world.currentIds(), [7, 8]);+ // And by `addRange`, not `setBaseAndExtent`, which takes ONE anchor/focus pair and so cannot+ // express two ranges. Firefox is the only engine that produces them, and this fast path does+ // not run there, but dropping a range would be worse than losing its direction.+ assert.deepEqual(world.calls.setBaseAndExtent, []);+});++// --- the serialiser ----------------------------------------------------------------------------++function serialise(root: FakeElement, ids: number[] = [1]) {+ const { selection, currentIds } = fakeSelection(root, { ids });+ const before = snapshot(root);+ const output = faithfulSelectionText(+ selection as unknown as Selection,+ root as unknown as Element,+ );+ return { output, before, after: snapshot(root), currentIds };+}++test("the alt text of an image reaches the output", () => {+ // Blink's EmitsImageAltText, which ApplyWebPreferences turns on for every web view, so this is+ // not conditional in practice. `toString()` drops it, so it has to arrive as a real node.+ const root = el("p", {+ children: ["before ", el("img", { alt: "a cat" }), " after"],+ });++ assert.equal(serialise(root).output, "before a cat after");+});++test("an image with an empty alt contributes nothing", () => {+ // alt="" is what every decorative image in the thread carries, and it emits nothing on either+ // side. An empty holder would serialise to nothing too, so the output alone does not show the+ // difference: what is checked is that no node is inserted at all. Inserting one costs a+ // document mutation inside the user's live selection, which collapses it, per image, per copy.+ const root = el("p", {+ children: ["before ", el("img", { alt: "" }), "after"],+ });+ const { selection } = fakeSelection(root);+ let childrenWhileReading = 0;+ const watched = {+ ...selection,+ toString: () => {+ childrenWhileReading = root.childNodes.length;+ return renderSelected(root);+ },+ };++ const output = faithfulSelectionText(+ watched as unknown as Selection,+ root as unknown as Element,+ );++ assert.equal(output, "before after");+ assert.equal(childrenWhileReading, 3);+});++test("the alt text holder has no box of its own", () => {+ // Studio's message images are display:block, so an inline holder placed beside one sits between+ // two blocks, the engine wraps it in an anonymous block, and the alt text arrives with a leading+ // newline the clipboard does not have. Measured on the real thread as 40,650 characters against+ // the clipboard's 40,648, two images each contributing one extra break. Taking the image out of+ // the flow removes the box the break came from; an image contributes no text of its own, so+ // hiding it changes nothing else.+ const image = el("img", { alt: "a cat", inline: [["display", "block"]] });+ const root = el("p", { children: ["before ", image, " after"] });+ let displayWhileReading = "";+ const { selection } = fakeSelection(root);+ const watched = {+ ...selection,+ toString: () => {+ displayWhileReading = image.style.getPropertyValue("display");+ return renderSelected(root);+ },+ };++ const output = faithfulSelectionText(+ watched as unknown as Selection,+ root as unknown as Element,+ );++ assert.equal(output, "before a cat after");+ assert.equal(displayWhileReading, "none");+});++test("a no-break space is folded to a plain space", () => {+ // Both engines' clipboards fold U+00A0 to a plain space; neither `toString()` does.+ const root = el("p", { children: ["one\u00a0two\u00a0three"] });++ const { output } = serialise(root);++ assert.equal(output, "one two three");+ assert.equal(output.includes("\u00a0"), false);+});++test("the source text under a text-transform is what is serialised", () => {+ // Blink's IgnoresCssTextTransforms: the clipboard carries the source text, `toString()` carries+ // the rendered text. Chromium is the engine this runs on, so the source text is the target.+ const root = el("div", {+ children: [el("span", { rule: "uppercase", children: ["stdout"] })],+ });++ assert.equal(serialise(root).output, "stdout");+});++test("a transform inherited from an ancestor is neutralised too", () => {+ // text-transform inherits, so a child with no rule of its own still renders transformed, and+ // the patch has to reach it rather than only the element carrying the class.+ const root = el("div", {+ rule: "uppercase",+ children: [el("span", { children: ["stdout"] })],+ });++ assert.equal(serialise(root).output, "stdout");+});++test("the dom is left exactly as it was found", () => {+ // A copy that left a stray <span> in the message, or an inline `display: none` on an image,+ // would be a far worse bug than the one being fixed -- and it would persist, because nothing+ // ever re-renders that subtree on its own.+ //+ // WHAT THIS TEST CANNOT PROVE, stated because it once passed while the code was wrong. These+ // run against a hand-rolled stub, so they check that the patch's own bookkeeping balances --+ // no leftover node, no leftover property. They CANNOT see how a real engine serialises what is+ // left: Chromium keeps a `style=""` attribute on an element whose inline declaration has been+ // touched, even after `removeAttribute("style")`, so every copy was permanently rewriting the+ // document while this test was green. The structural parity digest found it, six actions+ // differing against a null that matched fifteen of sixteen. The authoritative check is+ // `tests/studio/playwright_thread_fast_copy.py`, which compares `outerHTML` before and after+ // in a real browser, per construct.+ const root = el("div", {+ children: [+ el("span", { rule: "uppercase", children: ["stdout"] }),+ " ",+ el("img", { alt: "a cat" }),+ el("p", { children: ["tail"] }),+ ],+ });++ const { before, after } = serialise(root);++ assert.deepEqual(after, before);+ assert.deepEqual(+ root.querySelectorAll("*").map((node) => node.tagName),+ ["span", "img", "p"],+ );+});++test("an element's own inline text-transform keeps its value and priority", () => {+ // The patch writes `text-transform: none !important` over whatever was there. Restoring the+ // value but dropping `!important` would silently change how the message renders from then on.+ const span = el("span", {+ inline: [+ ["color", "red"],+ ["text-transform", "capitalize", "important"],+ ],+ children: ["stdout"],+ });+ const root = el("div", { children: [span] });++ const { before, after, output } = serialise(root);++ assert.equal(output, "stdout");+ assert.equal(span.style.getPropertyValue("text-transform"), "capitalize");+ assert.equal(span.style.getPropertyPriority("text-transform"), "important");+ assert.deepEqual(after, before);+});++test("an image's own inline display keeps its value and priority", () => {+ const image = el("img", {+ alt: "a cat",+ inline: [["display", "inline-block", "important"]],+ });+ const root = el("p", { children: [image] });++ const { before, after, output } = serialise(root);++ assert.equal(output, "a cat");+ assert.equal(image.style.getPropertyValue("display"), "inline-block");+ assert.equal(image.style.getPropertyPriority("display"), "important");+ assert.deepEqual(after, before);+});++test("an element with no inline style of its own keeps none", () => {+ // removeProperty on a property that was never there must not leave an empty declaration behind.+ const span = el("span", { rule: "uppercase", children: ["stdout"] });+ const image = el("img", { alt: "a cat" });+ const root = el("div", { children: [span, image] });++ serialise(root);++ assert.deepEqual([...span.styleEntries.keys()], []);+ assert.deepEqual([...image.styleEntries.keys()], []);+});++test("the user's selection ranges are put back", () => {+ // An alt text holder is INSERTED before the read and REMOVED after it, and each of those is a+ // node mutation inside the user's live range, which collapses it. So the ranges have to be+ // re-established twice, and the second time is after the undo. A copy that quietly dropped the+ // user's highlight would be its own bug, and a visible one.+ const root = el("div", {+ children: [+ el("span", { rule: "uppercase", children: ["stdout"] }),+ el("img", { alt: "a cat" }),+ ],+ });++ const { currentIds, output } = serialise(root, [4, 5]);++ assert.equal(output, "stdouta cat");+ assert.deepEqual(currentIds(), [4, 5]);+});++test("nothing untouched is patched, so an unremarkable selection restores trivially", () => {+ // With no transform and no alt text there is nothing to undo, and the selection is never+ // disturbed at all.+ const root = el("div", { children: ["plain prose"] });+ const { selection, currentIds } = fakeSelection(root, { ids: [9] });+ const seen: number[] = [];+ const watched = {+ ...selection,+ removeAllRanges() {+ seen.push(-1);+ selection.removeAllRanges();+ },+ };++ const output = faithfulSelectionText(+ watched as unknown as Selection,+ root as unknown as Element,+ );++ assert.equal(output, "plain prose");+ assert.deepEqual(seen, []);+ assert.deepEqual(currentIds(), [9]);+});++test("a selection wholly inside a text-transformed element serialises the source text", () => {+ // The root, not only its descendants. `scopeElement` hands the serialiser the range's common+ // ancestor, and for a selection inside one leaf -- `<span class="uppercase">stdout</span>`,+ // which the code execution card renders five times over -- that ancestor IS the transformed+ // span. `querySelectorAll("*")` does not include the element it is called on, so this wrote+ // "STDOUT" where the clipboard carries "stdout" until the root was added to the scan.+ const root = el("span", { rule: "uppercase", children: ["stdout"] });++ const { output, before, after } = serialise(root);++ assert.equal(output, "stdout");+ assert.deepEqual(after, before);+});++test("a transform patched onto the root itself is undone with the rest", () => {+ // The root is patched by a different line from its descendants, so its undo is worth its own+ // check: a leftover `text-transform: none !important` would flatten the message's own styling+ // from the first copy onwards.+ const root = el("span", {+ inline: [["text-transform", "uppercase", "important"]],+ children: ["stdout"],+ });++ const { output } = serialise(root);++ assert.equal(output, "stdout");+ assert.equal(root.style.getPropertyValue("text-transform"), "uppercase");+ assert.equal(root.style.getPropertyPriority("text-transform"), "important");+});++// --- the listener ------------------------------------------------------------------------------+// The decision and the serialiser are only worth anything wired to a real event, writing the+// flavour they claim to.++type FakeListener = (event: unknown) => void;++function fakeViewport(+ options: { root?: FakeElement; userAgent?: string; probeText?: string } = {},+) {+ const world = fakeView({+ userAgent: options.userAgent ?? CHROMIUM_UA,+ probeText: options.probeText ?? "a",+ root: options.root,+ });+ const listeners = new Map<string, Set<FakeListener>>();+ const viewport = {+ contains: () => true,+ querySelector: () => null,+ ownerDocument: { defaultView: world.view },+ addEventListener(type: string, listener: FakeListener) {+ const set = listeners.get(type) ?? new Set<FakeListener>();+ set.add(listener);+ listeners.set(type, set);+ },+ removeEventListener(type: string, listener: FakeListener) {+ listeners.get(type)?.delete(listener);+ },+ };+ const dispatch = (type: string, event: unknown) => {+ for (const listener of listeners.get(type) ?? []) listener(event);+ };+ return { viewport, listeners, dispatch, world };+}++function fakeCopyEvent(overrides: Partial<CopyEventLike> = {}) {+ const written: [string, string][] = [];+ let prevented = 0;+ return {+ written,+ prevented: () => prevented,+ event: {+ ...copyEvent(overrides),+ clipboardData:+ overrides.clipboardData === null+ ? null+ : {+ setData(format: string, data: string) {+ written.push([format, data]);+ },+ },+ preventDefault() {+ prevented += 1;+ },+ },+ };+}++test("the listener writes text/plain and takes the event away from the browser", () => {+ // One text node, not two paragraphs: the fake DOM deliberately does not model block boundary+ // emission, because the module does not either -- delegating to the engine's own iterator+ // instead of writing a walker is the whole point of the file.+ const root = el("div", { children: ["first message\n\nsecond message"] });+ const { viewport, dispatch } = fakeViewport({ root });+ attachThreadFastCopy(viewport as unknown as HTMLElement);+ const copy = fakeCopyEvent();++ dispatch("copy", copy.event);++ assert.equal(copy.prevented(), 1);+ assert.deepEqual(copy.written, [+ ["text/plain", "first message\n\nsecond message"],+ ]);+});++test("a copy that serialises to nothing is neither prevented nor written to", () => {+ // A selection can be non-collapsed and still serialise to nothing -- an image with an empty alt+ // on its own. Writing "" would clear a clipboard the browser would have left alone.+ const root = el("div", { children: [el("img", { alt: "" })] });+ const { viewport, dispatch } = fakeViewport({ root });+ attachThreadFastCopy(viewport as unknown as HTMLElement);+ const copy = fakeCopyEvent();++ dispatch("copy", copy.event);++ assert.equal(copy.prevented(), 0);+ assert.deepEqual(copy.written, []);+});++test("a serialiser that throws leaves the copy to the browser", () => {+ // The patch could not be applied or undone cleanly. Slow and right beats fast and silently+ // different, and preventDefault has not been called yet when it happens.+ const root = el("div", { children: ["text"] });+ const exploding = {+ ...root,+ querySelectorAll: () => {+ throw new Error("style recalc failed");+ },+ };+ const { viewport, dispatch, world } = fakeViewport({+ root: exploding as unknown as FakeElement,+ });+ // The range has to point at the exploding element for the serialiser to reach it.+ world.selection.getRangeAt = () =>+ fakeRange(1, exploding as unknown as FakeElement);+ attachThreadFastCopy(viewport as unknown as HTMLElement);+ const copy = fakeCopyEvent();++ dispatch("copy", copy.event);++ assert.equal(copy.prevented(), 0);+ assert.deepEqual(copy.written, []);+});++test("a refused copy is neither prevented nor written to", () => {+ const { viewport, dispatch } = fakeViewport();+ attachThreadFastCopy(viewport as unknown as HTMLElement);+ const copy = fakeCopyEvent({ defaultPrevented: true });++ dispatch("copy", copy.event);++ assert.equal(copy.prevented(), 0);+ assert.deepEqual(copy.written, []);+});++test("an unmapped engine leaves the listener's copy to the browser", () => {+ const { viewport, dispatch } = fakeViewport({ userAgent: WEBKIT_UA });+ attachThreadFastCopy(viewport as unknown as HTMLElement);+ const copy = fakeCopyEvent();++ dispatch("copy", copy.event);++ assert.equal(copy.prevented(), 0);+ assert.deepEqual(copy.written, []);+});++test("only copy is listened for, so a cut still cuts", () => {+ // A cut has to mutate the document it cut from. The thread is not editable, so a cut inside it+ // is already a no-op, and one inside a message being edited belongs to that textarea.+ const { viewport, listeners } = fakeViewport();+ attachThreadFastCopy(viewport as unknown as HTMLElement);++ assert.deepEqual([...listeners.keys()], ["copy"]);+});++test("detaching removes the listener", () => {+ // The viewport is remounted on every thread switch, so a handler that outlived its element+ // would accumulate one per thread the user opened.+ const { viewport, dispatch, listeners } = fakeViewport();+ const detach = attachThreadFastCopy(viewport as unknown as HTMLElement);++ detach();++ assert.equal(listeners.get("copy")?.size, 0);+ const copy = fakeCopyEvent();+ dispatch("copy", copy.event);+ assert.equal(copy.prevented(), 0);+});++// --- what the native iterator skips ------------------------------------------------------------++test("an image the native iterator skips contributes no alt text", () => {+ // Raised in review and confirmed against the real clipboard. Chromium's iterator skips an+ // image that is not rendered or not selectable, so inserting its alt text unconditionally+ // ADDED text the clipboard never carried: 'before SVG preview after' against 'before after'.+ for (const inline of [+ [["display", "none"]],+ [["visibility", "hidden"]],+ [["user-select", "none"]],+ ] as const) {+ const root = el("p", {+ children: [+ "before ",+ el("img", { alt: "SVG preview", inline: [...inline] }),+ " after",+ ],+ });+ assert.equal(serialise(root).output, "before after");+ }+});++test("studio's own invisible class suppresses the alt text", () => {+ // `ImagePreview` carries `invisible` until the image loads, so a copy across a message whose+ // image had not finished loading gained an alt string. This is the reachable case, not a+ // hypothetical one.+ const root = el("p", {+ children: [+ "before ",+ el("img", { alt: "SVG preview", ruleVisibility: "hidden" }),+ " after",+ ],+ });++ assert.equal(serialise(root).output, "before after");+});++test("a visible image still contributes its alt text", () => {+ // The guard must not swallow the case the feature exists for.+ const root = el("p", {+ children: ["before ", el("img", { alt: "SVG preview" }), " after"],+ });++ assert.equal(serialise(root).output, "before SVG preview after");+});++test("a backward selection comes back backward", () => {+ // A cloned Range carries ordered boundaries and no direction, so rebuilding with `addRange`+ // turned a selection dragged upwards into a forward one and the user's next Shift+Arrow moved+ // the opposite edge. Only the patched path rebuilds, hence the image.+ //+ // The restore reads the range's LIVE boundaries rather than the offsets captured before the+ // patch, because the alt holders are inserted before their images and an element/child offset+ // would then point at the wrong child. So what is asserted here is that the live boundaries+ // came back SWAPPED, which is direction and nothing else.+ const first = text("first paragraph");+ const second = text("second paragraph");+ const root = el("div", {+ children: [+ el("p", { children: [first] }),+ el("p", { children: [second, el("img", { alt: "a cat" })] }),+ ],+ });+ const { selection, calls } = fakeSelection(root, {+ anchorNode: second,+ anchorOffset: 16,+ focusNode: first,+ focusOffset: 0,+ bounds: {+ startContainer: first,+ startOffset: 0,+ endContainer: second,+ endOffset: 16,+ },+ });++ faithfulSelectionText(+ selection as unknown as Selection,+ root as unknown as Element,+ );++ assert.deepEqual(calls.setBaseAndExtent.at(-1), {+ anchorNode: second,+ anchorOffset: 16,+ focusNode: first,+ focusOffset: 0,+ });+});++test("a forward selection is restored from the live boundaries in order", () => {+ // The other half of the same rule: forward stays forward, and both ends come from the range+ // rather than from the pre-patch offsets.+ const first = text("first paragraph");+ const second = text("second paragraph");+ const root = el("div", {+ children: [+ el("p", { children: [first] }),+ el("p", { children: [second, el("img", { alt: "a cat" })] }),+ ],+ });+ const { selection, calls } = fakeSelection(root, {+ anchorNode: first,+ anchorOffset: 0,+ focusNode: second,+ focusOffset: 16,+ bounds: {+ startContainer: first,+ startOffset: 0,+ endContainer: second,+ endOffset: 16,+ },+ });++ faithfulSelectionText(+ selection as unknown as Selection,+ root as unknown as Element,+ );++ assert.deepEqual(calls.setBaseAndExtent.at(-1), {+ anchorNode: first,+ anchorOffset: 0,+ focusNode: second,+ focusOffset: 16,+ });+});diff --git a/tests/studio/_thread_fast_copy_constructs.py b/tests/studio/_thread_fast_copy_constructs.pynew file mode 100644index 00000000000..8575590a84b--- /dev/null+++ b/tests/studio/_thread_fast_copy_constructs.py@@ -0,0 +1,95 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""The HTML constructs the thread's fast copy path is proven against, one per case.++Split out from playwright_thread_fast_copy.py so the table can be read on its own: it is the+list of things a message can contain that a clipboard might treat differently from+``Selection.toString()``, and every claim in+studio/frontend/src/components/assistant-ui/thread-fast-copy.ts about "what the clipboard does"+was measured by copying these one at a time and pasting the result back.++Grouped by what the driver expects of each:++ ANSWERED everything not named below. The serialiser must produce the clipboard's own string+ byte for byte.+ REFUSED the form controls. Chromium emits a control's value AND wraps it in block breaks+ whose shape depends on the control, so the fast path hands the copy back.+ NO CLIPBOARD content the engine copies nothing at all for, so there is no string to compare.++Adding a case here widens the proof for free; the driver iterates this dict.+"""++from __future__ import annotations++#: A 1x1 transparent GIF, left unclosed so a caller appends its own `alt="..."` attribute.+IMG = '<img src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==" '++CONSTRUCTS = {+ "plain": "<p>plain line</p>",+ "text_transform_up": '<p style="text-transform:uppercase">transformed heading</p>',+ "text_transform_low": '<p style="text-transform:lowercase">SHOUTED LINE</p>',+ "text_transform_cap": '<p style="text-transform:capitalize">a capitalised sentence</p>',+ "img_alt": f'<p>{IMG}alt="SVG preview"></p>',+ "img_alt_empty": f'<p>{IMG}alt=""></p>',+ "img_no_alt": f"<p>{IMG}></p>",+ "img_alt_inline": f'<p>before{IMG}alt="Tool result 1">after</p>',+ # An image the native iterator SKIPS. Raised in review and confirmed against the real+ # clipboard: inserting alt text for one of these ADDS text the clipboard never carried.+ # The `invisible` case is Studio's own ImagePreview before the image has loaded.+ "img_alt_display_none": f'<p>before {IMG}alt="SVG preview" style="display:none"> after</p>',+ "img_alt_hidden": f'<p>before {IMG}alt="SVG preview" style="visibility:hidden"> after</p>',+ "img_alt_unselectable": f'<p>before {IMG}alt="SVG preview" style="user-select:none"> after</p>',+ "img_alt_invisible_cls": (+ "<style>.invisible{visibility:hidden}</style>"+ f'<p>before {IMG}alt="SVG preview" class="invisible"> after</p>'+ ),+ "input_text": '<p><input value="field value"></p>',+ "input_password": '<p><input type="password" value="hunter2"></p>',+ "input_checkbox": '<p><input type="checkbox" checked></p>',+ "textarea": "<p><textarea>textarea body</textarea></p>",+ "select": (+ "<p><select><option>option one</option><option selected>option two</option></select></p>"+ ),+ "user_select_none": '<p style="user-select:none;-webkit-user-select:none">unselectable</p>',+ "display_none": '<p style="display:none">hidden line</p>',+ "visibility_hidden": '<p style="visibility:hidden">invisible line</p>',+ "generated": '<style>.g::before{content:"GEN "}</style><p class="g">generated host</p>',+ "white_space_pre": '<p style="white-space:pre"> pre spacing </p>',+ "br": "<p>line with a<br>break</p>",+ "list": "<ul><li>item one</li><li>item two</li></ul>",+ "table": "<table><tr><td>cell a</td><td>cell b</td></tr></table>",+ "link": '<p>a <a href="https://example.com">link</a> inline</p>',+ "nbsp": "<p> nbsp line</p>",+ "pre_code": '<pre><code>fn main() {\n println!("hi");\n}</code></pre>',+ "emoji": "<p>emoji \U0001f600 accents éè</p>",+ "blockquote": "<blockquote>quoted</blockquote>",+ "collapse_ws": "<p>trailing whitespace collapse</p>",+}++#: The only constructs the serialiser is allowed to refuse on a mapped engine. Everything else+#: must be answered AND must match the clipboard byte for byte.+MUST_REFUSE = frozenset({"input_text", "input_password", "input_checkbox", "textarea", "select"})++#: Constructs where the engine copies nothing at all, so there is no clipboard to compare with.+NO_COPY = frozenset({"user_select_none", "display_none", "visibility_hidden"})++#: A SELECTION THAT LIES ENTIRELY INSIDE THE TRANSFORMED ELEMENT. Its common ancestor is the text+#: node, so the scope is the transformed element ITSELF, which `querySelectorAll("*")` does not+#: include. Raised in review against the earlier gate; it applies with more force to a serialiser+#: that patches the scope's descendants, because the miss produces a wrong string rather than a+#: slow copy. All three failed before the fix that added the root to the patched set.+INSIDE_SCOPE = {+ "inside a transformed span": (+ '<p><span style="text-transform:uppercase" id="t">transformed heading</span></p>',+ "document.getElementById('t')",+ ),+ "inside a transformed ancestor": (+ '<div style="text-transform:lowercase"><p><span id="t">SHOUTED LINE</span></p></div>',+ "document.getElementById('t')",+ ),+ "text node inside a transformed div": (+ '<div style="text-transform:capitalize" id="t">a capitalised sentence</div>',+ "document.getElementById('t')",+ ),+}diff --git a/tests/studio/playwright_thread_fast_copy.py b/tests/studio/playwright_thread_fast_copy.pynew file mode 100644index 00000000000..14f64757396--- /dev/null+++ b/tests/studio/playwright_thread_fast_copy.py@@ -0,0 +1,458 @@+# SPDX-License-Identifier: AGPL-3.0-only+# Copyright 2026-present the Unsloth AI Inc. team. All rights reserved. See /studio/LICENSE.AGPL-3.0++"""BYTE-FOR-BYTE, over every construct and over many partial selections.++studio/frontend/src/components/assistant-ui/thread-fast-copy.ts writes the thread's `text/plain`+clipboard payload itself instead of letting the browser build the styled flavour. That is only+safe if the string it writes is the string the browser would have written, and no unit test can+show that: the unit tests run against a hand-rolled DOM stub, so they check the patch's own+bookkeeping and cannot see how a real engine serialises anything. This file is the part that+needs a real browser and a real clipboard.++Two claims are under test and they are different claims:++ 1. where the serialiser ANSWERS, the string is identical to what the engine puts on the+ clipboard for the same selection;+ 2. where the gate REFUSES, the refusal is not gratuitous -- a form control is refused because+ the engine really does emit its value, and an unmapped engine is refused because its own+ `toString()` really does disagree with its clipboard.++A refusal that happens to be right by accident is not a pass, so the refusals are checked+separately rather than counted as successes.++WHAT IS BUILT, AND WHY IT IS BUILT. The bundle comes from the TypeScript in this tree, compiled+by studio/frontend/scripts/build-fast-copy-bundle.mjs. Proving a hand-kept reference implementation would+only prove the reference implementation; the thing that reaches a user is the module, so the+module is what is loaded into the page.++WHAT THIS DOES NOT COVER. `decideThreadCopy`'s branches that need no DOM -- an already-handled+event, a missing `clipboardData`, a copy originating in a text control -- are unit tested in+studio/frontend/tests/thread-fast-copy.test.ts and are not re-driven here. This file drives the+two halves that are only true of a real engine: `faithfulSelectionText` and+`engineClipboardIsMapped`. The gate itself is called for real, so a construct's verdict comes+from the shipped decision function rather than from a re-statement of it; only `scopeElement`,+which the module does not export, is restated in the page shim.++Prerequisites:++ (cd studio/frontend && npm ci) # the bundle is built with the frontend's own vite+ python3 -m playwright install chromium webkit++Run:++ python3 tests/studio/playwright_thread_fast_copy.py # chromium, then webkit+ python3 tests/studio/playwright_thread_fast_copy.py chromium++Exit codes:++ 0 every claim above held, OR a prerequisite is missing and the run was SKIPPED+ 1 at least one divergence was proven+ 2 the harness itself could not run (the bundle would not build)++It is deliberately not wired into Frontend CI, and is listed with its reason in+tests/studio/test_playwright_suites_run_in_ci.py. The short version: that job installs Chromium+only, and half of what is asserted here is about the engine that is NOT Chromium.+"""++from __future__ import annotations++import argparse+import subprocess+import sys+import tempfile+from pathlib import Path++from playwright.sync_api import sync_playwright++HERE = Path(__file__).resolve().parent+REPO = HERE.parents[1]+FRONTEND = REPO / "studio" / "frontend"+BUNDLER = FRONTEND / "scripts" / "build-fast-copy-bundle.mjs"++sys.path.insert(0, str(HERE))+from _thread_fast_copy_constructs import ( # noqa: E402+ CONSTRUCTS,+ IMG,+ INSIDE_SCOPE,+ MUST_REFUSE,+ NO_COPY,+)++IMG_TAG = IMG + 'alt="a cat">'+++class MissingPrerequisite(Exception):+ """Something the run needs is not installed. Reported as a SKIP, never as a pass."""+++#: The bundle exposes the module's exports; this gives the page one entry point with the shape+#: the driver wants. The gate and the serialiser are the shipped ones -- the only thing restated+#: here is `scopeElement`, which is module-private.+SHIM = """+window.__fastCopy = function () {+ const M = window.SBFastCopy;+ if (!M) return { text: null, reason: "the module did not load" };+ const viewport = document.getElementById("v");+ const selection = window.getSelection();+ const event = {+ defaultPrevented: false,+ target: selection.anchorNode,+ clipboardData: { setData() {} },+ };+ const decision = M.decideThreadCopy(+ event, selection, viewport, M.engineClipboardIsMapped(window),+ );+ if (decision.kind !== "fast") return { text: null, reason: decision.reason };+ let root = selection.getRangeAt(0).commonAncestorContainer;+ if (root.nodeType !== 1) root = root.parentElement;+ return { text: M.faithfulSelectionText(selection, root || viewport), reason: null };+};+"""++PAGE = """<!doctype html><meta charset=utf-8>+<div id="v">__BODY__</div>+<textarea id="sink" style="position:fixed;bottom:0"></textarea>"""++SELECT_ALL = "window.getSelection().selectAllChildren(document.getElementById('v'))"++#: Partial selections, because a whole-element selection is the easy case and the range's+#: boundaries are exactly what the alt-text insertion could disturb.+PARTIALS = """+ const v = document.getElementById('v');+ const walk = document.createTreeWalker(v, NodeFilter.SHOW_TEXT);+ const texts = []; let n; while ((n = walk.nextNode())) texts.push(n);+ const out = [];+ if (texts.length) {+ const mk = (a, ao, b, bo) => { const r = document.createRange();+ r.setStart(a, ao); r.setEnd(b, bo); return r; };+ out.push(mk(texts[0], Math.min(2, texts[0].length), texts[texts.length-1],+ Math.max(0, texts[texts.length-1].length - 2)));+ if (texts.length > 1) out.push(mk(texts[0], 0, texts[1], texts[1].length));+ out.push(mk(texts[texts.length-1], 0, texts[texts.length-1], texts[texts.length-1].length));+ }+ window.__ranges = out;+"""++UNMAPPED = "unmapped-engine"+FORM_CONTROL = "form-control"+++def build_module() -> str:+ """The shipped TypeScript, compiled to an IIFE bundle, as source text."""+ if not (FRONTEND / "node_modules").is_dir():+ raise MissingPrerequisite(+ f"{FRONTEND.relative_to(REPO)}/node_modules is missing; "+ f"run `cd {FRONTEND.relative_to(REPO)} && npm ci` first"+ )+ with tempfile.TemporaryDirectory(prefix = "fastcopy-bundle") as out:+ done = subprocess.run(+ ["node", str(BUNDLER.relative_to(FRONTEND)), out],+ cwd = FRONTEND,+ capture_output = True,+ text = True,+ )+ built = Path(out) / "fastcopy.js"+ if done.returncode != 0 or not built.is_file():+ raise RuntimeError(+ f"building {BUNDLER.name} failed ({done.returncode}):\n"+ f"{done.stdout}\n{done.stderr}"+ )+ return built.read_text(encoding = "utf-8")+++def launch(playwright, engine: str):+ """The browser, or a MissingPrerequisite if its executable was never downloaded."""+ args = {"args": ["--no-sandbox"]} if engine == "chromium" else {}+ try:+ return getattr(playwright, engine).launch(**args)+ except Exception as error: # noqa: BLE001 - playwright raises its own Error type+ text = str(error)+ if "Executable doesn't exist" in text or "playwright install" in text:+ raise MissingPrerequisite(+ f"the {engine} browser is not installed; "+ f"run `python3 -m playwright install {engine}`"+ ) from error+ raise+++def prime_clipboard(page, sentinel: str) -> None:+ """Put a known string on the clipboard, so a copy that writes nothing is visible as such.++ Without it, a selection the engine considers empty leaves the clipboard untouched and the+ paste below reports the PREVIOUS construct's result as this one's.+ """+ page.evaluate(+ "(s) => { const t = document.getElementById('sink');"+ " t.value = s; t.focus(); t.select(); document.execCommand('copy');"+ " t.value = ''; }",+ sentinel,+ )+++def read_clipboard(page, sentinel: str, restore: str) -> str | None:+ """What the engine's own copy of this selection puts on the clipboard, or None for nothing."""+ page.evaluate(f"() => {{ {restore} }}")+ page.evaluate("() => document.execCommand('copy')")+ page.click("#sink")+ page.keyboard.press("ControlOrMeta+v")+ got = page.evaluate("() => document.getElementById('sink').value")+ page.evaluate("() => document.getElementById('sink').value = ''")+ return None if got == sentinel else got+++def compare(engine: str, label: str, verdict: dict, native: str) -> list[str]:+ """One answered-or-refused verdict against one real clipboard string."""+ if verdict["text"] is None:+ if verdict["reason"] == UNMAPPED:+ return []+ return [f"{engine}/{label}: refused ({verdict['reason']}) with no divergence"]+ if verdict["text"] != native:+ return [+ f"{engine}/{label}: MISMATCH\n"+ f" native {native!r}\n ours {verdict['text']!r}"+ ]+ return []+++#: The floor on how many selections a run has to actually reach a verdict on. A comparison is+#: skipped when the engine copied nothing at all, and a driver that skipped every one of them+#: would print CLEAN having proven nothing -- which is the failure mode this whole file exists to+#: rule out for the unit tests.+EXPECTED_VERDICTS = len(CONSTRUCTS) - len(MUST_REFUSE) - len(NO_COPY)+++class Tally:+ """What a run reached a verdict on, so an empty run cannot read as a clean one."""++ def __init__(self) -> None:+ self.problems: list[str] = []+ #: Answered, and compared byte for byte against the real clipboard.+ self.compared = 0+ #: Refused because this engine's clipboard mapping is not one the module has proven.+ self.refused = 0+ #: Of those, how many really do differ from the engine's own `toString()`.+ self.diverged = 0++ def record(self, engine: str, label: str, verdict: dict, native: str) -> None:+ if verdict["reason"] == UNMAPPED:+ self.refused += 1+ return+ self.compared += 1+ self.problems += compare(engine, label, verdict, native)+++def check(engine: str, candidate: str) -> Tally:+ """Every claim in the module docstring, driven against one real engine."""+ tally = Tally()+ problems = tally.problems+ with sync_playwright() as playwright:+ browser = launch(playwright, engine)+ page = browser.new_page()++ for index, (name, body) in enumerate(CONSTRUCTS.items()):+ page.set_content(PAGE.replace("__BODY__", body))+ page.add_script_tag(content = candidate)+ sentinel = f"__s{index}__"+ page.evaluate(f"() => {{ {SELECT_ALL} }}")+ # THE SERIALISED DOM, not the computed style. The unit test asserted the computed+ # value came back and passed while every copy was leaving `style=""` behind, because+ # `removeAttribute` does not remove a style attribute whose declaration has been+ # touched. The structural parity digest caught it; this keeps it caught.+ dom_before = page.evaluate("() => document.getElementById('v').outerHTML")+ verdict = page.evaluate("() => window.__fastCopy()")+ dom_after = page.evaluate("() => document.getElementById('v').outerHTML")+ if dom_before != dom_after:+ problems.append(+ f"{engine}/{name}: the serialised DOM changed, "+ f"{len(dom_before)} chars -> {len(dom_after)}"+ )+ after = page.evaluate("() => window.getSelection().toString()")+ page.evaluate(f"() => {{ {SELECT_ALL} }}")+ before = page.evaluate("() => window.getSelection().toString()")+ if after != before:+ problems.append(f"{engine}/{name}: the serialiser did not restore the selection")++ # Both engines' clipboards fold a no-break space to a plain one and neither+ # `toString()` does, so that difference is not evidence of a divergence.+ raw = before.replace("\u00a0", " ")+ prime_clipboard(page, sentinel)+ native = read_clipboard(page, sentinel, SELECT_ALL)++ if name in MUST_REFUSE:+ # Not merely "did not answer": the gate has to refuse for the stated reason, or+ # a form control could be passing only because the engine was unmapped.+ if verdict["text"] is not None:+ problems.append(f"{engine}/{name}: ANSWERED a construct measured as divergent")+ elif verdict["reason"] not in (FORM_CONTROL, UNMAPPED):+ problems.append(+ f"{engine}/{name}: refused as {verdict['reason']!r}, "+ f"not as a form control"+ )+ continue+ if name in NO_COPY or native is None:+ continue+ # An engine-wide refusal is only honest if this engine's clipboard really does+ # disagree with its own `toString()`. Counted here, and asserted non-zero below.+ if verdict["reason"] == UNMAPPED and native != raw:+ tally.diverged += 1+ tally.record(engine, name, verdict, native)++ # ---- ENDPOINTS EXPRESSED AS ELEMENT/CHILD OFFSETS ----+ # The alt holders are inserted BEFORE their images, so a child offset in the same parent+ # points at a different child afterwards. Restoring from raw offsets silently dropped the+ # trailing text: the clipboard carried `first catsecond cattail text` and we produced+ # `first catsecond cat`, then took the copy because the result was non-empty.+ for label, selection_js in (+ ("element offsets forward", "s.setBaseAndExtent(p, 0, p, 3)"),+ ("element offsets backward", "s.setBaseAndExtent(p, 3, p, 0)"),+ ):+ page.set_content(+ PAGE.replace("__BODY__", f'<p id="ep">{IMG_TAG}{IMG_TAG}tail text</p>')+ )+ page.add_script_tag(content = candidate)+ restore = (+ "const p = document.getElementById('ep');"+ " const s = window.getSelection(); " + selection_js + ";"+ )+ sentinel = f"__ep_{label.replace(' ', '_')}__"+ page.evaluate(f"() => {{ {restore} }}")+ verdict = page.evaluate("() => window.__fastCopy()")+ prime_clipboard(page, sentinel)+ native = read_clipboard(page, sentinel, restore)+ if native is None:+ continue+ tally.record(engine, label, verdict, native)++ # ---- A BACKWARD SELECTION MUST COME BACK BACKWARD ----+ # A cloned Range carries ordered boundaries and no direction, so rebuilding with+ # `addRange` silently turns a selection dragged upwards into a forward one and the user's+ # next Shift+Arrow moves the opposite edge. Only the patched path rebuilds, so the+ # fixture needs an image in it.+ page.set_content(+ PAGE.replace(+ "__BODY__",+ '<p id="pa">first paragraph</p><p id="pb">second ' + IMG_TAG + " paragraph</p>",+ )+ )+ page.add_script_tag(content = candidate)+ page.evaluate("""() => {+ const a = document.getElementById('pa').firstChild;+ const b = document.getElementById('pb').firstChild;+ window.getSelection().setBaseAndExtent(b, b.length, a, 0);+ // The engine probe caches its answer on the window, and `set_content` does not replace+ // the window, so by here it has already run against some earlier construct. Clearing it+ // makes THIS selection the one the probe takes away and rebuilds -- which is a second+ // place the direction can be lost, and the only one a user meets on their first copy.+ delete window.__sbFastCopyMapped;+ }""")+ backward = page.evaluate("() => window.__fastCopy()")+ still = page.evaluate("""() => {+ const a = document.getElementById('pa').firstChild;+ return window.getSelection().focusNode === a;+ }""")+ if backward["reason"] != UNMAPPED and not still:+ problems.append(+ f"{engine}/backward selection: came back forward; the anchor and focus were "+ "swapped, so the user's next Shift+Arrow would move the opposite edge"+ )++ # ---- selections whose SCOPE is the diverging element itself ----+ for name, (body, target) in INSIDE_SCOPE.items():+ page.set_content(PAGE.replace("__BODY__", body))+ page.add_script_tag(content = candidate)+ restore = f"window.getSelection().selectAllChildren({target})"+ sentinel = f"__inside_{name.replace(' ', '_')}__"+ page.evaluate(f"() => {{ {restore} }}")+ verdict = page.evaluate("() => window.__fastCopy()")+ prime_clipboard(page, sentinel)+ native = read_clipboard(page, sentinel, restore)+ if native is None:+ continue+ tally.record(engine, name, verdict, native)++ # ---- partial selections over the whole hostile document at once ----+ safe = "".join(+ body+ for name, body in CONSTRUCTS.items()+ if name not in MUST_REFUSE and name not in NO_COPY+ )+ page.set_content(PAGE.replace("__BODY__", safe))+ page.add_script_tag(content = candidate)+ page.evaluate(f"() => {{ {PARTIALS} }}")+ for index in range(page.evaluate("() => window.__ranges.length")):+ restore = (+ "const s = window.getSelection(); s.removeAllRanges();"+ f" s.addRange(window.__ranges[{index}]);"+ )+ sentinel = f"__partial{index}__"+ page.evaluate(f"() => {{ {restore} }}")+ verdict = page.evaluate("() => window.__fastCopy()")+ prime_clipboard(page, sentinel)+ native = read_clipboard(page, sentinel, restore)+ if native is None:+ continue+ tally.record(engine, f"partial{index}", verdict, native)++ browser.close()++ if tally.refused and not tally.diverged:+ problems.append(+ f"{engine}: refused as an unmapped engine, but not one construct's clipboard "+ f"differs from its own toString() here, so the refusal is unjustified"+ )+ if tally.compared + tally.refused < EXPECTED_VERDICTS:+ problems.append(+ f"{engine}: only {tally.compared + tally.refused} selections reached a verdict, "+ f"under the {EXPECTED_VERDICTS} this document contains. The run proved nothing; "+ f"the fixture or the clipboard round trip is broken, not the module."+ )+ return tally+++def main() -> int:+ parser = argparse.ArgumentParser(description = __doc__)+ parser.add_argument(+ "engines",+ nargs = "*",+ default = ["chromium", "webkit"],+ help = "browser engines to drive (default: chromium webkit)",+ )+ engines = parser.parse_args().engines++ try:+ candidate = build_module() + SHIM+ except MissingPrerequisite as error:+ print(f"SKIP: {error}")+ return 0+ except RuntimeError as error:+ print(f"HARNESS FAILURE: {error}")+ return 2++ problems: list[str] = []+ ran = 0+ for engine in engines:+ try:+ tally = check(engine, candidate)+ except MissingPrerequisite as error:+ print(f"=== {engine}: SKIP, {error}")+ continue+ ran += 1+ problems += tally.problems+ outcome = "CLEAN" if not tally.problems else f"{len(tally.problems)} problem(s)"+ tail = f", {tally.compared} selections matched the clipboard byte for byte"+ if tally.refused:+ tail += (+ f", {tally.refused} refused as an unmapped engine "+ f"({tally.diverged} of them measurably divergent)"+ )+ print(f"=== {engine}: {outcome}{tail}")+ for problem in tally.problems:+ print(" " + problem)+ if not ran:+ print("SKIP: no engine could be launched; nothing was proven")+ return 1 if problems else 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/tests/studio/test_playwright_suites_run_in_ci.py b/tests/studio/test_playwright_suites_run_in_ci.pyindex 0b5093d99fe..9234f964c2a 100644--- a/tests/studio/test_playwright_suites_run_in_ci.py+++ b/tests/studio/test_playwright_suites_run_in_ci.py@@ -50,6 +50,16 @@ NOT_IN_CI = {# the unmeasured primitive, is covered without a browser by# studio/frontend/tests/reasoning-grid-collapse.test.ts, which CI does run."playwright_collapse_layout.py",+ # Half of what it asserts is about the engine Frontend CI does not install. It proves the+ # thread's fast copy path byte for byte against the real clipboard on BOTH engines: Chromium+ # answers and must match, WebKit must refuse and its refusal must be backed by a measured+ # divergence. That job installs Chromium only, so a Chromium-only run would assert the easy+ # half and silently drop the reason the fast path is engine-gated at all. It also needs a+ # vite library build of the module, which no other smoke there does. Run by hand when the+ # serialiser changes. What CI does run is studio/frontend/tests/thread-fast-copy.test.ts,+ # which pins the gate's branches and the patch's bookkeeping but, by its own docstring,+ # cannot see how a real engine serialises anything.+ "playwright_thread_fast_copy.py",}