Skip to content

The agent that grows with you

fix(desktop): strip off-scheme paint from selection copies

SHL0MS3cc7f220cdd2
diff --git a/apps/desktop/src/lib/selection-copy-colors.test.ts b/apps/desktop/src/lib/selection-copy-colors.test.ts
new file mode 100644
index 00000000000..54e3d4f3f1e
--- /dev/null
+++ b/apps/desktop/src/lib/selection-copy-colors.test.ts
@@ -0,0 +1,301 @@
+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
+
+import {
+ installSelectionCopyColorGuard,
+ selectionInkLuma,
+ serializeSelectionStructure,
+ textColorLuma
+} from './selection-copy-colors'
+
+function makeCopyEvent(): { event: ClipboardEvent; setData: ReturnType<typeof vi.fn>; preventDefault: ReturnType<typeof vi.fn> } {
+ const event = new Event('copy', { bubbles: true, cancelable: true }) as ClipboardEvent
+ const setData = vi.fn()
+ const preventDefault = vi.fn()
+
+ Object.defineProperty(event, 'clipboardData', { value: { setData } })
+ Object.defineProperty(event, 'preventDefault', { value: preventDefault })
+
+ return { event, setData, preventDefault }
+}
+
+/** Stage styled text and arm a real DOM selection over it. */
+function armSelection(html: string): HTMLDivElement {
+ const host = document.createElement('div')
+
+ host.innerHTML = html
+ document.body.append(host)
+
+ const range = document.createRange()
+
+ range.selectNodeContents(host)
+
+ const sel = window.getSelection()
+
+ sel?.removeAllRanges()
+ sel?.addRange(range)
+
+ return host
+}
+
+describe('textColorLuma', () => {
+ it('scores white near the top of the range', () => {
+ expect(textColorLuma('rgb(255, 255, 255)')).toBeGreaterThan(240)
+ })
+
+ it('scores black near the bottom of the range', () => {
+ expect(textColorLuma('rgb(10, 10, 10)')).toBeLessThan(20)
+ })
+
+ it('composites partial alpha over mid-gray', () => {
+ // White at 50% alpha lands halfway between white and gray.
+ const halfWhite = textColorLuma('rgba(255, 255, 255, 0.5)')
+
+ expect(halfWhite).not.toBeNull()
+ expect(halfWhite!).toBeGreaterThan(185)
+ expect(halfWhite!).toBeLessThan(200)
+ })
+
+ it('treats fully transparent paint as invisible', () => {
+ expect(textColorLuma('rgba(255, 255, 255, 0)')).toBeNull()
+ expect(textColorLuma('rgba(255, 255, 255, 0.03)')).toBeNull()
+ })
+
+ it('returns null for unparsable colors', () => {
+ expect(textColorLuma('var(--foreground)')).toBeNull()
+ expect(textColorLuma('inherit')).toBeNull()
+ expect(textColorLuma('')).toBeNull()
+ })
+
+ it('parses the color(srgb …) computed form Chromium serializes', () => {
+ // The app's dark-theme ink: color-mix(in srgb, #e6edf3 94%, transparent)
+ // computes to exactly this serialization.
+ const luma = textColorLuma('color(srgb 0.901961 0.929412 0.952941 / 0.94)')
+
+ expect(luma).not.toBeNull()
+ expect(luma!).toBeGreaterThan(220)
+ })
+
+ it('parses color(srgb …) with percentage components and alpha', () => {
+ const luma = textColorLuma('color(srgb 100% 100% 100% / 50%)')
+
+ expect(luma).not.toBeNull()
+ expect(luma!).toBeCloseTo(191.5, 0)
+ })
+
+ it('parses hex colors including alpha', () => {
+ expect(textColorLuma('#ffffff')).toBeGreaterThan(240)
+ expect(textColorLuma('#111111')).toBeLessThan(20)
+ expect(textColorLuma('#ffffff80')).not.toBeNull()
+ })
+})
+
+describe('selectionInkLuma', () => {
+ afterEach(() => {
+ window.getSelection()?.removeAllRanges()
+ })
+
+ it('scores the live computed ink of the selected text', () => {
+ const host = armSelection('<p style="color: rgb(230, 237, 243)">bright transcript ink</p>')
+ const luma = selectionInkLuma(window.getSelection()!, document)
+
+ expect(luma).not.toBeNull()
+ expect(luma!).toBeGreaterThan(220)
+
+ host.remove()
+ })
+
+ it('scores dark ink as dark', () => {
+ const host = armSelection('<p style="color: rgb(17, 17, 17)">dim transcript ink</p>')
+ const luma = selectionInkLuma(window.getSelection()!, document)
+
+ expect(luma).not.toBeNull()
+ expect(luma!).toBeLessThan(20)
+
+ host.remove()
+ })
+
+ it('returns null for a collapsed selection', () => {
+ const host = armSelection('<p style="color: rgb(255, 255, 255)">text</p>')
+
+ window.getSelection()?.collapseToEnd()
+
+ expect(selectionInkLuma(window.getSelection()!, document)).toBeNull()
+
+ host.remove()
+ })
+})
+
+describe('serializeSelectionStructure', () => {
+ afterEach(() => {
+ window.getSelection()?.removeAllRanges()
+ })
+
+ it('keeps semantic structure and hrefs while dropping paint and classes', () => {
+ const host = armSelection(
+ '<p class="aui-md" style="color: rgb(230, 237, 243)">see <a href="https://example.com">the doc</a> and <strong>this</strong></p>'
+ )
+
+ const html = serializeSelectionStructure(window.getSelection()!, document)
+
+ expect(html).toContain('<strong>this</strong>')
+ expect(html).toContain('href="https://example.com"')
+ expect(html).toContain('the doc')
+ // The only style attribute allowed is the wrapper's generic font anchor.
+ expect(html.replace('<div style="font-family: sans-serif;">', '')).not.toContain('style=')
+ expect(html).not.toContain('class=')
+ expect(html).not.toContain('rgb(230, 237, 243)')
+
+ host.remove()
+ })
+
+ it('keeps list and code structure', () => {
+ const host = armSelection('<ul><li>alpha</li><li><em>beta</em></li></ul><pre>code line</pre>')
+ const html = serializeSelectionStructure(window.getSelection()!, document)
+
+ expect(html).toContain('<li>alpha</li>')
+ expect(html).toContain('<em>beta</em>')
+ expect(html).toContain('code line')
+
+ host.remove()
+ })
+
+ it('anchors a generic sans family so rich-text receivers keep their own font', () => {
+ const host = armSelection('<p style="color: rgb(230, 237, 243); font-family: -apple-system, sans-serif">plain prose</p>')
+ const html = serializeSelectionStructure(window.getSelection()!, document)
+
+ // Generic family on the wrapper: resolves to each platform's own face,
+ // never the Times browser default, and carries no vendor font names.
+ expect(html).toContain('sans-serif')
+ expect(html).not.toContain('-apple-system')
+ expect(html).not.toContain('color')
+
+ host.remove()
+ })
+
+ it('pins monospace inside code elements', () => {
+ const host = armSelection('<pre><code>npm run build</code></pre>')
+ const html = serializeSelectionStructure(window.getSelection()!, document)
+
+ expect(html).toContain('monospace')
+
+ host.remove()
+ })
+})
+
+describe('installSelectionCopyColorGuard', () => {
+ beforeEach(() => {
+ document.documentElement.dataset.hermesMode = 'dark'
+ })
+
+ afterEach(() => {
+ delete document.documentElement.dataset.hermesMode
+ window.getSelection()?.removeAllRanges()
+ })
+
+ it('owns the payload when a light-ink selection is copied under a dark theme', () => {
+ const dispose = installSelectionCopyColorGuard(document)
+ const host = armSelection('<p style="color: rgb(230, 237, 243)">bright transcript ink</p>')
+
+ try {
+ const { event, setData, preventDefault } = makeCopyEvent()
+
+ document.body.dispatchEvent(event)
+
+ expect(preventDefault).toHaveBeenCalled()
+
+ const plainCall = setData.mock.calls.find(([type]) => type === 'text/plain')
+ const htmlCall = setData.mock.calls.find(([type]) => type === 'text/html')
+
+ expect(plainCall?.[1]).toContain('bright transcript ink')
+ expect(htmlCall?.[1]).toContain('bright transcript ink')
+ expect(htmlCall?.[1]).not.toContain('rgb(230, 237, 243)')
+ } finally {
+ dispose()
+ host.remove()
+ }
+ })
+
+ it('leaves dark-ink selections to Chromium under a dark theme', () => {
+ const dispose = installSelectionCopyColorGuard(document)
+ const host = armSelection('<p style="color: rgb(17, 17, 17)">dim transcript ink</p>')
+
+ try {
+ const { event, setData, preventDefault } = makeCopyEvent()
+
+ document.body.dispatchEvent(event)
+
+ expect(preventDefault).not.toHaveBeenCalled()
+ expect(setData).not.toHaveBeenCalled()
+ } finally {
+ dispose()
+ host.remove()
+ }
+ })
+
+ it('leaves light-ink selections alone when the theme is light', () => {
+ document.documentElement.dataset.hermesMode = 'light'
+
+ const dispose = installSelectionCopyColorGuard(document)
+ const host = armSelection('<p style="color: rgb(230, 237, 243)">bright transcript ink</p>')
+
+ try {
+ const { event, setData, preventDefault } = makeCopyEvent()
+
+ document.body.dispatchEvent(event)
+
+ expect(preventDefault).not.toHaveBeenCalled()
+ expect(setData).not.toHaveBeenCalled()
+ } finally {
+ dispose()
+ host.remove()
+ }
+ })
+
+ it('skips selections that start inside an editable field', () => {
+ const dispose = installSelectionCopyColorGuard(document)
+ const host = document.createElement('div')
+
+ host.setAttribute('contenteditable', 'true')
+ host.innerHTML = '<span style="color: rgb(230, 237, 243)">composer text</span>'
+ document.body.append(host)
+
+ const range = document.createRange()
+
+ range.selectNodeContents(host)
+
+ const sel = window.getSelection()
+
+ sel?.removeAllRanges()
+ sel?.addRange(range)
+
+ try {
+ const { event, setData, preventDefault } = makeCopyEvent()
+
+ document.body.dispatchEvent(event)
+
+ expect(preventDefault).not.toHaveBeenCalled()
+ expect(setData).not.toHaveBeenCalled()
+ } finally {
+ dispose()
+ host.remove()
+ }
+ })
+
+ it('stops intercepting after disposal', () => {
+ const dispose = installSelectionCopyColorGuard(document)
+ const host = armSelection('<p style="color: rgb(230, 237, 243)">bright transcript ink</p>')
+
+ dispose()
+
+ try {
+ const { event, setData, preventDefault } = makeCopyEvent()
+
+ document.body.dispatchEvent(event)
+
+ expect(preventDefault).not.toHaveBeenCalled()
+ expect(setData).not.toHaveBeenCalled()
+ } finally {
+ host.remove()
+ }
+ })
+})
diff --git a/apps/desktop/src/lib/selection-copy-colors.ts b/apps/desktop/src/lib/selection-copy-colors.ts
new file mode 100644
index 00000000000..de9d63b9a46
--- /dev/null
+++ b/apps/desktop/src/lib/selection-copy-colors.ts
@@ -0,0 +1,329 @@
+// Chromium's native selection copy (Cmd+C, right-click Copy) serializes the
+// selection as `text/html` with every element's COMPUTED paint inlined as
+// style attributes. Copied from a dark theme, body text lands on the
+// clipboard near-white; pasted into a light-background target (an email, a
+// shared doc) it is invisible.
+//
+// The serializer only runs AFTER `copy` handlers decline to intercept —
+// inside the handler, `clipboardData` reads back empty — so the guard cannot
+// inspect or patch Chromium's payload. Instead it decides from the LIVE DOM:
+// it scores the ink that paints the current selection against the theme
+// Hermes is rendering, and when the two are opposite schemes it takes over
+// the clipboard write entirely, emitting `text/plain` plus a tag-structured
+// `text/html` with no paint declarations. Structure — headings, lists,
+// tables, links, bold/italic, code layout — survives; colors come from the
+// paste target's own defaults. Same-scheme selections are left to Chromium's
+// default copy untouched.
+
+type RenderedMode = 'light' | 'dark'
+
+/** At or above this perceived luma, text reads as "light" (dark-theme ink). */
+const LIGHT_TEXT_LUMA_MIN = 150
+/** At or below this perceived luma, text reads as "dark" (light-theme ink). */
+const DARK_TEXT_LUMA_MAX = 105
+
+/** Upper bound on text nodes probed per copy; long selections stay O(50). */
+const MAX_PROBE_NODES = 50
+
+const RGB_FN_RE = /rgba?\(\s*([\d.]+)\s*[,\s]\s*([\d.]+)\s*[,\s]\s*([\d.]+)\s*(?:[/,]\s*([\d.%]+)\s*)?\)/i
+const SRGB_FN_RE = /^color\(\s*srgb\s+([\d.]+%?)\s+([\d.]+%?)\s+([\d.]+%?)(?:\s*[/\s]+\s*([\d.%]+))?\s*\)$/i
+const HEX_RE = /^#([0-9a-f]{3,4}|[0-9a-f]{6}|[0-9a-f]{8})$/i
+
+/** Parse one component: percentage or 0–255 integer. */
+const channelValue = (raw: string): number => {
+ const v = raw.trim()
+
+ return v.endsWith('%') ? (Number.parseFloat(v) / 100) * 255 : Number.parseFloat(v)
+}
+
+/** color(srgb …) components are 0–1 floats (or percentages), not 0–255. */
+const srgbChannelValue = (raw: string): number => {
+ const v = raw.trim()
+
+ return v.endsWith('%') ? (Number.parseFloat(v) / 100) * 255 : Number.parseFloat(v) * 255
+}
+
+const alphaValue = (raw: string): number =>
+ raw.endsWith('%') ? Number.parseFloat(raw) / 100 : Number.parseFloat(raw)
+
+function expandHex(hex: string): [number, number, number, number] | null {
+ const h = hex.slice(1)
+ const wide = h.length >= 6
+
+ const pick = (i: number) => Number.parseInt(wide ? h.slice(i, i + 2) : h[i]! + h[i]!, 16)
+
+ const r = pick(0)
+ const g = pick(1 * (wide ? 2 : 1))
+ const b = pick(2 * (wide ? 2 : 1))
+
+ if ([r, g, b].some(Number.isNaN)) {
+ return null
+ }
+
+ const aRaw = wide ? h.slice(6, 8) : h[3]
+
+ return [r, g, b, aRaw ? Number.parseInt(aRaw, 16) / 255 : 1]
+}
+
+function parseCssColor(cssColor: string): { r: number; g: number; b: number; alpha: number } | null {
+ const value = cssColor.trim()
+
+ const rgb = value.match(RGB_FN_RE)
+
+ if (rgb) {
+ return {
+ r: Number(rgb[1]),
+ g: Number(rgb[2]),
+ b: Number(rgb[3]),
+ alpha: rgb[4] ? alphaValue(rgb[4]) : 1
+ }
+ }
+
+ const srgb = value.match(SRGB_FN_RE)
+
+ if (srgb) {
+ return {
+ r: srgbChannelValue(srgb[1] ?? ''),
+ g: srgbChannelValue(srgb[2] ?? ''),
+ b: srgbChannelValue(srgb[3] ?? ''),
+ alpha: srgb[4] ? alphaValue(srgb[4]) : 1
+ }
+ }
+
+ if (HEX_RE.test(value)) {
+ const expanded = expandHex(value)
+
+ if (expanded) {
+ return { r: expanded[0], g: expanded[1], b: expanded[2], alpha: expanded[3] }
+ }
+ }
+
+ return null
+}
+
+/**
+ * Perceived luma (0–255, ITU-R BT.601 weighting) of a CSS color, with alpha
+ * composited over mid-gray so partial opacity neither overstates nor hides
+ * the paint. Accepts the serialization forms Chromium computes for the app's
+ * tokens: rgb()/rgba(), color(srgb …) (the computed form of modern functions
+ * like color-mix()), and hex. Returns null for anything else (keywords,
+ * variables, non-sRGB spaces) or effectively invisible paint (alpha ≤ 0.05).
+ */
+export function textColorLuma(cssColor: string): number | null {
+ const parsed = parseCssColor(cssColor)
+
+ if (!parsed || parsed.alpha <= 0.05) {
+ return null
+ }
+
+ const composite = (channel: number) => channel * parsed.alpha + 128 * (1 - parsed.alpha)
+
+ return 0.2126 * composite(parsed.r) + 0.7152 * composite(parsed.g) + 0.0722 * composite(parsed.b)
+}
+
+function isOppositeScheme(textLuma: number, mode: RenderedMode): boolean {
+ return mode === 'dark' ? textLuma >= LIGHT_TEXT_LUMA_MIN : textLuma <= DARK_TEXT_LUMA_MAX
+}
+
+function renderedMode(doc: Document): RenderedMode {
+ const attr = doc.documentElement.dataset.hermesMode
+
+ if (attr === 'light' || attr === 'dark') {
+ return attr
+ }
+
+ // Boot frame or a host that skipped theme application: fall back to the OS
+ // preference, which is what `system` mode resolves to anyway.
+ try {
+ return doc.defaultView?.matchMedia('(prefers-color-scheme: dark)').matches ? 'dark' : 'light'
+ } catch {
+ return 'light'
+ }
+}
+
+function rangeContainsNode(range: Range, node: Node): boolean {
+ try {
+ return range.intersectsNode(node)
+ } catch {
+ // Environments without intersectsNode: fall back to a boundary compare.
+ try {
+ range.comparePoint(node, 0)
+
+ return true
+ } catch {
+ return false
+ }
+ }
+}
+
+/**
+ * Mean perceived luma of the ink that paints the current selection, read
+ * from the LIVE DOM: the computed color (preferring -webkit-text-fill-color
+ * when set) of each selected text node's parent. Returns null when the
+ * selection holds no scoreable ink.
+ */
+export function selectionInkLuma(sel: Selection, doc: Document): number | null {
+ const view = doc.defaultView
+
+ if (!view) {
+ return null
+ }
+
+ const lumas: number[] = []
+ const seen = new Set<Element>()
+
+ for (let i = 0; i < sel.rangeCount && lumas.length < MAX_PROBE_NODES; i++) {
+ const range = sel.getRangeAt(i)
+ const root = range.commonAncestorContainer
+ const walker = doc.createTreeWalker(root.nodeType === 1 ? root : root.parentElement ?? doc.body, NodeFilter.SHOW_TEXT)
+
+ let node = walker.nextNode()
+
+ while (node && lumas.length < MAX_PROBE_NODES) {
+ if (rangeContainsNode(range, node)) {
+ const el = node.parentElement
+
+ if (el && !seen.has(el)) {
+ seen.add(el)
+
+ const style = view.getComputedStyle(el)
+ const fill = style.getPropertyValue('-webkit-text-fill-color')
+ const ink = textColorLuma(fill) ?? textColorLuma(style.color)
+
+ if (ink !== null) {
+ lumas.push(ink)
+ }
+ }
+ }
+
+ node = walker.nextNode()
+ }
+ }
+
+ if (lumas.length === 0) {
+ return null
+ }
+
+ return lumas.reduce((sum, l) => sum + l, 0) / lumas.length
+}
+
+/**
+ * Serialize the selection as tag-structured HTML with no paint and no
+ * app-internal attributes: semantic elements (p, strong, em, a, ul, pre,
+ * table, …) survive with their content and hrefs; style/class attributes —
+ * the only carriers of Hermes' palette — are dropped so the paste target's
+ * own color defaults apply.
+ *
+ * One exception to the strip-everything rule: the result carries a GENERIC
+ * font-family (`sans-serif`, `monospace` inside code). With no family at
+ * all, receivers that convert HTML to rich text (macOS Mail, Notes,
+ * TextEdit) fall back to the BROWSER default — Times — instead of their own
+ * compose font. Naming the generic family keeps the paste sans like the app
+ * renders it, while each platform resolves it to its own system face.
+ */
+export function serializeSelectionStructure(sel: Selection, doc: Document): string {
+ const container = doc.createElement('div')
+
+ for (let i = 0; i < sel.rangeCount; i++) {
+ container.append(sel.getRangeAt(i).cloneContents())
+ }
+
+ for (const el of container.querySelectorAll('[style]')) {
+ el.removeAttribute('style')
+ }
+
+ for (const el of container.querySelectorAll('[class]')) {
+ el.removeAttribute('class')
+ }
+
+ const wrapper = doc.createElement('div')
+
+ wrapper.style.fontFamily = 'sans-serif'
+
+ while (container.firstChild) {
+ wrapper.append(container.firstChild)
+ }
+
+ for (const el of wrapper.querySelectorAll<HTMLElement>('pre, code')) {
+ el.style.fontFamily = 'monospace'
+ }
+
+ // outerHTML, not innerHTML: the styled wrapper IS the font anchor.
+ return wrapper.outerHTML
+}
+
+function selectionStartsInEditable(sel: Selection): boolean {
+ const anchor = sel.anchorNode
+
+ if (!anchor) {
+ return false
+ }
+
+ const el = anchor.nodeType === 1 ? (anchor as Element) : anchor.parentElement
+
+ return Boolean(el?.closest('input, textarea, [contenteditable="true"], [contenteditable=""]'))
+}
+
+/**
+ * Install the document-level `copy` interceptor. Returns a dispose function.
+ *
+ * Runs in the CAPTURE phase so inner handlers cannot run first. Only an
+ * off-scheme selection is intercepted (payload owned and rewritten); every
+ * other copy — same-scheme, editable-field, empty — passes through to
+ * Chromium's default untouched.
+ */
+export function installSelectionCopyColorGuard(doc: Document = document): () => void {
+ const trace = (entry: Record<string, unknown>) => {
+ if (import.meta.env.DEV) {
+ const view = doc.defaultView as (Window & { __copyGuardLog?: unknown[] }) | null
+
+ if (view) {
+ ;(view.__copyGuardLog ??= []).push(entry)
+ }
+ }
+ }
+
+ const onCopy = (event: ClipboardEvent) => {
+ const sel = doc.getSelection()
+
+ if (!sel || sel.isCollapsed || sel.rangeCount === 0) {
+ return
+ }
+
+ if (selectionStartsInEditable(sel)) {
+ trace({ step: 'editable-skip' })
+
+ return
+ }
+
+ const mode = renderedMode(doc)
+ const inkLuma = selectionInkLuma(sel, doc)
+
+ if (inkLuma === null || !isOppositeScheme(inkLuma, mode)) {
+ trace({ step: inkLuma === null ? 'no-ink' : 'same-scheme', inkLuma, mode })
+
+ return
+ }
+
+ const clipboard = event.clipboardData
+
+ if (!clipboard) {
+ return
+ }
+
+ const plain = sel.toString()
+ const html = serializeSelectionStructure(sel, doc)
+
+ // Owning the payload is the only way to change it: Chromium's own
+ // serialization is produced after handlers decline, and preventDefault
+ // is required for setData writes to stick.
+ event.preventDefault()
+ clipboard.setData('text/plain', plain)
+ clipboard.setData('text/html', html)
+ trace({ step: 'owned-payload', mode, inkLuma, plainChars: plain.length, htmlChars: html.length })
+ }
+
+ doc.addEventListener('copy', onCopy, true)
+
+ return () => doc.removeEventListener('copy', onCopy, true)
+}
diff --git a/apps/desktop/src/main.tsx b/apps/desktop/src/main.tsx
index 39e21ce7434..3c2a116a6b7 100644
--- a/apps/desktop/src/main.tsx
+++ b/apps/desktop/src/main.tsx
@@ -26,9 +26,14 @@ import { I18nProvider } from './i18n'
import { installClipboardShim } from './lib/clipboard'
import { queryClient } from './lib/query-client'
import { installRendererAnimationPauseState } from './lib/renderer-loop-pause'
+import { installSelectionCopyColorGuard } from './lib/selection-copy-colors'
import { ThemeProvider } from './themes/context'
installClipboardShim()
+// Chromium serializes selection copies (Cmd+C, right-click Copy) with the
+// theme's computed colors inlined; without this guard a dark-theme selection
+// pastes as near-white text into light-background targets.
+installSelectionCopyColorGuard()
// The perf probe ships in dev, and in a production build ONLY when explicitly
// opted in (VITE_PERF_PROBE=1) — this lets the perf harness measure a real,