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
Pictures: PDF files that Claude sends draw one page under their row, with ‹ page › controls
razorback168d178acb5b47
diff --git a/docs/limitations.md b/docs/limitations.mdindex cc70e2c..1beffa4 100644--- a/docs/limitations.md+++ b/docs/limitations.md@@ -14,6 +14,7 @@- With two Claude Code sessions on one computer, a session that has no selection can change a copy from the other session, with the text of its own picture.- To stop the clipboard write on select, set `copyOnSelect` to `false` in `/config`. Then the mod does not copy a selection either, because it acts only when the clipboard changes. It changes only a clipboard that has picture cells (for example, after a copy with a key).- **Links in a picture:** a click on the picture does not open a link, because the mod cannot put a link on a picture. Use the link rows under the picture (refer to [Links, file paths and commands](usage.md#links-file-paths-and-commands)). A click on a command row copies the command only where Claude Code gets mouse clicks (fullscreen mode). A `file://` link opens in the app that the terminal chooses. A file row shows only when the file exists when the mod draws the answer.+- **PDF files** (refer to [What it draws](usage.md#what-it-draws)): a click on `‹`, `›` or the page number works only where Claude Code gets mouse clicks (fullscreen mode). The page field gets the keyboard only when the prompt is empty. If the prompt has text, the field opens without the keyboard: click the field to type. Then Esc goes to the prompt, not to the field. To close the field, click it and push Esc, or click its close mark. The mod draws one page at a time, and it does not show the number of pages. You cannot copy text from a PDF page.- **The row grid** (`/iui grid on`, refer to [Selection and the row grid](usage.md#selection-and-the-row-grid)) has these limits:- Inline math that is taller than a row adds 1 row or more to its line. The text stays on the rows. Math that is only a little taller than the row does not add a row, and its ink can come near the line above or below.- At 100% text size, a level-1, level-2 or level-3 heading uses 3 rows. A level-2 or level-3 heading has 2 rows for the text and half a row above and below it. With a large text size (`/iui size`), a line uses 2 rows. A line of code uses 2 rows from approximately 111%. A line of body text uses 2 rows from approximately 117%. Then there is an almost empty row between the lines of a paragraph, and the picture starts half a row down. A heading or a code block is 1 row taller if its lines use an odd number of rows and a line of body text uses an even number of rows (or the opposite), because the mod moves its lines down by half a row. These values change with the terminal font and the cell size.diff --git a/docs/usage.md b/docs/usage.mdindex 6d82285..627dac1 100644--- a/docs/usage.md+++ b/docs/usage.md@@ -21,9 +21,14 @@ Intelligent UI draws Claude's answers as rendered Markdown pictures. Only the drA `theme` dictionary (`theme.fg`, `theme.muted`, `theme.blue`, `theme.palette`, `theme.width`, …) is in scope, so drawings match the terminal's colours. The mod tells Claude about this in a short part of the system prompt. `theme.width` and `theme.height` give the space for a drawing. The mod keeps the size that a message had when it was drawn the first time. When the terminal size changes, the mod makes the drawings larger or smaller by the same amount.- Files that Claude sends to you (the SendUserFile tool). The mod draws each file under the row that shows the files, in the same order:- PNG, JPEG, WebP and SVG images. Typst changes a JPEG, WebP or SVG image into a PNG image in the cache folder. The PNG image is the size of the space for the picture in the transcript, or smaller. Typst does this one time for each version of the file and each size of the space. When the space changes, the mod shows the old PNG image until Typst makes the new one.+ - PDF files. The mod draws one page of the PDF. Typst changes the page into a PNG image in the cache folder. The page fills the space for the picture in the transcript, and it can be larger than the page in the PDF. A line with the page number shows under the page, for example `‹ 3 ›`. Click `‹` or `›` to show the page before or the page after. `‹` is gray on page 1, and `›` is gray on the last page. When a page shows, Typst also makes the next page, so that `›` shows it immediately. The mod does not show the number of pages.++ Click the page number to go to a page: a field with the page number opens above the prompt (in fullscreen mode in a wide terminal, at the side of the transcript). Type the page number and push Enter. Push Esc to close the field. If the page does not exist, the field stays open and shows `No page N`.++ A PDF with one page has no line under it. If Typst cannot read the PDF (for example, a PDF with a password or a damaged PDF), the row shows one gray line with the error from Typst. If Typst cannot make one page, the row shows the error for that page above the line. Each row starts on page 1. The mod keeps the page of each row in memory only: a reload of the mod sets all rows to page 1 again, and an old row can lose its page when there are many rows. If the PDF gets shorter, a row on a page that is gone shows the last page.- Markdown files (`.md` or `.markdown`, 256 KiB or less). The mod draws the file as rendered pictures, the same as an answer. A relative image path in the file starts from the folder of the file.- Other files stay as the normal row. JPEG images, WebP images, SVG images and Markdown files need Typst.+ Other files stay as the normal row. JPEG images, WebP images, SVG images, PDF files and Markdown files need Typst.- Images that you paste into the prompt (`[Image #N]`). The mod draws each image under your prompt.These pictures are not larger than the image. They are not wider than the transcript. The height setting (`/iui height`) sets the most rows that they can use (Typst drawings use it too): by default, half the screen and not more than 24 rows. The mod draws PNG, JPEG, WebP and SVG images only. Other image types (for example GIF) stay as the normal row. The size of an SVG image is its width and height in CSS px.diff --git a/hooks/lib/api.ts b/hooks/lib/api.tsindex b028cbb..49e545f 100644--- a/hooks/lib/api.ts+++ b/hooks/lib/api.ts@@ -5,7 +5,7 @@// follows `$` into a declaration only), with the types of EngineInterface.import type {AskOptions, CommandSpec, EngineInterface, FsBytes, FsReadBytesOptions, FsReadOptions, FsStatOptions, HttpInit, InvalidatableEventName,- OpEventOf, ProcessRunInit, ProcessSpawnRequest, ResolveInput, ToastOptions, UiCopyArgs, UiLogOptions,+ OpEventOf, PaneCloseArgs, PaneOpenArgs, ProcessRunInit, ProcessSpawnRequest, ResolveInput, ToastOptions, UiCopyArgs, UiLogOptions,} from 'claude-code'// The environment variables the mod reads. `$.env.get` takes a literal name@@ -156,6 +156,10 @@ export function uiAsk($: EngineInterface, question: string, options?: readonly sreturn $.ui.ask(question, options)}+export function uiClose($: EngineInterface, pane: PaneCloseArgs) {+ return $.ui.close(pane)+}+export function uiCopy($: EngineInterface, args: UiCopyArgs) {return $.ui.copy(args)}@@ -168,6 +172,10 @@ export function uiLog($: EngineInterface, text: string, options?: UiLogOptions)return $.ui.log(text, options)}+export function uiOpen($: EngineInterface, pane: PaneOpenArgs) {+ return $.ui.open(pane)+}+export function uiResolve<E extends ResolveInput>($: EngineInterface, e: E) {return $.ui.resolve(e)}diff --git a/hooks/lib/epoch.ts b/hooks/lib/epoch.tsindex 7b292da..c0ff6ee 100644--- a/hooks/lib/epoch.ts+++ b/hooks/lib/epoch.ts@@ -108,8 +108,8 @@ export function jobDone($: EngineInterface) {const holds = (job: Job) => job.epoch === S.epoch && job.onScreen !== false// Commits the open epoch when no burst runs and it is overdue, or it is-// ready and no job of it on screen waits or runs and no JPEG, WebP or SVG-// converts.+// ready and no job of it on screen waits or runs and no JPEG, WebP, SVG or+// PDF page converts.function maybeCommit($: EngineInterface) {if (S.resizing || !epochOpen()) returnif (!overdue) {diff --git a/hooks/lib/images.ts b/hooks/lib/images.tsindex e953284..cb4f8bd 100644--- a/hooks/lib/images.ts+++ b/hooks/lib/images.ts@@ -1,7 +1,7 @@-// Pictures under rows (pure): which images and Markdown files a SendUserFile-// result names, which images a prompt names, where Claude Code keeps pasted-// images, and the cells a picture takes. The drawing on the host is in-// pictures.tsx.+// Pictures under rows (pure): which images, PDFs and Markdown files a+// SendUserFile result names, which images a prompt names, where Claude Code+// 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 { hashOf } from './draw'@@ -33,9 +33,10 @@ export function pictureCells(size: { width: number; height: number }, columns: n}// The kinds of file a SendUserFile result can draw: an image the engine's-// Image takes (PNG), an image Typst makes a PNG of (JPEG, WebP, SVG), and a-// Markdown file (drawn as an answer is).-export type SentKind = 'png' | 'jpeg' | 'webp' | 'svg' | 'markdown'+// Image takes (PNG), an image Typst makes a PNG of (JPEG, WebP, SVG), a PDF+// (Typst makes a PNG of one page), and a Markdown file (drawn as an answer+// is).+export type SentKind = 'png' | 'jpeg' | 'webp' | 'svg' | 'pdf' | 'markdown'export type SentFile = { path: string; kind: SentKind }// An image's type: by its media type, else by its file name. Null for any@@ -61,6 +62,12 @@ export const isSvgPath = (path: string) => /\.svg$/i.test(path)const isSvg = (a: { path: string; media_type?: unknown }) =>typeof a.media_type === 'string' ? a.media_type.trim().toLowerCase() === 'image/svg+xml' : isSvgPath(a.path)+// A PDF file, by its name. Claude Code sends one with isImage false and the+// media type application/pdf.+export const isPdfPath = (path: string) => /\.pdf$/i.test(path)+const isPdf = (a: { path: string; media_type?: unknown }) =>+ typeof a.media_type === 'string' ? a.media_type.trim().toLowerCase() === 'application/pdf' : isPdfPath(a.path)+// A Markdown file, by its name: .md or .markdown.export const isMarkdownPath = (path: string) => /\.(md|markdown)$/i.test(path)@@ -72,31 +79,101 @@ export function sentFiles(output: unknown): SentFile[] {for (const a of list) {if (!a || typeof a !== 'object' || typeof a.path !== 'string' || a.path === '') continueif (found.some(f => f.path === a.path)) continue- const kind = a.isImage === true ? imageKindOf(a) : isSvg(a) ? 'svg' : isMarkdownPath(a.path) ? 'markdown' : null+ const kind = a.isImage === true ? imageKindOf(a) : isSvg(a) ? 'svg' : isPdf(a) ? 'pdf' : isMarkdownPath(a.path) ? 'markdown' : nullif (kind) found.push({ path: a.path, kind })}return found}-// The image paths of a SendUserFile result that can draw (PNG, JPEG, WebP, SVG).+// The paths of a SendUserFile result that draw as a picture (PNG, JPEG,+// WebP, SVG, and a page of a PDF).export const sentImages = (output: unknown) => sentFiles(output).filter(f => f.kind !== 'markdown').map(f => f.path)// The folder of a file, for the relative images of a Markdown file.export const folderOf = (path: string) => path.replace(/\/+[^/]*$/, '') || '/'-// The box in pixels a JPEG, WebP or SVG is made to fit: the space a picture-// takes (as pictureCells), each side at most CONVERT_MAX_SIDE.+// The box in pixels a JPEG, WebP, SVG or PDF page is made to fit: the space+// a picture takes (as pictureCells), each side at most CONVERT_MAX_SIDE.export type PixelBox = { width: number; height: number }export function convertBox(columns: number, rows: number, px: Cell): PixelBox {const side = (n: number) => Math.max(1, Math.min(CONVERT_MAX_SIDE, Math.round(n)))return { width: side(columns * px.width), height: side(rows * px.height) }}-// The PNG Typst makes of a JPEG, WebP or SVG: in a key folder of the cache (as a-// compile's, dropped after 2 days), by the file, its stat stamp and the box,-// so a changed file or a new box is made again.-export const convertedPath = (cache: string, file: string, stamp: string, box: PixelBox) =>- `${cache}/${hashOf(['convert', file, stamp, box.width, box.height])}/image.png`+// The PNG Typst makes of a JPEG, WebP or SVG, or of a PDF's page: in a key+// folder of the cache (as a compile's, dropped after 2 days), by the file,+// its stat stamp, the box and the page, so a changed file, a new box or+// another page is made again. With no page the key is as before.+export const convertedPath = (cache: string, file: string, stamp: string, box: PixelBox, page?: number) =>+ `${cache}/${hashOf(['convert', file, stamp, box.width, box.height, ...(page ? ['page', page] : [])])}/image.png`++// ---- PDF pages ----------------------------------------------------------------+// A PDF draws one page at a time. Its page count is not read: when page N+// shows, page N+1 is made too, and Typst's "page N+1 does not exist" tells+// that N is the last page. The hint of that error has the page count.++// What is known of a PDF's pages at one stat stamp: the highest page made+// (0: none yet), the lowest page Typst says does not exist (0: not known),+// the page count from Typst's hint (0: not known), and the short Typst+// error of each page that failed for another reason.+export type PdfFacts = { made: number; missing: number; pages: number; errors: Readonly<Record<number, string>> }+export const NO_FACTS: PdfFacts = { made: 0, missing: 0, pages: 0, errors: {} }++// Typst's error for a page that is not in the PDF ("failed to load PDF+// (page 4 does not exist)").+export const isNoPageError = (stderr: string) => /\bpage \d+ does not exist\b/i.test(stderr)++// The page count in the hint of that error ("hint: the document only has+// 3 pages", in Typst's human format only); 0 when it is not there.+export const pageCountOf = (stderr: string) => Number(/\bonly has (\d+) pages?\b/i.exec(stderr)?.[1] ?? 0)++// The first Typst error of a run, short: the text after "error: ", its+// "failed to load PDF (…)" cut to what is in the parentheses.+export function shortError(stderr: string): string {+ const line = stderr.split('\n').find(l => /\berror: /.test(l)) ?? stderr.split('\n').find(l => l.trim()) ?? ''+ const text = line.replace(/^.*?\berror: /, '').trim()+ return (/^failed to load PDF \((.+)\)$/i.exec(text)?.[1] ?? text) || 'Typst could not read it'+}++// The facts after a run for `page`: made (`stderr` null), not there (with+// the page count when the hint gives it), or another error.+export function factsAfter(f: PdfFacts, page: number, stderr: string | null): PdfFacts {+ if (stderr === null) {+ const { [page]: _, ...errors } = f.errors+ return { ...f, made: Math.max(f.made, page), errors }+ }+ if (isNoPageError(stderr)) {+ const pages = pageCountOf(stderr)+ if (pages > 0 && pages < page) return { ...f, pages, missing: pages + 1 }+ return { ...f, missing: f.missing ? Math.min(f.missing, page) : page }+ }+ return { ...f, errors: { ...f.errors, [page]: shortError(stderr) } }+}++// The last page as far as it is known, for a row whose page is gone (the+// file got shorter): the page count, or the page before the first missing+// one when that page was made; else page 1.+export const lastKnownPage = (f: PdfFacts) => (f.pages ? f.pages : f.missing > 1 && f.made === f.missing - 1 ? f.made : 1)++// The page to show: at least 1, and before a page known not to exist.+export const pageOf = (page: number, missing: number) => Math.max(1, missing ? Math.min(page, missing - 1) : page)++// The control line under a page: whether ‹ (`back`) and › (`forward`) act.+// › acts until the next page is known not to exist. Null for a PDF of one+// page: no line.+export function pageControls(page: number, missing: number): { back: boolean; forward: boolean } | null {+ if (missing === 2) return null+ return { back: page > 1, forward: !missing || page + 1 < missing }+}++// A page number the person typed: a whole number from 1, spaces around it+// allowed; null for any other text.+export function parsePage(text: string): number | null {+ const t = text.trim()+ if (!/^\d+$/.test(t)) return null+ const n = Number(t)+ return n >= 1 && Number.isSafeInteger(n) ? n : null+}// The numbers of the `[Image #N]` marks in a prompt, each once, in order.export function pastedNumbers(text: string): number[] {diff --git a/hooks/lib/pictures.tsx b/hooks/lib/pictures.tsxindex ee4012b..852f052 100644--- a/hooks/lib/pictures.tsx+++ b/hooks/lib/pictures.tsx@@ -1,29 +1,46 @@// Pictures under rows: the files Claude sends (SendUserFile) and the images// the user pastes are drawn under their row. An image is drawn at its own-// size or smaller (a JPEG, WebP or SVG as the PNG Typst makes of it); a Markdown-// file as an answer is. The pure parts are in images.ts.+// size or smaller (a JPEG, WebP or SVG as the PNG Typst makes of it); a PDF+// as one page, with a control line to turn the pages; a Markdown file as an+// answer is. The pure parts are in images.ts.import type { EngineInterface, FsStat, ImageSource, RenderElement, RenderInput } from 'claude-code'import { COMPILE_TIMEOUT_MS, GUTTER, PICTURES_KEPT, SENT_TEXT_MAX_BYTES, type Height } from './settings'-import { converted, converting, epochOpen, INLINE_KEPT, inlined, keep, lastConverted, pasteDirs, pictures, S, sentTexts, type Env } from './state'+import {+ converted, converting, epochOpen, INLINE_KEPT, inlined, keep, lastConverted, pageAsk, pasteDirs, pdfFacts, pdfPages, pictures, refresh, S, sentTexts,+ type Env,+} from './state'import { jobDone } from './epoch'import { fitBox, fitsInline, INLINE_MAX_BYTES, roomColumns } from './terminal'-import { convertBox, convertedPath, folderOf, onScreenOf, pasteDirOf, pictureCells, pictureRowsFor, type PixelBox, type SentFile } from './images'+import {+ convertBox, convertedPath, factsAfter, folderOf, isNoPageError, lastKnownPage, NO_FACTS, onScreenOf, pageControls, pageOf, parsePage, pasteDirOf, pictureCells,+ pictureRowsFor, type PdfFacts, type PixelBox, type SentFile,+} from './images'import { imagePathOf } from './markdown'import { drawPages, hashOf, linksFor, type ShownLink } from './draw'import { convertCall, logDebug, parseOd, pngSize } from './typst'import { pagesOf, type Drawing } from './answer'import { HEADERS_SH } from './host'import { frameFor, pictureColumns, shownFor, type Frame } from './frame'-import { clockAfter, fsExists, fsList, fsRead, fsStat, fsWrite, processRun, sessionId, sessionRoot, uiResolve } from './api'+import { clockAfter, fsExists, fsList, fsRead, fsStat, fsWrite, processRun, sessionId, sessionRoot, uiClose, uiInvalidate, uiOpen, uiResolve } from './api'export type Picture = { file: string; stamp: string; bytes: number; width: number; height: number }export type Shown = { source: ImageSource; columns: number; rows: number; alt: string }-// What draws under a SendUserFile row: a picture, or a Markdown file's-// pages (`blank`: an empty space while they compile; an older, wider page-// draws smaller to fit) with its pagesOf id (a copy reads them by it) and-// the link rows under its pages (none while blank).-export type Under = Shown | { drawing: Exclude<Drawing, { kind: 'text' }>; id: string; links?: readonly ShownLink[] }+// The control line under a PDF's page: the row's key in pdfPages, the+// file and its stat stamp, the page, whether ‹ and › act, and the box of+// the picture (the page field makes a page at it).+export type PageLine = { row: string; file: string; stamp: string; page: number; back: boolean; forward: boolean; box: PixelBox }+// What draws under a SendUserFile row: a picture (a PDF's page with its+// control line, none for a PDF of one page), a dim line with Typst's error+// (a PDF that Typst can not read; a PDF page that failed, with its control+// line), or a Markdown file's pages (`blank`: an empty space while they+// compile; an older, wider page draws smaller to fit) with its pagesOf id+// (a copy reads them by it) and the link rows under its pages (none while+// blank).+export type Under =+ | (Shown & { pdf?: PageLine })+ | { note: string; pdf?: PageLine }+ | { drawing: Exclude<Drawing, { kind: 'text' }>; id: string; links?: readonly ShownLink[] }export type RowInput = RenderInput<'ToolResult' | 'UserMessage', 'terminal'>// Where a stat is read: the `done` value the row read and the row's@@ -118,27 +135,33 @@ export async function shownOne($: EngineInterface, e: RowInput, ready: Env, fileconst nameOf = (file: string) => file.split('/').pop() || 'image'-// A JPEG, WebP or SVG as a PNG that Typst makes (render/convert.typ) in the-// cache, to fit `box`: once per stat stamp and box, one run at a time per-// key. The first PNG of a file is waited for; for a new box, the last PNG-// of the file draws at once while the new one is made, then jobDone draws-// it (in an open epoch: at its commit, which waits for every convert).-// `at`: as statOf. Null with no Typst, or when it fails (the row stays as is).-export async function convertedOf($: EngineInterface, ready: Env, file: string, box: PixelBox, at?: StatAt): Promise<string | null> {+// A JPEG, WebP or SVG, or a PDF's page, as a PNG that Typst makes+// (render/convert.typ) in the cache, to fit `box`: once per stat stamp, box+// and page, one run at a time per key. The first PNG of a file is waited+// for; for a new box or page, the last PNG shown of the file draws at once+// while the new one is made, then jobDone draws it (in an open epoch: at+// its commit, which waits for every convert). `at`: as statOf; `pdf`: as+// PdfRun. Null with no Typst, or when it fails (the row stays as is; a+// PDF's page that failed draws nothing in its place).+export async function convertedOf($: EngineInterface, ready: Env, file: string, box: PixelBox, at?: StatAt, pdf?: PdfRun): Promise<string | null> {if (!ready.typst) return nullconst st = await statOf($, file, at)if (!st || st.kind !== 'file') return nullconst stamp = `${st.mtimeMs}:${st.size}`- const before = lastPngOf(file, stamp)- const key = `${file}@${stamp}@${box.width}x${box.height}`- if (converted.has(key)) return converted.get(key) ?? before+ const before = pdf?.wait ? null : lastPngOf(pdf?.row ?? file, stamp)+ const key = convertKey(file, stamp, box, pdf?.page)+ if (converted.has(key)) {+ const png = converted.get(key) ?? null+ // A page made ahead is the one shown now.+ if (png && pdf && !pdf.probe) keep(lastConverted, pdf.row, { stamp, png }, PICTURES_KEPT)+ return pdf ? png : png ?? before+ }let run = converting.get(key)if (!run) {- // A new box while another box of this file is made: wait for that run- // (its refresh draws the row again, with the box of that time).+ // A new box or page while another of this file is made: wait for that+ // run (its refresh draws the row again, with the box of that time).if (before && [...converting.keys()].some(k => k.startsWith(`${file}@${stamp}@`))) return before- run = convertOnce($, ready, file, stamp, box, key).finally(() => converting.delete(key))- converting.set(key, run)+ run = runOf($, ready, file, stamp, box, pdf)// jobDone one tick later: a run that ends while this row still draws// must not be lost. A run that is waited for (the first PNG, no epoch// open) draws in this render.@@ -147,22 +170,45 @@ export async function convertedOf($: EngineInterface, ready: Env, file: string,return before ?? run}-// The last PNG made of `file` at its stat stamp in this load (any box); null-// when there is none.+// A run for a PDF's page: the page, the row it shows in (pdfRow: its last+// PNG shown is the row's), `probe` for the next page made ahead (it does+// not show), `wait` for a page not known to exist (no older PNG draws in+// its place: it is waited for).+type PdfRun = { page: number; row: string; probe?: true; wait?: boolean }++// The key of a PNG in `converted` and `converting`; a PDF's has its page.+const convertKey = (file: string, stamp: string, box: PixelBox, page?: number) =>+ `${file}@${stamp}@${box.width}x${box.height}${page ? `@${page}` : ''}`++// The run that makes a key's PNG: the one that runs now, else a new one.+function runOf($: EngineInterface, ready: Env, file: string, stamp: string, box: PixelBox, pdf?: PdfRun) {+ const key = convertKey(file, stamp, box, pdf?.page)+ let run = converting.get(key)+ if (!run) {+ run = convertOnce($, ready, file, stamp, box, key, pdf).finally(() => converting.delete(key))+ converting.set(key, run)+ }+ return run+}++// The last PNG shown of `file` (a PDF's row) at its stat stamp in this load+// (any box or page); null when there is none.function lastPngOf(file: string, stamp: string): string | null {const last = lastConverted.get(file)return last?.stamp === stamp ? last.png : null}-// Whether a PNG of `file` as it is now was made in this load (any box).-// `at`: as statOf.-async function hasPngOf($: EngineInterface, file: string, at?: StatAt): Promise<boolean> {+// Whether a PNG of `file` as it is now was made in this load (any box; a+// PDF's: shown in its row `row`). `at`: as statOf.+async function hasPngOf($: EngineInterface, file: string, at?: StatAt, row?: string): Promise<boolean> {const st = await statOf($, file, at)- return !!st && st.kind === 'file' && !!lastPngOf(file, `${st.mtimeMs}:${st.size}`)+ return !!st && st.kind === 'file' && !!lastPngOf(row ?? file, `${st.mtimeMs}:${st.size}`)}-async function convertOnce($: EngineInterface, ready: Env, file: string, stamp: string, box: PixelBox, key: string): Promise<string | null> {- const out = convertedPath(ready.cache, file, stamp, box)+async function convertOnce($: EngineInterface, ready: Env, file: string, stamp: string, box: PixelBox, key: string, pdf?: PdfRun): Promise<string | null> {+ const out = convertedPath(ready.cache, file, stamp, box, pdf?.page)+ // The Typst error of a run that failed (null: made).+ let error: string | null = null// Made before (an earlier load): the same file, stamp and box.const made = await fsStat($, out).catch(() => null)let png: string | null = out@@ -174,20 +220,24 @@ async function convertOnce($: EngineInterface, ready: Env, file: string, stamp:// Typst writes a part file, moved to image.png only once it is whole, so// a run that is killed or fails leaves no image.png for a later load.const part = `${dir}/image.part.png`- const { argv, env } = convertCall({ typst: ready.typst!, root: ready.root, cache: ready.cache, file, box, out: part })+ const { argv, env } = convertCall({ typst: ready.typst!, root: ready.root, cache: ready.cache, file, box, out: part, page: pdf?.page })const failed = (err: unknown) => ({ exitCode: 1, stdout: '', stderr: `did not run: ${String(err)}` })const ran = await processRun($, argv, { timeoutMs: COMPILE_TIMEOUT_MS, env }).catch(failed)const moved = ran.exitCode === 0 ? await processRun($, ['mv', '-f', part, out]).catch(failed) : nullif (ran.exitCode !== 0) {- await logDebug($, ready.cache, `convert ${file} failed:\n${ran.stderr}`)+ // A PDF's page that is not there is no failure: it tells the last page.+ if (!pdf || !isNoPageError(ran.stderr)) await logDebug($, ready.cache, `convert ${file} failed:\n${ran.stderr}`)+ error = ran.stderrpng = null} else if (moved?.exitCode !== 0) {await logDebug($, ready.cache, `convert ${file}: could not move ${part}:\n${moved?.stderr ?? ''}`)+ error = `error: could not move ${part}`png = null}}keep(converted, key, png, PICTURES_KEPT)- if (png) keep(lastConverted, file, { stamp, png }, PICTURES_KEPT)+ if (pdf) keep(pdfFacts, `${file}@${stamp}`, factsAfter(factsOf(file, stamp), pdf.page, error), PICTURES_KEPT)+ if (png && !pdf?.probe) keep(lastConverted, pdf?.row ?? file, { stamp, png }, PICTURES_KEPT)return png}@@ -206,14 +256,14 @@ export async function sentTextOf($: EngineInterface, file: string, at?: StatAt):}// What draws under a SendUserFile row, in the attachments' order: each-// image, and each Markdown file's pages (through the answers' pipeline, its-// relative images by its own folder). `markdown`: the env for the Markdown-// files (null: they stay out); `id`: the call's tool_use_id; `at`: as-// statOf. Images size from the Frame on screen; while an epoch is open, the-// PNG of a JPEG, WebP or SVG for the target is made at once (not waited for), so-// it is there when the epoch commits. With no PNG of that file yet (a-// resumed session) only the target's is made, and nothing draws for it-// until the commit.+// image, each PDF's page (pdfOf), and each Markdown file's pages (through+// the answers' pipeline, its relative images by its own folder).+// `markdown`: the env for the Markdown files (null: they stay out); `id`:+// the call's tool_use_id; `at`: as statOf. Images size from the Frame on+// screen; while an epoch is open, the PNG of a JPEG, WebP, SVG or PDF page+// for the target is made at once (not waited for), so it is there when the+// epoch commits. With no PNG of that file yet (a resumed session) only the+// target's is made, and nothing draws for it until the commit.export async function sentOf($: EngineInterface, e: RowInput, o: { ready: Env; markdown: Env | null; files: readonly SentFile[]; id: string; at?: StatAt },): Promise<Under[]> {@@ -236,6 +286,11 @@ export async function sentOf(else if (drawing.kind !== 'text') under.push({ drawing, id })continue}+ if (f.kind === 'pdf') {+ const u = await pdfOf($, e, o.ready, { file: full, row: pdfRow(o.id, f.path), box, next, at: o.at })+ if (u) under.push(u)+ continue+ }if (f.kind !== 'png' && next && (next.width !== box.width || next.height !== box.height)) {void convertedOf($, o.ready, full, next, o.at).catch(() => null)if (!(await hasPngOf($, full, o.at))) continue@@ -247,20 +302,197 @@ export async function sentOf(return under}+// ---- PDF pages ----------------------------------------------------------------++// A PDF's key in pdfPages: its row's tool_use_id and its path.+const pdfRow = (id: string, path: string) => `${id}\n${path}`++// The pages a SendUserFile row shows of its PDFs, for its memo.+export const pdfPagesOf = (id: string, files: readonly SentFile[]) =>+ files.filter(f => f.kind === 'pdf').map(f => pdfPages.get(pdfRow(id, f.path)) ?? 1).join(',')++// What is known of a PDF's pages at its stat stamp (pdfFacts).+const factsOf = (file: string, stamp: string): PdfFacts => pdfFacts.get(`${file}@${stamp}`) ?? NO_FACTS++// The page a row shows of a PDF at its stat stamp: the page stored, before+// a page known not to exist (stored so, for the next press).+function rowPage(row: string, f: PdfFacts): number {+ const stored = pdfPages.get(row) ?? 1+ const page = pageOf(stored, f.missing)+ if (page !== stored) keep(pdfPages, row, page, PICTURES_KEPT)+ return page+}++// A PDF's page under its row (`row`: its key in pdfPages; page 1 at first)+// with its control line, or a dim line with Typst's error (with the control+// line after page 1). A page not known to exist is waited for (it is+// mostly made ahead already): no older page draws with its number. The next+// page is made too (pdfFacts then tells whether › acts); on the first draw+// it is waited for, so a PDF of one page never draws the line. `next`: the+// target's box in an open epoch (as for an image). Null with no Typst, or+// for a file that is gone.+async function pdfOf(+ $: EngineInterface, e: RowInput, ready: Env, o: { file: string; row: string; box: PixelBox; next: PixelBox | null; at?: StatAt },+): Promise<Under | null> {+ const { file, row, box, at } = o+ const st = await statOf($, file, at)+ if (!ready.typst || !st || st.kind !== 'file') return null+ const stamp = `${st.mtimeMs}:${st.size}`+ const known = factsOf(file, stamp)+ const page = rowPage(row, known)+ const wait = known.made < page+ if (o.next && (o.next.width !== box.width || o.next.height !== box.height)) {+ void convertedOf($, ready, file, o.next, at, { page, row, wait }).catch(() => null)+ if (!(await hasPngOf($, file, at, row))) return null+ }+ const first = !(await hasPngOf($, file, at, row))+ const made = convertedOf($, ready, file, box, at, { page, row, wait }).catch(() => null)+ const isKnown = known.made > page || (known.missing > 0 && page + 1 >= known.missing)+ const ahead = isKnown ? null : convertedOf($, ready, file, box, at, { page: page + 1, row, probe: true }).catch(() => null)+ const png = await made+ if (first) await ahead+ const now = factsOf(file, stamp)+ // The file got shorter and the row's page is gone: its last page (the+ // count in Typst's hint), else page 1. One run more at most.+ if (!png && page > 1 && now.missing && page >= now.missing) {+ keep(pdfPages, row, lastKnownPage(now), PICTURES_KEPT)+ return pdfOf($, e, ready, o)+ }+ const controls = pageControls(page, now.missing)+ const line = controls ? { row, file, stamp, page, box, ...controls } : undefined+ if (!png) {+ const error = now.errors[page]+ if (!error) return null+ return page > 1 ? { note: `PDF: page ${page}: ${error}`, pdf: line } : { note: `PDF: ${error}` }+ }+ const picture = await shownOne($, e, ready, png, nameOf(file), at)+ return picture && line ? { ...picture, pdf: line } : picture+}++// Whether page `page` of a PDF exists: by what is known, else by a run that+// makes it (at the box of its picture, so the row draws it at once). A+// string: Typst's error for another failure; null when it is not known (no+// Typst, a file that is gone).+async function pageMade($: EngineInterface, ready: Env, file: string, row: string, page: number, box: PixelBox): Promise<boolean | string | null> {+ const st = await fsStat($, file).catch(() => null)+ if (!ready.typst || !st || st.kind !== 'file') return null+ const stamp = `${st.mtimeMs}:${st.size}`+ const known = factsOf(file, stamp)+ if (known.missing && page >= known.missing) return false+ if (!converted.has(convertKey(file, stamp, box, page))) await runOf($, ready, file, stamp, box, { page, row }).catch(() => null)+ const f = factsOf(file, stamp)+ if (f.missing && page >= f.missing) return false+ return f.made >= page ? true : (f.errors[page] ?? null)+}++// A press on ‹ or ›: the row's page `by` one, within the pages known at the+// stamp it drew with, and the row draws again.+function turnPage($: EngineInterface, line: PageLine, by: number) {+ const known = factsOf(line.file, line.stamp)+ const now = pageOf(pdfPages.get(line.row) ?? line.page, known.missing)+ const page = pageOf(now + by, known.missing)+ if (page === now) return+ keep(pdfPages, line.row, page, PICTURES_KEPT)+ refresh($)+}++// The page field: a pane that opens above the prompt (docked beside the+// transcript in fullscreen) and takes the keys, its Input focused. Esc+// closes it (closeOnEscape). The band above the prompt can not take the+// keys for a plugin (only the person's ctrl+x tab or click), so it is a+// pane.+const PAGE_PANE = 'iui-page'++// A press on the page number: the page field, with the page in it.+async function askPage($: EngineInterface, line: PageLine) {+ pageAsk.now = { row: line.row, file: line.file, box: line.box, value: String(line.page), note: '' }+ await uiOpen($, { id: PAGE_PANE, title: 'Page', focus: true, closeOnEscape: true, rows: 2, columns: 24 }).catch(() => undefined)+ // An open field (another row's) draws the new page.+ uiInvalidate($, 'ui.render')+}++// Enter in the page field: a page that exists shows in its row and the+// field closes; else the field stays open with a note. Only the last Enter+// in the field as it is now acts: a field opened again (another row) or a+// later Enter makes an earlier one's result go unused.+async function submitPage($: EngineInterface, text: string) {+ const ask = pageAsk.now+ if (!ask) return void uiClose($, { id: PAGE_PANE }).catch(() => undefined)+ const mine = { ...ask, value: text }+ pageAsk.now = mine+ const page = parsePage(text)+ const made = page && S.env ? await pageMade($, S.env, ask.file, ask.row, page, ask.box) : null+ if (pageAsk.now !== mine) return+ if (!page || made !== true) {+ const note = !page ? 'Type a page number' : made === false ? `No page ${page}` : `Page ${page}: ${made ?? 'Typst could not make it'}`+ pageAsk.now = { ...mine, note }+ uiInvalidate($, 'ui.render')+ return+ }+ keep(pdfPages, ask.row, page, PICTURES_KEPT)+ pageAsk.now = null+ await uiClose($, { id: PAGE_PANE }).catch(() => undefined)+ refresh($)+}++// The page field's tree: the page in an Input that has the focus, and its+// note under it.+export function drawPageField($: EngineInterface, e: RenderInput<'Pane', 'terminal'>) {+ const { Box, Text, Input } = uiResolve($, e)+ const ask = pageAsk.now+ if (!ask) return <Text dimColor>No PDF page to go to. Esc closes this.</Text>+ return (+ <Box flexDirection="column">+ <Input key="page" label="Page " value={ask.value} submitLabel="go" autoFocus onSubmit={text => void submitPage($, text)} />+ {ask.note ? <Text dimColor>{ask.note}</Text> : null}+ </Box>+ )+}++// The control line under a PDF's page, one row: ‹, the page number and ›,+// each a Button in the accent color, or dim and no Button where it does+// nothing (‹ on page 1, › on the last page). The number opens the page+// field. Centered under the picture when `columns` (its width) is given:+// a margin of half the room the line leaves (it is 6 cells and the digits).+function drawPageLine($: EngineInterface, e: RowInput, line: PageLine, keys: string, columns?: number) {+ const { Box, Text, Button } = uiResolve($, e)+ const arrow = (glyph: string, on: boolean, by: number, key: string) =>+ on ? (+ <Button key={`${keys}${key}`} plain onPress={() => turnPage($, line, by)}>+ <Text color="suggestion">{glyph}</Text>+ </Button>+ ) : (+ <Text dimColor>{glyph}</Text>+ )+ return (+ <Box height={1} overflow="hidden" marginLeft={columns ? Math.max(0, Math.floor((columns - 6 - String(line.page).length) / 2)) : 0}>+ {arrow('‹', line.back, -1, 'page-back')}+ <Text>{' '}</Text>+ <Button key={`${keys}page-number`} plain onPress={() => void askPage($, line)}>+ <Text color="suggestion">{String(line.page)}</Text>+ </Button>+ <Text>{' '}</Text>+ {arrow('›', line.forward, 1, 'page-forward')}+ </Box>+ )+}+// The space a picture takes in `frame` with the height setting `height`-// (as in shownOne), which a JPEG, WebP or SVG is made to fit. Over ssh it stays-// INLINE_MAX_SIDE pixels wide at most.+// (as in shownOne), which a JPEG, WebP, SVG or PDF page is made to fit. Over+// ssh it stays INLINE_MAX_SIDE pixels wide at most.const boxOf = (frame: Frame, inline: boolean, height: Height): PixelBox =>convertBox(pictureColumns(frame, inline), pictureRowsFor(frame.rows, height), frame.cell)// The rows underRow draws under the pages of `under[i]` besides its Typst// error line: its link rows, then all after it (a picture its rows, a-// Markdown file its pages at their drawn box (fitBox in `room`, as-// drawPages), a Typst error line and its link rows, a blank none).+// PDF's error line one, each with a PDF's control line; a Markdown file its+// pages at their drawn box (fitBox in `room`, as drawPages), a Typst error+// line and its link rows; a blank none).export function rowsAfter(under: readonly Under[], i: number, room: number): number {const own = under[i]return linkRows(own) + under.slice(i + 1).reduce((sum, u) => {- if ('source' in u) return sum + u.rows+ if ('note' in u) return sum + 1 + (u.pdf ? 1 : 0)+ if ('source' in u) return sum + u.rows + (u.pdf ? 1 : 0)if (u.drawing.kind !== 'pages') return sumconst { pages, note } = u.drawing.resultreturn sum + pages.reduce((n, p) => n + fitBox(p, room).rows, 0) + (note ? 1 : 0) + linkRows(u)@@ -272,12 +504,29 @@ const linkRows = (u: Under | undefined) => (u && 'drawing' in u && u.drawing.kin// The engine's row, then the pictures under it.export function underRow($: EngineInterface, e: RowInput, row: RenderElement, under: readonly Under[]) {- const { Box, Image } = uiResolve($, e)+ const { Box, Image, Text } = uiResolve($, e)return (<Box flexDirection="column">{row}<Box flexDirection="column" marginLeft={GUTTER}>{under.map((s, i) => {+ if ('note' in s && s.pdf) {+ return (+ <Box key={`pdf-${i}`} flexDirection="column">+ <Text dimColor wrap="truncate-end">{s.note}</Text>+ {drawPageLine($, e, s.pdf, `pdf${i}-`)}+ </Box>+ )+ }+ if ('note' in s) return <Text key={`note-${i}`} dimColor wrap="truncate-end">{s.note}</Text>+ if ('source' in s && s.pdf) {+ return (+ <Box key={`pdf-${i}`} flexDirection="column">+ <Image source={s.source} columns={s.columns} rows={s.rows} alt={s.alt} />+ {drawPageLine($, e, s.pdf, `pdf${i}-`, s.columns)}+ </Box>+ )+ }if ('source' in s) return <Image key={`picture-${i}`} source={s.source} columns={s.columns} rows={s.rows} alt={s.alt} />const { drawing } = sif (drawing.kind === 'blank') return <Box key={`blank-${i}`} />diff --git a/hooks/lib/settings.ts b/hooks/lib/settings.tsindex 6049782..c4397ca 100644--- a/hooks/lib/settings.ts+++ b/hooks/lib/settings.ts@@ -135,8 +135,9 @@ export const DESIGNS_KEPT_DAYS = 180// A Markdown file Claude sends (SendUserFile) draws when it is at most this// many bytes.export const SENT_TEXT_MAX_BYTES = 256 * 1024-// The PNG Typst makes of a JPEG, WebP or SVG fits the space of the picture, and-// each side is at most this many pixels (never made larger).+// The PNG Typst makes of a JPEG, WebP or SVG (never made larger), or of a+// PDF page, fits the space of the picture, and each side is at most this+// many pixels.export const CONVERT_MAX_SIDE = 4096// What Claude is told while the mod draws its answers (a system promptdiff --git a/hooks/lib/state.ts b/hooks/lib/state.tsindex 9497087..864bbbf 100644--- a/hooks/lib/state.ts+++ b/hooks/lib/state.ts@@ -11,6 +11,7 @@ import type { Drawn } from './copy'import type { GridMetrics } from './grid'import type { Checked } from './updates'import type { ClipWay } from './clipboard'+import type { PdfFacts, PixelBox } from './images'import { DEFAULT_HEIGHT, DEFAULT_SIZE, DEFAULT_WIDTH, type Height, type Width } from './settings'import { uiInvalidate } from './api'@@ -233,15 +234,25 @@ export const INLINE_KEPT = 64// PNG), and the pasted-images folder of each session once found.export const pictures = new Map<string, { stamp: string; size: { width: number; height: number } | null }>()export const pasteDirs = new Map<string, string>()-// SendUserFile: the PNG Typst made of each JPEG, WebP or SVG by its file, stat-// stamp and box (null: it failed), the ones Typst makes now (same keys), the-// last PNG made of each file (any box: it draws while a new box is made),-// and the text of each Markdown file by its stat stamp (null: it does not-// draw).+// SendUserFile: the PNG Typst made of each JPEG, WebP or SVG, or PDF page,+// by its file, stat stamp, box and page (null: it failed), the ones Typst+// makes now (same keys), the last PNG shown of each file (a PDF's by its+// row; any box or page: it draws while a new box is made), and the text of+// each Markdown file by its stat stamp (null: it does not draw).export const converted = new Map<string, string | null>()export const converting = new Map<string, Promise<string | null>>()export const lastConverted = new Map<string, { stamp: string; png: string }>()export const sentTexts = new Map<string, { stamp: string; text: string | null }>()+// SendUserFile PDFs: what is known of each file's pages (by `<file>@<stat+// stamp>`), and the page each row shows of each PDF (by+// `<tool_use_id>\n<path>`; page 1 when not set). In memory only.+export const pdfFacts = new Map<string, PdfFacts>()+export const pdfPages = new Map<string, number>()+// The page field (pictures.tsx): the row and PDF it is for, the box of its+// picture, the text it holds and its note (''); null while it is closed.+export const pageAsk = {+ now: null as { row: string; file: string; box: PixelBox; value: string; note: string } | null,+}// The link rows (draw.tsx): whether each absolute path is a file (at most// LINK_FILES_KEPT).export const linkFiles = new Map<string, boolean>()diff --git a/hooks/lib/typst.ts b/hooks/lib/typst.tsindex da8faf4..bf9a8b0 100644--- a/hooks/lib/typst.ts+++ b/hooks/lib/typst.ts@@ -46,7 +46,9 @@ export const fontArgs = (fonts?: string) => (fonts ? ['--ignore-system-fonts', '// The typst command that makes a PNG of a JPEG, WebP or SVG (render/convert.typ)// that fits `box` (in pixels), never larger than its own pixel size: at 72-// ppi, 1 pt is 1 pixel.+// ppi, 1 pt is 1 pixel. For a PDF, `page` is the page (it fits the box,+// larger too), and the errors are in the human format: only it has the+// hint with the page count of a page that does not exist.export function convertCall(o: {typst: stringroot: string@@ -54,16 +56,18 @@ export function convertCall(o: {file: stringbox: { width: number; height: number }out: string+ page?: number}): { argv: string[]; env: Record<string, string> } {const argv = [o.typst, 'compile','--root', '/','--format', 'png',- '--diagnostic-format', 'short',+ '--diagnostic-format', o.page ? 'human' : 'short','--ppi', '72','--input', `f=${o.file}`,'--input', `maxw=${o.box.width}`,'--input', `maxh=${o.box.height}`,+ ...(o.page ? ['--input', `page=${o.page}`] : []),`${o.root}/render/convert.typ`,o.out,]diff --git a/hooks/register.tsx b/hooks/register.tsxindex ef3c155..853e3ae 100644--- a/hooks/register.tsx+++ b/hooks/register.tsx@@ -42,7 +42,7 @@ import { setUp } from './lib/env'import { frameFor, noteView, stopWatch, watchFrame, watchState } from './lib/frame'import { roomColumns } from './lib/terminal'import { onScreenOf, pastedImagePath, pastedNumbers, sentFiles } from './lib/images'-import { pasteDir, rowsAfter, sentOf, shownOf, underRow, type Shown, type Under } from './lib/pictures'+import { drawPageField, pasteDir, pdfPagesOf, rowsAfter, sentOf, shownOf, underRow, type Shown, type Under } from './lib/pictures'import { checkUpdates, loadUpdates, updateLine, updateNotice, type UpdateState } from './lib/updates'import { clockNow, fsWrite, sessionSurfaces, storeSet, uiCopy, uiResolve, uiSelection, uiToast } from './lib/api'import {@@ -83,6 +83,7 @@ export {} from './lib/draw'export { nextJob } from './lib/stream'export * from './lib/images'+export { rowsAfter, type Under } from './lib/pictures'export * from './lib/copy'export { autoCopyText, CLIP_TOOLS, clipToolsOf, clipWayOf, FIND_SH, GTK_READ_PY, GTK_WATCH_PY, WL_WATCH_SH, X11_WATCH_SH, type ClipTool, type ClipWay } from './lib/clipboard'export {@@ -695,8 +696,9 @@ export const register: Register = on => {})// The files Claude sends with SendUserFile, under the result row that lists- // them: PNG, JPEG and WebP images, and Markdown files drawn as an answer is- // (they need Typst). Its ToolUse row draws no attachments, and the tool is+ // them: PNG, JPEG, WebP and SVG images, one page of each PDF (with a control+ // line to turn the pages), and Markdown files drawn as an answer is (all+ // but a PNG need Typst). Its ToolUse row draws no attachments, and the tool is// never in a ToolGroup, so only ToolResult is hooked and no picture draws// twice.on('ui.render', { component: 'ToolResult' }, async ($, e, next) => {@@ -709,7 +711,7 @@ export const register: Register = on => {const markdown = files.some(f => f.kind === 'markdown') && ready.env.typst ? ready.env : nullconst id = e.props.tool_use_idconst onScreen = onScreenOf(e.props.onScreen)- const k = { text: files.map(f => `${f.kind}:${f.path}`).join('\n'), extra: '', stamp: stampOf(ready, e.viewport), onScreen }+ const k = { text: files.map(f => `${f.kind}:${f.path}`).join('\n'), extra: pdfPagesOf(id, files), stamp: stampOf(ready, e.viewport), onScreen }// Its jobs: one per Markdown file (pagesOf's id `file:<id>:<path>`).const kept = memoOf(unders, id, k, requestId => requestId.startsWith(`file:${id}:`))// Each Markdown file's pages with the rows drawn after them (rowsAfter)@@ -751,6 +753,13 @@ export const register: Register = on => {}})+ // The page field of a PDF under a SendUserFile row (pictures.tsx askPage):+ // the pane PAGE_PANE, named as a literal so the validator reads it.+ on('ui.render', { component: 'Pane', requestId: 'iui-page' }, async ($, e, next) => {+ if (e.surface !== 'terminal') return next(e)+ return drawPageField($, e)+ })+// The images the user pasted (`[Image #N]`), under the prompt row. Only the// user's own prompts: a notification's or another agent's row stays as is.on('ui.render', { component: 'UserMessage' }, async ($, e, next) => {diff --git a/render/convert.typ b/render/convert.typindex a5354c2..bfe3ffe 100644--- a/render/convert.typ+++ b/render/convert.typ@@ -1,8 +1,11 @@-// Intelligent UI: makes a PNG of a JPEG, WebP or SVG (the engine's Image-// draws PNG only). Compiled at 72 ppi, where 1 pt is 1 pixel.+// Intelligent UI: makes a PNG of a JPEG, WebP or SVG, or of one page of a+// PDF (the engine's Image draws PNG only). Compiled at 72 ppi, where 1 pt+// is 1 pixel.//// Inputs: f = the image's absolute path (with --root /); maxw, maxh = the-// box in pixels the PNG must fit (0 or absent: no limit on that side).+// box in pixels the PNG must fit (0 or absent: no limit on that side);+// page = the page of a PDF (default 1). A page that does not exist fails+// the compile ("page N does not exist").//// Typst sizes an image by its own DPI (a 300 dpi JPEG is drawn at a quarter// of its pixels), so the pixel size is read from the file and set as the@@ -42,12 +45,25 @@}#let svg = lower(f).ends-with(".svg")+#let pdf = has-tag(0, "%PDF-") or lower(f).ends-with(".pdf")#let size = if has-tag(0, "RIFF") and has-tag(8, "WEBP") { webp-size() } else if at(0) == 0xff and at(1) == 0xd8 { jpeg-size() }+// A PDF page is vector: its size in pt is its size in pixels, and it fits+// the box, the aspect kept (it can be made larger).+#context if pdf {+ let page = int(sys.inputs.at("page", default: "1"))+ let natural = measure(image(data, format: "pdf", page: page))+ let (w, h) = (natural.width / 1pt, natural.height / 1pt)+ let side(key) = int(sys.inputs.at(key, default: "0"))+ let (maxw, maxh) = (side("maxw"), side("maxh"))+ let scale = if maxw > 0 and maxh > 0 { calc.min(maxw / w, maxh / h) } else if maxw > 0 { maxw / w } else if maxh > 0 { maxh / h } else { 1 }+ image(data, format: "pdf", page: page, width: w * scale * 1pt)+}+// The sides as drawn: the pixel size, swapped when Typst turns the image by// its EXIF orientation; else Typst's own size. Then it fits the box, the// aspect kept; an image is never made larger.-#context {+#context if not pdf {let natural = measure(image(data))let natural = if svg { (width: natural.width / 0.75, height: natural.height / 0.75) } else { natural }let (w, h) = if size == none or size.at(0) == 0 or size.at(1) == 0 { (natural.width / 1pt, natural.height / 1pt) } else { size }diff --git a/tests/images.test.ts b/tests/images.test.tsindex 08cd278..35aff94 100644--- a/tests/images.test.ts+++ b/tests/images.test.ts@@ -1,8 +1,9 @@import { expect, mock, test } from 'claude-code/testing'import {- claudeTmpOf, convertBox, convertCall, convertedPath, DEFAULT_CELL, folderOf, imageKindOf, isMarkdownPath, pasteDirOf, pastedImagePath, pastedNumbers,- COMMIT_MIN_MS, DEFAULT_HEIGHT, parseCommand, RESIZE_QUIET_MS, PICTURE_MAX_ROWS, PICTURE_ROOM_ROWS, pictureCells, pictureRowsFor, projectSlug, renderKey, sentFiles, sentImages,+ 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, parseCommand, RESIZE_QUIET_MS, PICTURE_MAX_ROWS, PICTURE_ROOM_ROWS, pictureCells,+ pictureRowsFor, projectSlug, renderKey, rowsAfter, sentFiles, sentImages, shortError, type Under,} from '../hooks/register'// ---- Pure helpers -----------------------------------------------------------@@ -52,7 +53,7 @@ test('the height command: half, full, 6 to 200 rows, or nothing to show it', ()expect(parseCommand('height 12 rows')).toEqual({ kind: 'bad' })})-test('only PNG, JPEG, WebP and SVG image attachments are drawn', () => {+test('only PNG, JPEG, WebP, SVG and PDF attachments are drawn', () => {expect(sentImages({attachments: [{ path: '/t/a.png', size: 1, isImage: true, media_type: 'image/png' },@@ -68,7 +69,7 @@ test('only PNG, JPEG, WebP and SVG image attachments are drawn', () => {{ path: '/t/i.SVG', size: 1, isImage: false },{ path: '/t/j.svg', size: 1, isImage: false, media_type: 'text/plain' },],- })).toEqual(['/t/a.png', '/t/b.png', '/t/c.jpg', '/t/e.webp', '/t/g.svg', '/t/h.svg', '/t/i.SVG'])+ })).toEqual(['/t/a.png', '/t/b.png', '/t/c.jpg', '/t/d.pdf', '/t/e.webp', '/t/g.svg', '/t/h.svg', '/t/i.SVG'])expect(sentImages(undefined)).toEqual([])expect(sentImages('error text')).toEqual([])expect(sentImages({ attachments: 'x' })).toEqual([])@@ -116,6 +117,34 @@ test('a Markdown file: .md or .markdown, not an image; all files in their order,expect(sentFiles(null)).toEqual([])})+test('a PDF: by its media type application/pdf, else by its .pdf name; not Markdown; in the attachments order', () => {+ expect(isPdfPath('/t/a.pdf')).toBe(true)+ expect(isPdfPath('/t/A.PDF')).toBe(true)+ expect(isPdfPath('/t/a.pdf.md')).toBe(false)+ expect(isPdfPath('/t/pdf')).toBe(false)+ expect(sentFiles({+ attachments: [+ { path: '/t/notes.md', size: 1, isImage: false },+ // As Claude Code sends a PDF: not an image, its media type.+ { path: '/t/a.pdf', size: 1, isImage: false, media_type: 'application/pdf' },+ { path: '/t/b.png', size: 1, isImage: true },+ { path: '/t/c', size: 1, isImage: false, media_type: ' Application/PDF ' },+ { path: '/t/d.PDF', size: 1, isImage: false },+ // The media type wins over the name.+ { path: '/t/e.pdf', size: 1, isImage: false, media_type: 'text/plain' },+ { path: '/t/f.md', size: 1, isImage: false, media_type: 'application/pdf' },+ { path: '/t/a.pdf', size: 1, isImage: false, media_type: 'application/pdf' },+ ],+ })).toEqual([+ { path: '/t/notes.md', kind: 'markdown' },+ { path: '/t/a.pdf', kind: 'pdf' },+ { path: '/t/b.png', kind: 'png' },+ { path: '/t/c', kind: 'pdf' },+ { path: '/t/d.PDF', kind: 'pdf' },+ { path: '/t/f.md', kind: 'pdf' },+ ])+})+test('the folder of a file, for the relative images of a Markdown file', () => {expect(folderOf('/t/docs/notes.md')).toBe('/t/docs')expect(folderOf('/notes.md')).toBe('/')@@ -142,6 +171,15 @@ test('a converted PNG is named by the file, its stat stamp and the box, in a keyexpect(convertedPath('/c', '/t/a.jpg', '1:1000', { width: 1568, height: 768 })).not.toBe(one)})+test("each page of a PDF has a PNG of its own; with no page the name is as before", () => {+ const one = convertedPath('/c', '/t/a.pdf', '1:1000', BOX, 1)+ expect(one).toMatch(/^\/c\/[0-9a-f]{16}\/image\.png$/)+ expect(convertedPath('/c', '/t/a.pdf', '1:1000', BOX, 1)).toBe(one)+ expect(convertedPath('/c', '/t/a.pdf', '1:1000', BOX, 2)).not.toBe(one)+ expect(convertedPath('/c', '/t/a.pdf', '1:1000', BOX)).not.toBe(one)+ expect(convertedPath('/c', '/t/a.jpg', '1:1000', BOX, undefined)).toBe(convertedPath('/c', '/t/a.jpg', '1:1000', BOX))+})+test('the conversion call: render/convert.typ at 72 ppi, the file and the box as inputs, no network', () => {const { argv, env } = convertCall({ typst: '/usr/bin/typst', root: '/r', cache: '/c', file: '/t/a b.webp', box: BOX, out: '/c/k/image.png' })expect(argv).toEqual([@@ -152,6 +190,91 @@ test('the conversion call: render/convert.typ at 72 ppi, the file and the box asexpect(env.HTTPS_PROXY).toBe('http://127.0.0.1:9')})+test('the conversion call of a PDF page: the page as an input, the errors in the human format (its hint has the page count)', () => {+ const { argv } = convertCall({ typst: '/usr/bin/typst', root: '/r', cache: '/c', file: '/t/a.pdf', box: BOX, out: '/c/k/image.png', page: 3 })+ expect(argv.slice(-6)).toEqual(['--input', 'maxh=640', '--input', 'page=3', '/r/render/convert.typ', '/c/k/image.png'])+ expect(argv.slice(4, 8)).toEqual(['--format', 'png', '--diagnostic-format', 'human'])+})++test("Typst's error for a page that is not there; another error, short", () => {+ const typ = '../../r/render/convert.typ:55:30'+ expect(isNoPageError(`${typ}: error: failed to load PDF (page 4 does not exist)\n`)).toBe(true)+ expect(isNoPageError('error: failed to load PDF (page 99 does not exist in doc.pdf)')).toBe(true)+ expect(isNoPageError(`${typ}: error: failed to load PDF (the PDF could not be loaded)`)).toBe(false)+ expect(isNoPageError('')).toBe(false)+ expect(shortError(`${typ}: error: failed to load PDF (the PDF could not be loaded)\n`)).toBe('the PDF could not be loaded')+ expect(shortError(`warning: x\n${typ}: error: file is encrypted\n hint: y`)).toBe('file is encrypted')+ expect(shortError('did not run: timeout')).toBe('did not run: timeout')+ expect(shortError('')).toBe('Typst could not read it')+})++// Typst's human format for a page that is not there, with its hint.+const NO_PAGE = (page: number, pages: number) =>+ `error: failed to load PDF (page ${page} does not exist)\n ┌─ render/convert.typ:55:30\n │\n = hint: the document only has ${pages} page${pages === 1 ? '' : 's'}\n`++test('what is known of the pages of a PDF: the highest page made, the first page that is not there, the count, the errors', () => {+ const made = factsAfter(NO_FACTS, 3, null)+ expect(made).toEqual({ made: 3, missing: 0, pages: 0, errors: {} })+ expect(factsAfter(made, 2, null).made).toBe(3)+ // No hint (the short format): only that page and the pages after it are gone.+ const gone = factsAfter(made, 9, 'error: failed to load PDF (page 9 does not exist)')+ expect(gone).toEqual({ made: 3, missing: 9, pages: 0, errors: {} })+ expect(factsAfter(gone, 12, 'error: failed to load PDF (page 12 does not exist)').missing).toBe(9)+ expect(factsAfter(gone, 4, 'error: failed to load PDF (page 4 does not exist)').missing).toBe(4)+ // The hint gives the count: the last page at once.+ expect(pageCountOf(NO_PAGE(300, 3))).toBe(3)+ expect(pageCountOf(NO_PAGE(2, 1))).toBe(1)+ expect(pageCountOf('error: failed to load PDF (page 2 does not exist)')).toBe(0)+ expect(factsAfter(made, 300, NO_PAGE(300, 3))).toEqual({ made: 3, missing: 4, pages: 3, errors: {} })+ // Another error is kept for its page, until that page is made.+ const bad = factsAfter(made, 4, 'error: failed to load PDF (the PDF could not be loaded)')+ expect(bad.errors).toEqual({ 4: 'the PDF could not be loaded' })+ expect(bad.missing).toBe(0)+ expect(factsAfter(bad, 5, null).errors).toEqual({ 4: 'the PDF could not be loaded' })+ expect(factsAfter(bad, 4, null).errors).toEqual({})+})++test('the last page known for a row whose page is gone: the count, else the page before the first missing one when it was made, else 1', () => {+ expect(lastKnownPage({ ...NO_FACTS, pages: 3, missing: 4 })).toBe(3)+ expect(lastKnownPage({ ...NO_FACTS, made: 5, missing: 6 })).toBe(5)+ expect(lastKnownPage({ ...NO_FACTS, made: 0, missing: 300 })).toBe(1)+ expect(lastKnownPage({ ...NO_FACTS, made: 2, missing: 300 })).toBe(1)+})++test('the page shown and its control line: ‹ dim on page 1, › dim on the last page, no line for one page', () => {+ expect(pageOf(1, 0)).toBe(1)+ expect(pageOf(0, 0)).toBe(1)+ expect(pageOf(7, 0)).toBe(7)+ expect(pageOf(7, 5)).toBe(4)+ expect(pageOf(3, 2)).toBe(1)+ // The last page not known: › acts.+ expect(pageControls(1, 0)).toEqual({ back: false, forward: true })+ expect(pageControls(4, 0)).toEqual({ back: true, forward: true })+ // Page 3 of 3 (page 4 is not there).+ expect(pageControls(3, 4)).toEqual({ back: true, forward: false })+ expect(pageControls(2, 4)).toEqual({ back: true, forward: true })+ expect(pageControls(1, 4)).toEqual({ back: false, forward: true })+ // One page: no line.+ expect(pageControls(1, 2)).toBe(null)+})++test('a page number typed: a whole number from 1, spaces around it allowed', () => {+ expect(parsePage('3')).toBe(3)+ expect(parsePage(' 12 \n')).toBe(12)+ expect(parsePage('007')).toBe(7)+ for (const bad of ['', ' ', '0', '-1', '1.5', '2e3', 'x', '3 4', '+3', '99999999999999999999']) expect(parsePage(bad)).toBe(null)+})++test('a PDF page counts its control line, and an error line its row, in the rows after a drawing', () => {+ const picture = { source: { file: '/c/a.png', format: 'png' as const }, columns: 40, rows: 10, alt: 'a.png' }+ const line = { row: 'tu-1\n/t/a.pdf', file: '/t/a.pdf', stamp: '1:1000', page: 2, back: true, forward: true, box: BOX }+ const under: Under[] = [+ picture, { ...picture, pdf: line }, { note: 'PDF: the PDF could not be loaded' }, { note: 'PDF: page 2: boom', pdf: line }, picture,+ ]+ expect(rowsAfter(under, 0, 98)).toBe(10 + 1 + 1 + 2 + 10)+ expect(rowsAfter(under, 1, 98)).toBe(1 + 2 + 10)+})+test('a Markdown file folder is part of the key; with none, the key is as before', () => {const o = {textHash: 'h', columns: 100, cell: DEFAULT_CELL, size: 100, mode: 'dark' as const, termFont: '', columnPt: 6,@@ -199,7 +322,9 @@ const TALL = '89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 02 80 00 00// mtimes (1 when not set). `typst`: Typst is found; it makes a PNG of a JPEG// or WebP (unless `failConvert`, or from run number `failConvertFrom`; `mv`// moves it, unless `failMove`), and-// compiles Markdown to one page.+// compiles Markdown to one page. `pdfs`: the PDFs by path, their page+// count (a run for a page past it fails as Typst's does, with the hint+// that gives the count, unless `noHint`).// `holdConvert`: a conversion ends only once its file had that many stats// (other rows reached it while it runs). `holdRun`: conversion number `at`// (from 1) ends only when `until` settles. `holdCompile`: a Markdown compile@@ -220,6 +345,8 @@ function world(on: any, o: {holdConvert?: numberholdRun?: { at: number; until: Promise<void> }holdCompile?: Promise<void>+ pdfs?: Record<string, number>+ noHint?: boolean} = {}) {// 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.@@ -297,6 +424,11 @@ function world(on: any, o: {if ((stats.get(file) ?? 0) < (o.holdConvert ?? 0)) await new Promise<void>(done => waits.push({ path: file, done }))if (o.holdRun?.at === converts.length) await o.holdRun.untilif (o.failConvert || converts.length >= (o.failConvertFrom ?? Infinity)) return ok('', 1)+ const page = Number(argv.find(a => a.startsWith('page='))?.slice(5) ?? 1)+ if (o.pdfs && page > (o.pdfs[file] ?? Infinity)) {+ const stderr = o.noHint ? `error: failed to load PDF (page ${page} does not exist)\n` : NO_PAGE(page, o.pdfs[file]!)+ return { value: { exitCode: 1, stdout: '', stderr, isStdoutTruncated: false, isStderrTruncated: false } }+ }files[argv.at(-1)!] = HEADreturn ok('')}@@ -428,6 +560,320 @@ test('a JPEG, a WebP and an SVG Claude sends are made PNGs by Typst once, and drexpect(heads).not.toContain('/t/photo.jpg')})+// ---- PDFs ---------------------------------------------------------------------++// PDFs as Claude Code sends them: not images, the media type application/pdf.+const pdfs = (...paths: string[]) => ({ attachments: paths.map(path => ({ path, size: 1000, isImage: false, media_type: 'application/pdf' })) })+const all = (tree: any, type: string): any[] =>+ tree && typeof tree === 'object' ? [...(tree.type === type ? [tree] : []), ...(tree.children ?? []).flatMap((c: any) => all(c, type))] : []+const textOf = (tree: any): string => (typeof tree === 'string' ? tree : (tree?.children ?? []).map(textOf).join(''))+const pageArgs = (converts: string[][]) => converts.map(argv => `${argv.find(a => a.startsWith('f='))!.slice(2)}#${argv.find(a => a.startsWith('page='))?.slice(5)}`)+// The control line under the picture `i` of a SendUserFile row.+const lineOf = (tree: any, i = 0) => tree.children[1].children[i].children[1]+// A refresh (here a setting): the rows draw anew and see a new stat.+const refreshed = async ($: any, clock: any) => {+ await $.command.run({ command: 'iui', args: 'size 100' } as any)+ await clock.settle()+}+const PANE = {+ plugin: 'cc-intelligent-ui', surface: 'terminal' as const, component: 'Pane' as const, requestId: 'iui-page',+ props: { title: 'Page', isFocused: true, bodyColumns: 24, placement: 'inline' } as any, viewport: { columns: 100, rows: 40 },+}++test('a PDF Claude sends draws its first page with a control line; the next page is made too', async ($, on) => {+ const { converts } = world(on, { typst: true, pdfs: { '/t/doc.pdf': 3 }, files: { '/t/doc.pdf': '' } })+ await ready($)+ const ui = await $.ui.mount(sent(pdfs('/t/doc.pdf')))+ const tree: any = await ui.drawn()+ expect(tree.children[0]).toMatchObject(ENGINE)+ const [image] = images(tree)+ expect(image.props.source.file).toBe(convertedPath('/c', '/t/doc.pdf', '1:1000', BOX, 1))+ expect(image.props.alt).toBe('doc.pdf')+ expect(pageArgs(converts)).toEqual(['/t/doc.pdf#1', '/t/doc.pdf#2'])+ expect(converts[0]).toContain('maxw=1568')+ // One row: ‹ dim (page 1), the page number and › as Buttons; no page count.+ const line = lineOf(tree)+ expect(line.props).toMatchObject({ height: 1 })+ expect(textOf(line)).toBe('‹ 1 ›')+ expect(line.children[0]).toMatchObject({ type: 'Text', props: { dimColor: true } })+ expect(all(line, 'Button').map(b => b.props.key)).toEqual(['pdf0-page-number', 'pdf0-page-forward'])+ // A redraw makes nothing again.+ await ui.redraw(sent(pdfs('/t/doc.pdf')).props)+ expect(converts.length).toBe(2)+})++test('› and ‹ turn the pages: the page made ahead draws at once; › is dim on the last page', async ($, on) => {+ const { clock, converts } = world(on, { typst: true, pdfs: { '/t/doc.pdf': 3 }, files: { '/t/doc.pdf': '' } })+ await ready($)+ const ui = await $.ui.mount(sent(pdfs('/t/doc.pdf')))+ await ui.press({ key: 'pdf0-page-forward' })+ let tree: any = await ui.drawn()+ expect(images(tree)[0].props.source.file).toBe(convertedPath('/c', '/t/doc.pdf', '1:1000', BOX, 2))+ expect(textOf(lineOf(tree))).toBe('‹ 2 ›')+ expect(all(lineOf(tree), 'Button').map(b => b.props.key)).toEqual(['pdf0-page-back', 'pdf0-page-number', 'pdf0-page-forward'])+ await clock.settle()+ expect(pageArgs(converts)).toEqual(['/t/doc.pdf#1', '/t/doc.pdf#2', '/t/doc.pdf#3'])+ await ui.press({ key: 'pdf0-page-forward' })+ await clock.settle()+ tree = await ui.drawn()+ expect(images(tree)[0].props.source.file).toBe(convertedPath('/c', '/t/doc.pdf', '1:1000', BOX, 3))+ // Page 4 is not there: page 3 is the last, › is dim.+ expect(pageArgs(converts)).toEqual(['/t/doc.pdf#1', '/t/doc.pdf#2', '/t/doc.pdf#3', '/t/doc.pdf#4'])+ expect(textOf(lineOf(tree))).toBe('‹ 3 ›')+ expect(lineOf(tree).children.at(-1)).toMatchObject({ type: 'Text', props: { dimColor: true } })+ expect(all(lineOf(tree), 'Button').map(b => b.props.key)).toEqual(['pdf0-page-back', 'pdf0-page-number'])+ // Back to page 2: made before, no run.+ await ui.press({ key: 'pdf0-page-back' })+ await clock.settle()+ tree = await ui.drawn()+ expect(images(tree)[0].props.source.file).toBe(convertedPath('/c', '/t/doc.pdf', '1:1000', BOX, 2))+ expect(converts.length).toBe(4)+})++test('a PDF of one page draws its page with no control line', async ($, on) => {+ const { converts } = world(on, { typst: true, pdfs: { '/t/one.pdf': 1 }, files: { '/t/one.pdf': '' } })+ await ready($)+ const ui = await $.ui.mount(sent(pdfs('/t/one.pdf')))+ const tree: any = await ui.drawn()+ expect(images(tree).map(i => i.props.source.file)).toEqual([convertedPath('/c', '/t/one.pdf', '1:1000', BOX, 1)])+ expect(all(tree, 'Button')).toEqual([])+ expect(textOf(tree.children[1])).toBe('')+ expect(pageArgs(converts)).toEqual(['/t/one.pdf#1', '/t/one.pdf#2'])+})++test('a PDF that Typst can not read: the row and one dim line with the error', async ($, on) => {+ world(on, { typst: true, failConvert: true, files: { '/t/locked.pdf': '' } })+ await ready($)+ const ui = await $.ui.mount(sent(pdfs('/t/locked.pdf')))+ const tree: any = await ui.drawn()+ expect(tree.children[0]).toMatchObject(ENGINE)+ expect(images(tree)).toEqual([])+ const [note] = tree.children[1].children+ expect(note).toMatchObject({ type: 'Text', props: { dimColor: true, wrap: 'truncate-end' } })+ expect(textOf(note)).toBe('PDF: boom')+})++test('two PDFs in one result: each its own page and control line', async ($, on) => {+ const { clock } = world(on, { typst: true, pdfs: { '/t/a.pdf': 3, '/t/b.pdf': 3 }, files: { '/t/a.pdf': '', '/t/b.pdf': '' } })+ await ready($)+ const ui = await $.ui.mount(sent(pdfs('/t/a.pdf', '/t/b.pdf')))+ await ui.press({ key: 'pdf1-page-forward' })+ await clock.settle()+ const tree: any = await ui.drawn()+ expect(images(tree).map(i => i.props.source.file)).toEqual([+ convertedPath('/c', '/t/a.pdf', '1:1000', BOX, 1),+ convertedPath('/c', '/t/b.pdf', '1:1000', BOX, 2),+ ])+ expect([textOf(lineOf(tree, 0)), textOf(lineOf(tree, 1))]).toEqual(['‹ 1 ›', '‹ 2 ›'])+ // Another row of the same PDF keeps its own page.+ const other = await $.ui.mount(sent(pdfs('/t/b.pdf'), false, 'tu-2'))+ expect(textOf(lineOf(await other.drawn()))).toBe('‹ 1 ›')+})++test('the page number opens the page field: a page that is not there keeps it open with a note; a page goes there', async ($, on) => {+ const { clock, converts } = world(on, { typst: true, pdfs: { '/t/doc.pdf': 5 }, files: { '/t/doc.pdf': '' } })+ const opens: any[] = []+ const closes: any[] = []+ on('ui.open', async ($: any, e: any) => (opens.push(e), { value: { isPlaced: true } }))+ on('ui.close', async ($: any, e: any) => (closes.push(e), { value: undefined }))+ await ready($)+ const ui = await $.ui.mount(sent(pdfs('/t/doc.pdf')))+ await ui.press({ key: 'pdf0-page-number' })+ expect(opens).toMatchObject([{ id: 'iui-page', focus: true, closeOnEscape: true }])+ const field = await $.ui.mount(PANE)+ const input = () => field.drawn().then((tree: any) => all(tree, 'Input')[0])+ expect((await input()).props).toMatchObject({ key: 'page', value: '1', autoFocus: true })+ await field.input({ key: 'page', text: '9' })+ expect(textOf(await field.drawn())).toContain('No page 9')+ expect((await input()).props.value).toBe('9')+ expect(closes).toEqual([])+ // Page 12 is past page 9: known, no run.+ const runs = converts.length+ await field.input({ key: 'page', text: '12' })+ expect(textOf(await field.drawn())).toContain('No page 12')+ expect(converts.length).toBe(runs)+ await field.input({ key: 'page', text: 'two' })+ expect(textOf(await field.drawn())).toContain('Type a page number')+ await field.input({ key: 'page', text: ' 4 ' })+ expect(closes).toMatchObject([{ id: 'iui-page' }])+ await clock.settle()+ const tree: any = await ui.drawn()+ expect(images(tree)[0].props.source.file).toBe(convertedPath('/c', '/t/doc.pdf', '1:1000', BOX, 4))+ expect(textOf(lineOf(tree))).toBe('‹ 4 ›')+ expect(pageArgs(converts).filter(p => p === '/t/doc.pdf#4')).toEqual(['/t/doc.pdf#4'])+})++test('a file that got shorter under a row on a high page: one failed run, then its last page (the count in the hint)', async ($, on) => {+ const counts: Record<string, number> = { '/t/doc.pdf': 300 }+ const { clock, converts, mtimes } = world(on, { typst: true, pdfs: counts, files: { '/t/doc.pdf': '' } })+ on('ui.open', async () => ({ value: { isPlaced: true } }))+ on('ui.close', async () => ({ value: undefined }))+ await ready($)+ const ui = await $.ui.mount(sent(pdfs('/t/doc.pdf')))+ await ui.press({ key: 'pdf0-page-number' })+ const field = await $.ui.mount(PANE)+ await field.input({ key: 'page', text: '299' })+ await clock.settle()+ expect(textOf(lineOf(await ui.drawn()))).toBe('‹ 299 ›')+ counts['/t/doc.pdf'] = 3+ mtimes['/t/doc.pdf'] = 2+ const n = converts.length+ await refreshed($, clock)+ const tree: any = await ui.drawn()+ // Page 299 and the look-ahead for page 300 run side by side; then page 3.+ expect(pageArgs(converts.slice(n))).toEqual(['/t/doc.pdf#299', '/t/doc.pdf#300', '/t/doc.pdf#3'])+ expect(images(tree)[0].props.source.file).toBe(convertedPath('/c', '/t/doc.pdf', '2:1000', BOX, 3))+ expect(textOf(lineOf(tree))).toBe('‹ 3 ›')+ expect(all(lineOf(tree), 'Button').map(b => b.props.key)).toEqual(['pdf0-page-back', 'pdf0-page-number'])+ // The page is stored: ‹ goes to page 2.+ await ui.press({ key: 'pdf0-page-back' })+ await clock.settle()+ expect(textOf(lineOf(await ui.drawn()))).toBe('‹ 2 ›')+})++test('a file that got shorter, with no count in the error: page 1 at once', async ($, on) => {+ const counts: Record<string, number> = { '/t/doc.pdf': 300 }+ const { clock, converts, mtimes } = world(on, { typst: true, noHint: true, pdfs: counts, files: { '/t/doc.pdf': '' } })+ on('ui.open', async () => ({ value: { isPlaced: true } }))+ on('ui.close', async () => ({ value: undefined }))+ await ready($)+ const ui = await $.ui.mount(sent(pdfs('/t/doc.pdf')))+ await ui.press({ key: 'pdf0-page-number' })+ await (await $.ui.mount(PANE)).input({ key: 'page', text: '299' })+ await clock.settle()+ counts['/t/doc.pdf'] = 3+ mtimes['/t/doc.pdf'] = 2+ const n = converts.length+ await refreshed($, clock)+ const tree: any = await ui.drawn()+ expect(pageArgs(converts.slice(n))).toEqual(['/t/doc.pdf#299', '/t/doc.pdf#300', '/t/doc.pdf#1', '/t/doc.pdf#2'])+ expect(textOf(lineOf(tree))).toBe('‹ 1 ›')+})++test('› while the next page is still made: the row waits for that page; past the last page it stays on the last page', async ($, on) => {+ let release = () => {}+ const until = new Promise<void>(done => (release = done))+ // Run 4 is the look-ahead for page 4, made while page 3 shows.+ const { clock, converts } = world(on, { typst: true, pdfs: { '/t/doc.pdf': 3 }, files: { '/t/doc.pdf': '' }, holdRun: { at: 4, until } })+ await ready($)+ const ui = await $.ui.mount(sent(pdfs('/t/doc.pdf')))+ await ui.press({ key: 'pdf0-page-forward' })+ await ui.press({ key: 'pdf0-page-forward' })+ let tree: any = await ui.drawn()+ expect(textOf(lineOf(tree))).toBe('‹ 3 ›')+ expect(pageArgs(converts)).toEqual(['/t/doc.pdf#1', '/t/doc.pdf#2', '/t/doc.pdf#3', '/t/doc.pdf#4'])+ // Page 4 is not known yet: › still acts.+ const press = ui.press({ key: 'pdf0-page-forward' })+ release()+ await press+ await clock.settle()+ tree = await ui.drawn()+ // The row waited for page 4: it is not there, so page 3 (never page 3's picture with the number 4).+ expect(images(tree)[0].props.source.file).toBe(convertedPath('/c', '/t/doc.pdf', '1:1000', BOX, 3))+ expect(textOf(lineOf(tree))).toBe('‹ 3 ›')+ expect(all(lineOf(tree), 'Button').map(b => b.props.key)).toEqual(['pdf0-page-back', 'pdf0-page-number'])+ expect(converts.length).toBe(4)+ // One ‹ goes to page 2.+ await ui.press({ key: 'pdf0-page-back' })+ await clock.settle()+ tree = await ui.drawn()+ expect(textOf(lineOf(tree))).toBe('‹ 2 ›')+ expect(images(tree)[0].props.source.file).toBe(convertedPath('/c', '/t/doc.pdf', '1:1000', BOX, 2))+})++test('a page that fails for another reason: its error line and the control line, never the page before; the field says so too', async ($, on) => {+ // From run 3 (the look-ahead for page 3) Typst fails.+ const { clock, converts } = world(on, { typst: true, pdfs: { '/t/doc.pdf': 5 }, files: { '/t/doc.pdf': '' }, failConvertFrom: 3 })+ const closes: any[] = []+ on('ui.open', async () => ({ value: { isPlaced: true } }))+ on('ui.close', async ($: any, e: any) => (closes.push(e), { value: undefined }))+ await ready($)+ const ui = await $.ui.mount(sent(pdfs('/t/doc.pdf')))+ await ui.press({ key: 'pdf0-page-forward' })+ await clock.settle()+ await ui.press({ key: 'pdf0-page-forward' })+ await clock.settle()+ let tree: any = await ui.drawn()+ expect(images(tree)).toEqual([])+ const [box] = tree.children[1].children+ expect(textOf(box.children[0])).toBe('PDF: page 3: boom')+ expect(textOf(box.children[1])).toBe('‹ 3 ›')+ // The failed page is not run again.+ expect(pageArgs(converts).filter(p => p === '/t/doc.pdf#3')).toEqual(['/t/doc.pdf#3'])+ await ui.press({ key: 'pdf0-page-back' })+ await clock.settle()+ tree = await ui.drawn()+ expect(images(tree)[0].props.source.file).toBe(convertedPath('/c', '/t/doc.pdf', '1:1000', BOX, 2))+ // In the field: page 3 keeps it open, with the error.+ await ui.press({ key: 'pdf0-page-number' })+ const field = await $.ui.mount(PANE)+ await field.input({ key: 'page', text: '3' })+ expect(textOf(await field.drawn())).toContain('Page 3: boom')+ expect(closes).toEqual([])+})++test('the field opened from row A, then from row B while A\'s Enter runs: A\'s result is not used', async ($, on) => {+ let release = () => {}+ const until = new Promise<void>(done => (release = done))+ // Runs 1-4 draw the two rows; run 5 is A's page 7.+ const { clock, converts } = world(on, {+ typst: true, pdfs: { '/t/a.pdf': 9, '/t/b.pdf': 9 }, files: { '/t/a.pdf': '', '/t/b.pdf': '' }, holdRun: { at: 5, until },+ })+ const closes: any[] = []+ on('ui.open', async () => ({ value: { isPlaced: true } }))+ on('ui.close', async ($: any, e: any) => (closes.push(e), { value: undefined }))+ await ready($)+ const a = await $.ui.mount(sent(pdfs('/t/a.pdf'), false, 'tu-a'))+ const b = await $.ui.mount(sent(pdfs('/t/b.pdf'), false, 'tu-b'))+ expect(converts.length).toBe(4)+ const field = await $.ui.mount(PANE)+ await a.press({ key: 'pdf0-page-number' })+ const enter = field.input({ key: 'page', text: '7' })+ while (converts.length < 5) await clock.settle()+ await b.press({ key: 'pdf0-page-number' })+ release()+ await enter+ await clock.settle()+ // The field is B's, still open, with B's page and no note.+ expect(closes).toEqual([])+ const input = all(await field.drawn(), 'Input')[0]+ expect(input.props.value).toBe('1')+ expect(textOf(await field.drawn())).toBe('')+ expect(textOf(lineOf(await a.drawn()))).toBe('‹ 1 ›')+ expect(textOf(lineOf(await b.drawn()))).toBe('‹ 1 ›')+ // Two Enters: the later one acts.+ await field.input({ key: 'page', text: '5' })+ expect(textOf(lineOf(await b.drawn()))).toBe('‹ 5 ›')+})++test('a run of the old file that ends after the file changed does not change what is known of the new file', async ($, on) => {+ let release = () => {}+ const until = new Promise<void>(done => (release = done))+ // Run 3 is the look-ahead for page 3 of the old file.+ const counts: Record<string, number> = { '/t/doc.pdf': 3 }+ const { clock, converts, mtimes } = world(on, { typst: true, pdfs: counts, files: { '/t/doc.pdf': '' }, holdRun: { at: 3, until } })+ await ready($)+ const ui = await $.ui.mount(sent(pdfs('/t/doc.pdf')))+ await ui.press({ key: 'pdf0-page-forward' })+ expect(converts.length).toBe(3)+ // The file now has one page.+ counts['/t/doc.pdf'] = 1+ mtimes['/t/doc.pdf'] = 2+ await refreshed($, clock)+ let tree: any = await ui.drawn()+ expect(images(tree)[0].props.source.file).toBe(convertedPath('/c', '/t/doc.pdf', '2:1000', BOX, 1))+ expect(all(tree, 'Button')).toEqual([])+ const n = converts.length+ // The old run ends (as made): the new file's facts stay.+ counts['/t/doc.pdf'] = 3+ release()+ await clock.settle()+ await refreshed($, clock)+ tree = await ui.drawn()+ expect(all(tree, 'Button')).toEqual([])+ expect(converts.length).toBe(n)+})+test('a JPEG by its name; two rows at once convert it once; a changed file converts again', async ($, on) => {// The first row's run ends only after the second row read the file's stat.const { converts, mtimes } = world(on, { typst: true, holdConvert: 2, files: { '/t/a.JPG': JPEG } })