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
Paste preview: a pasted image path shows its preview
razorback161595dea3fcc1
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4d1fbdd..54396ca 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -2,6 +2,16 @@All releases of Intelligent UI for Claude Code (`cc-intelligent-ui`). Claude Code finds a new version by the `version` in `.claude-plugin/plugin.json`. To get it, refer to [Update](docs/install.md#update).+## Unreleased++### New++- **A preview of pasted image paths.** When you paste the path of an image file (path text that you copied), Claude Code shows `[Image #N]` but writes no file until you send the prompt. The mod now reads the clipboard one time to find the file, and shows its preview. Absolute paths, `~/` paths, paths from the session folder, `file://` URLs, quoted paths and paths with escaped spaces work. It shows PNG, JPEG and WebP files (JPEG and WebP need Typst).++### Fixed++- **An empty row above the previews.** The previews of pasted images no longer touch the line above them (for example "Crunched for 7s").+## 0.3.3 (2026-10-23)### Newdiff --git a/docs/development.md b/docs/development.mdindex 4f4a6ff..c1ef11a 100644--- a/docs/development.md+++ b/docs/development.md@@ -52,7 +52,7 @@ Picture select writes trace lines that start with `select:`:## Module layout-The hooks module is `hooks/register.tsx`. It connects the hooks to the modules in `hooks/lib/`. Each module has one topic, for example `markdown.ts` (blocks and segments), `mode.ts` (light or dark), `typst.ts` (compile), `fonts.ts` (the lean font set: the fonts that a compile of plain text loads), `draw.tsx` (the pages of an answer and the link rows under them), `links.ts` (the links, file paths and commands of a text), `answer.ts` (one text through the compile and cache steps), `plan.tsx` (the plan approval question and the plan rows), `composer.tsx` (the previews of the images pasted in the draft, above the prompt box), `frame.ts` (the terminal size and the watcher process, which also reports the clipboard changes), `clipboard.ts` (how the clipboard is read and watched for the `/iui grab` toast: macOS, or the Linux tools), `copy.ts` (the text under a mouse selection of pictures), `select.ts` and `blit.ts` (picture select and its highlight), `frames.ts` (the frames of a page: the cell edges, the bands, the row pieces and the frame PNG), `pagecache.ts` (the background page cache: the build queue in slices, and the words probe), `png.ts` (PNG decode, also in steps, and the deflate pieces, in plain JavaScript), `flip.ts` (herdr in iTerm2: the pages and pictures stored with the bands of their rows moved), `probe.ts` (the drawn pages, and the words of a page that a copy reads, kept in memory) and `updates.ts` (the daily check for a new version). The values that change are in one object, `S`, in `state.ts`. The hook bodies in `register.tsx` call `$` themselves; every other `$` call is a wrapper with a short name in `api.ts` (for example `cat` for `$.fs.read`, `exec` for `$.process.run`). The `calls:` note of `claude plugin validate` names each method with the wrappers that call it (`via cat`), and a method that a hook body calls with none. The validator cuts a note at about 1,000 characters and marks the cut `[+N chars]`; the catalogue scan then cannot read the footprint. `tests/footprint-sh-test.sh` is the release gate for this: it fails on a `[+N chars]` mark in the text or the `--json` report, on a calls line (the text after `calls: `) of more than 850 characters, and on a `$` call in `hooks/` outside `api.ts` and `register.tsx`. The tests import from `hooks/register.tsx`, which exports the names that they use.+The hooks module is `hooks/register.tsx`. It connects the hooks to the modules in `hooks/lib/`. Each module has one topic, for example `markdown.ts` (blocks and segments), `mode.ts` (light or dark), `typst.ts` (compile), `fonts.ts` (the lean font set: the fonts that a compile of plain text loads), `draw.tsx` (the pages of an answer and the link rows under them), `links.ts` (the links, file paths and commands of a text), `answer.ts` (one text through the compile and cache steps), `plan.tsx` (the plan approval question and the plan rows), `composer.tsx` (the previews of the images pasted in the draft, above the prompt box, and the files of pasted image paths, from one clipboard read), `frame.ts` (the terminal size and the watcher process, which also reports the clipboard changes), `clipboard.ts` (how the clipboard is read and watched for the `/iui grab` toast and read for a pasted image path: macOS, or the Linux tools), `copy.ts` (the text under a mouse selection of pictures), `select.ts` and `blit.ts` (picture select and its highlight), `frames.ts` (the frames of a page: the cell edges, the bands, the row pieces and the frame PNG), `pagecache.ts` (the background page cache: the build queue in slices, and the words probe), `png.ts` (PNG decode, also in steps, and the deflate pieces, in plain JavaScript), `flip.ts` (herdr in iTerm2: the pages and pictures stored with the bands of their rows moved), `probe.ts` (the drawn pages, and the words of a page that a copy reads, kept in memory) and `updates.ts` (the daily check for a new version). The values that change are in one object, `S`, in `state.ts`. The hook bodies in `register.tsx` call `$` themselves; every other `$` call is a wrapper with a short name in `api.ts` (for example `cat` for `$.fs.read`, `exec` for `$.process.run`). The `calls:` note of `claude plugin validate` names each method with the wrappers that call it (`via cat`), and a method that a hook body calls with none. The validator cuts a note at about 1,000 characters and marks the cut `[+N chars]`; the catalogue scan then cannot read the footprint. `tests/footprint-sh-test.sh` is the release gate for this: it fails on a `[+N chars]` mark in the text or the `--json` report, on a calls line (the text after `calls: `) of more than 850 characters, and on a `$` call in `hooks/` outside `api.ts` and `register.tsx`. The tests import from `hooks/register.tsx`, which exports the names that they use.The skill for Claude is in `skills/intelligent-ui/`: `SKILL.md` (the contract, the workflow and an index), `references/` (one file for each topic: Typst, fletcher, CeTZ, plots and charts) and `scripts/check.sh` (the compile check, with the real template). `TYPST_PROMPT` in `hooks/lib/settings.ts` tells Claude when to load it.diff --git a/docs/limitations.md b/docs/limitations.mdindex 4d0d238..2a557c8 100644--- a/docs/limitations.md+++ b/docs/limitations.md@@ -49,6 +49,7 @@## Other features+- **Dragged image paths.** A path that you drag into the terminal does not change the clipboard, so its preview shows only after you send the prompt. If the clipboard holds the path of a different image at that time, the preview shows that image until you send.- **PDF files.** The page buttons work only in fullscreen mode. The mod shows one page at a time, with no page count, and you cannot copy text from a page. The page field gets the keyboard only when the prompt is empty; otherwise click the field to type. Esc then goes to the prompt. To close the field, click it and push Esc, or click its close mark.- **Plan approval.** A mod cannot draw Claude Code's dialog, so the mod asks its own question, with 4 options at most. There is no "keep planning" option: type a reply or push Esc. The edit option needs a GUI editor that waits until you close the file, so not vim or nano, and on Linux not `xdg-open`. Where an organization manages Claude Code, plugin permission hooks do not run, and Claude Code's dialog shows after the mod's question.- **Cache folders.** The mod uses only its private folder `$TMPDIR/cc-intelligent-ui-<uid>`, which must be yours, mode 700 and not a link. If it is not, the mod draws nothing and `/iui details` says why: fix or remove the folder, then start Claude Code again. The mod also keeps drawing spaces in `~/.cache/cc-intelligent-ui/designs` for 180 days, and fonts copied out of terminal apps in `~/.cache/cc-intelligent-ui/fonts` (fonts of an older app build are deleted after 30 days). It uses `$XDG_CACHE_HOME` when set.diff --git a/docs/privacy.md b/docs/privacy.mdindex 3d239dc..8d70f22 100644--- a/docs/privacy.md+++ b/docs/privacy.md@@ -5,8 +5,8 @@The mod sends nothing about you or your sessions anywhere.- **Network:** one GET request each day at most, to `raw.githubusercontent.com`, for the public `plugin.json` of this mod. It only tells you about a new version. `/iui updates off` stops it. It also stops when `CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC`, `DISABLE_UPDATES` or `DISABLE_AUTOUPDATER` is set.-- **Clipboard, read:** a small `perl` process watches the clipboard while the mod is on and has drawn a picture (not over ssh). On macOS it reads only the change counter; when the counter changes, the mod reads the text once with a short `perl` script (PerlObjCBridge). On Linux a notifier (`wl-paste --watch`, `clipnotify` or GTK 3 from `python3`) tells it of each change, and it then reads the text with `wl-paste`, `xclip` or GTK. `/iui grab` with no mouse selection also reads the clipboard once. The text is only checked for picture cells (then a toast names `/iui grab`); it is kept in memory only and sent nowhere (`/iui dump` writes the last clipboard with picture cells to `copy-debug.json` in the cache folder). A password manager's copy is never read: on macOS a copy with a concealed or transient type, on Linux a copy that offers the `x-kde-passwordManagerHint` target, and on Wayland also a copy marked sensitive. (On Wayland, `wl-paste --watch` hands each new copy to `cat`, which drops it.)+- **Clipboard, read:** a small `perl` process watches the clipboard while the mod is on and has drawn a picture (not over ssh). On macOS it reads only the change counter; when the counter changes, the mod reads the text once with a short `perl` script (PerlObjCBridge). On Linux a notifier (`wl-paste --watch`, `clipnotify` or GTK 3 from `python3`) tells it of each change, and it then reads the text with `wl-paste`, `xclip` or GTK. `/iui grab` with no mouse selection also reads the clipboard once. When you paste and a new `[Image #N]` has no image file from Claude Code (a pasted path of an image file), the mod reads the clipboard once to find that file (only while the mod is on and draws pictures, not over ssh); it uses the text only as a list of image paths, keeps them in memory only for the draft, and sends them nowhere. The text is only checked for picture cells (then a toast names `/iui grab`); it is kept in memory only and sent nowhere (`/iui dump` writes the last clipboard with picture cells to `copy-debug.json` in the cache folder). A password manager's copy is never read: on macOS a copy with a concealed or transient type, on Linux a copy that offers the `x-kde-passwordManagerHint` target, and on Wayland also a copy marked sensitive. (On Wayland, `wl-paste --watch` hands each new copy to `cat`, which drops it.)- **Clipboard, written:** only at these times: when you release a picture selection, when you click a link, a file path, a command or a copy button in a picture, on `/iui grab`, when you press the command button in a link row (in fullscreen with `/iui select off`, where Claude Code gets the click), and when the mod changes a `$.ui.copy` that has picture cells to its text.-- **Files:** a private cache folder in `$TMPDIR` (`cc-intelligent-ui-<uid>`, `/tmp` when `TMPDIR` is not set; mode 700, its folders deleted after 2 days). Each compile makes a folder of its own in it (the Typst root, see below) and deletes it after the compile. Also `~/.cache/cc-intelligent-ui/designs` (files deleted after 180 days) and `~/.cache/cc-intelligent-ui/fonts` (fonts copied out of a terminal app, such as Ghostty's JetBrains Mono; `$XDG_CACHE_HOME` in place of `~/.cache` when it is set). The previews of pasted images are made in the cache folder too, from the image files that Claude Code writes when you paste. `/iui setup` (iTerm2 on macOS, and herdr) changes your shell start file, only when you run it or agree to its question. The install script adds the same block when iTerm2 or herdr is there (`IUI_NO_SHELL_SETUP=1` stops it).+- **Files:** a private cache folder in `$TMPDIR` (`cc-intelligent-ui-<uid>`, `/tmp` when `TMPDIR` is not set; mode 700, its folders deleted after 2 days). Each compile makes a folder of its own in it (the Typst root, see below) and deletes it after the compile. Also `~/.cache/cc-intelligent-ui/designs` (files deleted after 180 days) and `~/.cache/cc-intelligent-ui/fonts` (fonts copied out of a terminal app, such as Ghostty's JetBrains Mono; `$XDG_CACHE_HOME` in place of `~/.cache` when it is set). The previews of pasted images are made in the cache folder too, from the image files that Claude Code writes when you paste, or, for a pasted path, from the image file that the path names (a JPEG or WebP first as a PNG that Typst makes). `/iui setup` (iTerm2 on macOS, and herdr) changes your shell start file, only when you run it or agree to its question. The install script adds the same block when iTerm2 or herdr is there (`IUI_NO_SHELL_SETUP=1` stops it).- **Processes:** `typst`, the `perl` watcher, and short helper commands such as `perl`, `sh`, `osascript`, `defaults`, `plutil`, `fc-list` and `fc-match`. In herdr, only while the mod is on and pictures show (from the start), a check each second finds the herdr client that you use: `stat` of the clients' terminal devices (the time of the last key), and on macOS `lsappinfo` (the app in front); with no client attached, no check each second. Each 10 s, and when the check each second finds a change, a full check: `ps` (the list of processes), `lsof` (with more than one herdr server), and the variables of your own herdr clients (Linux: `/proc/<pid>/environ`; macOS: `ps eww`). The shell of this check keeps only `TERM`, `TERM_PROGRAM`, `COLORFGBG`, `LC_TERMINAL`, `ITERM_PROFILE`, `ITERM_SESSION_ID`, `GHOSTTY_BIN_DIR`, `GHOSTTY_RESOURCES_DIR`, `KITTY_CONFIG_DIRECTORY`, `KITTY_INSTALLATION_DIR`, `KITTY_PID`, `KITTY_WINDOW_ID`, `CMUX_SOCKET_PATH`, `CMUX_SURFACE_ID`, `CMUX_WORKSPACE_ID` and `RIO_CONFIG_HOME`; the mod (and other mods' hooks) get no other variable. It writes none of this anywhere. With the `auto` theme, a `perl` asks herdr's pane for its background (OSC 11) at the start and when you change to a different herdr client, not on a timer. On Linux also `wl-paste`, `xclip`, `clipnotify` or `python3 -I` (GTK 3; isolated, so it loads no code from the project folder) for the clipboard.- **Typst:** each compile of an answer or a plan runs with a narrow root: a new folder with the mod's template, the theme and the images that the text names. So the code in an answer cannot read other files on your computer. The skill's `check.sh` compiles the same way, and so does the preview of a pasted image (a folder with only its template and the pasted image).diff --git a/docs/usage.md b/docs/usage.mdindex fcad433..a14459b 100644--- a/docs/usage.md+++ b/docs/usage.md@@ -43,6 +43,7 @@ When you paste an image into the prompt box, the box shows `[Image #N]`. The mod- The previews show side by side. When they do not fit in one line, they go on to the next line.- A preview is approximately 5 rows tall, or less when the space above the prompt box is small. The image keeps its shape.- When you delete the `[Image #N]` text, the preview of that image goes away. When you send or clear the prompt, all the previews go away.+- A pasted path of an image file (path text that you copied) also shows a preview. Claude Code writes no file for it until you send the prompt, so the mod reads the clipboard one time to find the file. It shows PNG, JPEG and WebP files (JPEG and WebP need Typst).- The mod shows PNG images only. If Claude Code wrote no PNG file for an image, that image has no preview.- A survey above the prompt box hides the previews until it closes.- With `/iui off`, or in a terminal that shows no pictures, there are no previews.diff --git a/hooks/lib/composer.tsx b/hooks/lib/composer.tsxindex 82ffa60..000692f 100644--- a/hooks/lib/composer.tsx+++ b/hooks/lib/composer.tsx@@ -6,18 +6,21 @@// its cells exactly (render/fill.typ: no empty cell area under it, unless// that cuts more than half a cell: fillFitOf); the plain image shows until it is made. The draft's numbers are in the `draft` atom// (register.tsx, which writes it at each edit that changes them); the-// pictures are the files Claude Code wrote at the paste (pasteDir).+// pictures are the files Claude Code wrote at the paste (pasteDir), else, for+// a pasted path (no file there until the prompt is sent), the file that the+// clipboard named (pathPaste).import type { EngineInterface, ImageSource, RenderElement, RenderInput, RenderViewport } from 'claude-code'-import { COMPILE_TIMEOUT_MS, GUTTER, PICTURES_KEPT, PREVIEW_GAP, PREVIEW_RETRY_MS, PREVIEW_ROWS, PREVIEW_TRIES } from './settings'-import { keep, type Cell, type Env } from './state'-import { folderOf, pastedImagePath, pictureCells, type PixelBox } from './images'-import { pasteDir, pictureOf, sourceOf, type Picture } from './pictures'+import { COMPILE_TIMEOUT_MS, GUTTER, PATH_RECHECK_MS, PICTURES_KEPT, PREVIEW_GAP, PREVIEW_RETRY_MS, PREVIEW_ROWS, PREVIEW_TRIES } from './settings'+import { keep, S, type Cell, type Env } from './state'+import { clipImagePaths, convertBox, folderOf, pastedImagePath, pictureCells, type PixelBox } from './images'+import { convertedOf, pasteDir, pictureOf, sourceOf, type Picture } from './pictures'+import { clipboardRead } from './clipboard'import { shownFor } from './frame'import { hashOf } from './draw'import { FILL_SH, fillCall, logDebug } from './typst'import { isFlipHere } from './terminal'-import { delay, stat, write, exec, uiResolve } from './api'+import { delay, stat, write, exec, sid, uiResolve } from './api'export type BandInput = RenderInput<'AbovePrompt', 'terminal'>export type RowInput = RenderInput<'UserMessage', 'terminal'>@@ -104,23 +107,27 @@ export function linesOf(widths: readonly number[], columns: number): number[][]// else after the gutter: each one's filled copy// once made, else the plain image (in flip mode none while the copy is// made: only a PNG stored for its rows draws; with no copy, the image as it-// is stored so). A file that is gone or not a PNG is left out;+// is stored so). A number with no file in the paste folder draws its+// `paths` file (a pasted path: a JPEG or WebP as the PNG Typst makes of it).+// A file that is gone or not a PNG is left out;// `isWhole` is false then (it may not be written yet: previewRetry).// `isFinal` is false while a copy is made (`redraw` once it is).export async function previewsOf(- $: EngineInterface, view: RenderViewport | undefined, ready: Env, numbers: readonly number[], o: { columns: number; maxRows: number; labelled: boolean; redraw: () => void },+ $: EngineInterface, view: RenderViewport | undefined, ready: Env, numbers: readonly number[],+ o: { columns: number; maxRows: number; labelled: boolean; redraw: () => void; paths?: ReadonlyMap<number, string> },): Promise<{ lines: Preview[][]; isWhole: boolean; isFinal: boolean }> {const dir = await pasteDir($, ready)- if (!dir) return { lines: [], isWhole: false, isFinal: true }+ if (!dir && !o.paths?.size) return { lines: [], isWhole: false, isFinal: true }const flip = isFlipHere(ready)+ const cell = shownFor(view).cellconst found: { n: number; plain: ImageSource | null; p: Picture }[] = []for (const n of numbers) {- const p = await pictureOf($, pastedImagePath(dir, n))+ const path = o.paths?.get(n)+ const p = (dir ? await pictureOf($, pastedImagePath(dir, n)) : null) ?? (path ? await pathPicture($, ready, path, convertBox(o.columns, PREVIEW_ROWS, cell)) : null)const plain = p && !flip ? await sourceOf($, ready, p) : nullif (p && (flip || plain)) found.push({ n, plain, p })}const isWhole = found.length === numbers.length- const cell = shownFor(view).cellconst laid = o.labelled? previewLayout(found.map(f => f.p), cell, o.columns, o.maxRows, found.map(f => labelColumns(f.n))): previewLayout(found.map(f => f.p), cell, o.columns - GUTTER, o.maxRows)@@ -141,6 +148,93 @@ export async function previewsOf(return { lines, isWhole, isFinal }}+// A pasted path's picture: a PNG as it is, a JPEG or WebP as the PNG Typst+// makes of it to fit `box` (none with no Typst).+async function pathPicture($: EngineInterface, ready: Env, path: string, box: PixelBox): Promise<Picture | null> {+ if (/\.png$/i.test(path)) return pictureOf($, path)+ const png = await convertedOf($, ready, path, box)+ return png ? pictureOf($, png) : null+}++// ---- Pasted paths ---------------------------------------------------------------++// The files of pasted paths by number, for one session (its id): a new+// session (/clear) numbers from #1 again. `pathTurn` counts the pastes that+// look for a file: a read of an older one maps nothing.+let pathed = { sid: '', paths: new Map<number, string>() }+let pathTurn = 0++// The pasted paths' files of `numbers` in session `id`.+export function pathsOf(id: string, numbers: readonly number[]): Map<number, string> {+ const paths = new Map<number, string>()+ if (pathed.sid !== id) return paths+ for (const n of numbers) {+ const path = pathed.paths.get(n)+ if (path) paths.set(n, path)+ }+ return paths+}++// Only the files of the numbers still in the draft are kept.+export function keepPaths(numbers: readonly number[]) {+ for (const n of [...pathed.paths.keys()]) if (!numbers.includes(n)) pathed.paths.delete(n)+}++// A session ends (/clear, a resume, an exit): no file is kept.+export function forgetPaths() {+ pathed = { sid: '', paths: new Map() }+ pathTurn+++}++// New `[Image #N]` marks (`fresh`, in order) of one change: those with no+// file in the paste folder (looked for again after PATH_RECHECK_MS: Claude+// Code may write it just after) are a pasted path. Then one clipboard read+// (clipboardRead: a password manager's copy is never read); a text that is+// a path list (clipImagePaths) with one path per new mark gives each mark+// its file, when it is a file. `envOf` is null when no picture draws. True+// when a file was found (the band draws again). A newer paste, a new+// session, a mark gone from the draft or a failed read maps nothing.+export async function pathPaste($: EngineInterface, fresh: readonly number[], envOf: () => Promise<Env | null>): Promise<boolean> {+ const turn = ++pathTurn+ const live = () => turn === pathTurn+ const ready = await envOf()+ if (!ready || !live()) return false+ const id = await sid($)+ const missing = async (numbers: readonly number[]) => {+ const dir = await pasteDir($, ready)+ const left: number[] = []+ const isFile = async (n: number) => (await stat($, pastedImagePath(dir, n)).catch(() => null))?.kind === 'file'+ for (const n of numbers) if (!dir || !(await isFile(n))) left.push(n)+ return left+ }+ let left = await missing(fresh)+ if (left.length) {+ await new Promise<void>(done => void delay($, PATH_RECHECK_MS, done))+ if (live()) left = await missing(left)+ }+ if (!left.length || !live()) return false+ const text = await clipboardRead($).catch(() => undefined)+ if (typeof text !== 'string' || !live()) return false+ const paths = clipImagePaths(text, { cwd: ready.cwd, home: ready.home })+ if (!paths || paths.length !== fresh.length) return false+ const found = new Map<number, string>()+ for (const [i, n] of fresh.entries()) {+ if (!left.includes(n)) continue+ const st = await stat($, paths[i]!).catch(() => null)+ if (st?.kind === 'file' && st.size > 0) found.set(n, paths[i]!)+ }+ if (!found.size || !live() || (await sid($)) !== id) return false+ if (pathed.sid !== id) pathed = { sid: id, paths: new Map() }+ const draft = S.draftImages ?? []+ let mapped = false+ for (const [n, path] of found) {+ if (!draft.includes(n)) continue+ pathed.paths.set(n, path)+ mapped = true+ }+ return mapped+}+// The filled copies made in this load by key (null: it failed), and the// ones being made, each with the redraws of the drawings that wait for it.const filled = new Map<string, string | null>()diff --git a/hooks/lib/images.ts b/hooks/lib/images.tsindex cb4f8bd..dfa7d24 100644--- a/hooks/lib/images.ts+++ b/hooks/lib/images.ts@@ -3,7 +3,7 @@// keeps pasted images, the cells a picture takes, and the pages of a PDF.// The drawing on the host is in pictures.tsx.import type { Cell } from './state'-import { CONVERT_MAX_SIDE, MAX_IMAGE_ROWS, PICTURE_MAX_ROWS, PICTURE_MIN_ROWS, PICTURE_ROOM_ROWS, type Height } from './settings'+import { CONVERT_MAX_SIDE, MAX_IMAGE_ROWS, PATH_TEXT_MAX, PATHS_MOST, PICTURE_MAX_ROWS, PICTURE_MIN_ROWS, PICTURE_ROOM_ROWS, type Height } from './settings'import { hashOf } from './draw'// The most rows a picture under a row (or a drawing's room) takes in a@@ -201,3 +201,97 @@ export function claudeTmpOf(o: { tmpdir?: string; uid: string; isMac: boolean })// Where Claude Code keeps the images pasted in a session, and image N there.export const pasteDirOf = (claudeTmp: string, cwd: string, sessionId: string) => `${claudeTmp}/${projectSlug(cwd)}/${sessionId}/images`export const pastedImagePath = (dir: string, n: number) => `${dir}/${n}.png`++// ---- Pasted paths ---------------------------------------------------------------+// A pasted path of an image file (copied path text) is an `[Image #N]` with+// no file in the paste folder until the prompt is sent; the clipboard text+// names its file (composer.tsx pathPaste).++// The image files a pasted path can show: PNG, and JPEG and WebP (Typst+// makes a PNG of them), by the name's end.+export const isPastedImage = (path: string) => /\.(png|jpe?g|webp)$/i.test(path)++// The image files a clipboard text names, as absolute paths, in order. Each+// line is one path (a name may have spaces), or several paths apart by+// spaces when each word is one, or when quotes or backslash escapes split+// them (as a terminal or a file manager copies them). A path is absolute,+// `~/…`, from `cwd`, or a file:// URL (percent-decoded). Null for any other+// text (a word that is not an image file's path), an empty one, or one over+// PATH_TEXT_MAX chars or PATHS_MOST paths.+export function clipImagePaths(text: string, o: { cwd: string; home: string }): string[] | null {+ if (text.length > PATH_TEXT_MAX) return null+ const words: string[] = []+ for (const line of text.split(/\r?\n/)) {+ if (!line.trim()) continue+ const got = lineWords(line.trim())+ if (!got) return null+ words.push(...got)+ }+ if (!words.length || words.length > PATHS_MOST) return null+ const paths = words.map(w => absolutePath(w, o))+ return paths.every((p): p is string => !!p && isPastedImage(p)) ? paths : null+}++// One line's words: split at spaces outside quotes and escapes; a plain+// line (no quote, no backslash) is one path unless each word is an image's.+// Null for an open quote, a backslash at the end, or a plain line whose+// later word starts as a path does.+function lineWords(line: string): string[] | null {+ if (!/['"\\]/.test(line)) {+ const plain = line.split(/\s+/)+ if (plain.length > 1 && plain.every(isPastedImage)) return plain+ return plain.slice(1).some(w => /^(\/|~|file:)/i.test(w)) ? null : [line]+ }+ const words: string[] = []+ let word = ''+ let has = false+ let quote = ''+ for (let i = 0; i < line.length; i++) {+ const c = line[i]!+ if (quote) {+ if (c === quote) quote = ''+ else if (c === '\\' && quote === '"' && /["\\$`]/.test(line[i + 1] ?? '')) word += line[++i]+ else word += c+ } else if (c === '\'' || c === '"') {+ quote = c+ has = true+ } else if (c === '\\') {+ if (i + 1 >= line.length) return null+ word += line[++i]+ has = true+ } else if (/\s/.test(c)) {+ if (has) words.push(word)+ word = ''+ has = false+ } else {+ word += c+ has = true+ }+ }+ if (quote) return null+ if (has) words.push(word)+ return words+}++// A word as an absolute path; null for a control character, another URL+// scheme, `~user`, or a bad percent escape.+function absolutePath(word: string, o: { cwd: string; home: string }): string | null {+ const bad = /[\x00-\x1f\x7f]/+ if (!word || bad.test(word)) return null+ if (/^file:\/\//i.test(word)) {+ const rest = word.slice(7).replace(/^localhost(?=\/)/i, '')+ if (!rest.startsWith('/')) return null+ let path: string+ try {+ path = decodeURIComponent(rest)+ } catch {+ return null+ }+ return bad.test(path) ? null : path+ }+ if (/^[a-z][a-z0-9+.-]*:/i.test(word)) return null+ if (word.startsWith('~/')) return o.home ? `${o.home.replace(/\/+$/, '')}/${word.slice(2)}` : null+ if (word.startsWith('~')) return null+ if (word.startsWith('/')) return word+ return o.cwd ? `${o.cwd.replace(/\/+$/, '')}/${word.replace(/^(\.\/)+/, '')}` : null+}diff --git a/hooks/lib/settings.ts b/hooks/lib/settings.tsindex ba9979a..4fbcd55 100644--- a/hooks/lib/settings.ts+++ b/hooks/lib/settings.ts@@ -134,6 +134,12 @@ export const PREVIEW_ROWS = 5export const PREVIEW_GAP = 2export const PREVIEW_RETRY_MS = 250export const PREVIEW_TRIES = 8+// A pasted path (an `[Image #N]` with no file): the file looked for once+// more after PATH_RECHECK_MS before the clipboard is read; a clipboard text+// over PATH_TEXT_MAX chars, or with more than PATHS_MOST paths, is no path list.+export const PATH_RECHECK_MS = 200+export const PATH_TEXT_MAX = 4096+export const PATHS_MOST = 20// The file paths of the link rows under a picture: whether each one is a// file, kept for this many paths (the oldest go).export const LINK_FILES_KEPT = 512diff --git a/hooks/register.tsx b/hooks/register.tsxindex 6d30498..0416a0a 100644--- a/hooks/register.tsx+++ b/hooks/register.tsx@@ -52,9 +52,9 @@ import { frameFor, noteView, stopWatch, watchFrame, watchState } from './lib/fraimport { herdrText, isFlipHere, roomColumns } from './lib/terminal'import { onScreenOf, pastedNumbers, sentFiles } from './lib/images'import { drawPageField, pasteDir, pdfPagesOf, rowsAfter, sentOf, underRow, type Under } from './lib/pictures'-import { drawPreviews, previewRetry, previewsOf, previewsUnder, sameNumbers, type Preview } from './lib/composer'+import { drawPreviews, forgetPaths, keepPaths, pathPaste, pathsOf, previewRetry, previewsOf, previewsUnder, sameNumbers, type Preview } from './lib/composer'import { checkUpdates, loadUpdates, updateLine, updateNotice, type UpdateState } from './lib/updates'-import { nowMs, write, surf, save, copy, uiSelection, toast } from './lib/api'+import { nowMs, write, surf, save, copy, uiSelection, toast, sid } from './lib/api'import {currentPlan, decidePlan, decisionOf, drawAskLine, drawPlanResult, drawPlanUse, isPlanQuestion, planFileOf, planInputOf, planOf,planShownOf, scheduleClear, type PlanVerdict,@@ -63,7 +63,7 @@ import {// The names this module exported before the split (the tests import them).export {BASE_THEME, DEFAULT_CELL, DEFAULT_HEIGHT, DEFAULT_SIZE, DEFAULT_THEME, DEFAULT_WIDTH, gridText, heightText, IMAGE_MAX_COLUMNS, MAX_HEIGHT, MAX_SIZE, MAX_WIDTH,- MIN_HEIGHT, MIN_SIZE, MIN_WIDTH, PICTURE_MAX_ROWS, PICTURE_MIN_ROWS, PICTURE_ROOM_ROWS, PREVIEW_RETRY_MS, PREVIEW_ROWS, SEGMENT_ROWS, TYPST_PROMPT, widthText, type Height, type Width,+ MIN_HEIGHT, MIN_SIZE, MIN_WIDTH, PICTURE_MAX_ROWS, PICTURE_MIN_ROWS, PICTURE_ROOM_ROWS, PATH_RECHECK_MS, PREVIEW_RETRY_MS, PREVIEW_ROWS, SEGMENT_ROWS, TYPST_PROMPT, widthText, type Height, type Width,COMMIT_MAX_MS, COMMIT_MIN_MS, DESIGNS_KEPT_DAYS, RESIZE_QUIET_MS, RESULTS_KEPT, TOUCH_FLUSH_MS,} from './lib/settings'export { DEFAULT_METRICS, keep, type Cell, type Design, type FontMetrics, type Frame, type Look, type Metrics, type Room } from './lib/state'@@ -155,19 +155,38 @@ async function answerEnv($: EngineInterface, e: { viewport?: RenderViewport }):// The draft's `[Image #N]` numbers to the `draft` atom, only when they// changed (the band above the prompt draws again): a key that keeps them-// writes nothing. Never throws. `draftSeq` counts the box changes seen: an-// edit's box that comes after a newer change is not noted.+// writes nothing. The numbers that are new, in order. Never throws.+// `draftSeq` counts the box changes seen: an edit's box that comes after a+// newer change is not noted.let draftSeq = 0-function noteDraft($: EngineInterface, text: string) {+function noteDraft($: EngineInterface, text: string): number[] {try {const now = pastedNumbers(text)- if (S.draftImages && sameNumbers(S.draftImages, now)) return+ if (S.draftImages && sameNumbers(S.draftImages, now)) return []+ const was = S.draftImages ?? []S.draftImages = now+ keepPaths(now)// The newest numbers at the write, should two writes cross.void update($, draft, () => S.draftImages ?? []).catch(() => undefined)- } catch {}+ return now.filter(n => !was.includes(n))+ } catch {+ return []+ }}+// New image marks of a paste: those with no file are a pasted path, whose+// file the clipboard names (composer.tsx pathPaste); the band draws again+// once one is found. Only while pictures draw here (not over ssh).+function pastedPaths($: EngineInterface, fresh: number[]) {+ const envOf = async () => ((await read($, isOn)) && S.env?.canDraw && !S.isRemote ? S.env : null)+ void pathPaste($, fresh, envOf)+ .then(found => (found ? update($, draft, ns => [...ns]) : undefined))+ .catch(() => undefined)+}++// The change kinds that are no paste: a recall, a clear, an undo, a fill.+const NOT_PASTES: readonly string[] = ['history', 'clear', 'undo', 'plugin', 'app']+// ---- Rows drawn before ----------------------------------------------------------// What a drawn row depends on besides its own inputs: `done` (every result@@ -808,6 +827,7 @@ export const register: Register = on => {// the next picture. Any other end (/exit): the watcher stops, and no new// child starts.on('session.end', async ($, e, next) => {+ forgetPaths()if (e.reason === 'clear' || e.reason === 'resume') stopClipboard($)else {stopWatch()@@ -876,7 +896,10 @@ export const register: Register = on => {void Promise.resolve().then(() => nowMs($)).then(t => void (S.keyAt = t), () => undefined)const seq = ++draftSeqconst box = await next(e)- if (isEdit && e.origin.kind === 'composer' && seq === draftSeq) noteDraft($, box.text)+ if (isEdit && e.origin.kind === 'composer' && seq === draftSeq) {+ const fresh = noteDraft($, box.text)+ if (fresh.length && e.inputText.includes('[Image #')) pastedPaths($, fresh)+ }return box}).catch(($, e, next) => next(e))@@ -886,7 +909,9 @@ export const register: Register = on => {on('prompt.change', async ($, e, next) => {if (picked.now && e.origin.kind !== 'plugin' && e.origin.kind !== 'app') clearSelection($)draftSeq++- noteDraft($, e.text)+ const fresh = noteDraft($, e.text)+ // A path pasted (an engine change): its file from the clipboard.+ if (fresh.length && !NOT_PASTES.includes(e.origin.kind)) pastedPaths($, fresh)return next(e)}).catch(($, e, next) => next(e))@@ -1272,13 +1297,16 @@ export const register: Register = on => {if (ready) {// The paste folder in the key: a new session (/clear) numbers from #1 again.const dir = await pasteDir($, ready.env)- const k = { text: numbers.join(','), extra: `${e.props.bodyColumns}x${e.props.maxRows}|${dir}`, stamp: stampOf(ready, e.viewport), onScreen: undefined }+ // The files of pasted paths (by the session: /clear numbers from #1 again).+ const paths = pathsOf(await sid($), numbers)+ const named = [...paths].map(([n, path]) => `${n}=${path}`).join('\n')+ const k = { text: numbers.join(','), extra: `${e.props.bodyColumns}x${e.props.maxRows}|${dir}|${named}`, stamp: stampOf(ready, e.viewport), onScreen: undefined }const kept = memoOf(drafts, 'draft', k, () => false)if (kept) lines = keptelse {// The same numbers written again: only the band reads them.const redraw = () => void update($, draft, ns => [...ns]).catch(() => undefined)- const made = await previewsOf($, e.viewport, ready.env, numbers, { columns: e.props.bodyColumns, maxRows: e.props.maxRows - 1, labelled: true, redraw })+ const made = await previewsOf($, e.viewport, ready.env, numbers, { columns: e.props.bodyColumns, maxRows: e.props.maxRows - 1, labelled: true, redraw, paths })lines = made.linesif (made.isWhole && made.isFinal) memoSet(drafts, 'draft', k, lines)else drafts.delete('draft')diff --git a/tests/images.test.ts b/tests/images.test.tsindex fa7136a..0172812 100644--- a/tests/images.test.ts+++ b/tests/images.test.ts@@ -9,6 +9,7 @@ import {claudeTmpOf, convertBox, convertCall, convertedPath, DEFAULT_CELL, factsAfter, folderOf, imageKindOf, isMarkdownPath, isNoPageError, isPdfPath, lastKnownPage,NO_FACTS, pageControls, pageCountOf, pageOf, parsePage, pasteDirOf, pastedImagePath, pastedNumbers, COMMIT_MIN_MS, DEFAULT_HEIGHT, RESIZE_QUIET_MS, PICTURE_MAX_ROWS, PICTURE_ROOM_ROWS, pictureCells,pictureRowsFor, projectSlug, renderKey, rowsAfter, sentFiles, sentImages, shortError, type Under, altOf, cellPixels, fillCall, filledPath, labelColumns, labelOf, linesOf, previewLayout, PREVIEW_RETRY_MS, sameNumbers,+ clipImagePaths, PATH_RECHECK_MS, READ_PL,} from '../hooks/register'// ---- Pure helpers -----------------------------------------------------------@@ -379,6 +380,8 @@ function world(on: any, o: {failStage?: boolean// The first flip writes (WRITE_PL) that fail.failWrites?: number+ // The clipboard's text (READ_PL; none: no text; false: the read fails).+ clipboard?: string | false} = {}) {// Intelligent UI's store in memory (as mock.store), and its writes by key;// `redrawsAt`: by key, the `done` writes (redraws) made when its write ended.@@ -413,6 +416,8 @@ function world(on: any, o: {const reads: string[] = []const converts: string[][] = []const fills: string[][] = []+ // The clipboard reads, and the session's id (a /clear gives a new one).+ const clipboard: { text: string | false | undefined; reads: number; sid: string } = { text: o.clipboard, reads: 0, sid: 'sid-1' }// The roots of the fills made (FILL_SH's arguments), and the folders removed.const fillRoots: string[][] = []const removed: string[] = []@@ -450,6 +455,11 @@ function world(on: any, o: {const cmd = argv.join(' ')if (argv[0] === 'kill') return ok('')if (o.herdr && argv[0] === 'sh' && argv[2] === HERDR_CLIENT_SH) return ok(`pid 77\natime 5\ntty /dev/ttys003\ncmd herdr\napp ${o.herdr}\nenv\nherdr TERM=xterm-256color\n`)+ if (argv[0] === '/usr/bin/perl' && argv[2] === READ_PL) {+ clipboard.reads+++ if (clipboard.text === false) throw new Error('no bridge')+ return clipboard.text === undefined ? ok('', 1) : ok(clipboard.text)+ }if (argv[0] === '/usr/bin/perl' && argv[2] === WRITE_PL) return writes++ < (o.failWrites ?? 0) ? ok('', 1) : (pngs.set(argv[3]!, fromBase64(e.init.stdin)), ok(''))if (/cc-intelligent-ui-/.test(cmd)) return ok('/c\nDarwin\n')if (argv[0] === 'id' && argv[1] === '-u') return ok('501\n')@@ -496,7 +506,7 @@ function world(on: any, o: {}return ok('', 1)})- on('session.id', async () => ({ value: 'sid-1' }))+ on('session.id', async () => ({ value: clipboard.sid }))on('session.cwd', async () => ({ value: '/w/app' }))on('session.root', async () => ({ value: '/w/app' }))on('fs.stat', async ($: any, e: any, next: any) => {@@ -527,7 +537,7 @@ function world(on: any, o: {})on('ui.toast', async () => ({ value: undefined }))on('ui.render', () => ENGINE as any)- return { clock, heads, reads, converts, moves, pngs, writes: () => writes, docs, logs, files, texts, mtimes, written, kept, redrawsAt, redraws: () => redraws, sets, stats, fills, fillRoots, removed }+ return { clipboard, dirs, clock, heads, reads, converts, moves, pngs, writes: () => writes, docs, logs, files, texts, mtimes, written, kept, redrawsAt, redraws: () => redraws, sets, stats, fills, fillRoots, removed }}const sent = (output: unknown, isErrored = false, id = 'tu-1') =>@@ -1733,6 +1743,264 @@ test('the band stays as it is with a survey, with no image, with Intelligent UIexpect(await (await $.ui.mount({ ...band(), requestId: 'band-5' })).drawn()).toMatchObject(ENGINE)})+test('the band leaves its first row empty: the previews do not touch the line above', async ($, on) => {+ world(on, { files: { [`${PASTED}/5.png`]: HEAD }, dirs: [PASTED] })+ editor(on)+ await ready($)+ const ui = await $.ui.mount(band({ maxRows: 6 }))+ await ($ as any).prompt.edit(typed('', '[Image #5]'))+ const tree: any = await ui.drawn()+ // One empty row above the previews, and the previews one row shorter for it (5 rows less the free one).+ expect(tree.props.marginTop).toBe(1)+ expect(images(tree)[0].props.rows).toBe(4)+})++// ---- Pasted paths ---------------------------------------------------------------++test('a clipboard text is a list of image paths, or nothing', () => {+ const o = { cwd: '/w/app', home: '/h' }+ expect(clipImagePaths('/t/shot.png', o)).toEqual(['/t/shot.png'])+ expect(clipImagePaths(' /t/shot.png\n', o)).toEqual(['/t/shot.png'])+ // From the cwd, from home, a file:// URL (percent-decoded).+ expect(clipImagePaths('shots/a.png', o)).toEqual(['/w/app/shots/a.png'])+ expect(clipImagePaths('./a.PNG', o)).toEqual(['/w/app/a.PNG'])+ expect(clipImagePaths('~/Desktop/a.jpg', o)).toEqual(['/h/Desktop/a.jpg'])+ expect(clipImagePaths('file:///t/My%20Shot.png', o)).toEqual(['/t/My Shot.png'])+ expect(clipImagePaths('file://localhost/t/a.webp', o)).toEqual(['/t/a.webp'])+ // Quotes and backslash escapes, as terminals copy them; several paths.+ expect(clipImagePaths(`'/t/My Shot.png'`, o)).toEqual(['/t/My Shot.png'])+ expect(clipImagePaths('"/t/My Shot.png" /t/b.jpeg', o)).toEqual(['/t/My Shot.png', '/t/b.jpeg'])+ expect(clipImagePaths('/t/My\\ Shot.png /t/b.png', o)).toEqual(['/t/My Shot.png', '/t/b.png'])+ expect(clipImagePaths('/t/a.png /t/b.png', o)).toEqual(['/t/a.png', '/t/b.png'])+ expect(clipImagePaths('/t/a.png\n/t/b.png\n', o)).toEqual(['/t/a.png', '/t/b.png'])+ // A plain line with spaces is one path (a file manager's copy).+ expect(clipImagePaths('/t/My Shot.png', o)).toEqual(['/t/My Shot.png'])+ expect(clipImagePaths('/t/My Shot.png\n/t/b.png', o)).toEqual(['/t/My Shot.png', '/t/b.png'])+ // Anything else: no list.+ for (const text of [+ '', ' \n', 'hello world', 'see /t/a.png', '/t/notes.txt', '/t/a.png /t/notes.txt', '/t/a.gif', 'https://x.test/a.png', '~bob/a.png',+ '"/t/a.png', '/t/a.png\\', 'file://host/t/a.png', 'file:///t/%E0%A4%A.png', 'file:///t/a%0A.png', `/t/${'a'.repeat(5000)}.png`,+ Array.from({ length: 21 }, (_, i) => `/t/${i}.png`).join(' '),+ ]) expect([text.slice(0, 40), clipImagePaths(text, o)]).toEqual([text.slice(0, 40), null])+ // No cwd or home: no relative or ~ path.+ expect(clipImagePaths('a.png', { cwd: '', home: '' })).toBe(null)+ expect(clipImagePaths('~/a.png', { cwd: '', home: '' })).toBe(null)+})++// A path pasted (Cmd+V of a copied path, a drag into the terminal): the+// engine's change with the new mark; no edit carries it, and no file is in+// the paste folder until the prompt is sent.+const pathPasted = (text: string) => ({ text, cursor: text.length, origin: { kind: 'engine' } }) as any+const sources = (tree: any): string[] => images(tree).map(i => i.props.source.file)++test('a pasted image path shows its preview from that file: the clipboard is read once', async ($, on) => {+ const { clipboard, clock } = world(on, { files: { '/t/shot.png': HEAD }, clipboard: '/t/shot.png' })+ editor(on)+ await ready($)+ const ui = await $.ui.mount(band())+ await ($ as any).prompt.change(pathPasted('look [Image #1]'))+ // The file may come a moment after the change: no read yet.+ await clock.settle()+ expect(clipboard.reads).toBe(0)+ await clock.advance(PATH_RECHECK_MS)+ expect(clipboard.reads).toBe(1)+ const tree: any = await ui.drawn()+ expect(alts(tree)).toEqual(['[Image #1]'])+ expect(sources(tree)).toEqual(['/t/shot.png'])+ expect(images(tree)[0].props).toMatchObject({ columns: 20, rows: 5 })+ // Typing after it reads nothing more; the preview stays.+ await ($ as any).prompt.edit(typed('look [Image #1]', ' what'))+ await clock.advance(1000)+ expect(clipboard.reads).toBe(1)+ expect(sources(await ui.drawn())).toEqual(['/t/shot.png'])+})++for (const [form, text, file] of [+ ['a relative path', 'shots/a.png', '/w/app/shots/a.png'],+ ['a ~ path', '~/Desktop/a.png', '/h/Desktop/a.png'],+ ['a file:// URL', 'file:///t/My%20Shot.png', '/t/My Shot.png'],+ ['a quoted path', `'/t/My Shot.png'`, '/t/My Shot.png'],+ ['a path with escaped spaces', '/t/My\\ Shot.png', '/t/My Shot.png'],+] as const) {+ test(`a pasted image path shows its preview: ${form}`, async ($, on) => {+ const { clock } = world(on, { files: { [file]: HEAD }, clipboard: `${text}\n` })+ editor(on)+ await ready($)+ const ui = await $.ui.mount(band())+ await ($ as any).prompt.change(pathPasted('[Image #1]'))+ await clock.advance(PATH_RECHECK_MS)+ expect(sources(await ui.drawn())).toEqual([file])+ })+}++test('two pasted paths are the two new marks, in order', async ($, on) => {+ const { clipboard, clock } = world(on, { files: { '/t/a.png': HEAD, '/t/b.png': TALL }, clipboard: '/t/a.png /t/b.png' })+ editor(on)+ await ready($)+ const ui = await $.ui.mount(band())+ await ($ as any).prompt.change(pathPasted('[Image #1] [Image #2] '))+ await clock.advance(PATH_RECHECK_MS)+ const tree: any = await ui.drawn()+ expect(alts(tree)).toEqual(['[Image #1]', '[Image #2]'])+ expect(sources(tree)).toEqual(['/t/a.png', '/t/b.png'])+ expect(clipboard.reads).toBe(1)+})++test('a pasted JPEG path shows as the PNG Typst makes of it', async ($, on) => {+ const { clock, converts } = world(on, { typst: true, files: { '/t/photo.jpg': JPEG }, clipboard: '/t/photo.jpg' })+ editor(on)+ await ready($)+ const ui = await $.ui.mount(band())+ await ($ as any).prompt.change(pathPasted('[Image #1]'))+ await clock.advance(PATH_RECHECK_MS)+ await clock.settle()+ expect(converts.map(argv => argv.find(a => a.startsWith('f=')))).toEqual(['f=/t/photo.jpg'])+ expect(alts(await ui.drawn())).toEqual(['[Image #1]'])+})++for (const [what, clipboardText, files] of [+ ['a text that is no path', 'hello [Image #1] world', {}],+ ['a path to no file', '/t/gone.png', {}],+ ['a file that is no image', '/t/notes.txt', { '/t/notes.txt': HEAD }],+ ['an image file that is no PNG', '/t/fake.png', { '/t/fake.png': JPEG }],+ ['more paths than new marks', '/t/a.png /t/b.png', { '/t/a.png': HEAD, '/t/b.png': HEAD }],+ ['a read that fails', false, { '/t/a.png': HEAD }],+] as const) {+ test(`a pasted mark draws no preview, and nothing fails, for ${what}`, async ($, on) => {+ const { clipboard, clock } = world(on, { files: { ...files }, clipboard: clipboardText })+ editor(on)+ await ready($)+ const ui = await $.ui.mount(band())+ await ($ as any).prompt.change(pathPasted('[Image #1]'))+ await clock.advance(PATH_RECHECK_MS)+ await clock.advance(PREVIEW_RETRY_MS * 10)+ expect(clipboard.reads).toBe(1)+ expect(await ui.drawn()).toMatchObject(ENGINE)+ })+}++test('a pasted image (its file in the paste folder) reads no clipboard, nor one written just after the paste', async ($, on) => {+ const { clipboard, clock, files } = world(on, { files: { [`${PASTED}/5.png`]: HEAD, '/t/shot.png': TALL }, dirs: [PASTED], clipboard: '/t/shot.png' })+ editor(on)+ await ready($)+ const prompt = ($ as any).prompt+ const ui = await $.ui.mount(band())+ await prompt.edit(typed('', '[Image #5]'))+ await prompt.change(pathPasted('[Image #5] [Image #6]'))+ // #6 is written a moment after its change (after the first look for it).+ await clock.settle()+ files[`${PASTED}/6.png`] = HEAD+ await clock.advance(PATH_RECHECK_MS)+ await clock.advance(PREVIEW_RETRY_MS)+ expect(clipboard.reads).toBe(0)+ expect(sources(await ui.drawn())).toEqual([`${PASTED}/5.png`, `${PASTED}/6.png`])+ // A path pasted then: the one read.+ await prompt.change(pathPasted('[Image #5] [Image #6] [Image #7]'))+ await clock.advance(PATH_RECHECK_MS)+ expect(clipboard.reads).toBe(1)+ expect(sources(await ui.drawn())).toEqual([`${PASTED}/5.png`, `${PASTED}/6.png`, '/t/shot.png'])+})++test('a recalled entry, a plugin\'s fill or an undo reads no clipboard; only a paste does', async ($, on) => {+ const { clipboard, clock } = world(on, { files: { '/t/shot.png': HEAD }, clipboard: '/t/shot.png' })+ editor(on)+ await ready($)+ const prompt = ($ as any).prompt+ const ui = await $.ui.mount(band())+ await prompt.change({ text: '[Image #1] old', cursor: 14, origin: { kind: 'history' } })+ await prompt.change({ text: '[Image #2]', cursor: 10, origin: { kind: 'plugin', name: 'other' } })+ await prompt.change({ text: '[Image #3]', cursor: 10, origin: { kind: 'undo' } })+ await clock.advance(PATH_RECHECK_MS)+ expect(clipboard.reads).toBe(0)+ expect(await ui.drawn()).toMatchObject(ENGINE)+ await prompt.change(pathPasted('[Image #3] [Image #4]'))+ await clock.advance(PATH_RECHECK_MS)+ expect(clipboard.reads).toBe(1)+ expect(alts(await ui.drawn())).toEqual(['[Image #4]'])+})++test('a paste while a read waits: the older paste maps nothing, the newer one its own path', async ($, on) => {+ const { clipboard, clock } = world(on, { files: { '/t/a.png': HEAD, '/t/b.png': TALL }, clipboard: '/t/a.png' })+ editor(on)+ await ready($)+ const prompt = ($ as any).prompt+ const ui = await $.ui.mount(band())+ await prompt.change(pathPasted('[Image #1]'))+ await clock.advance(PATH_RECHECK_MS / 2)+ // B copied and pasted before the first read: the clipboard is B's now.+ clipboard.text = '/t/b.png'+ await prompt.change(pathPasted('[Image #1] [Image #2]'))+ await clock.advance(PATH_RECHECK_MS)+ expect(clipboard.reads).toBe(1)+ const tree: any = await ui.drawn()+ expect(alts(tree)).toEqual(['[Image #2]'])+ expect(sources(tree)).toEqual(['/t/b.png'])+})++test('a mark deleted while its read runs maps nothing; a mark that leaves the draft drops its file', async ($, on) => {+ const { clipboard, clock } = world(on, { files: { '/t/a.png': HEAD }, clipboard: '/t/a.png' })+ editor(on)+ await ready($)+ const prompt = ($ as any).prompt+ const ui = await $.ui.mount(band())+ await prompt.change(pathPasted('[Image #1]'))+ await prompt.edit(cut('[Image #1]', 0, 10))+ await clock.advance(PATH_RECHECK_MS)+ expect(clipboard.reads).toBe(1)+ await prompt.change({ text: '[Image #1]', cursor: 10, origin: { kind: 'undo' } })+ expect(await ui.drawn()).toMatchObject(ENGINE)+ // Mapped, then deleted and put back by an undo: no file kept for it.+ await prompt.change(pathPasted('[Image #1] [Image #2]'))+ await clock.advance(PATH_RECHECK_MS)+ expect(alts(await ui.drawn())).toEqual(['[Image #2]'])+ await prompt.edit(cut('[Image #1] [Image #2]', 10, 21))+ await prompt.change({ text: '[Image #1] [Image #2]', cursor: 21, origin: { kind: 'undo' } })+ expect(await ui.drawn()).toMatchObject(ENGINE)+ expect(clipboard.reads).toBe(2)+})++test('once the prompt is sent, the file Claude Code writes is the one drawn, with no read', async ($, on) => {+ const { clipboard, clock, dirs, files } = world(on, { files: { '/t/shot.png': TALL }, clipboard: '/t/shot.png' })+ editor(on)+ await ready($)+ const box = ($ as any).prompt+ const ui = await $.ui.mount(band())+ await box.change(pathPasted('look [Image #1]'))+ await clock.advance(PATH_RECHECK_MS)+ expect(sources(await ui.drawn())).toEqual(['/t/shot.png'])+ // Claude Code writes images/1.png at the send: it wins.+ dirs.add(PASTED)+ files[`${PASTED}/1.png`] = HEAD+ await ui.redraw()+ expect(sources(await ui.drawn())).toEqual([`${PASTED}/1.png`])+ // Sent: the box clears.+ await box.change({ text: '', cursor: 0, origin: { kind: 'clear' } })+ const row = await $.ui.mount(prompt('look [Image #1]'))+ expect(sources(await row.drawn())).toEqual([`${PASTED}/1.png`])+ // Recalled: the written file, not the path.+ await box.change({ text: 'look [Image #1]', cursor: 15, origin: { kind: 'history' } })+ await clock.advance(PATH_RECHECK_MS)+ expect(sources(await ui.drawn())).toEqual([`${PASTED}/1.png`])+ expect(clipboard.reads).toBe(1)+})++test('a pasted path\'s file is not kept for a new session (/clear numbers from #1 again)', async ($, on) => {+ const { clipboard, clock } = world(on, { files: { '/t/shot.png': HEAD }, clipboard: '/t/shot.png' })+ editor(on)+ await ready($)+ const prompt = ($ as any).prompt+ const ui = await $.ui.mount(band())+ await prompt.change(pathPasted('[Image #1]'))+ await clock.advance(PATH_RECHECK_MS)+ expect(sources(await ui.drawn())).toEqual(['/t/shot.png'])+ // A new session with #1 in its draft (no change of the numbers): no file for it.+ clipboard.sid = 'sid-2'+ await prompt.change({ text: '[Image #1] new', cursor: 14, origin: { kind: 'history' } })+ await ui.redraw()+ expect(await ui.drawn()).toMatchObject(ENGINE)+ expect(clipboard.reads).toBe(1)+})+// ---- The height setting -------------------------------------------------------test('a kept height caps sent images (not pasted ones); height full draws them taller at the commit', async ($, on) => {