Skip to content

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

TypeScript claude-code-mod

Remove the copy shims; build page frames and words in the background

razorback16bdcf8b6ac9dd
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1674355..05ae86c 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,13 +6,13 @@ All releases of Intelligent UI for Claude Code (`cc-intelligent-ui`). Claude Cod
### New
-- **Picture select.** Since Claude Code 2.1.305, the mouse selection of Claude Code skips pictures: no highlight and no text. In fullscreen mode, the mod now selects the text of a picture itself. Drag over the picture: the selected cells show on a blue background, and when you release the button, the mod copies their text and shows the toast "copied N chars of text". A click with no drag removes the selection. The highlight swaps the page's picture with `$.ui.blit` (a frame with the selected cells tinted), so the layout never changes and a clear leaves no old cells. This needs Claude Code 2.1.305 or newer. `/iui select off` turns it off. Refer to [Copy text from a picture](docs/usage.md#copy-text-from-a-picture).
+- **Picture select.** In fullscreen mode, with Claude Code 2.1.298 or newer, the mod selects the text of a picture itself. Drag over the picture: the selected cells show on a blue background (VS Code's selection colour), and when you release the button, the mod copies their text and shows the toast "copied N chars of text". A click with no drag removes the selection. A selection can go on into the next page of the same answer. The highlight swaps the page's picture with `$.ui.blit` (a frame with the selected cells tinted), so the layout never changes. `/iui select off` turns it off. Refer to [Picture select](docs/usage.md#picture-select-claude-code-21298-or-newer).
+- **Pages ready in the background.** When a page is drawn or comes on the screen, the mod decodes it and finds its words in the background, in short slices, so scrolling and drawing continue. Thus the first highlight and the copy at the button's up do not wait. Refer to [The page cache](docs/how-it-works.md#the-page-cache).
### Changed
-- **The automatic copy asks its own session.** The mod puts small shims of Claude Code's clipboard tools (`pbcopy`; `wl-copy`, `xclip`, `xsel`) first on the `PATH` of the Claude Code process, in a folder of that process only. When Claude Code copies picture cells, the shim asks the mod of its session for their text through a private FIFO, and the real tool gets that text. The shim waits 1.5 s at most; then it uses the cells, and a toast names `/iui grab`. The mod never writes the clipboard for a copy that it did not answer. Thus a copy of a different session is never changed, also when it has the same cells. Before, the mod read the clipboard after the copy and used the mouse selection: a session with an old selection of the same cells changed the copy of a different session. Refer to [Clipboard shims](README.md#clipboard-shims).
-- A copy of picture cells that is not from this session gets the `/iui grab` toast, also in fullscreen mode.
-- `/iui details` says why the automatic copy is off when the shims cannot work (ssh, a background session, a terminal with no pictures, no `perl`, or Linux with no `wl-copy`, `xclip` or `xsel`).
+- The automatic copy of 0.3.0 is gone: the mod does not write the clipboard after a copy of picture cells in fullscreen mode. Picture select copies the text of pictures. A copy that still gives picture cells (the main screen, a selection of Claude Code that starts outside a picture) gets a toast that names `/iui grab`, and the clipboard does not change.
+- `/iui details` shows the lines `Picture select:` and `/iui grab hint:` in place of `Auto copy:`.
## 0.3.0 (2026-10-20)
diff --git a/README.md b/README.md
index a3443ed..65587fe 100644
--- a/README.md
+++ b/README.md
@@ -51,7 +51,7 @@ In other terminals, the mod shows the normal text. Refer to [Install](docs/insta
- **LaTeX math.** Inline `$…$` and display `$$…$$` math, typeset.
- **Live diagrams, charts and plots.** Claude writes Typst with CeTZ, cetz-plot and fletcher. The drawings use your theme's colours and work offline. For a complex drawing, Claude loads the bundled `intelligent-ui` skill, with the full API and a compile check.
- **Images and files.** Images in an answer, images that Claude sends, Markdown files that Claude sends, and images that you paste show in the transcript.
-- **Copy text from pictures.** In fullscreen mode, select and copy text with the mouse, as you do with normal text. On Linux, this needs a clipboard tool (refer to [Install](docs/install.md#linux)).
+- **Copy text from pictures.** In fullscreen mode, drag over a picture with the mouse, as you do over normal text. The mod highlights the selected text and copies it when you release the button. Refer to [Copy text from a picture](docs/usage.md#copy-text-from-a-picture).
- **Links you can click.** The links, file paths and commands of an answer show in rows under its picture. A cmd+click on a link opens it. A click on a command copies it.
- **Plans you can read.** In plan mode, the plan shows rendered, with an approve, edit or reject question under it.
- **Themes that follow light and dark.** Claude Code's own colours by default, or VS Code's Markdown preview. You can make your own.
@@ -88,7 +88,7 @@ More in the [gallery](docs/gallery.md): plots, fractals and a tour of all the Ma
| `/iui theme <name>` | Changes the theme: `claude-code`, `vscode-modern`, `vscode` or your own |
| `/iui size <80–200>` | Text size in percent of your terminal text |
| `/iui grid on` / `off` | Puts each line of text on the terminal rows, so that a mouse selection covers the text (on by default) |
-| `/iui select on` / `off` | Claude Code 2.1.305+, fullscreen: the mod selects and copies picture text with the mouse (on by default) |
+| `/iui select on` / `off` | Claude Code 2.1.298+, fullscreen: the mod selects and copies picture text with the mouse (on by default) |
| `/iui updates on` / `off` | Turns the daily check for a new version on or off (on by default) |
| `/iui details` | Shows the terminal, font, mode and Typst that the mod found |
| `/iui setup` | iTerm2 (macOS): adds the shell line that turns pictures on |
@@ -97,10 +97,6 @@ More in the [gallery](docs/gallery.md): plots, fractals and a tour of all the Ma
All commands are in [Usage](docs/usage.md).
-## Clipboard shims
-
-For the automatic copy, the clipboard must get the text of a copy in place of its picture cells. At the start (not over ssh, not in a background session, and only in a terminal that shows the pictures), the mod writes small `sh` scripts (shims) for the clipboard tools that Claude Code uses and that are installed: `pbcopy` on macOS, and `wl-copy`, `xclip` and `xsel` on Linux. It puts them in a folder of this Claude Code process, `shims-<pid>/`, in its cache folder (`${TMPDIR}/cc-intelligent-ui-<uid>/`), and puts this folder first on the `PATH` of the process. It also makes the folder `ask/` and a FIFO (a named pipe) `ask-<pid>` in the cache folder, and sets `IUI_COPY_ASK` to the FIFO. Before that, a setup script (`hooks/clip-shim-setup.sh`) makes sure that these folders are yours, are not links, and only you can write to them. If not, the mod makes no shims and does not change `PATH`. A shim runs the real tool with the same arguments and the same exit status. A shim asks only when Claude Code itself starts it (the shim is a direct child of the process of the FIFO) and Claude Code writes text (not an image) to the clipboard. Then `perl` keeps the text in memory. If the text has picture cells and is 4 MiB or less, the shim writes it to a request file in `ask/` (mode 600) and writes the name of the file to the FIFO. The mod of this session reads the name, finds the text under the cells, and writes it to an answer file. The shim gives this text to the real tool. If no answer comes in 1.5 s, or the mod does not run, the shim gives the cells as they are. Then it deletes the files. The shim writes no other text to disk. Nothing leaves the computer. Refer to [How it works](docs/how-it-works.md).
-
## Docs
- [Install](docs/install.md): requirements, terminal support and updates
diff --git a/docs/development.md b/docs/development.md
index 61cb408..475af2e 100644
--- a/docs/development.md
+++ b/docs/development.md
@@ -10,7 +10,7 @@ cd cc-intelligent-ui
claude --plugin-dir . # once: Claude Code writes the API types to .claude-plugin/types/
npx -p typescript tsc -p . # type check
claude plugin test . # tests
-sh tests/shim-test.sh # the clipboard shims and their asks, with fake tools and a fake mod (also dash, bash --posix)
+sh tests/cache-sh-test.sh # the cache folder sweep (CACHE_SH) in sh, dash and bash --posix
claude plugin validate .
```
@@ -20,11 +20,18 @@ claude plugin validate .
Set `IUI_DEBUG=1` before you start Claude Code. The mod then writes trace lines to `debug.log` in the cache folder (`${TMPDIR}/cc-intelligent-ui-<uid>/`, `/tmp` when `TMPDIR` is not set).
-Picture select writes one line for each post of a `Client` (lines that start with `select:`): the phase and the order, the drawing's id, the page, the anchor and the head (the `Client`'s cells), the size of the `Client`'s region, the page's size in cells, the rows of the message on screen (`onScreen`), the page's top row in the message, its rows above the screen (`above`), and the selected rows of each page. Each blit of the highlight writes a line too (`select: blit`): the page, its selected rows (or `plain`), the times to decode the page (0 when it is decoded already), make the frame and write it, the frame's bytes, and the time of `$.ui.blit`. The first decode of a page writes `select: decoded` with its time.
+Picture select writes trace lines that start with `select:`:
+
+- `select: <phase> #<order> ...`: one line for each post of a `Client`. It gives the phase and the order, the drawing's id, the page, the anchor and the head (the `Client`'s cells), the size of the `Client`'s region, the page's size in cells, the rows of the message on screen (`onScreen`), the page's top row in the message, its rows above the screen (`above`), and the selected rows of each page.
+- `select: blit <id> page <n> rows <a>..<b> (<count>)` (or `plain`): one line for each blit of the highlight. It gives the time that the frame waited for the page cache (`wait`, 0 when the page is ready), the times to make the frame (`frame`) and to write it (`write`), the frame's bytes, and the time of `$.ui.blit` (`blit`).
+- `select: cache start|first|pause|resume|stop|built ...`: the page cache. `start` gives the time to read the PNG and the pages in the queue. `first` is a `down` on a page that is not ready. `built` gives the page's size, `ready in` (the time until a frame can be made), `done in` (the time until the tinted pieces are made too), the read, the number of slices, their max and their p95, the pages kept with their MB, and the pages in the queue.
+- `select: words <id> page <n> <k> words in <ms> (background)`: the background probe of a page's words (`none` when it found no words).
+- `select: copy <n> chars <ms>ms after the up (text <ms>ms, words cached | words probed for page <n>); native selection seen (...) | no native selection`: the copy at `up`, and whether Claude Code has a selection of its own with picture cells.
+- `select: native copy seen: ...`: picture cells on the clipboard, or a `$.ui.copy` with picture cells.
## 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), `fonts.ts` (the lean font set: the fonts that a compile of plain text loads), `draw.tsx` (the pages of an answer and the link rows under them), `links.ts` (the links, file paths and commands of a text), `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), `clipboard.ts` (how the clipboard is read and watched: macOS, or the Linux tools; the clipboard shims, from the template `hooks/clip-shim.sh`, set up by `hooks/clip-shim-setup.sh`; and the reader of their asks), `copy.ts` (the text under a mouse selection of pictures), `select.ts` and `blit.ts` (picture select and its highlight), `png.ts` (PNG decode and the frames' deflate pieces, in plain JavaScript), `probe.ts` (the drawn pages, and the words of a page that a copy reads, kept in memory) and `updates.ts` (the daily check for a new version). The values that change are in one object, `S`, in `state.ts`. Each `$` method has one call site, a wrapper in `api.ts`; the other modules call the wrappers. This keeps the `calls:` note of `claude plugin validate` short (the validator cuts a note at about 1,000 characters, and the catalogue scan then cannot read the footprint). 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), `fonts.ts` (the lean font set: the fonts that a compile of plain text loads), `draw.tsx` (the pages of an answer and the link rows under them), `links.ts` (the links, file paths and commands of a text), `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), `clipboard.ts` (how the clipboard is read and watched for the `/iui grab` toast: macOS, or the Linux tools), `copy.ts` (the text under a mouse selection of pictures), `select.ts` and `blit.ts` (picture select and its highlight), `frames.ts` (the frames of a page: the cell edges, the bands, the row pieces and the frame PNG), `pagecache.ts` (the background page cache: the build queue in slices, and the words probe), `png.ts` (PNG decode, also in steps, and the deflate pieces, in plain JavaScript), `probe.ts` (the drawn pages, and the words of a page that a copy reads, kept in memory) and `updates.ts` (the daily check for a new version). The values that change are in one object, `S`, in `state.ts`. Each `$` method has one call site, a wrapper in `api.ts`; the other modules call the wrappers. This keeps the `calls:` note of `claude plugin validate` short (the validator cuts a note at about 1,000 characters, and the catalogue scan then cannot read the footprint). The tests import from `hooks/register.tsx`, which exports the names that they use.
The skill for Claude is in `skills/intelligent-ui/`: `SKILL.md` (the contract, the workflow and an index), `references/` (one file for each topic: Typst, fletcher, CeTZ, plots and charts) and `scripts/check.sh` (the compile check, with the real template). `TYPST_PROMPT` in `hooks/lib/settings.ts` tells Claude when to load it.
diff --git a/docs/how-it-works.md b/docs/how-it-works.md
index 9d58ad9..354fb3e 100644
--- a/docs/how-it-works.md
+++ b/docs/how-it-works.md
@@ -12,28 +12,41 @@
6. Pictures are kept in `${TMPDIR}/cc-intelligent-ui-<uid>/` (`/tmp` when `TMPDIR` is not set). Folders older than 2 days are deleted at start. The drawing space of each answer at its first compile is kept in `~/.cache/cc-intelligent-ui/designs`, so that its Typst drawings keep the same share of the screen in later sessions.
7. Links: the mod finds the web links, file paths and commands in the Markdown (not in code blocks or math). It draws one dim row for each under the pages, with a `Link` (an OSC 8 link) for a web link or a file, and a `Button` that copies a command (`$.ui.copy`). It keeps a file row only when the file exists (`$.fs.exists`, kept in memory for 512 paths). Each row is one terminal row, cut at its end. The copy (step 9) counts these rows under the pages, so it still finds the page that you select.
8. 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.
-9. Copy: Claude Code writes a copy (copy on select in fullscreen mode, `/copy`, `$.ui.copy`) with a tool that it starts by name from the `PATH`, as its direct child: `pbcopy` on macOS, and `wl-copy`, `xclip` or `xsel` on Linux. Before it starts the tool, it also sends the text to the terminal (OSC 52). At the start, the mod writes a small `sh` script (a shim) for each of these tools that is installed, into `<cache>/shims-<pid>/`, a folder of this Claude Code process only. It also makes the folder `<cache>/ask/` (mode 700) and the FIFO `<cache>/ask-<pid>` (mode 600) for this process. It does this only when the cache folder, the shims folder and `ask/` are folders of your user, not links, and not writable by other users (`hooks/clip-shim-setup.sh` checks this). It never uses the shared fallback folder `/tmp/cc-intelligent-ui` for this. It does not do this over ssh, in a background session, or in a terminal that shows no pictures. It puts the shims folder first on the `PATH` of the Claude Code process, one time, and sets `IUI_COPY_ASK` to the FIFO (`$.env.set`). With no `perl`, it makes no shims. Each shim has the full path of `perl`. When the mod draws its first picture, it starts a reader: a small `perl` process that keeps the FIFO open and gives the mod each name that a shim writes to it. The reader stops when Claude Code stops. If the reader stops for a different reason, the mod starts it again after 1 s (3 times at most).
+9. Copy: in fullscreen mode, picture select copies the text of a picture (refer to [Picture select](#picture-select)). A copy that still puts picture cells on the clipboard is a native copy: the copy of the terminal itself on the main screen, a selection of Claude Code that starts outside a picture, or a copy of a different session. The mod never writes the clipboard for a native copy.
- A shim asks only for a clipboard write of text (with no type, or a text type: `text/plain…`, `UTF8_STRING`, `STRING` or `TEXT`), and only when its parent is the process of the FIFO (the number in `ask-<pid>`). Other calls (a read, the primary selection, an image type) go to the real tool with no change and with no `perl`. For a write, the shim starts `perl`, which keeps the text in memory. If the text has picture cells (the bytes of U+10EEEE) and is 4 MiB or less, `perl` writes it to a request file `ask/<pid>-<shim pid>-<time>` (mode 600) and writes the name of the file to the FIFO. Before that, it makes sure that the FIFO and `ask/` are of your user and are not links. If no reader has the FIFO open (for example, the mod stopped), the open fails immediately, and the shim uses the cells. `perl` waits for the answer file for 1.5 s at most from its start, because Claude Code stops the tool after 2 s. Then it gives the answer (or the cells, when the answer is empty or did not come) to the real tool through a pipe, with the same arguments, and gives the exit status of the tool (also a signal). The shim deletes the request and the answer. It writes no other file. The mod takes only names of letters, digits, `.`, `_` and `-` from the FIFO (never a path), and reads the request file only in `ask/`, at most 4 MiB. It finds the text under the cells (see below). When the mouse selection of its session is that copy, the mod uses the row of the selection. It always answers: with the text, or with an empty answer when it cannot read the cells, so the shim does not wait. It writes the answer (mode 600) to a temporary file, then makes a hard link with the answer name. If the shim stopped waiting, the shim made that name first, so the link fails. Then the mod writes nothing to the clipboard: a different session can copy the same cells at that time. It deletes the request and the mark, and a toast tells you to use `/iui grab`. The mod writes the clipboard only in its answer to its own shim, and in `/iui grab` and the `ui.copy` hook. At `/clear` or a resume, the reader continues. At other session ends (for example `/exit`), the mod stops the reader and deletes the FIFO, the request files and the shims folder of this process. At the start, the mod deletes the FIFOs, the request files and the shims folders of processes that stopped, and request files that are older than 2 days. It does nothing in a cache folder that is a link or that is not yours.
+ One long-lived `perl` process (the watcher) watches the terminal size (at each SIGWINCH) and the clipboard. On macOS, 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). On Linux, the process starts a child in a process group of its own. The child runs a tool that prints a line at each clipboard change (`wl-paste --watch`, `clipnotify` or GTK 3 from Python, refer to [Linux](install.md#linux)) and gives the mod a counter for each line. Nothing runs between two changes. When the `perl` process stops, it stops that process group. 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` on macOS; `wl-paste`, `xclip`, `xsel` or GTK on Linux). When the clipboard has picture cells that fit a page drawn in this session, the mod shows one toast that names `/iui grab`. It does not change the clipboard. The first counter after a start is not a change, so an old clipboard gets no toast. If the watcher stops, the mod starts it again after 1 s (3 times at most). At `/clear` or a resume, the watcher continues without the clipboard part. At other session ends (for example `/exit`), the mod stops it and does not start a new one.
- One long-lived `perl` process (the watcher) watches the terminal size (at each SIGWINCH) and the clipboard. On macOS, 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). On Linux, the process starts a child in a process group of its own. The child runs a tool that prints a line at each clipboard change (`wl-paste --watch`, `clipnotify` or GTK 3 from Python, refer to [Linux](install.md#linux)) and gives the mod a counter for each line. Nothing runs between two changes. When the `perl` process stops, it stops that process group. 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` on macOS; `wl-paste`, `xclip`, `xsel` or GTK on Linux). The mod never changes a copy of picture cells that no shim of this session asked for (a copy of a different session, or of the terminal itself on the main screen). When these cells fit a page drawn in this session, it shows one toast that names `/iui grab`. In fullscreen mode, it first waits 2 s, because the OSC 52 copy can come before the shim asks. `/iui grab` then reads the picture cells on the clipboard and writes their text. The first counter after a start is not a change, so an old clipboard gets no toast. If the watcher stops, the mod starts it again after 1 s (3 times at most). At `/clear` or a resume, the watcher continues without the clipboard part. At other session ends, the mod stops it and does not start a new one.
+ `/iui grab` reads the last mouse selection of Claude Code (`$.ui.selection`). With no selection (the main screen), it reads the picture cells on the clipboard. Then it writes their text with `$.ui.copy`. A `ui.copy` hook also changes a copy with picture cells (for example, from `/copy` or `$.ui.copy`) to the text. The mod writes the clipboard only for picture select, `/iui grab` and the `ui.copy` hook.
- 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. A `ui.copy` hook also changes a copy with picture cells to the text.
+ 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>`) only for the pages that a copy reads, and (for picture select) for the pages on the screen. 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.
## Picture select
-From Claude Code 2.1.305, the mod's `Image` has `noSelect`: the selection painter and the copy on select of Claude Code skip picture cells. Thus the mod selects pictures itself (`hooks/lib/select.ts`):
+The selection of Claude Code copies picture cells as kitty placeholder characters, not as text (from Claude Code 2.1.305, it skips picture cells). Thus the mod selects pictures itself (`hooks/lib/select.ts`):
1. Each page is in a `Box` of its size. The last child is a `Client` (`hooks/sel.tsx`) in a `Box` with a negative top margin (the page's rows), so it is over the page. The `Client` draws only an empty `Box` (anything that it draws hides the picture cells). It takes the pointer and posts the selection whole: the anchor, the head, the phase (`down`, `move`, `up` or `clear`) and an order. Posts of one frame merge, so a bare event could be lost.
2. The `ui.message` hook keeps the newest selection. The selected rows are in stream order, in the rows of the whole drawing, so a drag can go on into the next page.
3. The highlight does not change the layout. Each page stays one keyed `Image`, and the mod swaps its picture with `$.ui.blit` (`hooks/lib/blit.ts`). This is one small kitty command with the same image id (`a=T`, `t=f`, the file name), so the terminal replaces the picture in place. The frame is the page with the selected cells changed: in a selected cell, each pixel of the page (straight alpha) over the opaque selection colour; in the other cells, the page as it is. A clear swaps the page's own PNG back. Cell `i` is the pixels from `round(i × pixels / cells)` to `round((i + 1) × pixels / cells)`, so the cells cover the page with no gap at any ratio.
-4. The hooks runtime has no zlib, so `hooks/lib/png.ts` decodes the page in JavaScript (inflate and unfilter) at the first `down` on it, one time. The mod keeps the decoded pages in memory, 128 MB at most (about two pages of 3392 × 4284 pixels). For each row of cells, it makes a deflate piece one time (fixed Huffman codes, matches of one pixel to the left or one pixel up, ended on a byte). A row that is selected whole has a tinted piece, also made one time. A frame makes new pieces only for the first and last selected rows (partly selected), and joins the pieces into one PNG (about 1.5 MB for a page of 3392 × 4284 pixels). The hooks can write only text, so `perl` writes the frame (base64 on its stdin) to `<cache>/select-<id>/f-<n>.png`. The terminal reads the file after the blit. The mod deletes a frame file when 4 newer frames are written and it is 2 s old. The 2-day cleanup of the cache folder deletes the rest.
+4. The hooks runtime has no zlib, so `hooks/lib/png.ts` decodes the page in JavaScript (inflate and unfilter). For each row of cells, the mod makes a deflate piece one time (fixed Huffman codes, matches of one pixel to the left or one pixel up, ended on a byte). A row that is selected whole has a tinted piece, also made one time. A frame makes new pieces only for the first and last selected rows (partly selected), and joins the pieces into one PNG (about 1.5 MB for a page of 3392 × 4284 pixels). The first highlight frame of a ready page takes approximately 2–3 ms to make. The hooks can write only text, so `perl` writes the frame (base64 on its stdin) to `<cache>/select-<id>/f-<n>.png`. The terminal reads the file after the blit. The mod deletes a frame file when 4 newer frames are written and it is 2 s old. The 2-day cleanup of the cache folder deletes the rest.
5. A new frame starts at most once in 16 ms, and only after the last one is blitted. The posts between fold into one frame of the newest selection. If Claude Code refuses a blit, the mod writes the reason one time to the debug log and shows no highlight on that page until the next `down`. The copy still works.
-6. At `up`, the mod reads the words under the selected cells the same way as for a copy of these cells (`textOfRun` on the words of the probe), and copies them with `$.ui.copy`.
+6. At `up`, the mod reads the words under the selected cells the same way as for a copy of these cells (`textOfRun` on the words of the probe), and copies them with `$.ui.copy`. A toast shows "copied N chars of text".
The `Client` is in the flow, not in an absolute `Box`. Claude Code (2.1.306) moves an absolute `Box` whose top is above the screen down to row 0, with its children. Then the pointer `y` of a `Client` in such a `Box` counts from row 0 of the screen, not from the top of the page, so the selection was too high by the rows that were scrolled away. Also, the `Client` took the pointer under the page. A `Box` in the flow has its true position, also when its top is above the screen.
-A `Client` over a picture also takes the selection from Claude Code before 2.1.305 (which selects and copies pictures itself), so the mod draws it only from 2.1.305 (`$.session.version()`), in fullscreen mode. A `Client` that fails (`ui.fault`) turns picture select off until a reload.
+The mod draws the `Client` only from Claude Code 2.1.298 (`$.session.version()`), which has the `Client`, `ui.message`, `$.ui.blit` and `$.ui.copy`. It draws it only in fullscreen mode, and not over ssh (pages sent as bytes). A `Client` that fails (`ui.fault`) turns picture select off until a reload. `/iui details` shows the state on the line `Picture select:`.
+
+### The page cache
+
+The mod gets each page ready for the highlight before the first `down` on it (`hooks/lib/pagecache.ts`). When a page is drawn or comes on the screen (picture select on, fullscreen mode), the mod reads its PNG, decodes it, and makes the deflate piece of each row of cells, in the background. The hooks have no thread and no timer of their own. Thus the mod does this work in short slices: 4 ms at most each (8 ms when a `down` waits for the page), with `$.clock.after(0)` between two slices. Thus scrolling and drawing continue.
+
+- The mod gets one page ready at a time. A page that you push the button on goes first. Then the pages on the screen go, the newest answer first.
+- A page that goes off the screen leaves the queue, and its work stops.
+- When a `down` comes on a different page, the work on the page in progress pauses (if that page is on the screen). It continues later.
+- When a page is ready, the mod continues with the tinted piece of each row (for a row that is selected whole).
+- The mod keeps the decoded pages in memory, 128 MB at most (about two pages of 3392 × 4284 pixels). When it needs space, the pages off the screen go first. It writes nothing of this to disk.
+- The mod also finds the words of each page on the screen: it runs the probe of that page (`typst query`, one page at a time). Thus the copy at `up` does not wait.
+
+On Apple Silicon (bun), a page of 3392 × 4284 pixels is ready after approximately 0.24 s of work (about 60 slices of 4 ms, over a longer time). A page of 3392 × 756 pixels is ready after approximately 0.045 s. If a page is not ready at the `down`, the first highlight waits for it: the mod completes that page first, in slices of 8 ms. If the words of a page are not ready at `up`, the copy waits for the probe (approximately 0.05 s for plain text, 0.15–0.5 s for other text, 2–3 s for a page with a large Typst drawing).
## The lean font set
diff --git a/docs/install.md b/docs/install.md
index b901397..293c994 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -55,16 +55,15 @@ The mod finds Typst on the `PATH` of your login shell. It also looks in `/usr/lo
The mod works on Linux with X11 and with Wayland. It uses these tools. Most Linux systems have the first three.
-- **perl** (perl 5): reads the terminal size and its cell size, and watches for a change of the size. The clipboard shims and their reader also use it (for the automatic copy).
+- **perl** (perl 5): reads the terminal size and its cell size, and watches for a change of the size. It also writes the frame files of the highlight for picture select (with `MIME::Base64`, a core module). On macOS, `/usr/bin/perl` also watches the clipboard for the `/iui grab` toast, with Apple's PerlObjCBridge (macOS has it).
- **fontconfig** (`fc-match`, `fc-list`): finds the terminal font when the terminal's config does not name one. kitty and most terminals use fontconfig's `monospace` font. Ghostty uses its own JetBrains Mono when its config names no font. If fontconfig does not have JetBrains Mono, the mod copies the font from the Ghostty program (refer to [How it works](how-it-works.md)).
- **The light or dark mode of the desktop** (for the `auto` theme): the freedesktop portal (`org.freedesktop.appearance color-scheme`, through `gdbus` or `busctl`). GNOME, KDE Plasma and most desktops have the portal. If the portal does not answer, the mod reads GNOME's `color-scheme` (`gsettings`).
-- **The clipboard** (for the `/iui grab` toast and for `/iui grab` on the main screen, refer to [Copy text from a picture](usage.md#copy-text-from-a-picture)). The mod uses the first of these that it finds:
+- **The clipboard** (only for the `/iui grab` toast and for `/iui grab` on the main screen, refer to [Picture cells on the clipboard](usage.md#picture-cells-on-the-clipboard)). The mod uses the first of these that it finds:
1. **Wayland, not GNOME:** `wl-paste` from `wl-clipboard`. `wl-paste --watch` tells the mod about each clipboard change. It needs the data-control protocol of the compositor (KDE Plasma, Sway, Hyprland and other wlroots compositors have it).
2. **X11, and GNOME on Wayland (through Xwayland):** `clipnotify` tells the mod about each clipboard change, and `xclip` or `xsel` reads the clipboard. If `clipnotify` is not installed, the mod uses GTK 3 from Python (`python3-gi`, which most GNOME desktops have) for both.
3. **GNOME on Wayland with no X11 tool:** `wl-paste`. GNOME does not have the data-control protocol, so `wl-paste --watch` stops, and there is no `/iui grab` toast.
- If none of these work, there is no `/iui grab` toast. The automatic copy, `/iui grab` (with a selection, in fullscreen mode), Claude Code's `/copy` and the `ui.copy` hook still work. `/iui details` shows the tool in use, or why there is no toast, on the line `Auto copy:`.
-- **The clipboard write tools** (for the automatic copy): `wl-copy` (from `wl-clipboard`), `xclip` or `xsel`. Claude Code copies with one of them. The mod puts a shim for each one that is installed first on the `PATH` (refer to [How it works](how-it-works.md)). The shims need `perl`. If none of these tools is installed, Claude Code copies with its own built-in code, and the automatic copy is off.
+ If none of these work, there is no `/iui grab` toast. Picture select, `/iui grab` (with a selection, in fullscreen mode), Claude Code's `/copy` and the `ui.copy` hook still work. `/iui details` shows the tool in use, or why there is no toast, on the line `/iui grab hint:`.
- **"Edit the plan"** (refer to [Plan approval](usage.md#plan-approval)): VS Code (`code --wait`), else the first of VSCodium, Zed, Sublime Text, Kate, gedit and gvim that is on the `PATH`. These editors can wait until you close the file. If none is installed, the option does not show.
- **The cache folder** is in `$TMPDIR`, else in `/tmp`.
diff --git a/docs/limitations.md b/docs/limitations.md
index 5444209..2ca4943 100644
--- a/docs/limitations.md
+++ b/docs/limitations.md
@@ -3,36 +3,32 @@
← 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 on macOS and on Linux, but not over ssh (the clipboard tools of Claude Code run on the computer that runs Claude Code), and not in a background session. It needs the clipboard shims and `perl` (refer to [How it works](how-it-works.md)). With no `perl`, the mod makes no shims, and a copy keeps the picture cells. On Linux with no `wl-copy`, `xclip` or `xsel`, Claude Code copies with its own built-in code, which no shim sees. Then there is no automatic copy. `/iui details` shows the state on the line `Auto copy:`.
- - A shim asks only when Claude Code starts it directly. A clipboard tool that a different program starts (for example a script that runs `pbcopy`) gets its text with no change. The shim asks only for 4 MiB of text or less.
- - The `/iui grab` toast for picture cells that are not from this session needs a tool that tells the mod about each clipboard change. On macOS, this is `/usr/bin/perl` with Apple's PerlObjCBridge (macOS has it), which reads the change counter of the clipboard. On Linux, it is `wl-paste --watch` on Wayland, else `clipnotify` or GTK 3 from Python on X11 and Xwayland (refer to [Linux](install.md#linux)). If no such tool works, there is no toast: the mod does not read the clipboard at intervals in its place.
+ - Picture select is the copy for pictures. It works only in fullscreen mode, with Claude Code 2.1.298 or newer, and not over ssh. On the main screen, a copy gives picture cells (U+10EEEE plus combining marks), and a paste gives strange characters. Then 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 `/iui grab` toast for a copy of picture cells needs a tool that tells the mod about each clipboard change. On macOS, this is `/usr/bin/perl` with Apple's PerlObjCBridge (macOS has it), which reads the change counter of the clipboard. On Linux, it is `wl-paste --watch` on Wayland, else `clipnotify` or GTK 3 from Python on X11 and Xwayland (refer to [Linux](install.md#linux)). If no such tool works, there is no toast: the mod does not read the clipboard at intervals in its place. There is no toast over ssh or in a background session. `/iui details` shows the state on the line `/iui grab hint:`.
- On GNOME with Wayland, `wl-paste --watch` does not work (GNOME does not have the data-control protocol). The mod then uses the X11 tools through Xwayland. This works on Ubuntu 24.04 with GNOME and Python GTK 3.
- - On Linux with the old `clipnotify` (1.0.2 or earlier), a mouse selection (the PRIMARY selection) also makes the mod read the clipboard once. The mod changes nothing in that case. 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 first copy from a page takes approximately 0.05 s for plain text (refer to [The lean font set](how-it-works.md#the-lean-font-set)), 0.15–0.5 s for other text, and 2–3 s for a page with a large Typst drawing. No toast shows during this time. If you paste before the toast "copied N chars of text" shows, the paste gives the picture cells.
- - The shim waits 1.5 s at most for the text, because Claude Code stops the clipboard tool after 2 s. When the mod needs more time (for example, the first copy from a large Typst drawing), the shim writes the picture cells. The mod does not write the text later, because a different session can copy the same cells in that time. A toast tells you to use `/iui grab`.
- - While the shim waits, the clipboard can have the picture cells from the OSC 52 copy of the terminal. If you copy something different in a different app in this time, the shim then writes the text over it.
- - If the terminal applies the OSC 52 copy after the clipboard tool wrote, the clipboard has the picture cells again. The mod does not write over them. Use `/iui grab`.
+ - On Linux with the old `clipnotify` (1.0.2 or earlier), a mouse selection (the PRIMARY selection) also makes the mod read the clipboard once. The mod changes nothing in that case.
+ - The mod finds the words of a page in the background when the page is on the screen. If they are not ready when you release the button (or when you run `/iui grab`), the copy takes approximately 0.05 s for plain text (refer to [The lean font set](how-it-works.md#the-lean-font-set)), 0.15–0.5 s for other text, and 2–3 s for a page with a large Typst drawing. Wait for the toast "copied N chars of text", then paste.
- 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.
+ - For picture cells on the clipboard, 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.
- - On the main screen (not fullscreen mode), there is no automatic copy. There the terminal copies the selection itself, not Claude Code, so no shim asks the mod. Two sessions can have the same picture cells. Thus the mod does not change the clipboard, and a toast tells you to use `/iui grab`. On the main screen, you must run `/iui grab` in the session that has the picture.
+ - The mod never changes the clipboard for a copy of picture cells: two sessions can have the same picture cells, and the mod cannot know which session a copy is from. A toast tells you to use `/iui grab`. Run `/iui grab` in the session that has the picture.
- On the main screen, `/iui grab` does not know the row of the selection. Thus it can give the wrong text for a picture from before `/clear`, from a session that ended, or older than the last 64 pictures, and for a page after the first page of a long answer.
- - When a different session copies exactly the same cells less than 5 s after a copy of this session, the mod shows no `/iui grab` toast for it.
- - The mod makes the shims only in its own cache folder, and only when that folder, its `shims-<pid>` folder and its `ask` folder are folders of your user, not links, with no write access for other users. Else `/iui details` shows `Auto copy: off (the cache folder is not private)`.
- - In fullscreen mode, the mod does not change a copy of a selection that the terminal makes itself (for example, a drag with Option in iTerm2), because Claude Code does not see that selection. Select without the modifier key.
- - To stop the clipboard write on select, set `copyOnSelect` to `false` in `/config`. Then the mod does not copy a selection either, because Claude Code writes no copy that a shim can change. It changes only a clipboard that has picture cells (for example, after a copy with a key).
-- **Picture select** (Claude Code 2.1.305 or newer, refer to [Picture select](usage.md#picture-select-claude-code-21305-or-newer)) has these limits:
+ - In fullscreen mode, a selection that the terminal makes itself (for example, a drag with Option in iTerm2) is not picture select, because Claude Code does not see it. It copies picture cells. Select without the modifier key.
+- **Picture select** (Claude Code 2.1.298 or newer, refer to [Picture select](usage.md#picture-select-claude-code-21298-or-newer)) has these limits:
- It works only in fullscreen mode, and not over ssh (pages sent as bytes).
- - A selection is in one picture (an answer, a plan or a Markdown file, all its pages). A drag that starts on normal text and goes into a picture is the selection of Claude Code, which skips the picture. A drag that starts in a picture stays in that picture. Thus a selection of text and a picture together is not possible.
+ - On Claude Code 2.1.298 to 2.1.304, a selection that starts outside a picture (in the margin or the gutter, in normal text, or a double or triple click) is the selection of Claude Code, not picture select. It can copy picture cells (kitty placeholder characters) in place of the text of the picture. Then the mod shows the toast that names `/iui grab`. Run `/iui grab` to put the text on the clipboard. To use picture select, start the drag on the picture. From Claude Code 2.1.305, the selection of Claude Code skips picture cells, so such a selection copies no text of the picture.
+ - A selection is in one picture (an answer, a plan or a Markdown file, all its pages). A drag that starts in a picture stays in that picture. Thus a selection of text and a picture together is not possible.
- A click on normal text does not remove a picture selection. A click in a picture, a new picture selection or your next prompt removes it.
- It has no double click (word) or triple click (line) selection, and no Shift+click to make a selection longer.
- - The highlight shows a short time after the first `down` on a page: the mod decodes the page one time (approximately 50 ms for a page of 3392 × 756 pixels, 200 ms for 3392 × 4284). Each frame is a new PNG that the terminal decodes (1.5 MB at most for the tallest page).
+ - The mod gets a page ready for the highlight in the background, when the page is drawn or comes on the screen (refer to [The page cache](how-it-works.md#the-page-cache)). If you push the button on a page that is not ready, the highlight shows a short time later: the mod completes that page first (approximately 0.24 s of work for a page of 3392 × 4284 pixels, 0.045 s for 3392 × 756). Each frame is a new PNG that the terminal decodes (1.5 MB at most for the tallest page).
+ - The mod keeps the ready pages in memory, 128 MB at most (about two tall pages). The mod drops the pages off the screen first. It makes a dropped page ready again when the page comes on the screen, or at the next push of the button on it.
- The highlight maps cells to pixels by the page's size in cells. If the terminal draws a page with space at its side or above (another aspect than its cells), the highlight can be off by part of a cell.
- When Claude Code draws the page again from the start (for example, a page that scrolled far away and comes back), the page shows without its highlight until the selection changes. The copy is not changed.
- The blue background is VS Code's selection colour, not the one of your terminal or Claude Code theme.
- A page whose PNG is over 4 MiB (the most that the mod can read) has no highlight.
- It needs `perl` (with `MIME::Base64`, a core module) to write the frames. With no `perl`, the selection and the copy work with no highlight.
+ - It copies at the button's up, also when `copyOnSelect` is `false` in `/config`.
- **Links in a picture:** a click on the picture does not open a link, because the mod cannot put a link on a picture. Use the link rows under the picture (refer to [Links, file paths and commands](usage.md#links-file-paths-and-commands)). A click on a command row copies the command only where Claude Code gets mouse clicks (fullscreen mode). A `file://` link opens in the app that the terminal chooses. A file row shows only when the file exists when the mod draws the answer.
- **PDF files** (refer to [What it draws](usage.md#what-it-draws)): a click on `‹`, `›` or the page number works only where Claude Code gets mouse clicks (fullscreen mode). The page field gets the keyboard only when the prompt is empty. If the prompt has text, the field opens without the keyboard: click the field to type. Then Esc goes to the prompt, not to the field. To close the field, click it and push Esc, or click its close mark. The mod draws one page at a time, and it does not show the number of pages. You cannot copy text from a PDF page.
- **The row grid** (`/iui grid on`, refer to [Selection and the row grid](usage.md#selection-and-the-row-grid)) has these limits:
diff --git a/docs/usage.md b/docs/usage.md
index 67fa8bd..158c9f7 100644
--- a/docs/usage.md
+++ b/docs/usage.md
@@ -47,7 +47,7 @@ You can also start the skill yourself: type `/cc-intelligent-ui:intelligent-ui`
| Command | What it does |
|---|---|
| `/iui` | Shows the state, the theme, the text size, the width, the image height and the row grid, a problem that keeps pictures away, and a new version when there is one |
-| `/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, if the automatic copy is on (`Auto copy:`), and the state of the update check (`Update checks:`) |
+| `/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, if picture select is on (`Picture select:`), if the `/iui grab` toast is on (`/iui grab hint:`), and the state of the update check (`Update checks:`) |
| `/iui on` / `off` | Turns the pictures on or off (kept for later sessions) |
| `/iui setup` / `setup remove` | iTerm2 (macOS only): adds or removes the shell line that turns pictures on (then close the tab and open a new one). On Linux, it changes no file. |
| `/iui size <80–200>` | Text size in percent. 100 is the same visual size as your terminal text. |
@@ -62,8 +62,8 @@ You can also start the skill yourself: type `/cc-intelligent-ui:intelligent-ui`
| `/iui grid on` | Puts each line of text in a picture on the terminal rows (kept for later sessions). This is the default. Refer to [Selection and the row grid](#selection-and-the-row-grid). |
| `/iui grid off` | Lines of text in a picture have the usual spacing (kept for later sessions). |
| `/iui select` | Shows the picture select setting: on or off |
-| `/iui select on` | With Claude Code 2.1.305 or newer, in fullscreen mode, a drag over a picture selects its text and copies it (kept for later sessions). This is the default. Refer to [Copy text from a picture](#copy-text-from-a-picture). |
-| `/iui select off` | Stops picture select (kept for later sessions). Then the selection of Claude Code skips pictures (2.1.305 or newer). |
+| `/iui select on` | With Claude Code 2.1.298 or newer, in fullscreen mode, a drag over a picture selects its text and copies it (kept for later sessions). This is the default. Refer to [Picture select](#picture-select-claude-code-21298-or-newer). |
+| `/iui select off` | Stops picture select (kept for later sessions). Then a drag over a picture is the selection of Claude Code. From Claude Code 2.1.305, that selection skips pictures. |
| `/iui updates` | Shows the update check: on or off, and the newest version that it found |
| `/iui updates on` | Looks for a new version one time each day at most, and shows a toast when there is one (kept for later sessions). This is the default. Refer to [Update](install.md#update). |
| `/iui updates off` | Stops the check for a new version and its toast (kept for later sessions) |
@@ -92,23 +92,29 @@ The mod does not take web links from code blocks, inline code or math. It takes
## 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 gives picture cells. The automatic copy works in fullscreen mode only. We recommend fullscreen mode: run `/tui fullscreen` (`/tui default` goes back to the main screen). Claude Code writes the copy with a clipboard tool (`pbcopy` on macOS). A small shim of this tool asks the mod of this session for the text under the picture cells (refer to [How it works](how-it-works.md)). The clipboard then gets this text in place of the cells, and a toast shows the number of characters. Wait for this toast, then paste. If the text is not ready in 1.5 s (for example, the first copy from a large Typst drawing), the clipboard keeps the cells, and a toast tells you to use `/iui grab`. A copy from a different Claude Code session goes to the mod of that session, so this session does not change it. The mod does not change a clipboard that has no picture cells.
+We recommend fullscreen mode: run `/tui fullscreen` (`/tui default` goes back to the main screen). In fullscreen mode, picture select copies the text of a picture (an answer, a plan or a Markdown file that Claude sent). Refer to [Picture select](#picture-select-claude-code-21298-or-newer).
-On the main screen (not fullscreen mode), the terminal copies the selection itself, not Claude Code. Thus the mod cannot know which session a copy is from, and it does not change the clipboard. While the mod is on and has drawn a picture in this session, it sees each change of the clipboard (on macOS in 0.3 s or less; on Linux at once, with the tools in [Linux](install.md#linux)). When the clipboard has picture cells of a picture in this session, a toast tells you to use `/iui grab`. Select and copy, then run `/iui grab` in the same session. `/iui grab` puts the text of these picture cells on the clipboard. When the mod draws its first picture on the main screen, a toast recommends fullscreen mode (one time in each session).
+### Picture select (Claude Code 2.1.298 or newer)
-The mod finds the position of each word on a page when you copy from that page for the first time. This takes approximately 0.05 s for plain text (only ASCII characters, no math, no Typst block and no image), 0.15–0.5 s for other text, and more (2–3 s) for a page with a large Typst drawing. No toast shows while it does this. Only the toast of the copy shows. The mod keeps the positions in memory, so the next copy from the same page is fast.
+Picture select works in fullscreen mode only. It is on by default. `/iui select off` turns it off, and `/iui select on` turns it on again.
-If the clipboard did not change, use `/iui grab`. In fullscreen mode, it reads the last mouse selection of Claude Code and copies its text. With no selection (the main screen), it reads the picture cells on the clipboard and copies their text. If the clipboard has the text already, it tells you. 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.
+1. Drag over a picture with the left button. Start the drag on the picture. The selected cells show on a blue background (VS Code's selection colour), in the order of the text: the first row from where you started, the rows between, and the last row to the pointer. The layout does not change.
+2. Release the button. The mod copies the text of the selected cells (the same words that a copy of these cells gives) and shows the toast "copied N chars of text". Then paste.
+3. A click with no drag, a new selection in a different picture, or your next prompt removes the selection.
-### Picture select (Claude Code 2.1.305 or newer)
+A selection can go on into the next page of the same answer.
-From Claude Code 2.1.305, the mouse selection of Claude Code skips pictures. It shows no highlight on a picture and copies no picture cells. Thus in fullscreen mode the mod selects the text of a picture itself:
+When a page is drawn or comes on the screen, the mod gets the page ready for the highlight in the background. It also finds the position of each word on the page. Thus the first highlight and the copy are fast. If you push the button on a page that is not ready, the mod gets that page ready first, and the first highlight shows a short time later. If the words of the page are not ready when you release the button, the copy waits for them: approximately 0.05 s for plain text (only ASCII characters, no math, no Typst block and no image), 0.15–0.5 s for other text, and more (2–3 s) for a page with a large Typst drawing. No toast shows while the mod does this. Only the toast of the copy shows. The mod keeps the positions in memory, so the next copy from the same page is fast.
-1. Drag over a picture with the left button. The selected rows show on a blue background, in the order of the text: the first row from where you started, the rows between, and the last row to the pointer.
-2. Release the button. The mod copies the text of the selected cells (the same words that a copy of these cells gives) and shows the toast "copied N chars of text".
-3. A click with no drag, a new selection in a different picture, or your next prompt removes the selection.
+### Picture cells on the clipboard
+
+On the main screen (not fullscreen mode), there is no picture select. The terminal copies the selection itself, not Claude Code. The copy gives picture cells (kitty placeholder characters), not text. A selection of Claude Code that starts outside a picture can also copy picture cells (refer to [Limitations](limitations.md)). The mod never changes the clipboard for such a copy, because it cannot know which session the copy is from.
+
+While the mod is on and has drawn a picture in this session, it sees each change of the clipboard (on macOS in 0.3 s or less; on Linux at once, with the tools in [Linux](install.md#linux)). When the clipboard has picture cells of a picture in this session, a toast tells you to use `/iui grab`. Run `/iui grab` in the same session. When the mod draws its first picture on the main screen, a toast recommends fullscreen mode (one time in each session).
+
+`/iui grab` puts the text on the clipboard. In fullscreen mode, it reads the last mouse selection of Claude Code and copies its text. With no selection (the main screen), it reads the picture cells on the clipboard and copies their text. If the clipboard has the text already, it tells you. 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.
-A selection can go on into the next page of the same answer. The first selection on a page takes approximately 0.2 s more: the mod cuts the page into rows (one PNG for each row, kept with the page). `/iui select off` turns picture select off. Before Claude Code 2.1.305, and on the main screen, the selection is the one of Claude Code or of the terminal, as before.
+A copy of picture cells through Claude Code's `/copy` or `$.ui.copy` gets the text in place of the cells.
For the limits, refer to [Limitations](limitations.md).
diff --git a/hooks/clip-shim-setup.sh b/hooks/clip-shim-setup.sh
deleted file mode 100644
index 9d0a95a..0000000
--- a/hooks/clip-shim-setup.sh
+++ /dev/null
@@ -1,59 +0,0 @@
-#!/bin/sh
-# Intelligent UI (cc-intelligent-ui): sets up the clipboard shims (clip-shim.sh).
-# find <cache> <tool>...: prints `pid <Claude Code's pid>`, makes the shims
-# folder <cache>/shims-<pid> of this process, then `<tool> <path>` for each
-# tool found on PATH without a shims folder, `perl <path>`, and `ask <fifo>`
-# when it made the private folder <cache>/ask and the FIFO <cache>/ask-<pid>
-# (mode 600) for the shims' asks.
-# install <cache> <suffix> <file>...: puts each new shim `<file><suffix>` in
-# place, executable first; `-<file>` removes the shim of a tool that is gone.
-# Only in the shims folder of this process: never the one of another.
-# Exit 3: <cache> or the shims folder is not a private folder of this user.
-
-# A folder of this user (not a link), made 700, with no group or other write.
-private() {
- [ ! -L "$1" ] && [ -d "$1" ] && [ -O "$1" ] && chmod 700 "$1" 2>/dev/null || return 1
- case $(ls -ld "$1") in d????-??-*) return 0 ;; esac
- return 1
-}
-# The shims folder: private, and each entry a file of this user (not a link).
-shims_ok() {
- private "$1" || return 1
- [ -z "$(find "$1" -mindepth 1 \( ! -type f -o ! -user "$(id -u)" \) 2>&1)" ]
-}
-# A FIFO of this user (not a link).
-fifo_ok() { [ -p "$1" ] && [ ! -L "$1" ] && [ -O "$1" ]; }
-
-mode=$1; c=$2; d=$2/shims-$PPID
-shift 2
-case $mode in
- find)
- echo "pid $PPID"
- private "$c" || { echo "unsafe $c"; exit 3; }
- mkdir "$d" 2>/dev/null
- shims_ok "$d" || { echo "unsafe $d"; exit 3; }
- p=; IFS=:; set -f
- for e in $PATH; do case $e in "$c"/shims|"$c"/shims-*) ;; *) p=${p:+$p:}$e ;; esac; done
- unset IFS; set +f; PATH=$p
- for t in "$@" perl; do x=$(command -v "$t" 2>/dev/null) && case $x in /*) echo "$t $x" ;; esac; done
- q=$c/ask; f=$c/ask-$PPID
- mkdir "$q" 2>/dev/null
- private "$q" || exit 0
- fifo_ok "$f" || { rm -f "$f"; mkfifo -m 600 "$f" 2>/dev/null; }
- fifo_ok "$f" && chmod 600 "$f" && echo "ask $f"
- exit 0 ;;
- install)
- private "$c" && shims_ok "$d" || exit 3
- s=$1; shift
- for f in "$@"; do
- # Only files in the shims folder.
- case ${f#-} in "$d"/*) ;; *) exit 1 ;; esac
- case $f in
- -*) rm -f -- "${f#-}" ;;
- *)
- { [ -f "$f$s" ] && [ ! -L "$f$s" ] && [ -O "$f$s" ] && chmod 755 "$f$s" && mv -f "$f$s" "$f"; } || { rm -f "$f$s"; exit 1; }
- [ -f "$f" ] && [ ! -L "$f" ] && [ -O "$f" ] || exit 1 ;;
- esac
- done ;;
- *) exit 2 ;;
-esac
diff --git a/hooks/clip-shim.sh b/hooks/clip-shim.sh
deleted file mode 100644
index a798fde..0000000
--- a/hooks/clip-shim.sh
+++ /dev/null
@@ -1,157 +0,0 @@
-#!/bin/sh
-# Intelligent UI (cc-intelligent-ui): a pass-through shim for one clipboard tool.
-# It runs the real tool with the same arguments and exit status. A clipboard
-# write of picture cells by the Claude Code process of the FIFO $IUI_COPY_ASK
-# (its direct child) asks that process's mod for their text, and the real
-# tool gets that text. Only the request file has text on disk. See the README.
-tool=@TOOL@
-real=@REAL@
-dir=@DIR@
-perl=@PERL@
-if [ ! -x "$real" ]; then
- # The real tool moved: find it on PATH without this folder (never this shim).
- [ -z "${IUI_SHIM_IN:-}" ] || { echo "$tool: not found" >&2; exit 127; }
- IUI_SHIM_IN=1; export IUI_SHIM_IN
- p=; IFS=:; set -f
- for e in $PATH; do [ "$e" = "$dir" ] || p=${p:+$p:}$e; done
- unset IFS; set +f; PATH=$p; real=$tool
-fi
-
-# w=1: a write of text to the clipboard (not primary) with the text on stdin.
-# Any other call (also a type that is not text), or an argument not known
-# here, passes through untouched.
-w=1; v=; s=; i=; b=
-text_type() { case $1 in text/plain*|UTF8_STRING|STRING|TEXT) ;; *) w=0 ;; esac; }
-case $tool in
- pbcopy)
- for a in "$@"; do
- if [ -n "$v" ]; then [ "$a" = general ] || w=0; v=; continue; fi
- case $a in -pboard) v=1 ;; *) w=0 ;; esac
- done ;;
- wl-copy)
- for a in "$@"; do
- if [ -n "$v" ]; then [ "$v" = type ] && text_type "$a"; v=; continue; fi
- case $a in
- -n|--trim-newline|-f|--foreground|-o|--paste-once|--regular|--seat=*) ;;
- --type=*) text_type "${a#--type=}" ;;
- -t|--type) v=type ;;
- -s|--seat) v=1 ;;
- *) w=0 ;;
- esac
- done ;;
- xclip)
- # Its default selection is primary: only an explicit clipboard counts.
- for a in "$@"; do
- if [ -n "$v" ]; then
- if [ "$v" = sel ]; then case $a in c*) s=1 ;; *) s= ;; esac; fi
- [ "$v" = type ] && text_type "$a"
- v=; continue
- fi
- case $a in
- -i|-in|-input|-f|-filter|-quiet|-silent|-verbose|-noutf8|-rmlastnl) ;;
- -sel|-selection) v=sel ;;
- -t|-target) v=type ;;
- -d|-display|-l|-loops) v=1 ;;
- *) w=0 ;;
- esac
- done
- [ "$s" = 1 ] || w=0 ;;
- xsel)
- for a in "$@"; do
- if [ -n "$v" ]; then v=; continue; fi
- case $a in
- --input|--append) i=1 ;;
- --clipboard) b=1 ;;
- --nodetach|--verbose|--zeroflush) ;;
- --selectionTimeout|--logfile|--display) v=1 ;;
- --*|-) w=0 ;;
- -*)
- r=${a#-}
- while [ -n "$r" ]; do
- c=${r%"${r#?}"}; r=${r#?}
- case $c in
- i|a) i=1 ;;
- b) b=1 ;;
- n|v|z) ;;
- t|l) if [ -z "$r" ]; then v=1; else w=0; fi ;;
- *) w=0 ;;
- esac
- done ;;
- *) w=0 ;;
- esac
- done
- [ "$i" = 1 ] && [ "$b" = 1 ] || w=0 ;;
- *) w=0 ;;
-esac
-[ -z "$v" ] || w=0
-
-# The ask: only from the Claude Code process of the FIFO <cache>/ask-<pid>.
-f=${IUI_COPY_ASK:-}; n=${f##*/ask-}
-case $n in ''|*[!0-9]*) w=0 ;; esac
-[ "$n" = "$PPID" ] || w=0
-[ "$w" = 1 ] && [ -x "$perl" ] || exec "$real" "$@"
-# Perl keeps the text in memory. Picture cells (U+10EEEE, F4 8E BB AE), 4 MiB
-# at most: a request file in <cache>/ask, its id to the FIFO, then the answer
-# (1.5 s from the start at most: Claude Code stops the tool at 2 s), else the
-# cells as they are. Then the real tool through a pipe, and its exit status.
-exec "$perl" -e '
-use strict; use Fcntl; use POSIX (); use Config; use Time::HiRes ();
-my $END = Time::HiRes::time() + 1.5;
-my $MAX = 4 << 20;
-my ($fifo, $real, @args) = @ARGV;
-binmode STDIN;
-# A text over $MAX: no end of file here, so no ask.
-my ($text, $eof) = ("", 0);
-while (length($text) <= $MAX) {
- my $n = sysread(STDIN, $text, 65536, length $text);
- if (!$n) { $eof = 1; last; }
-}
-my $out = $text;
-my $q;
-my ($root, $own) = $fifo =~ m{^(.*)/ask-(\d+)$};
-if ($eof && defined $own && $own == getppid() && index($text, "\xF4\x8E\xBB\xAE") >= 0) {
- $q = "$root/ask/$own-$$-" . int(Time::HiRes::time() * 1000);
- eval {
- my @d = lstat("$root/ask"); die unless @d && -d _ && $d[4] == $>;
- my @f = lstat($fifo); die unless @f && -p _ && $f[4] == $>;
- sysopen(my $w, "$q.tmp", O_WRONLY | O_CREAT | O_EXCL, 0600) or die;
- (print $w $text) && close($w) or die;
- rename("$q.tmp", $q) or die;
- # No reader (ENXIO): the mod does not run, so no wait.
- sysopen(my $p, $fifo, O_WRONLY | O_NONBLOCK) or die;
- my @s = stat($p); die unless -p _ && $s[0] == $f[0] && $s[1] == $f[1];
- my $id = substr($q, length("$root/ask/"));
- syswrite($p, "$id\n") == length($id) + 1 or die; close $p;
- my $a;
- until (open($a, "<:raw", "$q.answer")) {
- if (Time::HiRes::time() >= $END) {
- # Too late: the mark stops a later answer (the mod links it with no overwrite).
- die if sysopen(my $m, "$q.answer", O_WRONLY | O_CREAT | O_EXCL, 0600);
- open($a, "<:raw", "$q.answer") or die; last;
- }
- Time::HiRes::sleep(0.01);
- }
- my $got = do { local $/; <$a> }; close $a;
- unlink "$q.answer";
- # An empty answer: the cells as they are.
- $out = $got if defined $got && length $got;
- };
- unlink $q, "$q.tmp";
-}
-$SIG{PIPE} = "IGNORE";
-my $to;
-unless (open($to, "|-", $real, @args)) { print STDERR "$real: $!\n"; exit 127; }
-binmode $to;
-print $to $out;
-unless ($eof) { my $b; while (sysread(STDIN, $b, 65536)) { print $to $b or last; } }
-my $ok = close($to); my ($st, $err) = ($?, $! + 0);
-exit 1 if $st == -1;
-if (my $sig = $st & 127) {
- my $name = (split " ", $Config{sig_name})[$sig];
- $SIG{$name} = "DEFAULT" if $name;
- kill $sig, $$;
- exit 128 + $sig;
-}
-exit($st >> 8) if $st >> 8;
-exit(!$ok && $err && $err != POSIX::EPIPE() ? 1 : 0);
-' -- "$f" "$real" "$@"
diff --git a/hooks/lib/api.ts b/hooks/lib/api.ts
index d1caed9..bd873ef 100644
--- a/hooks/lib/api.ts
+++ b/hooks/lib/api.ts
@@ -14,11 +14,9 @@ export type EnvName =
| 'CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC' | 'CLAUDE_CODE_FORCE_TERMINAL_IMAGES' | 'CLAUDE_CODE_SESSION_KIND' | 'CLAUDE_CODE_TMPDIR'
| 'CMUX_SOCKET_PATH' | 'CMUX_SURFACE_ID' | 'CMUX_WORKSPACE_ID' | 'COLORFGBG' | 'DISABLE_AUTOUPDATER' | 'DISABLE_UPDATES' | 'DISPLAY'
| 'GHOSTTY_RESOURCES_DIR' | 'HOME'
- | 'ITERM_PROFILE' | 'ITERM_SESSION_ID' | 'IUI_COPY_ASK' | 'IUI_COPY_SHIM' | 'IUI_DEBUG' | 'IUI_FORCE' | 'KITTY_CONFIG_DIRECTORY' | 'KITTY_PID'
- | 'KITTY_WINDOW_ID' | 'LC_TERMINAL' | 'PATH' | 'RIO_CONFIG_HOME' | 'SHELL' | 'SSH_CONNECTION' | 'SSH_TTY' | 'STY'
+ | 'ITERM_PROFILE' | 'ITERM_SESSION_ID' | 'IUI_DEBUG' | 'IUI_FORCE' | 'KITTY_CONFIG_DIRECTORY' | 'KITTY_PID'
+ | 'KITTY_WINDOW_ID' | 'LC_TERMINAL' | 'RIO_CONFIG_HOME' | 'SHELL' | 'SSH_CONNECTION' | 'SSH_TTY' | 'STY'
| 'TERM' | 'TERM_PROGRAM' | 'TMUX' | 'WAYLAND_DISPLAY' | 'XDG_CONFIG_HOME' | 'XDG_CURRENT_DESKTOP' | 'ZDOTDIR'
-// The variables the mod sets (the clipboard shims).
-export type EnvSetName = 'IUI_COPY_ASK' | 'PATH'
export function clockAfter($: EngineInterface, ms: number, fn: () => void) {
return $.clock.after(ms, fn)
@@ -61,15 +59,12 @@ export function envGet($: EngineInterface, name: EnvName): Promise<string | unde
case 'HOME': return $.env.get('HOME')
case 'ITERM_PROFILE': return $.env.get('ITERM_PROFILE')
case 'ITERM_SESSION_ID': return $.env.get('ITERM_SESSION_ID')
- case 'IUI_COPY_ASK': return $.env.get('IUI_COPY_ASK')
- case 'IUI_COPY_SHIM': return $.env.get('IUI_COPY_SHIM')
case 'IUI_DEBUG': return $.env.get('IUI_DEBUG')
case 'IUI_FORCE': return $.env.get('IUI_FORCE')
case 'KITTY_CONFIG_DIRECTORY': return $.env.get('KITTY_CONFIG_DIRECTORY')
case 'KITTY_PID': return $.env.get('KITTY_PID')
case 'KITTY_WINDOW_ID': return $.env.get('KITTY_WINDOW_ID')
case 'LC_TERMINAL': return $.env.get('LC_TERMINAL')
- case 'PATH': return $.env.get('PATH')
case 'RIO_CONFIG_HOME': return $.env.get('RIO_CONFIG_HOME')
case 'SHELL': return $.env.get('SHELL')
case 'SSH_CONNECTION': return $.env.get('SSH_CONNECTION')
@@ -85,13 +80,6 @@ export function envGet($: EngineInterface, name: EnvName): Promise<string | unde
}
}
-export function envSet($: EngineInterface, name: EnvSetName, value: string): ReturnType<EngineInterface['env']['set']> {
- switch (name) {
- case 'IUI_COPY_ASK': return $.env.set('IUI_COPY_ASK', value)
- case 'PATH': return $.env.set('PATH', value)
- }
-}
-
export function fsExists($: EngineInterface, path: string) {
return $.fs.exists(path)
}
diff --git a/hooks/lib/blit.ts b/hooks/lib/blit.ts
index e3105ad..6fd48f4 100644
--- a/hooks/lib/blit.ts
+++ b/hooks/lib/blit.ts
@@ -5,8 +5,8 @@
// a selected cell each page pixel (straight alpha) over the opaque colour,
// elsewhere the page as it is. A clear swaps the page's own PNG back.
//
-// The page is decoded once, the first time a selection reaches it (png.ts:
-// the hooks have no zlib), and kept in memory (FRAMES_KEPT_BYTES at most).
+// The page is decoded once, in the background when it is drawn or comes on
+// screen (pagecache.ts; png.ts: the hooks have no zlib), and kept in memory.
// Its rows are deflate pieces made once (plain, and tinted the first time a
// whole row is selected); a frame makes only the selection's first and last
// rows (partly selected) and joins the pieces: about 1.5 MB for a page of
@@ -14,85 +14,17 @@
// (base64 on its stdin) to a file of its own, which the terminal reads.
import type { EngineInterface } from 'claude-code'
-import type { IuiTheme } from '../../types'
import { drawnAnswers, S } from './state'
-import { chunk, concat, decodePng, deflatePiece, fromBase64, headOf, tailOf, toBase64, type Piece, type Rgba } from './png'
+import { toBase64 } from './png'
+import { frameOf, selectColor } from './frames'
+import { forgetPages, needFrames } from './pagecache'
import type { DrawnPage } from './copy'
import type { SelRow } from './select'
import { perlFor } from './host'
import { traceDebug } from './log'
-import { clockAfter, clockNow, fsRead, processRun, uiBlit, uiLog } from './api'
+import { clockNow, processRun, uiBlit, uiLog } from './api'
-export type Rgb = readonly [number, number, number]
-
-// VS Code's selection colour of the mode.
-export const selectColor = (mode: IuiTheme) => (mode === 'light' ? '#add6ff' : '#264f78')
-export const rgbOf = (hex: string): Rgb => [1, 3, 5].map(i => parseInt(hex.slice(i, i + 2), 16)) as unknown as Rgb
-
-// The pixel edges of `cells` cells over `px` pixels: cell i is pixels
-// edges[i] to edges[i + 1] (exclusive). Each edge is rounded once, so the
-// cells tile the picture with no gap or overlap, whatever the ratio.
-export function edgesOf(px: number, cells: number): number[] {
- return Array.from({ length: cells + 1 }, (_, i) => Math.round((i * px) / cells))
-}
-
-// One channel of a page pixel of alpha `a` over the opaque colour channel `c`.
-export const over = (p: number, a: number, c: number) => Math.floor((p * a + c * (255 - a) + 127) / 255)
-
-// Pixel rows y0 to y1 (exclusive) of `img` as PNG scanlines (filter 0),
-// pixels x0 to x1 (exclusive) over the colour.
-export function bandOf(img: Rgba, y0: number, y1: number, x0: number, x1: number, color: Rgb): Uint8Array {
- const stride = img.width * 4
- const out = new Uint8Array((y1 - y0) * (stride + 1))
- const [r, g, b] = color
- for (let y = y0; y < y1; y++) {
- const o = (y - y0) * (stride + 1) + 1
- out.set(img.data.subarray(y * stride, (y + 1) * stride), o)
- for (let p = o + x0 * 4, end = o + x1 * 4; p < end; p += 4) {
- const a = out[p + 3]!
- if (a === 255) continue
- out[p] = over(out[p]!, a, r)
- out[p + 1] = over(out[p + 1]!, a, g)
- out[p + 2] = over(out[p + 2]!, a, b)
- out[p + 3] = 255
- }
- }
- return out
-}
-
-// A piece with its IDAT chunk (the CRC is made once).
-type Chunked = { piece: Piece; chunk: Uint8Array }
-const chunked = (raw: Uint8Array, line: number): Chunked => {
- const piece = deflatePiece(raw, 4, line)
- return { piece, chunk: chunk('IDAT', piece.bytes) }
-}
-
-// A decoded page ready for frames: its pixels, the cells' pixel edges, the
-// plain row pieces, and the tinted ones made so far.
-export type Frames = { img: Rgba; xs: number[]; ys: number[]; color: Rgb; head: Uint8Array; plain: Chunked[]; tint: (Chunked | undefined)[] }
-
-export function framesOf(img: Rgba, box: { columns: number; rows: number }, color: Rgb): Frames {
- const xs = edgesOf(img.width, box.columns)
- const ys = edgesOf(img.height, box.rows)
- const line = img.width * 4 + 1
- const plain = Array.from({ length: box.rows }, (_, r) => chunked(bandOf(img, ys[r]!, ys[r + 1]!, 0, 0, color), line))
- return { img, xs, ys, color, head: headOf(img.width, img.height), plain, tint: [] }
-}
-
-// The frame PNG of a page with `rows` selected (cells x0 to x1, inclusive).
-export function frameOf(f: Frames, rows: readonly SelRow[]): Uint8Array {
- const line = f.img.width * 4 + 1
- const columns = f.xs.length - 1
- const at = new Map(rows.map(r => [r.row, r]))
- const parts = f.plain.map((plain, r) => {
- const sel = at.get(r)
- if (!sel || sel.x1 < sel.x0) return plain
- const [y0, y1] = [f.ys[r]!, f.ys[r + 1]!]
- if (sel.x0 <= 0 && sel.x1 >= columns - 1) return (f.tint[r] ??= chunked(bandOf(f.img, y0, y1, 0, f.img.width, f.color), line))
- return chunked(bandOf(f.img, y0, y1, f.xs[Math.max(0, sel.x0)]!, f.xs[Math.min(columns, sel.x1 + 1)]!, f.color), line)
- })
- return concat([f.head, ...parts.map(p => p.chunk), tailOf(parts.map(p => p.piece))])
-}
+export { bandOf, edgesOf, frameOf, framesOf, over, rgbOf, selectColor, type Frames, type Rgb } from './frames'
// What a page shows, as a string: '' its own PNG, else the colour and rows.
export const sigOf = (rows: readonly SelRow[], color: string) => (rows.length ? `${color}|${rows.map(r => `${r.row}:${r.x0}-${r.x1}`).join(',')}` : '')
@@ -132,8 +64,6 @@ export function endFold(f: Fold): boolean {
// One blit frame a screen frame at most.
export const FRAME_MS = 16
-// The decoded pages kept (their pixels), by bytes: about two of the tallest.
-export const FRAMES_KEPT_BYTES = 128 * 1024 * 1024
// The frame files kept: the terminal reads each after its blit, at the
// engine's next frame; older ones go once they are this old.
const FILES_KEPT = 4
@@ -145,12 +75,11 @@ export const WRITE_PL = 'use MIME::Base64; local $/; my $b = <STDIN>; my ($f, @o
// Each drawing's site (the requestId its Images are drawn under) and its
// Images' key prefix, noted by drawPages; what each page shows now (sigOf,
-// by `<id>#<page>`); the decoded pages; the frame files written; the
-// reasons logged; pages whose blit was refused (none until the next down).
+// by `<id>#<page>`); the frame files written; the reasons logged; pages
+// whose blit was refused (none until the next down).
export const blits = {
sites: new Map<string, { requestId: string; keys: string }>(),
shown: new Map<string, string>(),
- frames: new Map<string, Frames | null>(),
files: [] as { path: string; at: number }[],
logged: new Set<string>(),
refused: new Set<string>(),
@@ -168,7 +97,8 @@ export function noteSite(id: string, requestId: string, keys: string) {
// Forgets everything (for tests).
export function forgetBlits() {
- for (const m of [blits.sites, blits.shown, blits.frames, blits.logged, blits.refused, decoding]) m.clear()
+ for (const m of [blits.sites, blits.shown, blits.logged, blits.refused]) m.clear()
+ forgetPages()
blits.files = []
blits.seq = 0
blits.dir = ''
@@ -184,50 +114,6 @@ function logOnce($: EngineInterface, text: string) {
void Promise.resolve(uiLog($, `Intelligent UI: picture select: ${text}`, { to: 'debug' })).catch(() => undefined)
}
-// A page's frames: decoded once (null: it can not be, not tried again); a
-// decode that runs now is shared.
-const decoding = new Map<string, Promise<{ frames: Frames | null; ms: number }>>()
-function framesFor($: EngineInterface, page: DrawnPage, color: string): Promise<{ frames: Frames | null; ms: number }> {
- const key = `${page.file}|${page.columns}x${page.rows}|${color}`
- const kept = blits.frames.get(key)
- if (kept !== undefined) {
- blits.frames.delete(key)
- blits.frames.set(key, kept)
- return Promise.resolve({ frames: kept, ms: 0 })
- }
- const running = decoding.get(key)
- if (running) return running
- const run = decodeFrames($, page, color, key).finally(() => decoding.delete(key))
- decoding.set(key, run)
- return run
-}
-
-async function decodeFrames($: EngineInterface, page: DrawnPage, color: string, key: string): Promise<{ frames: Frames | null; ms: number }> {
- const t = performance.now()
- let frames: Frames | null = null
- try {
- const { base64 } = await fsRead($, page.file, { as: 'bytes' })
- frames = framesOf(decodePng(fromBase64(base64)), page, rgbOf(color))
- } catch (err) {
- logOnce($, `no highlight for ${page.file}: ${err instanceof Error ? err.message : String(err)}`)
- }
- blits.frames.set(key, frames)
- let bytes = [...blits.frames.values()].reduce((n, f) => n + (f?.img.data.length ?? 0), 0)
- for (const [k, f] of blits.frames) {
- if (bytes <= FRAMES_KEPT_BYTES || k === key) continue
- bytes -= f?.img.data.length ?? 0
- blits.frames.delete(k)
- }
- const took = performance.now() - t
- if (frames) traceDebug($, `select: decoded ${page.file} ${frames.img.width}x${frames.img.height} in ${ms(took)}`)
- return { frames, ms: took }
-}
-
-// Decodes a page before its first frame (at a down), in the background.
-export function warmPage($: EngineInterface, page: DrawnPage | undefined) {
- if (page && S.env) clockAfter($, 0, () => void framesFor($, page, selectColor(S.theme)).catch(() => undefined))
-}
-
// The newest frame file's name, and the old ones that can go.
function nextFile(cache: string, now: number): { path: string; old: string[] } {
blits.dir ||= `${cache}/select-${now.toString(36)}${Math.floor(Math.random() * 1e6).toString(36)}`
@@ -250,7 +136,8 @@ async function showPage($: EngineInterface, id: string, i: number, page: DrawnPa
let source: { file: string; format: 'png' } = { file: page.file, format: 'png' }
let timing = ''
if (rows.length) {
- const got = await framesFor($, page, selectColor(S.theme))
+ const d = drawnAnswers.get(id)
+ const got = await needFrames($, page, selectColor(S.theme), { id, index: i, seq: d?.seq ?? 0 })
if (!got.frames) {
blits.shown.set(k, sig)
return
@@ -267,7 +154,7 @@ async function showPage($: EngineInterface, id: string, i: number, page: DrawnPa
return
}
source = { file: path, format: 'png' }
- timing = `decode ${ms(got.ms)} frame ${ms(t2 - t1)} write ${ms(t3 - t2)} ${png.length} bytes`
+ timing = `wait ${ms(got.waitMs)} frame ${ms(t2 - t1)} write ${ms(t3 - t2)} ${png.length} bytes`
}
const t4 = performance.now()
const res = await uiBlit($, { requestId: site.requestId, key, source }).catch(err => ({ deny: String(err) }))
diff --git a/hooks/lib/clipboard.ts b/hooks/lib/clipboard.ts
index 47a9c8f..1733cef 100644
--- a/hooks/lib/clipboard.ts
+++ b/hooks/lib/clipboard.ts
@@ -4,14 +4,11 @@
// change), else X11 (also Xwayland): xclip or xsel to read, clipnotify for
// an event at each change, else GTK 3 from Python (python3-gi, on most GNOME
// desktops) for both. The changes give the /iui grab hint (where no tool sees
-// them there is none: the clipboard is never read at intervals). The shims
-// (below) ask this session's mod for the text of a copy of picture cells.
+// them there is none: the clipboard is never read at intervals).
import type { EngineInterface } from 'claude-code'
import { S } from './state'
-import { lineSplitter } from './frame'
-import { perlFor } from './host'
-import { clockAfter, envGet, envSet, fsExists, fsRead, fsStat, fsWrite, pluginRoot, processRun, spawn } from './api'
+import { envGet, processRun } from './api'
// The tools the choice looks for, in the order it prefers them. `gtk` is
// python3 when it can load GTK 3 (gi).
@@ -22,7 +19,7 @@ export type ClipTool = (typeof CLIP_TOOLS)[number]
// text; `watch` the notifier's argv (the watcher runs it and gives one
// `clip <n>` line for each line it prints, the first at its start: its
// clipboard then is no new copy); `name` for /iui details. `off`: why the
-// automatic copy is off (`read`, when set, still serves the ui.copy hook).
+// /iui grab hint is off.
export type ClipWay = { name: string; read: string[]; watch: string[]; wayland: boolean } | { off: string }
// The Wayland notifier's command: wl-paste runs it at each change (and once
@@ -156,296 +153,23 @@ export function clipWatchArgs(isMac: boolean): string[] | null {
return way && 'watch' in way ? way.watch : null
}
-// ---- The shims: Claude Code's own clipboard writes ---------------------------
-// Claude Code copies with pbcopy, wl-copy, xclip or xsel, found by name on
-// PATH. A shim folder of this process (<cache>/shims-<pid>) first on PATH
-// sends each write of picture cells to the mod of its session, which gives
-// their text (hooks/clip-shim.sh).
-export const SHIM_TOOLS = { mac: ['pbcopy'], linux: ['wl-copy', 'xclip', 'xsel'] } as const
-export type ShimState = { tools: string[] } | { off: string }
-
-// The setup script (in the plugin): `find` and `install`, each after it
-// checks that the cache folder and the shims folder are private (exit 3).
-export const SHIM_SETUP = 'hooks/clip-shim-setup.sh'
-
-export const shQuote = (s: string) => `'${s.replace(/'/g, `'\\''`)}'`
-
-// The shim of one tool: the template with its name, the real tool, the folder and perl.
-export const shimText = (template: string, tool: string, real: string, dir: string, perl: string) =>
- template.split('@TOOL@').join(shQuote(tool)).split('@REAL@').join(shQuote(real)).split('@DIR@').join(shQuote(dir))
- .split('@PERL@').join(shQuote(perl))
-
-// The `find` output: the pid, the tools found (absolute, not in a shims
-// folder), perl, and the FIFO for the asks ('' when it was not made).
-export function shimFindOf(stdout: string, tools: readonly string[], cache: string): { pid: string; found: Record<string, string>; perl: string; ask: string } {
- let pid = ''
- let perl = ''
- let ask = ''
- const found: Record<string, string> = {}
- for (const line of stdout.split('\n')) {
- const m = /^(\S+) (.+)$/.exec(line.trim())
- if (!m) continue
- const [, key, value] = m as unknown as [string, string, string]
- if (key === 'pid' && /^\d+$/.test(value)) pid = value
- else if (key === 'perl' && value.startsWith('/')) perl = value
- else if (key === 'ask' && value.startsWith(`${cache}/ask-`) && /^\d+$/.test(value.slice(cache.length + 5))) ask = value
- else if (tools.includes(key) && value.startsWith('/') && !value.startsWith(`${cache}/shims`)) found[key] = value
- }
- return { pid, found, perl, ask }
-}
-
-// PATH with the folder first, once; null when it is so already.
-export function pathWith(path: string, dir: string): string | null {
- const parts = path ? path.split(':') : []
- if (parts[0] === dir && !parts.slice(1).includes(dir)) return null
- return [dir, ...parts.filter(p => p !== dir)].join(':')
-}
-
-// setUp, on this computer (macOS or Linux): the shims of the tools found,
-// IUI_COPY_ASK and PATH (once per process: a hot reload finds them set).
-export async function setUpShims($: EngineInterface, cache: string, isMac: boolean): Promise<ShimState> {
- S.askFifo = ''
- S.shimDir = ''
- S.shims = await shimsFor($, cache, isMac).catch(() => ({ off: 'the clipboard shims could not be set up' }))
- return S.shims
-}
-export const NOT_PRIVATE = 'the cache folder is not private'
-// No shims, PATH as it is: no private cache folder (CACHE_SH failed), or no
-// pictures here (a terminal with no pictures, a background session).
-export function noShims(off = NOT_PRIVATE): ShimState {
- S.askFifo = ''
- S.shimDir = ''
- S.shims = { off }
- return S.shims
-}
-async function shimsFor($: EngineInterface, cache: string, isMac: boolean): Promise<ShimState> {
- const setup = `${pluginRoot($)}/${SHIM_SETUP}`
- const tools = isMac ? SHIM_TOOLS.mac : SHIM_TOOLS.linux
- const path = await envGet($, 'PATH')
- if (!path) return { off: 'no PATH' }
- const got = await processRun($, ['sh', setup, 'find', cache, ...tools], { timeoutMs: 5000 })
- if (got.exitCode === 3) return { off: NOT_PRIVATE }
- if (got.exitCode !== 0) return { off: 'the shim folder could not be made' }
- const { pid, found, perl, ask } = shimFindOf(got.stdout, tools, cache)
- if (!pid) return { off: 'the shim folder could not be made' }
- const dir = `${cache}/shims-${pid}`
- const names = tools.filter(t => found[t])
- if (!names.length) return { off: isMac ? 'no pbcopy' : 'no wl-copy, xclip or xsel: Claude Code copies with its own addon' }
- if (!perl) return { off: 'no perl' }
- if (!ask) return { off: 'the ask FIFO could not be made' }
- const template = await fsRead($, `${pluginRoot($)}/hooks/clip-shim.sh`)
- const suffix = `.new-${pid || 'x'}`
- const args: string[] = []
- for (const tool of tools) {
- const file = `${dir}/${tool}`
- const real = found[tool]
- if (!real) {
- if (await fsExists($, file).catch(() => false)) args.push(`-${file}`)
- continue
- }
- const text = shimText(template, tool, real, dir, perl)
- if ((await fsRead($, file).catch(() => null)) === text) continue
- await fsWrite($, `${file}${suffix}`, text)
- args.push(file)
- }
- if (args.length) {
- const put = await processRun($, ['sh', setup, 'install', cache, suffix, ...args], { timeoutMs: 5000 })
- if (put.exitCode === 3) return { off: NOT_PRIVATE }
- if (put.exitCode !== 0) return { off: 'the clipboard shims could not be installed' }
- }
- // One FIFO per Claude Code process (a nested one has its own).
- if ((await envGet($, 'IUI_COPY_ASK')) !== ask) {
- const set = await envSet($, 'IUI_COPY_ASK', ask)
- if (set.deny) return { off: `IUI_COPY_ASK not set: ${set.deny}` }
- }
- const next = pathWith(path, dir)
- if (next !== null) {
- const set = await envSet($, 'PATH', next)
- if (set.deny) return { off: `PATH not set: ${set.deny}` }
- }
- S.askFifo = ask
- S.shimDir = dir
- return { tools: names }
-}
-
-// ---- The asks: a shim wants the text of the picture cells it copies ----------
-// The shim writes the cells to <cache>/ask/<id> and the id to the FIFO
-// <cache>/ask-<pid>; the reader (ASK_PL) prints `ask <id>`, the mod answers.
-
-// The reader: prints `pid <n>`, then `ask <id>` for each id line of the FIFO
-// (open to read and write, so a writer that closes is no end of file). Exit 3
-// when the FIFO is not a FIFO of this user; exit 0 when the parent dies.
-export const ASK_PL = [
- 'my $fifo = shift; my $parent = getppid(); $| = 1;',
- '$SIG{PIPE} = sub { exit 0 };',
- 'print "pid $$\\n" or exit 0;',
- 'my @l = lstat($fifo); exit 3 unless @l && -p _ && $l[4] == $>;',
- 'open(my $f, "+<", $fifo) or exit 3;',
- 'my @s = stat($f); exit 3 unless -p _ && $s[0] == $l[0] && $s[1] == $l[1];',
- 'my $buf = "";',
- 'while (1) {',
- ' my $r = ""; vec($r, fileno($f), 1) = 1;',
- ' my $n = select($r, undef, undef, 2);',
- ' exit 0 if getppid() != $parent;',
- ' next unless $n && $n > 0;',
- ' sysread($f, $buf, 4096, length $buf) or exit 0;',
- ' while ($buf =~ s/^([^\\n]*)\\n//) { my $id = $1; if ($id =~ /^[A-Za-z0-9_-][A-Za-z0-9._-]{0,127}$/) { print "ask $id\\n" or exit 0; } }',
- ' $buf = "" if length $buf > 4096;',
- '}',
-].join(' ')
-// A request id: no path, no dot first.
-export const ASK_ID = /^[A-Za-z0-9_-][A-Za-z0-9._-]{0,127}$/
-// The answer to <request> (stdin): mode 600, a temp file, then a link, which
-// never replaces the mark of a shim that gave up (then exit 1).
-export const ANSWER_SH = 'umask 077; cat >"$1.tmp" || { rm -f "$1.tmp"; exit 1; }; ln "$1.tmp" "$1.answer" 2>/dev/null; r=$?; rm -f "$1.tmp"; exit "$r"'
-// After a give-up: the request and the shim's mark.
-export const ASK_CLEAN_SH = 'rm -f -- "$1" "$1.answer"'
-// The end of the session: the FIFO, this process's request files and its shims folder.
-export const ASK_END_SH = 'rm -f -- "$1" "$2/$3"-*; rm -rf -- "$4"'
-// A request larger than this is not read (the shim does not ask for one).
-export const ASK_MAX = 4 << 20
-export const ASK_RESTARTS = 3
-export const ASK_RESTART_MS = 1000
-
-const askDir = () => `${S.askFifo.slice(0, S.askFifo.lastIndexOf('/'))}/ask`
-
-// The reader's child now, its restarts (at most ASK_RESTARTS per load) and
-// where its ids go (register.tsx).
-let asker: { ended: boolean; final: boolean; stop: () => void } | null = null
-let askRestarts = 0
-let askTo: ((id: string) => void) | null = null
-export const asking = () => !!asker && !asker.ended
-
-// Starts the reader of the FIFO (at the first picture: before it, a shim
-// finds no reader and copies at once), or again when it ended on its own
-// (after ASK_RESTART_MS, ASK_RESTARTS times at most). True when one started.
-export function listenAsks($: EngineInterface, to?: (id: string) => void): boolean {
- if (to) askTo = to
- if (!S.askFifo || asker?.final) return false
- if (asker) {
- if (!asker.ended || askRestarts >= ASK_RESTARTS) return false
- askRestarts++
- }
- let pid = ''
- let stopped = false
- const kill = () => {
- if (stopped && pid) void Promise.resolve(processRun($, ['kill', pid], { timeoutMs: 5000 })).catch(() => undefined)
- }
- const me = {
- ended: false,
- final: false,
- stop: () => {
- if (stopped) return
- stopped = true
- kill()
- },
- }
- asker = me
- try {
- const child = spawn($, { argv: [perlFor(S.hostOs === 'Darwin'), '-e', ASK_PL, S.askFifo] })
- void followAsks(child, line => {
- const m = /^(pid|ask) (\S+)$/.exec(line)
- if (m?.[1] === 'pid') {
- pid = m[2]!
- kill()
- } else if (m && !stopped) askTo?.(m[2]!)
- }).then(code => {
- me.ended = true
- if (code === 3) me.final = true
- if (stopped || me.final) return
- try {
- clockAfter($, ASK_RESTART_MS, () => {
- if (asker === me) listenAsks($)
- })
- } catch {}
- }).catch(() => undefined)
- } catch {
- me.ended = me.final = true
- }
- return true
-}
-
-// The reader's lines, each to `note`, until it ends: its exit code (null
-// when it did not start or a signal ended it).
-async function followAsks(
- child: AsyncIterator<{ stream: 'stdout' | 'stderr'; text: string }, { code: number | null } | undefined>,
- note: (line: string) => void,
-): Promise<number | null> {
- const lines = lineSplitter()
- try {
- for (;;) {
- const got = await child.next()
- if (got.done) return got.value?.code ?? null
- if (got.value.stream === 'stdout') for (const line of lines(got.value.text)) note(line)
- }
- } catch {
- return null
- }
-}
-
-// The cells of request `id`: a file in <cache>/ask (never a link), ASK_MAX
-// bytes at most; null for a bad id, no such file or a larger one.
-export async function askRequest($: EngineInterface, id: string): Promise<string | null> {
- if (!S.askFifo || !ASK_ID.test(id)) return null
- const path = `${askDir()}/${id}`
- const stat = await fsStat($, path).catch(() => null)
- if (stat?.kind !== 'file' || stat.isLink || stat.size > ASK_MAX) return null
- return fsRead($, path).catch(() => null)
-}
-
-// Answers request `id` with `text`: false when the shim gave up (or the write failed).
-export async function answerAsk($: EngineInterface, id: string, text: string): Promise<boolean> {
- if (!S.askFifo || !ASK_ID.test(id)) return false
- const got = await processRun($, ['sh', '-c', ANSWER_SH, 'sh', `${askDir()}/${id}`], { stdin: text, timeoutMs: 5000 }).catch(() => null)
- return got?.exitCode === 0
-}
-
-// After a give-up of the shim of request `id` (its mark): removes its files.
-export async function askGaveUp($: EngineInterface, id: string) {
- if (!S.askFifo || !ASK_ID.test(id)) return
- await processRun($, ['sh', '-c', ASK_CLEAN_SH, 'sh', `${askDir()}/${id}`], { timeoutMs: 5000 }).catch(() => undefined)
-}
-
-// The session ends (not a /clear or a resume): the reader stops, and the
-// FIFO, this process's request files and its shims folder go.
-export async function endAsks($: EngineInterface) {
- asker?.stop()
- asker = { ended: true, final: true, stop: () => {} }
- const fifo = S.askFifo
- if (!fifo) return
- const dir = S.shimDir
- S.askFifo = ''
- S.shimDir = ''
- await processRun($, ['sh', '-c', ASK_END_SH, 'sh', fifo, `${fifo.slice(0, fifo.lastIndexOf('/'))}/ask`, fifo.slice(fifo.lastIndexOf('-') + 1), dir], { timeoutMs: 5000 })
- .catch(() => undefined)
-}
-
-// The automatic copy now, for /iui details and dump: the shims and the
-// reader of their asks (`asking`). `isFullscreen`: null before a render hook
-// says; on the main screen the terminal copies, not Claude Code. The watcher
-// (`none`: it printed `clip none`; `way` on Linux) only gives the /iui grab
-// hint for the other copies.
-export function autoCopyText(o: {
- isMac: boolean; hostOs: string; isRemote: boolean; isOn: boolean; isFullscreen: boolean | null; none: boolean; drawn: boolean; asking: boolean; way: ClipWay | null
- shims: ShimState | null
+// The /iui grab hint now, for /iui details and dump: the watcher sees each
+// clipboard change, and picture cells copied (a native drag over text and
+// pictures, the main screen's copy) get a toast that names /iui grab.
+// `none`: the watcher printed `clip none`; `way` on Linux.
+export function hintText(o: {
+ isMac: boolean; hostOs: string; isRemote: boolean; isOn: boolean; none: boolean; drawn: boolean; running: boolean; way: ClipWay | null
}): string {
if (!o.isMac && o.hostOs !== 'Linux') return 'off (not macOS or Linux)'
if (o.isRemote) return 'off (ssh)'
- if (!o.shims) return 'off (the clipboard shims are not set up yet)'
- if ('off' in o.shims) return `off (${o.shims.off})`
+ if (!o.isMac && o.way && 'off' in o.way) return `off (${o.way.off})`
+ if (!o.isMac && !o.way) return 'off (the clipboard tools are not looked up yet)'
if (!o.isOn) return 'off (Intelligent UI is off)'
- if (o.isFullscreen === false) return 'off on the main screen (use /iui grab)'
+ if (o.none) {
+ if (o.isMac || !o.way || 'off' in o.way) return 'off (no PerlObjCBridge in /usr/bin/perl)'
+ return `off (${o.way.name} stopped${o.way.wayland ? ': the compositor may not have the data-control protocol' : ''})`
+ }
if (!o.drawn) return 'off (no picture yet)'
- if (!o.asking) return 'off (the ask reader does not run)'
- const hint = hintOffOf(o)
- if (hint) return `on (no /iui grab hint: ${hint})`
+ if (!o.running) return 'off (the watcher does not run)'
return o.isMac || !o.way || !('name' in o.way) ? 'on' : `on, with ${o.way.name}`
}
-
-// Why the watcher gives no /iui grab hint; '' when it does.
-function hintOffOf(o: { isMac: boolean; none: boolean; way: ClipWay | null }): string {
- if (!o.isMac && o.way && 'off' in o.way) return o.way.off
- if (!o.none) return ''
- if (o.isMac || !o.way || 'off' in o.way) return 'no PerlObjCBridge in /usr/bin/perl'
- return `${o.way.name} stopped${o.way.wayland ? ': the compositor may not have the data-control protocol' : ''}`
-}
diff --git a/hooks/lib/env.ts b/hooks/lib/env.ts
index ff76e84..a4803a7 100644
--- a/hooks/lib/env.ts
+++ b/hooks/lib/env.ts
@@ -4,7 +4,7 @@ import { atom, update } from 'claude-code'
import type { EngineInterface } from 'claude-code'
import {
- BASE_THEME, DEFAULT_HEIGHT, DEFAULT_SIZE, DESIGNS_KEPT_DAYS, DEFAULT_THEME, DEFAULT_WIDTH, MAX_HEIGHT, MAX_SIZE, MAX_WIDTH, MIN_HEIGHT, MIN_SIZE, MIN_WIDTH, noTypstOf, USE_COPY_SHIM,
+ BASE_THEME, DEFAULT_HEIGHT, DEFAULT_SIZE, DESIGNS_KEPT_DAYS, DEFAULT_THEME, DEFAULT_WIDTH, MAX_HEIGHT, MAX_SIZE, MAX_WIDTH, MIN_HEIGHT, MIN_SIZE, MIN_WIDTH, noTypstOf,
} from './settings'
import { DEFAULT_METRICS, refresh, S, type Env } from './state'
import { resolveMode, settingOf } from './mode'
@@ -16,7 +16,7 @@ import { registerCommand } from './command'
import { readHostMode, termFontOf, watchHost } from './host'
import { readFrame, setFrame, watchFrame } from './frame'
import { offerSetup } from './setup'
-import { findClipWay, noShims, setUpShims } from './clipboard'
+import { findClipWay } from './clipboard'
import { findTypst, measureFonts } from './typst'
import { checkUpdates } from './updates'
import { configs, envGet, fsList, fsStat, pluginRoot, processRun, sessionCwd, sessionVersion, storeGet, uiToast } from './api'
@@ -26,13 +26,11 @@ import { configs, envGet, fsList, fsStat, pluginRoot, processRun, sessionCwd, se
const isOn = atom({ plugin: 'cc-intelligent-ui', key: 'isOn' } as const, true)
// Makes the cache folder (stops when it is a link or not this user's),
-// drops key folders not touched for 2 days (not the asks and shims of a
-// live process), the ask FIFOs, request files and shims folders of a pid
-// that is gone (and request files of 2 days), makes the designs folder
+// drops key folders not touched for 2 days, makes the designs folder
// (outside the tmp cache) and drops design files not touched for
// DESIGNS_KEPT_DAYS; prints the cache folder, the OS name and the designs
// folder (the OS name alone when the cache folder can not be made private).
-export const CACHE_SH = `d="\${TMPDIR:-/tmp}"; d="\${d%/}/cc-intelligent-ui-$(id -u)"; g="\${XDG_CACHE_HOME:-$HOME/.cache}/cc-intelligent-ui/designs"; mkdir "$d" 2>/dev/null; [ ! -L "$d" ] && [ -d "$d" ] && [ -O "$d" ] && chmod 700 "$d" && { find "$d" -mindepth 1 -maxdepth 1 -type d -mtime +2 ! -name pkg-cache ! -name ask ! -name 'shims-*' -exec rm -rf {} + 2>/dev/null; for f in "$d"/ask-* "$d"/ask/* "$d"/shims-*; do n=\${f##*/}; n=\${n#ask-}; n=\${n#shims-}; n=\${n%%-*}; case $n in ''|*[!0-9]*) continue ;; esac; kill -0 "$n" 2>/dev/null || rm -rf -- "$f"; done; find "$d/ask" -type f -mtime +2 -delete 2>/dev/null; mkdir -p "$g" 2>/dev/null && find "$g" -type f -mtime +${DESIGNS_KEPT_DAYS} -delete 2>/dev/null; printf '%s\\n%s\\n%s\\n' "$d" "$(uname -s)" "$g"; } || printf '\\n%s\\n\\n' "$(uname -s)"`
+export const CACHE_SH = `d="\${TMPDIR:-/tmp}"; d="\${d%/}/cc-intelligent-ui-$(id -u)"; g="\${XDG_CACHE_HOME:-$HOME/.cache}/cc-intelligent-ui/designs"; mkdir "$d" 2>/dev/null; [ ! -L "$d" ] && [ -d "$d" ] && [ -O "$d" ] && chmod 700 "$d" && { find "$d" -mindepth 1 -maxdepth 1 -type d -mtime +2 ! -name pkg-cache -exec rm -rf {} + 2>/dev/null; mkdir -p "$g" 2>/dev/null && find "$g" -type f -mtime +${DESIGNS_KEPT_DAYS} -delete 2>/dev/null; printf '%s\\n%s\\n%s\\n' "$d" "$(uname -s)" "$g"; } || printf '\\n%s\\n\\n' "$(uname -s)"`
// Once per load: the cache folder, Typst, the terminal and its font, the
// theme, the cell. A failed setup is tried again on the next call.
@@ -48,14 +46,13 @@ export function setUp($: EngineInterface): Promise<Env> {
const program = (await envGet($, 'TERM_PROGRAM')) ?? ''
const term = (await envGet($, 'TERM')) ?? ''
const ssh = !!(await envGet($, 'SSH_CONNECTION')) || !!(await envGet($, 'SSH_TTY'))
- const background = (await envGet($, 'CLAUDE_CODE_SESSION_KIND')) === 'bg'
const canDraw = canDrawIn({
program,
term,
kitty: !!(await envGet($, 'KITTY_WINDOW_ID')),
tmux: !!(await envGet($, 'TMUX')) || !!(await envGet($, 'STY')) || /^tmux|^screen/i.test(term),
ssh,
- background,
+ background: (await envGet($, 'CLAUDE_CODE_SESSION_KIND')) === 'bg',
engineForced: isSet(await envGet($, 'CLAUDE_CODE_FORCE_TERMINAL_IMAGES')),
modForced: isSet(await envGet($, 'IUI_FORCE')),
})
@@ -71,15 +68,6 @@ export function setUp($: EngineInterface): Promise<Env> {
S.itermProfile = (await envGet($, 'ITERM_PROFILE')) || undefined
S.isKitty = /kitty/i.test(term) || !!(await envGet($, 'KITTY_WINDOW_ID')) || !!(await envGet($, 'KITTY_PID'))
S.isRemote = ssh
- // On this computer, where pictures draw: the clipboard shims, before Claude Code copies.
- if (!ssh && (S.hostOs === 'Darwin' || S.hostOs === 'Linux')) {
- if (!USE_COPY_SHIM && !isSet(await envGet($, 'IUI_COPY_SHIM'))) noShims('the copy shims are off')
- else if (background) noShims('a background session')
- else if (!canDraw) noShims('no pictures in this terminal')
- // Never in the shared fallback folder.
- else if (made1.trim()) await setUpShims($, cache, S.hostOs === 'Darwin')
- else noShims()
- }
S.debug = isSet(await envGet($, 'IUI_DEBUG'))
S.isIterm = isItermIn({
program,
diff --git a/hooks/lib/frames.ts b/hooks/lib/frames.ts
new file mode 100644
index 0000000..9bc305e
--- /dev/null
+++ b/hooks/lib/frames.ts
@@ -0,0 +1,109 @@
+// A page ready for picture select's frames (blit.ts): its pixels, the
+// cells' pixel edges and the deflate piece of each plain cell row (png.ts),
+// made at once (framesOf) or in steps (framesSteps, for pagecache.ts).
+// Pure: no hooks call here.
+import type { IuiTheme } from '../../types'
+import { chunk, concat, decodeSteps, deflatePiece, headOf, tailOf, type Piece, type Rgba } from './png'
+import type { SelRow } from './select'
+
+export type Rgb = readonly [number, number, number]
+
+// VS Code's selection colour of the mode.
+export const selectColor = (mode: IuiTheme) => (mode === 'light' ? '#add6ff' : '#264f78')
+export const rgbOf = (hex: string): Rgb => [1, 3, 5].map(i => parseInt(hex.slice(i, i + 2), 16)) as unknown as Rgb
+
+// The pixel edges of `cells` cells over `px` pixels: cell i is pixels
+// edges[i] to edges[i + 1] (exclusive). Each edge is rounded once, so the
+// cells tile the picture with no gap or overlap, whatever the ratio.
+export function edgesOf(px: number, cells: number): number[] {
+ return Array.from({ length: cells + 1 }, (_, i) => Math.round((i * px) / cells))
+}
+
+// One channel of a page pixel of alpha `a` over the opaque colour channel `c`.
+export const over = (p: number, a: number, c: number) => Math.floor((p * a + c * (255 - a) + 127) / 255)
+
+// Pixel rows y0 to y1 (exclusive) of `img` as PNG scanlines (filter 0),
+// pixels x0 to x1 (exclusive) over the colour.
+export function bandOf(img: Rgba, y0: number, y1: number, x0: number, x1: number, color: Rgb): Uint8Array {
+ const stride = img.width * 4
+ const out = new Uint8Array((y1 - y0) * (stride + 1))
+ const [r, g, b] = color
+ for (let y = y0; y < y1; y++) {
+ const o = (y - y0) * (stride + 1) + 1
+ out.set(img.data.subarray(y * stride, (y + 1) * stride), o)
+ for (let p = o + x0 * 4, end = o + x1 * 4; p < end; p += 4) {
+ const a = out[p + 3]!
+ if (a === 255) continue
+ out[p] = over(out[p]!, a, r)
+ out[p + 1] = over(out[p + 1]!, a, g)
+ out[p + 2] = over(out[p + 2]!, a, b)
+ out[p + 3] = 255
+ }
+ }
+ return out
+}
+
+// A piece with its IDAT chunk (the CRC is made once).
+export type Chunked = { piece: Piece; chunk: Uint8Array }
+const chunked = (raw: Uint8Array, line: number): Chunked => {
+ const piece = deflatePiece(raw, 4, line)
+ return { piece, chunk: chunk('IDAT', piece.bytes) }
+}
+
+// A decoded page ready for frames: its pixels, the cells' pixel edges, the
+// plain row pieces, and the tinted ones made so far.
+export type Frames = { img: Rgba; xs: number[]; ys: number[]; color: Rgb; head: Uint8Array; plain: Chunked[]; tint: (Chunked | undefined)[] }
+
+export function framesOf(img: Rgba, box: { columns: number; rows: number }, color: Rgb): Frames {
+ const steps = framesFrom(img, box, color)
+ for (;;) {
+ const got = steps.next()
+ if (got.done) return got.value
+ }
+}
+
+// The same Frames from a PNG's bytes, in steps: the decode's (decodeSteps),
+// then a yield after each plain row piece. The Frames are yielded once they
+// can make frames; the steps after it make the tinted piece of each row.
+export function* framesSteps(png: Uint8Array, box: { columns: number; rows: number }, color: Rgb): Generator<Frames | undefined, Frames, void> {
+ const img = yield* decodeSteps(png)
+ const f = yield* framesFrom(img, box, color)
+ yield f
+ const line = img.width * 4 + 1
+ for (let r = 0; r < box.rows; r++) {
+ f.tint[r] ??= chunked(bandOf(img, f.ys[r]!, f.ys[r + 1]!, 0, img.width, color), line)
+ yield
+ }
+ return f
+}
+
+function* framesFrom(img: Rgba, box: { columns: number; rows: number }, color: Rgb): Generator<undefined, Frames, void> {
+ const xs = edgesOf(img.width, box.columns)
+ const ys = edgesOf(img.height, box.rows)
+ const line = img.width * 4 + 1
+ const plain: Chunked[] = []
+ for (let r = 0; r < box.rows; r++) {
+ plain.push(chunked(bandOf(img, ys[r]!, ys[r + 1]!, 0, 0, color), line))
+ yield
+ }
+ return { img, xs, ys, color, head: headOf(img.width, img.height), plain, tint: [] }
+}
+
+// The bytes a page's Frames hold (the pixels and the pieces).
+export const bytesOf = (f: Frames) => f.img.data.length + [...f.plain, ...f.tint].reduce((n, p) => n + (p ? p.chunk.length + p.piece.bytes.length : 0), 0)
+
+// The frame PNG of a page with `rows` selected (cells x0 to x1, inclusive).
+export function frameOf(f: Frames, rows: readonly SelRow[]): Uint8Array {
+ const line = f.img.width * 4 + 1
+ const columns = f.xs.length - 1
+ const at = new Map(rows.map(r => [r.row, r]))
+ const parts = f.plain.map((plain, r) => {
+ const sel = at.get(r)
+ if (!sel || sel.x1 < sel.x0) return plain
+ const [y0, y1] = [f.ys[r]!, f.ys[r + 1]!]
+ if (sel.x0 <= 0 && sel.x1 >= columns - 1) return (f.tint[r] ??= chunked(bandOf(f.img, y0, y1, 0, f.img.width, f.color), line))
+ return chunked(bandOf(f.img, y0, y1, f.xs[Math.max(0, sel.x0)]!, f.xs[Math.min(columns, sel.x1 + 1)]!, f.color), line)
+ })
+ return concat([f.head, ...parts.map(p => p.chunk), tailOf(parts.map(p => p.piece))])
+}
+
diff --git a/hooks/lib/pagecache.ts b/hooks/lib/pagecache.ts
new file mode 100644
index 0000000..3d7a1e2
--- /dev/null
+++ b/hooks/lib/pagecache.ts
@@ -0,0 +1,340 @@
+// Picture select's page cache: each page that takes picture select is made
+// ready for its frames (frames.ts: decoded, its plain row pieces) and its
+// words are probed (probe.ts) in the background, when it is drawn or comes
+// on screen, so the first highlight and the copy at the button's up wait
+// for nothing. The hooks have no thread, worker or timer of their own (only
+// `$.clock`; `$.process` is a process whose pixels would come back as
+// base64): a build runs in slices of SLICE_MS at most, each after a
+// `clock.after(0)`, so render hooks run between them. One build at a time:
+// a page a down asks for first, then the pages on screen, the newest
+// drawing first; a build that a down puts aside is paused and goes on
+// later; a page that leaves the screen is dropped (its build too). The
+// pages built stay in memory (FRAMES_KEPT_BYTES at most; the ones off
+// screen go first). Nothing is written to disk: the pixels are the most of
+// it, and a text write of them would cost more than the decode.
+import type { EngineInterface } from 'claude-code'
+
+import type { DrawnPage, Drawn } from './copy'
+import { pageTopsOf } from './copy'
+import { bytesOf, framesSteps, rgbOf, type Frames } from './frames'
+import { fromBase64 } from './png'
+import { knownWords, wordsOf } from './probe'
+import type { Job } from './state'
+import { traceDebug } from './log'
+import { clockAfter, fsRead, uiLog } from './api'
+
+// A slice's budget, and a page a down waits for.
+export const SLICE_MS = 4
+export const PROMOTED_SLICE_MS = 8
+// The pages built kept (their pixels and pieces), by bytes: about two of the tallest.
+export const FRAMES_KEPT_BYTES = 128 * 1024 * 1024
+// The pages whose words the background probed and got none: not probed again
+// in the background (a copy still tries).
+const WORDS_TRIED_KEPT = 256
+
+// A page to build: its drawing (`id`, `seq`: newer is larger) and index,
+// whether it is on screen, `promoted` (0: no down asked; else the order of
+// the ask, the last one first) and its build put aside, if any.
+export type Want = { key: string; page: DrawnPage; color: string; id: string; index: number; seq: number; onScreen: boolean; promoted: number; paused?: Build }
+export type Build = {
+ want: Want; steps: Generator<Frames | undefined, Frames, void> | null; png: Uint8Array | null; slices: number[]; started: number
+ readMs: number; readyMs: number; stepMs: number; isCancelled: boolean; isReady: boolean
+}
+
+export const keyOf = (page: DrawnPage, color: string) => `${page.file}|${page.columns}x${page.rows}|${color}`
+
+// The next page to build: the last one a down asked for, then the pages on
+// screen, the newest drawing first, its pages in order.
+export function nextWant(wants: Iterable<Want>): Want | undefined {
+ let best: Want | undefined
+ const before = (a: Want, b: Want) =>
+ a.promoted !== b.promoted ? a.promoted > b.promoted : a.onScreen !== b.onScreen ? a.onScreen : a.seq !== b.seq ? a.seq > b.seq : a.index < b.index
+ for (const w of wants) if (!best || before(w, best)) best = w
+ return best
+}
+
+// The keys to drop so the rest fit `budget` bytes: `kept` in use order (the
+// oldest first), the ones off screen before the ones on screen; `keep` never.
+export function evictKeys(kept: readonly { key: string; bytes: number; onScreen: boolean }[], budget: number, keep: string): string[] {
+ let bytes = kept.reduce((n, k) => n + k.bytes, 0)
+ const out: string[] = []
+ for (const k of [...kept.filter(k => !k.onScreen), ...kept.filter(k => k.onScreen)]) {
+ if (bytes <= budget) break
+ if (k.key === keep) continue
+ bytes -= k.bytes
+ out.push(k.key)
+ }
+ return out
+}
+
+// One slice of `steps`: steps until `budget` ms have gone, never one that
+// the last step's time says would go past it (one step at least). `each`
+// gets each value yielded; `done` the result when the steps end.
+export function sliceOf<T>(
+ steps: Generator<T | undefined, T, void>, budget: number, b: { stepMs: number }, each: (value: T) => void, now = () => performance.now(),
+): { done?: T; ms: number } {
+ const t0 = now()
+ for (;;) {
+ const t = now()
+ const got = steps.next()
+ const end = now()
+ b.stepMs = end - t
+ if (got.done) return { done: got.value, ms: end - t0 }
+ if (got.value) each(got.value)
+ if (end - t0 + b.stepMs >= budget) return { ms: end - t0 }
+ }
+}
+
+// The value at `p` (0 to 1) of the sorted numbers.
+export const quantile = (sorted: readonly number[], p: number) => sorted[Math.min(sorted.length - 1, Math.max(0, Math.ceil(p * sorted.length) - 1))] ?? 0
+
+// The pages of `d` on screen now: by its rows on screen and its page tops;
+// all of them when the tops are not known, none when it is off screen.
+export function pagesOnScreen(d: Drawn): number[] {
+ if (d.onScreen === null) return []
+ const tops = pageTopsOf(d)
+ const all = d.pages.map((_, i) => i)
+ if (!tops || !d.onScreen) return all
+ const { first, last } = d.onScreen
+ return all.filter(i => tops[i]! <= last && tops[i]! + d.pages[i]!.rows - 1 >= first)
+}
+
+// The cache: the pages built (in use order; null: it can not be), the
+// pages to build, the pages on screen, the build now and who waits for a
+// page; the words to probe, and the ones the background got none for.
+export const pages = {
+ frames: new Map<string, Frames | null>(),
+ wants: new Map<string, Want>(),
+ screen: new Set<string>(),
+ build: null as Build | null,
+ waiters: new Map<string, ((f: Frames | null) => void)[]>(),
+ promotions: 0,
+ isPumping: false,
+ words: [] as { key: string; d: Drawn & { job?: Job }; page: number }[],
+ wordsTried: new Set<string>(),
+ isProbing: false,
+}
+
+// Forgets everything (for tests).
+export function forgetPages() {
+ pages.frames.clear()
+ pages.wants.clear()
+ pages.screen.clear()
+ pages.waiters.clear()
+ pages.build = null
+ pages.promotions = 0
+ pages.isPumping = false
+ pages.words = []
+ pages.wordsTried.clear()
+ pages.isProbing = false
+}
+
+const ms = (t: number) => `${Math.round(t)}ms`
+const nameOf = (file: string) => file.split('/').slice(-2).join('/')
+
+// A page's frames when they are built (null: they can not be; undefined: not yet).
+export function framesKnown(page: DrawnPage, color: string): Frames | null | undefined {
+ const key = keyOf(page, color)
+ const got = pages.frames.get(key)
+ if (got !== undefined) {
+ pages.frames.delete(key)
+ pages.frames.set(key, got)
+ }
+ return got
+}
+
+// The pages of drawing `d` now (drawn, or a new onScreen): the ones on
+// screen are queued (with their words); the others leave the queue, and a
+// build of one stops (not one a down asked for). Never waits.
+export function notePages($: EngineInterface, d: Drawn & { job?: Job }, color: string) {
+ const on = new Set(pagesOnScreen(d))
+ d.pages.forEach((page, index) => {
+ const key = keyOf(page, color)
+ const wordsKey = `${d.dir}#${index}`
+ if (!on.has(index)) {
+ pages.screen.delete(key)
+ const want = pages.wants.get(key)
+ if (want && !want.promoted) {
+ pages.wants.delete(key)
+ if (want.paused) traceDebug($, `select: cache stop ${nameOf(page.file)} (off screen, paused) after ${want.paused.slices.length} slices`)
+ }
+ const b = pages.build
+ if (b && b.want.key === key && !b.want.promoted && !b.isCancelled) {
+ b.isCancelled = true
+ traceDebug($, `select: cache stop ${nameOf(page.file)} (off screen) after ${b.slices.length} slices`)
+ }
+ pages.words = pages.words.filter(w => w.key !== wordsKey)
+ return
+ }
+ pages.screen.add(key)
+ if (!pages.frames.has(key) && pages.build?.want.key !== key) {
+ const want = pages.wants.get(key)
+ if (want) Object.assign(want, { page, id: d.id, index, seq: d.seq, onScreen: true })
+ else pages.wants.set(key, { key, page, color, id: d.id, index, seq: d.seq, onScreen: true, promoted: 0 })
+ }
+ if (d.job && !knownWords(d, index) && !pages.wordsTried.has(wordsKey) && !pages.words.some(w => w.key === wordsKey)) pages.words.push({ key: wordsKey, d, page: index })
+ })
+ kick($)
+ probeNext($)
+}
+
+// A page's frames, built first now (a down): at once when they are there,
+// else when its build (to the front of the queue) is done. `waitMs` the wait.
+export async function needFrames($: EngineInterface, page: DrawnPage, color: string, at?: { id: string; index: number; seq: number }): Promise<{ frames: Frames | null; waitMs: number }> {
+ const known = framesKnown(page, color)
+ if (known !== undefined) return { frames: known, waitMs: 0 }
+ const t = performance.now()
+ const key = keyOf(page, color)
+ const promoted = ++pages.promotions
+ const b = pages.build
+ if (b && b.want.key === key) b.want.promoted = promoted
+ else {
+ // The build now is put aside: paused (on screen), else dropped.
+ if (b && !b.isCancelled) {
+ pages.build = null
+ if (!b.isReady && (pages.screen.has(b.want.key) || b.want.promoted)) {
+ b.want.paused = b
+ pages.wants.set(b.want.key, b.want)
+ traceDebug($, `select: cache pause ${nameOf(b.want.page.file)} after ${b.slices.length} slices`)
+ } else b.isCancelled = true
+ }
+ const want = pages.wants.get(key)
+ if (want) Object.assign(want, { onScreen: true, promoted, ...(at ? { id: at.id, index: at.index, seq: at.seq } : {}) })
+ else pages.wants.set(key, { key, page, color, id: at?.id ?? '', index: at?.index ?? 0, seq: at?.seq ?? 0, onScreen: true, promoted })
+ traceDebug($, `select: cache first ${nameOf(page.file)} (a down; ${pages.wants.size} queued)`)
+ }
+ const frames = await new Promise<Frames | null>(done => {
+ pages.waiters.set(key, [...(pages.waiters.get(key) ?? []), done])
+ kick($)
+ })
+ return { frames, waitMs: performance.now() - t }
+}
+
+// The next slice, after the hooks' other work.
+function later($: EngineInterface) {
+ try {
+ clockAfter($, 0, () => void slice($).catch(() => (pages.isPumping = false)))
+ } catch {
+ pages.isPumping = false
+ }
+}
+
+function kick($: EngineInterface) {
+ if (pages.isPumping) return
+ pages.isPumping = true
+ later($)
+}
+
+// One slice: the next build begun (its PNG read) or taken up again, or
+// SLICE_MS of the build now.
+async function slice($: EngineInterface) {
+ let b = pages.build
+ if (b?.isCancelled) b = pages.build = null
+ if (!b) {
+ const want = nextWant(pages.wants.values())
+ if (!want) {
+ pages.isPumping = false
+ return
+ }
+ pages.wants.delete(want.key)
+ if (want.paused) {
+ b = pages.build = want.paused
+ want.paused = undefined
+ traceDebug($, `select: cache resume ${nameOf(want.page.file)} after ${b.slices.length} slices${want.promoted ? ', asked by a down' : ''}`)
+ } else {
+ const started = performance.now()
+ b = pages.build = { want, steps: null, png: null, slices: [], started, readMs: 0, readyMs: 0, stepMs: 0, isCancelled: false, isReady: false }
+ try {
+ const { base64 } = await fsRead($, want.page.file, { as: 'bytes' })
+ if (!b.isCancelled) b.png = fromBase64(base64)
+ } catch (err) {
+ fail($, b, err)
+ }
+ b.readMs = performance.now() - started
+ if (b.png) traceDebug($, `select: cache start ${nameOf(want.page.file)} (read ${ms(b.readMs)}${want.promoted ? ', asked by a down' : ''}, ${pages.wants.size} queued)`)
+ later($)
+ return
+ }
+ }
+ const build = b
+ try {
+ build.steps ??= framesSteps(build.png!, build.want.page, rgbOf(build.want.color))
+ const got = sliceOf(build.steps, build.want.promoted ? PROMOTED_SLICE_MS : SLICE_MS, build, f => ready($, build, f))
+ build.slices.push(got.ms)
+ if (got.done) {
+ if (pages.build === build) pages.build = null
+ built($, build, got.done)
+ }
+ } catch (err) {
+ if (build.isReady) {
+ if (pages.build === build) pages.build = null
+ } else fail($, build, err)
+ }
+ later($)
+}
+
+// The cache within its budget: the oldest pages off screen go first.
+function evict(keep: string) {
+ const kept = [...pages.frames].map(([k, f]) => ({ key: k, bytes: f ? bytesOf(f) : 0, onScreen: pages.screen.has(k) }))
+ for (const k of evictKeys(kept, FRAMES_KEPT_BYTES, keep)) pages.frames.delete(k)
+}
+
+// A build's frames are ready (or can not be: null): kept and given to who
+// waits; its tinted rows go on.
+function ready($: EngineInterface, b: Build, frames: Frames | null) {
+ b.isReady = true
+ b.readyMs = performance.now() - b.started
+ const { key } = b.want
+ pages.frames.delete(key)
+ pages.frames.set(key, frames)
+ evict(key)
+ const waiters = pages.waiters.get(key) ?? []
+ pages.waiters.delete(key)
+ for (const done of waiters) done(frames)
+}
+
+// A build that failed: no frames for the page (not tried again).
+function fail($: EngineInterface, b: Build, err: unknown) {
+ if (pages.build === b) pages.build = null
+ pages.wants.delete(b.want.key)
+ ready($, b, null)
+ const why = `no highlight for ${b.want.page.file}: ${err instanceof Error ? err.message : String(err)}`
+ traceDebug($, `select: ${why}`)
+ void Promise.resolve(uiLog($, `Intelligent UI: picture select: ${why}`, { to: 'debug' })).catch(() => undefined)
+}
+
+// A build done (its tinted rows too): the cache within its budget again, and its trace.
+function built($: EngineInterface, b: Build, frames: Frames) {
+ evict(b.want.key)
+ const sorted = [...b.slices].sort((x, y) => x - y)
+ let bytes = 0
+ for (const f of pages.frames.values()) bytes += f ? bytesOf(f) : 0
+ traceDebug($,
+ `select: cache built ${nameOf(b.want.page.file)} ${frames.img.width}x${frames.img.height} ready in ${ms(b.readyMs)}, done in ${ms(performance.now() - b.started)} ` +
+ `(read ${ms(b.readMs)}, ${b.slices.length} slices, max ${(sorted.at(-1) ?? 0).toFixed(1)}ms, p95 ${quantile(sorted, 0.95).toFixed(1)}ms` +
+ `${b.want.promoted ? ', asked by a down' : ''}); ${pages.frames.size} pages kept, ${(bytes / (1 << 20)).toFixed(0)} MB, ${pages.wants.size} queued`)
+}
+
+// The words of the pages queued, one probe at a time (a typst process: it
+// does not hold the hooks), the newest drawing first.
+function probeNext($: EngineInterface) {
+ if (pages.isProbing || !pages.words.length) return
+ pages.words.sort((a, b) => b.d.seq - a.d.seq || a.page - b.page)
+ const next = pages.words.shift()!
+ if (knownWords(next.d, next.page)) return probeNext($)
+ pages.isProbing = true
+ const t = performance.now()
+ void wordsOf($, next.d, next.page)
+ .then(got => {
+ if (!got) {
+ if (pages.wordsTried.size >= WORDS_TRIED_KEPT) pages.wordsTried.clear()
+ pages.wordsTried.add(next.key)
+ }
+ traceDebug($, `select: words ${next.d.id} page ${next.page} ${got ? `${got.items.length} words` : 'none'} in ${ms(performance.now() - t)} (background)`)
+ })
+ .catch(() => undefined)
+ .finally(() => {
+ pages.isProbing = false
+ probeNext($)
+ })
+}
diff --git a/hooks/lib/png.ts b/hooks/lib/png.ts
index 3a57513..06dfb44 100644
--- a/hooks/lib/png.ts
+++ b/hooks/lib/png.ts
@@ -94,137 +94,179 @@ function tableOf(lens: ArrayLike<number>, n: number): Table {
const FIXED_LIT = tableOf(Array.from({ length: 288 }, (_, i) => (i < 144 ? 8 : i < 256 ? 9 : i < 280 ? 7 : 8)), 288)
const FIXED_DIST = tableOf(new Array<number>(32).fill(5), 32)
-// Inflates the zlib stream `src` into `out` (its size known); returns the
-// bytes written. Throws on a stream that is not one.
-export function inflate(src: Uint8Array, out: Uint8Array): number {
- if (src.length < 2 || (src[0]! & 0x0f) !== 8 || ((src[0]! << 8) | src[1]!) % 31 !== 0 || src[1]! & 0x20) throw new Error('not a zlib stream')
- let pos = 2
- let bb = 0
- let bc = 0
- let op = 0
- const bitsOf = (n: number) => {
- while (bc < n) {
- bb |= (src[pos++] ?? 0) << bc
- bc += 8
- }
- const v = bb & ((1 << n) - 1)
- bb >>>= n
- bc -= n
- return v
- }
- const symOf = (t: Table) => {
- while (bc < t.bits) {
- bb |= (src[pos++] ?? 0) << bc
- bc += 8
- }
- const e = t.table[bb & ((1 << t.bits) - 1)]!
- const len = e & 15
- if (!len) throw new Error('bad Huffman code')
- bb >>>= len
- bc -= len
- return e >> 4
+// A zlib stream inflated into `out` (its size known), in steps: `run(limit)`
+// goes on until `limit` bytes are out or the stream ends (true then). Any
+// limits give the same bytes. Throws on a stream that is not one.
+export class Inflater {
+ op = 0
+ isDone = false
+ private pos = 2
+ private bb = 0
+ private bc = 0
+ private last = 0
+ // The block now (null: at a block's header).
+ private lit: Table | null = null
+ private dist: Table | null = null
+ constructor(private readonly src: Uint8Array, readonly out: Uint8Array) {
+ if (src.length < 2 || (src[0]! & 0x0f) !== 8 || ((src[0]! << 8) | src[1]!) % 31 !== 0 || src[1]! & 0x20) throw new Error('not a zlib stream')
}
- for (let last = 0; !last; ) {
- last = bitsOf(1)
- const type = bitsOf(2)
- if (type === 0) {
- pos -= bc >> 3
- bb = bc = 0
- const len = src[pos]! | (src[pos + 1]! << 8)
- pos += 4
- if (pos + len > src.length || op + len > out.length) throw new Error('stored block past the end')
- out.set(src.subarray(pos, pos + len), op)
- pos += len
- op += len
- continue
- }
- let lit = FIXED_LIT
- let dist = FIXED_DIST
- if (type === 2) {
- const hlit = bitsOf(5) + 257
- const hdist = bitsOf(5) + 1
- const hclen = bitsOf(4) + 4
- const cl = new Uint8Array(19)
- for (let i = 0; i < hclen; i++) cl[CL_ORDER[i]!] = bitsOf(3)
- const clt = tableOf(cl, 19)
- const lens = new Uint8Array(hlit + hdist)
- for (let i = 0; i < hlit + hdist; ) {
- const sym = symOf(clt)
- if (sym < 16) lens[i++] = sym
- else {
- const [rep, prev] = sym === 16 ? [3 + bitsOf(2), i ? lens[i - 1]! : -1] : sym === 17 ? [3 + bitsOf(3), 0] : [11 + bitsOf(7), 0]
- if (prev < 0 || i + rep > hlit + hdist) throw new Error('bad code lengths')
- lens.fill(prev, i, i + rep)
- i += rep
- }
- }
- lit = tableOf(lens.subarray(0, hlit), hlit)
- dist = tableOf(lens.subarray(hlit), hdist)
- } else if (type !== 1) throw new Error('bad block type')
- // The hot loop, inlined: refill, look up, consume.
- const lt = lit.table
- const lb = lit.bits
- const lm = (1 << lb) - 1
- const dt = dist.table
- const db = dist.bits
- const dm = (1 << db) - 1
- for (;;) {
- while (bc < lb) {
+
+ run(limit: number): boolean {
+ const { src, out } = this
+ let { pos, bb, bc, op } = this
+ const bitsOf = (n: number) => {
+ while (bc < n) {
bb |= (src[pos++] ?? 0) << bc
bc += 8
}
- let e = lt[bb & lm]!
- let n = e & 15
- if (!n) throw new Error('bad Huffman code')
+ const v = bb & ((1 << n) - 1)
bb >>>= n
bc -= n
- const sym = e >> 4
- if (sym < 256) {
- if (op >= out.length) throw new Error('output past the end')
- out[op++] = sym
- continue
- }
- if (sym === 256) break
- const li = sym - 257
- if (li >= 29) throw new Error('bad length code')
- let len = LEN_BASE[li]!
- n = LEN_EXTRA[li]!
- while (bc < 15) {
+ return v
+ }
+ const symOf = (t: Table) => {
+ while (bc < t.bits) {
bb |= (src[pos++] ?? 0) << bc
bc += 8
}
- if (n) {
- len += bb & ((1 << n) - 1)
+ const e = t.table[bb & ((1 << t.bits) - 1)]!
+ const len = e & 15
+ if (!len) throw new Error('bad Huffman code')
+ bb >>>= len
+ bc -= len
+ return e >> 4
+ }
+ const save = () => {
+ this.pos = pos
+ this.bb = bb
+ this.bc = bc
+ this.op = op
+ }
+ while (!this.isDone) {
+ if (!this.lit) {
+ if (this.last) {
+ this.isDone = true
+ break
+ }
+ if (op >= limit) break
+ this.last = bitsOf(1)
+ const type = bitsOf(2)
+ if (type === 0) {
+ pos -= bc >> 3
+ bb = bc = 0
+ const len = src[pos]! | (src[pos + 1]! << 8)
+ pos += 4
+ if (pos + len > src.length || op + len > out.length) throw new Error('stored block past the end')
+ out.set(src.subarray(pos, pos + len), op)
+ pos += len
+ op += len
+ continue
+ }
+ if (type === 1) {
+ this.lit = FIXED_LIT
+ this.dist = FIXED_DIST
+ } else if (type === 2) {
+ const hlit = bitsOf(5) + 257
+ const hdist = bitsOf(5) + 1
+ const hclen = bitsOf(4) + 4
+ const cl = new Uint8Array(19)
+ for (let i = 0; i < hclen; i++) cl[CL_ORDER[i]!] = bitsOf(3)
+ const clt = tableOf(cl, 19)
+ const lens = new Uint8Array(hlit + hdist)
+ for (let i = 0; i < hlit + hdist; ) {
+ const sym = symOf(clt)
+ if (sym < 16) lens[i++] = sym
+ else {
+ const [rep, prev] = sym === 16 ? [3 + bitsOf(2), i ? lens[i - 1]! : -1] : sym === 17 ? [3 + bitsOf(3), 0] : [11 + bitsOf(7), 0]
+ if (prev < 0 || i + rep > hlit + hdist) throw new Error('bad code lengths')
+ lens.fill(prev, i, i + rep)
+ i += rep
+ }
+ }
+ this.lit = tableOf(lens.subarray(0, hlit), hlit)
+ this.dist = tableOf(lens.subarray(hlit), hdist)
+ } else throw new Error('bad block type')
+ }
+ // The hot loop, inlined: refill, look up, consume; it stops at `limit`.
+ const lt = this.lit.table
+ const lb = this.lit.bits
+ const lm = (1 << lb) - 1
+ const dt = this.dist!.table
+ const db = this.dist!.bits
+ const dm = (1 << db) - 1
+ let isEnd = false
+ while (op < limit) {
+ while (bc < lb) {
+ bb |= (src[pos++] ?? 0) << bc
+ bc += 8
+ }
+ let e = lt[bb & lm]!
+ let n = e & 15
+ if (!n) throw new Error('bad Huffman code')
bb >>>= n
bc -= n
+ const sym = e >> 4
+ if (sym < 256) {
+ if (op >= out.length) throw new Error('output past the end')
+ out[op++] = sym
+ continue
+ }
+ if (sym === 256) {
+ isEnd = true
+ break
+ }
+ const li = sym - 257
+ if (li >= 29) throw new Error('bad length code')
+ let len = LEN_BASE[li]!
+ n = LEN_EXTRA[li]!
+ while (bc < 15) {
+ bb |= (src[pos++] ?? 0) << bc
+ bc += 8
+ }
+ if (n) {
+ len += bb & ((1 << n) - 1)
+ bb >>>= n
+ bc -= n
+ }
+ while (bc < db) {
+ bb |= (src[pos++] ?? 0) << bc
+ bc += 8
+ }
+ e = dt[bb & dm]!
+ n = e & 15
+ if (!n) throw new Error('bad Huffman code')
+ bb >>>= n
+ bc -= n
+ const di = e >> 4
+ if (di >= 30) throw new Error('bad distance code')
+ n = DIST_EXTRA[di]!
+ while (bc < n) {
+ bb |= (src[pos++] ?? 0) << bc
+ bc += 8
+ }
+ const d = DIST_BASE[di]! + (bb & ((1 << n) - 1))
+ bb >>>= n
+ bc -= n
+ if (d > op || op + len > out.length) throw new Error('bad match')
+ if (d >= len) {
+ out.copyWithin(op, op - d, op - d + len)
+ op += len
+ } else for (const end = op + len; op < end; op++) out[op] = out[op - d]!
}
- while (bc < db) {
- bb |= (src[pos++] ?? 0) << bc
- bc += 8
- }
- e = dt[bb & dm]!
- n = e & 15
- if (!n) throw new Error('bad Huffman code')
- bb >>>= n
- bc -= n
- const di = e >> 4
- if (di >= 30) throw new Error('bad distance code')
- n = DIST_EXTRA[di]!
- while (bc < n) {
- bb |= (src[pos++] ?? 0) << bc
- bc += 8
- }
- const d = DIST_BASE[di]! + (bb & ((1 << n) - 1))
- bb >>>= n
- bc -= n
- if (d > op || op + len > out.length) throw new Error('bad match')
- if (d >= len) {
- out.copyWithin(op, op - d, op - d + len)
- op += len
- } else for (const end = op + len; op < end; op++) out[op] = out[op - d]!
+ if (!isEnd) break
+ this.lit = this.dist = null
}
+ save()
+ return this.isDone
}
- return op
+}
+
+// Inflates the zlib stream `src` into `out` (its size known); returns the
+// bytes written. Throws on a stream that is not one.
+export function inflate(src: Uint8Array, out: Uint8Array): number {
+ const z = new Inflater(src, out)
+ z.run(Infinity)
+ return z.op
}
// ---- Decode ------------------------------------------------------------------------
@@ -232,9 +274,9 @@ export function inflate(src: Uint8Array, out: Uint8Array): number {
const SIGNATURE = [137, 80, 78, 71, 13, 10, 26, 10]
const u32 = (b: Uint8Array, i: number) => ((b[i]! << 24) | (b[i + 1]! << 16) | (b[i + 2]! << 8) | b[i + 3]!) >>> 0
-// A PNG's pixels as RGBA. Throws on one that is not 8-bit RGBA or RGB, not
-// interlaced, or is broken.
-export function decodePng(png: Uint8Array): Rgba {
+// A PNG's size, its channels (4 RGBA, 3 RGB) and its IDAT data joined.
+// Throws on one that is not 8-bit RGBA or RGB, not interlaced, or is broken.
+export function pngParts(png: Uint8Array): { width: number; height: number; channels: number; z: Uint8Array } {
if (png.length < 33 || SIGNATURE.some((v, i) => png[i] !== v)) throw new Error('not a PNG')
let width = 0
let height = 0
@@ -255,28 +297,74 @@ export function decodePng(png: Uint8Array): Rgba {
i += 12 + len
}
if (!width || !height || !idat.length) throw new Error('no IHDR or IDAT')
- const z = new Uint8Array(idat.reduce((n, d) => n + d.length, 0))
- idat.reduce((at, d) => (z.set(d, at), at + d.length), 0)
+ return { width, height, channels, z: concat(idat) }
+}
+
+// A PNG's pixels as RGBA, at once. Throws as pngParts.
+export function decodePng(png: Uint8Array): Rgba {
+ const { width, height, channels, z } = pngParts(png)
const stride = width * channels
const filtered = new Uint8Array(height * (stride + 1))
if (inflate(z, filtered) !== filtered.length) throw new Error('short image data')
- const rows = unfilter(filtered, width, height, channels)
+ const rows = new Uint8Array(height * stride)
+ unfilterRows(filtered, rows, width, channels, 0, height)
+ if (channels === 4) return { width, height, data: rows }
+ const data = new Uint8Array(width * height * 4)
+ rgbaRows(rows, data, width, 0, height)
+ return { width, height, data }
+}
+
+// The same pixels as decodePng, in steps: a yield after each `step` bytes
+// inflated or unfiltered, so a caller can stop between them (pagecache.ts).
+export function* decodeSteps(png: Uint8Array, step = DECODE_STEP): Generator<undefined, Rgba, void> {
+ const { width, height, channels, z } = pngParts(png)
+ const stride = width * channels
+ const line = stride + 1
+ const filtered = new Uint8Array(height * line)
+ const rows = new Uint8Array(height * stride)
+ const inflater = new Inflater(z, filtered)
+ const batch = Math.max(1, Math.floor(step / line))
+ let y = 0
+ for (;;) {
+ const isEnd = inflater.run(inflater.op + step)
+ if (isEnd && inflater.op !== filtered.length) throw new Error('short image data')
+ // The rows inflated whole so far.
+ const ready = isEnd ? height : Math.floor(inflater.op / line)
+ while (y < ready) {
+ const y1 = Math.min(ready, y + batch)
+ unfilterRows(filtered, rows, width, channels, y, y1)
+ y = y1
+ yield
+ }
+ if (isEnd) break
+ yield
+ }
if (channels === 4) return { width, height, data: rows }
const data = new Uint8Array(width * height * 4)
- for (let p = 0, q = 0; p < rows.length; p += 3, q += 4) {
+ for (let y0 = 0; y0 < height; y0 += batch) {
+ rgbaRows(rows, data, width, y0, Math.min(height, y0 + batch))
+ yield
+ }
+ return { width, height, data }
+}
+// The bytes of one decode step: about a millisecond or less.
+export const DECODE_STEP = 256 * 1024
+
+// RGB rows y0 to y1 (exclusive) of `rows` as opaque RGBA in `data`.
+function rgbaRows(rows: Uint8Array, data: Uint8Array, width: number, y0: number, y1: number) {
+ for (let p = y0 * width * 3, q = y0 * width * 4, end = y1 * width * 3; p < end; p += 3, q += 4) {
data[q] = rows[p]!
data[q + 1] = rows[p + 1]!
data[q + 2] = rows[p + 2]!
data[q + 3] = 255
}
- return { width, height, data }
}
-// The scanlines' filters undone (PNG filter types 0 to 4).
-function unfilter(f: Uint8Array, width: number, height: number, bpp: number): Uint8Array {
+// The scanlines y0 to y1 (exclusive) of `f` with their filters undone (PNG
+// filter types 0 to 4) into `out`; the rows above y0 are done already.
+function unfilterRows(f: Uint8Array, out: Uint8Array, width: number, bpp: number, y0: number, y1: number) {
const stride = width * bpp
- const out = new Uint8Array(height * stride)
- for (let y = 0; y < height; y++) {
+ for (let y = y0; y < y1; y++) {
const type = f[y * (stride + 1)]!
const s = y * (stride + 1) + 1
const o = y * stride
@@ -310,7 +398,6 @@ function unfilter(f: Uint8Array, width: number, height: number, bpp: number): Ui
}
} else throw new Error(`bad filter type ${type}`)
}
- return out
}
// ---- Deflate pieces -------------------------------------------------------------------
diff --git a/hooks/lib/probe.ts b/hooks/lib/probe.ts
index 0f048e5..7fa6b3a 100644
--- a/hooks/lib/probe.ts
+++ b/hooks/lib/probe.ts
@@ -63,6 +63,9 @@ const inflight = new Map<string, Promise<PageWords | null>>()
const pageKey = (d: Drawn, page: number) => `${d.dir}#${page}`
+// The words of a page when they are probed already (no probe runs).
+export const knownWords = (d: Drawn, page: number): PageWords | undefined => probed.get(pageKey(d, page))
+
// 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).
diff --git a/hooks/lib/select.ts b/hooks/lib/select.ts
index e9eff3a..885d6b0 100644
--- a/hooks/lib/select.ts
+++ b/hooks/lib/select.ts
@@ -1,9 +1,9 @@
// Picture select: a mouse selection over the pictures of an answer, a plan
-// or a Markdown file Claude sent. Since Claude Code 2.1.305 its own
-// selection skips an Image's cells (no highlight, no text), so a Client
-// (hooks/sel.tsx) over each page takes the pointer and posts the selection;
-// the hooks module shows it on the page and copies its text on the
-// button's up. The highlight swaps the page's picture (blit.ts); the page's
+// or a Markdown file Claude sent. Claude Code's own selection copies an
+// Image's cells as kitty placeholders (2.1.305 and newer skip them), so a
+// Client (hooks/sel.tsx) over each page takes the pointer and posts the
+// selection; the hooks module shows it on the page and copies its text on
+// the button's up. The highlight swaps the page's picture (blit.ts); the page's
// layout never changes. The pure parts are here, with the selection now.
import type { EngineInterface } from 'claude-code'
@@ -169,9 +169,8 @@ export function textOfRuns(
return joinSegments(runs.map(run => ({ kind: 'image', lines: run.lines })), texts)
}
-// Whether Claude Code is a version whose selection skips pictures
-// (SELECT_SINCE or newer; a dev build by its release). Before it, its own
-// selection copies them, and a Client over a picture would take that away.
+// Whether Claude Code has what picture select uses (SELECT_SINCE or newer;
+// a dev build by its release): the Client, ui.message, ui.blit and ui.copy.
export function needsSelect(version: string): boolean {
const release = /^\d+\.\d+\.\d+/.exec(version.trim())?.[0]
return !!release && (compareVersions(release, SELECT_SINCE) ?? -1) >= 0
diff --git a/hooks/lib/settings.ts b/hooks/lib/settings.ts
index c77aa86..221ac9b 100644
--- a/hooks/lib/settings.ts
+++ b/hooks/lib/settings.ts
@@ -83,11 +83,6 @@ export const HOST_CHECK_MS = 2000
// many pages are kept in memory (a copy probes only the pages it reads).
export const CLIP_WAKE_MS = 300
export const PROBED_KEPT = 64
-// A copy of picture cells that the watcher sees waits this long for its shim's
-// ask (which waits 1.5 s at most) before the /iui grab hint; an ask keeps
-// its cells from the hint this long.
-export const HINT_WAIT_MS = 2000
-export const ASKED_MS = 5000
// 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.
@@ -122,10 +117,6 @@ export const gridText = (grid: boolean) => (grid ? 'on (each line of text on who
// Claude Code the mod supports (the Client, ui.message, ui.blit and ui.copy are there).
export const SELECT_SINCE = '2.1.298'
export const selectText = (on: boolean) => (on ? 'on (select and copy picture text with the mouse, fullscreen)' : 'off')
-// The copy shims (pbcopy, xclip, wl-copy) that ask the mod for the text of
-// picture cells (clipboard.ts). Off: no shims folder, no PATH change, no ask
-// FIFO, no answers. IUI_COPY_SHIM=1 turns them on for one session (tests too).
-export const USE_COPY_SHIM = false
export const PICTURES_KEPT = 64
// The file paths of the link rows under a picture: whether each one is a
// file, kept for this many paths (the oldest go).
diff --git a/hooks/lib/state.ts b/hooks/lib/state.ts
index b66fff6..5805602 100644
--- a/hooks/lib/state.ts
+++ b/hooks/lib/state.ts
@@ -10,7 +10,7 @@ import type { PlanVerdict } from './plan'
import type { Drawn } from './copy'
import type { GridMetrics } from './grid'
import type { Checked } from './updates'
-import type { ClipWay, ShimState } from './clipboard'
+import type { ClipWay } from './clipboard'
import type { PdfFacts, PixelBox } from './images'
import { DEFAULT_HEIGHT, DEFAULT_SIZE, DEFAULT_WIDTH, type Height, type Width } from './settings'
import { invalidate } from './api'
@@ -191,11 +191,6 @@ export const S = {
// Linux: how the clipboard is read and watched (clipboard.ts; null: not
// looked up, as on macOS and over ssh).
clipWay: null as ClipWay | null,
- // The clipboard shims (clipboard.ts; null: not set up), this process's
- // FIFO for their asks and its shims folder ('' when the shims are off).
- shims: null as ShimState | null,
- askFifo: '',
- shimDir: '',
// Streaming: model requests of the main loop in flight.
stepsLive: 0,
// The plan (plan.tsx): the main loop's running turn (`turn.start`), the
@@ -292,10 +287,9 @@ export const DRAWN_KEPT = 64
// 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 cells of the last
-// shim asks with their times (`asked`: such a copy gets no hint), 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`).
+// written (so a write is never read back as new), the last text with
+// placeholders with its row (`rawRow`, when known) and how it was read (for
+// dump), and the order of the drawings (`seq`).
export const clip = {
count: null as number | null,
none: false,
@@ -303,7 +297,6 @@ export const clip = {
again: false,
seen: '',
wrote: '',
- asked: [] as { text: string; at: number }[],
raw: '',
rawRow: undefined as string | undefined,
seq: 0,
diff --git a/hooks/register.tsx b/hooks/register.tsx
index fa0ec1d..a4df67a 100644
--- a/hooks/register.tsx
+++ b/hooks/register.tsx
@@ -21,8 +21,8 @@ import { atom, read, update } from 'claude-code'
import type { EngineInterface, Register, RenderElement, RenderSurface, RenderViewport } from 'claude-code'
import {
- ASKED_MS, DEFAULT_THEME, gridText, heightText, IMAGE_MAX_COLUMNS, MARGIN_TOP, MAX_HEIGHT, MAX_SIZE, MAX_WIDTH, MIN_HEIGHT, MIN_SIZE, MIN_WIDTH, RESULTS_KEPT, TYPST_PROMPT,
- HINT_WAIT_MS, selectText, typstHintOf, widthText,
+ DEFAULT_THEME, gridText, heightText, IMAGE_MAX_COLUMNS, MARGIN_TOP, MAX_HEIGHT, MAX_WIDTH, MIN_HEIGHT, MIN_WIDTH, RESULTS_KEPT, TYPST_PROMPT,
+ SELECT_SINCE, selectText, typstHintOf, widthText,
} from './lib/settings'
import { clip, drawnAnswers, editedPlans, keep, queue, refresh, running, S, subagentPlans, writesLive, type Env, type Job, type Result } from './lib/state'
import { beginEpoch } from './lib/epoch'
@@ -33,21 +33,22 @@ import { runSetup } from './lib/setup'
import { pollHost, PROBE_RUNS, probeOsc11, showMode, USE_OSC11, watchHost } from './lib/host'
import { measureFonts } from './lib/typst'
import { drawPages, linksFor, type ShownLink } from './lib/draw'
-import { picked, postOf, redrawSelection, runsOf, selectedRows, selectionAfter, selectTrace, textOfRuns, topsOf, type SelectPost, type Selection } from './lib/select'
-import { blits, warmPage } from './lib/blit'
+import { needsSelect, picked, postOf, redrawSelection, runsOf, selectedRows, selectionAfter, selectTrace, textOfRuns, topsOf, type SelectPost, type Selection } from './lib/select'
+import { blits, selectColor } from './lib/blit'
+import { needFrames, notePages } from './lib/pagecache'
import { traceDebug } from './lib/log'
import { finalizeAll } from './lib/stream'
-import { noteDrawn, noteDrawnAgain, noteOnScreen, wordsOf, type PageWords } from './lib/probe'
+import { knownWords, noteDrawn, noteDrawnAgain, noteOnScreen, wordsOf, type PageWords } from './lib/probe'
import { codePointsOf, decodeSelection, hasPlaceholders, joinSegments, pageTopsOf, pickPages, textOfRun, type Drawn, type Pick, type Segment } from './lib/copy'
import { pagesOf, type Drawing } from './lib/answer'
-import { answerAsk, askGaveUp, askRequest, asking, autoCopyText, clipboardNow, clipWatchArgs, clipWayReady, endAsks, listenAsks } from './lib/clipboard'
+import { clipboardNow, clipWatchArgs, clipWayReady, hintText } from './lib/clipboard'
import { setUp } from './lib/env'
import { frameFor, noteView, stopWatch, watchFrame, watchState } from './lib/frame'
import { roomColumns } from './lib/terminal'
import { onScreenOf, pastedImagePath, pastedNumbers, sentFiles } from './lib/images'
import { drawPageField, pasteDir, pdfPagesOf, rowsAfter, sentOf, shownOf, underRow, type Shown, type Under } from './lib/pictures'
import { checkUpdates, loadUpdates, updateLine, updateNotice, type UpdateState } from './lib/updates'
-import { clockAfter, clockNow, fsWrite, sessionSurfaces, storeSet, uiCopy, uiLog, uiResolve, uiSelection, uiToast } from './lib/api'
+import { clockNow, fsWrite, sessionSurfaces, storeSet, uiCopy, uiLog, uiResolve, uiSelection, uiToast } from './lib/api'
import {
currentPlan, decidePlan, decisionOf, drawAskLine, drawPlanResult, drawPlanUse, isPlanQuestion, planFileOf, planInputOf, planOf,
planShownOf, scheduleClear, type PlanVerdict,
@@ -88,10 +89,7 @@ export { nextJob } from './lib/stream'
export * from './lib/images'
export { rowsAfter, type Under } from './lib/pictures'
export * from './lib/copy'
-export {
- autoCopyText, CLIP_TOOLS, clipToolsOf, clipWayOf, FIND_SH, GTK_READ_PY, GTK_WATCH_PY, pathWith, SHIM_SETUP, SHIM_TOOLS, shimFindOf, shimText,
- shQuote, WL_WATCH_SH, X11_WATCH_SH, type ClipTool, type ClipWay, type ShimState,
-} from './lib/clipboard'
+export { CLIP_TOOLS, clipToolsOf, clipWayOf, FIND_SH, GTK_READ_PY, GTK_WATCH_PY, hintText, WL_WATCH_SH, X11_WATCH_SH, type ClipTool, type ClipWay } from './lib/clipboard'
export {
agoText, checkedOf, compareVersions, isDue, isNewer, parseVersion, shouldTell, toldOf, UPDATE_EVERY_MS, UPDATE_FETCH_MS, UPDATE_STEPS, UPDATE_TOAST_MS,
UPDATE_URL, updateLine, updateNotice, updateToast, versionOf,
@@ -128,7 +126,7 @@ async function pictureEnv($: EngineInterface, e: { viewport?: RenderViewport }):
}
// Once a session, where pictures draw on the main screen: fullscreen gives
-// the automatic copy (there Claude Code copies a selection itself).
+// picture select (a mouse drag over a picture copies its text).
function tellFullscreen($: EngineInterface) {
if (S.fullscreenTold) return
S.fullscreenTold = true
@@ -222,27 +220,34 @@ 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. Claude Code writes it with pbcopy (wl-copy,
-// xclip or xsel), whose shim asks this process for the text of the cells
-// (answerCopy; lib/clipboard.ts) and writes that text in their place (see
-// lib/copy.ts; the drawn pages and the words of a page are in lib/probe.ts).
-// The watcher (lib/frame.ts) prints a line when the clipboard changes; at a
-// change the clipboard is read once (pbpaste, wl-paste, xclip, xsel or GTK),
-// and picture cells that no shim asked for (the terminal's own copy on the
-// main screen, another session's) get the /iui grab hint. No timer reads the
-// clipboard or the selection.
+// Picture select (below) copies the text of a drag over the pictures. A
+// copy that still puts kitty placeholder cells on the clipboard (the main
+// screen's, a native drag over text and pictures) is seen by the watcher
+// (lib/frame.ts), which prints a line when the clipboard changes: the
+// clipboard is read once (pbpaste, wl-paste, xclip, xsel or GTK), and cells
+// that fit a page drawn here get a toast that names /iui grab, which reads
+// them (see lib/copy.ts; the drawn pages and the words of a page are in
+// lib/probe.ts). The clipboard is never written but by a copy the person
+// asked for. No timer reads the clipboard or the selection.
-// Notes a drawing for a copy (noteDrawn, noteDrawnAgain) and turns on the
-// ask reader and the watcher's clipboard part; a failure never stops the row
-// from drawing.
-function noteCopy($: EngineInterface, note: () => void) {
+// Notes a drawing for a copy (noteDrawn, noteDrawnAgain), turns on the
+// watcher's clipboard part and queues its pages for picture select's
+// cache; a failure never stops the row from drawing.
+function noteCopy($: EngineInterface, id: string, note: () => void) {
try {
note()
watchClipboard($)
+ queueSelect($, id)
} catch {}
}
+// A drawing whose pages take picture select (drawn with its Client): its
+// pages on screen to the cache (lib/pagecache.ts), the others out of it.
+function queueSelect($: EngineInterface, id: string) {
+ const d = drawnAnswers.get(id)
+ if (d && S.select && S.isFullscreen !== false && !picked.isBroken && blits.sites.has(id)) notePages($, d, selectColor(S.theme))
+}
+
type CopyRead = { text: string; segments: Segment[]; picks: Pick[]; runs: number; resolved: number }
// The text for a clipboard (or selection) text with placeholders. A page
@@ -271,57 +276,10 @@ async function readCopy($: EngineInterface, raw: string, requestId?: string): Pr
return read
}
-// A shim's ask (request `id`, lib/clipboard.ts): the text of its picture
-// cells, the selection's row when it is that copy. Each ask gets an answer:
-// '' when there is no text (the shim then keeps its own bytes). A shim that
-// gave up (1.5 s) wrote the cells: the clipboard is not written then (another
-// session can copy the same cells), only a toast names /iui grab.
-async function answerCopy($: EngineInterface, id: string) {
- let text: string | null = null
- let answered = false
- try {
- const raw = await askRequest($, id)
- if (raw !== null) {
- const now = await clockNow($).catch(() => Date.now())
- clip.asked = [{ text: raw, at: now }, ...clip.asked.filter(a => now - a.at < ASKED_MS)].slice(0, 8)
- text = await askedText($, raw)
- }
- } finally {
- answered = await answerAsk($, id, text ?? '')
- }
- if (answered) {
- if (text !== null) uiToast($, `Intelligent UI: copied ${text.length} chars of text`)
- return
- }
- await askGaveUp($, id)
- if (text !== null) uiToast($, 'Intelligent UI: the picture text was not ready in time; /iui grab copies it')
-}
-
-// The text of the cells in `raw`; null when they are not read (one toast).
-async function askedText($: EngineInterface, raw: string): Promise<string | null> {
- if (!hasPlaceholders(raw) || !drawnAnswers.size) return null
- const selected = await uiSelection($).catch(() => undefined)
- clip.raw = raw
- clip.rawRow = selected && sameCopy(selected.text, raw) ? selected.requestId : undefined
- const read = await readCopy($, raw, clip.rawRow)
- if (!read.resolved) {
- uiToast($, 'Intelligent UI: could not read the selected picture (/iui dump says why)')
- return null
- }
- // The clipboard change of this text is not read again.
- clip.wrote = read.text
- clip.seen = read.text
- return read.text
-}
-
-// A selection and a clipboard text are the same copy (a copy can end in
-// 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+$/, '')
-
// A watcher line `clip <count>` (null: `clip none`, no PerlObjCBridge or
-// the Linux notifier ended: 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).
+// the Linux notifier ended: the /iui grab hint 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
@@ -331,29 +289,20 @@ function clipChanged($: EngineInterface, count: number | null, first: boolean) {
if (!first) void readClipboard($).catch(() => undefined)
}
-// Cells that a shim of this process asked for lately.
-async function askedFor($: EngineInterface, text: string): Promise<boolean> {
- const now = await clockNow($).catch(() => Date.now())
- return clip.asked.some(a => now - a.at < ASKED_MS && sameCopy(a.text, text))
-}
-
-// Picture cells that no shim of this process asked for (the terminal's own
-// copy on the main screen, another session's): never written. Cells that
-// fit a page drawn here get one toast that names /iui grab.
+// Picture cells on the clipboard (a native copy: their session is not
+// known), never written. Cells that fit a page drawn here get one toast that
+// names /iui grab.
function hintGrab($: EngineInterface, text: string) {
- clip.seen = text
if (!pickPages(decodeSelection(text), [...drawnAnswers.values()]).some(Boolean)) return
clip.raw = text
clip.rawRow = undefined
+ if (S.debug) traceDebug($, `select: native copy seen: ${decodeSelection(text).filter(seg => seg.kind === 'image').length} picture run(s) on the clipboard`)
uiToast($, 'Intelligent UI: picture cells copied; /iui grab puts their text on the clipboard')
}
-// The clipboard changed: one read (clipboardNow). Picture cells that a shim
-// of this process asked for are its own copy (answerCopy). Out of the main
-// screen, the terminal's OSC 52 write of a copy comes before its shim asks:
-// the cells wait HINT_WAIT_MS for the ask, then get the hint while the
-// clipboard still has them. A clipboard with no placeholders, and our own
-// write, are never touched. A change while a read runs reads once more after it.
+// The clipboard changed: one read (clipboardNow). A clipboard with no
+// placeholders, and our own write, are never touched. A change while a
+// read runs reads once more after it.
async function readClipboard($: EngineInterface) {
if (clip.busy) {
clip.again = true
@@ -365,21 +314,8 @@ async function readClipboard($: EngineInterface) {
clip.again = false
const text = await clipboardNow($)
if (text === null || text === clip.seen) continue
- if (text === clip.wrote || !hasPlaceholders(text) || (await askedFor($, text))) {
- clip.seen = text
- continue
- }
- if (S.isFullscreen !== false) {
- await new Promise<void>(done => clockAfter($, HINT_WAIT_MS, done))
- if (await askedFor($, text)) {
- clip.seen = text
- continue
- }
- if ((await clipboardNow($)) !== text) {
- clip.again = true
- continue
- }
- }
+ clip.seen = text
+ if (text === clip.wrote || !hasPlaceholders(text)) continue
hintGrab($, text)
} while (clip.again)
} finally {
@@ -394,11 +330,9 @@ async function readClipboard($: EngineInterface) {
// 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 (or a notifier that ended) the child goes on as it is
-// (size only). The ask reader (lib/clipboard.ts) starts with the first picture.
+// (size only).
function watchClipboard($: EngineInterface) {
- if (!S.env || S.isRemote || !drawnAnswers.size) return
- listenAsks($, id => void answerCopy($, id).catch(() => undefined))
- if (clip.none || clipWatchArgs(S.env.isMac) === null) return
+ if (!S.env || S.isRemote || !drawnAnswers.size || clip.none || clipWatchArgs(S.env.isMac) === null) return
watchFrame($, (count, first) => clipChanged($, count, first))
}
@@ -408,11 +342,12 @@ function stopClipboard($: EngineInterface) {
if (watchState()?.clip && !clip.none) watchFrame($, null)
}
-// The automatic copy now, for /iui details and dump.
-function autoCopyOf(isOn: boolean): string {
- return autoCopyText({
- isMac: !!S.env?.isMac, hostOs: S.hostOs, isRemote: S.isRemote, isOn, isFullscreen: S.isFullscreen, none: clip.none, drawn: drawnAnswers.size > 0,
- asking: asking(), way: S.clipWay, shims: S.shims,
+// The /iui grab hint now, for /iui details and dump.
+function hintOf(isOn: boolean): string {
+ const now = watchState()
+ return hintText({
+ isMac: !!S.env?.isMac, hostOs: S.hostOs, isRemote: S.isRemote, isOn, none: clip.none, drawn: drawnAnswers.size > 0,
+ running: !!now?.clip && !now.ended, way: S.clipWay,
})
}
@@ -466,8 +401,8 @@ function screenText(pick: { id: string; page: number }): string {
// UI is on.
async function dump($: EngineInterface, on: boolean): Promise<string> {
await clipWayReady()
- 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 hint = hintOf(on)
+ if (!clip.raw) return `Intelligent UI: no clipboard text with picture cells seen yet (grab hint ${hint}; ${drawnAnswers.size} pictures drawn).`
const read = await readCopy($, clip.raw, clip.rawRow)
const runs = read.segments
.map((seg, i) => {
@@ -483,7 +418,7 @@ async function dump($: EngineInterface, on: boolean): Promise<string> {
await fsWrite($, `${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; auto copy ${auto}):`,
+ `Intelligent UI: last clipboard with picture cells (${Array.from(clip.raw).length} code points; grab hint ${hint}):`,
codePointsOf(clip.raw, 40),
runs,
`Read as ${read.text.length} chars: ${JSON.stringify(read.text.slice(0, 200))}`,
@@ -494,12 +429,13 @@ async function dump($: EngineInterface, on: boolean): Promise<string> {
// ---- Picture select -------------------------------------------------------
// The Client over each page (hooks/sel.tsx) posts the selection; the pages
// show it (a blit of each page's picture, lib/blit.ts) and its text is
-// copied on the button's up, read as a shim's copy is (wordsOf, textOfRun).
+// copied on the button's up, read as a copy of its cells is (wordsOf, textOfRun).
// See lib/select.ts.
// A Client's post: the selection after it, shown (once a frame at most, the
-// newest selection). A down decodes its page now, for the drag's frames,
-// and lets a page whose blit was refused try again.
+// newest selection). A down puts its page first in the cache (lib/pagecache.ts)
+// and probes its words if they are not there, for the drag's frames and the
+// copy at the up, and lets a page whose blit was refused try again.
function onSelect($: EngineInterface, post: SelectPost, surface: RenderSurface) {
if (post.seq <= picked.seq) return
picked.seq = post.seq
@@ -507,28 +443,40 @@ function onSelect($: EngineInterface, post: SelectPost, surface: RenderSurface)
const was = picked.now
picked.now = d ? selectionAfter(post, topsOf(d.pages)) : null
if (S.debug) traceDebug($, selectTrace(post, d, picked.now))
+ const page = d?.pages[post.page]
if (post.phase === 'down') {
blits.refused.clear()
- warmPage($, d?.pages[post.page])
+ if (d && page && S.env) {
+ void needFrames($, page, selectColor(S.theme), { id: d.id, index: post.page, seq: d.seq }).catch(() => undefined)
+ void wordsOf($, d, post.page).catch(() => undefined)
+ }
}
if (was || picked.now) redrawSelection($)
- // The copy waits for the page's words (a probe): the next posts do not.
+ // The copy waits for the page's words when they are not there: the next posts do not.
if (post.phase === 'up' && d && picked.now) void copySelection($, d, picked.now, surface).catch(() => undefined)
}
// The text of a selection's cells, page by page, as a copy of those cells
// reads it (textOfRuns); null when a page's words can not be read.
-async function selectionText($: EngineInterface, d: Drawn & { job?: Job }, sel: Omit<Selection, 'id' | 'isUp'>): Promise<string | null> {
+// `probed`: the pages whose words were not there yet (a probe ran or ran on).
+async function selectionText($: EngineInterface, d: Drawn & { job?: Job }, sel: Omit<Selection, 'id' | 'isUp'>, probed: number[] = []): Promise<string | null> {
const runs = runsOf(selectedRows(sel, d.pages))
const words = new Map<number, PageWords | null>()
- for (const run of runs) words.set(run.page, await wordsOf($, d, run.page))
+ for (const run of runs) {
+ const known = knownWords(d, run.page)
+ if (!known) probed.push(run.page)
+ words.set(run.page, known ?? (await wordsOf($, d, run.page)))
+ }
return textOfRuns(runs, page => words.get(page) ?? null, d.pages)
}
// The button came up: the selection's text on the clipboard, with the
// toast of a copy. No text under it: nothing is copied.
async function copySelection($: EngineInterface, d: Drawn & { job?: Job }, sel: Selection, surface: RenderSurface) {
- const text = await selectionText($, d, sel)
+ const t = performance.now()
+ const probed: number[] = []
+ const text = await selectionText($, d, sel, probed)
+ const read = performance.now() - t
if (text === null) {
uiToast($, 'Intelligent UI: could not read the selected picture')
return
@@ -539,6 +487,27 @@ async function copySelection($: EngineInterface, d: Drawn & { job?: Job }, sel:
clip.seen = text
const copied = await uiCopy($, { text, surface })
uiToast($, copied.isCopied ? `Intelligent UI: copied ${text.length} chars of text` : `Intelligent UI: the copy failed: ${copied.reason}`)
+ if (S.debug) void traceCopy($, text, performance.now() - t, read, probed)
+}
+
+// The trace of a copy: the time from the up to the copy, whether the words
+// were there, and whether Claude Code has a selection of its own with
+// picture cells (a native selection: it copies them itself).
+async function traceCopy($: EngineInterface, text: string, total: number, read: number, probed: readonly number[]) {
+ const native = await uiSelection($).catch(() => undefined)
+ const seen = native && hasPlaceholders(native.text) ? `native selection seen (${Array.from(native.text).length} code points with picture cells)` : 'no native selection'
+ const words = probed.length ? `words probed for page ${probed.join(', ')}` : 'words cached'
+ traceDebug($, `select: copy ${text.length} chars ${Math.round(total)}ms after the up (text ${Math.round(read)}ms, ${words}); ${seen}`)
+}
+
+// Picture select now, for /iui details: on, or why it is off.
+function selectState(): string {
+ if (!S.select) return 'off (/iui select off)'
+ if (picked.isBroken) return 'off until a reload (its Client failed: see the debug log)'
+ if (!needsSelect(S.engine)) return `off (Claude Code ${S.engine || 'of an unknown version'}; it needs ${SELECT_SINCE} or newer)`
+ if (S.env && (!S.env.canDraw || S.env.inline)) return 'off (no pictures drawn from files here)'
+ if (S.isFullscreen === false) return 'off on the main screen (use /tui fullscreen, or /iui grab)'
+ return S.isFullscreen === null ? 'on in fullscreen (the screen is not known yet)' : 'on'
}
// No selection drawn (a new turn, Intelligent UI or select off).
@@ -558,14 +527,11 @@ export const register: Register = on => {
})
// A /clear or a resume: the process goes on, with no clipboard reads until
- // the next picture. Any other end (/exit): the watcher and the ask reader
- // stop, no new child starts, and the FIFO and the request files go.
+ // the next picture. Any other end (/exit): the watcher stops, and no new
+ // child starts.
on('session.end', async ($, e, next) => {
if (e.reason === 'clear' || e.reason === 'resume') stopClipboard($)
- else {
- stopWatch()
- await endAsks($)
- }
+ else stopWatch()
return next(e)
}).catch(($, e, next) => next(e))
@@ -574,6 +540,7 @@ export const register: Register = on => {
// hold no placeholders and pass on as they are.
on('ui.copy', async ($, e, next) => {
if (!hasPlaceholders(e.text) || !drawnAnswers.size) return next(e)
+ if (S.debug) traceDebug($, 'select: native copy seen: a $.ui.copy with picture cells (read as their text)')
const selected = await uiSelection($).catch(() => undefined)
clip.raw = e.text
clip.rawRow = selected?.text === e.text ? selected.requestId : undefined
@@ -738,7 +705,7 @@ export const register: Register = on => {
? `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'
await clipWayReady()
- const auto = `Auto copy: ${autoCopyOf(state === 'on')}`
+ const auto = `Picture select: ${selectState()}\n/iui grab hint: ${hintOf(state === 'on')}`
const updates = `Update checks: ${updateLine(await updateState($))}`
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)}, row grid ${S.grid ? 'on' : 'off'}, picture select ${S.select ? 'on' : 'off'}, ${font}. ${typst}; ${terminal}.\n${auto}\n${updates}` }
}
@@ -842,7 +809,7 @@ export const register: Register = on => {
// Its pages are under the top margin (drawPages) with its link rows
// under them; the rows on screen at each draw, a memo hit too.
if (kept) {
- noteCopy($, () => {
+ noteCopy($, e.requestId, () => {
noteDrawnAgain(e.requestId, roomColumns(e.viewport), { top: MARGIN_TOP, after: kept.links.length })
noteOnScreen(e.requestId, e.props.onScreen)
})
@@ -853,7 +820,7 @@ export const register: Register = on => {
const links = await linksFor($, e.props.text, ready.env.cwd)
const tree = drawPages($, e, drawing.result, drawing.bytes, { bullet, links, id: e.requestId })
const { result } = drawing
- noteCopy($, () => {
+ noteCopy($, e.requestId, () => {
noteDrawn(e.requestId, result, roomColumns(e.viewport), { top: MARGIN_TOP, after: links.length })
noteOnScreen(e.requestId, e.props.onScreen)
})
@@ -892,7 +859,7 @@ export const register: Register = on => {
under = kept
kept.forEach((u, i) => {
if (!('drawing' in u)) return
- noteCopy($, () => {
+ noteCopy($, u.id, () => {
noteDrawnAgain(u.id, room, { after: rowsAfter(kept, i, room) })
noteOnScreen(u.id, e.props.onScreen)
})
@@ -905,7 +872,7 @@ export const register: Register = on => {
drawn.forEach((u, i) => {
if (!('drawing' in u) || u.drawing.kind !== 'pages') return
const { result } = u.drawing
- noteCopy($, () => {
+ noteCopy($, u.id, () => {
noteDrawn(u.id, result, room, { after: rowsAfter(drawn, i, room) })
noteOnScreen(u.id, e.props.onScreen)
})
@@ -993,7 +960,7 @@ export const register: Register = on => {
if (drawing.kind === 'pages') {
const { result } = drawing
const id = `plan:${e.props.tool_use_id}`
- noteCopy($, () => {
+ noteCopy($, id, () => {
noteDrawn(id, result, roomColumns(e.viewport), { after: links.length })
noteOnScreen(id, e.props.onScreen)
})
diff --git a/tests/blit.test.ts b/tests/blit.test.ts
index 816d86c..209cf4e 100644
--- a/tests/blit.test.ts
+++ b/tests/blit.test.ts
@@ -1,7 +1,10 @@
import { expect, test } from 'claude-code/testing'
import { bandOf, edgesOf, endFold, foldNew, frameOf, framesOf, over, pokeFold, rgbOf, selectColor, sigOf, startFold } from '../hooks/lib/blit'
-import { adler32, adlerJoin, concat, crc32, decodePng, deflatePiece, fromBase64, headOf, inflate, tailOf, type Rgba } from '../hooks/lib/png'
+import { framesSteps } from '../hooks/lib/frames'
+import {
+ adler32, adlerJoin, chunk, concat, crc32, DECODE_STEP, decodePng, decodeSteps, deflatePiece, fromBase64, headOf, inflate, Inflater, pngParts, tailOf, type Rgba,
+} from '../hooks/lib/png'
// ---- PNG ---------------------------------------------------------------------------
@@ -26,6 +29,7 @@ const FIXTURE = [
'rdpYwg/Q76KbLeEfQ/GorH+e/u6v/Yfxp39WO+/i/KnT1vncz3VAAAAABJRU5ErkJggg==',
].join('')
const pixelOf = (x: number, y: number) => [(x * 7 + y * 13) & 255, (x * x + y) & 255, ((x ^ y) * 5) & 255, (x * 29 + y * 3) & 255]
+const toHex = (b: Uint8Array) => Array.from(b, v => v.toString(16).padStart(2, '0')).join('')
const imageOf = (width: number, height: number, at: (x: number, y: number) => number[]): Rgba => {
const data = new Uint8Array(width * height * 4)
for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) data.set(at(x, y), (y * width + x) * 4)
@@ -68,6 +72,114 @@ test('deflate pieces join into one stream: each alone, ended on a byte, inflated
expect([...out]).toEqual([...concat(raws)])
})
+// A PNG of `channels` (3: RGB, 4: RGBA) pixels, row y with filter y % 5,
+// in zlib stored blocks of `block` bytes, in two IDAT chunks.
+function storedPng(width: number, height: number, channels: number, at: (x: number, y: number) => number[], block: number): Uint8Array {
+ const stride = width * channels
+ const px = new Uint8Array(height * stride)
+ for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) px.set(at(x, y).slice(0, channels), y * stride + x * channels)
+ const raw = new Uint8Array(height * (stride + 1))
+ for (let y = 0; y < height; y++) {
+ const f = y % 5
+ raw[y * (stride + 1)] = f
+ for (let i = 0; i < stride; i++) {
+ const o = y * stride + i
+ const [a, b, c] = [i >= channels ? px[o - channels]! : 0, y ? px[o - stride]! : 0, y && i >= channels ? px[o - stride - channels]! : 0]
+ const [pa, pb, pc] = [Math.abs(b - c), Math.abs(a - c), Math.abs(a + b - 2 * c)]
+ const pred = [0, a, b, (a + b) >> 1, pa <= pb && pa <= pc ? a : pb <= pc ? b : c][f]!
+ raw[y * (stride + 1) + 1 + i] = (px[o]! - pred) & 255
+ }
+ }
+ const parts = [Uint8Array.of(0x78, 0x01)]
+ for (let i = 0; i < raw.length; i += block) {
+ const n = Math.min(block, raw.length - i)
+ parts.push(Uint8Array.of(i + n >= raw.length ? 1 : 0, n & 255, n >> 8, ~n & 255, (~n >> 8) & 255), raw.subarray(i, i + n))
+ }
+ const a = adler32(raw)
+ parts.push(Uint8Array.of(a >>> 24, (a >>> 16) & 255, (a >>> 8) & 255, a & 255))
+ const z = concat(parts)
+ const ihdr = Uint8Array.of(0, 0, 0, width, 0, 0, 0, height, 8, channels === 4 ? 6 : 2, 0, 0, 0)
+ const sig = Uint8Array.of(137, 80, 78, 71, 13, 10, 26, 10)
+ return concat([sig, chunk('IHDR', ihdr), chunk('IDAT', z.subarray(0, 40)), chunk('IDAT', z.subarray(40)), chunk('IEND', new Uint8Array(0))])
+}
+
+// A 50 x 12 RGBA PNG of one piece (fixed Huffman blocks), as frames are.
+const FIXED_PNG = (() => {
+ const line = 50 * 4 + 1
+ const raw = new Uint8Array(12 * line)
+ for (let y = 0; y < 12; y++) for (let x = 0; x < 50; x++) raw.set(pixelOf(x >> 2, y), y * line + 1 + x * 4)
+ const piece = deflatePiece(raw, 4, line)
+ return concat([headOf(50, 12), chunk('IDAT', piece.bytes), tailOf([piece])])
+})()
+
+const drain = <T>(steps: Generator<undefined, T, void>): T => {
+ for (;;) {
+ const got = steps.next()
+ if (got.done) return got.value
+ }
+}
+
+test('a decode in steps gives the pixels of a decode at once, at any step (dynamic, fixed and stored blocks; RGBA and RGB)', () => {
+ const pngs = [fromBase64(FIXTURE), FIXED_PNG, storedPng(40, 12, 3, pixelOf, 100), storedPng(33, 9, 4, pixelOf, 7)]
+ expect([...decodePng(pngs[2]!).data]).toEqual([...imageOf(40, 12, (x, y) => [...pixelOf(x, y).slice(0, 3), 255]).data])
+ expect([...decodePng(pngs[3]!).data]).toEqual([...imageOf(33, 9, pixelOf).data])
+ for (const png of pngs) {
+ const one = decodePng(png)
+ for (const step of [1, 13, 256, 5000, DECODE_STEP]) {
+ const got = drain(decodeSteps(png, step))
+ expect([got.width, got.height]).toEqual([one.width, one.height])
+ expect(toHex(got.data)).toBe(toHex(one.data))
+ }
+ }
+ // The inflate goes on from where it stopped, whatever the limits.
+ for (const png of pngs) {
+ const { z, width, height, channels } = pngParts(png)
+ const once = new Uint8Array(height * (width * channels + 1))
+ expect(inflate(z, once)).toBe(once.length)
+ for (const limit of [1, 3, 97]) {
+ const z2 = new Inflater(z, new Uint8Array(once.length))
+ let runs = 0
+ while (!z2.run(z2.op + limit)) runs++
+ expect(runs).toBeGreaterThan(0)
+ expect(toHex(z2.out)).toBe(toHex(once))
+ }
+ }
+ // A stream cut short: the steps say so, as the decode at once does.
+ const cut = storedPng(40, 12, 3, pixelOf, 100)
+ const short = concat([cut.subarray(0, 33), chunk('IDAT', pngParts(cut).z.subarray(0, 300)), chunk('IEND', new Uint8Array(0))])
+ expect(() => decodePng(short)).toThrow()
+ expect(() => drain(decodeSteps(short, 64))).toThrow()
+})
+
+test("a page's frames in steps: ready with its plain rows, then its tinted rows; the same frames as made at once", () => {
+ const box = { columns: 10, rows: 4 }
+ for (const png of [fromBase64(FIXTURE), FIXED_PNG]) {
+ const one = framesOf(decodePng(png), box, COLOR)
+ const steps = framesSteps(png, box, COLOR)
+ let ready: ReturnType<typeof framesOf> | undefined
+ let got: ReturnType<typeof framesOf> | undefined
+ for (;;) {
+ const s = steps.next()
+ if (s.done) {
+ got = s.value
+ break
+ }
+ if (s.value && !ready) {
+ ready = s.value
+ // Ready: the plain rows made, no tinted row yet.
+ expect(ready.plain.length).toBe(4)
+ expect(ready.tint.filter(Boolean).length).toBe(0)
+ }
+ }
+ expect(got).toBe(ready)
+ expect(got!.plain.map(p => toHex(p.chunk))).toEqual(one.plain.map(p => toHex(p.chunk)))
+ // Done: each row's tinted piece, as a whole row selected makes it.
+ expect(got!.tint.filter(Boolean).length).toBe(4)
+ const rows = [{ row: 0, x0: 3, x1: 9 }, { row: 1, x0: 0, x1: 9 }, { row: 2, x0: 0, x1: 9 }, { row: 3, x0: 0, x1: 4 }]
+ expect(toHex(frameOf(got!, rows))).toBe(toHex(frameOf(one, rows)))
+ }
+})
+
// ---- Cells to pixels -------------------------------------------------------------
test('cell edges: whole pixels a cell are exact; any other ratio tiles the picture with no gap or overlap', () => {
diff --git a/tests/cache-sh-test.sh b/tests/cache-sh-test.sh
new file mode 100644
index 0000000..f86261b
--- /dev/null
+++ b/tests/cache-sh-test.sh
@@ -0,0 +1,44 @@
+#!/bin/sh
+# Runs the cache sweep (CACHE_SH in hooks/lib/env.ts) in sh, dash and bash:
+# a cache folder that is a link is never used or changed; in a cache folder
+# of this user, key folders of 2 days go and pkg-cache stays.
+# Usage: sh tests/cache-sh-test.sh (exit 0 when all pass)
+set -u
+here=$(cd "$(dirname "$0")/.." && pwd)
+tmp=$(mktemp -d "${TMPDIR:-/tmp}/iui-cache-test.XXXXXX")
+trap 'rm -rf "$tmp"' EXIT
+pass=0
+fail=0
+ok() { pass=$((pass + 1)); }
+bad() { fail=$((fail + 1)); echo "FAIL: $*"; }
+
+# The TypeScript text as sh: ${DESIGNS_KEPT_DAYS} as 30, the escapes undone.
+cache_sh=$(perl -ne 'if (/^export const CACHE_SH = `(.*)`$/) { $_ = $1; s/(?<!\\)\$\{DESIGNS_KEPT_DAYS\}/30/g; s/\\\$/\$/g; s/\\\\/\\/g; print }' "$here/hooks/lib/env.ts")
+[ -n "$cache_sh" ] && ok || bad "CACHE_SH: not found in env.ts"
+uid=$(id -u)
+shells=
+for s in sh dash bash; do command -v "$s" >/dev/null 2>&1 && shells="$shells $s"; done
+for s in $shells; do
+ [ "$s" = bash ] && s='bash --posix'
+ k=$(echo "$s" | tr -d ' -')
+ # A link as the cache folder (to a folder of the victim): nothing there changes.
+ td=$tmp/td-$k; v=$tmp/victim-$k
+ mkdir -p "$td" "$v/old"; chmod 755 "$v"
+ touch -t 202001010000 "$v/old"
+ ln -s "$v" "$td/cc-intelligent-ui-$uid"
+ out=$(TMPDIR=$td XDG_CACHE_HOME=$tmp/xdg-$k $s -c "$cache_sh")
+ [ -z "$(echo "$out" | sed -n 1p)" ] && ok || bad "$s CACHE_SH: a linked cache folder was used ($out)"
+ [ "$(echo "$out" | sed -n 2p)" = "$(uname -s)" ] && ok || bad "$s CACHE_SH: no OS name for a linked cache folder ($out)"
+ [ -d "$v/old" ] && case $(ls -ld "$v") in drwxr-xr-x*) true ;; *) false ;; esac && ok || bad "$s CACHE_SH: the link target changed"
+ # A cache folder of this user: old key folders go, pkg-cache and new ones stay.
+ td=$tmp/te-$k; d=$td/cc-intelligent-ui-$uid
+ mkdir -p "$d/old" "$d/new" "$d/pkg-cache"
+ touch -t 202001010000 "$d/old" "$d/pkg-cache"
+ out=$(TMPDIR=$td XDG_CACHE_HOME=$tmp/xdg-$k $s -c "$cache_sh")
+ [ "$(echo "$out" | sed -n 1p)" = "$d" ] && ok || bad "$s CACHE_SH: not the cache folder ($out)"
+ [ ! -e "$d/old" ] && [ -d "$d/new" ] && [ -d "$d/pkg-cache" ] && ok || bad "$s CACHE_SH: the sweep is wrong ($(ls -A "$d" | tr '\n' ' '))"
+ case $(ls -ld "$d") in drwx------*) ok ;; *) bad "$s CACHE_SH: the cache folder is not private" ;; esac
+done
+
+echo "cache-sh-test: $pass passed, $fail failed (shells:$shells)"
+[ "$fail" = 0 ]
diff --git a/tests/copy.test.ts b/tests/copy.test.ts
index 9d69451..bbdd156 100644
--- a/tests/copy.test.ts
+++ b/tests/copy.test.ts
@@ -2,13 +2,14 @@ import { expect, mock, test } from 'claude-code/testing'
import {
codePointsOf, commandSuggestions, decodeSelection, DIACRITICS, hasPlaceholders, isDrawnIn, joinSegments, pageTopsOf, pickPages,
- placeholderCell, isSafePage, positionsOf, screenOf, SHIM_SETUP, textOfRun, WATCH_PL, type Drawn, type TextBlock, type Item, type Mark, type OnScreen,
+ placeholderCell, isSafePage, positionsOf, screenOf, textOfRun, WATCH_PL, type Drawn, type TextBlock, type Item, type Mark, type OnScreen,
type Place,
} from '../hooks/register'
+import * as registerModule from '../hooks/register'
+import * as clipboardModule from '../hooks/lib/clipboard'
+import * as settingsModule from '../hooks/lib/settings'
import { joinItems } from '../hooks/lib/copy'
import { WATCH_RESTART_MS } from '../hooks/lib/frame'
-import { ANSWER_SH, ASK_CLEAN_SH, ASK_END_SH, ASK_MAX, ASK_PL, ASK_RESTART_MS, ASK_RESTARTS } from '../hooks/lib/clipboard'
-import { HINT_WAIT_MS } from '../hooks/lib/settings'
import { rowsAfter, type Under } from '../hooks/lib/pictures'
import { forgetProbed, noteDrawn, noteDrawnAgain, noteOnScreen, wordsOf } from '../hooks/lib/probe'
import { clip, drawnAnswers, lastKey, results, type Job, type Result } from '../hooks/lib/state'
@@ -491,18 +492,14 @@ const inputsOf = (argv: readonly string[]) => Object.fromEntries(argv.flatMap((a
// 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`, the shims (pbcopy found, perl,
-// the FIFO ASK: IUI_COPY_ASK and PATH set, `envSets`), the ask reader
-// (ASK_PL: its PID, then `ask <id>` lines) and the copies, toasts and
-// selection the test sees. `copy` is Claude Code's own copy (copy on select
-// in fullscreen, /copy, $.ui.copy): the terminal's OSC 52 write of the text
-// (a clipboard change), then pbcopy through its shim: picture cells go to
-// ask/<id> and the id to the reader; the answer (ANSWER_SH), or the cells
-// when the shim gives up after 1.5 s (it leaves its mark), go on the
-// clipboard. `copies` are the texts the mod put there. While `selects`, a
-// copy of picture cells is this session's selection too. `foreign` is a copy
-// with no ask (another session's, the terminal's own on the main screen,
-// another app's); `change` is one more change with the same text.
+// `noBridge`), pbpaste reading `clipboard`, and the copies, toasts and
+// selection the test sees. `copy` is a native copy (a drag over text and
+// pictures, the main screen's terminal copy): while `selects`, picture cells
+// are this session's selection too; the text goes on the clipboard, one
+// change. `foreign` is a copy of another session or app (no selection);
+// `change` is one more change with the same text. `copies` are the texts
+// the mod put on the clipboard ($.ui.copy). `ran` and `spawned` are the
+// processes run and spawned, `envSets` the env vars set.
// `tty`: the tty size line its read gives (none: no read), `version`
// Claude Code's (picture select); `frames` the highlight's frame files
// written, `blits` the blits asked (`deny`: each refused with it), `logs`
@@ -512,12 +509,11 @@ function world(on: any, o: { failFirst?: boolean; noBridge?: boolean; env?: Reco
forgetRedraws()
mock.store(on)
const clock = mock.clock(on)
- const vars: Record<string, string | undefined> = { PATH: '/usr/bin:/bin', IUI_COPY_SHIM: '1', ...(o.env ?? { HOME: '/h', CLAUDE_CODE_FORCE_TERMINAL_IMAGES: '1' }) }
+ const vars: Record<string, string | undefined> = { PATH: '/usr/bin:/bin', ...(o.env ?? { HOME: '/h', CLAUDE_CODE_FORCE_TERMINAL_IMAGES: '1' }) }
const envSets: [string, string | undefined][] = []
on('env.get', async ($: any, e: any) => ({ value: vars[e.name] }))
on('env.set', async ($: any, e: any) => {
envSets.push([e.name, e.value])
- vars[e.name] = e.value
return { value: {} }
})
const files = new Map<string, string>()
@@ -525,13 +521,11 @@ function world(on: any, o: { failFirst?: boolean; noBridge?: boolean; env?: Reco
const queries: Record<string, string>[] = []
const kills: string[] = []
const killers = new Map<string, () => void>()
- type Child = { argv: string[]; pid: string; say: (line: string) => void; dead: boolean; end: (code: number) => void }
+ type Child = { argv: string[]; pid: string; say: (line: string) => void; dead: boolean }
const watchers: Child[] = []
- const readers: Child[] = []
- const waits = new Map<string, (text: string) => void>()
const w = {
- clock, files, compiles, queries, kills, watchers, readers, vars, envSets,
- ended: [] as string[][], answers: [] as string[], late: [] as string[], cleaned: [] as string[], asks: 0, reads: [] as string[],
+ clock, files, compiles, queries, kills, watchers, vars, envSets,
+ ran: [] as string[][], spawned: [] as string[][], reads: [] as string[],
clipboard: 'nothing yet', count: 40, pastes: 0, copies: [] as string[], toasts: [] as string[], traces: [] as string[], logs: [] as string[],
frames: [] as { path: string; old: string[]; png: Uint8Array }[], blits: [] as any[],
selection: undefined as { text: string; requestId?: string } | undefined,
@@ -543,27 +537,6 @@ function world(on: any, o: { failFirst?: boolean; noBridge?: boolean; env?: Reco
copy(text: string) {
if (w.selects && hasPlaceholders(text)) w.selection = { text }
w.foreign(text)
- void w.shim(text)
- },
- // pbcopy through its shim: an ask for picture cells while a reader runs.
- async shim(text: string) {
- let out = text
- const reader = readers.find(c => !c.dead)
- if (hasPlaceholders(text) && reader) {
- const id = `4242-${++w.asks}-7`
- const request = `${ASK_DIR}/${id}`
- files.set(request, text)
- const answered = new Promise<string | null>(r => waits.set(id, r))
- reader.say(`ask ${id}`)
- const got = await Promise.race([answered, clock.sleep(1500).then(() => null)])
- waits.delete(id)
- files.delete(request)
- if (got === null) files.set(`${request}.answer`, '')
- // An empty answer: the shim keeps its own bytes.
- else if (got) out = got
- }
- if (out !== text) w.copies.push(out)
- w.foreign(out)
},
foreign(text: string) {
w.clipboard = text
@@ -580,25 +553,21 @@ function world(on: any, o: { failFirst?: boolean; noBridge?: boolean; env?: Reco
const pid = String(pids++)
const lines = [`pid ${pid}`, ...first]
let wake = () => {}
- let code: number | null = null
- const me: Child = { argv, pid, dead: false, say: line => (lines.push(line), wake()), end: c => ((code = c), (me.dead = true), wake()) }
+ const me: Child = { argv, pid, dead: false, say: line => (lines.push(line), wake()) }
list.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, signal: code === null ? 'SIGTERM' : null } }
+ if (me.dead) return { value: { code: null, signal: 'SIGTERM' } }
await new Promise<void>(r => (wake = r))
}
}
on('process.spawn', async function* ($: any, e: any) {
const argv: string[] = e.argv
+ w.spawned.push(argv)
if (argv[0] === '/usr/bin/perl' && argv[1] === '-e' && argv[2] === WATCH_PL) {
return yield* child(watchers, argv, argv[3] === 'clip' ? [o.noBridge ? 'clip none' : `clip ${w.count}`] : [])
}
- if (argv[0] === '/usr/bin/perl' && argv[1] === '-e' && argv[2] === ASK_PL) {
- expect(argv.slice(3)).toEqual([ASK])
- return yield* child(readers, argv, [])
- }
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
@@ -623,35 +592,12 @@ function world(on: any, o: { failFirst?: boolean; noBridge?: boolean; env?: Reco
on('process.run', async ($: any, e: any) => {
const argv: string[] = e.argv
const cmd = argv.join(' ')
+ w.ran.push(argv)
if (argv[0] === 'kill') {
kills.push(argv[1]!)
killers.get(argv[1]!)?.()
return ok('')
}
- // The answer: to the shim that waits, else refused (its mark).
- if (argv[0] === 'sh' && argv[2] === ANSWER_SH) {
- const request = argv[4]!
- const text: string = e.init?.stdin ?? ''
- const to = waits.get(request.slice(ASK_DIR.length + 1))
- if (!to || files.has(`${request}.answer`)) {
- w.late.push(text)
- return ok('', 1)
- }
- w.answers.push(text)
- to(text)
- return ok('')
- }
- // After a refused answer: the request and the mark go.
- if (argv[0] === 'sh' && argv[2] === ASK_CLEAN_SH) {
- files.delete(argv[4]!)
- files.delete(`${argv[4]}.answer`)
- w.cleaned.push(argv[4]!)
- return ok('')
- }
- if (argv[0] === 'sh' && argv[2] === ASK_END_SH) {
- w.ended.push(argv.slice(4))
- return ok('')
- }
if (/cc-intelligent-ui-/.test(cmd)) return ok('/c\nDarwin\n')
if (o.tty && argv[0] === 'sh' && cmd.includes('ioctl(T')) return ok(o.tty)
if (argv[0] === '/usr/bin/perl' && argv[2] === WRITE_PL) {
@@ -662,14 +608,6 @@ function world(on: any, o: { failFirst?: boolean; noBridge?: boolean; env?: Reco
w.traces.push(e.init?.stdin ?? '')
return ok('')
}
- if (argv[1]?.endsWith(SHIM_SETUP) && argv[2] === 'find') return ok(`pid 4242\npbcopy /usr/bin/pbcopy\nperl /usr/bin/perl\nask ${ASK}\n`)
- if (argv[1]?.endsWith(SHIM_SETUP) && argv[2] === 'install') {
- for (const f of argv.slice(5)) {
- files.set(f, files.get(`${f}${argv[4]}`) ?? '')
- files.delete(`${f}${argv[4]}`)
- }
- return ok('')
- }
if (cmd.includes('command -v typst')) return ok('/usr/bin/typst\n')
if (argv[0] === '/usr/bin/typst' && argv[1] === 'eval') return ok('{}')
if (cmd.includes('od -An')) return ok(argv.filter(a => a.endsWith('.png')).map(() => `${HEAD}\n@\n`).join(''))
@@ -683,12 +621,10 @@ function world(on: any, o: { failFirst?: boolean; noBridge?: boolean; env?: Reco
files.set(e.path, e.text)
return { value: undefined }
})
- on('fs.stat', async ($: any, e: any, next: any) =>
- e.path.startsWith(`${ASK_DIR}/`) && files.has(e.path) ? { value: { kind: 'file', size: files.get(e.path)!.length, mtimeMs: 1, isLink: false } } : next(e))
on('fs.read', async ($: any, e: any, next: any) => {
w.reads.push(e.path)
if (e.as === 'bytes' && /^\/c\/.*\.png$/.test(e.path)) return { value: { base64: PAGE_PNG } }
- return e.path.endsWith('/hooks/clip-shim.sh') ? { value: SHIM_STUB } : files.has(e.path) ? { value: files.get(e.path) } : e.path.startsWith('/c/') ? { deny: 'ENOENT' } : next(e)
+ return 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) => {
@@ -697,9 +633,10 @@ function world(on: any, o: { failFirst?: boolean; noBridge?: boolean; env?: Reco
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 })) }
})
+ // The mod's write: its text on the clipboard, one change.
on('ui.copy', async ($: any, e: any) => {
w.copies.push(e.text)
- w.copy(e.text)
+ w.foreign(e.text)
return { value: { isCopied: true } }
})
on('ui.selection', async () => ({ value: w.selection }))
@@ -720,19 +657,13 @@ function world(on: any, o: { failFirst?: boolean; noBridge?: boolean; env?: Reco
return w
}
-// The shim template, as setUp reads it (the real one: tests/shim-test.sh).
-const SHIM_STUB = 'tool=@TOOL@ real=@REAL@ dir=@DIR@ perl=@PERL@'
-// The FIFO of this process (Claude Code's pid from the shim find: 4242) and the ask folder.
-const ASK = '/c/ask-4242'
-const ASK_DIR = '/c/ask'
-
const message = (requestId: string, text: string, isFullscreen: boolean | null = true) =>
({
plugin: 'cc-intelligent-ui', surface: 'terminal', component: 'AssistantMessage', requestId,
props: { text, isFirstOfReply: true }, viewport: { columns: 100, rows: 40, ...(isFullscreen === null ? {} : { isFullscreen }) },
}) as any
const props = (text: string) => ({ text, isFirstOfReply: true }) as any
-const names = (files: Map<string, string>) => [...new Set([...files.keys()].filter(k => k.startsWith('/c/') && !k.startsWith('/c/shims-') && !k.startsWith(`${ASK_DIR}/`)).map(k => k.replace(/^.*\//, '')))].sort()
+const names = (files: Map<string, string>) => [...new Set([...files.keys()].filter(k => k.startsWith('/c/')).map(k => k.replace(/^.*\//, '')))].sort()
// Draws `text` (SMALL_MD) as answer `id` (98 columns: the fixture's),
// compiled; the watcher has its clipboard part (its first count noted).
@@ -746,19 +677,35 @@ async function drawAnswer($: any, w: ReturnType<typeof world>, id = 'ans-1', tex
return ui
}
+// Picture select off: its prefetch of a page's words and PNG is not in the probes counted.
+const selectOff = ($: any) => $.command.run({ command: 'iui', args: 'select off' } as any)
+const grab = async ($: any): Promise<string | undefined> => (await $.command.run({ command: 'iui', args: 'grab' } as any)).text
+const detailLines = async ($: any) =>
+ ((await $.command.run({ command: 'iui', args: 'details' } as any)).text ?? '').split('\n').filter((l: string) => l.startsWith('Picture select:') || l.startsWith('/iui grab hint:'))
+
// 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'
+const GRABBED = 'Intelligent UI: copied 35 chars (1 of 1 picture runs read).'
+const GRAB_HINT = 'Intelligent UI: picture cells copied; /iui grab puts their text on the clipboard'
+const hints = (w: ReturnType<typeof world>) => w.toasts.filter(t => t === GRAB_HINT).length
+const long = Array.from({ length: 240 }, (_, i) => `Paragraph ${i} with a few words in it.`).join('\n\n')
+const pagesOf = (w: ReturnType<typeof world>) => (JSON.parse(w.files.get([...w.files.keys()].find(k => k.endsWith('/doc.json'))!)!) as { segments: string[] }).segments.length
-test('a compile writes no probe file and runs no probe; a copy probes only its page, with the PNG compile inputs', async ($, on) => {
+test('a compile writes no probe file and runs no probe, nor does the hint; /iui grab probes only its page, with the PNG compile inputs', async ($, on) => {
const w = world(on)
+ await selectOff($)
await $.command.run({ command: 'iui', args: '' } as any)
await drawAnswer($, w)
expect(w.compiles.length).toBe(1)
expect(names(w.files)).toEqual(['doc.json', 'pages.json'])
expect(w.queries).toEqual([])
+ // A native copy: the hint picks the page with no probe.
w.copy(COPY)
await w.clock.settle()
+ expect(hints(w)).toBe(1)
+ expect(w.queries).toEqual([])
+ expect(await grab($)).toBe(GRABBED)
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' }])
@@ -768,17 +715,17 @@ test('a compile writes no probe file and runs no probe; a copy probes only its p
test("an answer's link rows are under its pages: the page on screen is found above them", async ($, on) => {
const w = world(on)
+ await selectOff($)
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')
const text = `${long}\n\nSee https://typst.app/docs.\n\n\`\`\`sh\nbrew install typst\n\`\`\``
const ui = await drawAnswer($, w, 'ans-1', text)
- const pages = (JSON.parse(w.files.get([...w.files.keys()].find(k => k.endsWith('/doc.json'))!)!) as { segments: string[] }).segments.length
// 16 rows a page under the top margin, then 2 link rows: page 2 is rows 17 to 32.
- const of = 1 + 16 * pages + 2
+ const of = 1 + 16 * pagesOf(w) + 2
await ui.redraw({ ...props(text), onScreen: { first: 17, last: 32, of } })
await w.clock.settle()
w.copy([cells(2, 0, 97), cells(3, 0, 97)].join('\n'))
await w.clock.settle()
+ expect(await grab($)).toContain('Intelligent UI: copied')
expect(w.queries.map(q => q.page)).toEqual(['2'])
const dumped = await $.command.run({ command: 'iui', args: 'dump' } as any)
expect(dumped.text).toContain(`-> answer ans-1 page 1 (rows 17-32 of ${of} on screen, page top 17)`)
@@ -786,11 +733,12 @@ test("an answer's link rows are under its pages: the page on screen is found abo
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 selectOff($)
await $.command.run({ command: 'iui', args: '' } as any)
await drawAnswer($, w)
expect(w.compiles.map(c => c.safe)).toEqual([undefined, '1'])
- w.copy(COPY)
- await w.clock.settle()
+ w.selection = { text: COPY }
+ expect(await grab($)).toBe(GRABBED)
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)
@@ -799,27 +747,26 @@ test('a compile retried in safe mode gives the probe safe=1 (its page files say
expect(isSafePage('/c/k/c-3.png')).toBe(false)
})
-test('a copy over two pages of a long answer probes those two pages only', async ($, on) => {
+test('a grab over two pages of a long answer probes those two pages only', async ($, on) => {
const w = world(on)
+ await selectOff($)
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)
+ expect(pagesOf(w)).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()
+ w.selection = { text: [cells(15, 0, 97, '⏺ '), cells(0, 0, 97), cells(1, 0, 97)].join('\n') }
+ expect(await grab($)).toMatch(/^Intelligent UI: copied \d+ chars \([12] of 2 picture runs read\)\.$/)
expect(w.queries.map(q => q.page)).toEqual(['1', '2'])
expect(w.copies.length).toBe(1)
expect(w.copies[0]).toContain('Copy test')
})
-test('a copy goes to the page on screen: the rows on screen of the last draw (a memo hit) reach the pick and dump', async ($, on) => {
+test('a grab goes to the page on screen: the rows on screen of the last draw (a memo hit) reach the pick and dump', async ($, on) => {
const w = world(on)
+ await selectOff($)
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')
const ui = 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
+ const pages = pagesOf(w)
expect(pages).toBeGreaterThan(2)
// 16 rows a page under the top margin: page 2 is rows 17 to 32.
const of = 1 + 16 * pages
@@ -827,9 +774,8 @@ test('a copy goes to the page on screen: the rows on screen of the last draw (a
await ui.redraw({ ...props(long), onScreen: { first: 17, last: 32, of } })
await w.clock.settle()
expect(w.compiles.length).toBe(compiles)
- const rows = [cells(2, 0, 97), cells(3, 0, 97)].join('\n')
- w.copy(rows)
- await w.clock.settle()
+ w.selection = { text: [cells(2, 0, 97), cells(3, 0, 97)].join('\n') }
+ expect(await grab($)).toContain('Intelligent UI: copied')
expect(w.queries.map(q => q.page)).toEqual(['2'])
expect(w.copies.length).toBe(1)
const dumped = await $.command.run({ command: 'iui', args: 'dump' } as any)
@@ -837,107 +783,107 @@ test('a copy goes to the page on screen: the rows on screen of the last draw (a
// Scrolled up to page 1: the same rows are page 1's.
await ui.redraw({ ...props(long), onScreen: { first: 0, last: 16, of } })
await w.clock.settle()
- w.copy(rows)
- await w.clock.settle()
+ expect(await grab($)).toContain('Intelligent UI: copied')
expect(w.queries.map(q => q.page)).toEqual(['2', '1'])
expect(w.copies.length).toBe(2)
})
-test('positions are kept in memory: copies of the same page share one probe run, and a later copy runs none', async ($, on) => {
+test('positions are kept in memory: grabs of the same page share one probe run, and a later grab runs none', async ($, on) => {
const w = world(on)
+ await selectOff($)
await $.command.run({ command: 'iui', args: '' } as any)
await drawAnswer($, w)
- // A slow probe: no toast until the copy is done.
- const before = w.toasts.length
+ // A slow probe: nothing is copied until it is done.
w.hold()
- w.copy(COPY)
+ w.selection = { text: COPY, requestId: 'ans-1' }
+ const first = grab($)
await w.clock.settle()
expect(w.queries.length).toBe(1)
- await w.clock.advance(1000)
- expect(w.toasts.length).toBe(before)
- // /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)
+ // A second grab meanwhile waits for the same run.
+ const second = grab($)
await w.clock.settle()
+ await w.clock.advance(1000)
expect(w.queries.length).toBe(1)
+ expect(w.copies).toEqual([])
w.release()
await w.clock.settle()
- expect((await grabbed).text).toBe('Intelligent UI: copied 35 chars (1 of 1 picture runs read, row ans-1).')
+ expect(await first).toBe('Intelligent UI: copied 35 chars (1 of 1 picture runs read, row ans-1).')
+ expect(await second).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.length
+ // Known now: no probe for the next grab.
w.gate = null
- w.selection = undefined
- w.copy([cells(1, 0, 97), cells(2, 0, 97), cells(3, 0, 21)].join('\n'))
- await w.clock.settle()
- await w.clock.advance(1000)
+ w.selection = { text: [cells(1, 0, 97), cells(2, 0, 97), cells(3, 0, 21)].join('\n') }
+ expect(await grab($)).toBe(GRABBED)
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'])
+ expect(w.copies).toEqual([COPIED, COPIED, COPIED])
})
-test("a copy of picture cells gets its text through the shim's ask; the watcher reads each change once and never writes", async ($, on) => {
+test('the watcher: its first count is only noted, each change is read once, the clipboard is never written; off stops its clipboard part', async ($, on) => {
const w = world(on)
await $.command.run({ command: 'iui', args: '' } as any)
- // No picture drawn: the watcher has no clipboard part, and no ask reader runs.
+ // No picture drawn: the watcher has no clipboard part.
await w.clock.advance(900)
expect(w.watchers.map(c => c.argv.slice(3))).toEqual([[]])
- expect(w.readers.length).toBe(0)
await drawAnswer($, w)
- expect(w.readers.length).toBe(1)
// 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.
+ // A copy with no placeholders: one read, no hint.
w.foreign('copied in another app')
await w.clock.settle()
expect(w.pastes).toBe(1)
+ expect(hints(w)).toBe(0)
+ // Picture cells: one read, one hint.
w.copy(COPY)
await w.clock.settle()
- // The shim got the text; the mod wrote nothing itself.
- expect(w.answers).toEqual([COPIED])
- expect(w.copies).toEqual([COPIED])
- expect(w.clipboard).toBe(COPIED)
- expect(w.toasts).toContain('Intelligent UI: copied 35 chars of text')
- // The OSC 52 write of the cells and the shim's write: read, no hint.
+ expect(w.pastes).toBe(2)
+ expect(hints(w)).toBe(1)
+ // The same text again (the terminal's second write): read, no second hint.
+ w.change()
await w.clock.advance(3000)
- const pastes = w.pastes
- expect(pastes).toBeGreaterThan(1)
- expect(w.toasts.filter(t => t === GRAB_HINT)).toEqual([])
- // The request and the answer are gone.
- expect([...w.files.keys()].filter(k => k.startsWith(`${ASK_DIR}/`))).toEqual([])
+ expect(w.pastes).toBe(3)
+ expect(hints(w)).toBe(1)
+ expect(w.copies).toEqual([])
+ expect(w.clipboard).toBe(COPY)
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(dumped.text).toContain('code points; grab hint on):')
expect(w.files.has('/c/copy-debug.json')).toBe(true)
// Off: the watcher again with no clipboard part; no reads.
await $.command.run({ command: 'iui', args: 'off' } as any)
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)
+ w.copy(COPY.replace(cells(3, 0, 21), cells(3, 0, 20)))
await w.clock.settle()
- expect(w.pastes).toBe(pastes)
+ expect(w.pastes).toBe(3)
+ expect(hints(w)).toBe(1)
})
-test('/iui details says whether the automatic copy is on', async ($, on) => {
+test('/iui details says whether picture select is on, and whether the /iui grab hint is', 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)')
+ expect((await detailLines($))[1]).toBe('/iui grab hint: off (no picture yet)')
+ await $.command.run({ command: 'iui', args: '' } as any)
await drawAnswer($, w)
- expect(await details()).toBe('Auto copy: on')
+ expect(await detailLines($)).toEqual(['Picture select: on', '/iui grab hint: on'])
+ await selectOff($)
+ expect(await detailLines($)).toEqual(['Picture select: off (/iui select off)', '/iui grab hint: on'])
await $.command.run({ command: 'iui', args: 'off' } as any)
- expect(await details()).toBe('Auto copy: off (Intelligent UI is off)')
- // The shims were set up once: the FIFO, then PATH with the folder first.
- expect(w.envSets).toEqual([['IUI_COPY_ASK', ASK], ['PATH', '/c/shims-4242:/usr/bin:/bin']])
- expect(w.files.get('/c/shims-4242/pbcopy')).toBe(`tool='pbcopy' real='/usr/bin/pbcopy' dir='/c/shims-4242' perl='/usr/bin/perl'`)
+ expect((await detailLines($))[1]).toBe('/iui grab hint: off (Intelligent UI is off)')
})
-test('with no PerlObjCBridge (clip none) the shim still gets the text; no read, no hint; details says so; grab still copies', async ($, on) => {
+test('/iui details: picture select off before Claude Code 2.1.298', async ($, on) => {
+ const w = world(on, { version: '2.1.297' })
+ await $.command.run({ command: 'iui', args: '' } as any)
+ await drawAnswer($, w)
+ expect(await detailLines($)).toEqual(['Picture select: off (Claude Code 2.1.297; it needs 2.1.298 or newer)', '/iui grab hint: on'])
+})
+
+test('with no PerlObjCBridge (clip none): no read, no hint; details says so; no new watcher for it; /iui grab still copies', async ($, on) => {
const w = world(on, { noBridge: true })
await $.command.run({ command: 'iui', args: '' } as any)
await drawAnswer($, w)
@@ -945,15 +891,15 @@ test('with no PerlObjCBridge (clip none) the shim still gets the text; no read,
await w.clock.advance(900)
await w.clock.settle()
expect(w.pastes).toBe(0)
- expect(w.copies).toEqual([COPIED])
- const details = await $.command.run({ command: 'iui', args: 'details' } as any)
- expect(details.text).toContain('\nAuto copy: on (no /iui grab hint: no PerlObjCBridge in /usr/bin/perl)')
+ expect(hints(w)).toBe(0)
+ expect(w.copies).toEqual([])
+ expect((await detailLines($))[1]).toBe('/iui grab hint: 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(await grab($)).toBe('Intelligent UI: copied 35 chars (1 of 1 picture runs read, row ans-1).')
+ expect(w.copies).toEqual([COPIED])
})
// Another plugin's `$.ui.copy`, from its command `cp` (args: the text).
@@ -972,13 +918,10 @@ test('a copy of picture cells through $.ui.copy is rewritten to their text; othe
expect(JSON.parse(got.text!)).toEqual({ isCopied: true })
expect(w.copies).toEqual([COPIED])
await $.command.run({ command: 'cp', args: 'plain text' } as any)
- expect(w.copies[1]).toBe('plain text')
- // The text went through the shim: no ask.
- await w.clock.settle()
- expect(w.answers).toEqual([])
+ expect(w.copies).toEqual([COPIED, 'plain text'])
})
-test('a $.ui.copy of picture cells is not copied again at its clipboard change', { plugins: [COPIER] }, async ($, on) => {
+test('a $.ui.copy of picture cells: its clipboard change is read once and gets no hint', { plugins: [COPIER] }, async ($, on) => {
const w = world(on)
await $.command.run({ command: 'iui', args: '' } as any)
await drawAnswer($, w)
@@ -986,83 +929,66 @@ test('a $.ui.copy of picture cells is not copied again at its clipboard change',
await $.command.run({ command: 'cp', args: COPY } as any)
await w.clock.advance(900)
await w.clock.settle()
- expect(w.pastes).toBe(2)
+ expect(w.pastes).toBe(1)
expect(w.copies).toEqual([COPIED])
+ expect(w.clipboard).toBe(COPIED)
+ expect(hints(w)).toBe(0)
expect(w.toasts.filter(t => t.startsWith('Intelligent UI: copied')).length).toBe(0)
})
-const GRAB_HINT = 'Intelligent UI: picture cells copied; /iui grab puts their text on the clipboard'
-
-test("another session's copy of the same cells (no ask here) is never rewritten, even with this session's old selection of them; one hint", async ($, on) => {
+test('native copies in fullscreen: one hint for cells that fit a page drawn here, never a write; none for the same text again, our own write, plain text or cells that fit no page', async ($, on) => {
const w = world(on)
await $.command.run({ command: 'iui', args: '' } as any)
await drawAnswer($, w)
- // This session copied these cells a while ago (answered then).
w.copy(COPY)
await w.clock.settle()
- expect(w.copies).toEqual([COPIED])
- await w.clock.advance(60000)
- // The selection stays; another session copies the same cells.
+ expect(hints(w)).toBe(1)
+ expect(w.copies).toEqual([])
+ expect(w.clipboard).toBe(COPY)
+ // Another session's copy of the same cells, with this session's old selection of them: the same text, no write, no second hint.
expect(w.selection?.text).toBe(COPY)
w.foreign(COPY)
await w.clock.settle()
- // A shim of this session could still ask: no hint yet.
- expect(w.toasts.filter(t => t === GRAB_HINT)).toEqual([])
- await w.clock.advance(HINT_WAIT_MS)
- expect(w.copies).toEqual([COPIED])
- expect(w.clipboard).toBe(COPY)
- expect(w.toasts.filter(t => t === GRAB_HINT)).toEqual([GRAB_HINT])
- // Its OSC 52 write of the same text: no second hint.
- w.change()
- await w.clock.advance(HINT_WAIT_MS)
- expect(w.toasts.filter(t => t === GRAB_HINT).length).toBe(1)
- expect(w.copies).toEqual([COPIED])
-})
-
-test('cells the watcher sees before their ask comes (a slow shim start): the ask in the wait stops the hint', async ($, on) => {
- const w = world(on)
- await $.command.run({ command: 'iui', args: '' } as any)
- await drawAnswer($, w)
- // The OSC 52 write only, then pbcopy's shim 300 ms later.
- w.foreign(COPY)
- await w.clock.advance(300)
- void w.shim(COPY)
+ expect(hints(w)).toBe(1)
+ expect(w.copies).toEqual([])
+ // /iui grab's own write: not hinted.
+ expect(await grab($)).toBe(GRABBED)
await w.clock.settle()
expect(w.copies).toEqual([COPIED])
- await w.clock.advance(HINT_WAIT_MS)
- expect(w.toasts.filter(t => t === GRAB_HINT)).toEqual([])
- expect(w.clipboard).toBe(COPIED)
- // A copy that changes in the wait: no hint for the old one.
- w.foreign(COPY.replace(cells(3, 0, 21), cells(3, 0, 20)))
- await w.clock.advance(500)
+ expect(hints(w)).toBe(1)
+ // Plain text, then cells that fit no page drawn here (column 150): no hint.
w.foreign('copied in another app')
- await w.clock.advance(HINT_WAIT_MS)
- expect(w.toasts.filter(t => t === GRAB_HINT)).toEqual([])
+ await w.clock.settle()
+ w.copy([cells(1, 0, 150), cells(2, 0, 150)].join('\n'))
+ await w.clock.settle()
+ expect(hints(w)).toBe(1)
+ // Other cells that fit: one hint again.
+ w.copy(cells(5, 0, 40))
+ await w.clock.settle()
+ expect(hints(w)).toBe(2)
+ expect(w.copies).toEqual([COPIED])
})
-test("the selection gives the row (its requestId) only when it is that copy", async ($, on) => {
+test('the selection gives a $.ui.copy its row (its requestId) only when it is that copy', { plugins: [COPIER] }, async ($, on) => {
const w = world(on)
await $.command.run({ command: 'iui', args: '' } as any)
// Two answers that both fit the cells: with no row, the newer one.
await drawAnswer($, w)
await drawAnswer($, w, 'ans-2', `${SMALL_MD}\n\nEnd.`)
- w.selects = false
const picked = async () => ((await $.command.run({ command: 'iui', args: 'dump' } as any)).text ?? '').match(/-> answer (\S+) page/)?.[1]
// A selection of other cells (and a row) does not name this copy's row.
w.selection = { text: cells(9, 0, 9), requestId: 'ans-1' }
- w.copy(COPY)
- await w.clock.settle()
+ await $.command.run({ command: 'cp', args: COPY } as any)
expect(w.copies).toEqual([COPIED])
expect(await picked()).toBe('ans-2')
- // The selection of this copy (a last line break less): its row.
+ // The selection of this copy: its row.
w.selection = { text: COPY, requestId: 'ans-1' }
- w.copy(`${COPY}\n`)
- await w.clock.settle()
+ await $.command.run({ command: 'cp', args: COPY } as any)
expect(w.copies).toEqual([COPIED, COPIED])
expect(await picked()).toBe('ans-1')
})
-test('cells that can not be read: an empty answer at once (no wait; the shim keeps its cells), one toast for each copy', async ($, on) => {
+test('cells that fit no page: no hint; /iui grab says it could not read them; $.ui.copy passes them as they are', { plugins: [COPIER] }, async ($, on) => {
const w = world(on)
await $.command.run({ command: 'iui', args: '' } as any)
await drawAnswer($, w)
@@ -1070,128 +996,13 @@ test('cells that can not be read: an empty answer at once (no wait; the shim kee
const text = [cells(1, 0, 150), cells(2, 0, 150)].join('\n')
w.copy(text)
await w.clock.settle()
- expect(w.answers).toEqual([''])
- expect(w.clipboard).toBe(text)
- expect(w.copies).toEqual([])
- expect(w.toasts.filter(t => t.startsWith('Intelligent UI: could not read')).length).toBe(1)
- // No /iui grab hint for it: its own shim asked.
- await w.clock.advance(HINT_WAIT_MS)
- expect(w.toasts.filter(t => t === GRAB_HINT)).toEqual([])
- w.copy(text)
- await w.clock.settle()
- expect(w.answers).toEqual(['', ''])
- expect(w.toasts.filter(t => t.startsWith('Intelligent UI: could not read')).length).toBe(2)
-})
-
-test('a request over ASK_MAX bytes is not read: an empty answer at once', async ($, on) => {
- const w = world(on)
- await $.command.run({ command: 'iui', args: '' } as any)
- await drawAnswer($, w)
- w.reads.length = 0
- const big = `${COPY}${' '.repeat(ASK_MAX)}`
- void w.shim(big)
- await w.clock.settle()
- expect(w.answers).toEqual([''])
- expect(w.reads.filter(p => p.startsWith(`${ASK_DIR}/`))).toEqual([])
- expect(w.clipboard).toBe(big)
- expect(w.copies).toEqual([])
-})
-
-test('a throw while the text is read (a bad selection): an empty answer all the same', async ($, on) => {
- const w = world(on)
- await $.command.run({ command: 'iui', args: '' } as any)
- await drawAnswer($, w)
- w.selects = false
- w.selection = { text: 5 } as any
- void w.shim(COPY)
- await w.clock.settle()
- expect(w.answers).toEqual([''])
- expect(w.clipboard).toBe(COPY)
- expect(w.copies).toEqual([])
-})
-
-test('a bad id is never read or answered; an id with no request file gets an empty answer', async ($, on) => {
- const w = world(on)
- await $.command.run({ command: 'iui', args: '' } as any)
- await drawAnswer($, w)
- w.reads.length = 0
- w.files.set('/c/secret', COPY)
- w.files.set(`${ASK_DIR}/.hidden`, COPY)
- for (const id of ['../secret', '.hidden', '..', 'a/b', 'x'.repeat(200), '4242-1-1']) w.readers[0]!.say(`ask ${id}`)
- await w.clock.settle()
- expect(w.reads.filter(p => p.startsWith('/c/'))).toEqual([])
- expect(w.answers).toEqual([])
- // Only 4242-1-1 (no shim waits for it): refused, its files go.
- expect(w.late).toEqual([''])
- expect(w.cleaned).toEqual([`${ASK_DIR}/4242-1-1`])
- expect(w.copies).toEqual([])
- expect(w.toasts.filter(t => t.includes('not ready'))).toEqual([])
-})
-
-const NOT_READY = 'Intelligent UI: the picture text was not ready in time; /iui grab copies it'
-
-test('a late answer (the shim gave up at 1.5 s) writes nothing: the cells stay, one toast names /iui grab', async ($, on) => {
- const w = world(on)
- await $.command.run({ command: 'iui', args: '' } as any)
- await drawAnswer($, w)
- // A slow probe: the shim gives up and writes the cells, with its mark.
- w.hold()
- w.copy(COPY)
- await w.clock.settle()
- await w.clock.advance(1500)
- expect(w.clipboard).toBe(COPY)
- expect([...w.files.keys()].filter(k => k.startsWith(`${ASK_DIR}/`))).toEqual([`${ASK_DIR}/4242-1-7.answer`])
- w.release()
- await w.clock.settle()
- // The answer meets the mark: no write, the files go, one toast.
- expect(w.late).toEqual([COPIED])
- expect(w.copies).toEqual([])
- expect(w.clipboard).toBe(COPY)
- expect([...w.files.keys()].filter(k => k.startsWith(`${ASK_DIR}/`))).toEqual([])
- expect(w.toasts.filter(t => t === NOT_READY)).toEqual([NOT_READY])
- expect(w.toasts.filter(t => t.startsWith('Intelligent UI: copied'))).toEqual([])
- // Its own shim asked for these cells: no /iui grab hint as well.
- await w.clock.advance(HINT_WAIT_MS)
- expect(w.toasts.filter(t => t === GRAB_HINT)).toEqual([])
- // /iui grab then copies the text.
- expect((await $.command.run({ command: 'iui', args: 'grab' } as any)).text).toContain('copied')
- expect(w.copies).toEqual([COPIED])
-})
-
-test('session A in fullscreen keeps an old selection equal to the cells; the same cells come on the clipboard not through its shim: no write by A, at most one hint', async ($, on) => {
- const w = world(on)
- await $.command.run({ command: 'iui', args: '' } as any)
- await drawAnswer($, w)
- // An old selection of A, with the text of these cells.
- w.selection = { text: COPY }
- await w.clock.advance(60000)
- // Another session copies identical cells (no ask comes to A).
- w.foreign(COPY)
- await w.clock.settle()
- await w.clock.advance(HINT_WAIT_MS)
- w.change()
- await w.clock.advance(HINT_WAIT_MS)
+ expect(hints(w)).toBe(0)
+ expect(await grab($)).toBe('Intelligent UI: found 1 picture run(s) but could not read them (see /iui dump).')
expect(w.copies).toEqual([])
- expect(w.answers).toEqual([])
- expect(w.clipboard).toBe(COPY)
- expect(w.toasts.filter(t => t === GRAB_HINT).length).toBeLessThanOrEqual(1)
-})
-
-test('the same copy again while its picture is read: one probe, each copy gets the text', 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 $.command.run({ command: 'cp', args: text } as any)
await w.clock.settle()
- expect(w.queries.length).toBe(1)
- expect(w.copies).toEqual([COPIED, COPIED])
- expect(w.clipboard).toBe(COPIED)
- expect(w.toasts.filter(t => t.startsWith('Intelligent UI: copied')).length).toBe(2)
+ expect(w.copies).toEqual([text])
+ expect(hints(w)).toBe(0)
})
test('a watcher that starts again gives no hint for the clipboard that was there before (its first count is only noted)', async ($, on) => {
@@ -1202,51 +1013,15 @@ test('a watcher that starts again gives no hint for the clipboard that was there
await drawAnswer($, w)
await w.clock.advance(3000)
expect(w.pastes).toBe(0)
- expect(w.toasts.filter(t => t === GRAB_HINT)).toEqual([])
- // A new copy is answered.
- w.copy(COPY)
- await w.clock.settle()
- expect(w.copies).toEqual([COPIED])
-})
-
-test('the ask reader that ends on its own is started again, ASK_RESTARTS times at most; a FIFO that is not safe (exit 3) is final', async ($, on) => {
- const w = world(on)
- await $.command.run({ command: 'iui', args: '' } as any)
- await drawAnswer($, w)
- const details = async () => ((await $.command.run({ command: 'iui', args: 'details' } as any)).text ?? '').split('\n').find(l => l.startsWith('Auto copy:'))
- for (let i = 0; i < ASK_RESTARTS; i++) {
- w.readers.at(-1)!.end(0)
- await w.clock.settle()
- expect(await details()).toBe('Auto copy: off (the ask reader does not run)')
- await w.clock.advance(ASK_RESTART_MS)
- expect(w.readers.length).toBe(i + 2)
- expect(await details()).toBe('Auto copy: on')
- }
- // The new reader gets the asks.
+ expect(hints(w)).toBe(0)
+ // A new copy gets the hint.
w.copy(COPY)
await w.clock.settle()
- expect(w.copies).toEqual([COPIED])
- // The cap: no more.
- w.readers.at(-1)!.end(0)
- await w.clock.advance(ASK_RESTART_MS * 3)
- expect(w.readers.length).toBe(ASK_RESTARTS + 1)
- // No reader: the shim writes the cells at once (its FIFO open fails).
- w.copy(COPY)
- await w.clock.settle()
- expect(w.clipboard).toBe(COPY)
- expect(w.copies).toEqual([COPIED])
-})
-
-test('an unsafe FIFO (the reader exits 3) is not read again', async ($, on) => {
- const w = world(on)
- await $.command.run({ command: 'iui', args: '' } as any)
- await drawAnswer($, w)
- w.readers[0]!.end(3)
- await w.clock.advance(ASK_RESTART_MS * 3)
- expect(w.readers.length).toBe(1)
+ expect(hints(w)).toBe(1)
+ expect(w.copies).toEqual([])
})
-test('at an exit the watcher and the ask reader are killed, no child takes their place, the FIFO and the requests go; a /clear keeps the reader', async ($, on) => {
+test('at an exit the watcher is killed and no child takes its place; a /clear stops only its 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)
@@ -1254,22 +1029,18 @@ test('at an exit the watcher and the ask reader are killed, no child takes their
expect(w.watchers.map(c => c.argv.slice(3))).toEqual([[], ['clip']])
await $.session.end({ reason: 'clear', sessionId: 's1' } as any)
await w.clock.settle()
+ // The process goes on: the watcher again with no clipboard part.
expect(w.watchers.map(c => c.argv.slice(3))).toEqual([[], ['clip'], []])
- // The process goes on: the reader and its FIFO stay.
- expect(w.ended).toEqual([])
- expect(w.readers.map(c => c.dead)).toEqual([false])
expect(w.kills).toEqual([w.watchers[0]!.pid, w.watchers[1]!.pid])
w.copy(COPY)
await w.clock.settle()
expect(w.pastes).toBe(0)
- expect(w.copies).toEqual([COPIED])
+ expect(hints(w)).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.readers.length).toBe(1)
- expect(w.kills).toEqual([...w.watchers.map(c => c.pid), w.readers[0]!.pid])
- expect(w.ended).toEqual([[ASK, ASK_DIR, '4242', '/c/shims-4242']])
+ 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 gets no hint', async ($, on) => {
@@ -1290,21 +1061,44 @@ test('a clip child that ends on its own is started again; its old clipboard gets
expect(w.pastes).toBe(0)
// The new child sees a later copy of another session.
w.foreign([cells(1, 0, 97), cells(2, 0, 97), cells(3, 0, 21)].join('\n'))
- await w.clock.advance(HINT_WAIT_MS)
+ await w.clock.settle()
expect(w.toasts.filter(t => t === GRAB_HINT)).toEqual([GRAB_HINT])
})
-// ---- The main screen: the terminal copies, so no automatic copy ------------
+test('nothing of the shim is left: no env var set, no shim script run or read, no perl child but the watcher, none of its exports', async ($, on) => {
+ const w = world(on)
+ await $.command.run({ command: 'iui', args: '' } as any)
+ await drawAnswer($, w)
+ w.copy(COPY)
+ await w.clock.settle()
+ expect(await grab($)).toBe(GRABBED)
+ // No PATH or IUI_COPY_ASK change.
+ expect(w.envSets).toEqual([])
+ expect(w.vars.PATH).toBe('/usr/bin:/bin')
+ expect([...w.ran, ...w.spawned].some(argv => argv.some(a => /clip-shim|IUI_COPY|ask-\d|shims-/.test(a)))).toBe(false)
+ expect(w.reads.some(p => p.includes('clip-shim'))).toBe(false)
+ expect([...w.files.keys()].filter(k => /\/(shims-|ask)/.test(k))).toEqual([])
+ // The perl children: the watcher only (a size one, then one with `clip`).
+ const perls = w.spawned.filter(argv => /perl$/.test(argv[0]!))
+ expect(perls.length).toBe(2)
+ expect(perls.every(argv => argv[1] === '-e' && argv[2] === WATCH_PL)).toBe(true)
+ const gone = ['SHIM_SETUP', 'shimText', 'shimFindOf', 'pathWith', 'setUpShims', 'autoCopyText', 'ASK_PL', 'ANSWER_SH', 'ASK_CLEAN_SH', 'ASK_END_SH', 'ASK_MAX', 'listenAsks']
+ expect(Object.keys(registerModule).filter(k => gone.includes(k))).toEqual([])
+ expect(Object.keys(clipboardModule).filter(k => gone.includes(k))).toEqual([])
+ expect(Object.keys(settingsModule).filter(k => ['HINT_WAIT_MS', 'ASKED_MS', 'USE_COPY_SHIM'].includes(k))).toEqual([])
+})
+
+// ---- The main screen: the terminal copies, so only the hint ----------------
const FULLSCREEN_TOAST = 'Intelligent UI works best in fullscreen mode: run /tui fullscreen'
test('main screen: picture cells on the clipboard are never rewritten (their session is not known); one toast names /iui grab', async ($, on) => {
const w = world(on)
w.selects = false
+ await selectOff($)
await $.command.run({ command: 'iui', args: '' } as any)
await drawAnswer($, w, 'ans-1', SMALL_MD, false)
- // The terminal's own copy (or another session's): no ask, so no write,
- // no probe, one toast at once.
+ // The terminal's own copy (or another session's): no write, no probe, one toast at once.
w.foreign(COPY)
await w.clock.settle()
await w.clock.advance(1000)
@@ -1314,7 +1108,7 @@ test('main screen: picture cells on the clipboard are never rewritten (their ses
expect(w.toasts.filter(t => t.includes('/iui grab'))).toEqual([GRAB_HINT])
// dump shows them (its read probes the page).
const dumped = await $.command.run({ command: 'iui', args: 'dump' } as any)
- expect(dumped.text).toContain('auto copy off on the main screen (use /iui grab)')
+ expect(dumped.text).toContain('code points; grab hint on):')
expect(dumped.text).toContain('-> answer ans-1 page 0')
// The same cells again: no second toast.
w.foreign(COPY)
@@ -1326,6 +1120,14 @@ test('main screen: picture cells on the clipboard are never rewritten (their ses
expect(w.toasts.filter(t => t.includes('/iui grab')).length).toBe(1)
expect(w.copies).toEqual([])
expect(w.queries.length).toBe(1)
+ expect(await detailLines($)).toEqual(['Picture select: off (/iui select off)', '/iui grab hint: on'])
+})
+
+test('main screen: picture select says to use fullscreen or /iui grab', async ($, on) => {
+ const w = world(on)
+ await $.command.run({ command: 'iui', args: '' } as any)
+ await drawAnswer($, w, 'ans-1', SMALL_MD, false)
+ expect(await detailLines($)).toEqual(['Picture select: off on the main screen (use /tui fullscreen, or /iui grab)', '/iui grab hint: on'])
})
test('main screen: /iui grab with no selection reads the clipboard and writes its text; a second grab says it is there', async ($, on) => {
@@ -1335,20 +1137,17 @@ test('main screen: /iui grab with no selection reads the clipboard and writes it
await drawAnswer($, w, 'ans-1', SMALL_MD, false)
w.foreign(COPY)
await w.clock.settle()
- 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).')
+ expect(await grab($)).toBe(GRABBED)
expect(w.copies).toEqual([COPIED])
// Our own write is not read back as new: no toast, no copy.
await w.clock.settle()
expect(w.copies).toEqual([COPIED])
expect(w.toasts.filter(t => t.includes('/iui grab')).length).toBe(1)
- const again = await $.command.run({ command: 'iui', args: 'grab' } as any)
- expect(again.text).toBe('Intelligent UI: the clipboard has the text already.')
+ expect(await grab($)).toBe('Intelligent UI: the clipboard has the text already.')
expect(w.copies).toEqual([COPIED])
w.foreign('plain text')
await w.clock.settle()
- const none = await $.command.run({ command: 'iui', args: 'grab' } as any)
- expect(none.text).toBe('Intelligent UI: no mouse selection and no picture cells on the clipboard; select over a picture and copy first.')
+ expect(await grab($)).toBe('Intelligent UI: no mouse selection and no picture cells on the clipboard; select over a picture and copy first.')
expect(w.copies).toEqual([COPIED])
})
@@ -1358,27 +1157,26 @@ test('main screen: /copy or $.ui.copy of picture cells gets their text (the ui.c
await $.command.run({ command: 'iui', args: '' } as any)
await drawAnswer($, w, 'ans-1', SMALL_MD, false)
await $.command.run({ command: 'cp', args: COPY } as any)
- await w.clock.advance(HINT_WAIT_MS)
+ await w.clock.advance(1000)
expect(w.copies).toEqual([COPIED])
expect(w.clipboard).toBe(COPIED)
- expect(w.toasts.filter(t => t === GRAB_HINT)).toEqual([])
+ expect(hints(w)).toBe(0)
})
-// The ask says whose copy it is, so a write is safe before the layout is known.
-test('fullscreen or main screen not known yet: a copy through the shim gets its text, another one gets the hint', async ($, on) => {
+test('fullscreen or main screen not known yet: a native copy gets the hint, a $.ui.copy its text; no advice', { plugins: [COPIER] }, async ($, on) => {
const w = world(on)
w.selects = false
await $.command.run({ command: 'iui', args: '' } as any)
await drawAnswer($, w, 'ans-1', SMALL_MD, null)
w.foreign(COPY)
- await w.clock.advance(HINT_WAIT_MS)
+ await w.clock.settle()
expect(w.copies).toEqual([])
- expect(w.toasts.filter(t => t === GRAB_HINT)).toEqual([GRAB_HINT])
- w.copy(COPY)
+ expect(hints(w)).toBe(1)
+ await $.command.run({ command: 'cp', args: COPY } as any)
await w.clock.settle()
expect(w.copies).toEqual([COPIED])
- const details = await $.command.run({ command: 'iui', args: 'details' } as any)
- expect(details.text).toContain('\nAuto copy: on')
+ expect(hints(w)).toBe(1)
+ expect(await detailLines($)).toEqual(['Picture select: on in fullscreen (the screen is not known yet)', '/iui grab hint: on'])
// No advice: the layout is not known.
expect(w.toasts).not.toContain(FULLSCREEN_TOAST)
})
@@ -1398,12 +1196,13 @@ test('the fullscreen advice is not shown in fullscreen', async ($, on) => {
expect(w.toasts).not.toContain(FULLSCREEN_TOAST)
})
-test('the fullscreen advice is not shown where no picture draws (tmux)', async ($, on) => {
+test('the fullscreen advice is not shown where no picture draws (tmux); picture select is off there', async ($, on) => {
const w = world(on, { env: { HOME: '/h', CLAUDE_CODE_FORCE_TERMINAL_IMAGES: '1', TMUX: '/tmp/tmux-501/default,1,0' } })
await $.command.run({ command: 'iui', args: '' } as any)
await drawAnswer($, w, 'ans-1', SMALL_MD, false)
expect(w.compiles).toEqual([])
expect(w.toasts).not.toContain(FULLSCREEN_TOAST)
+ expect((await detailLines($))[0]).toBe('Picture select: off (no pictures drawn from files here)')
})
test('the fullscreen advice is not shown with Intelligent UI off', async ($, on) => {
@@ -1497,6 +1296,71 @@ test('picture select: a drag swaps the page\'s picture for a frame of its select
expect(w.reads.filter(r => r.endsWith('/a-1.png')).length).toBe(1)
})
+test('picture select: a page drawn is built and its words probed in the background, before any down; the copy at the up runs no probe', async ($, on) => {
+ const w = world(on, { tty: TTY })
+ await $.command.run({ command: 'iui', args: '' } as any)
+ const ui = await drawAnswer($, w)
+ expect(w.reads.filter(r => r.endsWith('/a-1.png')).length).toBe(1)
+ expect(w.queries.map(q => q.page)).toEqual(['1'])
+ // No frame or blit until a selection.
+ expect(w.frames).toEqual([])
+ await ui.pointer({ type: 'down', x: 0, y: 1, button: 'left', in: 'sel0' })
+ await ui.pointer({ type: 'move', x: 10, y: 2, button: 'left', in: 'sel0' })
+ await ui.pointer({ type: 'up', x: 21, y: 3, button: 'left', in: 'sel0' })
+ await settle(w)
+ expect(w.copies).toEqual([COPIED])
+ expect(w.queries.length).toBe(1)
+ expect(w.reads.filter(r => r.endsWith('/a-1.png')).length).toBe(1)
+})
+
+test('picture select: with the background probe still running, the copy at the up waits for it and gets the same text', async ($, on) => {
+ const w = world(on, { tty: TTY })
+ await $.command.run({ command: 'iui', args: '' } as any)
+ w.hold()
+ const ui = await drawAnswer($, w)
+ expect(w.queries.length).toBe(1)
+ await ui.pointer({ type: 'down', x: 0, y: 1, button: 'left', in: 'sel0' })
+ await ui.pointer({ type: 'move', x: 10, y: 2, button: 'left', in: 'sel0' })
+ await ui.pointer({ type: 'up', x: 21, y: 3, button: 'left', in: 'sel0' })
+ await settle(w)
+ expect(w.copies).toEqual([])
+ w.release()
+ await settle(w)
+ expect(w.copies).toEqual([COPIED])
+ // One probe run for the background and the copy.
+ expect(w.queries.length).toBe(1)
+})
+
+test('picture select: only the pages on screen are built and probed; a page that comes on screen is, once', async ($, on) => {
+ const w = world(on, { tty: TTY })
+ await $.command.run({ command: 'iui', args: '' } as any)
+ const off = { ...props(long), onScreen: null }
+ const ui = await $.ui.mount({ ...message('ans-1', long), props: off })
+ await w.clock.settle()
+ await ui.redraw(off)
+ await settle(w)
+ await w.clock.advance(300)
+ await settle(w)
+ const pages = pagesOf(w)
+ expect(pages).toBeGreaterThan(2)
+ const pngReads = () => w.reads.filter(r => /\/a-\d+\.png$/.test(r)).map(r => r.replace(/^.*\//, ''))
+ expect(pngReads()).toEqual([])
+ expect(w.queries).toEqual([])
+ // 16 rows a page under the top margin: page 2 is rows 17 to 32.
+ const of = 1 + 16 * pages
+ await ui.redraw({ ...props(long), onScreen: { first: 17, last: 32, of } })
+ await settle(w)
+ expect(pngReads()).toEqual(['a-2.png'])
+ expect(w.queries.map(q => q.page)).toEqual(['2'])
+ // Scrolled up to page 1, then back: page 1 once, page 2 not again.
+ await ui.redraw({ ...props(long), onScreen: { first: 0, last: 16, of } })
+ await settle(w)
+ await ui.redraw({ ...props(long), onScreen: { first: 17, last: 32, of } })
+ await settle(w)
+ expect(pngReads()).toEqual(['a-2.png', 'a-1.png'])
+ expect(w.queries.map(q => q.page)).toEqual(['2', '1'])
+})
+
test('picture select: a fast drag folds into few frames, the last one the newest selection', async ($, on) => {
const w = world(on, { tty: TTY })
await $.command.run({ command: 'iui', args: '' } as any)
@@ -1555,7 +1419,16 @@ test('picture select: with IUI_DEBUG, each post writes a trace line (the post, i
expect(lines[1]).toContain('anchor 0,1 head 10,2 size ')
expect(lines[1]).toContain('rows p0 1..2 (2)')
const blit = w.traces.find(t => t.includes('select: blit '))
- expect(blit).toMatch(/select: blit ans-1 page 0 rows 1\.\.2 \(2\) decode \d+ms frame \d+ms write \d+ms \d+ bytes blit \d+ms/)
+ expect(blit).toMatch(/select: blit ans-1 page 0 rows 1\.\.2 \(2\) wait \d+ms frame \d+ms write \d+ms \d+ bytes blit \d+ms/)
+ // The page's cache, built when it was drawn: its build and its words.
+ expect(w.traces.some(t => /select: cache start [0-9a-f]+\/a-1\.png \(read \d+ms, 0 queued\)/.test(t))).toBe(true)
+ const built = w.traces.find(t => t.includes('select: cache built '))
+ expect(built).toMatch(/select: cache built [0-9a-f]+\/a-1\.png 1568x512 ready in \d+ms, done in \d+ms \(read \d+ms, \d+ slices, max [\d.]+ms, p95 [\d.]+ms\); 1 pages kept, \d+ MB, 0 queued/)
+ expect(w.traces.some(t => /select: words ans-1 page 0 \d+ words in \d+ms \(background\)/.test(t))).toBe(true)
+ // The up: its copy, with the words there already.
+ await ui.pointer({ type: 'up', x: 21, y: 3, button: 'left', in: 'sel0' })
+ await settle(w)
+ expect(w.traces.find(t => t.includes('select: copy '))).toMatch(/select: copy 35 chars \d+ms after the up \(text \d+ms, words cached\); no native selection/)
})
test('picture select: with no IUI_DEBUG, a post writes no trace line', async ($, on) => {
diff --git a/tests/linux.test.ts b/tests/linux.test.ts
index 9c93de0..79ae9f3 100644
--- a/tests/linux.test.ts
+++ b/tests/linux.test.ts
@@ -1,12 +1,11 @@
import { expect, mock, test } from 'claude-code/testing'
import {
- autoCopyText, clipToolsOf, clipWayOf, editorArgv, familyOfFc, FIND_SH, GHOSTTY_DEFAULT_FONT, GTK_READ_PY, GTK_WATCH_PY, guiEditorOf, LINUX_EDITORS,
- placeholderCell, schemeOfPortal, SETUP_NOT_MAC, WATCH_PL, WL_WATCH_SH, X11_WATCH_SH, type ClipWay, type ShimState,
+ clipToolsOf, clipWayOf, editorArgv, familyOfFc, FIND_SH, GHOSTTY_DEFAULT_FONT, GTK_READ_PY, GTK_WATCH_PY, guiEditorOf, hintText, LINUX_EDITORS,
+ placeholderCell, schemeOfPortal, SETUP_NOT_MAC, WATCH_PL, WL_WATCH_SH, X11_WATCH_SH, type ClipWay,
} from '../hooks/register'
import { CACHE_SH } from '../hooks/lib/env'
-import { ANSWER_SH, ASK_END_SH, ASK_PL, clipboardNow, clipWatchArgs, clipWayReady, findClipWay, SHIM_SETUP } from '../hooks/lib/clipboard'
-import { ASKED_MS, HINT_WAIT_MS } from '../hooks/lib/settings'
+import { clipboardNow, clipWatchArgs, clipWayReady, findClipWay } from '../hooks/lib/clipboard'
import { S } from '../hooks/lib/state'
import { SMALL_MARKS, SMALL_MD } from './copy-fixture'
@@ -76,38 +75,32 @@ test('the GTK scripts: X11 events, a line at the start, a text read that fails w
expect(GTK_READ_PY).toContain('if t is None: sys.exit(1)')
})
-test('the automatic copy line: the shims and the ask reader say on or off; the watcher only the /iui grab hint', () => {
- const base = {
- isMac: true, hostOs: 'Darwin', isRemote: false, isOn: true, isFullscreen: true as boolean | null, none: false, drawn: true, asking: true, way: null,
- shims: { tools: ['pbcopy'] } as ShimState | null,
- }
- expect(autoCopyText(base)).toBe('on')
- // Only fullscreen copies by itself: the main screen has /iui grab.
- expect(autoCopyText({ ...base, isFullscreen: false })).toBe('off on the main screen (use /iui grab)')
- expect(autoCopyText({ ...base, isFullscreen: false, isOn: false })).toBe('off (Intelligent UI is off)')
- // The layout not known yet: the ask says whose copy it is, so it is on.
- expect(autoCopyText({ ...base, isFullscreen: null })).toBe('on')
- // The shims: not set up yet, or off with the reason.
- expect(autoCopyText({ ...base, shims: null })).toBe('off (the clipboard shims are not set up yet)')
- expect(autoCopyText({ ...base, shims: { off: 'no pbcopy' } })).toBe('off (no pbcopy)')
- expect(autoCopyText({ ...base, shims: { off: 'no perl' } })).toBe('off (no perl)')
- expect(autoCopyText({ ...base, shims: { off: 'no pbcopy' }, isRemote: true })).toBe('off (ssh)')
- expect(autoCopyText({ ...base, isFullscreen: null, drawn: false })).toBe('off (no picture yet)')
- expect(autoCopyText({ ...base, asking: false })).toBe('off (the ask reader does not run)')
- expect(autoCopyText({ ...base, none: true })).toBe('on (no /iui grab hint: no PerlObjCBridge in /usr/bin/perl)')
- expect(autoCopyText({ ...base, isRemote: true })).toBe('off (ssh)')
+test('the /iui grab hint line: on when the watcher sees the changes, else off with the reason', () => {
+ const base = { isMac: true, hostOs: 'Darwin', isRemote: false, isOn: true, none: false, drawn: true, running: true, way: null as ClipWay | null }
+ expect(hintText(base)).toBe('on')
+ expect(hintText({ ...base, isMac: false, hostOs: 'FreeBSD' })).toBe('off (not macOS or Linux)')
+ expect(hintText({ ...base, isRemote: true })).toBe('off (ssh)')
+ expect(hintText({ ...base, isOn: false })).toBe('off (Intelligent UI is off)')
+ expect(hintText({ ...base, none: true })).toBe('off (no PerlObjCBridge in /usr/bin/perl)')
+ expect(hintText({ ...base, drawn: false })).toBe('off (no picture yet)')
+ expect(hintText({ ...base, running: false })).toBe('off (the watcher does not run)')
+ // ssh first, then Intelligent UI off, then the bridge, then no picture.
+ expect(hintText({ ...base, isRemote: true, isOn: false, none: true })).toBe('off (ssh)')
+ expect(hintText({ ...base, isOn: false, none: true, drawn: false })).toBe('off (Intelligent UI is off)')
+ expect(hintText({ ...base, none: true, drawn: false })).toBe('off (no PerlObjCBridge in /usr/bin/perl)')
const wl = clipWayOf({ wayland: true, x11: false, desktop: 'sway', found: ALL })
const linux = { ...base, isMac: false, hostOs: 'Linux', way: wl }
- expect(autoCopyText(linux)).toBe('on, with wl-paste --watch (Wayland)')
- expect(autoCopyText({ ...linux, none: true })).toBe('on (no /iui grab hint: wl-paste --watch (Wayland) stopped: the compositor may not have the data-control protocol)')
- expect(autoCopyText({ ...linux, way: clipWayOf({ wayland: false, x11: true, desktop: '', found: ALL }), none: true })).toBe('on (no /iui grab hint: clipnotify and xclip (X11) stopped)')
- expect(autoCopyText({ ...linux, way: { off: 'no Wayland or X11 display' } })).toBe('on (no /iui grab hint: no Wayland or X11 display)')
- expect(autoCopyText({ ...linux, way: null })).toBe('on')
- const addon = { off: 'no wl-copy, xclip or xsel: Claude Code copies with its own addon' }
- expect(autoCopyText({ ...linux, shims: addon })).toBe('off (no wl-copy, xclip or xsel: Claude Code copies with its own addon)')
- expect(autoCopyText({ ...linux, drawn: false })).toBe('off (no picture yet)')
- expect(autoCopyText({ ...linux, isFullscreen: false })).toBe('off on the main screen (use /iui grab)')
- expect(autoCopyText({ ...linux, hostOs: 'FreeBSD' })).toBe('off (not macOS or Linux)')
+ expect(hintText(linux)).toBe('on, with wl-paste --watch (Wayland)')
+ expect(hintText({ ...linux, none: true })).toBe('off (wl-paste --watch (Wayland) stopped: the compositor may not have the data-control protocol)')
+ expect(hintText({ ...linux, way: clipWayOf({ wayland: false, x11: true, desktop: '', found: ALL }), none: true })).toBe('off (clipnotify and xclip (X11) stopped)')
+ expect(hintText({ ...linux, way: { off: 'no Wayland or X11 display' } })).toBe('off (no Wayland or X11 display)')
+ expect(hintText({ ...linux, way: null })).toBe('off (the clipboard tools are not looked up yet)')
+ // On Linux: ssh first, then the way, then Intelligent UI off.
+ expect(hintText({ ...linux, isRemote: true, way: null })).toBe('off (ssh)')
+ expect(hintText({ ...linux, way: { off: 'no wl-paste (install wl-clipboard)' }, isOn: false })).toBe('off (no wl-paste (install wl-clipboard))')
+ expect(hintText({ ...linux, drawn: false })).toBe('off (no picture yet)')
+ expect(hintText({ ...linux, running: false })).toBe('off (the watcher does not run)')
+ expect(hintText({ ...linux, isOn: false })).toBe('off (Intelligent UI is off)')
})
// A $ whose process.run answers `got` (or throws) and whose env.get reads `env`; `argvs` keeps each call.
@@ -227,51 +220,32 @@ const cells = (row: number, from: number, to: number, lead = ' ') =>
// A Linux computer in kitty on Wayland (sway): uname says Linux, the tools
// are wl-paste only, the portal says `scheme`, kitty's config names no font
// (fontconfig gives one), and the watcher is `perl` with the notifier after
-// `clip`. The clipboard write tools found are `writers` (wl-copy by default),
-// with perl and the FIFO L_ASK; the ask reader is `perl` too. `copy` is
-// Claude Code's own copy: the OSC 52 write, then the shim, whose ask for
-// picture cells the reader gets and the mod answers (ANSWER_SH). `foreign`
-// is a copy with no ask (another session's, the terminal's): each changes
-// the clipboard, and each clip child prints a line.
-function linuxWorld(on: any, o: { scheme?: number; noPortal?: boolean; env?: Record<string, string>; noTypst?: boolean; jetbrains?: boolean; writers?: string[] } = {}) {
+// `clip`. `copy` is a native copy (in fullscreen picture cells are this
+// session's selection too), `foreign` another session's or the terminal's:
+// each changes the clipboard, and each clip child prints a line. `copies`
+// are the texts the mod put on the clipboard; `envSets` the env vars set.
+function linuxWorld(on: any, o: { scheme?: number; noPortal?: boolean; env?: Record<string, string>; noTypst?: boolean; jetbrains?: boolean } = {}) {
mock.store(on)
const clock = mock.clock(on)
const vars: Record<string, string | undefined> = {
- PATH: '/usr/local/bin:/usr/bin', IUI_COPY_SHIM: '1', ...(o.env ?? { HOME: '/h', TERM: 'xterm-kitty', KITTY_WINDOW_ID: '1', WAYLAND_DISPLAY: 'wayland-1', XDG_CURRENT_DESKTOP: 'sway' }),
+ PATH: '/usr/local/bin:/usr/bin', ...(o.env ?? { HOME: '/h', TERM: 'xterm-kitty', KITTY_WINDOW_ID: '1', WAYLAND_DISPLAY: 'wayland-1', XDG_CURRENT_DESKTOP: 'sway' }),
}
+ const envSets: string[] = []
on('env.get', async ($: any, e: any) => ({ value: vars[e.name] }))
on('env.set', async ($: any, e: any) => {
- vars[e.name] = e.value
+ envSets.push(e.name)
return { value: {} }
})
const files = new Map<string, string>()
const ran: string[][] = []
const watchers: { argv: string[]; say: (line: string) => void; dead: boolean; n: number }[] = []
- const readers: { argv: string[]; say: (line: string) => void; dead: boolean }[] = []
- const waits = new Map<string, (text: string) => void>()
const w = {
- clock, files, ran, watchers, readers, vars, clipboard: 'old', reads: 0, asks: 0, copies: [] as string[], toasts: [] as string[], ended: [] as string[][],
+ clock, files, ran, watchers, vars, envSets, clipboard: 'old', reads: 0, copies: [] as string[], toasts: [] as string[],
selection: undefined as { text: string } | undefined,
copy(text: string) {
// A mouse copy of picture cells in fullscreen is this session's selection.
if (text.includes('\u{10EEEE}')) w.selection = { text }
w.foreign(text)
- void w.shim(text)
- },
- async shim(text: string) {
- let out = text
- const reader = readers.find(c => !c.dead)
- if (text.includes('\u{10EEEE}') && reader) {
- const id = `77-${++w.asks}-1`
- files.set(`/c/ask/${id}`, text)
- const answered = new Promise<string | null>(r => waits.set(id, r))
- reader.say(`ask ${id}`)
- out = (await Promise.race([answered, clock.sleep(1500).then(() => null)])) ?? text
- waits.delete(id)
- files.delete(`/c/ask/${id}`)
- }
- if (out !== text) w.copies.push(out)
- w.foreign(out)
},
foreign(text: string) {
w.clipboard = text
@@ -297,19 +271,6 @@ function linuxWorld(on: any, o: { scheme?: number; noPortal?: boolean; env?: Rec
await new Promise<void>(r => (wake = r))
}
}
- if (argv[0] === 'perl' && argv[1] === '-e' && argv[2] === ASK_PL && argv[3] === L_ASK) {
- const pid = String(pids++)
- const lines = [`pid ${pid}`]
- let wake = () => {}
- const me = { argv, dead: false, say: (line: string) => (lines.push(line), wake()) }
- readers.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 } }
yield { stream: 'stdout', text: `${pids++}\n` }
const typst = argv.slice(4)
@@ -329,23 +290,6 @@ function linuxWorld(on: any, o: { scheme?: number; noPortal?: boolean; env?: Rec
if (/cc-intelligent-ui-/.test(cmd)) return ok('/c\nLinux\n/h/.cache/cc-intelligent-ui/designs\n')
if (cmd.includes('command -v typst')) return o.noTypst ? ok('', 1) : ok('/usr/bin/typst\n')
if (argv[0] === 'sh' && argv[2] === FIND_SH) return ok('wl-paste /usr/bin/wl-paste\n')
- if (argv[0] === 'sh' && argv[1]?.endsWith(SHIM_SETUP) && argv[2] === 'find') {
- return ok(`pid 77\n${(o.writers ?? ['wl-copy']).map(t => `${t} /usr/bin/${t}\n`).join('')}perl /usr/bin/perl\nask ${L_ASK}\n`)
- }
- if (argv[0] === 'sh' && argv[2] === ANSWER_SH) {
- const to = waits.get(argv[4]!.slice('/c/ask/'.length))
- if (!to) return ok('', 1)
- to(e.init?.stdin ?? '')
- return ok('')
- }
- if (argv[0] === 'sh' && argv[2] === ASK_END_SH) {
- w.ended.push(argv.slice(4))
- return ok('')
- }
- if (argv[0] === 'sh' && argv[1]?.endsWith(SHIM_SETUP) && argv[2] === 'install') {
- for (const f of argv.slice(5)) files.set(f, files.get(`${f}${argv[4]}`) ?? '')
- return ok('')
- }
if (argv[0] === '/usr/bin/typst' && argv[1] === 'eval') return ok('{}')
if (cmd.includes('od -An')) return ok(argv.filter(a => a.endsWith('.png')).map(() => `${HEAD}\n@\n`).join(''))
if (argv[0] === 'gdbus') return o.noPortal ? ok('', 1) : ok(`(<<uint32 ${o.scheme ?? 1}>>,)\n`)
@@ -363,18 +307,17 @@ function linuxWorld(on: any, o: { scheme?: number; noPortal?: boolean; env?: Rec
files.set(e.path, e.text)
return { value: undefined }
})
- on('fs.stat', async ($: any, e: any, next: any) =>
- e.path.startsWith('/c/ask/') && files.has(e.path) ? { value: { kind: 'file', size: 1, mtimeMs: 1, isLink: false } } : next(e))
- on('fs.read', async ($: any, e: any, next: any) => (e.path.endsWith('/hooks/clip-shim.sh') ? { value: 'tool=@TOOL@ real=@REAL@' } : files.has(e.path) ? { value: files.get(e.path) } : e.path.startsWith('/c/') || e.path.startsWith('/h/') ? { deny: 'ENOENT' } : next(e)))
+ on('fs.read', async ($: any, e: any, next: any) => (files.has(e.path) ? { value: files.get(e.path) } : e.path.startsWith('/c/') || e.path.startsWith('/h/') ? { deny: 'ENOENT' } : next(e)))
on('fs.exists', async ($: any, e: any, next: any) => (o.noTypst || e.path.startsWith('/h/') ? { value: false } : next(e)))
on('fs.list', async ($: any, e: any, next: any) => {
if (!e.path.startsWith('/c/')) return next(e)
const segments = (JSON.parse(files.get(`${e.path}/doc.json`) ?? '{"segments":[""]}') as { segments: string[] }).segments
return { value: segments.map((_, i) => ({ name: `a-${i + 1}.png`, kind: 'file', size: 1, mtimeMs: 1, isLink: false })) }
})
+ // The mod's write: its text on the clipboard, one change.
on('ui.copy', async ($: any, e: any) => {
w.copies.push(e.text)
- w.copy(e.text)
+ w.foreign(e.text)
return { value: { isCopied: true } }
})
on('ui.selection', async () => ({ value: w.selection }))
@@ -387,100 +330,82 @@ function linuxWorld(on: any, o: { scheme?: number; noPortal?: boolean; env?: Rec
return w
}
-// The FIFO of this process (pid 77).
-const L_ASK = '/c/ask-77'
-
const message = (requestId: string, text: string, isFullscreen = true) =>
({
plugin: 'cc-intelligent-ui', surface: 'terminal', component: 'AssistantMessage', requestId,
props: { text, isFirstOfReply: true }, viewport: { columns: 100, rows: 40, isFullscreen },
}) as any
-const autoLine = async ($: any) => ((await $.command.run({ command: 'iui', args: 'details' } as any)).text ?? '').split('\n').find((l: string) => l.startsWith('Auto copy:'))
+const hintLine = async ($: any) => ((await $.command.run({ command: 'iui', args: 'details' } as any)).text ?? '').split('\n').find((l: string) => l.startsWith('/iui grab hint:'))
+const GRAB_HINT = 'Intelligent UI: picture cells copied; /iui grab puts their text on the clipboard'
+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('Linux on Wayland: the reader (perl) gets the asks of the wl-copy shim, and the watcher runs wl-paste --watch after clip for the hint', async ($, on) => {
- const w = linuxWorld(on)
- await $.command.run({ command: 'iui', args: '' } as any)
- expect(await autoLine($)).toBe('Auto copy: off (no picture yet)')
- const ui = await $.ui.mount(message('ans-1', SMALL_MD))
+// Draws SMALL_MD as answer ans-1; the watcher has its clipboard part.
+async function drawAnswer($: any, w: ReturnType<typeof linuxWorld>, isFullscreen = true) {
+ const ui = await $.ui.mount(message('ans-1', SMALL_MD, isFullscreen))
await w.clock.settle()
await ui.redraw({ text: SMALL_MD, isFirstOfReply: true } as any)
await w.clock.settle()
await w.clock.advance(300)
await w.clock.settle()
+ return ui
+}
+
+test('Linux on Wayland: the watcher runs wl-paste --watch after clip; picture cells copied get the /iui grab hint, and no shim is set up', async ($, on) => {
+ const w = linuxWorld(on)
+ await $.command.run({ command: 'iui', args: '' } as any)
+ expect(await hintLine($)).toBe('/iui grab hint: off (no picture yet)')
+ await drawAnswer($, w)
// The size watcher (perl from the PATH), then the one with the notifier.
expect(w.watchers.map(c => c.argv.slice(3))).toEqual([[], ['clip', '/usr/bin/wl-paste', '--watch', 'sh', '-c', WL_WATCH_SH]])
- expect(w.readers.map(c => c.argv[0])).toEqual(['perl'])
- expect(await autoLine($)).toBe('Auto copy: on, with wl-paste --watch (Wayland)')
+ expect(await hintLine($)).toBe('/iui grab hint: on, with wl-paste --watch (Wayland)')
// The first line (the notifier's start) is not a change: no read.
expect(w.reads).toBe(0)
- w.copy([cells(1, 0, 97, '● '), cells(2, 0, 97), cells(3, 0, 21)].join('\n'))
+ // A native copy of picture cells: one read, one hint, never written.
+ w.copy(COPY)
await w.clock.settle()
- expect(w.copies).toEqual(['Copy test\nThe quick brown fox jumps'])
- expect(w.toasts.some(t => t.startsWith('Intelligent UI: copied'))).toBe(true)
+ expect(w.reads).toBe(1)
+ expect(w.toasts.filter(t => t === GRAB_HINT).length).toBe(1)
+ expect(w.copies).toEqual([])
// A copy with no picture cells is read and left as it is.
w.copy('plain text')
await w.clock.settle()
- expect(w.copies.length).toBe(1)
- // Another session's copy of picture cells (no ask here, none of them lately): never written, one hint after the wait.
- await w.clock.advance(ASKED_MS)
- w.foreign([cells(1, 0, 97), cells(2, 0, 97), cells(3, 0, 21)].join('\n'))
- await w.clock.advance(HINT_WAIT_MS)
- expect(w.copies.length).toBe(1)
- expect(w.toasts).toContain('Intelligent UI: picture cells copied; /iui grab puts their text on the clipboard')
+ expect(w.reads).toBe(2)
+ expect(w.toasts.filter(t => t === GRAB_HINT).length).toBe(1)
+ // /iui grab copies the text of the selection.
+ expect((await $.command.run({ command: 'iui', args: 'grab' } as any)).text).toBe('Intelligent UI: copied 35 chars (1 of 1 picture runs read).')
+ expect(w.copies).toEqual([COPIED])
// pbpaste is never run on Linux.
expect(w.ran.some(argv => argv[0] === 'pbpaste')).toBe(false)
- // The wl-copy shim only (the tool found), its folder first on PATH.
- expect([...w.files.keys()].filter(k => k.startsWith('/c/shims') && !k.includes('.new-'))).toEqual(['/c/shims-77/wl-copy'])
- expect(w.vars.PATH).toBe('/c/shims-77:/usr/local/bin:/usr/bin')
- expect(w.vars.IUI_COPY_ASK).toBe(L_ASK)
- // The end of the session: the FIFO, the requests and the shims of pid 77 go.
+ // No shim: no env var set, no shim files, no ask reader.
+ expect(w.envSets).toEqual([])
+ expect(w.vars.PATH).toBe('/usr/local/bin:/usr/bin')
+ expect([...w.files.keys()].filter(k => /\/(shims-|ask)/.test(k))).toEqual([])
+ expect(w.ran.some(argv => argv.some(a => a.includes('clip-shim')))).toBe(false)
+ // The end of the session: the watchers stop.
await $.session.end({ reason: 'prompt_input_exit', sessionId: 's1' } as any)
await w.clock.settle()
- expect(w.ended).toEqual([[L_ASK, '/c/ask', '77', '/c/shims-77']])
- expect(w.readers.map(c => c.dead)).toEqual([true])
-})
-
-test('Linux with no wl-copy, xclip or xsel: Claude Code copies with its addon, so no shim, no automatic copy; the hint and /iui grab stay', async ($, on) => {
- const w = linuxWorld(on, { writers: [] })
- await $.command.run({ command: 'iui', args: '' } as any)
- const ui = await $.ui.mount(message('ans-1', SMALL_MD))
- await w.clock.settle()
- await ui.redraw({ text: SMALL_MD, isFirstOfReply: true } as any)
- await w.clock.settle()
- await w.clock.advance(300)
- await w.clock.settle()
- expect(await autoLine($)).toBe('Auto copy: off (no wl-copy, xclip or xsel: Claude Code copies with its own addon)')
- expect(w.vars.PATH).toBe('/usr/local/bin:/usr/bin')
- expect(w.vars.IUI_COPY_ASK).toBeUndefined()
- expect(w.readers).toEqual([])
- w.copy([cells(1, 0, 97), cells(2, 0, 97), cells(3, 0, 21)].join('\n'))
- await w.clock.advance(HINT_WAIT_MS)
- expect(w.copies).toEqual([])
- expect(w.toasts).toContain('Intelligent UI: picture cells copied; /iui grab puts their text on the clipboard')
- w.selection = undefined
- 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).')
+ expect(w.watchers.map(c => c.dead)).toEqual([true, true])
})
test('Linux on Wayland, main screen: a copy of picture cells is not changed; /iui grab reads it with wl-paste and writes its text', async ($, on) => {
const w = linuxWorld(on)
await $.command.run({ command: 'iui', args: '' } as any)
- const ui = await $.ui.mount(message('ans-1', SMALL_MD, false))
- await w.clock.settle()
- await ui.redraw({ text: SMALL_MD, isFirstOfReply: true } as any)
- await w.clock.settle()
- await w.clock.advance(300)
- await w.clock.settle()
- expect(await autoLine($)).toBe('Auto copy: off on the main screen (use /iui grab)')
- // The terminal's own copy: no ask, the hint at once.
- w.foreign([cells(1, 0, 97, '● '), cells(2, 0, 97), cells(3, 0, 21)].join('\n'))
+ await drawAnswer($, w, false)
+ expect(await hintLine($)).toBe('/iui grab hint: on, with wl-paste --watch (Wayland)')
+ // The terminal's own copy: the hint at once.
+ w.foreign(COPY)
await w.clock.settle()
expect(w.copies).toEqual([])
- expect(w.toasts).toContain('Intelligent UI: picture cells copied; /iui grab puts their text on the clipboard')
+ expect(w.toasts).toContain(GRAB_HINT)
+ const reads = w.reads
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).')
- expect(w.copies).toEqual(['Copy test\nThe quick brown fox jumps'])
+ expect(w.reads).toBe(reads + 2)
+ expect(w.copies).toEqual([COPIED])
+ expect(w.clipboard).toBe(COPIED)
+ expect(w.toasts.filter(t => t === GRAB_HINT).length).toBe(1)
})
test('Linux, auto, in kitty: kitty\'s config comes first; the font is fontconfig\'s monospace', async ($, on) => {
@@ -543,4 +468,8 @@ test('the cache folder: TMPDIR, else /tmp (Linux often has no TMPDIR); the desig
expect(CACHE_SH).toContain('d="${TMPDIR:-/tmp}"; d="${d%/}/cc-intelligent-ui-$(id -u)"')
expect(CACHE_SH).toContain('g="${XDG_CACHE_HOME:-$HOME/.cache}/cc-intelligent-ui/designs"')
expect(CACHE_SH).toContain('"$(uname -s)"')
+ // A folder that is not private: only the OS name. No shim or ask folder is swept.
+ expect(CACHE_SH).toContain('[ ! -L "$d" ] && [ -d "$d" ] && [ -O "$d" ] && chmod 700 "$d"')
+ expect(CACHE_SH).toContain(`|| printf '\\n%s\\n\\n' "$(uname -s)"`)
+ expect(CACHE_SH).not.toMatch(/ask|shims/)
})
diff --git a/tests/pagecache.test.ts b/tests/pagecache.test.ts
new file mode 100644
index 0000000..7386f97
--- /dev/null
+++ b/tests/pagecache.test.ts
@@ -0,0 +1,217 @@
+import { expect, test } from 'claude-code/testing'
+
+// The hooks module first, as the engine loads it (its modules import each other).
+import '../hooks/register'
+import {
+ evictKeys, forgetPages, keyOf, needFrames, nextWant, notePages, pages, pagesOnScreen, PROMOTED_SLICE_MS, quantile, SLICE_MS, sliceOf, type Want,
+} from '../hooks/lib/pagecache'
+import { framesOf, frameOf, rgbOf } from '../hooks/lib/frames'
+import { chunk, concat, decodePng, deflatePiece, headOf, tailOf, toBase64 } from '../hooks/lib/png'
+import type { Drawn, DrawnPage } from '../hooks/lib/copy'
+
+const COLOR = '#264f78'
+
+// ---- The queue -------------------------------------------------------------
+
+const want = (key: string, o: Partial<Want> = {}): Want =>
+ ({ key, page: { file: `/c/k/${key}.png`, width: 16, height: 16, columns: 2, rows: 2 }, color: COLOR, id: 'a', index: 0, seq: 1, onScreen: true, promoted: 0, ...o })
+
+test("the next page: the last down's first, then the pages on screen, the newest drawing first, its pages in order", () => {
+ const all = [
+ want('old-0', { seq: 1, index: 0 }), want('new-1', { seq: 2, index: 1 }), want('new-0', { seq: 2, index: 0 }), want('off', { seq: 3, onScreen: false }),
+ ]
+ expect(nextWant(all)?.key).toBe('new-0')
+ expect(nextWant(all.filter(w => !w.key.startsWith('new')))?.key).toBe('old-0')
+ expect(nextWant([want('off', { seq: 3, onScreen: false })])?.key).toBe('off')
+ // A down's page goes first, whatever its drawing; the last down before an older one.
+ expect(nextWant([...all, want('down-1', { seq: 0, promoted: 1 })])?.key).toBe('down-1')
+ expect(nextWant([...all, want('down-1', { promoted: 1 }), want('down-2', { promoted: 2 })])?.key).toBe('down-2')
+ expect(nextWant([])).toBeUndefined()
+})
+
+test('the pages kept fit their budget: the oldest off screen go first, then the oldest on screen; the page just built never', () => {
+ const kept = [
+ { key: 'a', bytes: 40, onScreen: true }, { key: 'b', bytes: 40, onScreen: false }, { key: 'c', bytes: 40, onScreen: true }, { key: 'd', bytes: 40, onScreen: false },
+ ]
+ expect(evictKeys(kept, 160, 'd')).toEqual([])
+ expect(evictKeys(kept, 120, 'd')).toEqual(['b'])
+ expect(evictKeys(kept, 80, 'd')).toEqual(['b', 'a'])
+ expect(evictKeys(kept, 40, 'a')).toEqual(['b', 'd', 'c'])
+ expect(evictKeys(kept, 0, 'c')).toEqual(['b', 'd', 'a'])
+})
+
+test('the pages on screen: by the rows of the message on screen and the page tops; all when not known, none off screen', () => {
+ const page = (rows: number): DrawnPage => ({ file: `/c/k/a-${rows}.png`, width: 1568, height: rows * 32, columns: 98, rows })
+ const d: Drawn = { id: 'a', seq: 1, dir: '/c/k', pages: [page(16), page(16), page(4)], place: { top: 1, below: 0 } }
+ expect(pagesOnScreen(d)).toEqual([0, 1, 2])
+ expect(pagesOnScreen({ ...d, onScreen: null })).toEqual([])
+ // Under a top margin of 1: page 0 is rows 1 to 16, page 1 rows 17 to 32, page 2 rows 33 to 36.
+ expect(pagesOnScreen({ ...d, onScreen: { first: 0, last: 16, of: 37 } })).toEqual([0])
+ expect(pagesOnScreen({ ...d, onScreen: { first: 16, last: 17, of: 37 } })).toEqual([0, 1])
+ expect(pagesOnScreen({ ...d, onScreen: { first: 30, last: 36, of: 37 } })).toEqual([1, 2])
+})
+
+test("a slice: steps until its budget, never one that the last step's time says goes past it; one step at least", () => {
+ let t = 0
+ const now = () => t
+ // Each step takes 1.5 ms.
+ function* steps(n: number): Generator<string | undefined, string, void> {
+ for (let i = 0; i < n; i++) {
+ t += 1.5
+ yield i === 1 ? 'ready' : undefined
+ }
+ return 'done'
+ }
+ const b = { stepMs: 0 }
+ const seen: string[] = []
+ const s = steps(5)
+ // 1.5, then 3 (+ 1.5 would pass 4): two steps.
+ expect(sliceOf(s, 4, b, v => seen.push(v), now)).toEqual({ ms: 3 })
+ expect(seen).toEqual(['ready'])
+ expect(b.stepMs).toBe(1.5)
+ expect(sliceOf(s, 4, b, v => seen.push(v), now)).toEqual({ ms: 3 })
+ // The fifth step, then the end.
+ expect(sliceOf(s, 4, b, v => seen.push(v), now)).toEqual({ ms: 1.5, done: 'done' })
+ // A step longer than the budget: one step a slice.
+ const long = (function* (): Generator<undefined, string, void> {
+ t += 9
+ yield
+ return 'end'
+ })()
+ expect(sliceOf(long, 4, b, () => {}, now)).toEqual({ ms: 9 })
+ expect(sliceOf(long, 4, b, () => {}, now)).toEqual({ ms: 0, done: 'end' })
+ expect([SLICE_MS, PROMOTED_SLICE_MS]).toEqual([4, 8])
+ expect(quantile([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 0.95)).toBe(10)
+ expect(quantile([1, 2, 3, 4], 0.5)).toBe(2)
+})
+
+// ---- The scheduler -----------------------------------------------------------
+
+// A 1568 x 512 page (98 x 16 cells of 16 x 32), pixels of its number: a build of a few slices.
+const pngOf = (n: number) => {
+ const line = 1568 * 4 + 1
+ const raw = new Uint8Array(512 * line)
+ for (let y = 0; y < 512; y++) for (let x = 0; x < 1568; x++) if ((x + y + n) % 3 === 0) raw.set([n * 40, 210, 220, 255], y * line + 1 + x * 4)
+ const piece = deflatePiece(raw, 4, line)
+ return toBase64(concat([headOf(1568, 512), chunk('IDAT', piece.bytes), tailOf([piece])]))
+}
+const PNGS = [pngOf(0), pngOf(1), pngOf(2)]
+const pageOf = (n: number): DrawnPage => ({ file: `/c/k${n}/a-1.png`, width: 1568, height: 512, columns: 98, rows: 16 })
+const drawn = (id: string, seq: number, ns: number[], onScreen?: Drawn['onScreen']): Drawn => ({ id, seq, dir: `/c/${id}`, pages: ns.map(pageOf), place: { below: 0 }, onScreen })
+
+// The hooks beneath: `$.clock.after` queues its callback (a slice), which
+// `tick` runs with the promises after it; `$.fs.read` gives each page's PNG,
+// noting the read and the pages built at that time.
+function fake() {
+ forgetPages()
+ const timers: (() => void)[] = []
+ const reads: { file: string; built: string[] }[] = []
+ const $ = {
+ clock: { after: (_ms: number, fn: () => void) => (timers.push(fn), { cancel() {} }) },
+ fs: {
+ read: async (path: string) => {
+ reads.push({ file: path, built: [...pages.frames.keys()].map(k => k.split('|')[0]!) })
+ return { base64: PNGS[Number(/k(\d)\//.exec(path)![1])]! }
+ },
+ },
+ ui: { log: async () => undefined },
+ } as any
+ const flush = async () => {
+ for (let i = 0; i < 20; i++) await Promise.resolve()
+ }
+ const tick = async () => {
+ const fn = timers.shift()
+ if (!fn) return false
+ fn()
+ await flush()
+ return true
+ }
+ const drain = async () => {
+ for (let n = 0; n < 100000 && (await tick()); n++);
+ }
+ return { $, timers, reads, tick, drain, flush }
+}
+const files = (reads: { file: string }[]) => reads.map(r => r.file)
+
+test('the cache builds one page at a time, the pages on screen of the newest drawing first; each page is read once', async () => {
+ const f = fake()
+ notePages(f.$, drawn('old', 1, [0, 1]), COLOR)
+ notePages(f.$, drawn('new', 2, [2]), COLOR)
+ // One pump: one slice queued at a time.
+ expect(f.timers.length).toBe(1)
+ await f.drain()
+ expect(files(f.reads)).toEqual([pageOf(2).file, pageOf(0).file, pageOf(1).file])
+ // Each read began once the page before it was built.
+ expect(f.reads.map(r => r.built)).toEqual([[], [pageOf(2).file], [pageOf(2).file, pageOf(0).file]])
+ expect(pages.isPumping).toBe(false)
+ expect(pages.wants.size).toBe(0)
+ // Drawn again (or scrolled): nothing to build, nothing read.
+ notePages(f.$, drawn('old', 1, [0, 1]), COLOR)
+ await f.drain()
+ expect(f.reads.length).toBe(3)
+ // The frames are the ones made at once.
+ const one = framesOf(decodePng(Uint8Array.from(atob(PNGS[0]!), c => c.charCodeAt(0))), pageOf(0), rgbOf(COLOR))
+ const got = pages.frames.get(keyOf(pageOf(0), COLOR))!
+ const rows = [{ row: 2, x0: 5, x1: 97 }, { row: 3, x0: 0, x1: 97 }, { row: 4, x0: 0, x1: 40 }]
+ expect(toBase64(frameOf(got, rows))).toBe(toBase64(frameOf(one, rows)))
+})
+
+test('a down on a page not built: it goes first; the build it puts aside pauses, then goes on (its PNG read once)', async () => {
+ const f = fake()
+ notePages(f.$, drawn('a', 1, [0, 1]), COLOR)
+ // The read of page 0, then one slice of its decode.
+ await f.tick()
+ await f.tick()
+ expect(pages.build?.want.page.file).toBe(pageOf(0).file)
+ expect(pages.build?.isReady).toBe(false)
+ const order: string[] = []
+ const got = needFrames(f.$, pageOf(1), COLOR, { id: 'a', index: 1, seq: 1 }).then(r => (order.push('page 1'), r))
+ await f.flush()
+ expect(pages.wants.get(keyOf(pageOf(0), COLOR))?.paused).toBeDefined()
+ for (let n = 0; n < 100000 && !order.length && (await f.tick()); n++);
+ expect(order).toEqual(['page 1'])
+ expect((await got).frames?.img.width).toBe(1568)
+ expect(pages.frames.has(keyOf(pageOf(0), COLOR))).toBe(false)
+ await f.drain()
+ expect(files(f.reads)).toEqual([pageOf(0).file, pageOf(1).file])
+ expect(pages.frames.get(keyOf(pageOf(0), COLOR))?.plain.length).toBe(16)
+ // Built now: a down waits for nothing.
+ expect((await needFrames(f.$, pageOf(0), COLOR)).waitMs).toBe(0)
+})
+
+test('a page that leaves the screen leaves the queue and its build stops; a page a down asked for goes on', async () => {
+ const f = fake()
+ notePages(f.$, drawn('a', 1, [0, 1]), COLOR)
+ await f.tick()
+ await f.tick()
+ expect(pages.build?.want.page.file).toBe(pageOf(0).file)
+ notePages(f.$, drawn('a', 1, [0, 1], null), COLOR)
+ await f.drain()
+ expect(files(f.reads)).toEqual([pageOf(0).file])
+ expect(pages.frames.size).toBe(0)
+ expect(pages.isPumping).toBe(false)
+ // Asked for by a down, then off screen: built all the same.
+ const got = needFrames(f.$, pageOf(1), COLOR)
+ notePages(f.$, drawn('a', 1, [0, 1], null), COLOR)
+ await f.drain()
+ expect((await got).frames?.plain.length).toBe(16)
+ expect(files(f.reads)).toEqual([pageOf(0).file, pageOf(1).file])
+ // Back on screen: page 0 is built from the start.
+ notePages(f.$, drawn('a', 1, [0, 1]), COLOR)
+ await f.drain()
+ expect(files(f.reads)).toEqual([pageOf(0).file, pageOf(1).file, pageOf(0).file])
+ expect(pages.frames.size).toBe(2)
+})
+
+test('a page that can not be read gets no frames, is not tried again, and a down on it waits for nothing', async () => {
+ const f = fake()
+ f.$.fs.read = async () => {
+ throw new Error('ENOENT')
+ }
+ notePages(f.$, drawn('a', 1, [0]), COLOR)
+ await f.drain()
+ expect(pages.frames.get(keyOf(pageOf(0), COLOR))).toBeNull()
+ notePages(f.$, drawn('a', 1, [0]), COLOR)
+ await f.drain()
+ expect(await needFrames(f.$, pageOf(0), COLOR)).toEqual({ frames: null, waitMs: 0 })
+})
diff --git a/tests/shim-test.sh b/tests/shim-test.sh
deleted file mode 100755
index 0c2d770..0000000
--- a/tests/shim-test.sh
+++ /dev/null
@@ -1,529 +0,0 @@
-#!/bin/sh
-# Runs the clipboard shims (hooks/clip-shim.sh) against fake tools and a fake
-# mod (the reader of the ask FIFO), on macOS and Linux: what counts as a
-# clipboard write, the ask for picture cells and its limits, the bytes and
-# arguments the real tool gets, the exit status, and no recursion. Then the
-# setup script (hooks/clip-shim-setup.sh) and the cache sweep (CACHE_SH).
-# Usage: sh tests/shim-test.sh (also dash, bash --posix; exit 0 when all pass)
-set -u
-here=$(cd "$(dirname "$0")/.." && pwd)
-template=$here/hooks/clip-shim.sh
-tmp=$(mktemp -d "${TMPDIR:-/tmp}/iui-shim-test.XXXXXX")
-mod=
-trap '[ -z "$mod" ] || kill "$mod" 2>/dev/null; rm -rf "$tmp"' EXIT
-real=$tmp/real
-shims=$tmp/shims
-log=$tmp/log
-bin=$tmp/bin
-stub=$tmp/stub
-c=$tmp/c
-mkdir -p "$real" "$shims" "$log" "$bin" "$stub" "$c/ask"
-chmod 700 "$c" "$c/ask"
-# The mod's FIFO. `launch` names it for its own pid while a shim runs.
-fifo=$c/ask-mod
-mkfifo -m 600 "$fifo"
-pass=0
-fail=0
-
-ok() { pass=$((pass + 1)); }
-bad() { fail=$((fail + 1)); echo "FAIL: $*"; }
-
-# The tools the shims and the fake tools use, with no perl among them.
-for t in sh dash bash cat grep rm mv ln chmod basename dirname env sleep cp mkdir ls kill sed; do
- p=$(command -v "$t") && ln -s "$p" "$bin/$t"
-done
-perl=$(command -v perl)
-# A perl that notes each run, then runs the real one (the shims' @PERL@).
-printf '#!/bin/sh\necho run >>"%s/perl.runs"\nexec "%s" "$@"\n' "$log" "$perl" >"$stub/perl"
-chmod 755 "$stub/perl"
-P=$shims:$real:$bin
-
-# The fake real tools: they keep their arguments (one per line) and their
-# stdin, then exit with $FAKE_EXIT or die of $FAKE_SIG.
-for t in pbcopy wl-copy xclip xsel; do
- cat >"$real/$t" <<EOF
-#!/bin/sh
-l='$log'/\$(basename "\$0")
-printf '%s\n' "\$@" >"\$l.args"
-cat >"\$l.in"
-[ -z "\${FAKE_SIG:-}" ] || kill -"\$FAKE_SIG" \$\$
-exit "\${FAKE_EXIT:-0}"
-EOF
- chmod 755 "$real/$t"
-done
-# make_shim <folder> <tool> <perl>: the shim as the mod writes it (each value quoted for sh).
-make_shim() {
- sed -e "s|@TOOL@|'$2'|" -e "s|@REAL@|'$real/$2'|" -e "s|@DIR@|'$1'|" -e "s|@PERL@|'$3'|" "$template" >"$1/$2"
- chmod 755 "$1/$2"
-}
-for t in pbcopy wl-copy xclip xsel; do make_shim "$shims" "$t" "$stub/perl"; done
-
-# The fake mod: reads ids from the FIFO (open to read and write, as the real
-# reader), notes them, and answers after $2 seconds ("ANSWER for N bytes",
-# or nothing with $4 = empty): a temp file, then a link. A link that fails
-# meets the shim's mark: then it notes `late <id>`, and the files go.
-cat >"$tmp/mod.pl" <<'EOF'
-use Time::HiRes ();
-my ($fifo, $wait, $log, $kind) = @ARGV;
-open(my $f, "+<", $fifo) or die "fifo: $!";
-(my $dir = $fifo) =~ s{/[^/]*$}{/ask};
-$| = 1;
-while (my $id = <$f>) {
- chomp $id;
- open(my $n, ">>", "$log/mod.ids"); print $n "$id\n"; close $n;
- open(my $r, "<:raw", "$dir/$id") or next;
- my $raw = do { local $/; <$r> }; close $r;
- Time::HiRes::sleep($wait);
- open(my $w, ">:raw", "$dir/$id.answer.tmp");
- print $w "ANSWER for " . length($raw) . " bytes" unless ($kind // "") eq "empty";
- close $w;
- if (!link("$dir/$id.answer.tmp", "$dir/$id.answer")) {
- unlink "$dir/$id", "$dir/$id.answer";
- open(my $l, ">>", "$log/mod.late"); print $l "late $id\n"; close $l;
- }
- unlink "$dir/$id.answer.tmp";
-}
-EOF
-start_mod() {
- stop_mod
- "$perl" "$tmp/mod.pl" "$fifo" "$1" "$log" "${2:-}" &
- mod=$!
- # Until it has the FIFO open (a writer's open then works).
- n=0
- while [ "$n" -lt 100 ]; do
- "$perl" -MFcntl -e 'sysopen(my $f, $ARGV[0], O_WRONLY | O_NONBLOCK) or exit 1' "$fifo" && return
- n=$((n + 1)); sleep 0.05 2>/dev/null || sleep 1
- done
-}
-stop_mod() {
- [ -z "$mod" ] || { kill "$mod" 2>/dev/null; wait "$mod" 2>/dev/null; }
- mod=
-}
-now() { "$perl" -MTime::HiRes=time -e 'printf "%.3f", time'; }
-# The seconds from $1 to now, under $2: true or false.
-under() { "$perl" -MTime::HiRes=time -e 'exit(time - $ARGV[0] < $ARGV[1] ? 0 : 1)' "$1" "$2"; }
-
-# launch <ask> <cmd>...: runs <cmd> as a child of this shell (as Claude Code
-# runs the tool), with IUI_COPY_ASK=<ask>, PID in it replaced by this pid.
-# LAUNCH (default fifo) puts there the mod's FIFO, a file, a link to it, or
-# nothing; LAUNCH_DEEP=1 runs <cmd> one shell further down (not a child).
-cat >"$tmp/launch" <<EOF
-#!/bin/sh
-a=\$(printf '%s' "\$1" | sed "s/PID/\$\$/"); shift
-case \${LAUNCH:-fifo} in
- fifo) mv '$fifo' "\$a" ;;
- file) : >"\$a" ;;
- link) ln -s '$fifo' "\$a" ;;
-esac
-IUI_COPY_ASK=\$a; export IUI_COPY_ASK
-if [ -n "\${LAUNCH_DEEP:-}" ]; then sh -c '"\$@"; exit \$?' sh "\$@"; else "\$@"; fi
-r=\$?
-case \${LAUNCH:-fifo} in
- fifo) mv "\$a" '$fifo' ;;
- file|link) rm -f "\$a" ;;
-esac
-exit \$r
-EOF
-chmod 755 "$tmp/launch"
-L=$tmp/launch
-
-input=$tmp/input
-cells=$tmp/cells
-answer=$tmp/answer
-printf 'Copy test\nThe quick brown fox jumps' >"$input"
-# Two picture cells (U+10EEEE, a row and a column diacritic) between text.
-printf 'Copy \364\216\273\256\314\205\314\205\364\216\273\256\314\205\314\215 test\n' >"$cells"
-printf 'ANSWER for %s bytes' "$(wc -c <"$cells" | tr -d ' ')" >"$answer"
-
-# The ask folder has nothing left: no request, answer or mark.
-clean() { [ -z "$(ls -A "$c/ask")" ] && ok || { bad "$1: files left in ask/: $(ls -A "$c/ask" | tr '\n' ' ')"; rm -f "$c/ask"/*; }; }
-reset_log() { rm -f "$log"/*.args "$log"/*.in "$log/perl.runs" "$log/mod.ids" "$log/mod.late"; }
-
-# run <shell> <file> <tool> [args...]: the shim with <file> on stdin, as
-# Claude Code's exec finds it (on PATH $P, shim folder first), with the ask.
-run() {
- sh_=$1 in_=$2 tool=$3
- shift 3
- reset_log
- if [ "$sh_" = exec ]; then
- PATH=$P "$L" "$c/ask-PID" "$tool" "$@" <"$in_"
- elif [ "$sh_" = bash ]; then
- PATH=$P "$L" "$c/ask-PID" bash --posix "$shims/$tool" "$@" <"$in_"
- else
- PATH=$P "$L" "$c/ask-PID" "$sh_" "$shims/$tool" "$@" <"$in_"
- fi
-}
-
-# check <shell> <write 0|1> <tool> [args...]: a write runs perl once, and
-# picture cells get the mod's answer; plain text, and any other call, pass
-# as they are (no perl for another call). The same arguments and exit
-# status each time, and nothing left in ask/.
-check() {
- sh_=$1 want=$2 tool=$3
- shift 3
- printf '%s\n' "$@" >"$tmp/want.args"
- code=${FAKE_EXIT:-0}
- what="$sh_ $tool $*"
- for kind in plain cells; do
- if [ "$kind" = plain ]; then in_=$input; else in_=$cells; fi
- run "$sh_" "$in_" "$tool" "$@"
- got=$?
- [ "$got" = "$code" ] && ok || bad "$what ($kind): exit $got, not $code"
- cmp -s "$log/$tool.args" "$tmp/want.args" && ok || bad "$what ($kind): the real tool did not get the same arguments"
- if [ "$kind" = cells ] && [ "$want" = 1 ]; then
- cmp -s "$log/$tool.in" "$answer" && ok || bad "$what: the real tool did not get the answer ($(cat "$log/$tool.in"))"
- else
- cmp -s "$log/$tool.in" "$in_" && ok || bad "$what ($kind): the real tool did not get the same stdin"
- fi
- if [ "$want" = 1 ]; then
- [ "$(cat "$log/perl.runs" 2>/dev/null)" = run ] && ok || bad "$what ($kind): not one perl run"
- else
- [ ! -e "$log/perl.runs" ] && ok || bad "$what ($kind): perl ran"
- fi
- clean "$what ($kind)"
- done
-}
-
-shells=exec
-for s in sh dash bash; do command -v "$s" >/dev/null 2>&1 && shells="$shells $s"; done
-
-start_mod 0
-for s in $shells; do
- # pbcopy: a write of the general pasteboard.
- check "$s" 1 pbcopy
- check "$s" 1 pbcopy -pboard general
- check "$s" 0 pbcopy -pboard find
- check "$s" 0 pbcopy -help
- # wl-copy: a write of text unless primary, clear, or text in the arguments.
- check "$s" 1 wl-copy
- check "$s" 1 wl-copy -n --type 'text/plain;charset=utf-8'
- check "$s" 1 wl-copy --type=text/plain
- check "$s" 1 wl-copy -t UTF8_STRING
- check "$s" 0 wl-copy -t image/png
- check "$s" 0 wl-copy --type=image/png
- check "$s" 0 wl-copy --primary
- check "$s" 0 wl-copy -p
- check "$s" 0 wl-copy --clear
- check "$s" 0 wl-copy hello
- # xclip: input mode and the clipboard selection (its default is primary).
- check "$s" 1 xclip -selection clipboard
- check "$s" 1 xclip -sel c
- check "$s" 1 xclip -i -selection clipboard -t text/plain
- check "$s" 1 xclip -selection clipboard -target STRING
- check "$s" 0 xclip -selection clipboard -t image/png
- check "$s" 0 xclip -selection clipboard -target text/html
- check "$s" 0 xclip -selection primary
- check "$s" 0 xclip
- check "$s" 0 xclip -selection clipboard -o
- check "$s" 0 xclip -selection clipboard -t text/plain -o
- check "$s" 0 xclip -selection clipboard -t TARGETS -o
- check "$s" 0 xclip -selection clipboard -t image/png -o
- check "$s" 0 xclip -selection clipboard file.txt
- # xsel: input (or append) and the clipboard.
- check "$s" 1 xsel --clipboard --input
- check "$s" 1 xsel -bi
- check "$s" 1 xsel -b -i
- check "$s" 0 xsel --primary --input
- check "$s" 0 xsel --clipboard --output
- check "$s" 0 xsel -bo
- check "$s" 0 xsel --clipboard
- check "$s" 0 xsel
-done
-
-# The exit status of the real tool, for a write and for a read, each tool.
-for t in pbcopy wl-copy; do FAKE_EXIT=3 check exec 1 "$t"; done
-FAKE_EXIT=3 check dash 1 xclip -selection clipboard
-FAKE_EXIT=3 check sh 1 xsel -bi
-FAKE_EXIT=4 check exec 0 xclip -selection clipboard -o
-# (An assignment before a function call stays in some shells.)
-unset FAKE_EXIT
-
-# A real tool that a signal ends: the same signal status (128 + n), with
-# perl (a write) and with no perl (a read).
-for a in "1 pbcopy" "0 xsel -bo"; do
- for kind in plain cells; do
- if [ "$kind" = plain ]; then in_=$input; else in_=$cells; fi
- set -- $a
- FAKE_SIG=TERM run dash "$in_" $2 ${3:-} 2>/dev/null
- got=$?
- [ "$got" = 143 ] && ok || bad "signal ($2 $kind): exit $got, not 143"
- clean "signal ($2 $kind)"
- done
-done
-unset FAKE_SIG
-# The same signal itself, not only its status, for its parent.
-for t in pbcopy "xsel -bo"; do
- reset_log
- FAKE_SIG=TERM PATH=$P "$perl" -e 'my ($f, @cmd) = @ARGV; (my $a = $f) =~ s/-mod$/-$$/; rename $f, $a; $ENV{IUI_COPY_ASK} = $a; system(@cmd); my $s = $?; rename $a, $f; exit(($s & 127) == 15 ? 0 : 1)' "$fifo" $t <"$cells"
- [ $? = 0 ] && ok || bad "signal ($t): its parent did not see SIGTERM"
- clean "signal itself ($t)"
-done
-
-# A binary type passes untouched: all bytes, no ask.
-printf '\211PNG\r\n\032\n\364\216\273\256\000\377' >"$tmp/png"
-run exec "$tmp/png" wl-copy -t image/png
-cmp -s "$log/wl-copy.in" "$tmp/png" && [ ! -e "$log/mod.ids" ] && [ ! -e "$log/perl.runs" ] && ok || bad "image/png: not all bytes untouched"
-
-# 4 MiB of any bytes (the limit), text with no last line break, and none.
-dd if=/dev/urandom of="$tmp/big" bs=1024 count=4096 2>/dev/null
-for f in big: nolf:no\ line\ break empty:; do
- name=${f%%:*}
- [ "$name" = big ] || printf '%s' "${f#*:}" >"$tmp/$name"
- run exec "$tmp/$name" xsel -bi
- cmp -s "$log/xsel.in" "$tmp/$name" && ok || bad "$name input: the text did not pass"
- clean "$name input"
-done
-# Picture cells in more than 4 MiB: no ask, all bytes pass (also after the
-# first 4 MiB); exactly 4 MiB with cells: asked.
-{ cat "$cells"; cat "$tmp/big"; } >"$tmp/big5"
-run exec "$tmp/big5" pbcopy
-cmp -s "$log/pbcopy.in" "$tmp/big5" && [ ! -e "$log/mod.ids" ] && ok || bad "over 4 MiB: not all bytes, or asked"
-clean "over 4 MiB"
-{ cat "$cells"; head -c $((4194304 - $(wc -c <"$cells"))) "$tmp/big"; } >"$tmp/big4"
-run exec "$tmp/big4" pbcopy
-[ -s "$log/mod.ids" ] && ok || bad "4 MiB with cells: not asked"
-clean "4 MiB with cells"
-
-# An empty answer (the mod has no text): the shim's own cells.
-start_mod 0 empty
-run sh "$cells" pbcopy
-cmp -s "$log/pbcopy.in" "$cells" && [ -s "$log/mod.ids" ] && ok || bad "empty answer: not the cells"
-clean "empty answer"
-start_mod 0
-
-# Not a direct child of the FIFO's process: no ask, no perl, the cells.
-reset_log
-PATH=$P LAUNCH_DEEP=1 "$L" "$c/ask-PID" pbcopy <"$cells"
-got=$?
-[ "$got" = 0 ] && cmp -s "$log/pbcopy.in" "$cells" && [ ! -e "$log/perl.runs" ] && [ ! -e "$log/mod.ids" ] && ok || bad "not a child: asked, or not the cells ($got)"
-clean "not a child"
-
-# IUI_COPY_ASK not set, or not a FIFO path: the cells pass, no perl.
-for a in '' "$c/foo" "$c/ask-x1"; do
- reset_log
- PATH=$P LAUNCH=none "$L" "$a" pbcopy <"$cells"
- cmp -s "$log/pbcopy.in" "$cells" && [ ! -e "$log/perl.runs" ] && ok || bad "IUI_COPY_ASK '$a': the cells did not pass as they are"
-done
-
-# No reader (the mod stopped): the cells at once.
-stop_mod
-t0=$(now)
-run exec "$cells" pbcopy
-under "$t0" 0.3 && ok || bad "no reader: the shim waited"
-cmp -s "$log/pbcopy.in" "$cells" && ok || bad "no reader: not the cells"
-clean "no reader"
-
-# A slow mod (1.8 s): the cells after the limit (1.5 s), well before Claude
-# Code's 2 s. The late answer meets the shim's mark, and the files go.
-start_mod 1.8
-t0=$(now)
-run dash "$cells" xclip -selection clipboard
-under "$t0" 1.4 && bad "slow mod: the shim did not wait for the answer" || ok
-under "$t0" 2 && ok || bad "slow mod: the shim took 2 s or more"
-cmp -s "$log/xclip.in" "$cells" && ok || bad "slow mod: not the cells"
-n=0
-while [ ! -s "$log/mod.late" ] && [ "$n" -lt 40 ]; do sleep 0.1 2>/dev/null || sleep 1; n=$((n + 1)); done
-grep -q "^late " "$log/mod.late" 2>/dev/null && ok || bad "slow mod: its answer was not refused"
-clean "slow mod"
-stop_mod
-
-# No perl (the shim's perl is not there): the cells, the exit status.
-start_mod 0
-mkdir -p "$tmp/noperl"
-make_shim "$tmp/noperl" pbcopy "$tmp/no/perl"
-for s in exec sh; do
- reset_log
- if [ "$s" = exec ]; then
- PATH=$tmp/noperl:$real:$bin FAKE_EXIT=5 "$L" "$c/ask-PID" pbcopy <"$cells"
- else
- PATH=$tmp/noperl:$real:$bin FAKE_EXIT=5 "$L" "$c/ask-PID" sh "$tmp/noperl/pbcopy" <"$cells"
- fi
- got=$?
- [ "$got" = 5 ] && ok || bad "$s no perl: exit $got, not 5"
- cmp -s "$log/pbcopy.in" "$cells" && [ ! -e "$log/mod.ids" ] && ok || bad "$s no perl: not the cells"
- clean "$s no perl"
-done
-
-# A FIFO that is a regular file, or a link to the mod's FIFO: the cells, and
-# the file is not written, the mod gets no id.
-for kind in file link; do
- reset_log
- PATH=$P LAUNCH=$kind "$L" "$c/ask-PID" wl-copy <"$cells"
- cmp -s "$log/wl-copy.in" "$cells" && ok || bad "a $kind as the FIFO: not the cells"
- [ ! -e "$log/mod.ids" ] && ok || bad "a $kind as the FIFO: the mod got an id"
- clean "a $kind as the FIFO"
-done
-
-# An ask folder that is a link, or not this user's (root's /usr): no ask,
-# the cells as they are.
-mkdir -p "$tmp/l"; ln -s "$c/ask" "$tmp/l/ask"
-for a in "fifo $tmp/l/ask-PID" "none /usr/ask-PID"; do
- reset_log
- PATH=$P LAUNCH=${a%% *} "$L" "${a#* }" pbcopy <"$cells"
- cmp -s "$log/pbcopy.in" "$cells" && [ ! -e "$log/mod.ids" ] && ok || bad "ask folder of ${a#* }: not the cells as they are"
-done
-clean "ask folder links"
-
-# The request can not be written (ask/ read-only): all of the text, and the
-# exit status.
-if [ "$(id -u)" != 0 ]; then
- chmod 500 "$c/ask"
- for s in exec dash; do
- reset_log
- if [ "$s" = exec ]; then
- PATH=$P FAKE_EXIT=6 "$L" "$c/ask-PID" xsel -bi <"$cells"
- else
- PATH=$P FAKE_EXIT=6 "$L" "$c/ask-PID" dash "$shims/xsel" -bi <"$cells"
- fi
- got=$?
- [ "$got" = 6 ] && ok || bad "$s read-only ask/: exit $got, not 6"
- cmp -s "$log/xsel.in" "$cells" && [ ! -e "$log/mod.ids" ] && ok || bad "$s read-only ask/: the text did not pass"
- done
- chmod 700 "$c/ask"
-fi
-stop_mod
-
-# The real tool moved: found on PATH without the shim folder, still asked.
-start_mod 0
-mv "$real" "$tmp/moved"
-reset_log
-PATH=$shims:$tmp/moved:$bin "$L" "$c/ask-PID" xclip -selection clipboard <"$cells"
-got=$?
-[ "$got" = 0 ] && ok || bad "a moved tool: exit $got"
-cmp -s "$log/xclip.in" "$answer" && ok || bad "a moved tool: not the answer"
-clean "a moved tool"
-stop_mod
-
-# No real tool, and the shim folder on PATH again in another spelling: the
-# shim stops (127), it never runs itself in a loop; also through perl.
-for a in none fifo; do
- start_mod 0
- out=$(PATH="$shims:$tmp/./shims:$bin" LAUNCH=$a "$L" "$c/ask-PID" xsel -bi <"$input" 2>&1)
- got=$?
- [ "$got" = 127 ] && ok || bad "no real tool ($a): exit $got, not 127 ($out)"
- stop_mod
-done
-mv "$tmp/moved" "$real"
-
-# ---- The setup script: only a private folder of this user gets shims ----
-# Each call runs as a child of this shell, so the pid it prints is $$.
-setup=$here/hooks/clip-shim-setup.sh
-sleep 60 &
-other=$!
-for s in $shells; do
- [ "$s" = exec ] && continue
- [ "$s" = bash ] && s='bash --posix'
- k=$(echo "$s" | tr -d ' -')
- d=$tmp/cache-$k
- m=$d/shims-$$
- mkdir -p "$d/shims" "$d/shims-$other"
- # Shims of another process (and an old shims folder) on PATH: found outside them.
- cp "$shims/pbcopy" "$d/shims/pbcopy"
- cp "$shims/pbcopy" "$d/shims-$other/pbcopy"
- PATH="$d/shims-$other:$d/shims:$real:/usr/bin:/bin" $s "$setup" find "$d" pbcopy xclip nosuchtool >"$tmp/out"
- [ $? = 0 ] && ok || bad "$s setup find: a private folder fails"
- out=$(cat "$tmp/out")
- echo "$out" | grep -qx "pid $$" && ok || bad "$s setup find: not the pid of its parent ($out)"
- echo "$out" | grep -qx "pbcopy $real/pbcopy" && ok || bad "$s setup find: pbcopy not found outside the shim folders ($out)"
- echo "$out" | grep -q nosuchtool && bad "$s setup find: a tool that is not there" || ok
- echo "$out" | grep -q '^perl /' && ok || bad "$s setup find: no perl line"
- [ -d "$m" ] && [ ! -L "$m" ] && ok || bad "$s setup find: no shims folder of the pid"
- case $(ls -ld "$m") in drwx------*) ok ;; *) bad "$s setup find: shims folder not 700" ;; esac
- # The ask folder (700) and the FIFO of the pid (600).
- echo "$out" | grep -qx "ask $d/ask-$$" && ok || bad "$s setup find: no ask line ($out)"
- case $(ls -ld "$d/ask") in drwx------*) ok ;; *) bad "$s setup find: ask folder not 700" ;; esac
- case $(ls -l "$d/ask-$$") in prw-------*) ok ;; *) bad "$s setup find: the FIFO is not a FIFO of mode 600" ;; esac
- rm -f "$d/ask-$$"
- # A file or a link in the FIFO's place (the parent's pid): a new FIFO, the target stays.
- for kind in file link; do
- printf 'keep' >"$tmp/target"
- out=$($s -c 'if [ "$1" = file ]; then printf x >"$2/ask-$$"; else ln -s "$3" "$2/ask-$$"; fi; shift 3; "$@"; :' \
- sh "$kind" "$d" "$tmp/target" $s "$setup" find "$d" pbcopy)
- p2=$(echo "$out" | sed -n 's/^pid \([0-9][0-9]*\)$/\1/p')
- [ -n "$p2" ] && [ -p "$d/ask-$p2" ] && [ ! -L "$d/ask-$p2" ] && echo "$out" | grep -qx "ask $d/ask-$p2" && ok || bad "$s setup find: no new FIFO for a $kind ($out)"
- [ "$(cat "$tmp/target")" = keep ] && ok || bad "$s setup find: the link target changed"
- rm -rf "$d/ask-$p2" "$d/shims-$p2"
- done
- # An ask folder that is a link: no ask line, the shims still set up.
- c5=$tmp/c5-$k; mkdir -p "$c5" "$tmp/other5-$k"; ln -s "$tmp/other5-$k" "$c5/ask"
- $s "$setup" find "$c5" pbcopy >"$tmp/out"; got=$?
- [ "$got" = 0 ] && ! grep -q '^ask ' "$tmp/out" && ok || bad "$s setup find: an ask link gives $got ($(cat "$tmp/out"))"
- # Install: a new shim takes its place, executable; `-file` removes one.
- printf 'x' >"$m/xclip.new-1"
- printf 'y' >"$m/xsel"
- $s "$setup" install "$d" .new-1 "$m/xclip" "-$m/xsel"
- [ $? = 0 ] && [ -x "$m/xclip" ] && [ ! -e "$m/xclip.new-1" ] && [ ! -e "$m/xsel" ] && ok || bad "$s setup install"
- # The shims of another process: never installed or removed by this one.
- printf 'z' >"$d/shims-$other/xclip.new-1"
- $s "$setup" install "$d" .new-1 "$d/shims-$other/xclip" 2>/dev/null; got=$?
- $s "$setup" install "$d" .new-1 "-$d/shims-$other/pbcopy" 2>/dev/null; got2=$?
- [ "$got" != 0 ] && [ "$got2" != 0 ] && [ ! -e "$d/shims-$other/xclip" ] && cmp -s "$d/shims-$other/pbcopy" "$shims/pbcopy" && ok || bad "$s setup install: the shims of another process changed ($got $got2)"
- # A temp file that is a link: refused, the target is not changed.
- printf 'keep' >"$tmp/target"
- ln -s "$tmp/target" "$m/pbcopy.new-2"
- $s "$setup" install "$d" .new-2 "$m/pbcopy" 2>/dev/null
- got=$?
- [ "$got" != 0 ] && [ "$(cat "$tmp/target")" = keep ] && [ ! -e "$m/pbcopy" ] && ok || bad "$s setup install: a link was used ($got)"
- # A cache folder that others can write: ours, so it is made 700 and used.
- c2=$tmp/open-$k; mkdir -p "$c2"; chmod 777 "$c2"
- $s "$setup" find "$c2" pbcopy >/dev/null
- [ $? = 0 ] && case $(ls -ld "$c2") in drwx------*) true ;; *) false ;; esac && ok || bad "$s setup: an open folder of this user was not made private"
- # A link as the cache folder, or as its shims folder: exit 3.
- ln -s "$d" "$tmp/link-$k"
- $s "$setup" find "$tmp/link-$k" pbcopy >/dev/null; got=$?
- [ "$got" = 3 ] && ok || bad "$s setup: a linked cache folder gives $got, not 3"
- c3=$tmp/c3-$k; mkdir -p "$c3" "$tmp/other-$k"; ln -s "$tmp/other-$k" "$c3/shims-$$"
- $s "$setup" find "$c3" pbcopy >/dev/null; got=$?
- [ "$got" = 3 ] && ok || bad "$s setup: a linked shims folder gives $got, not 3"
- $s "$setup" install "$c3" .new-1 "$c3/shims-$$/pbcopy" >/dev/null 2>&1; got=$?
- [ "$got" = 3 ] && ok || bad "$s setup install: a linked shims folder gives $got, not 3"
- # A link in the shims folder (it could point anywhere): exit 3.
- c4=$tmp/c4-$k; mkdir -p "$c4/shims-$$"; ln -s /usr/bin/true "$c4/shims-$$/pbcopy"
- $s "$setup" find "$c4" pbcopy >/dev/null; got=$?
- [ "$got" = 3 ] && ok || bad "$s setup: a link in the shims folder gives $got, not 3"
- # A file as the cache folder, and a folder of another user (root's /usr): exit 3.
- printf '' >"$tmp/file-$k"
- $s "$setup" find "$tmp/file-$k" pbcopy >/dev/null; got=$?
- [ "$got" = 3 ] && ok || bad "$s setup: a file as the cache folder gives $got, not 3"
- if [ "$(id -u)" != 0 ]; then
- $s "$setup" find /usr pbcopy >/dev/null 2>&1; got=$?
- [ "$got" = 3 ] && ok || bad "$s setup: a folder of another user gives $got, not 3"
- fi
-done
-
-# ---- The cache sweep (CACHE_SH in hooks/lib/env.ts) ----
-# The TypeScript text as sh: ${DESIGNS_KEPT_DAYS} as 30, the escapes undone.
-cache_sh=$("$perl" -ne 'if (/^export const CACHE_SH = `(.*)`$/) { $_ = $1; s/(?<!\\)\$\{DESIGNS_KEPT_DAYS\}/30/g; s/\\\$/\$/g; s/\\\\/\\/g; print }' "$here/hooks/lib/env.ts")
-[ -n "$cache_sh" ] && ok || bad "CACHE_SH: not found in env.ts"
-sh -c 'exit 0' &
-dead=$!
-wait "$dead"
-uid=$(id -u)
-for s in $shells; do
- [ "$s" = exec ] && continue
- [ "$s" = bash ] && s='bash --posix'
- k=$(echo "$s" | tr -d ' -')
- # A link as the cache folder (to a folder of the victim): nothing there changes.
- td=$tmp/td-$k; v=$tmp/victim-$k
- mkdir -p "$td" "$v/old" "$v/ask"; chmod 755 "$v"
- : >"$v/ask-$dead"; : >"$v/ask/$dead-1-2"
- touch -t 202001010000 "$v/old"
- ln -s "$v" "$td/cc-intelligent-ui-$uid"
- out=$(TMPDIR=$td XDG_CACHE_HOME=$tmp/xdg-$k $s -c "$cache_sh")
- [ -z "$(echo "$out" | sed -n 1p)" ] && ok || bad "$s CACHE_SH: a linked cache folder was used ($out)"
- [ -d "$v/old" ] && [ -e "$v/ask-$dead" ] && [ -e "$v/ask/$dead-1-2" ] && case $(ls -ld "$v") in drwxr-xr-x*) true ;; *) false ;; esac && ok || bad "$s CACHE_SH: the link target changed"
- # A cache folder of this user: the files of a dead pid go, of a live pid stay.
- td=$tmp/te-$k; d=$td/cc-intelligent-ui-$uid
- mkdir -p "$d/ask" "$d/shims-$dead" "$d/shims-$$" "$d/old" "$d/pkg-cache"
- : >"$d/ask-$dead"; : >"$d/ask-$$"; : >"$d/ask/$dead-1-2"; : >"$d/ask/$dead-1-2.answer"; : >"$d/ask/$$-1-2"
- : >"$d/shims-$dead/pbcopy"
- touch -t 202001010000 "$d/old" "$d/shims-$$" "$d/pkg-cache"
- out=$(TMPDIR=$td XDG_CACHE_HOME=$tmp/xdg-$k $s -c "$cache_sh")
- [ "$(echo "$out" | sed -n 1p)" = "$d" ] && ok || bad "$s CACHE_SH: not the cache folder ($out)"
- [ ! -e "$d/ask-$dead" ] && [ ! -e "$d/ask/$dead-1-2" ] && [ ! -e "$d/ask/$dead-1-2.answer" ] && [ ! -e "$d/shims-$dead" ] && [ ! -e "$d/old" ] && ok || bad "$s CACHE_SH: files of a dead pid or an old folder stayed ($(ls -A "$d" "$d/ask" | tr '\n' ' '))"
- [ -e "$d/ask-$$" ] && [ -e "$d/ask/$$-1-2" ] && [ -d "$d/shims-$$" ] && [ -d "$d/pkg-cache" ] && ok || bad "$s CACHE_SH: files of a live pid went"
-done
-kill "$other" 2>/dev/null; wait "$other" 2>/dev/null
-
-echo "shim-test: $pass passed, $fail failed (shells: $shells)"
-[ "$fail" = 0 ]
diff --git a/tests/shims.test.ts b/tests/shims.test.ts
deleted file mode 100644
index e2667d4..0000000
--- a/tests/shims.test.ts
+++ /dev/null
@@ -1,212 +0,0 @@
-import { expect, test } from 'claude-code/testing'
-
-import { pathWith, SHIM_SETUP, SHIM_TOOLS, shimFindOf, shimText, shQuote } from '../hooks/register'
-import { setUpShims } from '../hooks/lib/clipboard'
-import { S } from '../hooks/lib/state'
-
-const ok = (stdout: string, exitCode = 0) => ({ value: { exitCode, stdout, stderr: '', isStdoutTruncated: false, isStderrTruncated: false } })
-const TEMPLATE = 'tool=@TOOL@\nreal=@REAL@\ndir=@DIR@\nperl=@PERL@\n'
-
-test('a shim is the template with the tool, the real tool, the folder and perl, each quoted for sh', () => {
- expect(shQuote("it's")).toBe(`'it'\\''s'`)
- expect(shimText(TEMPLATE, 'xclip', '/usr/bin/xclip', "/t/a'b/shims-1", '/usr/bin/perl'))
- .toBe(`tool='xclip'\nreal='/usr/bin/xclip'\ndir='/t/a'\\''b/shims-1'\nperl='/usr/bin/perl'\n`)
- // A `$` in a path stays as it is.
- expect(shimText('@REAL@', 'pbcopy', '/x/$HOME', '/d', '/p')).toBe(`'/x/$HOME'`)
- expect(SHIM_TOOLS).toEqual({ mac: ['pbcopy'], linux: ['wl-copy', 'xclip', 'xsel'] })
-})
-
-test("the find script's output: the pid, only absolute tools outside the shim folders, perl, and the FIFO in the cache folder", () => {
- const out = 'pid 123\nwl-copy /usr/bin/wl-copy\nxclip /c/shims-7/xclip\nxsel xsel\nfoo /usr/bin/foo\nperl /usr/bin/perl\nask /c/ask-123\n'
- expect(shimFindOf('xclip /c/shims/xclip\n', SHIM_TOOLS.linux, '/c').found).toEqual({})
- expect(shimFindOf(out, SHIM_TOOLS.linux, '/c')).toEqual({ pid: '123', found: { 'wl-copy': '/usr/bin/wl-copy' }, perl: '/usr/bin/perl', ask: '/c/ask-123' })
- expect(shimFindOf('', SHIM_TOOLS.mac, '/c')).toEqual({ pid: '', found: {}, perl: '', ask: '' })
- // A FIFO outside the cache folder, or not of a pid: none.
- for (const ask of ['/tmp/ask-1', '/c/ask-', '/c/ask-1/x', '/c/x/ask-1', 'perl']) expect(shimFindOf(`ask ${ask}\n`, SHIM_TOOLS.mac, '/c').ask).toBe('')
- expect(shimFindOf('perl perl\n', SHIM_TOOLS.mac, '/c').perl).toBe('')
- expect(SHIM_SETUP).toBe('hooks/clip-shim-setup.sh')
-})
-
-test('PATH gets the shim folder first, once', () => {
- expect(pathWith('/usr/bin:/bin', '/c/shims')).toBe('/c/shims:/usr/bin:/bin')
- expect(pathWith('/c/shims:/usr/bin:/bin', '/c/shims')).toBe(null)
- // Not first, or twice: moved to the front, once.
- expect(pathWith('/usr/bin:/c/shims:/bin', '/c/shims')).toBe('/c/shims:/usr/bin:/bin')
- expect(pathWith('/c/shims:/usr/bin:/c/shims', '/c/shims')).toBe('/c/shims:/usr/bin')
- expect(pathWith('', '/c/shims')).toBe('/c/shims')
-})
-
-// A computer for setUpShims (a $ of its own): `found` the tools the find
-// script prints, the files in `files`, PATH in `vars`; `runs` and `sets`
-// keep the calls.
-function shimWorld(o: {
- found: string[]; files?: Record<string, string>; chmodFails?: boolean; denyPath?: boolean; path?: string; unsafe?: 'find' | 'install'; noPerl?: boolean; noAsk?: boolean
- noPid?: boolean
-}) {
- const files = new Map<string, string>(Object.entries(o.files ?? {}))
- const vars: Record<string, string | undefined> = { PATH: o.path ?? '/usr/bin:/bin' }
- const runs: string[][] = []
- const sets: [string, string | undefined][] = []
- const run = async (argv: string[]) => {
- runs.push(argv)
- if (o.unsafe === argv[2]) return ok('unsafe /c\n', 3).value
- if (argv[1]?.endsWith(SHIM_SETUP) && argv[2] === 'find') {
- return ok(`${o.noPid ? '' : 'pid 99\n'}${o.found.map(t => `${t} /usr/bin/${t}\n`).join('')}${o.noPerl ? '' : 'perl /usr/bin/perl\n'}${o.noAsk ? '' : 'ask /c/ask-99\n'}`).value
- }
- if (argv[1]?.endsWith(SHIM_SETUP) && argv[2] === 'install') {
- if (o.chmodFails) return ok('', 1).value
- for (const f of argv.slice(5)) {
- if (f.startsWith('-')) files.delete(f.slice(1))
- else {
- files.set(f, files.get(`${f}${argv[4]}`)!)
- files.delete(`${f}${argv[4]}`)
- }
- }
- return ok('').value
- }
- return ok('', 1).value
- }
- const $ = {
- plugin: { root: '/p' },
- process: { run },
- env: {
- get: async (name: string) => vars[name],
- set: async (name: string, value: string | undefined) => {
- sets.push([name, value])
- if (o.denyPath && name === 'PATH') return { deny: 'held by the organization' }
- vars[name] = value
- return {}
- },
- },
- fs: {
- read: async (path: string) => {
- if (path === '/p/hooks/clip-shim.sh') return TEMPLATE
- if (files.has(path)) return files.get(path)
- throw new Error('ENOENT')
- },
- write: async (path: string, text: string) => void files.set(path, text),
- exists: async (path: string) => files.has(path),
- },
- session: { id: async () => 'sess-1' },
- } as any
- return { $, files, vars, runs, sets }
-}
-
-const shimsOf = (files: Map<string, string>) => [...files.keys()].filter(k => k.startsWith('/c/shims-99/')).sort()
-
-test('macOS: the pbcopy shim, then IUI_COPY_ASK and PATH; again (a hot reload): nothing written or set', async () => {
- const w = shimWorld({ found: ['pbcopy'] })
- expect(await setUpShims(w.$, '/c', true)).toEqual({ tools: ['pbcopy'] })
- expect(w.runs[0]).toEqual(['sh', '/p/hooks/clip-shim-setup.sh', 'find', '/c', 'pbcopy'])
- // The shims folder of this process (pid 99), with the perl that find gave.
- expect(shimsOf(w.files)).toEqual(['/c/shims-99/pbcopy'])
- expect(w.files.get('/c/shims-99/pbcopy')).toBe(shimText(TEMPLATE, 'pbcopy', '/usr/bin/pbcopy', '/c/shims-99', '/usr/bin/perl'))
- // The FIFO first, so the first shim run has it.
- expect(w.sets).toEqual([['IUI_COPY_ASK', '/c/ask-99'], ['PATH', '/c/shims-99:/usr/bin:/bin']])
- expect(S.askFifo).toBe('/c/ask-99')
- expect(S.shimDir).toBe('/c/shims-99')
- const runs = w.runs.length
- expect(await setUpShims(w.$, '/c', true)).toEqual({ tools: ['pbcopy'] })
- // Only the find: the shim is the same, PATH and the FIFO are set.
- expect(w.runs.length).toBe(runs + 1)
- expect(w.sets.length).toBe(2)
- expect(w.vars.PATH).toBe('/c/shims-99:/usr/bin:/bin')
-})
-
-test('a find with no pid: off, nothing written or set', async () => {
- const w = shimWorld({ found: ['pbcopy'], noPid: true })
- expect(await setUpShims(w.$, '/c', true)).toEqual({ off: 'the shim folder could not be made' })
- expect(w.files.size).toBe(0)
- expect(w.sets).toEqual([])
-})
-
-test('no perl, or no FIFO: off with the reason; PATH and IUI_COPY_ASK not set', async () => {
- for (const [o, off] of [[{ noPerl: true }, 'no perl'], [{ noAsk: true }, 'the ask FIFO could not be made']] as const) {
- const w = shimWorld({ found: ['pbcopy'], ...o })
- expect(await setUpShims(w.$, '/c', true)).toEqual({ off })
- expect(w.sets).toEqual([])
- expect(S.askFifo).toBe('')
- }
-})
-
-test('Linux: a shim for each write tool found, none for the others; the shim of a tool that is gone goes', async () => {
- // Another process's shims folder is not touched.
- const w = shimWorld({ found: ['wl-copy', 'xsel'], files: { '/c/shims-99/xclip': 'old', '/c/shims-5/xclip': 'other' } })
- expect(await setUpShims(w.$, '/c', false)).toEqual({ tools: ['wl-copy', 'xsel'] })
- expect(w.runs[0]!.slice(4)).toEqual(['wl-copy', 'xclip', 'xsel'])
- expect(shimsOf(w.files)).toEqual(['/c/shims-99/wl-copy', '/c/shims-99/xsel'])
- expect(w.files.get('/c/shims-5/xclip')).toBe('other')
- expect(w.runs[1]!.slice(2)).toEqual(['install', '/c', '.new-99', '/c/shims-99/wl-copy', '-/c/shims-99/xclip', '/c/shims-99/xsel'])
-})
-
-test('Linux with no write tool: no shim, PATH not changed, off with the reason; S.askFifo stays empty', async () => {
- const w = shimWorld({ found: [] })
- expect(await setUpShims(w.$, '/c', false)).toEqual({ off: 'no wl-copy, xclip or xsel: Claude Code copies with its own addon' })
- expect(w.sets).toEqual([])
- expect(S.askFifo).toBe('')
-})
-
-test('a chmod that fails: off, with no FIFO', async () => {
- const w = shimWorld({ found: ['pbcopy'], chmodFails: true })
- expect(await setUpShims(w.$, '/c', true)).toEqual({ off: 'the clipboard shims could not be installed' })
- expect(w.sets).toEqual([])
- expect(S.askFifo).toBe('')
-})
-
-test('a PATH write the engine holds: off, with the reason', async () => {
- const w = shimWorld({ found: ['pbcopy'], denyPath: true })
- expect(await setUpShims(w.$, '/c', true)).toEqual({ off: 'PATH not set: held by the organization' })
- expect(S.askFifo).toBe('')
-})
-
-test('over ssh no shim is made and PATH is not changed; details say why', async ($, on) => {
- const runs: string[][] = []
- const sets: string[] = []
- on('env.get', async ($: any, e: any) => ({ value: ({ HOME: '/h', PATH: '/usr/bin', SSH_CONNECTION: '1.2.3.4 5 6.7.8.9 22' } as Record<string, string>)[e.name] }))
- on('env.set', async ($: any, e: any) => (sets.push(e.name), { value: {} }))
- on('process.run', async ($: any, e: any) => (runs.push(e.argv), /cc-intelligent-ui-/.test(e.argv.join(' ')) ? ok('/c\nDarwin\n') : ok('', 1)))
- const ran = await $.command.run({ command: 'iui', args: 'details' } as any)
- expect(ran.text).toContain('\nAuto copy: off (ssh)')
- expect(runs.some(argv => argv[1]?.endsWith(SHIM_SETUP) && argv[2] === 'find')).toBe(false)
- expect(sets).toEqual([])
-})
-
-test('a cache or shims folder that is not private (exit 3 at find or at install): no shims, PATH and IUI_COPY_ASK as they were', async () => {
- for (const unsafe of ['find', 'install'] as const) {
- const w = shimWorld({ found: ['pbcopy'], unsafe })
- expect(await setUpShims(w.$, '/c', true)).toEqual({ off: 'the cache folder is not private' })
- expect(w.sets).toEqual([])
- expect(w.vars.PATH).toBe('/usr/bin:/bin')
- expect(S.askFifo).toBe('')
- }
-})
-
-test('no private cache folder (the cache script failed): no shim step, PATH not changed; details say why', async ($, on) => {
- const runs: string[][] = []
- const sets: string[] = []
- on('env.get', async ($: any, e: any) => ({ value: ({ HOME: '/h', PATH: '/usr/bin', TERM_PROGRAM: 'ghostty', IUI_COPY_SHIM: '1' } as Record<string, string>)[e.name] }))
- on('env.set', async ($: any, e: any) => (sets.push(e.name), { value: {} }))
- // The cache script gives only the OS name: the shared fallback is for Typst only.
- on('process.run', async ($: any, e: any) => (runs.push(e.argv), /cc-intelligent-ui-/.test(e.argv.join(' ')) ? ok('\nDarwin\n\n') : ok('', 1)))
- const ran = await $.command.run({ command: 'iui', args: 'details' } as any)
- expect(ran.text).toContain('\nAuto copy: off (the cache folder is not private)')
- expect(runs.some(argv => argv[1]?.endsWith(SHIM_SETUP))).toBe(false)
- expect(sets).toEqual([])
-})
-
-for (const [what, vars, off] of [
- ['a background session', { TERM_PROGRAM: 'ghostty', CLAUDE_CODE_SESSION_KIND: 'bg' }, 'a background session'],
- ['a terminal with no pictures', { TERM_PROGRAM: 'Apple_Terminal' }, 'no pictures in this terminal'],
-] as const) {
- test(`${what}: no shims, PATH not changed; details say why`, async ($, on) => {
- const runs: string[][] = []
- const sets: string[] = []
- on('env.get', async ($: any, e: any) => ({ value: ({ HOME: '/h', PATH: '/usr/bin', IUI_COPY_SHIM: '1', ...vars } as Record<string, string>)[e.name] }))
- on('env.set', async ($: any, e: any) => (sets.push(e.name), { value: {} }))
- on('process.run', async ($: any, e: any) => (runs.push(e.argv), /cc-intelligent-ui-/.test(e.argv.join(' ')) ? ok('/c\nDarwin\n') : ok('', 1)))
- const ran = await $.command.run({ command: 'iui', args: 'details' } as any)
- expect(ran.text).toContain(`\nAuto copy: off (${off})`)
- expect(runs.some(argv => argv[1]?.endsWith(SHIM_SETUP))).toBe(false)
- expect(sets).toEqual([])
- })
-}