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: a click waits for the read of a newer outside copy; the same text again, a Wayland password copy, /iui off and /clear count

razorback161b1e10cb66cd
diff --git a/hooks/lib/clipboard.ts b/hooks/lib/clipboard.ts
index cc1e279..42cf229 100644
--- a/hooks/lib/clipboard.ts
+++ b/hooks/lib/clipboard.ts
@@ -56,9 +56,10 @@ export const READ_PL = [
// 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
-// marks as sensitive gives no line, so it is never read.
-export const WL_WATCH_SH = 'cat >/dev/null; [ "$CLIPBOARD_STATE" = sensitive ] || echo'
+// app that copied does not get a broken pipe. Each change gives a line, a copy
+// that a password manager marks as sensitive too (a newer copy): its read
+// (WL_READ_SH) sees the mark and never reads its text.
+export const WL_WATCH_SH = 'cat >/dev/null; echo'
// The X11 notifier: a line at its start, then one at each change of the
// CLIPBOARD selection. clipnotify 1.0.3+ prints them itself (-l); an older
// one does not know the flags, watches PRIMARY too, and exits at the first
diff --git a/hooks/register.tsx b/hooks/register.tsx
index 9de4ac4..5e2dc42 100644
--- a/hooks/register.tsx
+++ b/hooks/register.tsx
@@ -374,8 +374,13 @@ function clipChanged($: EngineInterface, count: number | null, first: boolean) {
return
}
clip.count = count
- if (!first) changed = ++asked
- if (!first) void readClipboard($).catch(() => undefined)
+ if (first) return
+ changed = ++asked
+ // Undecided until a read that began after it ends: a copy that claims waits for it.
+ let end = () => {}
+ undecided.set(changed, new Promise<void>(r => (end = r)))
+ unread.set(changed, end)
+ void readClipboard($).catch(() => undefined)
}
// Picture cells on the clipboard (a native copy: their session is not
@@ -390,10 +395,15 @@ function hintGrab($: EngineInterface, text: string) {
}
// The clipboard changed: one read (clipboardRead). A clipboard with no
-// placeholders, and our own write, are never touched. A new text that no
+// placeholders, and our own write, are never touched. A text that no
// recent $.ui.copy wrote (another app's copy, Claude Code's copy on select, a
-// password manager's: null) is a newer copy; a failed read is none. A change
-// while a read runs reads once more after it.
+// password manager's: null), even the same text again, is a newer copy; a
+// failed read is none. A change while a read runs reads once more after it.
+// A read decides the changes before it began (`unread`), failed or not.
+const unread = new Map<number, () => void>()
+function readsEnded(upTo: number) {
+ for (const [n, end] of unread) if (n <= upTo) (unread.delete(n), undecided.delete(n), end())
+}
async function readClipboard($: EngineInterface) {
if (clip.busy) {
clip.again = true
@@ -404,15 +414,21 @@ async function readClipboard($: EngineInterface) {
do {
clip.again = false
const n = changed
- const text = await clipboardRead($)
- if (text === undefined || text === clip.seen) continue
- clip.seen = text
- if (text === null || !copiedTexts.includes(text)) copies = Math.max(copies, n)
- if (text === null || text === clip.wrote || !hasPlaceholders(text)) continue
- hintGrab($, text)
+ try {
+ const text = await clipboardRead($)
+ if (text === undefined) continue
+ if (text === null || !isOwnChange(text, n)) copies = Math.max(copies, n)
+ if (text === clip.seen) continue
+ clip.seen = text
+ if (text === null || text === clip.wrote || !hasPlaceholders(text)) continue
+ hintGrab($, text)
+ } finally {
+ readsEnded(n)
+ }
} while (clip.again)
} finally {
clip.busy = false
+ readsEnded(Infinity)
}
}
@@ -430,8 +446,9 @@ function watchClipboard($: EngineInterface) {
}
// Intelligent UI off, or a /clear (the process goes on): the watcher again
-// with no clipboard part (no reads).
+// with no clipboard part (no reads), and no copy begun before it copies.
function stopClipboard($: EngineInterface) {
+ copies = ++asked
if (watchState()?.clip && !clip.none) watchFrame($, null)
}
@@ -456,16 +473,26 @@ async function updateState($: EngineInterface): Promise<UpdateState> {
// the clipboard once it has a text (`copies`: the newest claim). An older
// one that still reads its text when a newer one claimed copies nothing; a
// click or an up with nothing to copy claims nothing. `copiedTexts`: the texts of the
-// last 4 $.ui.copy calls (their changes, even read late, are no copy from outside).
+// last 4 $.ui.copy calls whose change the watcher has not read, each with `asked`
+// when it was made (its change, even read late, is no copy from outside).
let asked = 0
let copies = 0
// The number of the last clipboard change the watcher saw (taken when its line came).
let changed = 0
-const copiedTexts: string[] = []
+const copiedTexts: { text: string; at: number }[] = []
function noteCopied(text: string) {
- if (copiedTexts.at(-1) === text) return
- copiedTexts.push(text)
+ const own = { text, at: asked }
+ copiedTexts.push(own)
if (copiedTexts.length > 4) copiedTexts.shift()
+ return own
+}
+// Whether change n's text is an own write's: the change after the write takes it, once.
+function isOwnChange(text: string, n: number): boolean {
+ const i = copiedTexts.findIndex(own => own.text === text)
+ if (i < 0) return false
+ // A read of an older change that came late: the write's own change is still to come.
+ if (copiedTexts[i]!.at < n) copiedTexts.splice(i, 1)
+ return true
}
ownCopy.note = text => {
noteCopied(text)
@@ -475,13 +502,25 @@ ownCopy.note = text => {
// The mod's own write, noted here: a $.ui.copy made after an await does not
// pass the mod's own ui.copy hook. While it runs (`writing`), the hook passes it with no new claim.
const writing: string[] = []
+// Its change is not read again (clip.wrote, clip.seen); a write that fails leaves them as they were.
async function copyOwn($: EngineInterface, args: UiCopyArgs) {
- noteCopied(args.text)
+ const own = noteCopied(args.text)
+ const was = { wrote: clip.wrote, seen: clip.seen }
+ clip.wrote = args.text
+ clip.seen = args.text
writing.push(args.text)
+ let isCopied = false
try {
- return await copy($, args)
+ const copied = await copy($, args)
+ isCopied = copied.isCopied
+ return copied
} finally {
writing.splice(writing.indexOf(args.text), 1)
+ if (!isCopied) {
+ if (copiedTexts.includes(own)) copiedTexts.splice(copiedTexts.indexOf(own), 1)
+ if (clip.wrote === args.text) clip.wrote = was.wrote
+ if (clip.seen === args.text) clip.seen = was.seen
+ }
}
}
@@ -563,8 +602,6 @@ async function grab($: EngineInterface): Promise<string> {
} finally {
turn.done()
}
- clip.wrote = read.text
- clip.seen = read.text
const copied = await copyOwn($, { text: read.text })
return copied.isCopied
? `Intelligent UI: copied ${read.text.length} chars (${read.resolved} of ${read.runs} picture runs read${row ? `, row ${row}` : ''}).`
@@ -745,9 +782,6 @@ async function openTarget($: EngineInterface, target: Target, surface: RenderSur
async function copyTarget($: EngineInterface, target: Target, surface: RenderSurface, notOpened = false) {
const text = target.kind === 'web' ? target.href : target.kind === 'file' ? target.path : target.text
const name = target.kind === 'web' ? 'link' : target.kind === 'file' ? 'path' : target.kind === 'code' ? 'code' : 'command'
- // The clipboard change of this text is not read again.
- clip.wrote = text
- clip.seen = text
const copied = await copyOwn($, { text, surface })
const failed = notOpened ? `could not open the ${target.kind === 'web' ? 'link' : 'file'}` : ''
const done = failed ? `${failed}, so copied ${target.kind === 'web' ? 'it' : 'its path'}` : `copied the ${name}`
@@ -793,9 +827,6 @@ async function copySelection($: EngineInterface, d: Drawn & { job?: Job }, sel:
turn.done()
}
const read = performance.now() - t
- // The clipboard change of this text is not read again.
- clip.wrote = text
- clip.seen = text
const copied = await copyOwn($, { text, surface })
toast($, copied.isCopied ? `Intelligent UI: copied ${text.length} chars of text` : `Intelligent UI: the copy failed: ${copied.reason}`)
if (S.debug) void traceCopy($, text, performance.now() - t, read, probed)
@@ -905,8 +936,9 @@ export const register: Register = on => {
// one with placeholders whose words are read when a newer one came is refused.
on('ui.copy', async ($, e, next) => {
if (writing.includes(e.text)) return next(e)
- noteCopied(e.text)
+ // The text that goes on the clipboard is noted (copiedTexts), only it.
if (!hasPlaceholders(e.text) || !drawnAnswers.size) {
+ noteCopied(e.text)
copies = ++asked
return next(e)
}
@@ -919,7 +951,10 @@ export const register: Register = on => {
const read = await readCopy($, e.text, clip.rawRow)
await newerDecided(turn)
if (!(await isNewest($, turn))) return { value: { isCopied: false, reason: 'refused' } }
- if (!read.resolved) return next(e)
+ if (!read.resolved) {
+ noteCopied(e.text)
+ return next(e)
+ }
// The clipboard change of this write is not read again.
clip.wrote = read.text
clip.seen = read.text
diff --git a/tests/copy.test.ts b/tests/copy.test.ts
index 60c6a2f..c2a4315 100644
--- a/tests/copy.test.ts
+++ b/tests/copy.test.ts
@@ -645,7 +645,10 @@ function world(
holdOpens() {
w.openGate = new Promise<void>(r => (w.releaseOpens = r))
},
- readGate: null as Promise<void> | null, releaseReads: () => {},
+ // `lateReads`: a held read gives the clipboard when it goes on, not when it began.
+ readGate: null as Promise<void> | null, releaseReads: () => {}, lateReads: false,
+ // `copyFails`: each $.ui.copy fails and changes nothing.
+ copyFails: false,
holdReads() {
w.readGate = new Promise<void>(r => (w.releaseReads = r))
},
@@ -744,8 +747,9 @@ function world(
}
if (argv[0] === '/usr/bin/perl' && argv[2] === READ_PL) {
w.pastes++
- const { clipboard, secret } = w
+ let { clipboard, secret } = w
if (w.readGate) await w.readGate
+ if (w.lateReads) ({ clipboard, secret } = w)
// A read that failed (an error, the 2 s timeout).
if (w.readFails) return { deny: 'timed out' }
// A password manager's copy: exit 3, its text not read.
@@ -771,6 +775,7 @@ function world(
})
// The mod's write: its text on the clipboard, one change.
on('ui.copy', async ($: any, e: any) => {
+ if (w.copyFails) return { value: { isCopied: false, reason: 'boom' } }
w.copies.push(e.text)
w.foreign(e.text)
return { value: { isCopied: true } }
@@ -2562,3 +2567,142 @@ test('main screen with the watcher: a command button press is newer than a /iui
const said = await g
expect([said, w.copies]).toEqual(['Intelligent UI: a newer copy came first; this one copied nothing.', [pressed]])
})
+
+
+// The page ans-2 (one more line) whose words are held; a click on its link with alt (a copy).
+async function slowClick($: any, w: ReturnType<typeof world>, id = 'ans-2', text = `${TARGETS_MD}\n\nOne more line.`) {
+ w.hold()
+ const slow = await drawAnswer($, w, id, text)
+ await click(slow, 6, 3, { alt: true })
+ await settle(w)
+ return slow
+}
+
+test('a copy in another app made while a click reads its words is waited for when its read is slow: the click copies nothing', async ($, on) => {
+ const { w } = await drawTargets($, on)
+ await slowClick($, w)
+ w.holdReads()
+ w.foreign('copied in another app')
+ await settle(w)
+ // The words come first: the click waits for the read of the newer change.
+ w.release()
+ await settle(w)
+ expect(w.copies).toEqual([])
+ w.releaseReads()
+ await settle(w)
+ expect({ copies: w.copies, clip: w.clipboard }).toEqual({ copies: [], clip: 'copied in another app' })
+})
+
+test('a clipboard read that fails ends the wait: a click whose words are still read copies after it', async ($, on) => {
+ const { w } = await drawTargets($, on)
+ await slowClick($, w)
+ w.holdReads()
+ w.readFails = true
+ w.change()
+ await settle(w)
+ w.release()
+ await settle(w)
+ expect(w.copies).toEqual([])
+ w.releaseReads()
+ await settle(w)
+ expect({ copies: w.copies, clip: w.clipboard }).toEqual({ copies: ['https://example.com'], clip: 'https://example.com' })
+})
+
+test('the same text copied again is a newer copy: a password manager\'s copy twice, or another app\'s, while a click reads its words', async ($, on) => {
+ const { w } = await drawTargets($, on)
+ w.concealed('pw1')
+ await settle(w)
+ await slowClick($, w)
+ w.concealed('pw2')
+ await settle(w)
+ w.release()
+ await settle(w)
+ expect({ copies: w.copies, clip: w.clipboard }).toEqual({ copies: [], clip: 'pw2' })
+ w.foreign('X')
+ await settle(w)
+ await slowClick($, w, 'ans-3', `${TARGETS_MD}\n\nTwo more lines.\n\nHere.`)
+ w.foreign('X')
+ await settle(w)
+ w.release()
+ await settle(w)
+ expect({ copies: w.copies, clip: w.clipboard }).toEqual({ copies: [], clip: 'X' })
+})
+
+test('two copies in another app, the second while the read of the first runs (it gives the second text): a click between them copies nothing', async ($, on) => {
+ const { w } = await drawTargets($, on)
+ w.holdReads()
+ w.lateReads = true
+ w.foreign('A')
+ await settle(w)
+ await slowClick($, w)
+ w.foreign('B')
+ await settle(w)
+ w.releaseReads()
+ await settle(w)
+ w.release()
+ await settle(w)
+ expect({ copies: w.copies, clip: w.clipboard }).toEqual({ copies: [], clip: 'B' })
+})
+
+test('another app\'s copy of a text the mod copied before is a newer copy: a click whose words are still read copies nothing', async ($, on) => {
+ const { w, ui } = await drawTargets($, on)
+ await click(ui, 6, 3, { alt: true })
+ await settle(w)
+ expect(w.copies).toEqual(['https://example.com'])
+ await slowClick($, w)
+ w.foreign('https://example.com')
+ await settle(w)
+ w.release()
+ await settle(w)
+ expect({ copies: w.copies, clip: w.clipboard }).toEqual({ copies: ['https://example.com'], clip: 'https://example.com' })
+})
+
+test('a write that fails is no copy of the mod: another app\'s copy of its text is a newer copy', async ($, on) => {
+ const { w, ui } = await drawTargets($, on)
+ w.copyFails = true
+ await click(ui, 6, 3, { alt: true })
+ await settle(w)
+ expect(w.toasts.at(-1)).toBe('Intelligent UI: the copy failed: boom')
+ w.copyFails = false
+ await slowClick($, w)
+ w.foreign('https://example.com')
+ await settle(w)
+ w.release()
+ await settle(w)
+ expect({ copies: w.copies, clip: w.clipboard }).toEqual({ copies: [], clip: 'https://example.com' })
+})
+
+test('/iui off or a /clear while a click reads its words, or a link opens: neither copies, nor toasts a copy; a click after /iui on copies', async ($, on) => {
+ on('session.end', async ($: any, e: any) => ({ sessionId: e.sessionId }))
+ const { w, ui } = await drawTargets($, on)
+ await slowClick($, w)
+ // A link whose open fails late.
+ w.openFails = true
+ w.holdOpens()
+ await click(ui, 6, 3)
+ await settle(w)
+ await $.command.run({ command: 'iui', args: 'off' } as any)
+ await settle(w)
+ const toasts = w.toasts.length
+ w.release()
+ w.releaseOpens()
+ await settle(w)
+ // Off: no clipboard part, and a copy in another app is not overwritten.
+ w.foreign('copied in another app')
+ await settle(w)
+ expect({ copies: w.copies, clip: w.clipboard, toasts: w.toasts.slice(toasts) }).toEqual({
+ copies: [], clip: 'copied in another app', toasts: ['Intelligent UI: could not open the link'],
+ })
+ await $.command.run({ command: 'iui', args: 'on' } as any)
+ w.openFails = false
+ const slower = await slowClick($, w, 'ans-3', `${TARGETS_MD}\n\nTwo more lines.\n\nHere.`)
+ await $.session.end({ reason: 'clear', sessionId: 's1' } as any)
+ await settle(w)
+ w.release()
+ await settle(w)
+ expect(w.copies).toEqual([])
+ // Its words are there now: a new click copies.
+ await click(slower, 52, 4)
+ await settle(w)
+ expect({ copies: w.copies, clip: w.clipboard }).toEqual({ copies: ['ls -la'], clip: 'ls -la' })
+})
diff --git a/tests/linux.test.ts b/tests/linux.test.ts
index 4f5b313..15be7da 100644
--- a/tests/linux.test.ts
+++ b/tests/linux.test.ts
@@ -32,8 +32,8 @@ test('Wayland (not GNOME): wl-paste reads, and its --watch sees each change', ()
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.
- expect(WL_WATCH_SH).toBe('cat >/dev/null; [ "$CLIPBOARD_STATE" = sensitive ] || echo')
+ // The data goes to the end, and each change gives a line (a sensitive copy too).
+ expect(WL_WATCH_SH).toBe('cat >/dev/null; echo')
})
test('GNOME on Wayland (no data-control): the X11 tools through Xwayland come first, wl-paste last', () => {
@@ -294,7 +294,7 @@ function linuxWorld(on: any, o: { scheme?: number; noPortal?: boolean; env?: Rec
const ran: string[][] = []
const watchers: { argv: string[]; say: (line: string) => void; dead: boolean; n: number }[] = []
const w = {
- clock, files, ran, watchers, vars, envSets, clipboard: 'old', reads: 0, copies: [] as string[], toasts: [] as string[],
+ clock, files, ran, watchers, vars, envSets, clipboard: 'old', secret: false, reads: 0, copies: [] as string[], toasts: [] as string[],
selection: undefined as { text: string } | undefined,
copy(text: string) {
// A mouse copy of picture cells in fullscreen is this session's selection.
@@ -303,8 +303,17 @@ function linuxWorld(on: any, o: { scheme?: number; noPortal?: boolean; env?: Rec
},
foreign(text: string) {
w.clipboard = text
+ w.secret = false
for (const c of watchers) if (!c.dead && c.argv[3] === 'clip') c.say(`clip ${c.n++}`)
},
+ // A copy a password manager marks (its x-kde-passwordManagerHint target):
+ // wl-paste --watch runs the notifier with CLIPBOARD_STATE=sensitive.
+ sensitive(text: string) {
+ w.clipboard = text
+ w.secret = true
+ const says = (sh: string) => !sh.includes('"$CLIPBOARD_STATE" = sensitive ] ||')
+ for (const c of watchers) if (!c.dead && c.argv[3] === 'clip' && says(c.argv.at(-1)!)) c.say(`clip ${c.n++}`)
+ },
}
let pids = 7000
const killers = new Map<string, () => void>()
@@ -353,7 +362,8 @@ function linuxWorld(on: any, o: { scheme?: number; noPortal?: boolean; env?: Rec
if (argv[0] === 'fc-list' && argv[2] === 'JetBrains Mono') return ok('', o.jetbrains ? 0 : 1)
if (argv[0] === 'sh' && argv[2] === WL_READ_SH && argv[3] === '/usr/bin/wl-paste') {
w.reads++
- return ok(w.clipboard)
+ // The guard sees the target first: exit 3, no text.
+ return w.secret ? ok('', 3) : ok(w.clipboard)
}
return ok('', 1)
})
@@ -443,6 +453,20 @@ test('Linux on Wayland: the watcher runs wl-paste --watch after clip; picture ce
expect(w.watchers.map(c => c.dead)).toEqual([true, true])
})
+test('Linux on Wayland: a password manager\'s copy (sensitive) gives a line, a newer copy; its read sees the mark and gets no text', async ($, on) => {
+ const w = linuxWorld(on)
+ await $.command.run({ command: 'iui', args: '' } as any)
+ await drawAnswer($, w)
+ w.sensitive(COPY)
+ await w.clock.settle()
+ expect(w.reads).toBe(1)
+ expect(w.toasts).not.toContain(GRAB_HINT)
+ // /iui grab reads it again: no text either.
+ expect((await $.command.run({ command: 'iui', args: 'grab' } as any)).text).toBe('Intelligent UI: no mouse selection, and the clipboard can not be read (see /iui details).')
+ expect(w.reads).toBe(2)
+ expect(w.copies).toEqual([])
+})
+
test('Linux on Wayland, main screen: a copy of picture cells is not changed; /iui grab reads it with wl-paste and writes its text', async ($, on) => {
const w = linuxWorld(on)
await $.command.run({ command: 'iui', args: '' } as any)