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: one perl watcher for resize and clipboard events; probe on demand
razorback16340eeb839d41
diff --git a/docs/development.md b/docs/development.mdindex ef82312..b251e12 100644--- a/docs/development.md+++ b/docs/development.md@@ -21,7 +21,7 @@ Set `IUI_DEBUG=1` before you start Claude Code. The mod then writes trace lines## Module layout-The hooks module is `hooks/register.tsx`. It connects the hooks to the modules in `hooks/lib/`. Each module has one topic, for example `markdown.ts` (blocks and segments), `mode.ts` (light or dark), `typst.ts` (compile), `draw.tsx` (the pages of an answer), `answer.ts` (one text through the compile and cache steps), `plan.tsx` (the plan approval question and the plan rows), `copy.ts` (the text under a mouse selection of pictures) and `probe.ts` (the drawn pages and the probe that finds their words). The values that change are in one object, `S`, in `state.ts`. The tests import from `hooks/register.tsx`, which exports the names that they use.+The hooks module is `hooks/register.tsx`. It connects the hooks to the modules in `hooks/lib/`. Each module has one topic, for example `markdown.ts` (blocks and segments), `mode.ts` (light or dark), `typst.ts` (compile), `draw.tsx` (the pages of an answer), `answer.ts` (one text through the compile and cache steps), `plan.tsx` (the plan approval question and the plan rows), `frame.ts` (the terminal size and the watcher process, which also reports the clipboard changes), `copy.ts` (the text under a mouse selection of pictures) and `probe.ts` (the drawn pages, and the words of a page that a copy reads, kept in memory). The values that change are in one object, `S`, in `state.ts`. The tests import from `hooks/register.tsx`, which exports the names that they use.The Typst template is `render/md.typ`. The themes are in `render/themes/` (refer to [`render/themes/README.md`](../render/themes/README.md)). The vendored Typst packages are in `render/packages/preview/`.diff --git a/docs/how-it-works.md b/docs/how-it-works.mdindex 904e2a1..f4920af 100644--- a/docs/how-it-works.md+++ b/docs/how-it-works.md@@ -11,7 +11,7 @@5. If a compile fails (a bad Typst block or an unknown LaTeX command), the mod compiles once more in safe mode: Typst blocks and math show as code. A dim line under the picture names the error. If that also fails, the normal text shows.6. Pictures are kept in `${TMPDIR}/intelligent-ui-<uid>/`. Folders older than 2 days are deleted at start. The drawing space of each answer at its first compile is kept in `~/.cache/intelligent-ui/designs`, so that its Typst drawings keep the same share of the screen in later sessions.7. The plan: a `ui.render` hook on the ExitPlanMode `ToolUse` row draws the plan through the same steps. Claude Code shows that row above the approval question. The approved result row then shows only its header, so the plan does not show two times. A `tool.call` hook on ExitPlanMode asks the mod's question (`$.ui.ask`) before Claude Code asks for permission. Then a `classic.PermissionRequest` hook gives the answer to Claude Code at once, so the Claude Code dialog does not show. For an approval, the hook sends the plan (`updatedInput`) and the new permission mode (`setMode`). For the person's text, the `tool.call` hook refuses the call with that text.-8. Copy: each compile also writes `probe.json` beside the pages. It has the same Typst inputs as the PNG compile, plus `probe=1`. It does not start a process. The probe (`typst query` on the same template with `probe=1`) gives the position of each word and each code line. It runs when a copy needs the positions, or before: one probe at a time, only when no compile runs or waits and no new size is in progress. A new compile stops it. The mod keeps the positions in `positions.json` beside the pages. The PNGs do not change. On macOS, a timer reads the mouse selection (`$.ui.selection`) and then the clipboard (`pbpaste`). It runs only while the mod is on and has drawn a picture in this session. A picture cell holds its row and its column (kitty placeholder U+10EEEE plus two combining marks). The mod finds the drawn page that has these rows, at the size that it is drawn, takes the words in the selected cells, and writes the text with `$.ui.copy`. A `ui.copy` hook also changes a copy with picture cells to the text.+8. Copy: one long-lived `perl` process watches the terminal size (at each SIGWINCH) and, on macOS, the clipboard. For the clipboard, it uses `/usr/bin/perl` with Apple's PerlObjCBridge and reads the change counter of the clipboard (`NSPasteboard changeCount`) every 0.3 s. This read is in the process and starts no other process (approximately 0.05% of one CPU core). The clipboard part starts only while the mod is on and after the mod drew its first picture in this session; then the mod starts the process again with the clipboard part (and again without it after `/iui off`). When the counter changes, the mod reads the clipboard one time (`pbpaste`). The first counter after a start is not a change, so an old clipboard is not copied. A picture cell holds its row and its column (kitty placeholder U+10EEEE plus two combining marks). The mod finds the drawn page that has these rows, at the size that it is drawn. Then it finds the position of each word on that page: it runs the probe (`typst query` on the same template, with the same inputs as the PNG compile, plus `probe=1` and `page=<n>`) for the selected pages only. The mod keeps the positions of the last 64 pages in memory. It writes nothing to disk for this, and the PNGs do not change. The mod takes the words in the selected cells. Immediately before it writes the text with `$.ui.copy`, it reads the clipboard again. If the clipboard has a newer copy, the mod does not write over it, and it reads that copy next. If the process stops, the mod starts it again after 1 s (3 times at most). At `/clear` or a resume, the process continues without the clipboard part. At other session ends (for example `/exit`), the mod stops the process and does not start a new one. A `ui.copy` hook also changes a copy with picture cells to the text.## How `auto` is resolveddiff --git a/docs/limitations.md b/docs/limitations.mdindex 2176151..da3e622 100644--- a/docs/limitations.md+++ b/docs/limitations.md@@ -3,13 +3,13 @@← Back to the [README](../README.md)- **Copying text from a picture** (refer to [Copy text from a picture](usage.md#copy-text-from-a-picture)) has these limits:- - The automatic copy works only on macOS, and not over ssh (`pbpaste` reads the clipboard of the computer that runs Claude Code). On other systems, the clipboard keeps the picture cells (U+10EEEE plus combining marks), and a paste gives strange characters. Use `/iui grab`, Claude Code's `/copy` (the last answer as Markdown, `/copy 2` for the one before it), or turn the mod off (`/iui off`) to select text.+ - The automatic copy works only on macOS, and not over ssh (`pbpaste` reads the clipboard of the computer that runs Claude Code). It also needs `/usr/bin/perl` with Apple's PerlObjCBridge (macOS has it), which reads the change counter of the clipboard. If the bridge does not load, the automatic copy is off: the mod does not read the clipboard at intervals in its place. `/iui details` shows the state on the line `Auto copy:`. When the automatic copy is off, the clipboard keeps the picture cells (U+10EEEE plus combining marks), and a paste gives strange characters. Use `/iui grab`, Claude Code's `/copy` (the last answer as Markdown, `/copy 2` for the one before it), or turn the mod off (`/iui off`) to select text.- The mod copies whole words. It copies a word when the selection covers the middle of the word. In a code block, in a long word (30 characters or more, for example a path or a URL) and in CJK text, it copies each character whose middle is in the selection.- The mod does not copy math, the text in an image, or the text in a Typst drawing.- The cells do not identify the answer. The mod uses the answer of the selected row if it knows it, else the newest answer whose pages fit the selection. A selection in one page of a long answer fits each page that is tall enough, and the mod uses the first one. Thus the text can come from a different page or an older answer of the same width. `/iui dump` shows the page that the mod used.- The mod knows only the last 64 answers, plans or files that it drew in this session.- With two Claude Code sessions on one computer, a session that has no selection can change a copy from the other session, with the text of its own picture.- - To stop the clipboard write on select, set `copyOnSelect` to `false` in `/config`. Then the mod does not copy a selection either. It changes only a clipboard that has picture cells (for example, after a copy with a key).+ - To stop the clipboard write on select, set `copyOnSelect` to `false` in `/config`. Then the mod does not copy a selection either, because it acts only when the clipboard changes. It changes only a clipboard that has picture cells (for example, after a copy with a key).- **Search does not find text in a picture.**- **While Claude writes**, the block is hidden, and Claude Code's spinner shows the progress. When the block is final, its picture shows after the compile (0.15–0.6 s). A long answer shows only when it is done. If the picture is not ready 2 s after the block is final, the normal text shows until the picture is ready. If the compile fails, the normal text stays. An earlier answer that is not in the cache (for example, after a resume) is blank for up to 1 s, then shows as text until its picture is ready.- **Short summaries** between tool calls stay as text.diff --git a/docs/usage.md b/docs/usage.mdindex 3f9ce04..658d9b1 100644--- a/docs/usage.md+++ b/docs/usage.md@@ -34,7 +34,7 @@ Intelligent UI draws Claude's answers as rendered Markdown pictures. Only the dr| Command | What it does ||---|---|| `/iui` | Shows the state, the theme, the text size, the width and the image height, and a problem that keeps pictures away |-| `/iui details` | Shows all that the mod found: where the mode comes from, the terminal font, the Typst path and why the terminal can or cannot show pictures |+| `/iui details` | Shows all that the mod found: where the mode comes from, the terminal font, the Typst path, why the terminal can or cannot show pictures, and if the automatic copy is on (`Auto copy:`) || `/iui on` / `off` | Turns the pictures on or off (kept for later sessions) || `/iui setup` / `setup remove` | iTerm2: adds or removes the shell line that turns pictures on (then close the tab and open a new one) || `/iui size <80–200>` | Text size in percent. 100 is the same visual size as your terminal text. |@@ -53,9 +53,9 @@ Intelligent UI draws Claude's answers as rendered Markdown pictures. Only the dr## Copy text from a picture-Select the text in a picture (an answer, a plan or a Markdown file that Claude sent) with the mouse, as you do with normal text. The selection puts picture cells on the clipboard. On macOS, while the mod is on and has drawn a picture in this session, the mod reads the mouse selection and the clipboard every 0.3 s. When they have picture cells, the mod puts the text under your selection on the clipboard, and a toast shows the number of characters. In fullscreen mode, if this session has a selection, the mod changes the clipboard only when the clipboard holds that selection. Thus a copy from a different Claude Code session usually stays as it is. Wait approximately 0.3 s after you select, then paste. The mod does not change a clipboard that has no picture cells.+Select the text in a picture (an answer, a plan or a Markdown file that Claude sent) with the mouse, as you do with normal text. The selection puts picture cells on the clipboard. On macOS, while the mod is on and has drawn a picture in this session, the mod sees each change of the clipboard (in 0.3 s or less). When the clipboard has picture cells, the mod puts the text under your selection on the clipboard, and a toast shows the number of characters. Wait for this toast, then paste. In fullscreen mode, if this session has a selection, the mod changes the clipboard only when the clipboard holds that selection. Thus a copy from a different Claude Code session usually stays as it is. The mod does not change a clipboard that has no picture cells.-The mod finds the position of each word when a copy needs it, or before, when no picture compiles. The first copy from a picture can thus take a short time more.+The mod finds the position of each word on a page when you copy from that page for the first time. This takes 0.15–0.5 s, and more (2–3 s) for a page with a large Typst drawing. If it takes more than 0.15 s, a toast shows "reading the picture". The mod keeps the positions in memory, so the next copy from the same page is fast.If the clipboard did not change, use `/iui grab`. It reads the last mouse selection of Claude Code (fullscreen mode only) and copies its text. If the copied text is not correct, `/iui dump` shows the cells that the mod found and the page that it used. It also writes all of this to `copy-debug.json` in the cache folder.diff --git a/hooks/lib/answer.ts b/hooks/lib/answer.tsindex 66eab93..85cbf47 100644--- a/hooks/lib/answer.ts+++ b/hooks/lib/answer.ts@@ -144,7 +144,9 @@ export async function pagesOf($: EngineInterface, o: PagesInput): Promise<DrawintouchLater($, `${env.cache}/${key}`)}forget(id)- keep(lastKey, id, { key, textHash }, RESULTS_KEPT)+ // Its Job as it draws, for the probe of a copy: no text (the probe reads+ // doc.json), and its env as now (a font read later changes the env).+ keep(lastKey, id, { key, textHash, job: { ...job, text: '', env: { ...env } } }, RESULTS_KEPT)return withBytes($, env, got)}// Live: its text streams (inside a request we saw, or changing since wediff --git a/hooks/lib/copy.ts b/hooks/lib/copy.tsindex f9617f6..626547d 100644--- a/hooks/lib/copy.ts+++ b/hooks/lib/copy.ts@@ -8,8 +8,8 @@// runs of (row, columns) per picture; positionsOf turns the template's probe// marks (render/md.typ, `<mdpos>`) into word boxes in PNG pixels; pickPages// says which drawn page each run is; textOfRun reads the words under a run.-// The drawn pages and the probe runs are in probe.ts; the clipboard watcher-// and the commands are in register.tsx.+// The drawn pages and the probe of a page are in probe.ts; the clipboard+// watcher (its change counts) and the commands are in register.tsx.// kitty's rowcolumn-diacritics.txt: 297 combining marks; mark i means row or// column i. (The same table is in Claude Code's binary.)@@ -140,7 +140,7 @@ export type Item = { i: number; text: string; x0: number; y0: number; x1: number// A block: paragraph, heading, code, quote, cell (`cx` its column), item// (`prefix`); `first` its first item.export type TextBlock = { kind: string; prefix: string; cx?: number; first: number }-// positions.json: by page (0-based: PNG page N+1).+// A probe's words by page (0-based: PNG page N+1), and its blocks.export type Positions = { ppi: number; blocks: TextBlock[]; pages: Item[][] }const round = (n: number) => Math.round(n * 100) / 100diff --git a/hooks/lib/env.ts b/hooks/lib/env.tsindex a4614ff..bf400b0 100644--- a/hooks/lib/env.ts+++ b/hooks/lib/env.ts@@ -58,7 +58,6 @@ export function setUp($: EngineInterface): Promise<Env> {const raw = rows.find(row => row.key === 'theme')?.valueS.settingRaw = typeof raw === 'string' ? raw : ''S.setting = settingOf(raw)- S.copyOnSelect = rows.find(row => row.key === 'copyOnSelect')?.value !== falseS.hostOs = os.trim()S.termProgram = programS.termName = termdiff --git a/hooks/lib/epoch.ts b/hooks/lib/epoch.tsindex 674ecaf..fc31d3a 100644--- a/hooks/lib/epoch.ts+++ b/hooks/lib/epoch.ts@@ -3,14 +3,12 @@// target, and its pictures swap in all at once: a job of the open epoch that// ends does not redraw; the epoch commits (S.shown = S.frame, with the// height setting of the target, one redraw) when its jobs on screen are done. A burst (a drag not quiet yet) holds the-// jobs and the commit. An epoch begun stops the probe ahead (probe.ts); a-// commit, or a burst's end, arms it again.+// jobs and the commit.import type { EngineInterface } from 'claude-code'import { COMMIT_MAX_MS, COMMIT_MIN_MS } from './settings'import { converting, epochOpen, queue, refresh, running, S, type Frame, type Job } from './state'import { traceDebug } from './log'-import { probeLater, stopProbe } from './probe'// The open epoch: `ready` once COMMIT_MIN_MS passed with no new activity// (a row drawn, a job enqueued: extendEpoch), `overdue` once COMMIT_MAX_MS@@ -38,7 +36,6 @@ export function beginEpoch($: EngineInterface, frame?: Frame | null) {} catch {}}queue.length = 0- stopProbe()const target = frame ?? S.frameif (target) S.frame = { ...target }const epoch = ++S.epoch@@ -95,7 +92,6 @@ export function releaseJobs($: EngineInterface) {if (S.missed && !epochOpen()) refresh($)S.missed = falsemaybeCommit($)- probeLater($)}// A job ended (its result is stored): during a burst it is noted; in an open@@ -127,5 +123,4 @@ function maybeCommit($: EngineInterface) {S.shownHeight = S.heightS.shownEpoch = S.epochrefresh($)- probeLater($)}diff --git a/hooks/lib/frame.ts b/hooks/lib/frame.tsindex de1a047..416b5e0 100644--- a/hooks/lib/frame.ts+++ b/hooks/lib/frame.ts@@ -1,6 +1,7 @@// The Frame: the terminal's columns, rows and cell, the one source of truth// for every size. A small watcher prints the tty size (TIOCGWINSZ) at each-// SIGWINCH that changed it; the render hooks note the viewport (the+// SIGWINCH that changed it (and, on macOS once a picture is drawn, the+// clipboard's change count: register.tsx); the render hooks note the viewport (the// transcript can be narrower than the tty). Both restart one quiet timer:// during a burst no job starts, and once it is quiet one tty read settles// it. A changed Frame begins an epoch (epoch.ts), so a drag or a font size@@ -12,7 +13,7 @@ import { DEFAULT_METRICS, S, type Frame, type Metrics } from './state'import { beginEpoch, holdJobs, releaseJobs } from './epoch'import { pump } from './stream'import { columnsFor, sizeOf } from './terminal'-import { CELL_SH, FRAME_PL, termFontOf } from './host'+import { CELL_SH, perlFor, termFontOf, WATCH_PL } from './host'import { measureFonts } from './typst'export type { Cell, Frame } from './state'@@ -20,15 +21,28 @@ export type { Cell, Frame } from './state'// The viewport a render hook gives: its columns and rows.export type View = { columns: number; rows: number }-// One watcher line `rows cols xpixel ypixel` as a Frame; null when it is not-// 4 whole numbers or its cell can not be right (the rule of sizeOf: no-// pixels, or a cell under 4 or over 64 px wide).+// One tty size `rows cols xpixel ypixel` (a read, a watcher's size line) as+// a Frame; null when it is not 4 whole numbers or its cell can not be right+// (the rule of sizeOf: no pixels, or a cell under 4 or over 64 px wide).export function frameOfLine(line: string): Frame | null {if (!/^\d+ \d+ \d+ \d+$/.test(line.trim())) return nullconst size = sizeOf(line)return size?.cell ? { columns: size.columns, rows: size.rows, cell: size.cell } : null}+// One watcher line (WATCH_PL): `pid <n>`, `size <rows> <cols> <xpixel>+// <ypixel>` (a Frame, null when bad: frameOfLine), `clip <count>` or `clip+// none` (count null: no PerlObjCBridge). Null for any other line.+export type WatchLine = { pid: string } | { size: Frame | null } | { clip: number | null }+export function watchLineOf(line: string): WatchLine | null {+ const m = /^(pid|size|clip) (.*)$/.exec(line.trim())+ if (!m) return null+ const [, tag, value] = m as unknown as [string, string, string]+ if (tag === 'size') return { size: frameOfLine(value) }+ if (/^\d+$/.test(value)) return tag === 'pid' ? { pid: value } : { clip: Number(value) }+ return tag === 'clip' && value === 'none' ? { clip: null } : null+}+// What changed from `a` to `b`: the cell (a font size change), else the// columns, else the rows. No `a` (the first read) is a cell change.export function frameChange(a: Frame | null, b: Frame): 'none' | 'cell' | 'columns' | 'rows' {@@ -184,27 +198,101 @@ export function noteView($: EngineInterface, view: View) {else if (counts) burst($)}-// The watcher (started once per load: a hot reload kills the child with the-// old module).-let watching = false+// The watcher's child now (one at a time): whether it reads the clipboard,+// whether it ended (`final`: with no tty and no bridge, or it could not+// start; never again), and its stop (a kill by its PID; its later lines are+// dropped). A hot reload kills the child with the old module. Where the+// clip lines go (register.tsx): a change count, or null for `clip none`,+// and whether it is the first line of its child (the count at its start).+let watcher: { clip: boolean; ended: boolean; final?: boolean; stop: () => void } | null = null+let clipTo: ((count: number | null, first: boolean) => void) | null = null++// The watcher now, for /iui details: null when none was started.+export const watchState = (): { clip: boolean; ended: boolean } | null => (watcher ? { clip: watcher.clip, ended: watcher.ended } : null)-// Starts the Frame watcher: one long-lived child (the engine kills it when-// the module unloads). When it can not start, or it ends, nothing takes its-// place: a viewport change still reads the tty once it is quiet.-export function watchFrame($: EngineInterface) {- if (watching) return- watching = true+// The children that ended on their own and were started again, at most+// WATCH_RESTARTS per load: a perl that dies at once is not started in a loop.+let restarts = 0+export const WATCH_RESTARTS = 3+export const WATCH_RESTART_MS = 1000++// Starts the watcher (setUp: no `clip`, the clipboard part as it is), or+// starts it again when the clipboard part turns on (`clip`: where its lines+// go) or off (null): the arguments of a child are fixed at its start. The+// old child is stopped first; the new one prints the size again (the value+// known: no burst, no epoch). A clip child that ends on its own is started+// again (WATCH_RESTARTS times at most), and so is any child that ended, at+// the next call that wants it; until then a viewport change still reads+// the tty once it is quiet. True when a child was started.+export function watchFrame($: EngineInterface, clip?: ((count: number | null, first: boolean) => void) | null): boolean {+ if (clip !== undefined) clipTo = clip+ const isClip = !!clipTo+ // Nothing to change: the child runs as wanted, or none runs (setUp did+ // not start one) and the clipboard part is off.+ if (watcher && watcher.clip === isClip) {+ if (!watcher.ended || watcher.final || restarts >= WATCH_RESTARTS) return false+ restarts+++ }+ if (!watcher && clip !== undefined && !isClip) return false+ watcher?.stop()+ // The stop: a kill once its PID is known (its first line).+ let pid = ''+ let stopped = false+ let counted = false+ const kill = () => {+ if (stopped && pid) void Promise.resolve($.process.run(['kill', pid], { timeoutMs: 5000 })).catch(() => undefined)+ }+ const stop = () => {+ if (stopped) return+ stopped = true+ kill()+ }+ const me: NonNullable<typeof watcher> = { clip: isClip, ended: false, stop }+ watcher = metry {- void followWatcher($.process.spawn({ argv: ['perl', '-e', FRAME_PL] }), f => noteTty($, f))- } catch {}+ const child = $.process.spawn({ argv: [perlFor(S.hostOs === 'Darwin'), '-e', WATCH_PL, ...(isClip ? ['clip'] : [])] })+ void followWatcher(child, line => {+ if ('pid' in line) {+ pid = line.pid+ kill()+ } else if (stopped) return+ else if ('size' in line) noteTty($, line.size)+ else if (me.clip) {+ clipTo?.(line.clip, !counted)+ counted = true+ }+ }).then(got => {+ me.ended = true+ if (got === 'no tty') me.final = true+ // A clip child that ended on its own (no stop): again after+ // WATCH_RESTART_MS, while it is still the child now.+ if (stopped || me.final || !me.clip) return+ try {+ $.clock.after(WATCH_RESTART_MS, () => {+ if (watcher === me) watchFrame($)+ })+ } catch {}+ }).catch(() => undefined)+ } catch {+ me.ended = me.final = true+ }+ return true+}++// The session ends (not a /clear): the child is killed and none takes its+// place.+export function stopWatch() {+ watcher?.stop()+ if (watcher) watcher = { clip: watcher.clip, ended: true, stop: () => {} }+ restarts = WATCH_RESTARTS}-// Reads the watcher's pieces as lines, each to `note` as a Frame (null when-// bad), until it ends: 'no tty' when it exits 1, else 'failed' (it did not-// start: the first pull rejects; or it ended in another way).+// Reads the watcher's pieces as lines, each to `note` (other lines are+// dropped), until it ends: 'no tty' when it exits 1, else 'failed' (it did+// not start: the first pull rejects; or it ended in another way).export async function followWatcher(child: AsyncIterator<{ stream: 'stdout' | 'stderr'; text: string }, { code: number | null } | undefined>,- note: (frame: Frame | null) => void,+ note: (line: WatchLine) => void,): Promise<'no tty' | 'failed'> {const lines = lineSplitter()try {@@ -212,7 +300,10 @@ export async function followWatcher(const got = await child.next()if (got.done) return got.value?.code === 1 ? 'no tty' : 'failed'if (got.value.stream !== 'stdout') continue- for (const line of lines(got.value.text)) note(frameOfLine(line))+ for (const line of lines(got.value.text)) {+ const read = watchLineOf(line)+ if (read) note(read)+ }}} catch {return 'failed'diff --git a/hooks/lib/host.ts b/hooks/lib/host.tsindex dc0b471..a278056 100644--- a/hooks/lib/host.ts+++ b/hooks/lib/host.ts@@ -1,10 +1,10 @@// Work on the host: the shell snippets Intelligent UI runs, the tty size (one-// read, and the Frame watcher's loop), the terminal's font, and light or dark for auto (the terminal's settings, then+// read, and the watcher's loop: the size and the clipboard), the terminal's font, and light or dark for auto (the terminal's settings, then// COLORFGBG, then the OS appearance), read again by a poll.import type { EngineInterface } from 'claude-code'import type { IuiTheme } from '../../types'-import { HOST_CHECK_MS, HOST_POLL_MS, MODES } from './settings'+import { CLIP_WAKE_MS, HOST_CHECK_MS, HOST_POLL_MS, MODES } from './settings'import { S } from './state'import { beginEpoch } from './epoch'import { luminanceOf, modeOfColorFgBg, modeOfGnome, modeOfLuminance, modeOfMacAppearance, parseOsc11, resolveMode, type HostMode } from './mode'@@ -18,32 +18,54 @@ import { firstLine } from './markdown'// One tty size read: `rows cols xpixel ypixel` (TIOCGWINSZ); exit 1 with no tty.export const CELL_SH = `perl -e 'open(T, "</dev/tty") or exit 1; my $w = " " x 8; ioctl(T, ($^O eq "darwin" ? 0x40087468 : 0x5413), $w) or exit 1; print join(" ", unpack("S4", $w))'`-// The Frame watcher (frame.ts): prints a line `rows cols xpixel ypixel`-// at start and at each change. It sleeps in sigsuspend with SIGWINCH and-// SIGALRM blocked outside it, so a SIGWINCH that comes while it reads is-// kept for the next sleep (never lost), and it does no work between-// signals: no poll. Each 10 s an alarm wakes it to see that its parent-// still runs. Exit 1 when /dev/tty does not open; exit 0 when the parent-// dies (its parent id changes) or stdout breaks.-export const FRAME_PL = [- 'use POSIX (); use Config;',+// The watcher (frame.ts): one long-lived perl for the tty size and the+// clipboard. It prints `pid <n>` first, then a line `size rows cols xpixel+// ypixel` at start and at each change. With the argument `clip` (macOS+// only: /usr/bin/perl, which has PerlObjCBridge) it also prints `clip <n>`,+// the clipboard's change count, at start and at each change, read every+// CLIP_WAKE_MS; `clip none` once when the bridge does not load (then only+// the size). It sleeps in sigsuspend with SIGWINCH and SIGALRM blocked+// outside it, so a SIGWINCH that comes while it reads is kept for the next+// sleep (never lost), and it does no work between signals. With no clip,+// an alarm each 10 s wakes it only to see that its parent still runs. Exit+// 1 when /dev/tty does not open (and no clip); exit 0 when the parent dies+// (its parent id changes) or stdout breaks.+export const WATCH_PL = [+ 'use POSIX (); use Config; use Time::HiRes ();','my %n; @n{split " ", $Config{sig_name}} = split " ", $Config{sig_num};',- 'open(my $t, "<", "/dev/tty") or exit 1;',+ 'my $tty = open(my $t, "<", "/dev/tty");','my $req = $^O eq "darwin" ? 0x40087468 : 0x5413;',- 'my $parent = getppid(); my $last = ""; $| = 1;',+ 'my $parent = getppid(); my $last = ""; my $seen = ""; $| = 1;','$SIG{PIPE} = sub { exit 0 }; $SIG{WINCH} = sub {}; $SIG{ALRM} = sub {};',+ 'print "pid $$\\n" or exit 0;',+ 'my $pb;',+ 'if (($ARGV[0] // "") eq "clip") {',+ ' $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 };',+ ' print "clip none\\n" or exit 0 unless $pb;',+ '}',+ 'exit 1 unless $tty || $pb;','POSIX::sigprocmask(POSIX::SIG_BLOCK(), POSIX::SigSet->new($n{WINCH}, $n{ALRM}));','my $none = POSIX::SigSet->new();','while (1) {',' my $w = " " x 8;',- ' if (ioctl($t, $req, $w)) {',+ ' if ($tty && ioctl($t, $req, $w)) {',' my $line = join(" ", unpack("S4", $w));',- ' if ($line ne $last) { print "$line\\n" or exit 0; $last = $line; }',+ ' if ($line ne $last) { print "size $line\\n" or exit 0; $last = $line; }',+ ' }',+ ' if ($pb) {',+ ' my $c = eval { $pb->changeCount };',+ ' if (defined $c && "$c" ne $seen) { print "clip $c\\n" or exit 0; $seen = "$c"; }',' }',' exit 0 if getppid() != $parent;',- ' alarm(10); POSIX::sigsuspend($none);',+ ` if ($pb) { Time::HiRes::ualarm(${CLIP_WAKE_MS * 1000}); } else { alarm(10); }`,+ ' POSIX::sigsuspend($none);','}',].join(' ')+// The perl that runs the watcher: on macOS the system's (a Homebrew perl+// has no PerlObjCBridge), else the one on the PATH.+export const perlFor = (isMac: boolean) => (isMac ? '/usr/bin/perl' : 'perl')const ITERM_BOOKMARKS_SH = `defaults export com.googlecode.iterm2 - | plutil -extract "New Bookmarks" json -o - -`const ITERM_DEFAULT_SH = `defaults read com.googlecode.iterm2 "Default Bookmark Guid"`// A PostScript name (argv[0]) to its family name.diff --git a/hooks/lib/probe.ts b/hooks/lib/probe.tsindex 9cb079c..1c6415a 100644--- a/hooks/lib/probe.ts+++ b/hooks/lib/probe.ts@@ -1,23 +1,22 @@// The pages a copy reads (copy.ts) and the words on them: each answer, plan// and Markdown file Claude sent is noted as drawn (its pages at the box they-// are drawn at), and the probe (runProbe) makes a key folder's-// positions.json from its probe.json: at once when a copy needs it, else-// ahead, one at a time, only while nothing compiles, waits or is in an open-// epoch. A job enqueued or an epoch begun stops the probe ahead.+// are drawn at, and the Job that drew them), and a copy probes only the+// pages it reads (probePage: `typst query` of that page, with the PNG+// compile's own inputs). The positions are kept in memory only (the+// PROBED_KEPT pages read last); nothing is written.import type { EngineInterface } from 'claude-code'-import { PROBE_AHEAD, PROBE_IDLE_MS } from './settings'-import { clip, DRAWN_KEPT, drawnAnswers, epochOpen, keep, lastKey, positionsByDir, queue, results, running, S, type Result } from './state'+import { PROBED_KEPT } from './settings'+import { clip, DRAWN_KEPT, drawnAnswers, keep, lastKey, results, type Job, type Result } from './state'import { fitBox } from './terminal'-import { runProbe, type ProbeJob } from './typst'-import { traceDebug } from './log'-import type { DrawnPage, Positions } from './copy'+import { isSafePage, probePage } from './typst'+import type { Drawn, DrawnPage, Item, TextBlock } from './copy'// Notes the pages of `id` as drawn now, each at fitBox(page, room), as-// drawPages draws it. A redraw with the same pages at the same boxes keeps-// its place, so `seq` is when it was first drawn so. A new one arms the-// probe ahead.-export function noteDrawn($: EngineInterface, id: string, result: Result, room: number) {+// drawPages draws it, with the Job of the key the row drew last (lastKey:+// the result drawn is that key's). A redraw with the same pages at the same+// boxes keeps its place, so `seq` is when it was first drawn so.+export function noteDrawn(id: string, result: Result, room: number) {const pages: DrawnPage[] = result.pages.map(p => ({ file: p.file, width: p.width, height: p.height, ...fitBox(p, room) }))const dir = result.pages[0]?.file.replace(/\/[^/]*$/, '') ?? ''const was = drawnAnswers.get(id)@@ -26,119 +25,60 @@ export function noteDrawn($: EngineInterface, id: string, result: Result, room:return !!now && p.file === now.file && p.columns === now.columns && p.rows === now.rows}if (was && was.dir === dir && was.pages.length === pages.length && was.pages.every(same)) return- keep(drawnAnswers, id, { id, seq: ++clip.seq, dir, pages }, DRAWN_KEPT)- probeLater($)+ const last = lastKey.get(id)+ const job = last && `${last.job.env.cache}/${last.key}` === dir ? last.job : undefined+ keep(drawnAnswers, id, { id, seq: ++clip.seq, dir, pages, ...(job ? { job } : {}) }, DRAWN_KEPT)}// A memo hit (the same drawing as before): noted again only when it went// past DRAWN_KEPT, from the result the row last drew (lastKey).-export function noteDrawnAgain($: EngineInterface, id: string, room: number) {+export function noteDrawnAgain(id: string, room: number) {if (drawnAnswers.has(id)) returnconst result = results.get(lastKey.get(id)?.key ?? '')- if (result && result !== 'failed') noteDrawn($, id, result, room)+ if (result && result !== 'failed') noteDrawn(id, result, room)}// ---- Positions -----------------------------------------------------------------// The probes that run now by folder: a copy of the same folder waits for-// it (and runs its own when it was cancelled).-const inflight = new Map<string, Promise<Positions | null | 'cancelled'>>()-// The probe ahead: its timer, and the run with its cancel. Folders whose-// probe failed are not probed ahead again (bounded: cleared when full).-let idleTimer: { cancel: () => void } | null = null-let idle: { dir: string; cancel: () => void } | null = null-const failed = new Set<string>()+// The words of one page and the blocks they are in.+export type PageWords = { items: Item[]; blocks: TextBlock[] }-// A folder's positions: kept, positions.json, else the probe (probe.json).-async function load($: EngineInterface, dir: string, signal?: AbortSignal): Promise<Positions | null | 'cancelled'> {- const kept = await $.fs.read(`${dir}/positions.json`).catch(() => null)- try {- const got = kept ? (JSON.parse(kept) as Positions) : null- if (got && Array.isArray(got.pages) && Array.isArray(got.blocks)) return got- } catch {}- const job = await $.fs.read(`${dir}/probe.json`).catch(() => null)- let probe: ProbeJob- try {- probe = JSON.parse(job ?? '') as ProbeJob- if (!Array.isArray(probe.argv) || !(probe.ppi > 0)) return null- } catch {- return null- }- if (signal?.aborted) return 'cancelled'- return runProbe($, dir, probe, signal)-}--async function positionsRun($: EngineInterface, dir: string, signal?: AbortSignal): Promise<Positions | null | 'cancelled'> {- const known = positionsByDir.get(dir)- if (known) return known- const ahead = inflight.get(dir)- if (ahead) {- const got = await ahead- return got === 'cancelled' && !signal?.aborted ? positionsRun($, dir, signal) : got- }- const run = load($, dir, signal)- inflight.set(dir, run)- const got = await run.catch(() => null)- if (inflight.get(dir) === run) inflight.delete(dir)- if (got && got !== 'cancelled') keep(positionsByDir, dir, got, DRAWN_KEPT)- return got-}--// A folder's word positions for a copy, now; null when there are none.-export async function positionsFor($: EngineInterface, dir: string): Promise<Positions | null> {- const got = await positionsRun($, dir)- return got === 'cancelled' ? null : got-}--// ---- The probe ahead ------------------------------------------------------------+// The pages probed, by `<folder>#<page>` (the PROBED_KEPT read last), and+// the probes that run now (a copy of the same page waits for the same run).+const probed = new Map<string, PageWords>()+const inflight = new Map<string, Promise<PageWords | null>>()-const isIdle = () => !S.resizing && !epochOpen() && !queue.length && !running.size+const pageKey = (d: Drawn, page: number) => `${d.dir}#${page}`-// Arms the probe ahead: PROBE_IDLE_MS after the last call (a drawing noted,-// the last job ended, an epoch committed, a burst ended).-export function probeLater($: EngineInterface) {- idleTimer?.cancel()- idleTimer = $.clock.after(PROBE_IDLE_MS, () => {- idleTimer = null- probeNext($)- })-}+// Whether page `page` of a drawing is known (no probe needs to run).+export const isProbed = (d: Drawn, page: number) => probed.has(pageKey(d, page))-// Stops the probe ahead (a job enqueued, an epoch begun): its timer, and its-// run (killed; the folder is probed again later).-export function stopProbe() {- idleTimer?.cancel()- idleTimer = null- idle?.cancel()+// The words of page `page` (0-based) of a drawing, for a copy: kept, else+// its probe (one run per page at a time). Null when the drawing has no Job+// or the probe fails (a failure is not kept: the next copy probes again).+export async function wordsOf($: EngineInterface, d: Drawn & { job?: Job }, page: number): Promise<PageWords | null> {+ const key = pageKey(d, page)+ const known = probed.get(key)+ if (known) {+ keep(probed, key, known, PROBED_KEPT)+ return known+ }+ const running = inflight.get(key)+ if (running) return running+ const drawn = d.pages[page]+ if (!d.job || !drawn) return null+ const run = probePage($, d.job, d.dir, { page, pages: d.pages.length, isSafe: isSafePage(drawn.file) })+ .then(got => (got ? { items: got.pages[page] ?? [], blocks: got.blocks } : null))+ .catch(() => null)+ inflight.set(key, run)+ const got = await run+ if (inflight.get(key) === run) inflight.delete(key)+ if (got) keep(probed, key, got, PROBED_KEPT)+ return got}-// One probe ahead, while idle: the newest drawing (of the PROBE_AHEAD-// newest) with no positions yet; when it ends, the next one.-function probeNext($: EngineInterface) {- if (idle || !isIdle()) return- const next = [...drawnAnswers.values()]- .sort((a, b) => b.seq - a.seq)- .slice(0, PROBE_AHEAD)- .find(d => d.dir && !positionsByDir.has(d.dir) && !failed.has(d.dir) && !inflight.has(d.dir))- if (!next) return- const controller = new AbortController()- const entry = { dir: next.dir, cancel: () => controller.abort() }- idle = entry- void positionsRun($, next.dir, controller.signal)- .catch(() => null)- .then(got => {- if (idle === entry) idle = null- traceDebug($, `probe ahead ${next.dir}: ${got === 'cancelled' ? 'cancelled' : got ? 'done' : 'failed'}`)- // Cancelled: again once idle (a job that ended meanwhile armed it while- // this run held the slot).- if (got === 'cancelled') {- if (isIdle()) probeLater($)- return- }- if (!got) {- if (failed.size >= DRAWN_KEPT * 4) failed.clear()- failed.add(next.dir)- }- probeNext($)- })+// Forgets the pages probed (for tests).+export function forgetProbed() {+ probed.clear()+ inflight.clear()}diff --git a/hooks/lib/settings.ts b/hooks/lib/settings.tsindex 47d6a1e..75f4abe 100644--- a/hooks/lib/settings.ts+++ b/hooks/lib/settings.ts@@ -64,16 +64,13 @@ export const NO_NETWORK = 'http://127.0.0.1:9'// how long one read may take.export const HOST_POLL_MS = 3000export const HOST_CHECK_MS = 2000-// How often the clipboard is read (macOS pbpaste) for a mouse copy of-// answer pictures.-export const CLIP_POLL_MS = 300-// The word positions of a drawn page (the probe, a `typst query`) are made-// when a copy needs them, or ahead: one probe at a time, once nothing has-// compiled, waited or drawn new for this long; ahead only for the-// PROBE_AHEAD newest drawings (the rows drawn last: after a resize, the-// ones on screen).-export const PROBE_IDLE_MS = 1000-export const PROBE_AHEAD = 8+// Copy: how often the watcher reads the clipboard's change count (macOS;+// one call in the watcher, no process), the word positions of how many+// pages are kept in memory (a copy probes only the pages it reads), and+// how long a probe runs before a toast says the mod reads the picture.+export const CLIP_WAKE_MS = 300+export const PROBED_KEPT = 64+export const READING_TOAST_MS = 150// The base every theme merges over (its theme.json and syntax files).export const BASE_THEME = 'vscode'// The theme used when none is chosen, or when the chosen one is not usable.diff --git a/hooks/lib/state.ts b/hooks/lib/state.tsindex 13e4427..87ad591 100644--- a/hooks/lib/state.ts+++ b/hooks/lib/state.ts@@ -7,7 +7,7 @@ import type { IuiTheme } from '../../types'import type { ThemeInfo } from './themes'import type { HostMode, ThemeSetting } from './mode'import type { PlanVerdict } from './plan'-import type { Drawn, Positions } from './copy'+import type { Drawn } from './copy'import { DEFAULT_HEIGHT, DEFAULT_SIZE, DEFAULT_WIDTH, type Height, type Width } from './settings'// The `done` atom (see types/index.d.ts) for refresh. The state scan of@@ -168,9 +168,6 @@ export const S = {planVerdict: null as PlanVerdict | null,planAsking: '',planCode: null as string | null,- // Claude Code's copyOnSelect setting (setUp, config.set): false, a mouse- // selection is not copied, so the watcher does not copy it either.- copyOnSelect: true,}// The compile results by key (an LRU: set with `keep` at RESULTS_KEPT).export const results = new Map<string, Result | 'failed'>()@@ -191,8 +188,9 @@ export const running = new Map<string, { job: Job; cancel: () => void; signal: Aexport const epochOpen = () => S.epoch !== S.shownEpoch// The key last drawn per message (and its text), so a new size keeps the old// picture (at its own box) until the new one is ready instead of the text.-// The oldest go past RESULTS_KEPT, as `results`.-export const lastKey = new Map<string, { key: string; textHash: string }>()+// `job`: the Job of that key as it drew (its env as then, no text), for the+// probe of a copy. The oldest go past RESULTS_KEPT, as `results`.+export const lastKey = new Map<string, { key: string; textHash: string; job: Job }>()// Over ssh: each page file's PNG as base64 (null: too large to send), read// once so a redraw does not read it again; the oldest go past INLINE_KEPT.export const inlined = new Map<string, string | null>()@@ -221,25 +219,24 @@ export const writesLive = new Map<string, number>()// Copy (copy.ts, probe.ts): the pages drawn this session by their id (an// answer's requestId, `plan:<tool_use_id>`, `file:<tool_use_id>:<path>`;-// oldest first, at most DRAWN_KEPT), and each key folder's word positions-// once read (the oldest go past DRAWN_KEPT).-export const drawnAnswers = new Map<string, Drawn>()+// oldest first, at most DRAWN_KEPT), each with the Job that drew it (the+// probe's inputs; none when not known).+export const drawnAnswers = new Map<string, Drawn & { job?: Job }>()export const DRAWN_KEPT = 64-export const positionsByDir = new Map<string, Positions>()-// The clipboard watcher (register.tsx): its timer and when it last ran,-// whether its first tick noted the selection there was (`seeded`), the-// clipboard text last seen and last written (so a write is never read back-// as new), the last selection handled, 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`).+// 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`).export const clip = {- watch: null as { cancel: () => void } | null,- ticked: 0,- seeded: false,+ count: null as number | null,+ none: false,busy: false,+ again: false,seen: '',wrote: '',- selected: '',raw: '',rawRow: undefined as string | undefined,seq: 0,diff --git a/hooks/lib/stream.ts b/hooks/lib/stream.tsindex 95af151..f5e80d0 100644--- a/hooks/lib/stream.ts+++ b/hooks/lib/stream.ts@@ -2,8 +2,7 @@// final when its request moves on (or its text is still), then compiled, at// most MAX_RUNNING at once: rows on screen first, then the newest. No job// starts during a burst (S.resizing); a job that ends calls jobDone (no-// redraw while an epoch is open: the epoch commits). A job enqueued stops-// the probe ahead (probe.ts); the last job that ends arms it again.+// redraw while an epoch is open: the epoch commits).import type { EngineInterface } from 'claude-code'import { BLANK_AFTER_LIVE_MS, MAX_RUNNING, RESULTS_KEPT } from './settings'@@ -12,7 +11,6 @@ import { hashOf } from './draw'import { noteDesign, recordDesign } from './designs'import { compile, logDebug } from './typst'import { extendEpoch, jobDone, jobQueued } from './epoch'-import { probeLater, stopProbe } from './probe'// The order of enqueue calls: a higher `order` is newer.let enqueued = 0@@ -59,7 +57,6 @@ export function pump($: EngineInterface) {// A cancelled compile draws nothing new: no redraw.if (result !== 'cancelled') jobDone($)pump($)- if (!queue.length && !running.size) probeLater($)})}}@@ -78,7 +75,6 @@ export function enqueue($: EngineInterface, job: Job) {if (stale >= 0) queue.splice(stale, 1)job.epoch = S.epochjob.order = ++enqueued- stopProbe()queue.push(job)jobQueued(job)// A job of the open epoch: its rows still come, the commit waits for them.diff --git a/hooks/lib/typst.ts b/hooks/lib/typst.tsindex af88df3..fb8b854 100644--- a/hooks/lib/typst.ts+++ b/hooks/lib/typst.ts@@ -306,7 +306,8 @@ export async function runTypst($: EngineInterface, job: Job, segments: readonly// ---- The probe: where the words are ---------------------------------------// `typst query` of the template's <mdpos> marks with probe=1: the PNG-// compile's own inputs, root, package path and env (no ppi, format or out).+// compile's own inputs (and `page`), root, package path and env (no ppi,+// format or out).export function probeCall(o: { typst: string; root: string; cache: string; inputs: Readonly<Record<string, string | number>> }): { argv: string[]; env: Record<string, string> } {const argv = [o.typst, 'query',@@ -321,24 +322,34 @@ export function probeCall(o: { typst: string; root: string; cache: string; inputreturn { argv, env: noNetworkEnv(o.cache) }}-// What a page set's probe needs, kept as probe.json beside pages.json: the-// probe runs only when a copy needs it or when nothing compiles (probe.ts),-// in this load or a later one.-export type ProbeJob = { argv: string[]; env: Record<string, string>; ppi: number }--// Runs the probe and writes positions.json: the positions, null when it-// failed, 'cancelled' when `signal` stopped it.-export async function runProbe($: EngineInterface, dir: string, probe: ProbeJob, signal?: AbortSignal): Promise<Positions | null | 'cancelled'> {- const ran = await runKillable($, probe.argv, { env: probe.env, timeoutMs: COMPILE_TIMEOUT_MS, ...(signal ? { signal } : {}) })- if (ran.isCancelled) return 'cancelled'+// A drawn page's file says how it was compiled: `b` and `d` (the split+// retry) are the safe mode's tags.+export const isSafePage = (file: string) => /\/[bd]-\d+\.png$/.test(file)++// The word positions of page `page` (0-based) of a key folder: the probe+// of that page only (page=<n>), with the inputs of the PNG compile, built+// from the Job that drew it and the segments in its doc.json. Null when it+// fails, or when doc.json does not hold one segment per page drawn (a split+// retry that failed keeps the pages of the first compile).+export async function probePage(+ $: EngineInterface, job: Job, dir: string, o: { page: number; pages: number; isSafe: boolean },+): Promise<Positions | null> {+ let segments: unknown+ try {+ segments = (JSON.parse((await $.fs.read(`${dir}/doc.json`)) as string) as { segments?: unknown }).segments+ } catch {+ return null+ }+ if (!Array.isArray(segments) || segments.length !== o.pages || !job.env.typst) return null+ const { inputs, ppi } = typstInputs(job, segments as string[], dir, o.isSafe)+ const { argv, env } = probeCall({ typst: job.env.typst, root: job.env.root, cache: job.env.cache, inputs: { ...inputs, page: o.page + 1 } })+ const ran = await runKillable($, argv, { env, timeoutMs: COMPILE_TIMEOUT_MS })if (ran.exitCode !== 0) {- await logDebug($, dir.replace(/\/[^/]*$/, ''), `probe ${dir} failed:\n${ran.stderr}`)+ await logDebug($, job.env.cache, `probe ${dir} page ${o.page + 1} failed:\n${ran.stderr}`)return null}try {- const positions = positionsOf(JSON.parse(ran.stdout) as Mark[], probe.ppi)- await $.fs.write(`${dir}/positions.json`, JSON.stringify(positions))- return positions+ return positionsOf(JSON.parse(ran.stdout) as Mark[], ppi)} catch {return null}@@ -418,22 +429,13 @@ export async function compile($: EngineInterface, job: Job, signal?: AbortSignalif (split) {pages = splitsegments = cut- } else {- await logDebug($, job.env.cache, `compile ${job.key}: the split retry failed:\n${again.stderr}`)- // The probe reads doc.json: the segments of the pages kept.- await $.fs.write(`${dir}/doc.json`, JSON.stringify({ base, segments, images }))- }+ } else await logDebug($, job.env.cache, `compile ${job.key}: the split retry failed:\n${again.stderr}`)}pages = pages.map(p => ({ ...p, rows: Math.min(MAX_IMAGE_ROWS, p.rows) }))}const { rowPt } = sizing(job.columns, job.cell, fontFit(job.env.metrics, job.size).columnPt)const { bulletRow } = alignFirstLine(firstLineOf(segments[0] ?? ''), rowPt)const result: Result = { pages, bulletRow, ...(note ? { note } : {}) }- // Only what the probe needs, no process: it runs later (probe.ts). Before- // pages.json, so a kept key has it.- const { inputs, ppi } = typstInputs(job, segments, dir, isSafe)- const probe: ProbeJob = { ...probeCall({ typst: job.env.typst!, root: job.env.root, cache: job.env.cache, inputs }), ppi }- await $.fs.write(`${dir}/probe.json`, JSON.stringify(probe))await $.fs.write(`${dir}/pages.json`, JSON.stringify(result))return result}diff --git a/hooks/register.tsx b/hooks/register.tsxindex 632e960..3797238 100644--- a/hooks/register.tsx+++ b/hooks/register.tsx@@ -14,14 +14,14 @@// mutable state `S`), markdown, terminal, terminals, mode, themes, command,// setup, host, typst, draw, stream, answer (one text through the pipeline),// env, images, pictures, plan (the plan approval flow), copy (the text under-// a mouse copy of the pictures) and probe (the drawn pages and their word-// positions). This file joins them to the hooks, and gives the tests the-// names they import.+// a mouse copy of the pictures) and probe (the drawn pages, and the words of+// a page a copy reads). This file joins them to the hooks, and gives the+// tests the names they import.import { atom, read, update } from 'claude-code'import type { EngineInterface, Register, RenderElement, RenderViewport } from 'claude-code'import {- CLIP_POLL_MS, DEFAULT_THEME, heightText, IMAGE_MAX_COLUMNS, MAX_HEIGHT, MAX_SIZE, MAX_WIDTH, MIN_HEIGHT, MIN_SIZE, MIN_WIDTH, RESULTS_KEPT, TYPST_PROMPT, widthText,+ DEFAULT_THEME, heightText, IMAGE_MAX_COLUMNS, MAX_HEIGHT, MAX_SIZE, MAX_WIDTH, MIN_HEIGHT, MIN_SIZE, MIN_WIDTH, READING_TOAST_MS, RESULTS_KEPT, TYPST_PROMPT, widthText,} from './lib/settings'import { clip, drawnAnswers, editedPlans, keep, queue, refresh, running, S, subagentPlans, writesLive, type Env } from './lib/state'import { beginEpoch } from './lib/epoch'@@ -33,11 +33,11 @@ import { pollHost, PROBE_RUNS, probeOsc11, showMode, USE_OSC11, watchHost } fromimport { measureFonts } from './lib/typst'import { drawPages } from './lib/draw'import { finalizeAll } from './lib/stream'-import { noteDrawn, noteDrawnAgain, positionsFor } from './lib/probe'+import { isProbed, noteDrawn, noteDrawnAgain, wordsOf } from './lib/probe'import { codePointsOf, decodeSelection, hasPlaceholders, joinSegments, pickPages, textOfRun, type Pick, type Segment } from './lib/copy'import { pagesOf, type Drawing } from './lib/answer'import { setUp } from './lib/env'-import { frameFor, noteView } from './lib/frame'+import { frameFor, noteView, stopWatch, watchFrame, watchState } from './lib/frame'import { roomColumns } from './lib/terminal'import { onScreenOf, pastedImagePath, pastedNumbers, sentFiles } from './lib/images'import { pasteDir, sentOf, shownOf, underRow, type Shown, type Under } from './lib/pictures'@@ -54,7 +54,8 @@ export {} from './lib/settings'export { DEFAULT_METRICS, keep, type Cell, type Design, type FontMetrics, type Frame, type Look, type Metrics, type Room } from './lib/state'export {- composeFrame, followWatcher, frameChange, frameFor, frameOfLine, lineSplitter, noteTty, pictureColumns, quietTimer, shownFor, type View,+ composeFrame, followWatcher, frameChange, frameFor, frameOfLine, lineSplitter, noteTty, pictureColumns, quietTimer, shownFor, watchLineOf, type View,+ type WatchLine,} from './lib/frame'export { designKey, designPath, designText, loadDesign, parseDesign, recordDesign } from './lib/designs'export {@@ -69,9 +70,9 @@ export {} from './lib/themes'export { commandSuggestions, parseCommand, type Command, type Suggestion } from './lib/command'export { hasSetup, SETUP_END, SETUP_START, setupBlock, shellRcOf, withoutSetup, withSetup, type ShellRc } from './lib/setup'-export { OSC11_PL } from './lib/host'+export { OSC11_PL, perlFor, WATCH_PL } from './lib/host'export {- convertCall, measureCall, noNetworkEnv, pageRowsOf, parseOd, pngSize, probeCall, resultOf, roomInputs, shouldRetrySafe, typstCall, type ProbeJob,+ convertCall, isSafePage, measureCall, noNetworkEnv, pageRowsOf, parseOd, pngSize, probeCall, resultOf, roomInputs, shouldRetrySafe, typstCall, typstInputs,} from './lib/typst'export { alignFirstLine, firstLineOf, fontFit, hashOf, renderKey, scaledBulletRow, sizing, type FirstLine } from './lib/draw'export { nextJob } from './lib/stream'@@ -187,13 +188,15 @@ async function planEnv($: EngineInterface): Promise<Env | null> {// ---- Copy -----------------------------------------------------------------// A mouse copy over a picture puts kitty placeholder cells on the clipboard,-// and no hook sees that copy, so the selection and the clipboard are read-// afterwards (every CLIP_POLL_MS on macOS) and, when they hold placeholders,-// the clipboard is written again with the words under them (see-// lib/copy.ts; the drawn pages and their positions are in lib/probe.ts).--// Notes a drawing for a copy (noteDrawn, noteDrawnAgain) and starts the-// watcher; a failure never stops the row from drawing.+// and no hook sees that copy. On macOS the watcher (lib/frame.ts) prints the+// clipboard's change count when it changes; at a change the clipboard is+// read once (pbpaste) and, when it holds placeholders, written again with+// the words under them (see lib/copy.ts; the drawn pages and the words of+// a page are in lib/probe.ts). No timer reads the clipboard or the+// selection.++// Notes a drawing for a copy (noteDrawn, noteDrawnAgain) and turns on the+// watcher's clipboard part; a failure never stops the row from drawing.function noteCopy($: EngineInterface, note: () => void) {try {note()@@ -203,33 +206,56 @@ function noteCopy($: EngineInterface, note: () => void) {type CopyRead = { text: string; segments: Segment[]; picks: Pick[]; runs: number; resolved: number }-// The text for a clipboard (or selection) text with placeholders.+// The text for a clipboard (or selection) text with placeholders. A page+// not probed yet is probed now; when that takes longer than+// READING_TOAST_MS, a toast says so.async function readCopy($: EngineInterface, raw: string, requestId?: string): Promise<CopyRead> {const segments = decodeSelection(raw)const picks = pickPages(segments, [...drawnAnswers.values()], requestId)const texts: (string | null)[] = []let resolved = 0- for (const [i, seg] of segments.entries()) {- const pick = picks[i]- const d = pick ? drawnAnswers.get(pick.id) : undefined- const page = pick && d ? d.pages[pick.page] : undefined- if (seg.kind !== 'image' || !pick || !d || !page) {- texts.push(null)- continue+ let toast: { cancel: () => void } | null = null+ try {+ for (const [i, seg] of segments.entries()) {+ const pick = picks[i]+ const d = pick ? drawnAnswers.get(pick.id) : undefined+ const page = pick && d ? d.pages[pick.page] : undefined+ if (seg.kind !== 'image' || !pick || !d || !page) {+ texts.push(null)+ continue+ }+ if (!toast && !isProbed(d, pick.page)) {+ toast = $.clock.after(READING_TOAST_MS, () => {+ try {+ $.ui.toast('Intelligent UI: reading the picture…')+ } catch {}+ })+ }+ const words = await wordsOf($, d, pick.page)+ const text = words ? textOfRun(seg.lines, words.items, words.blocks, page) : ''+ if (text) resolved+++ texts.push(text || null)}- const positions = await positionsFor($, d.dir)- const text = positions ? textOfRun(seg.lines, positions.pages[pick.page] ?? [], positions.blocks, page) : ''- if (text) resolved++- texts.push(text || null)+ } finally {+ toast?.cancel()}const runs = segments.filter(seg => seg.kind === 'image').lengthconst read = { text: joinSegments(segments, texts), segments, picks, runs, resolved }- clip.last = { requestId: requestId ?? null, ...read, drawn: [...drawnAnswers.values()] }+ clip.last = { requestId: requestId ?? null, ...read, drawn: [...drawnAnswers.values()].map(({ job: _, ...d }) => d) }return read}+// The clipboard now (pbpaste, UTF-8); null when it can not be read.+async function clipboardNow($: EngineInterface): Promise<string | null> {+ const got = await $.process.run(['pbpaste'], { timeoutMs: 2000, env: { LANG: 'en_US.UTF-8', LC_ALL: 'en_US.UTF-8' } }).catch(() => null)+ return got && got.exitCode === 0 ? got.stdout : null+}+// Writes the text read for `raw` (placeholders) to the clipboard, once:-// our own write is never read back as new.+// our own write is never read back as new. Just before the write the+// clipboard is read again: a newer copy (made while the picture was read,+// or one the watcher has not seen yet) is not written over; it is read+// next (readClipboard), even when it is the same text again.async function copyRead($: EngineInterface, raw: string, requestId?: string) {clip.raw = rawclip.rawRow = requestId@@ -240,6 +266,11 @@ async function copyRead($: EngineInterface, raw: string, requestId?: string) {$.ui.toast('Intelligent UI: could not read the selected picture (/iui dump says why)')return}+ if ((await clipboardNow($)) !== raw) {+ clip.seen = ''+ clip.again = true+ return+ }clip.wrote = read.textclip.seen = read.textawait $.ui.copy({ text: read.text })@@ -250,68 +281,74 @@ async function copyRead($: EngineInterface, raw: string, requestId?: string) {// line breaks that the selection does not have, or the other way).const sameCopy = (a: string, b: string) => a.replace(/\r\n/g, '\n').replace(/\s+$/, '') === b.replace(/\r\n/g, '\n').replace(/\s+$/, '')-// One tick: first the mouse selection (in-process; a new one is copied only-// when Claude Code copies on select), else the clipboard (pbpaste).-// Placeholders that are not our own write are read and written back as-// text. A clipboard with no placeholders is never touched. When this-// session has a selection (fullscreen), the clipboard is rewritten only-// when it is that selection: another session's copy is that session's to-// read. The first tick of a watcher only notes the selection there is (an-// old one, after a hot reload), so it is never copied again.-async function clipTick($: EngineInterface) {- if (clip.busy) return+// A watcher line `clip <count>` (null: `clip none`, no PerlObjCBridge: the+// automatic copy stays off). The first count of a child (at its start) is+// only noted: the clipboard then is no new copy (after a hot reload, it can+// be an old copy of picture cells).+function clipChanged($: EngineInterface, count: number | null, first: boolean) {+ if (count === null) {+ clip.none = true+ return+ }+ clip.count = count+ if (!first) void readClipboard($).catch(() => undefined)+}++// The clipboard changed: one read (pbpaste). Placeholders that are not our+// own write are read and written back as text. A clipboard with no+// placeholders is never touched. When this session has a selection+// (fullscreen), the clipboard is rewritten only when it is that selection:+// another session's copy is that session's to read. A change while a read+// runs (a probe can take a second) reads once more after it.+async function readClipboard($: EngineInterface) {+ if (clip.busy) {+ clip.again = true+ return+ }clip.busy = truetry {- const selected = await $.ui.selection().catch(() => undefined)- if (!clip.seeded) {- clip.seeded = true- clip.selected = selected?.text ?? ''- return- }- if (S.copyOnSelect && selected && selected.text !== clip.selected && hasPlaceholders(selected.text)) {- clip.selected = selected.text- await copyRead($, selected.text, selected.requestId)- return- }- const got = await $.process.run(['pbpaste'], { timeoutMs: 2000, env: { LANG: 'en_US.UTF-8', LC_ALL: 'en_US.UTF-8' } }).catch(() => null)- if (!got || got.exitCode !== 0) return- const text = got.stdout- if (text === clip.seen) return- clip.seen = text- if (text === clip.wrote || !hasPlaceholders(text)) return- if (selected && !sameCopy(selected.text, text)) return- if (selected) clip.selected = selected.text- await copyRead($, text, selected?.requestId)+ do {+ clip.again = false+ const text = await clipboardNow($)+ if (text === null || text === clip.seen) continue+ clip.seen = text+ if (text === clip.wrote || !hasPlaceholders(text)) continue+ const selected = await $.ui.selection().catch(() => undefined)+ if (selected && !sameCopy(selected.text, text)) continue+ await copyRead($, text, selected?.requestId)+ } while (clip.again)} finally {clip.busy = false}}-// The watcher: on macOS, on this computer (over ssh pbpaste reads the remote-// one's clipboard), only while Intelligent UI is on (its callers draw, or-// read the atom) and a picture is drawn. One per load: a hot reload drops-// the old load's timers. A timer whose period was refused stops; one silent-// for 10 periods is started again (`ticked` is when it last ran).+// The watcher's clipboard part: on macOS, on this computer (over ssh+// pbpaste reads the remote one's clipboard), only while Intelligent UI is+// on (its callers draw, or read the atom) and a picture is drawn. It is a+// new child (the flag is an argument): its first count is only noted. A+// child that runs is kept; one that ended is started again (watchFrame+// caps it). With no+// PerlObjCBridge the child goes on as it is (size only).function watchClipboard($: EngineInterface) {- if (!S.env?.isMac || S.isRemote || !drawnAnswers.size) return- if (clip.watch && Date.now() - clip.ticked < 10 * CLIP_POLL_MS) return- clip.watch?.cancel()- clip.ticked = Date.now()- clip.seeded = false- try {- clip.watch = $.clock.every(CLIP_POLL_MS, () => {- clip.ticked = Date.now()- void clipTick($).catch(() => undefined)- })- } catch {- clip.watch = null- }+ if (!S.env?.isMac || S.isRemote || !drawnAnswers.size || clip.none) return+ watchFrame($, (count, first) => clipChanged($, count, first))+}++// Intelligent UI off, or a /clear (the process goes on): the watcher again+// with no clipboard part (no reads).+function stopClipboard($: EngineInterface) {+ if (watchState()?.clip && !clip.none) watchFrame($, null)}-// Intelligent UI off, or the session's end: no reads.-function stopClipboard() {- clip.watch?.cancel()- clip.watch = null+// The automatic copy now, for /iui details and dump.+function autoCopyOf(isOn: boolean): string {+ if (!S.env?.isMac) return 'off (not macOS)'+ if (S.isRemote) return 'off (ssh)'+ if (!isOn) return 'off (Intelligent UI is off)'+ if (clip.none) return 'off (no PerlObjCBridge in /usr/bin/perl)'+ if (!drawnAnswers.size) return 'off (no picture yet)'+ const now = watchState()+ return now?.clip && !now.ended ? 'on' : 'off (the watcher does not run)'}// /iui grab: the last mouse selection, read and copied.@@ -321,7 +358,6 @@ async function grab($: EngineInterface): Promise<string> {if (!hasPlaceholders(selected.text)) return `Intelligent UI: the selection has no picture cells; it is ${selected.text.length} chars of text already.`clip.raw = selected.textclip.rawRow = selected.requestId- clip.selected = selected.textconst read = await readCopy($, selected.text, selected.requestId)if (!read.resolved) return `Intelligent UI: found ${read.runs} picture run(s) but could not read them (see /iui dump).`clip.wrote = read.text@@ -333,10 +369,11 @@ async function grab($: EngineInterface): Promise<string> {}// /iui dump: the last placeholder text seen, as code points, how it was-// read, and the same in full in <cache>/copy-debug.json.-async function dump($: EngineInterface): Promise<string> {- const watcher = clip.watch ? 'on' : 'off'- if (!clip.raw) return `Intelligent UI: no clipboard text with picture cells seen yet (watcher ${watcher}; ${drawnAnswers.size} pictures drawn).`+// read, and the same in full in <cache>/copy-debug.json. `on`: Intelligent+// UI is on.+async function dump($: EngineInterface, on: boolean): Promise<string> {+ const auto = autoCopyOf(on)+ if (!clip.raw) return `Intelligent UI: no clipboard text with picture cells seen yet (auto copy ${auto}; ${drawnAnswers.size} pictures drawn).`const read = await readCopy($, clip.raw, clip.rawRow)const runs = read.segments.map((seg, i) => {@@ -352,7 +389,7 @@ async function dump($: EngineInterface): Promise<string> {await $.fs.write(`${cache}/copy-debug.json`, JSON.stringify(full, null, 1)).catch(() => undefined)}return [- `Intelligent UI: last clipboard with picture cells (${Array.from(clip.raw).length} code points; watcher ${watcher}):`,+ `Intelligent UI: last clipboard with picture cells (${Array.from(clip.raw).length} code points; auto copy ${auto}):`,codePointsOf(clip.raw, 40),runs,`Read as ${read.text.length} chars: ${JSON.stringify(read.text.slice(0, 200))}`,@@ -369,8 +406,12 @@ export const register: Register = on => {return next(e)})+ // A /clear or a resume: the process goes on, with no clipboard reads until+ // the next picture. Any other end (/exit): the watcher stops, and no new+ // child starts.on('session.end', async ($, e, next) => {- stopClipboard()+ if (e.reason === 'clear' || e.reason === 'resume') stopClipboard($)+ else stopWatch()return next(e)}).catch(($, e, next) => next(e))@@ -384,8 +425,7 @@ export const register: Register = on => {clip.rawRow = selected?.text === e.text ? selected.requestId : undefinedconst read = await readCopy($, e.text, clip.rawRow)if (!read.resolved) return next(e)- // The watcher does not copy the same selection again.- if (selected?.text === e.text) clip.selected = e.text+ // The clipboard change of this write is not read again.clip.wrote = read.textclip.seen = read.textreturn next({ ...e, text: read.text })@@ -403,11 +443,11 @@ export const register: Register = on => {on('command.run', { command: 'iui' }, async ($, e) => {const asked = parseCommand(e.args)if (asked.kind === 'grab') return { text: await grab($) }- if (asked.kind === 'dump') return { text: await dump($) }+ if (asked.kind === 'dump') return { text: await dump($, await read($, isOn)) }if (asked.kind === 'on' || asked.kind === 'off') {await update($, isOn, () => asked.kind === 'on')- // On: the watcher starts with the next picture drawn.- if (asked.kind === 'off') stopClipboard()+ // On: the clipboard part starts with the next picture drawn.+ if (asked.kind === 'off') stopClipboard($)await $.store.set('enabled', asked.kind === 'on')return { text: `Intelligent UI is ${asked.kind}.` }}@@ -485,7 +525,8 @@ export const register: Register = on => {const terminal = ready.canDraw? `this terminal draws pictures${ready.inline ? ' (over ssh, sent as bytes)' : ''}`: 'Claude Code draws no pictures here (it does in kitty and Ghostty, in iTerm2 3.6+ and Rio 0.5.27+ with CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1, over ssh when TERM names kitty or Ghostty or with that variable; never in tmux, screen or a background session; not in WezTerm, Warp, Konsole or others), so answers stay text'- return { text: `Intelligent UI is ${state}, theme ${theme}, ${modeLine(S.theme, S.setting, S.settingRaw, S.host)}, text size ${S.size}%, width ${widthText(S.width)}, image and drawing height ${heightText(S.height)}, ${font}. ${typst}; ${terminal}.` }+ const auto = `Auto copy: ${autoCopyOf(state === 'on')}`+ return { text: `Intelligent UI is ${state}, theme ${theme}, ${modeLine(S.theme, S.setting, S.settingRaw, S.host)}, text size ${S.size}%, width ${widthText(S.width)}, image and drawing height ${heightText(S.height)}, ${font}. ${typst}; ${terminal}.\n${auto}` }}// The short state: what is set, and only the problems that keep pictures away.const sized = (v: number | 'full' | 'half', unit: string) => (typeof v === 'number' ? `${v} ${unit}` : v)@@ -509,13 +550,6 @@ export const register: Register = on => {return set}).catch(($, e, next) => next(e))- // Claude Code's copyOnSelect: off, the watcher does not copy a selection.- on('config.set', { key: 'copyOnSelect' }, async ($, e, next) => {- const set = await next(e)- if (set.value !== undefined) S.copyOnSelect = set.value !== false- return set- }).catch(($, e, next) => next(e))-on('prompt.compose', async ($, e, next) => {const composed = await next(e)if (!e.surfaces.includes('terminal') || !(await read($, isOn))) return composed@@ -587,14 +621,14 @@ export const register: Register = on => {const k = { text: e.props.text, extra: bullet ? 'bullet' : '', stamp: stampOf(ready, e.viewport), onScreen }const kept = memoOf(answers, e.requestId, k)if (kept) {- noteCopy($, () => noteDrawnAgain($, e.requestId, roomColumns(e.viewport)))+ noteCopy($, () => noteDrawnAgain(e.requestId, roomColumns(e.viewport)))return kept}const drawing = await pagesOf($, { id: e.requestId, text: e.props.text, frame: frameFor(e.viewport), env: ready.env, canStream: true, onScreen })if (drawing.kind === 'pages') {const tree = drawPages($, e, drawing.result, drawing.bytes, { bullet })const { result } = drawing- noteCopy($, () => noteDrawn($, e.requestId, result, roomColumns(e.viewport)))+ noteCopy($, () => noteDrawn(e.requestId, result, roomColumns(e.viewport)))memoSet(answers, e.requestId, k, tree)return tree}@@ -624,7 +658,7 @@ export const register: Register = on => {const kept = memoOf(unders, id, k, requestId => requestId.startsWith(`file:${id}:`))if (kept) {under = kept- for (const u of under) if ('drawing' in u) noteCopy($, () => noteDrawnAgain($, u.id, roomColumns(e.viewport)))+ for (const u of under) if ('drawing' in u) noteCopy($, () => noteDrawnAgain(u.id, roomColumns(e.viewport)))} else {under = await sentOf($, e, { ready: ready.env, markdown, files, id, at: { done: ready.done, row: e.requestId } })if (under.length && under.every(u => !('drawing' in u) || u.drawing.kind === 'pages')) memoSet(unders, id, k, under)@@ -632,7 +666,7 @@ export const register: Register = on => {for (const u of under) {if (!('drawing' in u) || u.drawing.kind !== 'pages') continueconst { result } = u.drawing- noteCopy($, () => noteDrawn($, u.id, result, roomColumns(e.viewport)))+ noteCopy($, () => noteDrawn(u.id, result, roomColumns(e.viewport)))}}}@@ -683,7 +717,7 @@ export const register: Register = on => {// The main loop's running turn, which "clear context" ends.on('turn.start', async ($, e, next) => {if (e.agentId === undefined) S.mainTurnId = e.turnId- // The watcher again if it went silent.+ // The clipboard part, if it is not on (a picture drawn while it was off).if (await read($, isOn)) watchClipboard($)return next(e)}).catch(($, e, next) => next(e))@@ -704,7 +738,7 @@ export const register: Register = on => {// requestId can be an answer's own).if (drawing.kind === 'pages') {const { result } = drawing- noteCopy($, () => noteDrawn($, `plan:${e.props.tool_use_id}`, result, roomColumns(e.viewport)))+ noteCopy($, () => noteDrawn(`plan:${e.props.tool_use_id}`, result, roomColumns(e.viewport)))}return drawPlanUse($, e, row, drawing)} catch {diff --git a/render/md.typ b/render/md.typindex 48794dd..4dfb642 100644--- a/render/md.typ+++ b/render/md.typ@@ -21,6 +21,8 @@// design-h=<pt> the design room height: the `height` at the first// compile of the text (default = height)// safe=1 the retry mode (optional; below)+// page=<n> only the n-th segment (1-based, = the PNG's {0p});+// the probe of one page (below)//// Live ```typst blocks are laid out in the design space (theme.width,// theme.height, theme.page-width are the design values) and drawn scaled by@@ -42,6 +44,8 @@#let inp = sys.inputs#let dark = inp.at("theme", default: "dark") != "light"#let safe = inp.at("safe", default: "0") not in ("", "0", "false", "no", "off")+// One segment only (page=<n>, 1-based); 0 = all of them.+#let only = int(inp.at("page", default: "0"))#let page-w = float(inp.at("width", default: "600")) * 1pt// No left margin, so the text starts in the column normal replies start in.#let margin-left = 0pt@@ -300,6 +304,9 @@// (column `cx`), list item (`prefix`: "- ", "1. ", "- [x] ").// Math and live ```typst drawings have no marks (a drawing is scaled, so// its marks would not be where it is drawn).+// With page=<n>, only that segment is laid out, as in the whole document+// (each segment is a page of its own: its own margins and labels), so a+// copy probes only the pages it reads; `p` is still the PNG's page.// Each mark has its page `p` (1-based, = the PNG's {0p}) and the text size// `s`; all lengths in pt from the page's top-left. A bare (unboxed) mark at// the start of a wrapped line is placed at the end of the line above, and@@ -307,7 +314,7 @@#let probe = inp.at("probe", default: "0") not in ("", "0", "false", "no", "off")#let mark(kind, ..extra) = context {let at = here().position()- [#metadata((k: kind, p: at.page, x: at.x / 1pt, y: at.y / 1pt, s: text.size.to-absolute() / 1pt, ..extra.named()))<mdpos>]+ [#metadata((k: kind, p: at.page + calc.max(0, only - 1), x: at.x / 1pt, y: at.y / 1pt, s: text.size.to-absolute() / 1pt, ..extra.named()))<mdpos>]}// Block code sets this so the word rule leaves its text to the line marks;// math and live drawings set no-marks. The orphan cost changes nothing@@ -768,34 +775,55 @@)// ---------- render ----------+// The content of segment `i`; `scope` over the template's own functions.+#let render-md(md, i, math: md-math, scope: (:)) = cmarker.render(+ md,+ smart-punctuation: false,+ raw-typst: false,+ math: math,+ label-prefix: "s" + str(i) + "-",+ html: (+ img: ("void", html-img),+ a: html-a,+ table: html-table,+ td: html-cell,+ th: (attrs, body) => html-cell(attrs, strong(body)),+ tbody: (attrs, body) => [#metadata(("<tbody>", attrs))#body],+ kbd: kbd,+ ),+ scope: (+ image: md-image,+ raw: md-raw,+ ref: md-ref,+ link: md-link,+ list: md-list,+ enum: md-enum,+ rule: md-rule,+ ..scope,+ ),+)+// The footnotes in a content tree (not a reference to one: its body is a+// label).+#let notes-in(c) = if type(c) != content { 0 } else if c.func() == footnote {+ if type(c.body) == content { 1 + notes-in(c.body) } else { 0 }+} else {+ c.fields().values().map(v => if type(v) == array { v.map(notes-in).sum(default: 0) } else { notes-in(v) }).sum(default: 0)+}+// page=<n>: the footnotes of the segments before it (no drawing, math or+// image made), so its own have the numbers of the whole document.+#let notes-before = if only > 1 {+ let none-of(..args) = []+ segments.slice(0, calc.min(only - 1, segments.len())).enumerate().map(((i, seg)) => {+ notes-in(render-md(if type(seg) == str { seg } else { str(seg) }, i, math: (src, block: false) => [], scope: (image: none-of, raw: none-of)))+ }).sum(default: 0)+} else { 0 }+#for (i, seg) in segments.enumerate() {+ if only > 0 and i + 1 != only { continue }let md = if type(seg) == str { seg } else { str(seg) }let top = if i == 0 { first-top } else { margin-y }- let body = cmarker.render(- md,- smart-punctuation: false,- raw-typst: false,- math: md-math,- label-prefix: "s" + str(i) + "-",- html: (- img: ("void", html-img),- a: html-a,- table: html-table,- td: html-cell,- th: (attrs, body) => html-cell(attrs, strong(body)),- tbody: (attrs, body) => [#metadata(("<tbody>", attrs))#body],- kbd: kbd,- ),- scope: (- image: md-image,- raw: md-raw,- ref: md-ref,- link: md-link,- list: md-list,- enum: md-enum,- rule: md-rule,- ),- )+ let body = render-md(md, i)+ if notes-before > 0 { body = { counter(footnote).update(notes-before); body } }// Pad the bottom so the page is a whole number of terminal rows.context {// No bottom margin: text is measured to its descenders, so the last linediff --git a/tests/copy.test.ts b/tests/copy.test.tsindex e16d1ab..344cae4 100644--- a/tests/copy.test.ts+++ b/tests/copy.test.ts@@ -2,9 +2,10 @@ import { expect, mock, test } from 'claude-code/testing'import {codePointsOf, commandSuggestions, decodeSelection, DIACRITICS, hasPlaceholders, isDrawnIn, joinSegments, parseCommand, pickPages, placeholderCell,- positionsOf, probeCall, textOfRun, type Drawn, type TextBlock, type Item, type Mark,+ isSafePage, positionsOf, textOfRun, WATCH_PL, type Drawn, type TextBlock, type Item, type Mark,} from '../hooks/register'-import { PROBE_IDLE_MS } from '../hooks/lib/settings'+import { WATCH_RESTART_MS } from '../hooks/lib/frame'+import { READING_TOAST_MS } from '../hooks/lib/settings'import { LONG_MARKS, LONG_MD, LONG_PAGE, SMALL_MARKS, SMALL_MD, SMALL_PAGE, SMALL_PPI } from './copy-fixture'// One screen row of a picture as Claude Code draws it: `lead` (the gutter),@@ -237,7 +238,7 @@ test('/iui grab and dump are commands with typeahead rows; dump with nothing seeexpect(ran.text).toContain('Intelligent UI: no clipboard text with picture cells seen yet')})-// ---- The pipeline: probe.json, the probe, the watcher -------------------------+// ---- The pipeline: the watcher's clip lines, pbpaste, 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.@@ -246,10 +247,14 @@ const WRAP = 'echo $$; exec "$@"'const inputsOf = (argv: readonly string[]) => Object.fromEntries(argv.flatMap((a, i) => (argv[i - 1] === '--input' ? [a.split(/=(.*)/s).slice(0, 2)] : [])))// The world beneath the mod: a cache at /c, a typst whose compile writes a-// 1568 x 512 page and whose query gives the fixture's marks (`hold` holds-// the next query until `release`; a kill ends it), pbpaste reading-// `clipboard`, and the copies, toasts and selection the test sees.-function world(on: any, o: { failFirst?: boolean } = {}) {+// 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+// its start and at each change of the clipboard; `clip none` with+// `noBridge`), pbpaste reading `clipboard`, and the copies, toasts and+// selection the test sees. `copy` is a copy in another app (or a mouse+// copy): the clipboard and its change count change.+function world(on: any, o: { failFirst?: boolean; noBridge?: boolean } = {}) {mock.store(on)const clock = mock.clock(on)mock.env(on, { HOME: '/h', CLAUDE_CODE_FORCE_TERMINAL_IMAGES: '1' })@@ -258,18 +263,37 @@ function world(on: any, o: { failFirst?: boolean } = {}) {const queries: Record<string, string>[] = []const kills: string[] = []const killers = new Map<string, () => void>()+ const watchers: { argv: string[]; pid: string; say: (line: string) => void; dead: boolean }[] = []const w = {- clock, files, compiles, queries, kills,- clipboard: 'nothing yet', pastes: 0, copies: [] as string[], toasts: [] as string[],+ clock, files, compiles, queries, kills, watchers,+ clipboard: 'nothing yet', count: 40, pastes: 0, copies: [] as string[], toasts: [] as string[],selection: undefined as { text: string; requestId?: string } | undefined,gate: null as Promise<void> | null, release: () => {},hold() {w.gate = new Promise<void>(r => (w.release = r))},+ copy(text: string) {+ w.clipboard = text+ w.count+++ for (const c of watchers) if (!c.dead && c.argv[3] === 'clip' && !o.noBridge) c.say(`clip ${w.count}`)+ },}let pids = 5000on('process.spawn', async function* ($: any, e: any) {const argv: string[] = e.argv+ if (argv[0] === '/usr/bin/perl' && argv[1] === '-e' && argv[2] === WATCH_PL) {+ const pid = String(pids++)+ const lines = [`pid ${pid}`, ...(argv[3] === 'clip' ? [o.noBridge ? 'clip none' : `clip ${w.count}`] : [])]+ let wake = () => {}+ const me = { argv, pid, dead: false, say: (line: string) => (lines.push(line), wake()) }+ watchers.push(me)+ killers.set(pid, () => ((me.dead = true), wake()))+ for (;;) {+ while (lines.length && !me.dead) yield { stream: 'stdout', text: `${lines.shift()}\n` }+ if (me.dead) return { value: { code: null, signal: 'SIGTERM' } }+ await new Promise<void>(r => (wake = r))+ }+ }if (argv[0] !== 'sh' || argv[2] !== WRAP || argv[4] !== '/usr/bin/typst') return { value: { code: 2, signal: null } }const pid = String(pids++)let killed = false@@ -284,10 +308,11 @@ function world(on: any, o: { failFirst?: boolean } = {}) {}if (typst[1] !== 'query') return { value: { code: 1, signal: null } }expect(typst.slice(-3)).toEqual(['<mdpos>', '--field', 'value'])- queries.push(inputsOf(typst))+ const inputs = inputsOf(typst)+ queries.push(inputs)if (w.gate) await Promise.race([w.gate, dead])if (killed) return { value: { code: null, signal: 'SIGTERM' } }- yield { stream: 'stdout', text: JSON.stringify(SMALL_MARKS) }+ yield { stream: 'stdout', text: JSON.stringify(SMALL_MARKS.map(m => ({ ...m, p: Number(inputs.page) }))) }return { value: { code: 0, signal: null } }})on('process.run', async ($: any, e: any) => {@@ -313,14 +338,16 @@ function world(on: any, o: { failFirst?: boolean } = {}) {return { value: undefined }})on('fs.read', async ($: any, e: any, next: any) => (files.has(e.path) ? { value: files.get(e.path) } : e.path.startsWith('/c/') ? { deny: 'ENOENT' } : next(e)))+ // One page per segment of the folder's doc.json.on('fs.list', async ($: any, e: any, next: any) => {if (!e.path.startsWith('/c/')) return next(e)- const tag = files.has(`${e.path}/b-1.png`) || (o.failFirst && compiles.length > 1) ? 'b' : 'a'- return { value: [{ name: `${tag}-1.png`, kind: 'file', size: 1, mtimeMs: 1, isLink: false }] }+ const tag = o.failFirst && compiles.length > 1 ? 'b' : 'a'+ const segments = (JSON.parse(files.get(`${e.path}/doc.json`) ?? '{"segments":[""]}') as { segments: string[] }).segments+ return { value: segments.map((_, i) => ({ name: `${tag}-${i + 1}.png`, kind: 'file', size: 1, mtimeMs: 1, isLink: false })) }})on('ui.copy', async ($: any, e: any) => {w.copies.push(e.text)- w.clipboard = e.text+ w.copy(e.text)return { value: { isCopied: true } }})on('ui.selection', async () => ({ value: w.selection }))@@ -338,129 +365,173 @@ const message = (requestId: string, text: string) =>props: { text, isFirstOfReply: true }, viewport: { columns: 100, rows: 40 },}) as anyconst props = (text: string) => ({ text, isFirstOfReply: true }) as any-const written = (files: Map<string, string>, name: string) => [...files.keys()].filter(k => k.endsWith(`/${name}`))+const names = (files: Map<string, string>) => [...new Set([...files.keys()].filter(k => k.startsWith('/c/')).map(k => k.replace(/^.*\//, '')))].sort()-// Draws SMALL_MD as answer `id` (98 columns: the fixture's), compiled; the-// watcher's first tick (it only notes the selection there is) has run.-async function drawAnswer($: any, w: ReturnType<typeof world>, id = 'ans-1') {- const ui = await $.ui.mount(message(id, SMALL_MD))+// Draws `text` (SMALL_MD) as answer `id` (98 columns: the fixture's),+// compiled; the watcher has its clipboard part (its first count noted).+async function drawAnswer($: any, w: ReturnType<typeof world>, id = 'ans-1', text = SMALL_MD) {+ const ui = await $.ui.mount(message(id, text))await w.clock.settle()- await ui.redraw(props(SMALL_MD))+ await ui.redraw(props(text))await w.clock.settle()await w.clock.advance(300)+ await w.clock.settle()return ui}-test('a compile writes probe.json with the PNG compile inputs and runs no probe; a copy runs it then', async ($, on) => {+// The heading row and the start of the paragraph, as a mouse copy takes them.+const COPY = [cells(1, 0, 97, '⏺ '), cells(2, 0, 97), cells(3, 0, 21)].join('\n')+const COPIED = 'Copy test\nThe quick brown fox jumps'++test('a compile writes no probe file and runs no probe; a copy probes only its page, with the PNG compile inputs', async ($, on) => {const w = world(on)await $.command.run({ command: 'iui', args: '' } as any)await drawAnswer($, w)expect(w.compiles.length).toBe(1)- expect(written(w.files, 'probe.json').length).toBe(1)- expect(written(w.files, 'positions.json')).toEqual([])+ expect(names(w.files)).toEqual(['doc.json', 'pages.json'])expect(w.queries).toEqual([])- // The probe's inputs are the compile's, and probe=1.- const probe = JSON.parse(w.files.get(written(w.files, 'probe.json')[0]!)!)- expect(Math.round(probe.ppi * 1000)).toBe(198056)- expect(inputsOf(probe.argv)).toEqual({ ...w.compiles[0], probe: '1' })- expect(probe.argv).toEqual(probeCall({ typst: '/usr/bin/typst', root: probe.argv[5].replace(/\/render\/packages$/, ''), cache: '/c', inputs: w.compiles[0]! }).argv)- // A copy needs the positions: the probe runs now, once.- w.clipboard = [cells(1, 0, 97, '⏺ '), cells(2, 0, 97), cells(3, 0, 21)].join('\n')- await w.clock.advance(300)+ w.copy(COPY)await w.clock.settle()- expect(w.queries.length).toBe(1)- expect(written(w.files, 'positions.json').length).toBe(1)- expect(w.copies).toEqual(['Copy test\nThe quick brown fox jumps'])+ expect(w.copies).toEqual([COPIED])+ // The PNG compile's inputs, probe=1 and page=1.+ expect(w.queries).toEqual([{ ...w.compiles[0], probe: '1', page: '1' }])+ // Nothing is written for it.+ expect(names(w.files)).toEqual(['doc.json', 'pages.json'])})-test('a compile retried in safe mode gives the probe safe=1', async ($, on) => {+test('a compile retried in safe mode gives the probe safe=1 (its page files say so)', async ($, on) => {const w = world(on, { failFirst: true })await $.command.run({ command: 'iui', args: '' } as any)await drawAnswer($, w)expect(w.compiles.map(c => c.safe)).toEqual([undefined, '1'])- const probe = JSON.parse(w.files.get(written(w.files, 'probe.json')[0]!)!)- expect(inputsOf(probe.argv)).toEqual({ ...w.compiles[1], probe: '1' })+ w.copy(COPY)+ await w.clock.settle()+ expect(w.queries).toEqual([{ ...w.compiles[1], probe: '1', page: '1' }])+ expect(w.copies).toEqual([COPIED])+ expect(isSafePage('/c/k/b-1.png')).toBe(true)+ expect(isSafePage('/c/k/d-12.png')).toBe(true)+ expect(isSafePage('/c/k/a-1.png')).toBe(false)+ expect(isSafePage('/c/k/c-3.png')).toBe(false)})-test('the probe runs ahead once nothing compiles, and a new job stops it', async ($, on) => {+test('a copy over two pages of a long answer probes those two pages only', async ($, on) => {+ const w = world(on)+ await $.command.run({ command: 'iui', args: '' } as any)+ const long = Array.from({ length: 240 }, (_, i) => `Paragraph ${i} with a few words in it.`).join('\n\n')+ await drawAnswer($, w, 'ans-1', long)+ const pages = (JSON.parse(w.files.get([...w.files.keys()].find(k => k.endsWith('/doc.json'))!)!) as { segments: string[] }).segments.length+ expect(pages).toBeGreaterThan(2)+ // The last row of page 1, then the first two rows of page 2.+ w.copy([cells(15, 0, 97, '⏺ '), cells(0, 0, 97), cells(1, 0, 97)].join('\n'))+ await w.clock.settle()+ expect(w.queries.map(q => q.page)).toEqual(['1', '2'])+ expect(w.copies.length).toBe(1)+ expect(w.copies[0]).toContain('Copy test')+})++test('positions are kept in memory: copies of the same page share one probe run, and a later copy runs none', async ($, on) => {const w = world(on)await $.command.run({ command: 'iui', args: '' } as any)await drawAnswer($, w)- expect(w.queries).toEqual([])- // Idle: the newest drawing with no positions is probed, held here.+ // A slow probe: a toast says the mod reads the picture.w.hold()- await w.clock.advance(PROBE_IDLE_MS)+ w.copy(COPY)await w.clock.settle()expect(w.queries.length).toBe(1)- // A new answer compiles: the probe ahead is killed, nothing is written.- const other = await $.ui.mount(message('ans-2', 'Another **answer**.'))+ expect(w.toasts).not.toContain('Intelligent UI: reading the picture…')+ await w.clock.advance(READING_TOAST_MS)+ expect(w.toasts).toContain('Intelligent UI: reading the picture…')+ // /iui grab of the same page meanwhile waits for the same run.+ w.selection = { text: COPY, requestId: 'ans-1' }+ const grabbed = $.command.run({ command: 'iui', args: 'grab' } as any)await w.clock.settle()- expect(w.kills.length).toBe(1)+ expect(w.queries.length).toBe(1)w.release()await w.clock.settle()- expect(written(w.files, 'positions.json')).toEqual([])- await other.redraw(props('Another **answer**.'))- await w.clock.settle()- // Idle again: one probe at a time, the newest first, then the next.+ expect((await grabbed).text).toBe('Intelligent UI: copied 35 chars (1 of 1 picture runs read, row ans-1).')+ expect(w.copies).toEqual([COPIED, COPIED])+ // Known now: no probe and no toast for the next copy.+ const toasts = w.toasts.lengthw.gate = null- await w.clock.advance(PROBE_IDLE_MS)+ w.selection = undefined+ w.copy([cells(1, 0, 97), cells(2, 0, 97), cells(3, 0, 21)].join('\n'))await w.clock.settle()- expect(w.queries.length).toBe(3)- expect(written(w.files, 'positions.json').length).toBe(2)+ await w.clock.advance(READING_TOAST_MS)+ expect(w.queries.length).toBe(1)+ expect(w.copies.length).toBe(3)+ expect(w.toasts.slice(toasts)).toEqual(['Intelligent UI: copied 35 chars of text'])})-test('a mouse copy of a drawn answer is read from the clipboard and written back as text, once', async ($, on) => {+test('a clipboard change runs pbpaste once and copies; no change, no read; our own write is not read as new', async ($, on) => {const w = world(on)await $.command.run({ command: 'iui', args: '' } as any)- // No picture drawn: no clipboard reads.+ // No picture drawn: the watcher has no clipboard part.await w.clock.advance(900)- expect(w.pastes).toBe(0)+ expect(w.watchers.map(c => c.argv.slice(3))).toEqual([[]])await drawAnswer($, w)- // A clipboard with no placeholders is never written.- await w.clock.advance(300)- expect(w.pastes).toBeGreaterThan(0)+ // The first picture: the watcher again with `clip`, the first one killed.+ expect(w.watchers.map(c => c.argv.slice(3))).toEqual([[], ['clip']])+ expect(w.kills).toEqual([w.watchers[0]!.pid])+ // Its first count is only noted; no change, no read.+ await w.clock.advance(900)+ expect(w.pastes).toBe(0)+ // A copy with no placeholders: one read, never written.+ w.copy('copied in another app')+ await w.clock.settle()+ expect(w.pastes).toBe(1)expect(w.copies).toEqual([])- // The heading row and the start of the paragraph, as a mouse copy takes them.- w.clipboard = [cells(1, 0, 97, '⏺ '), cells(2, 0, 97), cells(3, 0, 21)].join('\n')- await w.clock.advance(300)+ w.copy(COPY)await w.clock.settle()- expect(w.copies).toEqual(['Copy test\nThe quick brown fox jumps'])+ expect(w.copies).toEqual([COPIED])expect(w.toasts).toContain('Intelligent UI: copied 35 chars of text')- // Our own write is not read again.+ // One read before the write; our own write changes the count: read+ // once, not copied again.+ expect(w.pastes).toBe(4)await w.clock.advance(900)+ expect(w.pastes).toBe(4)expect(w.copies.length).toBe(1)const dumped = await $.command.run({ command: 'iui', args: 'dump' } as any)expect(dumped.text).toContain('U+10EEEE[1,0]')expect(dumped.text).toContain('-> answer ans-1 page 0')+ expect(dumped.text).toContain('auto copy on')expect(w.files.has('/c/copy-debug.json')).toBe(true)- // Off: the watcher stops.+ // Off: the watcher again with no clipboard part; no reads.await $.command.run({ command: 'iui', args: 'off' } as any)- const pastes = w.pastes- await w.clock.advance(900)- expect(w.pastes).toBe(pastes)+ expect(w.watchers.map(c => c.argv.slice(3))).toEqual([[], ['clip'], []])+ await w.clock.settle()+ expect(w.kills).toEqual([w.watchers[0]!.pid, w.watchers[1]!.pid])+ w.copy(COPY)+ await w.clock.settle()+ expect(w.pastes).toBe(4)})-test('a new mouse selection with picture cells is copied at the next tick, with no clipboard read', async ($, on) => {+test('/iui details says whether the automatic copy is on', async ($, on) => {const w = world(on)+ const details = async () => ((await $.command.run({ command: 'iui', args: 'details' } as any)).text ?? '').split('\n').find(l => l.startsWith('Auto copy:'))+ expect(await details()).toBe('Auto copy: off (no picture yet)')+ await drawAnswer($, w)+ expect(await details()).toBe('Auto copy: on')+ await $.command.run({ command: 'iui', args: 'off' } as any)+ expect(await details()).toBe('Auto copy: off (Intelligent UI is off)')+})++test('with no PerlObjCBridge (clip none) the copy is off: no read, no copy; details says why; grab still copies', async ($, on) => {+ const w = world(on, { noBridge: true })await $.command.run({ command: 'iui', args: '' } as any)- await drawAnswer($, w, 'ans-1')- await drawAnswer($, w, 'ans-0')- // ans-0 is newer, but the selection names its row: ans-1.- w.selection = { text: [cells(1, 0, 97), cells(2, 0, 97), cells(3, 0, 21)].join('\n'), requestId: 'ans-1' }- const pastes = w.pastes- await w.clock.advance(300)+ await drawAnswer($, w)+ w.copy(COPY)+ await w.clock.advance(900)await w.clock.settle()- expect(w.copies).toEqual(['Copy test\nThe quick brown fox jumps'])- expect(w.pastes).toBe(pastes)- const dumped = await $.command.run({ command: 'iui', args: 'dump' } as any)- expect(dumped.text).toContain('-> answer ans-1 page 0')- // The same selection again: not copied again.- await w.clock.advance(600)- expect(w.copies.length).toBe(1)- // /iui grab copies it on request.+ expect(w.pastes).toBe(0)+ expect(w.copies).toEqual([])+ const details = await $.command.run({ command: 'iui', args: 'details' } as any)+ expect(details.text).toContain('\nAuto copy: off (no PerlObjCBridge in /usr/bin/perl)')+ // No new watcher for it: once is enough.+ await drawAnswer($, w, 'ans-2')+ expect(w.watchers.length).toBe(2)+ w.selection = { text: COPY, requestId: 'ans-1' }const grabbed = await $.command.run({ command: 'iui', args: 'grab' } as any)expect(grabbed.text).toBe('Intelligent UI: copied 35 chars (1 of 1 picture runs read, row ans-1).')- expect(w.copies.length).toBe(2)})// Another plugin's `$.ui.copy`, from its command `cp` (args: the text).@@ -477,11 +548,24 @@ test('a copy of picture cells through $.ui.copy is rewritten to their text; otheawait drawAnswer($, w)const got = await $.command.run({ command: 'cp', args: [cells(1, 0, 97), cells(2, 0, 97), cells(3, 0, 21)].join('\n') } as any)expect(JSON.parse(got.text!)).toEqual({ isCopied: true })- expect(w.copies).toEqual(['Copy test\nThe quick brown fox jumps'])+ expect(w.copies).toEqual([COPIED])await $.command.run({ command: 'cp', args: 'plain text' } as any)expect(w.copies[1]).toBe('plain text')})+test('a $.ui.copy of picture cells is not copied again at its clipboard change', { plugins: [COPIER] }, async ($, on) => {+ const w = world(on)+ await $.command.run({ command: 'iui', args: '' } as any)+ await drawAnswer($, w)+ w.selection = { text: COPY, requestId: 'ans-1' }+ await $.command.run({ command: 'cp', args: COPY } as any)+ await w.clock.advance(900)+ await w.clock.settle()+ expect(w.pastes).toBe(1)+ expect(w.copies).toEqual([COPIED])+ expect(w.toasts.filter(t => t.startsWith('Intelligent UI: copied')).length).toBe(0)+})+test('a clipboard with picture cells that is not this session\'s selection is not rewritten (another session\'s copy)', async ($, on) => {const w = world(on)await $.command.run({ command: 'iui', args: '' } as any)@@ -489,60 +573,159 @@ test('a clipboard with picture cells that is not this session\'s selection is no// This session has a selection of its own (no picture cells), and the// clipboard has another session's picture cells.w.selection = { text: 'my own text', requestId: 'u1' }- w.clipboard = [cells(1, 0, 97), cells(3, 0, 21)].join('\n')- await w.clock.advance(600)+ w.copy([cells(1, 0, 97), cells(3, 0, 21)].join('\n'))+ await w.clock.settle()+ expect(w.pastes).toBe(1)expect(w.copies).toEqual([])// The same copy as the selection, with a last line break: rewritten.- w.selection = { text: [cells(1, 0, 97), cells(2, 0, 97), cells(3, 0, 21)].join('\n'), requestId: 'ans-1' }- await $.command.run({ command: 'iui', args: 'off' } as any)- await $.command.run({ command: 'iui', args: 'on' } as any)- await drawAnswer($, w, 'ans-2')- w.clipboard = `${w.selection.text}\n`- await w.clock.advance(300)+ w.selection = { text: COPY, requestId: 'ans-1' }+ w.copy(`${COPY}\n`)await w.clock.settle()- expect(w.copies).toEqual(['Copy test\nThe quick brown fox jumps'])+ expect(w.copies).toEqual([COPIED])})-test('a watcher that starts again (a hot reload) does not copy the selection that was there before', async ($, on) => {+test('a watcher that starts again does not copy the clipboard that was there before (its first count is only noted)', async ($, on) => {const w = world(on)- // An old selection with picture cells, and a clipboard filled elsewhere.- w.selection = { text: [cells(1, 0, 97), cells(3, 0, 21)].join('\n'), requestId: 'ans-1' }- w.clipboard = 'copied in another app'+ // Picture cells on the clipboard before this load (a hot reload).+ w.clipboard = COPYawait $.command.run({ command: 'iui', args: '' } as any)await drawAnswer($, w)await w.clock.advance(900)+ expect(w.pastes).toBe(0)expect(w.copies).toEqual([])- expect(w.clipboard).toBe('copied in another app')- // A new selection is copied.- w.selection = { text: [cells(1, 0, 97), cells(2, 0, 97), cells(3, 0, 21)].join('\n'), requestId: 'ans-1' }- await w.clock.advance(300)+ // A new copy is copied.+ w.copy(COPY)await w.clock.settle()- expect(w.copies).toEqual(['Copy test\nThe quick brown fox jumps'])+ expect(w.copies).toEqual([COPIED])})-test('a selection that can not be read gives one toast, not one more from the clipboard', async ($, on) => {+test('a copy that can not be read gives one toast; the same text again gives none', async ($, on) => {const w = world(on)await $.command.run({ command: 'iui', args: '' } as any)await drawAnswer($, w)// Column 150: wider than any picture drawn.const text = [cells(1, 0, 150), cells(2, 0, 150)].join('\n')- w.selection = { text, requestId: 'ans-1' }- w.clipboard = text- await w.clock.advance(900)+ w.copy(text)+ await w.clock.settle()+ w.copy(text)await w.clock.settle()+ expect(w.pastes).toBe(2)expect(w.copies).toEqual([])expect(w.toasts.filter(t => t.startsWith('Intelligent UI: could not read')).length).toBe(1)})-test('a $.ui.copy of the selection is not copied again by the watcher', { plugins: [COPIER] }, async ($, on) => {+test('a clipboard change while a copy is read: the newer clipboard is read after it and is not written over', async ($, on) => {const w = world(on)await $.command.run({ command: 'iui', args: '' } as any)await drawAnswer($, w)- const text = [cells(1, 0, 97), cells(2, 0, 97), cells(3, 0, 21)].join('\n')- w.selection = { text, requestId: 'ans-1' }- await $.command.run({ command: 'cp', args: text } as any)- await w.clock.advance(900)+ w.hold()+ w.copy(COPY)await w.clock.settle()- expect(w.copies).toEqual(['Copy test\nThe quick brown fox jumps'])- expect(w.toasts.filter(t => t.startsWith('Intelligent UI: copied')).length).toBe(0)+ expect(w.queries.length).toBe(1)+ w.copy('copied in another app')+ await w.clock.settle()+ expect(w.pastes).toBe(1)+ w.release()+ await w.clock.settle()+ // One read before the write (not the copy now: no write), one of the newer.+ expect(w.pastes).toBe(3)+ expect(w.copies).toEqual([])+ expect(w.clipboard).toBe('copied in another app')+})++test('the same copy again while its picture is read: copied once, one toast', async ($, on) => {+ const w = world(on)+ await $.command.run({ command: 'iui', args: '' } as any)+ await drawAnswer($, w)+ w.hold()+ w.copy(COPY)+ await w.clock.settle()+ w.copy(COPY)+ await w.clock.settle()+ w.release()+ await w.clock.settle()+ expect(w.queries.length).toBe(1)+ expect(w.copies).toEqual([COPIED])+ expect(w.clipboard).toBe(COPIED)+ expect(w.toasts.filter(t => t.startsWith('Intelligent UI: copied'))).toEqual(['Intelligent UI: copied 35 chars of text'])+ // A copy of it after the write is a new copy: copied again (no probe).+ w.copy(COPY)+ await w.clock.settle()+ expect(w.copies).toEqual([COPIED, COPIED])+ expect(w.queries.length).toBe(1)+})++test('a newer clipboard that the watcher has not said yet is not written over; it is read next', async ($, on) => {+ const w = world(on)+ await $.command.run({ command: 'iui', args: '' } as any)+ await drawAnswer($, w)+ // Other picture cells: copied as their own text, not the first copy's.+ w.hold()+ w.copy([cells(2, 0, 97), cells(3, 0, 21)].join('\n'))+ await w.clock.settle()+ w.clipboard = COPY+ w.release()+ await w.clock.settle()+ expect(w.copies).toEqual([COPIED])+ expect(w.clipboard).toBe(COPIED)+ // Text with no picture cells (a page not probed yet): kept as it is.+ await drawAnswer($, w, 'ans-2', `${SMALL_MD}\n\nEnd.`)+ w.gate = null+ w.hold()+ w.copy(COPY)+ await w.clock.settle()+ expect(w.queries.length).toBe(2)+ w.clipboard = 'copied in another app'+ w.release()+ await w.clock.settle()+ expect(w.copies).toEqual([COPIED])+ expect(w.clipboard).toBe('copied in another app')+ expect(w.toasts.filter(t => t.startsWith('Intelligent UI: copied')).length).toBe(1)+ // Its change comes late: one read, the same text, nothing more.+ const pastes = w.pastes+ w.copy('copied in another app')+ await w.clock.settle()+ expect(w.pastes).toBe(pastes + 1)+ expect(w.copies).toEqual([COPIED])+})++test('at an exit the watcher is killed and no child takes its place; a /clear starts it again with no clipboard part', async ($, on) => {+ const w = world(on)+ on('session.end', async ($: any, e: any) => ({ sessionId: e.sessionId }))+ await $.command.run({ command: 'iui', args: '' } as any)+ await drawAnswer($, w)+ expect(w.watchers.map(c => c.argv.slice(3))).toEqual([[], ['clip']])+ await $.session.end({ reason: 'clear', sessionId: 's1' } as any)+ await w.clock.settle()+ expect(w.watchers.map(c => c.argv.slice(3))).toEqual([[], ['clip'], []])+ expect(w.kills).toEqual([w.watchers[0]!.pid, w.watchers[1]!.pid])+ w.copy(COPY)+ await w.clock.settle()+ expect(w.pastes).toBe(0)+ await $.session.end({ reason: 'prompt_input_exit', sessionId: 's2' } as any)+ await w.clock.settle()+ await w.clock.advance(5000)+ expect(w.watchers.length).toBe(3)+ expect(w.kills).toEqual(w.watchers.map(c => c.pid))+})++test('a clip child that ends on its own is started again; its old clipboard is not written', async ($, on) => {+ const w = world(on)+ await $.command.run({ command: 'iui', args: '' } as any)+ await drawAnswer($, w)+ const first = w.watchers[1]!+ first.dead = true+ first.say('')+ await w.clock.settle()+ // Picture cells put on the clipboard while no child watched: the count of+ // the new child at its start is only noted.+ w.clipboard = COPY+ w.count+++ await w.clock.advance(WATCH_RESTART_MS)+ await w.clock.settle()+ expect(w.watchers.map(c => c.argv.slice(3))).toEqual([[], ['clip'], ['clip']])+ expect(w.pastes).toBe(0)+ w.copy(COPY)+ await w.clock.settle()+ expect(w.copies).toEqual([COPIED])})diff --git a/tests/draw.test.ts b/tests/draw.test.tsindex 02a0823..43af218 100644--- a/tests/draw.test.ts+++ b/tests/draw.test.ts@@ -1,7 +1,7 @@import { expect, mock, test } from 'claude-code/testing'import {- scaledBulletRow, base64Bytes, canDrawIn, COMMIT_MIN_MS, DEFAULT_CELL, fitsInline, INLINE_MAX_BYTES, INLINE_MAX_SIDE, inlineBudget, renderKey, RESIZE_QUIET_MS, SEGMENT_ROWS,+ scaledBulletRow, base64Bytes, canDrawIn, COMMIT_MIN_MS, DEFAULT_CELL, fitsInline, INLINE_MAX_BYTES, INLINE_MAX_SIDE, inlineBudget, renderKey, RESIZE_QUIET_MS, SEGMENT_ROWS, WATCH_PL,} from '../hooks/register'// ---- Where pictures draw ----------------------------------------------------@@ -129,13 +129,13 @@ function world(on: any, vars: Record<string, string>, head = HEAD, stored: Recoron('process.spawn', async function* ($: any, e: any) {const argv: string[] = e.argvcalls.push(`spawn ${argv[0]}`)- if (argv[0] === 'perl') {+ if (argv[0] === '/usr/bin/perl' && argv[2] === WATCH_PL) {if (!tty || tty.watcher !== undefined) return { value: { code: tty?.watcher ?? 1, signal: null } }- // The watcher prints the size at its start, then at each change.- const lines: string[] = tty.line ? [tty.line] : []+ // The watcher prints its PID, then the size at its start and at each change.+ const lines: string[] = ['pid 777', ...(tty.line ? [`size ${tty.line}`] : [])]let wake = () => {}watchers.push(line => {- lines.push(line)+ lines.push(`size ${line}`)wake()})for (;;) {diff --git a/tests/frame.test.ts b/tests/frame.test.tsindex d4c49c4..d2aca12 100644--- a/tests/frame.test.ts+++ b/tests/frame.test.ts@@ -2,11 +2,11 @@ import { expect, test } from 'claude-code/testing'import {composeFrame, followWatcher, frameChange, frameFor, frameOfLine, lineSplitter, noteTty, noteView, pictureColumns, quietTimer, setFrame, shownFor,- type Frame,+ WATCH_RESTART_MS, WATCH_RESTARTS, watchFrame, watchLineOf, watchState, type Frame, type WatchLine,} from '../hooks/lib/frame'import { COMMIT_MIN_MS, DEFAULT_CELL, IMAGE_MAX_COLUMNS, RESIZE_QUIET_MS } from '../hooks/lib/settings'import { INLINE_MAX_SIDE } from '../hooks/lib/terminal'-import { FRAME_PL } from '../hooks/lib/host'+import { perlFor, WATCH_PL } from '../hooks/lib/host'// The module state the Frame reads and sets (this file's copy of the// modules is the one imported above).import { converting, queue, running, S } from '../hooks/lib/state'@@ -33,7 +33,7 @@ test('columns go before rows; rows only is a rows change', () => {// ---- One watcher line ----------------------------------------------------------test('a watcher line is rows, columns and the cell in device pixels', () => {+test('a tty size is rows, columns and the cell in device pixels', () => {expect(frameOfLine('50 120 2040 1700')).toEqual(frame(120, 50, 17, 34))expect(frameOfLine('40 200 3200 1360\n')).toEqual(frame(200, 40, 16, 34))})@@ -54,6 +54,21 @@ test('an absurd or broken line is no Frame', () => {expect(frameOfLine('-50 120 2040 1700')).toBe(null)})+test('a watcher line is its PID, a size, a clipboard change count or clip none; any other line is none', () => {+ expect(watchLineOf('pid 4242')).toEqual({ pid: '4242' })+ expect(watchLineOf('size 50 120 2040 1700')).toEqual({ size: frame(120, 50, 17, 34) })+ // A bad size is a size line with no Frame (noteTty drops it).+ expect(watchLineOf('size 50 200 0 0')).toEqual({ size: null })+ expect(watchLineOf('clip 1394')).toEqual({ clip: 1394 })+ expect(watchLineOf('clip none\r')).toEqual({ clip: null })+ expect(watchLineOf('clip -1')).toBe(null)+ expect(watchLineOf('clip')).toBe(null)+ expect(watchLineOf('pid x')).toBe(null)+ // The bare size of one tty read (CELL_SH) is not a watcher line.+ expect(watchLineOf('50 120 2040 1700')).toBe(null)+ expect(watchLineOf('')).toBe(null)+})+// ---- Pieces to lines ----------------------------------------------------------test('pieces join into lines across their borders', () => {@@ -71,10 +86,11 @@ const pieces = (texts: Array<{ stream?: 'stdout' | 'stderr'; text: string }>, coreturn { code, signal: null }})()-test('the watcher lines go to noteTty as Frames; a bad line goes as null', async () => {- const seen: Array<Frame | null> = []- const ended = await followWatcher(pieces([{ text: '50 120 20' }, { text: '40 1700\n' }, { stream: 'stderr', text: '1 1 1 1\n' }, { text: 'junk\n40 200 3200 1360\n' }], 0), f => seen.push(f))- expect(seen).toEqual([frame(120, 50, 17, 34), null, frame(200, 40, 16, 34)])+test('the watcher lines are read across pieces; stderr and other lines are dropped', async () => {+ const seen: WatchLine[] = []+ const text = [{ text: 'pid 7\nsize 50 120 20' }, { text: '40 1700\nclip 3' }, { stream: 'stderr' as const, text: 'size 1 1 1 1\n' }, { text: '\njunk\nsize 40 200 3200 1360\nclip none\n' }]+ const ended = await followWatcher(pieces(text, 0), line => seen.push(line))+ expect(seen).toEqual([{ pid: '7' }, { size: frame(120, 50, 17, 34) }, { clip: 3 }, { size: frame(200, 40, 16, 34) }, { clip: null }])expect(ended).toBe('failed')})@@ -88,14 +104,31 @@ test('a watcher that exits 1 has no tty; one that can not start failed', async (// ---- The watcher ------------------------------------------------------------------test('FRAME_PL sleeps in sigsuspend with SIGWINCH blocked outside it: no select, no poll', () => {- expect(FRAME_PL).toContain('POSIX::sigsuspend(')- expect(FRAME_PL).toContain('POSIX::sigprocmask(POSIX::SIG_BLOCK()')- expect(FRAME_PL).toContain('$n{WINCH}')- // The alarm only finds a dead parent.- expect(FRAME_PL).toContain('alarm(10)')- expect(FRAME_PL).not.toContain('select')- expect(FRAME_PL).not.toContain('sleep')+test('WATCH_PL sleeps in sigsuspend with SIGWINCH and SIGALRM blocked outside it: no select, no sleep', () => {+ expect(WATCH_PL).toContain('POSIX::sigsuspend(')+ expect(WATCH_PL).toContain('POSIX::sigprocmask(POSIX::SIG_BLOCK(), POSIX::SigSet->new($n{WINCH}, $n{ALRM}))')+ // With no clipboard part, the alarm only finds a dead parent; with it, a+ // 300 ms alarm reads the change count (the same sigsuspend: a SIGWINCH+ // that comes meanwhile is kept).+ expect(WATCH_PL).toContain('alarm(10)')+ expect(WATCH_PL).toContain('Time::HiRes::ualarm(300000)')+ expect(WATCH_PL).toContain('exit 0 if getppid() != $parent')+ expect(WATCH_PL).not.toContain('select')+ expect(WATCH_PL).not.toContain('sleep')+})++test('WATCH_PL loads the bridge in an eval only with the clip argument, and says clip none when it fails', () => {+ expect(WATCH_PL).toContain('if (($ARGV[0] // "") eq "clip")')+ expect(WATCH_PL).toContain('$pb = eval { require Foundation; Foundation->import;')+ expect(WATCH_PL).toContain('@NSPasteboard::ISA = ("PerlObjCBridge")')+ expect(WATCH_PL).toContain('print "clip none\\n" or exit 0 unless $pb;')+ expect(WATCH_PL).toContain('print "clip $c\\n"')+ expect(WATCH_PL).toContain('print "size $line\\n"')+ expect(WATCH_PL).toContain('print "pid $$\\n"')+ // No tty and no clipboard part: exit 1.+ expect(WATCH_PL).toContain('exit 1 unless $tty || $pb;')+ expect(perlFor(true)).toBe('/usr/bin/perl')+ expect(perlFor(false)).toBe('perl')})// ---- The quiet timer ----------------------------------------------------------------@@ -228,10 +261,33 @@ test('a picture takes the Frame\'s columns less the gutter, capped by the width// clock in memory, a tty read the test sets (and may hold), and the redraws.const clock = fakeClock()const tty = { line: '50 200 3400 1700', reads: 0, gate: null as Promise<void> | null, refreshes: 0 }+// The watchers started: each one's argv, `say` (a line it prints) and+// `end` (its exit); the PIDs killed.+type Child = { argv: string[]; say: (line: string) => void; end: (code: number) => void }+const children: Child[] = []+const kills: string[] = []+function spawn({ argv }: { argv: string[] }) {+ const lines: string[] = []+ let code: number | null = null+ let wake = () => {}+ children.push({ argv, say: line => (lines.push(line), wake()), end: c => ((code = c), wake()) })+ return (async function* () {+ for (;;) {+ while (lines.length) yield { stream: 'stdout' as const, text: `${lines.shift()}\n` }+ if (code !== null) return { code, signal: null }+ await new Promise<void>(r => (wake = r))+ }+ })()+}const $ = {clock: { after: clock.after },process: {- run: async () => {+ spawn,+ run: async (argv: string[]) => {+ if (argv[0] === 'kill') {+ kills.push(argv[1]!)+ return { exitCode: 0, stdout: '', stderr: '' }+ }tty.reads++if (tty.gate) await tty.gatereturn { exitCode: 0, stdout: tty.line, stderr: '' }@@ -356,3 +412,99 @@ test('an input during the quiet read stops that settle: the newer quiet settlesexpect(S.epoch).toBe(epoch + 1)expect(S.frame).toEqual(frame(140, 50, 17, 34))})++// ---- The watcher's restarts ---------------------------------------------------++test('with no watcher, the clipboard part off starts none', () => {+ watchFrame($, null)+ expect(children.length).toBe(0)+ expect(watchState()).toBe(null)+})++test('the clipboard part starts the watcher again with clip; the old one is killed and its lines dropped; the size again begins no epoch', async () => {+ await loaded('50 200 3400 1700')+ noteView($, { columns: 200, rows: 50 })+ const epoch = S.epoch+ watchFrame($)+ const first = children[0]!+ expect(first.argv).toEqual(['perl', '-e', WATCH_PL])+ first.say('pid 101')+ first.say('size 50 200 3400 1700')+ await flush()+ expect(watchState()).toEqual({ clip: false, ended: false })+ // On: a new child with the argument, and a kill of the first.+ const counts: Array<number | null> = []+ watchFrame($, n => counts.push(n))+ const second = children[1]!+ expect(second.argv).toEqual(['perl', '-e', WATCH_PL, 'clip'])+ await flush()+ expect(kills).toEqual(['101'])+ first.say('size 50 150 2550 1700')+ second.say('pid 102')+ second.say('size 50 200 3400 1700')+ second.say('clip 7')+ await flush()+ // The size known: no burst, no read, no epoch.+ expect(S.resizing).toBe(false)+ await clock.advance(RESIZE_QUIET_MS * 2)+ expect(tty.reads).toBe(0)+ expect(S.epoch).toBe(epoch)+ expect(S.frame).toEqual(frame(200, 50, 17, 34))+ expect(counts).toEqual([7])+ expect(watchState()).toEqual({ clip: true, ended: false })+ // The same part again, and setUp's start: no new child.+ watchFrame($, n => counts.push(n))+ watchFrame($)+ expect(children.length).toBe(2)+ second.say('clip 8')+ second.say('clip none')+ await flush()+ expect(counts).toEqual([7, 8, null])+ // Off: a child with no argument; the one before is killed.+ watchFrame($, null)+ expect(children[2]!.argv).toEqual(['perl', '-e', WATCH_PL])+ await flush()+ expect(kills).toEqual(['101', '102'])+ // A child stopped before its PID came is killed when it comes.+ watchFrame($, n => counts.push(n))+ children[2]!.say('pid 103')+ await flush()+ expect(kills).toEqual(['101', '102', '103'])+ // A size change from the child now goes on as before.+ const fourth = children[3]!+ fourth.say('pid 104')+ tty.line = '50 150 2550 1700'+ fourth.say('size 50 150 2550 1700')+ await flush()+ expect(S.resizing).toBe(true)+ await clock.advance(RESIZE_QUIET_MS)+ expect(S.epoch).toBe(epoch + 1)+ // A child that ends is noted (details says the copy is off).+ fourth.end(0)+ await flush()+ expect(watchState()).toEqual({ clip: true, ended: true })+})++test('a clip child that ends on its own starts again after WATCH_RESTART_MS, WATCH_RESTARTS times at most', async () => {+ // The last child of the test before ended on its own.+ const before = children.length+ await clock.advance(WATCH_RESTART_MS - 1)+ expect(children.length).toBe(before)+ await clock.advance(1)+ expect(children.length).toBe(before + 1)+ expect(children.at(-1)!.argv).toEqual(['perl', '-e', WATCH_PL, 'clip'])+ expect(watchState()).toEqual({ clip: true, ended: false })+ for (let i = 1; i < WATCH_RESTARTS; i++) {+ children.at(-1)!.end(0)+ await flush()+ await clock.advance(WATCH_RESTART_MS)+ }+ expect(children.length).toBe(before + WATCH_RESTARTS)+ // The cap: the next end starts none, and neither does a call that wants one.+ children.at(-1)!.end(0)+ await flush()+ await clock.advance(WATCH_RESTART_MS * 5)+ watchFrame($)+ expect(children.length).toBe(before + WATCH_RESTARTS)+ expect(watchState()).toEqual({ clip: true, ended: true })+})