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: grab and a ui.copy change wait for a newer click; outside copies counted from their change

razorback16df076134cbbf
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 9a43e1b..540b911 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,7 +6,7 @@ All releases of Intelligent UI for Claude Code (`cc-intelligent-ui`). Claude Cod
### Fixed
-- **The newest copy wins.** A click, a picture selection's up, `/iui grab` and the `ui.copy` change of picture cells each read their text first. An older one that was still reading wrote the clipboard over a newer copy. Now it writes nothing when a newer copy came: a newer click or up, a `$.ui.copy` (another plugin's, or the command button of a link row), Claude Code's own copy of a selection, or a copy in another app. A `ui.copy` change that lost its turn is refused. `/iui grab`, a click on no target and an up with no text copy nothing and cancel no other copy. An older copy waits for a newer click or up that still reads its text, so it never writes first and is then overwritten.
+- **The newest copy wins.** A click, a picture selection's up, `/iui grab` and the `ui.copy` change of picture cells each read their text first. An older one that was still reading wrote the clipboard over a newer copy. Now it writes nothing when a newer copy came: a newer click or up, a `$.ui.copy` (another plugin's, or the command button of a link row), Claude Code's own copy of a selection, or a copy in another app. A `ui.copy` change that lost its turn is refused. `/iui grab`, a click on no target and an up with no text copy nothing and cancel no other copy. An older copy (a click, an up, `/iui grab` or a `ui.copy` change) waits for a newer click or up that still reads its text, so it never writes first and is then overwritten. A copy in another app counts from the time the clipboard changed, not from the time the mod read it.
- **A password manager's copy is never read.** On macOS the mod reads the clipboard with a short `perl` script (PerlObjCBridge) in place of `pbpaste`, and stops at a copy with a concealed or transient type. On Linux, `xclip`, `wl-paste` and GTK look for the `x-kde-passwordManagerHint` target before and after the read. On Wayland, a copy marked sensitive was skipped already.
- **The code in an answer can read no other file.** Each compile of an answer or a plan had `/` as its Typst root, so a Typst block could read any file (`read`, `include`, `image`, `json`, `csv`), and `read("/dev/zero")` used all the memory. Now each compile runs in a root of its own, with only the template, the theme and the answer's images. The skill's `check.sh` does the same, and it stops with an error when its cache folder is a link or not yours. Pictures are the same as before.
- `/iui setup`, `/iui setup remove` and the setup question never write a shell start file that they cannot read (no permission, or too large). Before, such a file was replaced with only the Intelligent UI block. Now the mod changes no file and shows the line to add.
diff --git a/hooks/lib/draw.tsx b/hooks/lib/draw.tsx
index 1a4ba37..c6dfa75 100644
--- a/hooks/lib/draw.tsx
+++ b/hooks/lib/draw.tsx
@@ -6,7 +6,7 @@ import type { EngineInterface, RenderComponent, RenderSurface, RenderViewport, R
import type { IuiTheme } from '../../types'
import { BODY_PT, bulletOf, GRID_VERSION, GUTTER, LINK_FILES_KEPT, MARGIN_TOP, RESULTS_KEPT, TEMPLATE_VERSION } from './settings'
-import { INLINE_KEPT, inlined, keep, linkFiles, S, type Cell, type Look, type Metrics, type Result, type Room } from './state'
+import { INLINE_KEPT, inlined, keep, linkFiles, ownCopy, S, type Cell, type Look, type Metrics, type Result, type Room } from './state'
import { DEFAULT_GRID, gridFirstRow, type GridMetrics } from './grid'
import { FENCE, imagePathOf } from './markdown'
import { linksOf, type LinkItem } from './links'
@@ -317,6 +317,7 @@ export async function linksFor($: EngineInterface, text: string, base: string):
// Copies a command at a press of its row, with a toast.
async function copyCommand($: EngineInterface, text: string, surface: RenderSurface) {
+ ownCopy.note(text)
const copied = await copy($, { text, surface }).catch(() => null)
toast($, copied?.isCopied ? 'Copied' : `Could not copy${copied ? `: ${copied.reason}` : ''}`)
}
diff --git a/hooks/lib/state.ts b/hooks/lib/state.ts
index a999757..2c4cfce 100644
--- a/hooks/lib/state.ts
+++ b/hooks/lib/state.ts
@@ -299,6 +299,9 @@ export const writesLive = new Map<string, number>()
// probe's inputs; none when not known).
export const drawnAnswers = new Map<string, Drawn & { job?: Job }>()
export const DRAWN_KEPT = 64
+// The copy gate's hook for a mod copy no ui.copy hook sees (register.tsx sets it).
+export const ownCopy = { note: (_text: string) => {} }
+
// 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
diff --git a/hooks/register.tsx b/hooks/register.tsx
index becb17d..14bb1b4 100644
--- a/hooks/register.tsx
+++ b/hooks/register.tsx
@@ -24,7 +24,7 @@ import {
DEFAULT_THEME, gridText, heightText, IMAGE_MAX_COLUMNS, MARGIN_TOP, MAX_HEIGHT, MAX_WIDTH, MIN_HEIGHT, MIN_WIDTH, RESULTS_KEPT, TYPST_PROMPT,
SELECT_SINCE, selectText, typstHintOf, widthText,
} from './lib/settings'
-import { clip, DEFAULT_METRICS, drawnAnswers, editedPlans, keep, queue, refresh, running, S, settingsSet, subagentPlans, writesLive, type Env, type Job } from './lib/state'
+import { clip, DEFAULT_METRICS, drawnAnswers, editedPlans, keep, ownCopy, queue, refresh, running, S, settingsSet, subagentPlans, writesLive, type Env, type Job } from './lib/state'
import { beginEpoch } from './lib/epoch'
import { escapeControls, luminanceOf, modeLine, modeOfLuminance, parseOsc11, settingOf } from './lib/mode'
import { applyTheme, themeListing, userThemesOf } from './lib/themes'
@@ -299,6 +299,7 @@ function clipChanged($: EngineInterface, count: number | null, first: boolean) {
return
}
clip.count = count
+ if (!first) changed = ++asked
if (!first) void readClipboard($).catch(() => undefined)
}
@@ -327,10 +328,11 @@ async function readClipboard($: EngineInterface) {
try {
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 = ++asked
+ if (text === null || !copiedTexts.includes(text)) copies = Math.max(copies, n)
if (text === null || text === clip.wrote || !hasPlaceholders(text)) continue
hintGrab($, text)
} while (clip.again)
@@ -382,12 +384,18 @@ async function updateState($: EngineInterface): Promise<UpdateState> {
// last 4 $.ui.copy calls (their changes, even read late, are 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[] = []
function noteCopied(text: string) {
if (copiedTexts.at(-1) === text) return
copiedTexts.push(text)
if (copiedTexts.length > 4) copiedTexts.shift()
}
+ownCopy.note = text => {
+ noteCopied(text)
+ copies = ++asked
+}
// 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.
@@ -425,8 +433,11 @@ function takeTurn($: EngineInterface, native?: Promise<string>): Turn {
// A copy that has its text claims the clipboard: false when a newer one
// claimed. A newer one that does not know yet whether it copies is waited for.
-async function claim(turn: Turn): Promise<boolean> {
+async function newerDecided(turn: Turn) {
for (const [n, decided] of undecided) if (n > turn.n) await decided
+}
+async function claim(turn: Turn): Promise<boolean> {
+ await newerDecided(turn)
if (copies > turn.n) return false
copies = turn.n
return true
@@ -466,10 +477,17 @@ async function grab($: EngineInterface): Promise<string> {
clip.raw = raw
clip.rawRow = row
// Only a grab that copies takes a turn.
- const turn = claimNow($, Promise.resolve(nativeKey(selected)))
- const read = await readCopy($, raw, row)
- 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).`
+ const turn = takeTurn($, Promise.resolve(nativeKey(selected)))
+ let read: Awaited<ReturnType<typeof readCopy>>
+ try {
+ read = await readCopy($, raw, row)
+ if (!read.resolved) return `Intelligent UI: found ${read.runs} picture run(s) but could not read them (see /iui dump).`
+ const mine = await claim(turn)
+ turn.done()
+ if (!mine || !(await isNewest($, turn))) return 'Intelligent UI: a newer copy came first; this one copied nothing.'
+ } finally {
+ turn.done()
+ }
clip.wrote = read.text
clip.seen = read.text
const copied = await copyOwn($, { text: read.text })
@@ -784,6 +802,7 @@ export const register: Register = on => {
clip.raw = e.text
clip.rawRow = selected?.text === e.text ? selected.requestId : undefined
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)
// The clipboard change of this write is not read again.
diff --git a/tests/copy.test.ts b/tests/copy.test.ts
index 952e5fe..136931d 100644
--- a/tests/copy.test.ts
+++ b/tests/copy.test.ts
@@ -2316,3 +2316,187 @@ test('a password manager\'s copy is never read: no hint, no /iui grab, nothing i
await w.clock.settle()
expect(hints(w)).toBe(1)
})
+
+// ---- The copy gate: claims and waits ----
+
+const UNREADABLE = [cells(1, 0, 150), cells(2, 0, 150)].join('\n')
+const TCELLS = [cells(1, 0, 97), cells(2, 0, 97), cells(3, 0, 21)].join('\n')
+
+test('/iui grab that reads nothing (cells that fit no page) cancels no click whose words are still read', async ($, on) => {
+ const { w } = await drawTargets($, on)
+ // Unreadable cells on the clipboard before the click (their change seen first).
+ w.foreign(UNREADABLE)
+ await settle(w)
+ w.hold()
+ const slow = await drawAnswer($, w, 'ans-2', `${TARGETS_MD}\n\nOne more line.`)
+ await click(slow, 6, 3)
+ await settle(w)
+ expect(await grab($)).toContain('could not read them')
+ w.release()
+ await settle(w)
+ expect(w.copies).toEqual(['https://example.com'])
+})
+
+test('a /iui grab still reading copies nothing when a newer click will copy', async ($, on) => {
+ const { w } = await drawTargets($, on)
+ w.hold()
+ const older = await drawAnswer($, w, 'ans-2', `${TARGETS_MD}\n\nOne more line.`)
+ await drawAnswer($, w, 'ans-3', `${TARGETS_MD}\n\nAnother line.`)
+ // The grab's cells fit ans-3 (the newest): its probe is held.
+ w.selection = { text: TCELLS }
+ const g = grab($)
+ await settle(w)
+ await click(older, 6, 3)
+ await settle(w)
+ w.release()
+ await settle(w)
+ await g
+ await settle(w)
+ expect(w.clipboard).toBe('https://example.com')
+ expect(w.copies).toEqual(['https://example.com'])
+})
+
+test('a $.ui.copy of picture cells still reading is refused when a newer click will copy', { plugins: [COPIER] }, async ($, on) => {
+ const { w } = await drawTargets($, on)
+ w.hold()
+ const older = await drawAnswer($, w, 'ans-2', `${TARGETS_MD}\n\nOne more line.`)
+ await drawAnswer($, w, 'ans-3', `${TARGETS_MD}\n\nAnother line.`)
+ const cp = $.command.run({ command: 'cp', args: TCELLS } as any)
+ await settle(w)
+ await click(older, 6, 3)
+ await settle(w)
+ w.release()
+ await settle(w)
+ await cp
+ await settle(w)
+ expect(w.clipboard).toBe('https://example.com')
+ expect(w.copies).toEqual(['https://example.com'])
+})
+
+test('a copy in another app made before a click, read late by the watcher, does not cancel that newer click', async ($, on) => {
+ const { w } = await drawTargets($, on)
+ w.holdReads()
+ w.foreign('copied in another app')
+ await settle(w)
+ w.hold()
+ const slow = await drawAnswer($, w, 'ans-2', `${TARGETS_MD}\n\nOne more line.`)
+ await click(slow, 6, 3)
+ await settle(w)
+ w.releaseReads()
+ await settle(w)
+ w.release()
+ await settle(w)
+ expect(w.copies).toEqual(['https://example.com'])
+ expect(w.clipboard).toBe('https://example.com')
+})
+
+test('main screen: a command button press is newer than a /iui grab still reading (no watcher)', async ($, on) => {
+ const { w, ui } = await drawTargets($, on, { noBridge: true }, false)
+ const buttons = tree(await ui.drawn()).filter((n: any) => n.type === 'Button')
+ expect(buttons.length).toBe(2)
+ w.hold()
+ await drawAnswer($, w, 'ans-2', `${TARGETS_MD}\n\nOne more line.`, false)
+ w.selection = { text: TCELLS }
+ const g = grab($)
+ await settle(w)
+ await ui.press({ key: buttons[0].props.key })
+ await settle(w)
+ const pressed = w.copies.at(-1)
+ w.release()
+ await settle(w)
+ const said = await g
+ expect([said, w.copies]).toEqual(['Intelligent UI: a newer copy came first; this one copied nothing.', [pressed]])
+})
+
+test('three clicks: the oldest on a ready page copies at once; of two that still read, only the newer one with a target copies', async ($, on) => {
+ const { w, ui } = await drawTargets($, on)
+ await hover(ui, 52, 4)
+ await settle(w)
+ w.hold()
+ const mid = await drawAnswer($, w, 'ans-2', `${TARGETS_MD}\n\nOne more line.`)
+ const newest = await drawAnswer($, w, 'ans-3', `${TARGETS_MD}\n\nAnother line.`)
+ await click(ui, 52, 4)
+ await settle(w)
+ await click(mid, 1, 3)
+ await click(newest, 6, 3)
+ await settle(w)
+ w.release()
+ await settle(w)
+ expect(w.copies).toEqual(['ls -la', 'https://example.com'])
+})
+
+test('three clicks that still read: the middle one with a target copies; the oldest waits and never writes', async ($, on) => {
+ const { w } = await drawTargets($, on)
+ w.hold()
+ const a = await drawAnswer($, w, 'ans-2', `${TARGETS_MD}\n\nOne more line.`)
+ const b = await drawAnswer($, w, 'ans-3', `${TARGETS_MD}\n\nAnother line.`)
+ const c = await drawAnswer($, w, 'ans-4', `${TARGETS_MD}\n\nThird line.`)
+ await click(a, 6, 3)
+ await click(b, 52, 4)
+ await click(c, 1, 3)
+ await settle(w)
+ w.release()
+ await settle(w)
+ expect(w.copies).toEqual(['ls -la'])
+})
+
+test('a /iui grab whose words come first waits for a newer click that still reads, then copies nothing', async ($, on) => {
+ const { w } = await drawTargets($, on)
+ w.hold()
+ await drawAnswer($, w, 'ans-3', `${TARGETS_MD}\n\nAnother line.`)
+ w.selection = { text: TCELLS }
+ let said: any = 'pending'
+ const g = grab($).then(t => (said = t))
+ await settle(w)
+ const first = w.release
+ w.hold()
+ const newer = await drawAnswer($, w, 'ans-4', `${TARGETS_MD}\n\nThird line.`)
+ await click(newer, 6, 3)
+ await settle(w)
+ first()
+ await settle(w)
+ const mid = [said, [...w.copies]]
+ w.release()
+ await settle(w)
+ await g
+ expect(w.clipboard).toBe('https://example.com')
+ expect({ mid, end: w.copies, said }).toEqual({ mid: ['pending', []], end: ['https://example.com'], said: 'Intelligent UI: a newer copy came first; this one copied nothing.' })
+})
+
+test('a $.ui.copy of picture cells whose words come first waits for a newer click that still reads, then is refused', { plugins: [COPIER] }, async ($, on) => {
+ const { w } = await drawTargets($, on)
+ w.hold()
+ await drawAnswer($, w, 'ans-3', `${TARGETS_MD}\n\nAnother line.`)
+ const cp = $.command.run({ command: 'cp', args: TCELLS } as any)
+ await settle(w)
+ const first = w.release
+ w.hold()
+ const newer = await drawAnswer($, w, 'ans-4', `${TARGETS_MD}\n\nThird line.`)
+ await click(newer, 6, 3)
+ await settle(w)
+ first()
+ await settle(w)
+ const mid = [...w.copies]
+ w.release()
+ await settle(w)
+ await cp
+ expect(w.clipboard).toBe('https://example.com')
+ expect({ mid, end: w.copies }).toEqual({ mid: [], end: ['https://example.com'] })
+})
+
+test('main screen with the watcher: a command button press is newer than a /iui grab still reading', async ($, on) => {
+ const { w, ui } = await drawTargets($, on, {}, false)
+ const buttons = tree(await ui.drawn()).filter((n: any) => n.type === 'Button')
+ w.hold()
+ await drawAnswer($, w, 'ans-2', `${TARGETS_MD}\n\nOne more line.`, false)
+ w.selection = { text: TCELLS }
+ const g = grab($)
+ await settle(w)
+ await ui.press({ key: buttons[0].props.key })
+ await settle(w)
+ const pressed = w.copies.at(-1)
+ w.release()
+ await settle(w)
+ const said = await g
+ expect([said, w.copies]).toEqual(['Intelligent UI: a newer copy came first; this one copied nothing.', [pressed]])
+})