Skip to content

Claude's answers, rendered: Markdown, math, charts and diagrams drawn in the Claude Code terminal. Independent project, not affiliated with Anthropic.

TypeScript claude-code-mod

Copy: the newest copy wins; a password manager's copy is never read

razorback16be317e343ad2
diff --git a/hooks/lib/clipboard.ts b/hooks/lib/clipboard.ts
index 1733cef..2129146 100644
--- a/hooks/lib/clipboard.ts
+++ b/hooks/lib/clipboard.ts
@@ -1,10 +1,11 @@
// The clipboard of this computer: how a copy reads it and how its changes
-// are seen. macOS: pbpaste, and the change count of the watcher's
-// PerlObjCBridge (host.ts). Linux: Wayland's wl-paste (its --watch sees each
-// change), else X11 (also Xwayland): xclip or xsel to read, clipnotify for
-// an event at each change, else GTK 3 from Python (python3-gi, on most GNOME
-// desktops) for both. The changes give the /iui grab hint (where no tool sees
-// them there is none: the clipboard is never read at intervals).
+// are seen. macOS: READ_PL (PerlObjCBridge) to read, and the watcher's
+// change count (host.ts). Linux: Wayland's wl-paste (its --watch sees each
+// change), else X11 (also Xwayland): xclip to read, clipnotify for an event
+// at each change, else GTK 3 from Python (python3-gi, on most GNOME desktops)
+// for both. The changes give the /iui grab hint (where no tool sees them
+// there is none: the clipboard is never read at intervals). A password
+// manager's copy is never read: each read looks at the marks first.
import type { EngineInterface } from 'claude-code'
import { S } from './state'
@@ -22,6 +23,37 @@ export type ClipTool = (typeof CLIP_TOOLS)[number]
// /iui grab hint is off.
export type ClipWay = { name: string; read: string[]; watch: string[]; wayland: boolean } | { off: string }
+// A password manager's copy (KeePassXC, KDE's and others' on Linux) offers
+// this target (its data "secret"); such a copy is never read. On macOS the
+// marks are pasteboard types (nspasteboard.org): concealed or transient.
+export const SECRET_TARGET = 'x-kde-passwordManagerHint'
+export const SECRET_TYPES = ['org.nspasteboard.ConcealedType', 'org.nspasteboard.TransientType'] as const
+
+// A read with the targets looked at before it and after it (`$0` the tool):
+// the mark in either gives exit 3, and its text is dropped (a change between
+// the two can be such a copy). xclip on X11, wl-paste on Wayland.
+const guardedRead = (list: string, read: string) =>
+ `secret() { ${list} 2>/dev/null | grep -qx '${SECRET_TARGET}'; }; secret && exit 3; ${read} || exit; secret && exit 3; exit 0`
+export const XCLIP_READ_SH = guardedRead('"$0" -o -selection clipboard -t TARGETS', '"$0" -o -selection clipboard -t UTF8_STRING')
+export const WL_READ_SH = guardedRead('"$0" -l', '"$0" -n -t text')
+
+// The read on macOS (/usr/bin/perl: its PerlObjCBridge): exit 3 when the
+// pasteboard has a concealed or transient type (its text is not read), or
+// when it changed during the read; exit 2 with no bridge, 1 with no text;
+// else the text (UTF-8).
+export const READ_PL = [
+ 'my $pb = eval { require Foundation; Foundation->import;',
+ ' NSBundle->bundleWithPath_("/System/Library/Frameworks/AppKit.framework")->load;',
+ ' @NSPasteboard::ISA = ("PerlObjCBridge"); my $p = NSPasteboard->generalPasteboard; defined $p->changeCount ? $p : undef } or exit 2;',
+ `my %secret = map { $_ => 1 } qw(${SECRET_TYPES.join(' ')});`,
+ 'my $n = $pb->changeCount; my $t = $pb->types;',
+ 'if ($t && $$t) { for my $i (0 .. $t->count - 1) { exit 3 if $secret{$t->objectAtIndex_($i)->UTF8String} } }',
+ 'my $s = $pb->stringForType_("public.utf8-plain-text");',
+ 'exit 3 if $pb->changeCount != $n;',
+ 'exit 1 unless $s && $$s;',
+ 'my $u = $s->UTF8String; utf8::encode($u) if utf8::is_utf8($u); binmode STDOUT; print $u;',
+].join(' ')
+
// The Wayland notifier's command: wl-paste runs it at each change (and once
// at its start) with the new data on stdin, which it reads to the end so the
// app that copied does not get a broken pipe. A copy that a password manager
@@ -56,7 +88,13 @@ export const GTK_READ_PY = [
'gi.require_version("Gtk", "3.0")',
'from gi.repository import Gtk, Gdk',
'if Gdk.Display.get_default() is None: sys.exit(1)',
- 't = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD).wait_for_text()',
+ 'c = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD)',
+ 'def secret():',
+ ' ok, targets = c.wait_for_targets()',
+ ` return ok and any(a.name() == "${SECRET_TARGET}" for a in targets)`,
+ 'if secret(): sys.exit(3)',
+ 't = c.wait_for_text()',
+ 'if secret(): sys.exit(3)',
'if t is None: sys.exit(1)',
'sys.stdout.write(t)',
].join('\n')
@@ -66,19 +104,19 @@ const GTK_ENV = ['/usr/bin/env', 'GDK_BACKEND=x11', 'PYTHONIOENCODING=utf-8']
// (WAYLAND_DISPLAY, DISPLAY, the desktop) and the tools found (their paths).
// Wayland: wl-paste, whose --watch needs the data-control protocol. GNOME
// does not have it (and its wl-paste read shows a window), so on GNOME the
-// X11 ways through Xwayland come first. X11: xclip, xsel or GTK to read, and
+// X11 ways through Xwayland come first. X11: xclip or GTK to read, and
// clipnotify or GTK to see the changes (X11 has no other event for them).
export function clipWayOf(o: { wayland: boolean; x11: boolean; desktop: string; found: Partial<Record<ClipTool, string>> }): ClipWay {
const { found } = o
const wl = o.wayland && found['wl-paste'] ? found['wl-paste'] : ''
const gtk = found.gtk ? { read: [...GTK_ENV, found.gtk, '-c', GTK_READ_PY], watch: [...GTK_ENV, found.gtk, '-c', GTK_WATCH_PY] } : null
- const reader = found.xclip ? { tool: 'xclip', read: [found.xclip, '-o', '-selection', 'clipboard', '-t', 'UTF8_STRING'] }
- : found.xsel ? { tool: 'xsel', read: [found.xsel, '-o', '-b'] }
+ // xsel is no reader: it can not list the targets (a password manager's copy would be read).
+ const reader = found.xclip ? { tool: 'xclip', read: ['sh', '-c', XCLIP_READ_SH, found.xclip] }
: gtk ? { tool: 'GTK', read: gtk.read } : null
const watcher = found.clipnotify ? { tool: 'clipnotify', watch: ['sh', '-c', X11_WATCH_SH, found.clipnotify] } : gtk ? { tool: 'GTK', watch: gtk.watch } : null
const isGnome = /gnome/i.test(o.desktop)
const waylandWay = () =>
- ({ name: 'wl-paste --watch (Wayland)', read: [wl, '-n', '-t', 'text'], watch: [wl, '--watch', 'sh', '-c', WL_WATCH_SH], wayland: true })
+ ({ name: 'wl-paste --watch (Wayland)', read: ['sh', '-c', WL_READ_SH, wl], watch: [wl, '--watch', 'sh', '-c', WL_WATCH_SH], wayland: true })
const x11Way = () => {
if (!o.x11 || !reader || !watcher) return null
const name = watcher.tool === reader.tool ? watcher.tool : `${watcher.tool} and ${reader.tool}`
@@ -90,15 +128,16 @@ export function clipWayOf(o: { wayland: boolean; x11: boolean; desktop: string;
if (wl) return waylandWay()
if (!o.wayland && !o.x11) return { off: 'no Wayland or X11 display' }
if (o.x11 && reader) return { off: `no clipnotify and no GTK 3 for Python: X11 has no clipboard event for ${reader.tool}` }
- return { off: o.wayland ? 'no wl-paste (install wl-clipboard)' : 'no xclip, xsel or GTK 3 for Python, and no clipnotify' }
+ if (o.wayland) return { off: 'no wl-paste (install wl-clipboard)' }
+ return { off: found.xsel ? 'xsel can not see a password manager\'s copy: install xclip' : 'no xclip or GTK 3 for Python, and no clipnotify' }
}
// Prints `tool path` for each clipboard tool on the PATH, and `gtk <python3>`
-// when there is no clipnotify and python3 loads GTK 3.
+// when there is no clipnotify or no xclip, and python3 loads GTK 3.
const GTK_CHECK_PY = 'import gi; gi.require_version("Gtk", "3.0"); from gi.repository import Gtk'
export const FIND_SH = [
`for c in ${CLIP_TOOLS.filter(c => c !== 'gtk').join(' ')}; do p=$(command -v "$c" 2>/dev/null) && echo "$c $p"; done`,
- `command -v clipnotify >/dev/null 2>&1 || { p=$(command -v python3 2>/dev/null) && "$p" -c '${GTK_CHECK_PY}' >/dev/null 2>&1 && echo "gtk $p"; }`,
+ `{ command -v clipnotify && command -v xclip; } >/dev/null 2>&1 || { p=$(command -v python3 2>/dev/null) && "$p" -c '${GTK_CHECK_PY}' >/dev/null 2>&1 && echo "gtk $p"; }`,
].join('; ')
// The tools of `FIND_SH`'s output, by name; only absolute paths.
@@ -132,11 +171,12 @@ async function lookUp($: EngineInterface): Promise<ClipWay> {
return S.clipWay
}
-// The clipboard now as text: pbpaste (UTF-8) on macOS, else the way found
-// on Linux; null when it can not be read (no tool, or no text in it).
+// The clipboard now as text: READ_PL on macOS, else the way found on Linux;
+// null when it can not be read (no tool or no bridge, no text in it, or a
+// password manager's copy, which is never read).
export async function clipboardNow($: EngineInterface): Promise<string | null> {
if (S.env?.isMac) {
- const got = await processRun($, ['pbpaste'], { timeoutMs: 2000, env: { LANG: 'en_US.UTF-8', LC_ALL: 'en_US.UTF-8' } }).catch(() => null)
+ const got = await processRun($, ['/usr/bin/perl', '-e', READ_PL], { timeoutMs: 2000 }).catch(() => null)
return got && got.exitCode === 0 ? got.stdout : null
}
const way = S.clipWay
diff --git a/hooks/lib/state.ts b/hooks/lib/state.ts
index 5c3e414..8316d7a 100644
--- a/hooks/lib/state.ts
+++ b/hooks/lib/state.ts
@@ -293,16 +293,16 @@ export const DRAWN_KEPT = 64
// The clipboard (register.tsx): the change count last seen (null: none
// yet; the first of each watcher child is only noted), whether the watcher
// found no PerlObjCBridge (`none`), a read that runs (`busy`) and a change
-// that came during it (`again`), the clipboard text last seen and last
-// written (so a write is never read back as new), the last text with
-// placeholders with its row (`rawRow`, when known) and how it was read (for
-// dump), and the order of the drawings (`seq`).
+// that came during it (`again`), the clipboard text last seen (null: none
+// could be read) and last written (so a write is never read back as new),
+// the last text with placeholders with its row (`rawRow`, when known) and
+// how it was read (for dump), and the order of the drawings (`seq`).
export const clip = {
count: null as number | null,
none: false,
busy: false,
again: false,
- seen: '',
+ seen: '' as string | null,
wrote: '',
raw: '',
rawRow: undefined as string | undefined,
diff --git a/hooks/register.tsx b/hooks/register.tsx
index 919f18a..ab948fa 100644
--- a/hooks/register.tsx
+++ b/hooks/register.tsx
@@ -94,7 +94,10 @@ export * from './lib/images'
export { rowsAfter, type Under } from './lib/pictures'
export * from './lib/copy'
export { targetAt, targetsOf, type PageTarget, type Target } from './lib/targets'
-export { CLIP_TOOLS, clipToolsOf, clipWayOf, FIND_SH, GTK_READ_PY, GTK_WATCH_PY, hintText, WL_WATCH_SH, X11_WATCH_SH, type ClipTool, type ClipWay } from './lib/clipboard'
+export {
+ CLIP_TOOLS, clipToolsOf, clipWayOf, FIND_SH, GTK_READ_PY, GTK_WATCH_PY, hintText, READ_PL, SECRET_TARGET, SECRET_TYPES, WL_READ_SH, WL_WATCH_SH, X11_WATCH_SH, XCLIP_READ_SH,
+ type ClipTool, type ClipWay,
+} from './lib/clipboard'
export {
agoText, checkedOf, compareVersions, isDue, isNewer, parseVersion, shouldTell, toldOf, UPDATE_EVERY_MS, UPDATE_FETCH_MS, UPDATE_STEPS, UPDATE_TOAST_MS,
UPDATE_URL, updateLine, updateNotice, updateToast, versionOf,
@@ -232,12 +235,13 @@ async function planEnv($: EngineInterface): Promise<Env | null> {
// copy that still puts kitty placeholder cells on the clipboard (the main
// screen's, a native drag over text and pictures) is seen by the watcher
// (lib/frame.ts), which prints a line when the clipboard changes: the
-// clipboard is read once (pbpaste, wl-paste, xclip, xsel or GTK), and cells
-// that fit a page drawn here get a toast that names /iui grab, which reads
-// them (see lib/copy.ts; the drawn pages and the words of a page are in
-// lib/probe.ts). The clipboard is never written but by a copy the person
-// asked for. No timer reads the clipboard; the selection is read every
-// 250 ms only while a picture selection shows (watchNative).
+// clipboard is read once (perl on macOS, wl-paste, xclip or GTK; never a
+// password manager's copy), and cells that fit a page drawn here get a
+// toast that names /iui grab, which reads them (see lib/copy.ts; the drawn
+// pages and the words of a page are in lib/probe.ts). The clipboard is
+// never written but by a copy the person asked for, and never over a newer
+// copy (isNewest). No timer reads the clipboard; the selection is read
+// every 250 ms only while a picture selection shows (watchNative).
// Notes a drawing for a copy (noteDrawn, noteDrawnAgain), turns on the
// watcher's clipboard part and queues its pages for picture select's
@@ -310,8 +314,10 @@ function hintGrab($: EngineInterface, text: string) {
}
// The clipboard changed: one read (clipboardNow). A clipboard with no
-// placeholders, and our own write, are never touched. A change while a
-// read runs reads once more after it.
+// placeholders, and our own write, are never touched. A new text that no
+// $.ui.copy wrote (another app's copy, Claude Code's copy on select, a
+// password manager's: null) is a newer copy. A change while a read runs
+// reads once more after it.
async function readClipboard($: EngineInterface) {
if (clip.busy) {
clip.again = true
@@ -322,9 +328,10 @@ async function readClipboard($: EngineInterface) {
do {
clip.again = false
const text = await clipboardNow($)
- if (text === null || text === clip.seen) continue
+ if (text === clip.seen) continue
clip.seen = text
- if (text === clip.wrote || !hasPlaceholders(text)) continue
+ if (text !== copiedText) copies++
+ if (text === null || text === clip.wrote || !hasPlaceholders(text)) continue
hintGrab($, text)
} while (clip.again)
} finally {
@@ -367,15 +374,38 @@ async function updateState($: EngineInterface): Promise<UpdateState> {
return { on: S.updates, off: S.updatesOff, own: S.ownVersion, checked: S.updateChecked, now }
}
-// The newest copy (a grab, a click or an up): an older one that still
-// reads its text when a newer one starts copies nothing.
+// The newest copy (a grab, a click, an up, any $.ui.copy, or a copy from
+// outside that the watcher sees): an older one that still reads its text
+// when a newer one starts copies nothing. `copiedText`: the text of the
+// last $.ui.copy (its clipboard change is no copy from outside).
let copies = 0
+let copiedText: string | undefined
+
+// A copy's turn: its number and the native selection when it began.
+type Turn = { n: number; native: Promise<string> }
+const nativeKey = (s: { text: string; requestId?: string } | undefined) => (s ? `${s.requestId ?? ''}|${s.text}` : '')
+function nativeNow($: EngineInterface): Promise<string> {
+ try {
+ return Promise.resolve(uiSelection($)).then(nativeKey, () => '?')
+ } catch {
+ return Promise.resolve('?')
+ }
+}
+const takeTurn = ($: EngineInterface, native?: Promise<string>): Turn => ({ n: ++copies, native: native ?? nativeNow($) })
+
+// Whether a copy is still the newest when its text is read: no newer copy
+// came, and no new native selection (Claude Code copies that itself, past
+// every hook; no poll runs for a click).
+async function isNewest($: EngineInterface, turn: Turn): Promise<boolean> {
+ if (turn.n !== copies) return false
+ const [was, now] = await Promise.all([turn.native, nativeNow($)])
+ return turn.n === copies && was === now
+}
// /iui grab: the last mouse selection, read and copied. With no selection
// (the main screen), the picture cells on the clipboard: the command says
// that the copy is this session's.
async function grab($: EngineInterface): Promise<string> {
- const mine = ++copies
const selected = await uiSelection($).catch(() => undefined)
let raw = selected?.text
if (raw === undefined) {
@@ -389,8 +419,10 @@ async function grab($: EngineInterface): Promise<string> {
const row = selected?.requestId
clip.raw = raw
clip.rawRow = row
+ // Only a grab that copies takes a turn.
+ const turn = takeTurn($, Promise.resolve(nativeKey(selected)))
const read = await readCopy($, raw, row)
- if (mine !== copies) return 'Intelligent UI: a newer copy came first; this one copied nothing.'
+ if (!(await isNewest($, turn))) return 'Intelligent UI: a newer copy came first; this one copied nothing.'
if (!read.resolved) return `Intelligent UI: found ${read.runs} picture run(s) but could not read them (see /iui dump).`
clip.wrote = read.text
clip.seen = read.text
@@ -521,14 +553,14 @@ function lightHover($: EngineInterface) {
// A click (a clear) on a target of the page copies its text (a link's URL,
// a file's path, a command, a code block's code). The page's words are probed first when they
-// are not known; a newer copy while they are: the newer one copies.
+// are not known; a newer copy while they are (or a new native selection): the newer one copies.
async function clickAt($: EngineInterface, d: Drawn & { job?: Job }, post: SelectPost, surface: RenderSurface) {
- const mine = ++copies
+ const turn = takeTurn($)
const links = () => clickLinks.get(d.id) ?? NO_LINKS
let targets = knownTargets(d, post.page, links())
if (!targets) {
await wordsOf($, d, post.page)
- if (mine !== copies) return
+ if (!(await isNewest($, turn))) return
targets = knownTargets(d, post.page, links())
}
const target = targets?.[targetAt(targets, post.anchor.x, post.anchor.y)]?.target
@@ -563,13 +595,13 @@ async function selectionText($: EngineInterface, d: Drawn & { job?: Job }, sel:
// The button came up: the selection's text on the clipboard, with the
// toast of a copy. No text under it: nothing is copied; a newer up while
-// its words are read (or a newer click or grab): the newer one copies.
+// its words are read (or any newer copy, or a new native selection): the newer one copies.
async function copySelection($: EngineInterface, d: Drawn & { job?: Job }, sel: Selection, surface: RenderSurface) {
const t = performance.now()
- const mine = ++copies
+ const turn = takeTurn($)
const probed: number[] = []
const text = await selectionText($, d, sel, probed)
- if (mine !== copies) return
+ if (!(await isNewest($, turn))) return
const read = performance.now() - t
if (text === null) {
uiToast($, 'Intelligent UI: could not read the selected picture')
@@ -643,18 +675,27 @@ export const register: Register = on => {
// A copy with placeholders (a copy of picture cells, when the engine sends
// one through `$.ui.copy`): the words under them instead. Our own copies
- // hold no placeholders and pass on as they are.
+ // hold no placeholders and pass on as they are. Any copy is the newest:
+ // one with placeholders whose words are read when a newer one came is refused.
on('ui.copy', async ($, e, next) => {
- if (!hasPlaceholders(e.text) || !drawnAnswers.size) return next(e)
+ copiedText = e.text
+ if (!hasPlaceholders(e.text) || !drawnAnswers.size) {
+ copies++
+ return next(e)
+ }
if (S.debug) traceDebug($, 'select: native copy seen: a $.ui.copy with picture cells (read as their text)')
- const selected = await uiSelection($).catch(() => undefined)
+ const selection = uiSelection($).catch(() => undefined)
+ const turn = takeTurn($, selection.then(nativeKey))
+ const selected = await selection
clip.raw = e.text
clip.rawRow = selected?.text === e.text ? selected.requestId : undefined
const read = await readCopy($, e.text, clip.rawRow)
+ if (!(await isNewest($, turn))) return { value: { isCopied: false, reason: 'refused' } }
if (!read.resolved) return next(e)
// The clipboard change of this write is not read again.
clip.wrote = read.text
clip.seen = read.text
+ copiedText = read.text
return next({ ...e, text: read.text })
}).catch(($, e, next) => next(e))
diff --git a/tests/copy.test.ts b/tests/copy.test.ts
index 7dae4ad..91884cb 100644
--- a/tests/copy.test.ts
+++ b/tests/copy.test.ts
@@ -2,7 +2,7 @@ import { expect, mock, test } from 'claude-code/testing'
import {
codePointsOf, commandSuggestions, decodeSelection, DIACRITICS, hasPlaceholders, isDrawnIn, joinSegments, pageTopsOf, pickPages,
- placeholderCell, isSafePage, positionsOf, screenOf, textOfRun, WATCH_PL, type Drawn, type TextBlock, type Item, type Mark, type OnScreen,
+ placeholderCell, isSafePage, positionsOf, READ_PL, screenOf, textOfRun, WATCH_PL, type Drawn, type TextBlock, type Item, type Mark, type OnScreen,
type Place,
} from '../hooks/register'
import * as registerModule from '../hooks/register'
@@ -576,7 +576,7 @@ test('/iui grab and dump are commands with typeahead rows; dump with nothing see
expect(ran.text).toContain('Intelligent UI: no clipboard text with picture cells seen yet')
})
-// ---- The pipeline: the watcher's clip lines, pbpaste, the probe of a page ------
+// ---- The pipeline: the watcher's clip lines, the read, the probe of a page ----
const ok = (stdout: string, exitCode = 0) => ({ value: { exitCode, stdout, stderr: exitCode ? 'error: boom' : '', isStdoutTruncated: false, isStderrTruncated: false } })
// The first 24 bytes of a 1568 x 512 PNG (the fixture's page), as `od` prints them.
@@ -587,9 +587,10 @@ const inputsOf = (argv: readonly string[]) => Object.fromEntries(argv.flatMap((a
// The world beneath the mod: a cache at /c, a typst whose compile writes a
// 1568 x 512 page per segment and whose query of page n gives the fixture's
// marks on page n (`hold` holds the next query until `release`; a kill ends
-// it), the watcher (WATCH_PL: its PID, then with `clip` the change count at
+// it; `holdReads` the clipboard reads until `releaseReads`), the watcher (WATCH_PL: its PID, then with `clip` the change count at
// its start and at each change of the clipboard; `clip none` with
-// `noBridge`), pbpaste reading `clipboard`, and the copies, toasts and
+// `noBridge`), the read (READ_PL) giving `clipboard` (exit 3 for a
+// password manager's copy: `concealed`), and the copies, toasts and
// selection the test sees. `copy` is a native copy (a drag over text and
// pictures, the main screen's terminal copy): while `selects`, picture cells
// are this session's selection too; the text goes on the clipboard, one
@@ -630,7 +631,7 @@ function world(
const w = {
clock, files, compiles, queries, kills, watchers, vars, envSets,
ran: [] as string[][], spawned: [] as string[][], reads: [] as string[],
- clipboard: 'nothing yet', count: 40, pastes: 0, copies: [] as string[], toasts: [] as string[], traces: [] as string[], logs: [] as string[],
+ clipboard: 'nothing yet', secret: false, count: 40, pastes: 0, copies: [] as string[], toasts: [] as string[], traces: [] as string[], logs: [] as string[],
frames: [] as { path: string; old: string[]; png: Uint8Array }[], blits: [] as any[], writes: 0, selectionReads: 0,
selection: undefined as { text: string; requestId?: string } | undefined,
selects: true,
@@ -638,12 +639,23 @@ function world(
hold() {
w.gate = new Promise<void>(r => (w.release = r))
},
+ readGate: null as Promise<void> | null, releaseReads: () => {},
+ holdReads() {
+ w.readGate = new Promise<void>(r => (w.releaseReads = r))
+ },
copy(text: string) {
if (w.selects && hasPlaceholders(text)) w.selection = { text }
w.foreign(text)
},
foreign(text: string) {
w.clipboard = text
+ w.secret = false
+ w.change()
+ },
+ // A password manager's copy (concealed): the clipboard read gives exit 3.
+ concealed(text: string) {
+ w.clipboard = text
+ w.secret = true
w.change()
},
change() {
@@ -718,9 +730,11 @@ function world(
if (cmd.includes('command -v typst')) return ok('/usr/bin/typst\n')
if (argv[0] === '/usr/bin/typst' && argv[1] === 'eval') return ok('{}')
if (cmd.includes('od -An')) return ok(argv.filter(a => a.endsWith('.png')).map(() => `${HEAD}\n@\n`).join(''))
- if (argv[0] === 'pbpaste') {
+ if (argv[0] === '/usr/bin/perl' && argv[2] === READ_PL) {
w.pastes++
- return ok(w.clipboard)
+ if (w.readGate) await w.readGate
+ // A password manager's copy: exit 3, its text not read.
+ return w.secret ? ok('', 3) : ok(w.clipboard)
}
return ok('', 1)
})
@@ -1775,7 +1789,7 @@ test('picture select: with no perl the first frame write fails, is logged once a
// the link "the docs" row 3 columns 4 to 11, the bare URL row 3 16 to 45,
// `! ls -la` row 4 50 to 58, src/a.ts row 6 5 to 13, the bash block's copy
// button row 8 8 to 15 (its code rows 11 and 12: no target).
-async function drawTargets($: any, on: any, o: { env?: Record<string, string>; marks?: readonly object[] } = {}, isFullscreen: boolean | null = true) {
+async function drawTargets($: any, on: any, o: { env?: Record<string, string>; marks?: readonly object[]; noBridge?: boolean } = {}, isFullscreen: boolean | null = true) {
const w = world(on, { tty: TTY, marks: TARGETS_MARKS, ...o })
on('session.cwd', async () => ({ value: '/w' }))
on('fs.exists', async ($: any, e: any) => ({ value: e.path === '/w/src/a.ts' }))
@@ -2009,3 +2023,173 @@ test('no private cache folder: nothing is drawn (no shared folder instead); /iui
// The old shared folder is never used.
expect([...w.ran.flat(), ...w.reads, ...w.files.keys()].some(t => t.includes('/tmp/cc-intelligent-ui'))).toBe(false)
})
+
+// ---- The newest copy wins -----------------------------------------------------
+// A copy that still reads its words when a newer copy came (ours, another
+// plugin's $.ui.copy, Claude Code's copy on select, another app's) copies nothing.
+
+test('picture select: an up whose words are still read copies nothing after a native selection (the watcher sees its copy)', async ($, on) => {
+ const w = world(on, { tty: TTY })
+ await $.command.run({ command: 'iui', args: '' } as any)
+ w.hold()
+ const ui = await drawAnswer($, w)
+ await drag(ui)
+ await settle(w)
+ expect(w.copies).toEqual([])
+ // Claude Code's own selection: it copies on select, past every hook.
+ w.selection = { text: 'native text', requestId: 'ans-0' }
+ w.foreign('native text')
+ await w.clock.advance(600)
+ await settle(w)
+ expect(isPlain(w)).toBe(true)
+ w.release()
+ await settle(w)
+ expect(w.copies).toEqual([])
+ expect(w.clipboard).toBe('native text')
+})
+
+test('picture select: an up whose words are still read copies nothing after a native selection, with no watcher and no poll in between', async ($, on) => {
+ const w = world(on, { tty: TTY, noBridge: true })
+ await $.command.run({ command: 'iui', args: '' } as any)
+ w.hold()
+ const ui = await drawAnswer($, w)
+ await drag(ui)
+ await settle(w)
+ // The native selection comes just before the words: no poll ran, no clipboard change is seen.
+ w.selection = { text: 'native text', requestId: 'ans-0' }
+ w.foreign('native text')
+ w.release()
+ await settle(w)
+ expect(w.copies).toEqual([])
+ expect(w.clipboard).toBe('native text')
+})
+
+test('picture select: a click whose words are still read copies nothing after a native selection (no poll runs for a click)', async ($, on) => {
+ const { w } = await drawTargets($, on, { noBridge: true })
+ w.hold()
+ const slow = await drawAnswer($, w, 'ans-2', `${TARGETS_MD}\n\nOne more line.`)
+ await click(slow, 6, 3)
+ await settle(w)
+ expect(w.copies).toEqual([])
+ w.selection = { text: 'native text', requestId: 'ans-0' }
+ w.foreign('native text')
+ w.release()
+ await settle(w)
+ expect(w.copies).toEqual([])
+ expect(w.clipboard).toBe('native text')
+ // A native selection made before the click does not stop it.
+ await click(slow, 6, 3)
+ await settle(w)
+ expect(w.copies).toEqual(['https://example.com'])
+})
+
+test('picture select: a click whose words are still read copies nothing after a copy in another app; a password manager\'s copy too', async ($, on) => {
+ const { w } = await drawTargets($, on)
+ w.hold()
+ const slow = await drawAnswer($, w, 'ans-2', `${TARGETS_MD}\n\nOne more line.`)
+ await click(slow, 6, 3)
+ await settle(w)
+ w.foreign('copied in another app')
+ await settle(w)
+ w.release()
+ await settle(w)
+ expect(w.copies).toEqual([])
+ expect(w.clipboard).toBe('copied in another app')
+ // A password manager's copy: never read (exit 3), and a newer copy still.
+ w.hold()
+ const slower = await drawAnswer($, w, 'ans-3', `${TARGETS_MD}\n\nTwo more lines.\n\nHere.`)
+ await click(slower, 6, 3)
+ await settle(w)
+ w.concealed('hunter2')
+ await settle(w)
+ w.release()
+ await settle(w)
+ expect(w.copies).toEqual([])
+ expect(w.clipboard).toBe('hunter2')
+})
+
+test('a $.ui.copy of picture cells whose words are still read is refused after a newer click', { plugins: [COPIER] }, async ($, on) => {
+ const { w, ui } = await drawTargets($, on)
+ w.hold()
+ // A newer drawing (its own folder): its words held. The cells fit it first (the newest).
+ await drawAnswer($, w, 'ans-2', `${TARGETS_MD}\n\nOne more line.`)
+ const cp = $.command.run({ command: 'cp', args: [cells(1, 0, 97), cells(2, 0, 97), cells(3, 0, 21)].join('\n') } as any)
+ await settle(w)
+ await click(ui, 6, 3)
+ await settle(w)
+ expect(w.copies).toEqual(['https://example.com'])
+ w.release()
+ expect(JSON.parse((await cp).text!)).toEqual({ isCopied: false, reason: 'refused' })
+ await settle(w)
+ expect(w.copies).toEqual(['https://example.com'])
+ expect(w.clipboard).toBe('https://example.com')
+})
+
+test('another plugin\'s $.ui.copy cancels a click whose words are still read; its clipboard change is no copy from outside', { plugins: [COPIER] }, async ($, on) => {
+ const { w } = await drawTargets($, on)
+ w.hold()
+ const slow = await drawAnswer($, w, 'ans-2', `${TARGETS_MD}\n\nOne more line.`)
+ await click(slow, 6, 3)
+ await settle(w)
+ await $.command.run({ command: 'cp', args: 'plain text' } as any)
+ await settle(w)
+ w.release()
+ await settle(w)
+ expect(w.copies).toEqual(['plain text'])
+ expect(w.clipboard).toBe('plain text')
+ // Its clipboard change read only after a newer click started: that click still copies.
+ w.holdReads()
+ await $.command.run({ command: 'cp', args: 'more text' } as any)
+ w.hold()
+ const slower = await drawAnswer($, w, 'ans-3', `${TARGETS_MD}\n\nTwo more lines.\n\nHere.`)
+ await click(slower, 6, 3)
+ await settle(w)
+ w.releaseReads()
+ await settle(w)
+ w.release()
+ await settle(w)
+ expect(w.copies).toEqual(['plain text', 'more text', 'https://example.com'])
+ expect(w.clipboard).toBe('https://example.com')
+})
+
+test('/iui grab that copies nothing (no selection, no picture cells) does not cancel a click whose words are still read', async ($, on) => {
+ const { w } = await drawTargets($, on)
+ w.hold()
+ const slow = await drawAnswer($, w, 'ans-2', `${TARGETS_MD}\n\nOne more line.`)
+ await click(slow, 6, 3)
+ await settle(w)
+ // The same text the clipboard had: no change seen.
+ const said = await grab($)
+ expect(said).toContain('no picture cells')
+ w.release()
+ await settle(w)
+ expect(w.copies).toEqual(['https://example.com'])
+ expect(w.clipboard).toBe('https://example.com')
+})
+
+test('a password manager\'s copy is never read: no hint, no /iui grab, nothing in dump; the read looks at the marks first', async ($, on) => {
+ const w = world(on)
+ await $.command.run({ command: 'iui', args: '' } as any)
+ await drawAnswer($, w)
+ const pastes = w.pastes
+ w.concealed(COPY)
+ await w.clock.settle()
+ // One read, which gives exit 3 (no text).
+ expect(w.pastes).toBe(pastes + 1)
+ expect(hints(w)).toBe(0)
+ expect(await grab($)).toBe('Intelligent UI: no mouse selection, and the clipboard can not be read (see /iui details).')
+ expect((await $.command.run({ command: 'iui', args: 'dump' } as any)).text).toContain('no clipboard text with picture cells seen yet')
+ expect(w.copies).toEqual([])
+ // The perl read: the concealed and transient types (nspasteboard.org) before the text, and a change during the read drops it.
+ for (const type of ['org.nspasteboard.ConcealedType', 'org.nspasteboard.TransientType']) {
+ expect(READ_PL.indexOf(type)).toBeGreaterThan(-1)
+ expect(READ_PL.indexOf(type)).toBeLessThan(READ_PL.indexOf('stringForType_'))
+ }
+ expect(READ_PL).toContain('exit 3 if $secret{$t->objectAtIndex_($i)->UTF8String}')
+ expect(READ_PL.indexOf('exit 3 if $pb->changeCount != $n')).toBeGreaterThan(READ_PL.indexOf('stringForType_'))
+ expect(READ_PL.indexOf('exit 3 if $pb->changeCount != $n')).toBeLessThan(READ_PL.indexOf('print $u'))
+ // The same cells copied the usual way: the hint.
+ w.foreign(COPY)
+ await w.clock.settle()
+ expect(hints(w)).toBe(1)
+})
diff --git a/tests/linux.test.ts b/tests/linux.test.ts
index af578ff..f0199d0 100644
--- a/tests/linux.test.ts
+++ b/tests/linux.test.ts
@@ -2,7 +2,8 @@ import { expect, mock, test } from 'claude-code/testing'
import {
clipToolsOf, clipWayOf, editorArgv, familyOfFc, FIND_SH, GHOSTTY_DEFAULT_FONT, GTK_READ_PY, GTK_WATCH_PY, guiEditorOf, hintText, LINUX_EDITORS,
- placeholderCell, schemeOfPortal, SETUP_NOT_MAC, WATCH_PL, WL_WATCH_SH, X11_WATCH_SH, type ClipWay,
+ placeholderCell, READ_PL, schemeOfPortal, SECRET_TARGET, SECRET_TYPES, SETUP_NOT_MAC, WATCH_PL, WL_READ_SH, WL_WATCH_SH, X11_WATCH_SH, XCLIP_READ_SH,
+ type ClipWay,
} from '../hooks/register'
import { CACHE_SH } from '../hooks/lib/env'
import { clipboardNow, clipWatchArgs, clipWayReady, findClipWay } from '../hooks/lib/clipboard'
@@ -20,15 +21,15 @@ test('the tools found: `name path` lines, absolute paths only', () => {
'wl-paste': '/usr/bin/wl-paste', xclip: '/usr/bin/xclip', gtk: '/usr/bin/python3',
})
expect(clipToolsOf('')).toEqual({})
- // GTK is checked only when there is no clipnotify.
- expect(FIND_SH).toContain('command -v clipnotify >/dev/null 2>&1 || {')
+ // GTK is checked only when there is no clipnotify or no xclip.
+ expect(FIND_SH).toContain('{ command -v clipnotify && command -v xclip; } >/dev/null 2>&1 || {')
expect(FIND_SH).toContain('echo "gtk $p"')
})
test('Wayland (not GNOME): wl-paste reads, and its --watch sees each change', () => {
const way = clipWayOf({ wayland: true, x11: true, desktop: 'KDE', found: ALL })
expect(way).toEqual({
- name: 'wl-paste --watch (Wayland)', read: ['/usr/bin/wl-paste', '-n', '-t', 'text'],
+ name: 'wl-paste --watch (Wayland)', read: ['sh', '-c', WL_READ_SH, '/usr/bin/wl-paste'],
watch: ['/usr/bin/wl-paste', '--watch', 'sh', '-c', WL_WATCH_SH], wayland: true,
})
// The data goes to the end, and a sensitive copy gives no line.
@@ -37,7 +38,7 @@ test('Wayland (not GNOME): wl-paste reads, and its --watch sees each change', ()
test('GNOME on Wayland (no data-control): the X11 tools through Xwayland come first, wl-paste last', () => {
expect(clipWayOf({ wayland: true, x11: true, desktop: 'ubuntu:GNOME', found: ALL })).toEqual({
- name: 'clipnotify and xclip (X11, Xwayland)', read: ['/usr/bin/xclip', '-o', '-selection', 'clipboard', '-t', 'UTF8_STRING'],
+ name: 'clipnotify and xclip (X11, Xwayland)', read: ['sh', '-c', XCLIP_READ_SH, '/usr/bin/xclip'],
watch: ['sh', '-c', X11_WATCH_SH, '/usr/local/bin/clipnotify'], wayland: false,
})
// Only GTK (a GNOME desktop with no other tool): GTK reads and watches.
@@ -49,18 +50,21 @@ test('GNOME on Wayland (no data-control): the X11 tools through Xwayland come fi
expect(clipWayOf({ wayland: true, x11: true, desktop: 'GNOME', found: { 'wl-paste': '/w' } })).toMatchObject({ name: 'wl-paste --watch (Wayland)', wayland: true })
})
-test('X11: clipnotify or GTK sees the changes; xclip, xsel or GTK reads', () => {
- expect(clipWayOf({ wayland: false, x11: true, desktop: 'XFCE', found: { xsel: '/x/xsel', clipnotify: '/x/cn' } })).toMatchObject({
- name: 'clipnotify and xsel (X11)', read: ['/x/xsel', '-o', '-b'],
+test('X11: clipnotify or GTK sees the changes; xclip or GTK reads (xsel can not see a password manager\'s copy)', () => {
+ expect(clipWayOf({ wayland: false, x11: true, desktop: 'XFCE', found: { xsel: '/x/xsel', clipnotify: '/x/cn' } })).toEqual({
+ off: 'xsel can not see a password manager\'s copy: install xclip',
+ })
+ expect(clipWayOf({ wayland: false, x11: true, desktop: 'XFCE', found: { xsel: '/x/xsel', clipnotify: '/x/cn', gtk: '/p' } })).toMatchObject({
+ name: 'clipnotify and GTK (X11)', read: ['/usr/bin/env', 'GDK_BACKEND=x11', 'PYTHONIOENCODING=utf-8', '/p', '-c', GTK_READ_PY],
})
expect(clipWayOf({ wayland: false, x11: true, desktop: '', found: { xclip: '/x/xclip', gtk: '/p' } })).toMatchObject({
- name: 'GTK and xclip (X11)', read: ['/x/xclip', '-o', '-selection', 'clipboard', '-t', 'UTF8_STRING'],
+ name: 'GTK and xclip (X11)', read: ['sh', '-c', XCLIP_READ_SH, '/x/xclip'],
})
// wl-paste is not used with no Wayland display.
expect(clipWayOf({ wayland: false, x11: true, desktop: '', found: { 'wl-paste': '/w', xclip: '/x/xclip' } })).toEqual({
off: 'no clipnotify and no GTK 3 for Python: X11 has no clipboard event for xclip',
})
- expect(clipWayOf({ wayland: false, x11: true, desktop: '', found: {} })).toEqual({ off: 'no xclip, xsel or GTK 3 for Python, and no clipnotify' })
+ expect(clipWayOf({ wayland: false, x11: true, desktop: '', found: {} })).toEqual({ off: 'no xclip or GTK 3 for Python, and no clipnotify' })
expect(clipWayOf({ wayland: true, x11: false, desktop: 'sway', found: { xclip: '/x' } })).toEqual({ off: 'no wl-paste (install wl-clipboard)' })
expect(clipWayOf({ wayland: false, x11: false, desktop: '', found: ALL })).toEqual({ off: 'no Wayland or X11 display' })
// clipnotify 1.0.3+ loops by itself (-l); an older one exits at each change.
@@ -75,6 +79,31 @@ test('the GTK scripts: X11 events, a line at the start, a text read that fails w
expect(GTK_READ_PY).toContain('if t is None: sys.exit(1)')
})
+test('a password manager\'s copy is never read: each Linux read looks at the targets before and after it (exit 3, its text dropped)', async () => {
+ expect(SECRET_TARGET).toBe('x-kde-passwordManagerHint')
+ expect(SECRET_TYPES).toEqual(['org.nspasteboard.ConcealedType', 'org.nspasteboard.TransientType'])
+ const check = (list: string) => `secret() { ${list} 2>/dev/null | grep -qx 'x-kde-passwordManagerHint'; }; secret && exit 3;`
+ expect(XCLIP_READ_SH).toBe(`${check('"$0" -o -selection clipboard -t TARGETS')} "$0" -o -selection clipboard -t UTF8_STRING || exit; secret && exit 3; exit 0`)
+ expect(WL_READ_SH).toBe(`${check('"$0" -l')} "$0" -n -t text || exit; secret && exit 3; exit 0`)
+ // GTK: the targets before the text and after it.
+ const before = GTK_READ_PY.indexOf('if secret(): sys.exit(3)')
+ expect(GTK_READ_PY).toContain('return ok and any(a.name() == "x-kde-passwordManagerHint" for a in targets)')
+ expect(before).toBeGreaterThan(-1)
+ expect(before).toBeLessThan(GTK_READ_PY.indexOf('.wait_for_text()'))
+ expect(GTK_READ_PY.lastIndexOf('if secret(): sys.exit(3)')).toBeGreaterThan(GTK_READ_PY.indexOf('.wait_for_text()'))
+ // Each way found reads through its guard; xsel (no targets) is never a reader.
+ for (const found of [ALL, { xclip: '/x/xclip', clipnotify: '/x/cn' }, { gtk: '/p' }, { xsel: '/x/xsel', gtk: '/p' }]) {
+ for (const wayland of [true, false]) {
+ const way = clipWayOf({ wayland, x11: true, desktop: wayland ? 'KDE' : 'XFCE', found }) as Extract<ClipWay, { name: string }>
+ expect([XCLIP_READ_SH, WL_READ_SH, GTK_READ_PY].some(g => way.read.includes(g))).toBe(true)
+ expect(way.read.some(a => a.endsWith('xsel'))).toBe(false)
+ }
+ }
+ // Exit 3 (the mark seen): null, whatever was printed.
+ expect(await withClip(false, WL_WAY, () => clipboardNow(fake$({ exitCode: 3, stdout: 'hunter2' }).$))).toBe(null)
+ expect(await withClip(true, null, () => clipboardNow(fake$({ exitCode: 3, stdout: '' }).$))).toBe(null)
+})
+
test('the /iui grab hint line: on when the watcher sees the changes, else off with the reason', () => {
const base = { isMac: true, hostOs: 'Darwin', isRemote: false, isOn: true, none: false, drawn: true, running: true, way: null as ClipWay | null }
expect(hintText(base)).toBe('on')
@@ -135,13 +164,13 @@ test('the watcher arguments after clip: none on macOS, the notifier on Linux, nu
await withClip(false, null, () => expect(clipWatchArgs(false)).toBe(null))
})
-test('the clipboard now: pbpaste on macOS (UTF-8), the way found on Linux; null when it can not be read', async () => {
+test('the clipboard now: PerlObjCBridge on macOS, the way found on Linux; null when it can not be read', async () => {
const mac = fake$({ exitCode: 0, stdout: 'héllo' })
expect(await withClip(true, null, () => clipboardNow(mac.$))).toBe('héllo')
- expect(mac.argvs).toEqual([['pbpaste']])
+ expect(mac.argvs).toEqual([['/usr/bin/perl', '-e', READ_PL]])
const lin = fake$({ exitCode: 0, stdout: 'text' })
expect(await withClip(false, WL_WAY, () => clipboardNow(lin.$))).toBe('text')
- expect(lin.argvs).toEqual([['/usr/bin/wl-paste', '-n', '-t', 'text']])
+ expect(lin.argvs).toEqual([['sh', '-c', WL_READ_SH, '/usr/bin/wl-paste']])
// A read that fails, throws, or has no tool to run.
expect(await withClip(true, null, () => clipboardNow(fake$({ exitCode: 1, stdout: 'x' }).$))).toBe(null)
expect(await withClip(false, WL_WAY, () => clipboardNow(fake$(new Error('timeout')).$))).toBe(null)
@@ -163,7 +192,7 @@ test('looking up the clipboard way sets S.clipWay from the display, the desktop
// The tools can not be looked up: no tool, so the way is off.
const failed = findClipWay(fake$(new Error('boom'), { DISPLAY: ':0' }).$)
await clipWayReady()
- expect(await failed).toEqual({ off: 'no xclip, xsel or GTK 3 for Python, and no clipnotify' })
+ expect(await failed).toEqual({ off: 'no xclip or GTK 3 for Python, and no clipnotify' })
} finally {
S.clipWay = was
}
@@ -297,7 +326,7 @@ function linuxWorld(on: any, o: { scheme?: number; noPortal?: boolean; env?: Rec
if (argv[0] === 'gsettings') return ok("'prefer-light'\n")
if (argv[0] === 'fc-match' && argv[1] === 'monospace') return ok('DejaVu Sans Mono')
if (argv[0] === 'fc-list' && argv[2] === 'JetBrains Mono') return ok('', o.jetbrains ? 0 : 1)
- if (cmd === '/usr/bin/wl-paste -n -t text') {
+ if (argv[0] === 'sh' && argv[2] === WL_READ_SH && argv[3] === '/usr/bin/wl-paste') {
w.reads++
return ok(w.clipboard)
}
@@ -376,8 +405,8 @@ test('Linux on Wayland: the watcher runs wl-paste --watch after clip; picture ce
// /iui grab copies the text of the selection.
expect((await $.command.run({ command: 'iui', args: 'grab' } as any)).text).toBe('Intelligent UI: copied 35 chars (1 of 1 picture runs read).')
expect(w.copies).toEqual([COPIED])
- // pbpaste is never run on Linux.
- expect(w.ran.some(argv => argv[0] === 'pbpaste')).toBe(false)
+ // The macOS read is never run on Linux.
+ expect(w.ran.some(argv => argv.includes(READ_PL))).toBe(false)
// No shim: no env var set, no shim files, no ask reader.
expect(w.envSets).toEqual([])
expect(w.vars.PATH).toBe('/usr/local/bin:/usr/bin')