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

Picture select: review fixes; clear on typing and on a native selection; no shared cache fallback

razorback16782640e01b35
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 05ae86c..96a6a11 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,11 +8,22 @@ All releases of Intelligent UI for Claude Code (`cc-intelligent-ui`). Claude Cod
- **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).
+- **More ways to remove a picture selection:** a key typed in the prompt, and a new selection of Claude Code (normal text). A single click on normal text does not remove it (Claude Code tells a mod nothing about it), and Escape does not either. Refer to [Limitations](docs/limitations.md).
### Changed
- 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:`.
+- If the private cache folder cannot be used (a link, not a folder, or not yours), the mod draws nothing and tells you why in `/iui`, `/iui details` and a toast. Before, it used the shared folder `/tmp/cc-intelligent-ui`.
+
+### Fixed
+
+- Picture select: a push of the button on a page that had just gone off the screen no longer waits for ever (no highlight until a reload).
+- Picture select: two tall pages on the screen no longer make each other ready again and again (the page cache keeps the pages on the screen, and the page of the selection).
+- Picture select: a drawing drawn again with new page files (a stream, a resize, a theme or size change) no longer keeps its old pages in the queue.
+- Picture select: a slow copy no longer writes the clipboard after a newer copy.
+- Picture select: a selection of many full rows no longer stops the hooks for up to 0.16 s; the tinted rows are made in the background, and a frame makes them for 6 ms at most.
+- Picture select: a lost button up ends the drag; a reloaded Client is not ignored; a Client fault or a change to fullscreen mode takes effect at the next draw; `/iui off` and `/iui select off` let the page cache go; with no `perl`, the mod tries to write a frame one time only.
## 0.3.0 (2026-10-20)
diff --git a/docs/development.md b/docs/development.md
index 475af2e..fcf5bfc 100644
--- a/docs/development.md
+++ b/docs/development.md
@@ -24,7 +24,7 @@ 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: cache start|first|pause|resume|stop|drop|built ...`: the page cache. `drop` is a page file that no drawing uses now (a redraw). `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.
diff --git a/docs/how-it-works.md b/docs/how-it-works.md
index 354fb3e..170b0e5 100644
--- a/docs/how-it-works.md
+++ b/docs/how-it-works.md
@@ -27,23 +27,26 @@ The selection of Claude Code copies picture cells as kitty placeholder character
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). 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.
+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 (in the background, or by a frame: 6 ms of them at most per frame; a row that is not made yet shows plain in that frame, and the next frame continues). A frame makes new pieces only for the first and last selected rows (partly selected), and joins the pieces into one PNG (up to approximately 3 MB for a tall page). 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`. 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.
-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 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, and the rows are drawn again with no `Client`. The `Client` sets no key listener: with one, a click would give it the keys of the prompt until Escape, and Escape never reaches it.
+
+A picture selection goes when you type in the prompt (`prompt.edit`, and `prompt.change` for a recalled entry, an undo or a clear) or make a selection of Claude Code: while a picture selection shows, the mod reads `$.ui.selection()` every 250 ms with `$.clock.every` (one timer, stopped with the selection), and a new answer there removes it. No event tells a mod about a plain click outside its region. `/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.
+- A page that goes off the screen leaves the queue, and its work stops (a `down` on it before its next slice continues that work).
+- A drawing that is drawn again with new page files (a stream, a resize, a theme or size change) drops its old pages from the queue.
+- When a `down` comes on a different page, the work on the page in progress pauses (if that page is ready, is on the screen, or a `down` asked for it). 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 keeps the decoded pages in memory, 128 MB (a page of 3392 × 4932 pixels uses approximately 74 MB). When it needs space, only pages off the screen go, the oldest first; a page on the screen and the page of the selection stay. A page that does not fit with the pages on the screen waits for a `down` on it (which goes over the budget for a short time). `/iui off` and `/iui select off` let all of it go. 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).
diff --git a/docs/limitations.md b/docs/limitations.md
index 2ca4943..2dab243 100644
--- a/docs/limitations.md
+++ b/docs/limitations.md
@@ -19,15 +19,18 @@
- It works only in fullscreen mode, and not over ssh (pages sent as bytes).
- 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.
+ - A single click on normal text (no drag, and no typing after it) does not remove a picture selection, because Claude Code tells a mod nothing about such a click. These remove it: a click in a picture, a new picture selection, a key typed in the prompt, a new selection of Claude Code (the mod looks for one every 0.25 s while a picture selection shows), your next prompt, and `/iui off` or `/iui select off`.
+ - Escape does not remove a picture selection. Claude Code never gives Escape to a mod's region, and a region that takes keys would also take the keys that you type in the prompt after a click on a picture.
+ - A selection of Claude Code (normal text) stays on the screen when you then drag over a picture: Claude Code removes its highlight only for a press outside a mod's region, and a mod cannot remove it. Its copy is done already. To remove it first, click normal text or push a key.
- It has no double click (word) or triple click (line) selection, and no Shift+click to make a selection longer.
- - 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 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 (up to approximately 3 MB for a tall page). If you select many full rows of a page whose tinted rows are not ready, the highlight of those rows comes in some steps of one frame each.
+ - The mod keeps the ready pages in memory, 128 MB (one page of 3392 × 4932 pixels uses approximately 74 MB). It drops only pages off the screen, the oldest first; it never drops a page on the screen or the page of the selection. If a page on the screen does not fit with the other pages on the screen, the mod does not make it ready in the background: it makes it ready at the next push of the button on it (then the memory can go over 128 MB for a short time). 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 needs `perl` (with `MIME::Base64`, a core module) to write the frames. With no `perl`, the selection and the copy work with no highlight (the mod tries one time, then writes the reason to the debug log).
+- **The cache folder:** the mod uses only its private cache folder (`$TMPDIR/cc-intelligent-ui-<uid>`, mode 700, your own and not a link). If that folder is a link, is not a folder or is not yours, the mod draws nothing and picture select is off. `/iui`, `/iui details` and a toast at the start tell you why. Remove or fix that folder, then start Claude Code again.
- 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.
diff --git a/docs/usage.md b/docs/usage.md
index 158c9f7..699b6cd 100644
--- a/docs/usage.md
+++ b/docs/usage.md
@@ -100,7 +100,7 @@ Picture select works in fullscreen mode only. It is on by default. `/iui select
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.
+3. These remove the selection: a click with no drag in a picture, a new selection in a picture, a key typed in the prompt, a new selection of Claude Code (normal text), your next prompt, and `/iui off` or `/iui select off`. A single click on normal text does not (refer to [Limitations](limitations.md)).
A selection can go on into the next page of the same answer.
diff --git a/hooks/lib/blit.ts b/hooks/lib/blit.ts
index 6fd48f4..b6520fb 100644
--- a/hooks/lib/blit.ts
+++ b/hooks/lib/blit.ts
@@ -7,17 +7,18 @@
//
// 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
-// 3392 x 4284. The hooks can write only text, so perl writes the frame
-// (base64 on its stdin) to a file of its own, which the terminal reads.
+// Its rows are deflate pieces made once (plain, and tinted in the
+// background or the first time a whole row is selected, TINT_MS of them a
+// frame); a frame makes only the selection's first and last rows (partly
+// selected) and joins the pieces: up to about 3 MB for a tall page. The
+// hooks can write only text, so perl writes the frame (base64 on its
+// stdin) to a file of its own, which the terminal reads.
import type { EngineInterface } from 'claude-code'
import { drawnAnswers, S } from './state'
import { toBase64 } from './png'
-import { frameOf, selectColor } from './frames'
-import { forgetPages, needFrames } from './pagecache'
+import { frameNow, selectColor } from './frames'
+import { forgetPages, holdPages, keyOf, needFrames } from './pagecache'
import type { DrawnPage } from './copy'
import type { SelRow } from './select'
import { perlFor } from './host'
@@ -76,7 +77,8 @@ 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 frame files written; the reasons logged; pages
-// whose blit was refused (none until the next down).
+// whose blit was refused (none until the next down); `noWriter`: perl
+// could not start (no frame is tried again; the copy still works).
export const blits = {
sites: new Map<string, { requestId: string; keys: string }>(),
shown: new Map<string, string>(),
@@ -85,6 +87,7 @@ export const blits = {
refused: new Set<string>(),
seq: 0,
dir: '',
+ noWriter: false,
}
// A drawing's site, at each draw of its pages.
@@ -102,6 +105,7 @@ export function forgetBlits() {
blits.files = []
blits.seq = 0
blits.dir = ''
+ blits.noWriter = false
}
const ms = (t: number) => `${Math.round(t)}ms`
@@ -125,36 +129,45 @@ function nextFile(cache: string, now: number): { path: string; old: string[] } {
return { path, old: old.map(f => f.path) }
}
-// Shows one page: its own PNG back, or a frame of `rows`.
-async function showPage($: EngineInterface, id: string, i: number, page: DrawnPage, rows: readonly SelRow[], sig: string): Promise<void> {
+// Shows one page: its own PNG back, or a frame of `rows`. True when it
+// should be shown again: a frame with rows drawn plain for now, or one
+// dropped as its row was drawn again meanwhile.
+async function showPage($: EngineInterface, id: string, i: number, page: DrawnPage, rows: readonly SelRow[], sig: string): Promise<boolean> {
const k = `${id}#${i}`
const site = blits.sites.get(id)
const env = S.env
- if (!site || !env) return
+ if (!site || !env || (rows.length && blits.noWriter)) return false
const key = `${site.keys}p${i}`
const rowsText = rows.length ? `rows ${rows[0]!.row}..${rows[rows.length - 1]!.row} (${rows.length})` : 'plain'
let source: { file: string; format: 'png' } = { file: page.file, format: 'png' }
let timing = ''
+ let isWhole = true
if (rows.length) {
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
+ return false
}
const now = await clockNow($).catch(() => Date.now())
const t1 = performance.now()
- const png = frameOf(got.frames, rows)
+ const made = frameNow(got.frames, rows)
+ const png = made.png
+ isWhole = made.isWhole
const t2 = performance.now()
const { path, old } = nextFile(env.cache, now)
- const ran = await processRun($, [perlFor(env.isMac), '-e', WRITE_PL, path, ...old], { stdin: toBase64(png) }).catch(err => ({ exitCode: 1, stderr: String(err) }))
+ const ran = await processRun($, [perlFor(env.isMac), '-e', WRITE_PL, path, ...old], { stdin: toBase64(png) }).catch(err => ({ exitCode: -1, stderr: String(err) }))
const t3 = performance.now()
if (ran.exitCode !== 0) {
+ // No perl: no frame is tried again.
+ if (ran.exitCode === -1 && /ENOENT|not found/i.test(ran.stderr)) blits.noWriter = true
logOnce($, `the frame could not be written: ${ran.stderr.trim()}`)
- return
+ return false
}
+ // The row was drawn again meanwhile (a new page file, or a new site): this frame is of the old one.
+ if (drawnAnswers.get(id)?.pages[i]?.file !== page.file || blits.sites.get(id) !== site) return true
source = { file: path, format: 'png' }
- timing = `wait ${ms(got.waitMs)} frame ${ms(t2 - t1)} write ${ms(t3 - t2)} ${png.length} bytes`
+ timing = `wait ${ms(got.waitMs)} frame ${ms(t2 - t1)}${isWhole ? '' : ' (part)'} 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) }))
@@ -163,17 +176,21 @@ async function showPage($: EngineInterface, id: string, i: number, page: DrawnPa
blits.shown.delete(k)
blits.refused.add(k)
logOnce($, `the engine refused the highlight's blit (${res.deny})`)
- return
+ return false
}
- blits.shown.set(k, sig)
+ // A part frame is not what the page is to show: the next run makes the rest.
+ blits.shown.set(k, isWhole ? sig : `${sig}~`)
traceDebug($, `select: blit ${id} page ${i} ${rowsText} ${timing ? `${timing} ` : ''}${blit}`)
+ return !isWhole
}
// Brings every page to the selection now: the selected ones to their
// frames, the ones no longer selected back to their PNG. `selected` gives
-// a drawing's pages and rows (or none).
-export async function showSelection($: EngineInterface, selected: { id: string; pages: readonly DrawnPage[]; rows: readonly (readonly SelRow[])[] } | null) {
+// a drawing's pages and rows (or none). True when a page is to be shown
+// again (showPage).
+export async function showSelection($: EngineInterface, selected: { id: string; pages: readonly DrawnPage[]; rows: readonly (readonly SelRow[])[] } | null): Promise<boolean> {
const color = selectColor(S.theme)
+ holdPages(selected ? selected.pages.filter((_, i) => selected.rows[i]?.length).map(page => keyOf(page, color)) : [])
const want = new Map<string, { id: string; i: number; page: DrawnPage; rows: readonly SelRow[] }>()
if (selected) selected.pages.forEach((page, i) => want.set(`${selected.id}#${i}`, { id: selected.id, i, page, rows: selected.rows[i] ?? [] }))
// Pages shown with a highlight before, of this drawing or another.
@@ -184,10 +201,13 @@ export async function showSelection($: EngineInterface, selected: { id: string;
if (page) want.set(k, { id, i: n, page, rows: [] })
else blits.shown.delete(k)
}
+ let again = false
for (const [k, w] of want) {
- const sig = sigOf(w.rows, color)
+ // Its page file too: a row drawn again with a new file is shown again.
+ const sig = w.rows.length ? `${sigOf(w.rows, color)}|${w.page.file}` : ''
if ((blits.shown.get(k) ?? '') === sig || blits.refused.has(k)) continue
- await showPage($, w.id, w.i, w.page, w.rows, sig)
+ if (await showPage($, w.id, w.i, w.page, w.rows, sig)) again = true
}
+ return again
}
diff --git a/hooks/lib/env.ts b/hooks/lib/env.ts
index a4803a7..b1d950c 100644
--- a/hooks/lib/env.ts
+++ b/hooks/lib/env.ts
@@ -29,8 +29,9 @@ const isOn = atom({ plugin: 'cc-intelligent-ui', key: 'isOn' } as const, true)
// 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 -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)"`
+// folder (when the cache folder can not be made private: the OS name, then
+// that folder on the fourth line).
+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%s\\n' "$(uname -s)" "$d"`
// 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.
@@ -38,15 +39,17 @@ export function setUp($: EngineInterface): Promise<Env> {
S.envLoading ??= (async () => {
await registerCommand($)
const made = await processRun($, ['sh', '-c', CACHE_SH]).catch(() => null)
- const [made1 = '', os = '', made3 = ''] = (made?.stdout ?? '').split('\n')
- const cache = made1.trim() || '/tmp/cc-intelligent-ui'
+ const [made1 = '', os = '', made3 = '', refused = ''] = (made?.stdout ?? '').split('\n')
+ // No private cache folder: nothing is drawn (no shared folder instead).
+ const cache = made1.trim()
+ S.cacheProblem = cache ? '' : refused.trim() ? `the cache folder ${refused.trim()} is a link, not a folder, or not yours` : 'the cache folder could not be made'
// The key folders on disk now: a key found here is read back at once.
- const listed = await fsList($, cache).catch(() => [])
+ const listed = cache ? await fsList($, cache).catch(() => []) : []
S.onDisk = new Set(listed.filter(entry => entry.kind === 'dir' && entry.name !== 'pkg-cache').map(entry => entry.name))
const program = (await envGet($, 'TERM_PROGRAM')) ?? ''
const term = (await envGet($, 'TERM')) ?? ''
const ssh = !!(await envGet($, 'SSH_CONNECTION')) || !!(await envGet($, 'SSH_TTY'))
- const canDraw = canDrawIn({
+ const terminalDraws = canDrawIn({
program,
term,
kitty: !!(await envGet($, 'KITTY_WINDOW_ID')),
@@ -56,6 +59,7 @@ export function setUp($: EngineInterface): Promise<Env> {
engineForced: isSet(await envGet($, 'CLAUDE_CODE_FORCE_TERMINAL_IMAGES')),
modForced: isSet(await envGet($, 'IUI_FORCE')),
})
+ const canDraw = terminalDraws && !!cache
const root = pluginRoot($)
const template = await fsStat($, `${root}/render/md.typ`).catch(() => null)
const rows = await configs($).catch(() => [])
@@ -75,7 +79,7 @@ export function setUp($: EngineInterface): Promise<Env> {
session: (await envGet($, 'ITERM_SESSION_ID')) || undefined,
lcTerminal: (await envGet($, 'LC_TERMINAL')) || undefined,
})
- S.setupNeeded = S.isIterm && !canDraw && !ssh && S.hostOs === 'Darwin' &&
+ S.setupNeeded = S.isIterm && !terminalDraws && !ssh && S.hostOs === 'Darwin' &&
!(await envGet($, 'TMUX')) && !(await envGet($, 'STY')) && (await envGet($, 'CLAUDE_CODE_SESSION_KIND')) !== 'bg'
if (S.setupNeeded) void offerSetup($).catch(() => undefined)
S.isCmux = !!(await envGet($, 'CMUX_SURFACE_ID')) || !!(await envGet($, 'CMUX_WORKSPACE_ID')) || !!(await envGet($, 'CMUX_SOCKET_PATH'))
@@ -101,14 +105,18 @@ export function setUp($: EngineInterface): Promise<Env> {
setFrame(await readFrame($))
if (canDraw) watchFrame($)
const typst = await findTypst($)
- if (!typst) {
+ if (S.cacheProblem && terminalDraws) {
+ try {
+ uiToast($, `Intelligent UI: no pictures, ${S.cacheProblem} (see /iui details)`, { timeoutMs: 8000 })
+ } catch {}
+ } else if (!typst) {
try {
uiToast($, noTypstOf(isMac), { timeoutMs: 8000 })
} catch {}
}
const termFont = await termFontOf($, isMac).catch(() => '')
const home = (await envGet($, 'HOME')) ?? ''
- const designs = made3.trim() || (home ? `${home}/.cache/cc-intelligent-ui/designs` : `${cache}/designs`)
+ const designs = made3.trim() || (home ? `${home}/.cache/cc-intelligent-ui/designs` : cache ? `${cache}/designs` : '')
const stored = await storeGet($, 'theme-name').catch(() => undefined)
const wanted = typeof stored === 'string' && stored ? stored : DEFAULT_THEME
const applied = await applyTheme($, root, home, wanted).catch(() => null)
@@ -135,7 +143,7 @@ export function setUp($: EngineInterface): Promise<Env> {
}),
termFont,
designs,
- metrics: typst ? await measureFonts($, typst, root, cache, termFont, S.look?.dir ?? `${root}/render/themes/${BASE_THEME}`) : DEFAULT_METRICS,
+ metrics: typst && cache ? await measureFonts($, typst, root, cache, termFont, S.look?.dir ?? `${root}/render/themes/${BASE_THEME}`) : DEFAULT_METRICS,
}
refresh($)
// The start is done: the update check now, and nothing waits for it.
diff --git a/hooks/lib/frames.ts b/hooks/lib/frames.ts
index 9bc305e..f1b2c9a 100644
--- a/hooks/lib/frames.ts
+++ b/hooks/lib/frames.ts
@@ -92,18 +92,40 @@ function* framesFrom(img: Rgba, box: { columns: number; rows: number }, color: R
// 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 time a frame makes tinted rows for (a hooks slice stays short): the
+// rows past it are drawn plain, and made by a later frame or the build.
+export const TINT_MS = 6
+
// The frame PNG of a page with `rows` selected (cells x0 to x1, inclusive).
export function frameOf(f: Frames, rows: readonly SelRow[]): Uint8Array {
+ return frameNow(f, rows, Infinity).png
+}
+
+// The same, making tinted rows for `budgetMs` at most (one at least);
+// `isWhole` false when a selected row is drawn plain for now.
+export function frameNow(f: Frames, rows: readonly SelRow[], budgetMs = TINT_MS, now = () => performance.now()): { png: Uint8Array; isWhole: boolean } {
const line = f.img.width * 4 + 1
const columns = f.xs.length - 1
const at = new Map(rows.map(r => [r.row, r]))
+ const t0 = now()
+ let isWhole = true
+ let made = 0
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))
+ if (sel.x0 <= 0 && sel.x1 >= columns - 1) {
+ const tint = f.tint[r]
+ if (tint) return tint
+ if (made && now() - t0 >= budgetMs) {
+ isWhole = false
+ return plain
+ }
+ made++
+ 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))])
+ return { png: concat([f.head, ...parts.map(p => p.chunk), tailOf(parts.map(p => p.piece))]), isWhole }
}
diff --git a/hooks/lib/log.ts b/hooks/lib/log.ts
index 5c5d9c9..448ef00 100644
--- a/hooks/lib/log.ts
+++ b/hooks/lib/log.ts
@@ -5,6 +5,7 @@ import { S } from './state'
import { processRun } from './api'
export async function logDebug($: EngineInterface, cache: string, text: string) {
+ if (!cache) return
const stamp = new Date().toISOString()
await processRun($, ['sh', '-c', 'cat >> "$1"', 'sh', `${cache}/debug.log`], { stdin: `[${stamp}] ${text.trimEnd()}\n` }).catch(() => undefined)
}
diff --git a/hooks/lib/pagecache.ts b/hooks/lib/pagecache.ts
index 3d7a1e2..b7898cc 100644
--- a/hooks/lib/pagecache.ts
+++ b/hooks/lib/pagecache.ts
@@ -8,10 +8,12 @@
// `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.
+// later; a page that leaves the screen is dropped (its build too), and so
+// is a page file a drawing no longer uses (a redraw). The pages built stay
+// in memory (FRAMES_KEPT_BYTES; only the ones off screen go, the oldest
+// first; a page the background can not fit with the pages on screen waits
+// for a down). 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'
@@ -19,15 +21,19 @@ 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 { keep, 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.
+// The pages built kept (their pixels and pieces), by bytes: one page of 3392 x 4932 is about 74 MB.
export const FRAMES_KEPT_BYTES = 128 * 1024 * 1024
+// A page's bytes once built, before it is: its pixels, and a fifth more for its pieces.
+export const bytesFor = (page: { width: number; height: number }) => Math.ceil(page.width * page.height * 4 * 1.2)
+// The drawings whose page keys are kept (a redraw drops the keys it no longer uses).
+const DRAWN_KEPT = 256
// 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
@@ -54,13 +60,13 @@ export function nextWant(wants: Iterable<Want>): Want | undefined {
}
// 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[] {
+// oldest first), only the ones off screen; `keep` never.
+export function evictKeys(kept: readonly { key: string; bytes: number; onScreen: boolean }[], budget: number, keep: ReadonlySet<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)]) {
+ for (const k of kept) {
if (bytes <= budget) break
- if (k.key === keep) continue
+ if (k.onScreen || keep.has(k.key)) continue
bytes -= k.bytes
out.push(k.key)
}
@@ -100,12 +106,18 @@ export function pagesOnScreen(d: Drawn): number[] {
}
// 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
+// pages to build, the pages on screen, the selection's pages (never
+// dropped), each drawing's page keys, the build now and who waits for a
// page; the words to probe, and the ones the background got none for.
+// `epoch` goes up at each forget: a slice or probe of an older one stops.
export const pages = {
frames: new Map<string, Frames | null>(),
wants: new Map<string, Want>(),
screen: new Set<string>(),
+ active: new Set<string>(),
+ drawn: new Map<string, Set<string>>(),
+ budget: FRAMES_KEPT_BYTES,
+ epoch: 0,
build: null as Build | null,
waiters: new Map<string, ((f: Frames | null) => void)[]>(),
promotions: 0,
@@ -115,11 +127,17 @@ export const pages = {
isProbing: false,
}
-// Forgets everything (for tests).
+// Forgets everything (select off, and tests): who waits gets no frames.
export function forgetPages() {
+ const waiters = [...pages.waiters.values()].flat()
+ pages.epoch++
+ if (pages.build) pages.build.isCancelled = true
pages.frames.clear()
pages.wants.clear()
pages.screen.clear()
+ pages.active.clear()
+ pages.drawn.clear()
+ pages.budget = FRAMES_KEPT_BYTES
pages.waiters.clear()
pages.build = null
pages.promotions = 0
@@ -127,6 +145,12 @@ export function forgetPages() {
pages.words = []
pages.wordsTried.clear()
pages.isProbing = false
+ for (const done of waiters) done(null)
+}
+
+// The pages the selection shows (blit.ts): never dropped while it does.
+export function holdPages(keys: Iterable<string>) {
+ pages.active = new Set(keys)
}
const ms = (t: number) => `${Math.round(t)}ms`
@@ -143,11 +167,30 @@ export function framesKnown(page: DrawnPage, color: string): Frames | null | und
return got
}
+// A page key no drawing uses now (a redraw with new files): out of the
+// screen and the queue, its build stopped, who waits for it given none.
+function dropKey($: EngineInterface, key: string) {
+ pages.screen.delete(key)
+ pages.wants.delete(key)
+ const b = pages.build
+ if (b && b.want.key === key) b.isCancelled = true
+ const waiters = pages.waiters.get(key) ?? []
+ pages.waiters.delete(key)
+ for (const done of waiters) done(null)
+ traceDebug($, `select: cache drop ${nameOf(key.split('|')[0]!)} (no longer drawn)`)
+}
+
// 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.
+// build of one stops (not one a down asked for). The keys and words of its
+// last noted pages it no longer uses are dropped. Never waits.
export function notePages($: EngineInterface, d: Drawn & { job?: Job }, color: string) {
const on = new Set(pagesOnScreen(d))
+ const keys = new Set(d.pages.map(page => keyOf(page, color)))
+ const was = pages.drawn.get(d.id)
+ keep(pages.drawn, d.id, keys, DRAWN_KEPT)
+ if (was) for (const k of was) if (!keys.has(k) && ![...pages.drawn.values()].some(s => s.has(k))) dropKey($, k)
+ pages.words = pages.words.filter(w => w.d.id !== d.id || w.d.dir === d.dir)
d.pages.forEach((page, index) => {
const key = keyOf(page, color)
const wordsKey = `${d.dir}#${index}`
@@ -167,7 +210,10 @@ export function notePages($: EngineInterface, d: Drawn & { job?: Job }, color: s
return
}
pages.screen.add(key)
- if (!pages.frames.has(key) && pages.build?.want.key !== key) {
+ const b = pages.build
+ // Back on screen before the slice that would drop its build.
+ if (b && b.want.key === key && b.isCancelled) b.isCancelled = false
+ else if (!pages.frames.has(key) && b?.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 })
@@ -187,12 +233,15 @@ export async function needFrames($: EngineInterface, page: DrawnPage, color: str
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.want.key === key) {
+ // A build stopped (off screen) but not dropped yet goes on.
+ b.want.promoted = promoted
+ b.isCancelled = false
+ } else {
+ // The build now is put aside: paused (ready: its tinted rows; on screen), else dropped.
if (b && !b.isCancelled) {
pages.build = null
- if (!b.isReady && (pages.screen.has(b.want.key) || b.want.promoted)) {
+ 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`)
@@ -210,10 +259,13 @@ export async function needFrames($: EngineInterface, page: DrawnPage, color: str
return { frames, waitMs: performance.now() - t }
}
-// The next slice, after the hooks' other work.
+// The next slice, after the hooks' other work (none after a forget).
function later($: EngineInterface) {
+ const epoch = pages.epoch
try {
- clockAfter($, 0, () => void slice($).catch(() => (pages.isPumping = false)))
+ clockAfter($, 0, () => void slice($, epoch).catch(() => {
+ if (epoch === pages.epoch) pages.isPumping = false
+ }))
} catch {
pages.isPumping = false
}
@@ -225,31 +277,49 @@ function kick($: EngineInterface) {
later($)
}
+// The next page to build that fits: a down's, a paused one, or one that
+// fits the budget with the pages that stay (on screen, the selection's).
+function nextFit(): Want | undefined {
+ let stay = 0
+ for (const [k, f] of pages.frames) if (f && (pages.screen.has(k) || pages.active.has(k))) stay += bytesOf(f)
+ return nextWant([...pages.wants.values()].filter(w => w.promoted || w.paused || stay + bytesFor(w.page) <= pages.budget))
+}
+
// One slice: the next build begun (its PNG read) or taken up again, or
// SLICE_MS of the build now.
-async function slice($: EngineInterface) {
+async function slice($: EngineInterface, epoch: number) {
+ if (epoch !== pages.epoch) return
let b = pages.build
if (b?.isCancelled) b = pages.build = null
if (!b) {
- const want = nextWant(pages.wants.values())
+ const want = nextFit()
if (!want) {
pages.isPumping = false
return
}
pages.wants.delete(want.key)
if (want.paused) {
- b = pages.build = want.paused
+ b = want.paused
want.paused = undefined
+ // Ready, and its frames dropped since: nothing to go on with.
+ if (b.isReady && !pages.frames.has(want.key)) {
+ later($)
+ return
+ }
+ pages.build = b
traceDebug($, `select: cache resume ${nameOf(want.page.file)} after ${b.slices.length} slices${want.promoted ? ', asked by a down' : ''}`)
} else {
const started = performance.now()
+ evict(bytesFor(want.page))
b = pages.build = { want, steps: null, png: null, slices: [], started, readMs: 0, readyMs: 0, stepMs: 0, isCancelled: false, isReady: false }
try {
+ // Kept even when stopped meanwhile: a down can take the build up again.
const { base64 } = await fsRead($, want.page.file, { as: 'bytes' })
- if (!b.isCancelled) b.png = fromBase64(base64)
+ b.png = fromBase64(base64)
} catch (err) {
- fail($, b, err)
+ if (epoch === pages.epoch) fail($, b, err)
}
+ if (epoch !== pages.epoch) return
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($)
@@ -273,10 +343,13 @@ async function slice($: EngineInterface) {
later($)
}
-// The cache within its budget: the oldest pages off screen go first.
-function evict(keep: string) {
+// The cache within its budget less `room`: the oldest pages off screen go
+// first; the ones on screen, the selection's and `keep` never.
+function evict(room = 0, 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)
+ const keeps = new Set(pages.active)
+ if (keep) keeps.add(keep)
+ for (const k of evictKeys(kept, pages.budget - room, keeps)) pages.frames.delete(k)
}
// A build's frames are ready (or can not be: null): kept and given to who
@@ -287,7 +360,7 @@ function ready($: EngineInterface, b: Build, frames: Frames | null) {
const { key } = b.want
pages.frames.delete(key)
pages.frames.set(key, frames)
- evict(key)
+ evict(0, key)
const waiters = pages.waiters.get(key) ?? []
pages.waiters.delete(key)
for (const done of waiters) done(frames)
@@ -305,7 +378,7 @@ function fail($: EngineInterface, b: Build, err: unknown) {
// 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)
+ evict(0, 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
@@ -323,6 +396,7 @@ function probeNext($: EngineInterface) {
const next = pages.words.shift()!
if (knownWords(next.d, next.page)) return probeNext($)
pages.isProbing = true
+ const epoch = pages.epoch
const t = performance.now()
void wordsOf($, next.d, next.page)
.then(got => {
@@ -334,6 +408,7 @@ function probeNext($: EngineInterface) {
})
.catch(() => undefined)
.finally(() => {
+ if (epoch !== pages.epoch) return
pages.isProbing = false
probeNext($)
})
diff --git a/hooks/lib/select.ts b/hooks/lib/select.ts
index 885d6b0..566d122 100644
--- a/hooks/lib/select.ts
+++ b/hooks/lib/select.ts
@@ -12,7 +12,7 @@ import { drawnAnswers, S } from './state'
import { compareVersions } from './updates'
import { joinSegments, pageTopsOf, textOfRun, type Drawn, type Item, type RunLine, type TextBlock } from './copy'
import { endFold, foldNew, FRAME_MS, pokeFold, showSelection, startFold } from './blit'
-import { clockAfter } from './api'
+import { clockAfter, clockEvery, uiSelection } from './api'
export type Point = { x: number; y: number }
export type SelectPhase = 'down' | 'move' | 'up' | 'clear'
@@ -43,10 +43,12 @@ export function redrawSelection($: EngineInterface) {
else if (next.kind === 'run') void runSelection($)
}
+// A page shown in part (its tinted rows not all made) or drawn again
+// meanwhile: one more run, a frame later.
async function runSelection($: EngineInterface) {
startFold(fold, performance.now())
- await showSelection($, selectedNow()).catch(() => undefined)
- if (endFold(fold)) redrawSelection($)
+ const again = await showSelection($, selectedNow()).catch(() => false)
+ if (endFold(fold) || again) redrawSelection($)
}
// The selection's drawing, its pages and their selected rows (none: null).
@@ -56,9 +58,51 @@ function selectedNow() {
return sel && d ? { id: sel.id, pages: d.pages, rows: selectedRows(sel, d.pages) } : null
}
-// Forgets the fold (for tests).
+// Forgets the fold, the selection and the native watch (for tests).
export function forgetRedraws() {
fold = foldNew()
+ stopNative()
+ picked.now = null
+ picked.seq = 0
+ picked.isBroken = false
+}
+
+// A native selection (Claude Code's own) made while a picture selection
+// shows takes ours down (`clear`): no event says so, so `$.ui.selection()`
+// is read every NATIVE_POLL_MS while ours shows, one timer at most. Its
+// answer stays the last one made, so only a new one counts (one there
+// before ours stays as it is).
+export const NATIVE_POLL_MS = 250
+const UNREAD = '\0'
+const native = { timer: null as { cancel: () => void } | null, last: UNREAD as string | undefined }
+const nativeOf = (s: { text: string; requestId?: string } | undefined) => (s ? `${s.requestId ?? ''}|${s.text}` : undefined)
+
+export function watchNative($: EngineInterface, clear: () => void) {
+ if (!picked.now) return stopNative()
+ if (native.timer) return
+ native.last = UNREAD
+ try {
+ native.timer = clockEvery($, NATIVE_POLL_MS, () => void pollNative($, clear).catch(() => undefined))
+ } catch {
+ native.timer = null
+ return
+ }
+ void Promise.resolve(uiSelection($)).then(got => {
+ if (native.last === UNREAD) native.last = nativeOf(got)
+ }, () => undefined)
+}
+
+async function pollNative($: EngineInterface, clear: () => void) {
+ const now = nativeOf(await uiSelection($).catch(() => undefined))
+ if (!native.timer) return
+ const was = native.last
+ native.last = now
+ if (now !== undefined && was !== UNREAD && now !== was) clear()
+}
+
+export function stopNative() {
+ native.timer?.cancel()
+ native.timer = null
}
const isInt = (v: unknown): v is number => typeof v === 'number' && Number.isInteger(v)
diff --git a/hooks/lib/state.ts b/hooks/lib/state.ts
index 5805602..7f30cf6 100644
--- a/hooks/lib/state.ts
+++ b/hooks/lib/state.ts
@@ -132,6 +132,8 @@ export const S = {
isFullscreen: null as boolean | null,
// The fullscreen advice was shown (once, on the main screen).
fullscreenTold: false,
+ // Why there is no cache folder ('' when there is one): nothing is drawn.
+ cacheProblem: '',
// The key folders in the cache at setUp: a key found there is read back
// at once (a reopened session), with no queue and no blank.
onDisk: new Set<string>(),
diff --git a/hooks/register.tsx b/hooks/register.tsx
index a4df67a..ad10dbc 100644
--- a/hooks/register.tsx
+++ b/hooks/register.tsx
@@ -24,7 +24,7 @@ import {
DEFAULT_THEME, gridText, heightText, IMAGE_MAX_COLUMNS, MARGIN_TOP, MAX_HEIGHT, MAX_WIDTH, MIN_HEIGHT, MIN_WIDTH, RESULTS_KEPT, TYPST_PROMPT,
SELECT_SINCE, selectText, typstHintOf, widthText,
} from './lib/settings'
-import { clip, drawnAnswers, editedPlans, keep, queue, refresh, running, S, subagentPlans, writesLive, type Env, type Job, type Result } from './lib/state'
+import { clip, drawnAnswers, editedPlans, keep, queue, refresh, running, S, subagentPlans, writesLive, type Env, type Job } from './lib/state'
import { beginEpoch } from './lib/epoch'
import { escapeControls, luminanceOf, modeLine, modeOfLuminance, parseOsc11, settingOf } from './lib/mode'
import { applyTheme, themeListing, userThemesOf } from './lib/themes'
@@ -33,9 +33,11 @@ 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 { needsSelect, picked, postOf, redrawSelection, runsOf, selectedRows, selectionAfter, selectTrace, textOfRuns, topsOf, type SelectPost, type Selection } from './lib/select'
+import {
+ needsSelect, picked, postOf, redrawSelection, runsOf, selectedRows, selectionAfter, selectTrace, stopNative, textOfRuns, topsOf, watchNative, type SelectPost, type Selection,
+} from './lib/select'
import { blits, selectColor } from './lib/blit'
-import { needFrames, notePages } from './lib/pagecache'
+import { forgetPages, needFrames, notePages } from './lib/pagecache'
import { traceDebug } from './lib/log'
import { finalizeAll } from './lib/stream'
import { knownWords, noteDrawn, noteDrawnAgain, noteOnScreen, wordsOf, type PageWords } from './lib/probe'
@@ -147,9 +149,11 @@ async function answerEnv($: EngineInterface, e: { viewport?: RenderViewport }):
// (the target and shown Frames change only with them, but at setFrame and
// at the first viewport noted, both before a row is kept), the env, and the
// viewport's columns (the room: the engine draws every row again once a
-// width change settles; a scroll keeps them).
+// width change settles; a scroll keeps them), and picture select's state
+// (a Client failed, fullscreen or not: its Client is there or not).
const stampOf = (ready: { env: Env; done: number }, view?: RenderViewport) =>
- `${ready.done}|${S.epoch}|${S.shownEpoch}|${ready.env.inline ? 1 : 0}|${view?.columns ?? ''}|${roomColumns(view)}`
+ `${ready.done}|${S.epoch}|${S.shownEpoch}|${ready.env.inline ? 1 : 0}|${view?.columns ?? ''}|${roomColumns(view)}|` +
+ `${S.select ? 1 : 0}${picked.isBroken ? 1 : 0}${view?.isFullscreen === true ? 1 : 0}`
// Each row's last drawing, by its requestId: a redraw with the same inputs
// and the same stamp (a scroll step, a new onScreen) returns the same thing,
@@ -159,8 +163,8 @@ const stampOf = (ready: { env: Env; done: number }, view?: RenderViewport) =>
// one pointer), `extra` its other inputs.
type Memo<T> = { text: string; extra: string; stamp: string; onScreen: boolean | undefined; value: T }
// An answer's tree is kept with its link rows (the copy counts them under
-// its pages) and its pages, a plan's drawing with its link rows.
-type AnswerMemo = { tree: RenderElement; links: readonly ShownLink[]; pages: { result: Result; bytes?: readonly string[] } }
+// its pages), a plan's drawing with its link rows.
+type AnswerMemo = { tree: RenderElement; links: readonly ShownLink[] }
const answers = new Map<string, Memo<AnswerMemo>>()
const plans = new Map<string, Memo<{ drawing: Drawing; links: ShownLink[] }>>()
const unders = new Map<string, Memo<Under[]>>()
@@ -228,7 +232,8 @@ async function planEnv($: EngineInterface): Promise<Env | null> {
// 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.
+// asked for. No timer reads the clipboard; the selection is read every
+// 250 ms only while a picture selection shows (watchNative).
// Notes a drawing for a copy (noteDrawn, noteDrawnAgain), turns on the
// watcher's clipboard part and queues its pages for picture select's
@@ -435,9 +440,10 @@ async function dump($: EngineInterface, on: boolean): Promise<string> {
// A Client's post: the selection after it, shown (once a frame at most, the
// 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.
+// copy at the up, and lets a page whose blit was refused try again. A down
+// is always taken (a reloaded sel.tsx counts from 0 again).
function onSelect($: EngineInterface, post: SelectPost, surface: RenderSurface) {
- if (post.seq <= picked.seq) return
+ if (post.seq <= picked.seq && post.phase !== 'down') return
picked.seq = post.seq
const d = drawnAnswers.get(post.id)
const was = picked.now
@@ -452,6 +458,7 @@ function onSelect($: EngineInterface, post: SelectPost, surface: RenderSurface)
}
}
if (was || picked.now) redrawSelection($)
+ watchNative($, () => clearSelection($))
// 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)
}
@@ -471,11 +478,15 @@ async function selectionText($: EngineInterface, d: Drawn & { job?: Job }, sel:
}
// The button came up: the selection's text on the clipboard, with the
-// toast of a copy. No text under it: nothing is copied.
+// toast of a copy. No text under it: nothing is copied; a newer up while
+// its words are read: the newer one copies.
+let copies = 0
async function copySelection($: EngineInterface, d: Drawn & { job?: Job }, sel: Selection, surface: RenderSurface) {
const t = performance.now()
+ const mine = ++copies
const probed: number[] = []
const text = await selectionText($, d, sel, probed)
+ if (mine !== copies) return
const read = performance.now() - t
if (text === null) {
uiToast($, 'Intelligent UI: could not read the selected picture')
@@ -502,6 +513,7 @@ async function traceCopy($: EngineInterface, text: string, total: number, read:
// Picture select now, for /iui details: on, or why it is off.
function selectState(): string {
+ if (S.cacheProblem) return `off (${S.cacheProblem})`
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)`
@@ -510,13 +522,22 @@ function selectState(): string {
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).
+// No selection drawn (a new turn, typing in the prompt, a native
+// selection, Intelligent UI or select off).
function clearSelection($: EngineInterface) {
+ stopNative()
if (!picked.now) return
picked.now = null
redrawSelection($)
}
+// Intelligent UI or picture select off: no selection, and the page cache
+// let go (its pages, its build, its pump).
+function releaseSelect($: EngineInterface) {
+ clearSelection($)
+ forgetPages()
+}
+
// ---- Hooks ----------------------------------------------------------------
export const register: Register = on => {
@@ -567,12 +588,28 @@ export const register: Register = on => {
on('ui.fault', async ($, e, next) => {
if (e.module.endsWith('sel.tsx')) {
picked.isBroken = true
- picked.now = null
+ releaseSelect($)
+ // The rows drawn again with no Client.
+ refresh($)
void Promise.resolve(uiLog($, `Intelligent UI: picture select is off (${e.phase}: ${e.reason})`, { to: 'debug' })).catch(() => undefined)
}
return next(e)
}).catch(($, e, next) => next(e))
+ // Typing in the main prompt takes a picture selection down (a key that
+ // edits, not a bare cursor move); the edit passes on as it is.
+ on('prompt.edit', async ($, e, next) => {
+ if (picked.now && (e.inputText || e.end > e.start)) clearSelection($)
+ return next(e)
+ }).catch(($, e, next) => next(e))
+
+ // A change of the prompt box no edit carried (a recalled entry, an undo, a
+ // clear): the same, but not another plugin's fill. Observe only.
+ on('prompt.change', async ($, e, next) => {
+ if (picked.now && e.origin.kind !== 'plugin' && e.origin.kind !== 'app') clearSelection($)
+ return next(e)
+ }).catch(($, e, next) => next(e))
+
// Typeahead for /iui arguments; the theme list is the last scan's.
on('prompt.autocomplete', async ($, e, next) => {
const got = await next(e)
@@ -594,7 +631,7 @@ export const register: Register = on => {
// On: the clipboard part starts with the next picture drawn.
if (asked.kind === 'off') {
stopClipboard($)
- clearSelection($)
+ releaseSelect($)
}
await storeSet($, 'enabled', asked.kind === 'on')
return { text: `Intelligent UI is ${asked.kind}.` }
@@ -642,7 +679,7 @@ export const register: Register = on => {
if (asked.on === undefined) await setUp($).catch(() => null)
else {
S.select = asked.on
- if (!S.select) clearSelection($)
+ if (!S.select) releaseSelect($)
refresh($)
await storeSet($, 'select', S.select)
}
@@ -701,7 +738,9 @@ export const register: Register = on => {
if (asked.kind === 'details') {
const font = ready.termFont ? `terminal font ${ready.termFont}` : `terminal font not known (${ready.isMac ? 'Menlo' : "the theme's code font"} assumed)`
const typst = ready.typst ? `Typst: ${ready.typst}` : `Typst: not found (${typstHintOf(ready.isMac)})`
- const terminal = ready.canDraw
+ const terminal = S.cacheProblem
+ ? `Intelligent UI draws no pictures: ${S.cacheProblem} (it never uses a shared folder instead)`
+ : ready.canDraw
? `this terminal draws pictures${ready.inline ? ' (over ssh, sent as bytes)' : ''}`
: 'Claude Code draws no pictures here (it does in kitty and Ghostty, in iTerm2 3.6+ and Rio 0.5.27+ with CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1, over ssh when TERM names kitty or Ghostty or with that variable; never in tmux, screen or a background session; not in WezTerm, Warp, Konsole or others), so answers stay text'
await clipWayReady()
@@ -712,7 +751,8 @@ export const register: Register = on => {
// The short state: what is set, and only the problems that keep pictures away.
const sized = (v: number | 'full' | 'half', unit: string) => (typeof v === 'number' ? `${v} ${unit}` : v)
const lines = [`Intelligent UI is ${state}: theme ${theme}, ${S.theme}, text ${S.size}%, width ${sized(S.width, 'columns')}, height ${sized(S.height, 'rows')}, grid ${S.grid ? 'on' : 'off'}.`]
- if (S.setupNeeded) lines.push('In iTerm2, run /iui setup once to show pictures.')
+ if (S.cacheProblem) lines.push(`No pictures: ${S.cacheProblem}. See /iui details.`)
+ else if (S.setupNeeded) lines.push('In iTerm2, run /iui setup once to show pictures.')
else if (!ready.canDraw) {
const where = ready.isMac ? 'kitty, Ghostty and iTerm2 3.6+' : 'kitty and Ghostty, and in Rio with CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1'
lines.push(`This terminal shows no pictures, so answers stay text. Pictures show in ${where}.`)
@@ -824,7 +864,7 @@ export const register: Register = on => {
noteDrawn(e.requestId, result, roomColumns(e.viewport), { top: MARGIN_TOP, after: links.length })
noteOnScreen(e.requestId, e.props.onScreen)
})
- memoSet(answers, e.requestId, k, { tree, links, pages: { result, ...(drawing.bytes ? { bytes: drawing.bytes } : {}) } })
+ memoSet(answers, e.requestId, k, { tree, links })
return tree
}
answers.delete(e.requestId)
diff --git a/hooks/sel.tsx b/hooks/sel.tsx
index 818b64d..b2ae77b 100644
--- a/hooks/sel.tsx
+++ b/hooks/sel.tsx
@@ -3,6 +3,8 @@
// whole (anchor, head, phase and order), never a bare event: posts of one
// frame merge, the last one kept. A click with no drag posts `clear`. It
// draws only an empty Box: anything drawn would blank the picture's cells.
+// It sets no key listener: with one, a click would give it the keys (the
+// prompt would get none until Escape), and Escape never reaches it.
import type { ClientModule, JsonValue } from 'claude-code'
type Props = { id: string; page: number }
@@ -28,6 +30,13 @@ const Select: ClientModule<Props, Drag> = (props, surface) => {
return
}
if (!now?.isDown || (ev.type !== 'move' && ev.type !== 'up')) return
+ // A move with no button while down: its up was lost, so the drag ends where it was.
+ if (ev.type === 'move' && !ev.button) {
+ const ended = { ...now, isDown: false }
+ surface.setState(ended)
+ post(ended, ended.hx === ended.ax && ended.hy === ended.ay ? 'clear' : 'up')
+ return
+ }
const next = { ...now, hx: ev.x, hy: ev.y, isDown: ev.type === 'move' }
if (ev.type === 'move' && next.hx === now.hx && next.hy === now.hy) return
surface.setState(next)
diff --git a/tests/cache-sh-test.sh b/tests/cache-sh-test.sh
index f86261b..2480d10 100644
--- a/tests/cache-sh-test.sh
+++ b/tests/cache-sh-test.sh
@@ -1,6 +1,7 @@
#!/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
+# a cache folder that is a link is never used or changed (it is named, for
+# /iui details); 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
@@ -29,6 +30,7 @@ for s in $shells; do
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)"
+ [ "$(echo "$out" | sed -n 4p)" = "$td/cc-intelligent-ui-$uid" ] && ok || bad "$s CACHE_SH: the refused folder is not named ($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
diff --git a/tests/copy.test.ts b/tests/copy.test.ts
index bbdd156..6158593 100644
--- a/tests/copy.test.ts
+++ b/tests/copy.test.ts
@@ -503,8 +503,12 @@ const inputsOf = (argv: readonly string[]) => Object.fromEntries(argv.flatMap((a
// `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`
-// the debug log lines.
-function world(on: any, o: { failFirst?: boolean; noBridge?: boolean; env?: Record<string, string>; tty?: string; version?: string; deny?: string } = {}) {
+// the debug log lines. `noPerl`: perl can not start; `beforeWrite` runs
+// before each frame write; `refused`: the cache folder sweep refuses that folder.
+function world(
+ on: any,
+ o: { failFirst?: boolean; noBridge?: boolean; env?: Record<string, string>; tty?: string; version?: string; deny?: string; noPerl?: boolean; beforeWrite?: () => Promise<void>; refused?: string } = {},
+) {
forgetBlits()
forgetRedraws()
mock.store(on)
@@ -527,7 +531,7 @@ function world(on: any, o: { failFirst?: boolean; noBridge?: boolean; env?: Reco
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[],
+ frames: [] as { path: string; old: string[]; png: Uint8Array }[], blits: [] as any[], writes: 0, selectionReads: 0,
selection: undefined as { text: string; requestId?: string } | undefined,
selects: true,
gate: null as Promise<void> | null, release: () => {},
@@ -598,9 +602,12 @@ function world(on: any, o: { failFirst?: boolean; noBridge?: boolean; env?: Reco
killers.get(argv[1]!)?.()
return ok('')
}
- if (/cc-intelligent-ui-/.test(cmd)) return ok('/c\nDarwin\n')
+ if (/cc-intelligent-ui-/.test(cmd)) return ok(o.refused ? `\nDarwin\n\n${o.refused}\n` : '/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) {
+ w.writes++
+ if (o.noPerl) return { deny: 'spawn /usr/bin/perl ENOENT' }
+ await o.beforeWrite?.()
w.frames.push({ path: argv[3]!, old: argv.slice(4), png: fromBase64(e.init?.stdin ?? '') })
return ok('')
}
@@ -639,7 +646,10 @@ function world(on: any, o: { failFirst?: boolean; noBridge?: boolean; env?: Reco
w.foreign(e.text)
return { value: { isCopied: true } }
})
- on('ui.selection', async () => ({ value: w.selection }))
+ on('ui.selection', async () => {
+ w.selectionReads++
+ return { value: w.selection }
+ })
on('ui.blit', async ($: any, e: any) => {
w.blits.push(e)
return { value: o.deny ? { deny: o.deny } : {} }
@@ -1465,3 +1475,213 @@ test('picture select: /iui select off takes the Client away', async ($, on) => {
await w.clock.settle()
expect(tree(await ui.drawn()).some(n => n.type === 'Client')).toBe(false)
})
+
+// A drag over rows 1 to 3 (to column 21): COPIED.
+const drag = async (ui: any) => {
+ 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' })
+}
+// The last blit: the page's own PNG, or its newest frame.
+const isPlain = (w: ReturnType<typeof world>) => /^\/c\/[0-9a-f]+\/a-1\.png$/.test(w.blits.at(-1)?.source.file ?? '')
+const isFrame = (w: ReturnType<typeof world>) => !!w.frames.length && w.blits.at(-1)?.source.file === w.frames.at(-1)!.path
+const hasClient = async (ui: any) => tree(await ui.drawn()).some(n => n.type === 'Client')
+
+test('picture select: typing in the prompt takes the selection down; a bare cursor move and another plugin\'s fill do not', async ($, on) => {
+ const w = world(on, { tty: TTY })
+ on('prompt.edit', async ($: any, e: any) => ({ text: e.text.slice(0, e.start) + e.inputText + e.text.slice(e.end), cursor: e.start + e.inputText.length }))
+ on('prompt.change', async ($: any, e: any) => ({ text: e.text }))
+ await $.command.run({ command: 'iui', args: '' } as any)
+ const prompt = ($ as any).prompt
+ const ui = await drawAnswer($, w)
+ await drag(ui)
+ await settle(w)
+ expect(isFrame(w)).toBe(true)
+ const blits = w.blits.length
+ await prompt.edit({ origin: { kind: 'composer' }, text: 'ab', cursor: 2, start: 1, end: 1, inputText: '' } as any)
+ await prompt.change({ text: 'x', cursor: 1, origin: { kind: 'plugin', name: 'other' } })
+ await settle(w)
+ expect(w.blits.length).toBe(blits)
+ // A key typed: the page's own PNG back; the edit is the engine's as it was.
+ const edited = await prompt.edit({ origin: { kind: 'composer' }, text: 'ab', cursor: 2, start: 2, end: 2, inputText: 'c' })
+ expect(edited).toMatchObject({ text: 'abc', cursor: 3 })
+ await settle(w)
+ expect(isPlain(w)).toBe(true)
+ // A recalled history entry: the same.
+ await drag(ui)
+ await settle(w)
+ expect(isFrame(w)).toBe(true)
+ await prompt.change({ text: 'old', cursor: 3, origin: { kind: 'history' } })
+ await settle(w)
+ expect(isPlain(w)).toBe(true)
+})
+
+test('picture select: a new native selection takes it down (read every 250 ms while it shows); one made before it does not; no reads with none shown', async ($, on) => {
+ const w = world(on, { tty: TTY })
+ await $.command.run({ command: 'iui', args: '' } as any)
+ const ui = await drawAnswer($, w)
+ w.selection = { text: 'made before' }
+ await drag(ui)
+ await settle(w)
+ await w.clock.advance(600)
+ await settle(w)
+ expect(isFrame(w)).toBe(true)
+ expect(w.selectionReads).toBeGreaterThan(1)
+ w.selection = { text: 'a new one', requestId: 'ans-0' }
+ await w.clock.advance(300)
+ await settle(w)
+ expect(isPlain(w)).toBe(true)
+ // None shows now: the timer is gone.
+ const reads = w.selectionReads
+ await w.clock.advance(2000)
+ await settle(w)
+ expect(w.selectionReads).toBe(reads)
+})
+
+test('picture select: a move with no button while the button is down (its up lost) ends the drag where it was: copied, not extended', async ($, on) => {
+ const w = world(on, { tty: TTY })
+ await $.command.run({ command: 'iui', args: '' } as any)
+ const ui = await drawAnswer($, w)
+ 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: 'move', x: 21, y: 3, button: 'left', in: 'sel0' })
+ await ui.pointer({ type: 'move', x: 40, y: 8, in: 'sel0' })
+ await settle(w)
+ expect(w.copies).toEqual([COPIED])
+ const frames = w.frames.length
+ await ui.pointer({ type: 'move', x: 50, y: 9, in: 'sel0' })
+ await settle(w)
+ expect(w.frames.length).toBe(frames)
+ expect(cellOf(w.frames.at(-1)!.png, 3, 22)).toBe('page')
+})
+
+test('picture select: a down is taken whatever its order (a reloaded Client counts from 0 again)', async ($, on) => {
+ const w = world(on, { tty: TTY })
+ await $.command.run({ command: 'iui', args: '' } as any)
+ const ui = await drawAnswer($, w)
+ await drag(ui)
+ await settle(w)
+ const post = (phase: string, seq: number, head: { x: number; y: number }) => ui.post({ id: 'ans-1', page: 0, anchor: { x: 0, y: 1 }, head, phase, seq }, { in: 'sel0' })
+ await post('down', 1, { x: 0, y: 1 })
+ await post('move', 2, { x: 10, y: 2 })
+ await settle(w)
+ const png = w.frames.at(-1)!.png
+ expect([cellOf(png, 2, 10), cellOf(png, 2, 11), cellOf(png, 3, 0)]).toEqual(['selected', 'page', 'page'])
+})
+
+test('picture select: a slow copy never lands after a newer one: only the last up copies', async ($, on) => {
+ const w = world(on, { tty: TTY })
+ await $.command.run({ command: 'iui', args: '' } as any)
+ w.hold()
+ const ui = await drawAnswer($, w)
+ await drag(ui)
+ await settle(w)
+ await ui.pointer({ type: 'down', x: 0, y: 1, button: 'left', in: 'sel0' })
+ await ui.pointer({ type: 'up', x: 8, y: 1, button: 'left', in: 'sel0' })
+ await settle(w)
+ expect(w.copies).toEqual([])
+ w.release()
+ await settle(w)
+ expect(w.copies.length).toBe(1)
+ expect(w.copies[0]).not.toBe(COPIED)
+ expect(COPIED.startsWith(w.copies[0]!)).toBe(true)
+})
+
+test('picture select: the same row drawn on the main screen, then in fullscreen, gets its Client (no memo hit)', async ($, on) => {
+ const w = world(on, { tty: TTY })
+ await $.command.run({ command: 'iui', args: '' } as any)
+ const main = await drawAnswer($, w, 'ans-1', SMALL_MD, false)
+ expect(await hasClient(main)).toBe(false)
+ await main.unmount()
+ const full = await drawAnswer($, w, 'ans-1', SMALL_MD, true)
+ expect(await hasClient(full)).toBe(true)
+})
+
+test('picture select: /iui select off and /iui off let the page cache go', async ($, on) => {
+ const w = world(on, { tty: TTY })
+ await $.command.run({ command: 'iui', args: '' } as any)
+ const pngReads = () => w.reads.filter(r => r.endsWith('/a-1.png')).length
+ const ui = await drawAnswer($, w)
+ expect(pngReads()).toBe(1)
+ // Off, then on: the page is built again (read again) at the next draw.
+ await $.command.run({ command: 'iui', args: 'select off' } as any)
+ await $.command.run({ command: 'iui', args: 'select on' } as any)
+ await w.clock.settle()
+ await ui.redraw(props(SMALL_MD))
+ await settle(w)
+ expect(pngReads()).toBe(2)
+ await $.command.run({ command: 'iui', args: 'off' } as any)
+ await $.command.run({ command: 'iui', args: 'on' } as any)
+ await w.clock.settle()
+ await ui.redraw(props(SMALL_MD))
+ await settle(w)
+ expect(pngReads()).toBe(3)
+ // The drag still works on the page built again.
+ await drag(ui)
+ await settle(w)
+ expect(w.copies).toEqual([COPIED])
+ expect(isFrame(w)).toBe(true)
+})
+
+test('picture select: a frame of a page file the row no longer draws is not blitted; the new file gets its own frame', async ($, on) => {
+ let redraw: (() => Promise<void>) | null = null
+ const w = world(on, {
+ tty: TTY,
+ // The row is drawn again with a new page file while the first frame is written.
+ beforeWrite: async () => {
+ const r = redraw
+ redraw = null
+ await r?.()
+ },
+ })
+ await $.command.run({ command: 'iui', args: '' } as any)
+ const ui = await drawAnswer($, w)
+ const other = `${SMALL_MD}\n\nOne more line.`
+ redraw = async () => {
+ await ui.redraw(props(other))
+ await w.clock.settle()
+ await w.clock.advance(1000)
+ await w.clock.settle()
+ await ui.redraw(props(other))
+ await w.clock.settle()
+ }
+ await drag(ui)
+ await settle(w)
+ expect(w.compiles.length).toBe(2)
+ const stale = w.frames[0]!.path
+ expect(w.blits.some(b => b.source.file === stale)).toBe(false)
+ expect(new Set(w.reads.filter(r => r.endsWith('/a-1.png'))).size).toBe(2)
+ expect(isFrame(w)).toBe(true)
+})
+
+test('picture select: with no perl the first frame write fails, is logged once and none is tried again; the copy still works', async ($, on) => {
+ const w = world(on, { tty: TTY, noPerl: true })
+ await $.command.run({ command: 'iui', args: '' } as any)
+ const ui = await drawAnswer($, w)
+ await drag(ui)
+ await settle(w)
+ await drag(ui)
+ await settle(w)
+ expect(w.writes).toBe(1)
+ expect(w.logs.filter(l => l.includes('could not be written')).length).toBe(1)
+ expect(w.copies).toEqual([COPIED, COPIED])
+})
+
+test('no private cache folder: nothing is drawn (no shared folder instead); /iui, its details and a toast say why', async ($, on) => {
+ const refused = '/t/cc-intelligent-ui-501'
+ const w = world(on, { tty: TTY, refused })
+ const why = `the cache folder ${refused} is a link, not a folder, or not yours`
+ expect((await $.command.run({ command: 'iui', args: '' } as any)).text).toContain(`No pictures: ${why}. See /iui details.`)
+ const ui = await $.ui.mount(message('ans-1', SMALL_MD))
+ await settle(w)
+ await ui.redraw(props(SMALL_MD))
+ await settle(w)
+ expect(tree(await ui.drawn()).some(n => n.type === 'Image' || n.type === 'Client')).toBe(false)
+ expect(w.compiles).toEqual([])
+ const details = (await $.command.run({ command: 'iui', args: 'details' } as any)).text ?? ''
+ expect(details).toContain(`Intelligent UI draws no pictures: ${why}`)
+ expect((await detailLines($))[0]).toBe(`Picture select: off (${why})`)
+ expect(w.toasts).toContain(`Intelligent UI: no pictures, ${why} (see /iui details)`)
+ // The old shared folder is never used.
+ expect([...w.ran.flat(), ...w.reads, ...w.files.keys()].some(t => t.includes('/tmp/cc-intelligent-ui'))).toBe(false)
+})
diff --git a/tests/linux.test.ts b/tests/linux.test.ts
index 79ae9f3..af578ff 100644
--- a/tests/linux.test.ts
+++ b/tests/linux.test.ts
@@ -468,8 +468,9 @@ 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.
+ // A folder that is not private is never used. 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)"`)
+ // A refused folder: no cache line, the OS, then that folder (for /iui details).
+ expect(CACHE_SH).toContain(`|| printf '\\n%s\\n\\n%s\\n' "$(uname -s)" "$d"`)
expect(CACHE_SH).not.toMatch(/ask|shims/)
})
diff --git a/tests/pagecache.test.ts b/tests/pagecache.test.ts
index 7386f97..1cf2994 100644
--- a/tests/pagecache.test.ts
+++ b/tests/pagecache.test.ts
@@ -3,9 +3,9 @@ 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,
+ bytesFor, evictKeys, forgetPages, holdPages, 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 { bytesOf, frameNow, 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'
@@ -29,15 +29,16 @@ test("the next page: the last down's first, then the pages on screen, the newest
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', () => {
+test('the pages kept fit their budget: only the oldest off screen go; the ones on screen, the selection\'s and 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'])
+ expect(evictKeys(kept, 160, new Set(['d']))).toEqual([])
+ expect(evictKeys(kept, 120, new Set(['d']))).toEqual(['b'])
+ expect(evictKeys(kept, 80, new Set())).toEqual(['b', 'd'])
+ // Over the budget with the pages on screen: they stay (no thrash).
+ expect(evictKeys(kept, 80, new Set(['d']))).toEqual(['b'])
+ expect(evictKeys(kept, 0, new Set(['b']))).toEqual(['d'])
})
test('the pages on screen: by the rows of the message on screen and the page tops; all when not known, none off screen', () => {
@@ -215,3 +216,167 @@ test('a page that can not be read gets no frames, is not tried again, and a down
await f.drain()
expect(await needFrames(f.$, pageOf(0), COLOR)).toEqual({ frames: null, waitMs: 0 })
})
+
+const key = (n: number) => keyOf(pageOf(n), COLOR)
+
+test('a down on a page whose build was stopped (off screen) before its next slice takes the build up again: its frames come', async () => {
+ const f = fake()
+ notePages(f.$, drawn('a', 1, [0, 1], { first: 0, last: 15, of: 32 }), COLOR)
+ await f.tick()
+ await f.tick()
+ expect(pages.build?.want.page.file).toBe(pageOf(0).file)
+ // Scrolled: page 0 off screen, its build stopped but not dropped yet.
+ notePages(f.$, drawn('a', 1, [0, 1], { first: 16, last: 31, of: 32 }), COLOR)
+ expect(pages.build?.isCancelled).toBe(true)
+ let got: { frames: unknown } | undefined
+ void needFrames(f.$, pageOf(0), COLOR, { id: 'a', index: 0, seq: 1 }).then(r => (got = r))
+ await f.drain()
+ expect((got?.frames as { plain: unknown[] } | undefined)?.plain.length).toBe(16)
+ expect(pages.waiters.size).toBe(0)
+ expect(pages.isPumping).toBe(false)
+ // Read once: the build went on.
+ expect(files(f.reads).filter(r => r === pageOf(0).file).length).toBe(1)
+})
+
+test('a page stopped off screen and back on screen before its next slice goes on', async () => {
+ const f = fake()
+ notePages(f.$, drawn('a', 1, [0]), COLOR)
+ await f.tick()
+ notePages(f.$, drawn('a', 1, [0], null), COLOR)
+ notePages(f.$, drawn('a', 1, [0]), COLOR)
+ await f.drain()
+ expect(pages.frames.get(key(0))?.plain.length).toBe(16)
+ expect(f.reads.length).toBe(1)
+})
+
+test('pages on screen over the budget do not thrash: the background builds what fits, a down builds its page all the same', async () => {
+ const f = fake()
+ // One page fits, not two.
+ pages.budget = Math.floor(bytesFor(pageOf(0)) * 1.5)
+ const d = drawn('a', 1, [0, 1])
+ notePages(f.$, d, COLOR)
+ // Each render notes the pages again, as the row is drawn while the cache works.
+ for (let n = 0; n < 3000; n++) {
+ if (!(await f.tick())) {
+ notePages(f.$, d, COLOR)
+ if (!f.timers.length) break
+ continue
+ }
+ if (n % 5 === 0) notePages(f.$, d, COLOR)
+ }
+ expect(files(f.reads)).toEqual([pageOf(0).file])
+ expect([...pages.frames.keys()]).toEqual([key(0)])
+ expect(pages.wants.has(key(1))).toBe(true)
+ // A down on page 1: built over the budget (a soft limit); page 0, on screen, stays.
+ const got = needFrames(f.$, pageOf(1), COLOR, { id: 'a', index: 1, seq: 1 })
+ await f.drain()
+ expect((await got).frames?.plain.length).toBe(16)
+ expect(new Set(pages.frames.keys())).toEqual(new Set([key(0), key(1)]))
+ // Page 0 off screen: it goes at the next build.
+ notePages(f.$, drawn('a', 1, [0, 1, 2], { first: 17, last: 48, of: 49 }), COLOR)
+ const two = needFrames(f.$, pageOf(2), COLOR, { id: 'a', index: 2, seq: 1 })
+ await f.drain()
+ expect((await two).frames).not.toBeNull()
+ expect(pages.frames.has(key(0))).toBe(false)
+ expect(f.reads.length).toBe(3)
+})
+
+test("the selection's page is never dropped, on screen or not", async () => {
+ const f = fake()
+ pages.budget = Math.floor(bytesFor(pageOf(0)) * 1.5)
+ notePages(f.$, drawn('a', 1, [0]), COLOR)
+ await f.drain()
+ holdPages([key(0)])
+ // Page 0 off screen, page 1 on screen: no room for it in the background.
+ notePages(f.$, drawn('a', 1, [0, 1], { first: 17, last: 32, of: 33 }), COLOR)
+ await f.drain()
+ expect(f.reads.length).toBe(1)
+ // A down on page 1: built, and page 0 (the selection's) stays.
+ const one = needFrames(f.$, pageOf(1), COLOR, { id: 'a', index: 1, seq: 1 })
+ await f.drain()
+ expect((await one).frames).not.toBeNull()
+ expect(new Set(pages.frames.keys())).toEqual(new Set([key(0), key(1)]))
+ // Let go: the next build drops it.
+ holdPages([])
+ notePages(f.$, drawn('a', 1, [0, 1, 2], { first: 33, last: 48, of: 49 }), COLOR)
+ const two = needFrames(f.$, pageOf(2), COLOR, { id: 'a', index: 2, seq: 1 })
+ await f.drain()
+ expect((await two).frames).not.toBeNull()
+ expect(pages.frames.has(key(0))).toBe(false)
+})
+
+test('a drawing drawn again with new page files (a stream, a resize, a theme) drops its old keys: one page queued, the old builds stopped, who waits gets none', async () => {
+ const f = fake()
+ const page = (v: number) => ({ file: `/c/k${v % 3}/v${v}/a-1.png`, width: 1568, height: 512, columns: 98, rows: 16 })
+ const draw = (v: number): Drawn => ({ id: 'a', seq: v + 1, dir: `/c/v${v}`, pages: [page(v)], place: { below: 0 } })
+ notePages(f.$, draw(0), COLOR)
+ await f.tick()
+ await f.tick()
+ expect(pages.build?.want.page.file).toBe(page(0).file)
+ const old = needFrames(f.$, page(0), COLOR)
+ for (let v = 1; v < 10; v++) notePages(f.$, draw(v), COLOR)
+ expect([...pages.screen]).toEqual([keyOf(page(9), COLOR)])
+ expect([...pages.wants.keys()]).toEqual([keyOf(page(9), COLOR)])
+ expect(pages.build?.isCancelled).toBe(true)
+ expect((await old).frames).toBeNull()
+ await f.drain()
+ expect(files(f.reads)).toEqual([page(0).file, page(9).file])
+ expect([...pages.frames.keys()]).toEqual([keyOf(page(9), COLOR)])
+ // A key another drawing still uses stays.
+ notePages(f.$, { ...draw(9), id: 'b' }, COLOR)
+ notePages(f.$, draw(10), COLOR)
+ expect(pages.screen.has(keyOf(page(9), COLOR))).toBe(true)
+})
+
+test('a ready build a down puts aside is paused: its tinted rows are made in the background after the down', async () => {
+ const f = fake()
+ notePages(f.$, drawn('a', 1, [0, 1]), COLOR)
+ // Until page 0 is ready, with its tinted rows still to make.
+ for (let n = 0; n < 100000 && !(pages.frames.has(key(0)) && pages.build?.want.key === key(0)); n++) await f.tick()
+ expect(pages.frames.get(key(0))!.tint.filter(Boolean).length).toBeLessThan(16)
+ const one = needFrames(f.$, pageOf(1), COLOR, { id: 'a', index: 1, seq: 1 })
+ expect(pages.wants.get(key(0))?.paused?.isReady).toBe(true)
+ await f.drain()
+ expect((await one).frames).not.toBeNull()
+ expect(pages.frames.get(key(0))!.tint.filter(Boolean).length).toBe(16)
+ expect(f.reads.length).toBe(2)
+})
+
+test("a frame makes tinted rows for its time at most (one at least), the rest drawn plain; the next frames make them, the same frame in the end", () => {
+ const png = Uint8Array.from(atob(PNGS[0]!), c => c.charCodeAt(0))
+ const f = framesOf(decodePng(png), pageOf(0), rgbOf(COLOR))
+ const rows = Array.from({ length: 14 }, (_, i) => ({ row: i + 1, x0: 0, x1: 97 }))
+ // A clock that moves 1 ms at each read: 3 ms make three rows.
+ let t = 0
+ const now = () => t++
+ const first = frameNow(f, rows, 3, now)
+ expect(first.isWhole).toBe(false)
+ expect(f.tint.filter(Boolean).length).toBe(3)
+ let n = 1
+ for (let made = first; !made.isWhole; n++) made = frameNow(f, rows, 3, now)
+ expect(n).toBe(5)
+ expect(f.tint.filter(Boolean).length).toBe(14)
+ const whole = framesOf(decodePng(png), pageOf(0), rgbOf(COLOR))
+ expect(toBase64(frameNow(f, rows, 3, now).png)).toBe(toBase64(frameOf(whole, rows)))
+ // A budget of 0 still makes one row.
+ const g = framesOf(decodePng(png), pageOf(0), rgbOf(COLOR))
+ expect(frameNow(g, rows, 0, now).isWhole).toBe(false)
+ expect(g.tint.filter(Boolean).length).toBe(1)
+ expect(bytesOf(g)).toBeGreaterThan(0)
+})
+
+test('a forget (select off) gives who waits no frames, stops the pump, and a new pump starts clean', async () => {
+ const f = fake()
+ notePages(f.$, drawn('a', 1, [0]), COLOR)
+ await f.tick()
+ const got = needFrames(f.$, pageOf(1), COLOR, { id: 'a', index: 1, seq: 1 })
+ forgetPages()
+ expect((await got).frames).toBeNull()
+ await f.drain()
+ expect(pages.frames.size).toBe(0)
+ expect(pages.isPumping).toBe(false)
+ notePages(f.$, drawn('a', 1, [1]), COLOR)
+ expect(f.timers.length).toBe(1)
+ await f.drain()
+ expect(pages.frames.get(key(1))?.plain.length).toBe(16)
+})