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

Paste preview: new session key, late edit, herdr in iTerm2 with no Typst, wide image fit, fill root cleanup

razorback16b37213267365
diff --git a/CHANGELOG.md b/CHANGELOG.md
index eb79b03..5141722 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,7 +6,7 @@ All releases of Intelligent UI for Claude Code (`cc-intelligent-ui`). Claude Cod
### New
-- **A preview of pasted images above the prompt box.** When you paste an image (`[Image #N]`), a small preview of it shows above the prompt box before you send the prompt, with its number (`#N`) at its left. Typst makes a copy of the image that fills the cells of the preview. The previews show side by side, approximately 5 rows tall. When you delete the `[Image #N]` text, or send or clear the prompt, the preview goes away. Refer to [Preview of pasted images](docs/usage.md#preview-of-pasted-images).
+- **A preview of pasted images above the prompt box.** When you paste an image (`[Image #N]`), a small preview of it shows above the prompt box before you send the prompt, with its number (`#N`) at its left. Typst makes a copy of the image that fills the cells of the preview (a very wide or tall image shows whole, with an empty strip). The previews show side by side, approximately 5 rows tall. When you delete the `[Image #N]` text, or send or clear the prompt, the preview goes away. Refer to [Preview of pasted images](docs/usage.md#preview-of-pasted-images).
- **herdr support** (the terminal multiplexer). In a herdr pane, Claude Code needs `CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1` to show pictures. The mod asks one time to add the shell line, as in iTerm2. `/iui setup` also adds it. Then close the pane and open a new herdr pane. herdr must run in a terminal that shows kitty pictures (kitty, Ghostty or iTerm2). Refer to [Terminals](docs/install.md#terminals).
- **herdr in iTerm2.** iTerm2 shows each row of a herdr picture from the bottom of the image, so the rows of a page showed in the wrong order. When the herdr client in use is iTerm2, the mod stores the bands of rows of each page and picture in reverse order. Then iTerm2 shows them in the correct order. `/iui details` shows `pages and pictures stored upside down by rows` when this is on. It does not work with `herdr --remote` in iTerm2.
- `/iui setup` works in herdr on Linux too.
diff --git a/docs/how-it-works.md b/docs/how-it-works.md
index 21667c0..adf88af 100644
--- a/docs/how-it-works.md
+++ b/docs/how-it-works.md
@@ -20,7 +20,7 @@
A picture cell holds its row and its column (kitty placeholder U+10EEEE plus two combining marks). The mod finds the drawn page that has these rows, at the size that it is drawn. Then it finds the position of each word on that page: it runs the probe (`typst query` on the same template, with the same inputs as the PNG compile, plus `probe=1` and `page=<n>`) only for the pages that a copy reads, and (for picture select) for the pages on the screen. The mod keeps the positions of the last 64 pages in memory. It writes nothing to disk for this, and the PNGs do not change. The mod takes the words in the selected cells.
-10. Pasted images: the `prompt.edit` and `prompt.change` hooks note the `[Image #N]` numbers of the draft. A `ui.render` hook on `AbovePrompt` draws a small preview of each one above the prompt box, from the PNG that Claude Code wrote at the paste, and a hook on `UserMessage` draws them the same size under a sent prompt. Typst makes a copy that fills the preview's cells (`render/fill.typ`), in a root folder of its own with only that template and a link to the pasted PNG.
+10. Pasted images: the `prompt.edit` and `prompt.change` hooks note the `[Image #N]` numbers of the draft. A `ui.render` hook on `AbovePrompt` draws a small preview of each one above the prompt box, from the PNG that Claude Code wrote at the paste, and a hook on `UserMessage` draws them the same size under a sent prompt. Typst makes a copy that fills the preview's cells (`render/fill.typ`; `contain` in place of `cover` when a cover cuts more than half a cell), in a root folder of its own with only that template and a link to the pasted PNG.
## Picture select
diff --git a/docs/usage.md b/docs/usage.md
index c795323..fcad433 100644
--- a/docs/usage.md
+++ b/docs/usage.md
@@ -38,8 +38,8 @@ Intelligent UI draws Claude's answers as rendered Markdown pictures. Only the dr
When you paste an image into the prompt box, the box shows `[Image #N]`. The mod then shows a small preview of the image above the prompt box, before you send the prompt. The number of the image (`#N`) shows in dim text at the left of its preview.
-- The preview fills its cells. Typst makes a copy of the image that has the size of the cells, one time for each image and size, in the cache folder. Typst runs in a folder of its own with only the pasted image, so it reads no other file. Until the copy is ready, the preview shows the image as it is. Without Typst, or if Typst cannot make the copy, the preview also shows the image as it is.
-- In herdr in iTerm2, a preview shows only when its copy is ready (the mod stores the copy with its rows in the order that iTerm2 shows correctly).
+- The preview fills its cells. Typst makes a copy of the image that has the size of the cells, one time for each image and size, in the cache folder. To fill the cells, the copy can cut a small part of an edge of the image (at most half a cell). If the shape of the image is very different from the shape of its cells (for example, a wide screenshot of one line), the copy shows all of the image, with an empty strip above and below it or at its sides. Typst runs in a folder of its own with only the pasted image, so it reads no other file. Until the copy is ready, the preview shows the image as it is. Without Typst, or if Typst cannot make the copy, the preview also shows the image as it is.
+- In herdr in iTerm2, a preview shows only after the mod stores it with its rows in the order that iTerm2 shows correctly. While Typst makes the copy, there is no preview. Without Typst, or if Typst cannot make the copy, the mod stores the image as it is.
- 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.
diff --git a/hooks/lib/composer.tsx b/hooks/lib/composer.tsx
index e11ff8d..b3d9e73 100644
--- a/hooks/lib/composer.tsx
+++ b/hooks/lib/composer.tsx
@@ -3,8 +3,8 @@
// before it is sent, each after its dim `#N`; a sent prompt's under its row
// (UserMessage), the same size, after the gutter (Claude Code shows the
// numbers there). The picture is a copy that Typst makes to fill
-// its cells exactly (render/fill.typ: no empty cell area under it); the plain
-// image shows until it is made. The draft's numbers are in the `draft` atom
+// 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).
import type { EngineInterface, ImageSource, RenderElement, RenderInput, RenderViewport } from 'claude-code'
@@ -43,10 +43,20 @@ export const cellPixels = (cells: Slot, cell: Cell): PixelBox => ({
height: Math.max(1, Math.round(cells.rows * cell.height)),
})
+// How a filled copy fits its box: `cover` (the aspect kept, the rest cut)
+// only when it cuts at most half a cell, else `contain` (all of the image,
+// an empty strip beside it): a wide one-line screenshot is not cut in half.
+export function fillFitOf(size: Size, box: PixelBox, cell: Cell): 'cover' | 'contain' {
+ const scale = Math.max(box.width / size.width, box.height / size.height)
+ const cut = (n: number, side: number, c: number) => n * scale - side <= c / 2 + 1
+ return cut(size.width, box.width, cell.width) && cut(size.height, box.height, cell.height) ? 'cover' : 'contain'
+}
+
// Where the filled copy of a picture is kept: a key folder of the cache (as
-// a convert's, dropped after 2 days), by the file, its stat stamp and the
-// box in pixels (one copy, whatever its number).
-export const filledPath = (cache: string, p: Picture, box: PixelBox) => `${cache}/${hashOf(['fill', p.file, p.stamp, box.width, box.height])}/image.png`
+// a convert's, dropped after 2 days), by the file, its stat stamp, the box
+// in pixels and the fit (one copy, whatever its number).
+export const filledPath = (cache: string, p: Picture, box: PixelBox, fit: 'cover' | 'contain' = 'cover') =>
+ `${cache}/${hashOf(['fill', p.file, p.stamp, box.width, box.height, ...(fit === 'cover' ? [] : [fit])])}/image.png`
// The previews' layout in `columns` cells and `maxRows` rows (Infinity under
// a row: no cap): each picture at most PREVIEW_ROWS tall (less when the band
@@ -92,8 +102,9 @@ export function linesOf(widths: readonly number[], columns: number): number[][]
// The previews of the images `numbers`, in lines (previewLayout) of
// `columns` cells and `maxRows` rows, after their numbers when `labelled`,
// else after the gutter: each one's filled copy
-// once made, else the plain image (in flip mode none: only the filled copy
-// is stored for its rows). A file that is gone or not a PNG is left out;
+// 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;
// `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(
@@ -118,10 +129,12 @@ export async function previewsOf(
const previews = new Map<number, Preview>()
for (const [i, { n, plain, p }] of found.entries()) {
const box = laid.boxes[i]!
- const made = filledOf($, ready, p, cellPixels(box, cell), o.redraw)
+ const made = filledOf($, ready, p, cellPixels(box, cell), cell, o.redraw)
if (made === undefined) isFinal = false
const q = made ? await pictureOf($, made) : null
- const source = (q ? await sourceOf($, ready, q, box.rows) : null) ?? plain
+ // Flip mode with no copy (no Typst, or it failed): the image stored for its rows.
+ const bare = flip && made === null ? await sourceOf($, ready, p, box.rows) : plain
+ const source = (q ? await sourceOf($, ready, q, box.rows) : null) ?? bare
if (source) previews.set(i, { n, source, ...box })
}
const lines = laid.lines.map(line => line.flatMap(i => previews.get(i) ?? [])).filter(line => line.length)
@@ -136,9 +149,10 @@ const filling = new Map<string, Set<() => void>>()
// A picture's filled copy for `box` pixels: its path; undefined while it is
// made (`redraw` once it is, with every other caller's: the plain image
// shows meanwhile); null when it failed (not tried again) or with no Typst.
-function filledOf($: EngineInterface, ready: Env, p: Picture, box: PixelBox, redraw: () => void): string | null | undefined {
+function filledOf($: EngineInterface, ready: Env, p: Picture, box: PixelBox, cell: Cell, redraw: () => void): string | null | undefined {
if (!ready.typst) return null
- const key = `${p.file}@${p.stamp}@${box.width}x${box.height}`
+ const fit = fillFitOf(p, box, cell)
+ const key = `${p.file}@${p.stamp}@${box.width}x${box.height}@${fit}`
if (filled.has(key)) return filled.get(key) ?? null
const waits = filling.get(key)
if (waits) {
@@ -147,7 +161,7 @@ function filledOf($: EngineInterface, ready: Env, p: Picture, box: PixelBox, red
}
const redraws = new Set([redraw])
filling.set(key, redraws)
- void makeFilled($, ready, p, box).catch(() => null).then(png => {
+ void makeFilled($, ready, p, box, fit).catch(() => null).then(png => {
filling.delete(key)
keep(filled, key, png, PICTURES_KEPT)
if (png) for (const again of redraws) again()
@@ -159,8 +173,8 @@ function filledOf($: EngineInterface, ready: Env, p: Picture, box: PixelBox, red
// whole, as a convert), in a root of its own (FILL_SH: fill.typ and a link
// to the pasted file, removed after). One made in an earlier load is used
// as is. Null when the root can not be made or Typst fails.
-async function makeFilled($: EngineInterface, ready: Env, p: Picture, box: PixelBox): Promise<string | null> {
- const out = filledPath(ready.cache, p, box)
+async function makeFilled($: EngineInterface, ready: Env, p: Picture, box: PixelBox, fit: 'cover' | 'contain'): Promise<string | null> {
+ const out = filledPath(ready.cache, p, box, fit)
const made = await stat($, out).catch(() => null)
if (made?.kind === 'file' && made.size) return out
const dir = folderOf(out)
@@ -175,7 +189,7 @@ async function makeFilled($: EngineInterface, ready: Env, p: Picture, box: Pixel
return null
}
try {
- const { argv, env } = fillCall({ typst: ready.typst!, run, cache: ready.cache, box, out: part })
+ const { argv, env } = fillCall({ typst: ready.typst!, run, cache: ready.cache, box, fit, out: part })
const ran = await exec($, argv, { timeoutMs: COMPILE_TIMEOUT_MS, env })
if (ran.exitCode !== 0) {
await logDebug($, ready.cache, `fill ${p.file} failed:\n${ran.stderr}`)
diff --git a/hooks/lib/typst.ts b/hooks/lib/typst.ts
index bdf2657..c093ae8 100644
--- a/hooks/lib/typst.ts
+++ b/hooks/lib/typst.ts
@@ -213,7 +213,7 @@ export function convertCall(o: {
// A pasted image's preview made to fill `box` pixels (the cells it is drawn
// in) exactly (render/fill.typ), in the root `run` that FILL_SH made: the
// pasted file is /image.png there, and Typst reads no other file.
-export function fillCall(o: { typst: string; run: string; cache: string; box: { width: number; height: number }; out: string }): {
+export function fillCall(o: { typst: string; run: string; cache: string; box: { width: number; height: number }; fit?: 'cover' | 'contain'; out: string }): {
argv: string[]
env: Record<string, string>
} {
@@ -226,6 +226,7 @@ export function fillCall(o: { typst: string; run: string; cache: string; box: {
'--input', 'f=/image.png',
'--input', `maxw=${o.box.width}`,
'--input', `maxh=${o.box.height}`,
+ ...(o.fit === 'contain' ? ['--input', 'fit=contain'] : []),
`${o.run}/fill.typ`,
o.out,
]
@@ -234,13 +235,15 @@ export function fillCall(o: { typst: string; run: string; cache: string; box: {
// The root of a fill: a new private folder ($1) with fill.typ copied from
// the plugin root ($2) (Typst wants its main file inside the root) and a
-// link image.png to the pasted file ($3), which must be a .png file, not a link.
+// link image.png to the pasted file ($3), which must be a .png file, not a
+// link. A copy or link that fails removes the new folder.
export const FILL_SH = [
'umask 077',
'r=$1 p=$2 f=$3',
'case $f in /*.png) ;; *) exit 1 ;; esac',
'[ -f "$f" ] && [ ! -L "$f" ] || exit 1',
- 'mkdir "$r" && cp "$p/render/fill.typ" "$r/fill.typ" && ln -s "$f" "$r/image.png"',
+ 'mkdir "$r" || exit 1',
+ 'cp "$p/render/fill.typ" "$r/fill.typ" && ln -s "$f" "$r/image.png" || { rm -rf "$r"; exit 1; }',
].join('\n')
export function noNetworkEnv(cache: string): Record<string, string> {
diff --git a/hooks/register.tsx b/hooks/register.tsx
index dff2ed3..b1836dc 100644
--- a/hooks/register.tsx
+++ b/hooks/register.tsx
@@ -51,7 +51,7 @@ import { setUp } from './lib/env'
import { frameFor, noteView, stopWatch, watchFrame, watchState } from './lib/frame'
import { herdrText, isFlipHere, roomColumns } from './lib/terminal'
import { onScreenOf, pastedNumbers, sentFiles } from './lib/images'
-import { drawPageField, pdfPagesOf, rowsAfter, sentOf, underRow, type Under } from './lib/pictures'
+import { drawPageField, pasteDir, pdfPagesOf, rowsAfter, sentOf, underRow, type Under } from './lib/pictures'
import { drawPreviews, 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'
@@ -155,7 +155,9 @@ 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.
+// writes nothing. 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) {
try {
const now = pastedNumbers(text)
@@ -872,8 +874,9 @@ export const register: Register = on => {
const isEdit = !!e.inputText || e.end > e.start
if (picked.now && isEdit) clearSelection($)
void Promise.resolve().then(() => nowMs($)).then(t => void (S.keyAt = t), () => undefined)
+ const seq = ++draftSeq
const box = await next(e)
- if (isEdit && e.origin.kind === 'composer') noteDraft($, box.text)
+ if (isEdit && e.origin.kind === 'composer' && seq === draftSeq) noteDraft($, box.text)
return box
}).catch(($, e, next) => next(e))
@@ -882,6 +885,7 @@ export const register: Register = on => {
// change gives the draft's pasted images (a submit clears them).
on('prompt.change', async ($, e, next) => {
if (picked.now && e.origin.kind !== 'plugin' && e.origin.kind !== 'app') clearSelection($)
+ draftSeq++
noteDraft($, e.text)
return next(e)
}).catch(($, e, next) => next(e))
@@ -1263,9 +1267,12 @@ export const register: Register = on => {
let lines: Preview[][] = []
try {
const numbers = await read($, draft)
+ if (!numbers.length) drafts.delete('draft')
const ready = numbers.length ? await pictureEnv($, e) : null
if (ready) {
- const k = { text: numbers.join(','), extra: `${e.props.bodyColumns}x${e.props.maxRows}`, stamp: stampOf(ready, e.viewport), onScreen: undefined }
+ // 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 }
const kept = memoOf(drafts, 'draft', k, () => false)
if (kept) lines = kept
else {
@@ -1275,7 +1282,7 @@ export const register: Register = on => {
lines = made.lines
if (made.isWhole && made.isFinal) memoSet(drafts, 'draft', k, lines)
else drafts.delete('draft')
- if (!made.isWhole) previewRetry($, k.text, redraw)
+ if (!made.isWhole) previewRetry($, `${dir}|${k.text}`, redraw)
}
}
} catch {
diff --git a/render/fill.typ b/render/fill.typ
index 6342b19..dacd24b 100644
--- a/render/fill.typ
+++ b/render/fill.typ
@@ -4,12 +4,14 @@
//
// Inputs: f = the PNG's path in the root (/image.png: FILL_SH links it, and
// the root has only it and this file); maxw, maxh = the pixel size of its
-// cells. The page is exactly that, and the image covers it (the aspect kept,
-// centred, under half a cell cut on one side), so no empty cell area is left
-// under or beside it.
-#set page(width: auto, height: auto, margin: 0pt)
+// cells; fit = cover (the default) or contain. The page is exactly that
+// size. With cover the image covers it (the aspect kept, centred, at most
+// half a cell cut: fillFitOf in composer.tsx), so no empty cell area is left
+// under or beside it; with contain all of it shows, centred, the rest clear.
+#set page(width: auto, height: auto, margin: 0pt, fill: none)
#let num(key) = calc.max(1, float(sys.inputs.at(key, default: "1")))
#let (bw, bh) = (num("maxw"), num("maxh"))
+#let fit = if sys.inputs.at("fit", default: "cover") == "contain" { "contain" } else { "cover" }
-#box(width: bw * 1pt, height: bh * 1pt, clip: true, image(sys.inputs.at("f", default: ""), width: bw * 1pt, height: bh * 1pt, fit: "cover"))
+#box(width: bw * 1pt, height: bh * 1pt, clip: true, image(sys.inputs.at("f", default: ""), width: bw * 1pt, height: bh * 1pt, fit: fit))
diff --git a/tests/fill-sh-test.sh b/tests/fill-sh-test.sh
index 665d871..ebeaada 100644
--- a/tests/fill-sh-test.sh
+++ b/tests/fill-sh-test.sh
@@ -50,6 +50,9 @@ for s in $shells; do
$s -c "$fill_sh" sh "$k/r-no" "$here" "$no" 2>/dev/null && bad "$s: a root for $no" || ok
[ ! -e "$k/r-no" ] && ok || { bad "$s: $k/r-no made for $no"; rm -rf "$k/r-no"; }
done
+ # The copy fails (no render/fill.typ in the plugin root): the new folder goes.
+ $s -c "$fill_sh" sh "$k/r-nocp" "$tmp/no-root" "$paste/5.png" 2>/dev/null && bad "$s: a root with no fill.typ" || ok
+ [ ! -e "$k/r-nocp" ] && ok || bad "$s: $k/r-nocp left after the copy failed"
done
if ! command -v typst >/dev/null 2>&1; then
@@ -67,6 +70,29 @@ fill "$r" /image.png && ok || bad "the pasted image: $(head -n 3 "$tmp/err")"
# The copy is the box in pixels: 40 x 30.
size=$(perl -e 'open(F, "<", $ARGV[0]) or exit 1; binmode F; read(F, my $h, 24); my ($w, $h2) = unpack("NN", substr($h, 16, 8)); print "$w $h2"' "$tmp/out.png")
[ "$size" = "40 30" ] && ok || bad "the copy is $size, not 40 30"
+# Whether row 0 of PNG $1 is clear (alpha 0 all along): a clear first row
+# is all zero bytes whatever its filter.
+clear_top() {
+ perl -MCompress::Zlib -e 'open(F, "<", $ARGV[0]) or exit 2; binmode F; local $/; my $d = <F>; my ($w) = unpack("N", substr($d, 16, 4));
+ my $z = ""; my $i = 8; while ($i < length $d) { my ($n, $t) = unpack("Na4", substr($d, $i, 8)); $z .= substr($d, $i + 8, $n) if $t eq "IDAT"; $i += 12 + $n }
+ my $raw = uncompress($z); exit(substr($raw, 1, $w * 4) =~ /^\0+$/ ? 0 : 1)' "$1"
+}
+# A one-line screenshot (3000 x 36) in a box of one row (1472 x 32):
+# contain shows all of it, centred, with clear rows above and below; cover
+# (no fit input) fills the box (and cuts its ends).
+printf '#set page(width: 3000pt, height: 36pt, margin: 0pt, fill: white)\n' | typst compile -f png --ppi 72 - "$paste/wide.png"
+r=$tmp/cache/k1/r-wide
+sh -c "$fill_sh" sh "$r" "$here" "$paste/wide.png" && ok || bad "FILL_SH failed for the wide image"
+wide() {
+ perl -e 'alarm 20; exec @ARGV' typst compile --root "$r" --format png --ppi 72 --input f=/image.png --input maxw=1472 --input maxh=32 "$@" "$r/fill.typ" "$tmp/wide.png" > "$tmp/err" 2>&1
+}
+size_of() { perl -e 'open(F, "<", $ARGV[0]) or exit 1; binmode F; read(F, my $h, 24); my ($w, $h2) = unpack("NN", substr($h, 16, 8)); print "$w $h2"' "$1"; }
+wide --input fit=contain && ok || bad "fit contain: $(head -n 3 "$tmp/err")"
+[ "$(size_of "$tmp/wide.png")" = "1472 32" ] && ok || bad "fit contain: the copy is $(size_of "$tmp/wide.png"), not 1472 32"
+clear_top "$tmp/wide.png" && ok || bad "fit contain: the top row is not clear (the image was not contained)"
+wide && ok || bad "no fit: $(head -n 3 "$tmp/err")"
+clear_top "$tmp/wide.png" && bad "no fit (cover): the top row is clear" || ok
+
# Any other file: not found, or out of the root.
for f in /etc/hosts "$secret" "$paste/5.png" ../../../../../../../../etc/hosts /fill.typ; do
if fill "$r" "$f"; then bad "f=$f: compiled"
diff --git a/tests/preview.test.ts b/tests/preview.test.ts
new file mode 100644
index 0000000..bd9dd25
--- /dev/null
+++ b/tests/preview.test.ts
@@ -0,0 +1,224 @@
+import { expect, mock, test } from 'claude-code/testing'
+
+import { encodeSteps, flipRows, WRITE_PL } from '../hooks/lib/flip'
+import { decodePng, fromBase64, toBase64, type Rgba } from '../hooks/lib/png'
+import { HERDR_CLIENT_SH } from '../hooks/lib/host'
+import { FILL_SH } from '../hooks/lib/typst'
+import { fillFitOf } from '../hooks/lib/composer'
+import { cellPixels, DEFAULT_CELL, fillCall, filledPath, previewLayout } from '../hooks/register'
+
+// The previews of pasted images (the band above the prompt box): a new
+// session, a clear during a paste, herdr in iTerm2 with no Typst, and how a
+// filled copy fits its box. images.test.ts has the rest.
+
+const ok = (stdout: string, exitCode = 0) => ({ value: { exitCode, stdout, stderr: exitCode ? 'error: boom' : '', isStdoutTruncated: false, isStderrTruncated: false } })
+// `od -An -v -tx1` of a PNG's first 24 bytes: 640 x 320.
+const HEAD = '89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 02 80 00 00 01 40'
+// A tall PNG: 640 x 3200 px.
+const TALL = '89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 02 80 00 00 0c 80'
+// A one-line screenshot: 3000 x 36 px.
+const WIDE = '89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 0b b8 00 00 00 24'
+// The first 33 bytes of a PNG, base64.
+const PNG = 'iVBORw0KGgoAAAANSUhEUgAABkAAAABACAYAAAAAAAAA'
+const ENGINE = { type: 'Text', props: {}, children: ['engine drawing'] }
+const PASTED = '/private/tmp/claude-501/-w-app/sid-1/images'
+const NEW = '/private/tmp/claude-501/-w-app/sid-2/images'
+const ITERM = '/Applications/iTerm.app/Contents/MacOS/iTerm2'
+
+// A small RGBA picture (each row its own colour) as a PNG, and its pixels.
+const ROWS_IMG: Rgba = (() => {
+ const data = new Uint8Array(8 * 20 * 4)
+ for (let y = 0; y < 20; y++) for (let x = 0; x < 8; x++) data.set([y * 12, x * 30, 255 - y, 255], (y * 8 + x) * 4)
+ return { width: 8, height: 20, data }
+})()
+const ROWS_PNG = (() => {
+ const steps = encodeSteps(ROWS_IMG)
+ for (;;) {
+ const got = steps.next()
+ if (got.done) return toBase64(got.value)
+ }
+})()
+
+// A Mac with kitty (pictures drawn), uid 501, in /w/app. `files`: the files
+// that exist, by path (their first bytes as od prints them); `dirs`: the
+// folders. `typst`: Typst is found (a fill makes the copy). `herdr`: the
+// terminal app of the herdr client. `bytes`: what a read of any PNG gives
+// (else PNG). `sid`: the session id now.
+function world(on: any, o: { files?: Record<string, string>; dirs?: string[]; typst?: boolean; herdr?: string; bytes?: string; sid?: () => string } = {}) {
+ const clock = mock.clock(on)
+ mock.env(on, { HOME: '/h', TERM: 'xterm-kitty', ...(o.herdr ? { TERM_PROGRAM: 'herdr' } : {}) })
+ on('store.get', async () => ({ value: undefined }))
+ on('store.set', async () => ({ value: undefined }))
+ const files = o.files ?? {}
+ const dirs = new Set(o.dirs ?? [])
+ const fills: string[][] = []
+ const pngs = new Map<string, Uint8Array>()
+ on('process.spawn', async function* () {
+ return { value: { code: 1, signal: null } }
+ })
+ on('process.run', async ($: any, e: any) => {
+ const argv: string[] = e.argv
+ 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] === WRITE_PL) return (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')
+ if (cmd.includes('command -v typst')) return o.typst ? ok('/usr/bin/typst\n') : ok('', 1)
+ if (argv[0] === '/usr/bin/typst' && argv[1] === 'eval') return ok('{}')
+ if (argv[0] === 'mv') {
+ if (!(argv[2]! in files)) return ok('', 1)
+ files[argv[3]!] = files[argv[2]!]!
+ delete files[argv[2]!]
+ return ok('')
+ }
+ if (argv[0] === 'sh' && argv[2] === FILL_SH) return ok('')
+ if (argv[0] === 'rm' && argv[1] === '-rf') return ok('')
+ if (argv[0] === '/usr/bin/typst' && argv[1] === 'compile' && argv.at(-2)!.endsWith('/fill.typ')) {
+ fills.push(argv)
+ files[argv.at(-1)!] = HEAD
+ return ok('')
+ }
+ if (cmd.includes('od -An')) return ok(argv.slice(4).map(f => `${files[f] ?? ''}\n@\n`).join(''))
+ if (cmd.includes('debug.log')) return ok('')
+ return ok('', 1)
+ })
+ on('session.id', async () => ({ value: o.sid?.() ?? 'sid-1' }))
+ on('session.cwd', async () => ({ value: '/w/app' }))
+ on('session.root', async () => ({ value: '/w/app' }))
+ on('fs.stat', async ($: any, e: any, next: any) => {
+ if (e.path in files) return { value: { kind: 'file', size: 1000, mtimeMs: 1, isLink: false } }
+ return e.path.startsWith('/private/') || e.path.startsWith('/c/') ? { deny: 'ENOENT' } : next(e)
+ })
+ on('fs.exists', async ($: any, e: any, next: any) => {
+ if (e.path.startsWith('/private/')) return { value: dirs.has(e.path) }
+ return e.path.endsWith('/typst') ? { value: false } : next(e)
+ })
+ on('fs.list', async ($: any, e: any, next: any) => (e.path === '/private/tmp/claude-501' ? { value: [] } : next(e)))
+ on('fs.write', async () => ({ value: undefined }))
+ on('fs.read', async ($: any, e: any, next: any) => {
+ if (e.as === 'bytes' && e.path in files) return { value: { base64: o.bytes ?? PNG } }
+ return e.path.startsWith('/c/') ? { deny: 'ENOENT' } : next(e)
+ })
+ on('ui.toast', async () => ({ value: undefined }))
+ on('ui.render', () => ENGINE as any)
+ return { clock, fills, pngs, files }
+}
+
+const images = (tree: any): any[] =>
+ tree && typeof tree === 'object' ? [...(tree.type === 'Image' ? [tree] : []), ...(tree.children ?? []).flatMap(images)] : []
+const alts = (tree: any): string[] => images(tree).map(i => i.props.alt)
+// Sets the mod up (as the first answer would) before a row draws.
+const ready = ($: any) => $.command.run({ command: 'iui', args: '' } as any)
+const band = () =>
+ ({
+ plugin: 'cc-intelligent-ui', surface: 'terminal', component: 'AbovePrompt', requestId: 'band',
+ props: { hasSurvey: false, isWorking: false, maxRows: 20, bodyColumns: 95, scroll: { offset: 0, bodyRows: 19 }, view: {} },
+ viewport: { columns: 100, rows: 40 },
+ }) as any
+// The editor beneath the mod: an edit is its splice, a change the box as given.
+function editor(on: any) {
+ 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 }))
+}
+// A paste (or a key) at the end of `text`.
+const typed = (text: string, inputText: string) => ({ origin: { kind: 'composer' }, text, cursor: text.length, start: text.length, end: text.length, inputText }) as any
+const CLEAR = { text: '', cursor: 0, origin: { kind: 'clear' } }
+
+test('after /clear (a new session), a new [Image #1] previews its own file, not the last session\'s #1', async ($, on) => {
+ let id = 'sid-1'
+ world(on, { sid: () => id, files: { [`${PASTED}/1.png`]: HEAD, [`${NEW}/1.png`]: TALL }, dirs: [PASTED, NEW] })
+ editor(on)
+ await ready($)
+ const prompt = ($ as any).prompt
+ const ui = await $.ui.mount(band())
+ await prompt.edit(typed('', '[Image #1]'))
+ expect(images(await ui.drawn())[0].props.source.file).toBe(`${PASTED}/1.png`)
+ // The draft is cleared, then /clear starts a new session: its images are numbered from #1 again.
+ await prompt.change(CLEAR)
+ expect(await ui.drawn()).toMatchObject(ENGINE)
+ id = 'sid-2'
+ await prompt.edit(typed('', '[Image #1]'))
+ const [image] = images(await ui.drawn())
+ expect(image.props.source.file).toBe(`${NEW}/1.png`)
+ expect([image.props.columns, image.props.rows]).toEqual([2, 5])
+})
+
+test('a clear of the box that comes while a paste\'s edit is still answered: no preview; the next paste shows again', async ($, on) => {
+ world(on, { files: { [`${PASTED}/5.png`]: HEAD }, dirs: [PASTED] })
+ // The editor beneath the mod: the paste's answer comes late.
+ let release = () => {}
+ let pending = () => {}
+ const isPending = new Promise<void>(r => (pending = r))
+ const gate = new Promise<void>(r => (release = r))
+ let held = false
+ on('prompt.edit', async ($: any, e: any) => {
+ if (e.inputText === '[Image #5]' && !held) {
+ held = true
+ pending()
+ await gate
+ }
+ return { 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 ready($)
+ const prompt = ($ as any).prompt
+ const ui = await $.ui.mount(band())
+ const paste = prompt.edit(typed('', '[Image #5]'))
+ await isPending
+ await prompt.change(CLEAR)
+ release()
+ await paste
+ expect(alts(await ui.drawn())).toEqual([])
+ // A later paste is noted as before.
+ await prompt.edit(typed('', '[Image #5]'))
+ expect(alts(await ui.drawn())).toEqual(['[Image #5]'])
+})
+
+test('in herdr in iTerm2 with no Typst, a pasted image previews from the image itself, stored flipped by rows for its box', async ($, on) => {
+ const { pngs, fills } = world(on, { herdr: ITERM, files: { [`${PASTED}/5.png`]: HEAD }, dirs: [PASTED], bytes: ROWS_PNG })
+ editor(on)
+ await ready($)
+ const ui = await $.ui.mount(band())
+ await ($ as any).prompt.edit(typed('', '[Image #5]'))
+ const [image] = images(await ui.drawn())
+ expect(fills.length).toBe(0)
+ expect(image.props).toMatchObject({ columns: 20, rows: 5, alt: '[Image #5]' })
+ expect(image.props.source.file).toMatch(/^\/c\/[0-9a-f]{16}\/flip\.png$/)
+ expect([...decodePng(pngs.get(image.props.source.file)!).data]).toEqual([...flipRows(ROWS_IMG, 5).data])
+})
+
+test('a filled copy covers its box only when that cuts at most half a cell, else it contains the image', () => {
+ // A one-line screenshot: one row of 92 columns; a cover would cut 45% of it.
+ const wide = { width: 3000, height: 36 }
+ const laid = previewLayout([wide], DEFAULT_CELL, 95, 20, [3])!
+ const box = cellPixels(laid.boxes[0]!, DEFAULT_CELL)
+ expect(box).toEqual({ width: 1472, height: 32 })
+ expect(fillFitOf(wide, box, DEFAULT_CELL)).toBe('contain')
+ // A picture of the box's shape, and one a few pixels off it: cover.
+ expect(fillFitOf({ width: 640, height: 320 }, { width: 320, height: 160 }, DEFAULT_CELL)).toBe('cover')
+ expect(fillFitOf({ width: 1000, height: 700 }, { width: 224, height: 160 }, DEFAULT_CELL)).toBe('cover')
+ // More than half a cell cut on a side: contain.
+ expect(fillFitOf({ width: 100, height: 50 }, { width: 96, height: 64 }, DEFAULT_CELL)).toBe('contain')
+ // The fit is an input of fill.typ (none for cover), and part of the key.
+ const call = (fit?: 'cover' | 'contain') => fillCall({ typst: '/t', run: '/c/k/r-1', cache: '/c', box, fit, out: '/o.png' }).argv
+ expect(call('contain')).toEqual(expect.arrayContaining(['fit=contain']))
+ expect(call('cover')).toEqual(call())
+ const p = { file: '/t/5.png', stamp: '1:1000', bytes: 1000, ...wide }
+ expect(filledPath('/c', p, box, 'contain')).not.toBe(filledPath('/c', p, box))
+ expect(filledPath('/c', p, box, 'cover')).toBe(filledPath('/c', p, box))
+})
+
+test('a pasted one-line screenshot is filled with fit contain; a normal picture with no fit input (cover)', async ($, on) => {
+ const { clock, fills } = world(on, { typst: true, files: { [`${PASTED}/5.png`]: WIDE, [`${PASTED}/6.png`]: HEAD }, dirs: [PASTED] })
+ editor(on)
+ await ready($)
+ const ui = await $.ui.mount(band())
+ await ($ as any).prompt.edit(typed('', '[Image #5] [Image #6]'))
+ await ui.drawn()
+ await clock.settle()
+ expect(fills.length).toBe(2)
+ const of = (n: number) => fills.find(argv => argv.includes(`maxw=${n === 5 ? 1472 : 320}`))!
+ expect(of(5)).toContain('fit=contain')
+ expect(of(6).some(a => a.startsWith('fit='))).toBe(false)
+})