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
Draw JPEG, WebP and Markdown files that Claude sends
razorback16b552334d6227
diff --git a/README.md b/README.mdindex efcf3fb..401fff0 100644--- a/README.md+++ b/README.md@@ -19,10 +19,14 @@ Only the drawing changes. The saved answer stays Markdown.```A `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.-- Images that Claude sends to you as files (the SendUserFile tool). The mod draws each PNG image under the row that shows the file.+- 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 and WebP images. Typst changes a JPEG or WebP image into a PNG image in the cache folder. It does this one time for each version of the file. The long side of that PNG image is 4096 pixels or less.+ - 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 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, and not taller than 24 rows or half the screen. The mod draws PNG images only. Other image types stay as the normal row.+ These pictures are not larger than the image. They are not wider than the transcript, and not taller than 24 rows or half the screen. The mod draws PNG, JPEG and WebP images only. Other image types (for example GIF and SVG) stay as the normal row.- The plan in plan mode (the ExitPlanMode tool). The mod draws the plan as a picture in the transcript, the same as an answer. Then the mod asks you to approve the plan. Refer to [Plan approval](#plan-approval).## Requirementsdiff --git a/hooks/lib/answer.ts b/hooks/lib/answer.tsindex 34a080e..dd156a4 100644--- a/hooks/lib/answer.ts+++ b/hooks/lib/answer.ts@@ -1,7 +1,8 @@// One Markdown text through the answer pipeline: its key, the compiled// pages, and the states before they are ready (blank while it streams or-// compiles, then the engine's text). The AssistantMessage hook and the plan-// (its ExitPlanMode rows) all draw through it.+// compiles, then the engine's text). The AssistantMessage hook, the plan+// (its ExitPlanMode rows) and the Markdown files Claude sends all draw+// through it.import type { EngineInterface } from 'claude-code'import { BLANK_AFTER_LIVE_MS, BLANK_RESUMED_MS, DEFAULT_CELL, DEFAULT_THEME, LIVE_STILL_MS, SETTLE_MS } from './settings'@@ -15,15 +16,16 @@ export type Drawing = { kind: 'pages'; result: Result; px: Cell; bytes?: string[// `id` keys the text's place (its message, its row), `columns` is// the picture width. `canStream`: the text may still grow (an answer); a-// plan is final when it is drawn, so it never waits as live.-export async function pagesOf($: EngineInterface, o: { id: string; text: string; columns: number; env: Env; canStream: boolean }): Promise<Drawing> {- const { id, text, columns, env } = o+// plan is final when it is drawn, so it never waits as live. `base`: the+// folder relative images start from (a Markdown file's); else the session's.+export async function pagesOf($: EngineInterface, o: { id: string; text: string; columns: number; env: Env; canStream: boolean; base?: string }): Promise<Drawing> {+ const { id, text, columns, env, base } = oconst px = S.cell ?? DEFAULT_CELLconst textHash = hashOf([text])const active = S.look ?? { name: DEFAULT_THEME, dir: `${env.root}/render/themes/${DEFAULT_THEME}`, stamp: '0' }const key = renderKey({textHash, columns, cell: px, size: S.size, mode: S.theme, termFont: env.termFont,- columnPt: fontFit(env.metrics, S.size).columnPt, templateStamp: env.stamp, look: active, inline: env.inline,+ columnPt: fontFit(env.metrics, S.size).columnPt, templateStamp: env.stamp, look: active, inline: env.inline, base,})const seen = lastText.get(id)const changed = seen !== text@@ -40,7 +42,7 @@ export async function pagesOf($: EngineInterface, o: { id: string; text: string;const bytes = await inlineOf($, got)return bytes ? { kind: 'pages', result: got, px, bytes } : { kind: 'text' }}- const job: Job = { key, requestId: id, text, columns, cell: px, theme: S.theme, size: S.size, themeDir: active.dir, env }+ const job: Job = { key, requestId: id, text, columns, cell: px, theme: S.theme, size: S.size, themeDir: active.dir, env, ...(base ? { base } : {}) }// Live: its text streams (inside a request we saw, or changing since we// last drew it). Drawn blank; final at the request's next block or end,// or once still for LIVE_STILL_MS (SETTLE_MS when no request was seen).diff --git a/hooks/lib/draw.tsx b/hooks/lib/draw.tsxindex 981c4f6..7ada607 100644--- a/hooks/lib/draw.tsx+++ b/hooks/lib/draw.tsx@@ -63,10 +63,14 @@ export function renderKey(o: {look: Look// Over ssh: pages are cut shorter (inlineBudget), so they are other PNGs.inline?: boolean+ // The folder relative images start from, when it is not the session's (a+ // Markdown file's): the same text there shows other images.+ base?: string}): string {return hashOf([o.textHash, o.columns, o.cell.width, o.cell.height, o.size, o.mode, o.termFont, o.columnPt,o.templateStamp, o.look.name, o.look.dir, o.look.stamp, TEMPLATE_VERSION, ...(o.inline ? ['inline'] : []),+ ...(o.base ? ['base', o.base] : []),])}@@ -139,8 +143,9 @@ export async function inlineOf($: EngineInterface, result: Result): Promise<stri}// How a set of pages sits: `bullet` the reply bullet in the gutter (on the-// first line's row), `gutter` its width (0: none), `marginTop` the rows above.-export type PagesLayout = { bullet?: boolean; gutter?: number; marginTop?: number }+// first line's row), `gutter` its width (0: none), `marginTop` the rows above,+// `keys` a prefix for its Images' keys (several sets in one tree).+export type PagesLayout = { bullet?: boolean; gutter?: number; marginTop?: number; keys?: string }// `inline`: each page's PNG as base64 (over ssh); else the terminal reads the file.export function drawPages($: EngineInterface, e: ResolveInput<RenderComponent, 'terminal'>, result: Result, columns: number, px: Cell, inline?: readonly string[], layout: PagesLayout = {}) {@@ -158,7 +163,7 @@ export function drawPages($: EngineInterface, e: ResolveInput<RenderComponent, 'const rows = rowsFor(page, columns, px)return (<Image- key={`p${i}`}+ key={`${layout.keys ?? ''}p${i}`}source={inline ? { png: inline[i]! } : { file: page.file, format: 'png', generation: columns * 1000 + rows }}columns={columns}rows={rows}diff --git a/hooks/lib/images.ts b/hooks/lib/images.tsindex ae148b3..36b053f 100644--- a/hooks/lib/images.ts+++ b/hooks/lib/images.ts@@ -1,8 +1,10 @@-// Pictures under rows (pure): which images a SendUserFile result or 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 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.import type { Cell } from './state'import { MAX_IMAGE_ROWS, PICTURE_MAX_ROWS, PICTURE_MIN_ROWS } from './settings'+import { hashOf } from './draw'// The most rows a picture under a row takes: half the viewport, within// PICTURE_MIN_ROWS to PICTURE_MAX_ROWS.@@ -20,18 +22,55 @@ export function pictureCells(size: { width: number; height: number }, columns: n}}-// The image paths of a SendUserFile result that can be PNGs (the engine's-// Image draws PNG only; the header read tells for sure).-export function sentImages(output: unknown): string[] {+// 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), and a+// Markdown file (drawn as an answer is).+export type SentKind = 'png' | 'jpeg' | 'webp' | 'markdown'+export type SentFile = { path: string; kind: SentKind }++// An image's type: by its media type, else by its file name. Null for any+// other type (GIF, SVG, …). An image with neither is a PNG to try (the+// header read tells for sure).+export function imageKindOf(a: { path: string; media_type?: unknown }): 'png' | 'jpeg' | 'webp' | null {+ if (typeof a.media_type === 'string') {+ const type = a.media_type.trim().toLowerCase()+ if (type === 'image/png') return 'png'+ if (type === 'image/jpeg' || type === 'image/jpg') return 'jpeg'+ return type === 'image/webp' ? 'webp' : null+ }+ if (/\.jpe?g$/i.test(a.path)) return 'jpeg'+ if (/\.webp$/i.test(a.path)) return 'webp'+ return 'png'+}++// A Markdown file, by its name: .md or .markdown.+export const isMarkdownPath = (path: string) => /\.(md|markdown)$/i.test(path)++// The files of a SendUserFile result that can draw, in its order, each once.+export function sentFiles(output: unknown): SentFile[] {const list = output && typeof output === 'object' ? (output as { attachments?: unknown }).attachments : undefinedif (!Array.isArray(list)) return []- return list- .filter((a): a is { path: string; isImage: true; media_type?: unknown } =>- !!a && typeof a === 'object' && a.isImage === true && typeof a.path === 'string' && a.path !== '')- .filter(a => typeof a.media_type !== 'string' || /^image\/png$/i.test(a.media_type))- .map(a => a.path)+ const found: SentFile[] = []+ for (const a of list) {+ if (!a || typeof a !== 'object' || typeof a.path !== 'string' || a.path === '') continue+ if (found.some(f => f.path === a.path)) continue+ const kind = a.isImage === true ? imageKindOf(a) : isMarkdownPath(a.path) ? 'markdown' : null+ if (kind) found.push({ path: a.path, kind })+ }+ return found}+// The image paths of a SendUserFile result that can draw (PNG, JPEG, WebP).+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 PNG Typst makes of a JPEG or WebP: in a key folder of the cache (as a+// compile's, dropped after 2 days), by the file and its stat stamp, so a+// changed file is made again.+export const convertedPath = (cache: string, file: string, stamp: string) => `${cache}/${hashOf(['convert', file, stamp])}/image.png`+// The numbers of the `[Image #N]` marks in a prompt, each once, in order.export function pastedNumbers(text: string): number[] {const found: number[] = []diff --git a/hooks/lib/pictures.tsx b/hooks/lib/pictures.tsxindex 14b9cc0..cd8afb8 100644--- a/hooks/lib/pictures.tsx+++ b/hooks/lib/pictures.tsx@@ -1,18 +1,24 @@-// Pictures under rows: the PNGs Claude sends (SendUserFile) and the images-// the user pastes are drawn under their row, at their own size or smaller.-// The pure parts are in images.ts.+// 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 or WebP as the PNG Typst makes of it); a Markdown+// file as an answer is. The pure parts are in images.ts.import type { EngineInterface, ImageSource, RenderElement, RenderInput } from 'claude-code'-import { DEFAULT_CELL, GUTTER, PICTURES_KEPT } from './settings'-import { INLINE_KEPT, inlined, pasteDirs, pictures, S, type Env } from './state'+import { COMPILE_TIMEOUT_MS, DEFAULT_CELL, GUTTER, PICTURES_KEPT, SENT_TEXT_MAX_BYTES } from './settings'+import { converted, converting, INLINE_KEPT, inlined, pasteDirs, pictures, S, sentTexts, type Env } from './state'import { columnsFor, fitsInline, INLINE_MAX_BYTES } from './terminal'-import { pasteDirOf, pictureCells, pictureRowsFor } from './images'-import { hashOf } from './draw'-import { parseOd, pngSize } from './typst'+import { convertedPath, folderOf, pasteDirOf, pictureCells, pictureRowsFor, type SentFile } from './images'+import { imagePathOf } from './markdown'+import { drawPages, hashOf } from './draw'+import { convertCall, logDebug, parseOd, pngSize } from './typst'+import { pagesOf, type Drawing } from './answer'import { HEADERS_SH } from './host'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).+export type Under = Shown | { drawing: Exclude<Drawing, { kind: 'text' }>; columns: number }export type RowInput = RenderInput<'ToolResult' | 'UserMessage', 'terminal'>// A PNG's pixel size from its first 24 bytes, read again only when its stat@@ -55,34 +61,144 @@ export async function pictureBytes($: EngineInterface, p: Picture): Promise<stri// The Images for the files that are PNGs, sized to the viewport.export async function shownOf($: EngineInterface, e: RowInput, ready: Env, files: readonly string[]): Promise<Shown[]> {- const columns = columnsFor(e.viewport?.columns)- const rows = pictureRowsFor(e.viewport?.rows)- const px = S.cell ?? DEFAULT_CELLconst shown: Shown[] = []for (const file of new Set(files)) {- const p = await pictureOf($, file)- if (!p) continue- const fit = pictureCells(p, columns, rows, px)- const alt = file.split('/').pop() || 'image'- if (ready.inline) {- const png = await pictureBytes($, p)- if (png) shown.push({ source: { png }, ...fit, alt })+ const s = await shownOne($, e, ready, file)+ if (s) shown.push(s)+ }+ return shown+}++// One PNG's Image, sized to the viewport; null when it is not a PNG. `alt`+// is the file's name (the name of the file it was made of).+export async function shownOne($: EngineInterface, e: RowInput, ready: Env, file: string, alt = nameOf(file)): Promise<Shown | null> {+ const p = await pictureOf($, file)+ if (!p) return null+ const fit = pictureCells(p, columnsFor(e.viewport?.columns), pictureRowsFor(e.viewport?.rows), S.cell ?? DEFAULT_CELL)+ if (ready.inline) {+ const png = await pictureBytes($, p)+ return png ? { source: { png }, ...fit, alt } : null+ }+ const generation = Number.parseInt(hashOf([p.stamp, fit.columns, fit.rows]).slice(0, 8), 16)+ return { source: { file, format: 'png', generation }, ...fit, alt }+}++const nameOf = (file: string) => file.split('/').pop() || 'image'++// A JPEG or WebP as a PNG that Typst makes (render/convert.typ) in the+// cache: once per stat stamp, and one run at a time per file. Null with no+// Typst, or when it fails (the row stays as is).+export async function convertedOf($: EngineInterface, ready: Env, file: string): Promise<string | null> {+ if (!ready.typst) return null+ const st = await $.fs.stat(file).catch(() => null)+ if (!st || st.kind !== 'file') return null+ const stamp = `${st.mtimeMs}:${st.size}`+ const kept = converted.get(file)+ if (kept?.stamp === stamp) return kept.png+ const key = `${file}@${stamp}`+ let run = converting.get(key)+ if (!run) {+ run = convertOnce($, ready, file, stamp).finally(() => converting.delete(key))+ converting.set(key, run)+ }+ return run+}++async function convertOnce($: EngineInterface, ready: Env, file: string, stamp: string): Promise<string | null> {+ const out = convertedPath(ready.cache, file, stamp)+ // Made before (an earlier load): the same file at the same stamp.+ const made = await $.fs.stat(out).catch(() => null)+ let png: string | null = out+ if (made?.kind !== 'file' || !made.size) {+ const dir = out.replace(/\/[^/]*$/, '')+ // The write makes the key folder; Typst does not (a failed write fails+ // the run below).+ await $.fs.write(`${dir}/source.txt`, `${file}\n`).catch(() => undefined)+ // 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, out: part })+ const failed = (err: unknown) => ({ exitCode: 1, stdout: '', stderr: `did not run: ${String(err)}` })+ const ran = await $.process.run(argv, { timeoutMs: COMPILE_TIMEOUT_MS, env }).catch(failed)+ const moved = ran.exitCode === 0 ? await $.process.run(['mv', '-f', part, out]).catch(failed) : null+ if (ran.exitCode !== 0) {+ await logDebug($, ready.cache, `convert ${file} failed:\n${ran.stderr}`)+ png = null+ } else if (moved?.exitCode !== 0) {+ await logDebug($, ready.cache, `convert ${file}: could not move ${part}:\n${moved?.stderr ?? ''}`)+ png = null+ }+ }+ converted.delete(file)+ converted.set(file, { stamp, png })+ for (const old of converted.keys()) {+ if (converted.size <= PICTURES_KEPT) break+ converted.delete(old)+ }+ return png+}++// A Markdown file's text, read again only when its stat changes; null when+// it is gone, over SENT_TEXT_MAX_BYTES, not read, or empty.+export async function sentTextOf($: EngineInterface, file: string): Promise<string | null> {+ const st = await $.fs.stat(file).catch(() => null)+ if (!st || st.kind !== 'file') return null+ const stamp = `${st.mtimeMs}:${st.size}`+ const kept = sentTexts.get(file)+ if (kept?.stamp === stamp) return kept.text+ const got = st.size <= SENT_TEXT_MAX_BYTES ? await $.fs.read(file).catch(() => null) : null+ const text = got?.trim() ? got : null+ sentTexts.delete(file)+ sentTexts.set(file, { stamp, text })+ for (const old of sentTexts.keys()) {+ if (sentTexts.size <= PICTURES_KEPT) break+ sentTexts.delete(old)+ }+ return text+}++// 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.+export async function sentOf(+ $: EngineInterface, e: RowInput, o: { ready: Env; markdown: Env | null; files: readonly SentFile[]; id: string },+): Promise<Under[]> {+ const columns = columnsFor(e.viewport?.columns)+ const under: Under[] = []+ for (const f of o.files) {+ const full = imagePathOf(f.path, o.ready.cwd)+ if (f.kind === 'markdown') {+ const text = o.markdown ? await sentTextOf($, full) : null+ if (!o.markdown || !text) continue+ const drawing = await pagesOf($, { id: `file:${o.id}:${f.path}`, text, columns, env: o.markdown, canStream: false, base: folderOf(full) })+ if (drawing.kind !== 'text') under.push({ drawing, columns })continue}- const generation = Number.parseInt(hashOf([p.stamp, fit.columns, fit.rows]).slice(0, 8), 16)- shown.push({ source: { file, format: 'png', generation }, ...fit, alt })+ const png = f.kind === 'png' ? full : await convertedOf($, o.ready, full)+ const shown = png ? await shownOne($, e, o.ready, png, nameOf(full)) : null+ if (shown) under.push(shown)}- return shown+ return under}// The engine's row, then the pictures under it.-export function underRow($: EngineInterface, e: RowInput, row: RenderElement, shown: readonly Shown[]) {+export function underRow($: EngineInterface, e: RowInput, row: RenderElement, under: readonly Under[]) {const { Box, Image } = $.ui.resolve(e)return (<Box flexDirection="column">{row}<Box flexDirection="column" marginLeft={GUTTER}>- {shown.map((s, i) => <Image key={`picture-${i}`} source={s.source} columns={s.columns} rows={s.rows} alt={s.alt} />)}+ {under.map((s, i) => {+ if ('source' in s) return <Image key={`picture-${i}`} source={s.source} columns={s.columns} rows={s.rows} alt={s.alt} />+ const { drawing, columns } = s+ if (drawing.kind === 'blank') return <Box key={`blank-${i}`} />+ return (+ <Box key={`pages-${i}`} flexDirection="column">+ {drawPages($, e, drawing.result, columns, drawing.px, drawing.bytes, { gutter: 0, marginTop: 0, keys: `file${i}-` })}+ </Box>+ )+ })}</Box></Box>)diff --git a/hooks/lib/settings.ts b/hooks/lib/settings.tsindex 690e75c..7c73a33 100644--- a/hooks/lib/settings.ts+++ b/hooks/lib/settings.ts@@ -62,6 +62,12 @@ export const MODES = ['dark', 'light'] as constexport const PICTURE_MAX_ROWS = 24export const PICTURE_MIN_ROWS = 6export const PICTURES_KEPT = 64+// 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 or WebP: its long side at most this many+// pixels (never made larger).+export const CONVERT_MAX_SIDE = 4096// What Claude is told while the mod draws its answers (a system prompt// section, added last).diff --git a/hooks/lib/state.ts b/hooks/lib/state.tsindex fb08ef1..b126b99 100644--- a/hooks/lib/state.ts+++ b/hooks/lib/state.ts@@ -57,6 +57,8 @@ export type Job = {size: numberthemeDir: stringenv: Env+ // The folder relative images start from (a Markdown file's); else env.cwd.+ base?: string}// The active theme: its name, folder, and the mtimes of its files and the// base theme's, which are part of every key.@@ -135,6 +137,12 @@ 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 or WebP by its stat stamp+// (null: it failed), the ones Typst makes now, and the text of each Markdown+// file by its stat stamp (null: it does not draw).+export const converted = new Map<string, { stamp: string; png: string | null }>()+export const converting = new Map<string, Promise<string | null>>()+export const sentTexts = new Map<string, { stamp: string; text: string | null }>()// The plan: the text edited in md-preview's flow, by the call's tool_use_id// (its rows draw it), and the ExitPlanMode calls of subagents (drawn as the// engine draws them).diff --git a/hooks/lib/typst.ts b/hooks/lib/typst.tsindex 4c34178..584e1a9 100644--- a/hooks/lib/typst.ts+++ b/hooks/lib/typst.ts@@ -2,7 +2,7 @@// answer's segments to PNG pages (with a retry in safe mode).import type { EngineInterface } from 'claude-code'-import { COMPILE_TIMEOUT_MS, NO_NETWORK, SEGMENT_ROWS, TYPST_FALLBACKS } from './settings'+import { COMPILE_TIMEOUT_MS, CONVERT_MAX_SIDE, NO_NETWORK, SEGMENT_ROWS, TYPST_FALLBACKS } from './settings'import { DEFAULT_METRICS, type FontMetrics, type Job, type Metrics, type Result } from './state'import { firstLine, imagePathOf, localImages, plainOf, splitSegments } from './markdown'import { inlineBudget } from './terminal'@@ -33,6 +33,24 @@ export function typstCall(o: {return { argv, env: noNetworkEnv(o.cache) }}+// The typst command that makes a PNG of a JPEG or WebP (render/convert.typ)+// at its own pixel size, its long side at most CONVERT_MAX_SIDE: at 72 ppi,+// 1 pt is 1 pixel.+export function convertCall(o: { typst: string; root: string; cache: string; file: string; out: string }): { argv: string[]; env: Record<string, string> } {+ const argv = [+ o.typst, 'compile',+ '--root', '/',+ '--format', 'png',+ '--diagnostic-format', 'short',+ '--ppi', '72',+ '--input', `f=${o.file}`,+ '--input', `max=${CONVERT_MAX_SIDE}`,+ `${o.root}/render/convert.typ`,+ o.out,+ ]+ return { argv, env: noNetworkEnv(o.cache) }+}+export function noNetworkEnv(cache: string): Record<string, string> {return {HTTPS_PROXY: NO_NETWORK,@@ -155,8 +173,9 @@ export async function compile($: EngineInterface, job: Job): Promise<Result | 'fif (kept) return JSON.parse(kept) as Resultconst segments = splitSegments(job.text, job.columns, job.env.inline ? inlineBudget(job.cell) : SEGMENT_ROWS)- const images = await existingImages($, segments, job.env.cwd)- await $.fs.write(`${dir}/doc.json`, JSON.stringify({ base: job.env.cwd, segments, images }))+ const base = job.base ?? job.env.cwd+ const images = await existingImages($, segments, base)+ await $.fs.write(`${dir}/doc.json`, JSON.stringify({ base, segments, images }))let tag = 'a'let ran = await runTypst($, job, segments, dir, tag, false)diff --git a/hooks/register.tsx b/hooks/register.tsxindex ae89ab7..2633027 100644--- a/hooks/register.tsx+++ b/hooks/register.tsx@@ -20,7 +20,6 @@ import type { EngineInterface, Register, RenderElement, RenderViewport } from 'cimport { DEFAULT_THEME, MAX_SIZE, MIN_SIZE, TYPST_PROMPT } from './lib/settings'import { editedPlans, refresh, S, subagentPlans, writesLive, type Env } from './lib/state'-import { imagePathOf } from './lib/markdown'import { columnsFor } from './lib/terminal'import { escapeControls, luminanceOf, modeLine, modeOfLuminance, parseOsc11, settingOf } from './lib/mode'import { applyTheme, themeListing, userThemesOf } from './lib/themes'@@ -32,8 +31,8 @@ import { drawPages } from './lib/draw'import { finalizeAll } from './lib/stream'import { pagesOf } from './lib/answer'import { noteViewport, setUp } from './lib/env'-import { pastedImagePath, pastedNumbers, sentImages } from './lib/images'-import { pasteDir, shownOf, underRow, type Shown } from './lib/pictures'+import { pastedImagePath, pastedNumbers, sentFiles } from './lib/images'+import { pasteDir, sentOf, shownOf, underRow, type Shown, type Under } from './lib/pictures'import {currentPlan, decidePlan, decisionOf, drawAskLine, drawPlanResult, drawPlanUse, isPlanQuestion, planFileOf, planInputOf, planOf,planShownOf, scheduleClear, type PlanVerdict,@@ -57,7 +56,7 @@ export {export { commandSuggestions, parseCommand, type Command, type Suggestion } from './lib/command'export { hasSetup, SETUP_END, SETUP_START, setupBlock, shellRcOf, withoutSetup, withSetup, type ShellRc } from './lib/setup'export { OSC11_PL } from './lib/host'-export { measureCall, noNetworkEnv, parseOd, pngSize, shouldRetrySafe, typstCall } from './lib/typst'+export { convertCall, measureCall, noNetworkEnv, parseOd, pngSize, shouldRetrySafe, typstCall } from './lib/typst'export { alignFirstLine, firstLineOf, fontFit, hashOf, renderKey, rowsFor, sizing, type FirstLine } from './lib/draw'export * from './lib/images'export {@@ -273,23 +272,26 @@ export const register: Register = on => {return <Box />})- // The PNGs Claude sends with SendUserFile, under the result row that lists- // them. Its ToolUse row draws no attachments, and the tool is never in a- // ToolGroup, so only ToolResult is hooked and no picture draws twice.+ // 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+ // never in a ToolGroup, so only ToolResult is hooked and no picture draws+ // twice.on('ui.render', { component: 'ToolResult' }, async ($, e, next) => {if (e.surface !== 'terminal' || e.props.tool !== 'SendUserFile' || e.props.isErrored) return next(e)- let shown: Shown[] = []+ let under: Under[] = []try {- const files = sentImages(e.props.output)+ const files = sentFiles(e.props.output)const ready = files.length ? await pictureEnv($, e) : null- if (ready) shown = await shownOf($, e, ready, files.map(f => imagePathOf(f, ready.cwd)))+ const markdown = ready && files.some(f => f.kind === 'markdown') ? await answerEnv($, e) : null+ if (ready) under = await sentOf($, e, { ready, markdown, files, id: e.props.tool_use_id })} catch {- shown = []+ under = []}const row = await next(e)- if (!shown.length) return row+ if (!under.length) return rowtry {- return underRow($, e, row, shown)+ return underRow($, e, row, under)} catch {return row}diff --git a/render/convert.typ b/render/convert.typnew file mode 100644index 0000000..01d9cc7--- /dev/null+++ b/render/convert.typ@@ -0,0 +1,56 @@+// md-preview: makes a PNG of a JPEG or WebP (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 /); max = the most+// pixels of the long side (0 or absent: no cap).+//+// 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+// width. A file it can not read keeps Typst's size.+#set page(width: auto, height: auto, margin: 0pt)++#let f = sys.inputs.at("f", default: "")+#let data = read(f, encoding: none)+#let at(i) = if i < data.len() { data.at(i) } else { 0 }+#let be16(i) = at(i) * 256 + at(i + 1)+#let le16(i) = at(i) + at(i + 1) * 256+#let le24(i) = le16(i) + at(i + 2) * 65536+#let has-tag(i, tag) = data.len() >= i + tag.len() and data.slice(i, i + tag.len()) == bytes(tag)++// A JPEG's (width, height): from the first SOF marker.+#let jpeg-size() = {+ let sofs = (0xc0, 0xc1, 0xc2, 0xc3, 0xc5, 0xc6, 0xc7, 0xc9, 0xca, 0xcb, 0xcd, 0xce, 0xcf)+ let i = 2+ let size = none+ while size == none and i + 9 <= data.len() and at(i) == 0xff {+ let m = at(i + 1)+ if m == 0xff { i += 1 }+ else if m in sofs { size = (be16(i + 7), be16(i + 5)) }+ else { i += 2 + be16(i + 2) }+ }+ size+}++// A WebP's (width, height): from its VP8, VP8L or VP8X chunk.+#let webp-size() = {+ if has-tag(12, "VP8 ") { (calc.rem(le16(26), 16384), calc.rem(le16(28), 16384)) }+ else if has-tag(12, "VP8L") {+ let (b0, b1, b2, b3) = (at(21), at(22), at(23), at(24))+ (1 + b0 + calc.rem(b1, 64) * 256, 1 + calc.quo(b1, 64) + b2 * 4 + calc.rem(b3, 16) * 1024)+ } else if has-tag(12, "VP8X") { (1 + le24(24), 1 + le24(27)) }+}++#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() }++// The sides as drawn: the pixel size, swapped when Typst turns the image by+// its EXIF orientation; else Typst's own size. The long side is at most+// `max` pixels (0: no cap); an image is never made larger.+#context {+ let natural = measure(image(data))+ let (w, h) = if size == none or size.at(0) == 0 or size.at(1) == 0 { (natural.width / 1pt, natural.height / 1pt) } else { size }+ let turned = w != h and (natural.width > natural.height) != (w > h)+ let (dw, dh) = if turned { (h, w) } else { (w, h) }+ let max = int(sys.inputs.at("max", default: "0"))+ let scale = if max > 0 { calc.min(1, max / calc.max(dw, dh)) } else { 1 }+ image(data, width: dw * scale * 1pt)+}diff --git a/tests/images.test.ts b/tests/images.test.tsindex 520f2ac..c353e60 100644--- a/tests/images.test.ts+++ b/tests/images.test.ts@@ -1,8 +1,8 @@import { expect, mock, test } from 'claude-code/testing'import {- claudeTmpOf, DEFAULT_CELL, pasteDirOf, pastedImagePath, pastedNumbers, PICTURE_MAX_ROWS, pictureCells, pictureRowsFor,- projectSlug, sentImages,+ claudeTmpOf, convertCall, convertedPath, DEFAULT_CELL, folderOf, imageKindOf, isMarkdownPath, pasteDirOf, pastedImagePath, pastedNumbers,+ PICTURE_MAX_ROWS, pictureCells, pictureRowsFor, projectSlug, renderKey, sentFiles, sentImages,} from '../hooks/register'// ---- Pure helpers -----------------------------------------------------------@@ -26,7 +26,7 @@ test('a picture takes at most half the viewport, within 6 and 24 rows', () => {expect(pictureRowsFor(8)).toBe(6)})-test('only image attachments that can be PNGs are drawn', () => {+test('only PNG, JPEG and WebP image attachments are drawn', () => {expect(sentImages({attachments: [{ path: '/t/a.png', size: 1, isImage: true, media_type: 'image/png' },@@ -34,13 +34,91 @@ test('only image attachments that can be PNGs are drawn', () => {{ path: '/t/c.jpg', size: 1, isImage: true, media_type: 'image/jpeg' },{ path: '/t/d.pdf', size: 1, isImage: false },{ size: 1, isImage: true },+ { path: '/t/e.webp', size: 1, isImage: true, media_type: 'image/webp' },+ { path: '/t/f.gif', size: 1, isImage: true, media_type: 'image/gif' },+ { path: '/t/g.svg', size: 1, isImage: true, media_type: 'image/svg+xml' },],- })).toEqual(['/t/a.png', '/t/b.png'])+ })).toEqual(['/t/a.png', '/t/b.png', '/t/c.jpg', '/t/e.webp'])expect(sentImages(undefined)).toEqual([])expect(sentImages('error text')).toEqual([])expect(sentImages({ attachments: 'x' })).toEqual([])})+test('an image type: by its media type, else by its name; with neither, a PNG to try', () => {+ expect(imageKindOf({ path: '/t/a', media_type: 'image/png' })).toBe('png')+ expect(imageKindOf({ path: '/t/a', media_type: 'IMAGE/JPEG' })).toBe('jpeg')+ expect(imageKindOf({ path: '/t/a', media_type: 'image/jpg' })).toBe('jpeg')+ expect(imageKindOf({ path: '/t/a', media_type: 'image/webp' })).toBe('webp')+ // The media type wins over the name.+ expect(imageKindOf({ path: '/t/a.jpg', media_type: 'image/png' })).toBe('png')+ expect(imageKindOf({ path: '/t/a.png', media_type: 'image/gif' })).toBe(null)+ expect(imageKindOf({ path: '/t/a.png', media_type: 'image/svg+xml' })).toBe(null)+ expect(imageKindOf({ path: '/t/a.PNG' })).toBe('png')+ expect(imageKindOf({ path: '/t/a.JPG' })).toBe('jpeg')+ expect(imageKindOf({ path: '/t/a.jpeg' })).toBe('jpeg')+ expect(imageKindOf({ path: '/t/a.WebP' })).toBe('webp')+ expect(imageKindOf({ path: '/t/screenshot' })).toBe('png')+})++test('a Markdown file: .md or .markdown, not an image; all files in their order, each once', () => {+ expect(isMarkdownPath('/t/notes.md')).toBe(true)+ expect(isMarkdownPath('/t/NOTES.Markdown')).toBe(true)+ expect(isMarkdownPath('/t/notes.mdx')).toBe(false)+ expect(isMarkdownPath('/t/md')).toBe(false)+ expect(sentFiles({+ attachments: [+ { path: '/t/notes.md', size: 1, isImage: false },+ { path: '/t/a.jpg', size: 1, isImage: true },+ { path: '/t/b.txt', size: 1, isImage: false },+ { path: '/t/c.png', size: 1, isImage: true, media_type: 'image/png' },+ { path: '/t/notes.md', size: 1, isImage: false },+ { path: '/t/odd.md', size: 1, isImage: true, media_type: 'image/png' },+ { path: '/t/d.webp', size: 1, isImage: true },+ ],+ })).toEqual([+ { path: '/t/notes.md', kind: 'markdown' },+ { path: '/t/a.jpg', kind: 'jpeg' },+ { path: '/t/c.png', kind: 'png' },+ { path: '/t/odd.md', kind: 'png' },+ { path: '/t/d.webp', kind: 'webp' },+ ])+ expect(sentFiles(null)).toEqual([])+})++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('/')+ expect(folderOf('/t//notes.md')).toBe('/t')+})++test('a converted PNG is named by the file and its stat stamp, in a key folder of the cache', () => {+ const one = convertedPath('/c', '/t/a.jpg', '1:1000')+ expect(one).toMatch(/^\/c\/[0-9a-f]{16}\/image\.png$/)+ expect(convertedPath('/c', '/t/a.jpg', '1:1000')).toBe(one)+ expect(convertedPath('/c', '/t/a.jpg', '2:1000')).not.toBe(one)+ expect(convertedPath('/c', '/t/b.jpg', '1:1000')).not.toBe(one)+})++test('the conversion call: render/convert.typ at 72 ppi, the file and the 4096 px cap as inputs, no network', () => {+ const { argv, env } = convertCall({ typst: '/usr/bin/typst', root: '/r', cache: '/c', file: '/t/a b.webp', out: '/c/k/image.png' })+ expect(argv).toEqual([+ '/usr/bin/typst', 'compile', '--root', '/', '--format', 'png', '--diagnostic-format', 'short', '--ppi', '72',+ '--input', 'f=/t/a b.webp', '--input', 'max=4096', '/r/render/convert.typ', '/c/k/image.png',+ ])+ expect(env.TYPST_PACKAGE_CACHE_PATH).toBe('/c/pkg-cache')+ expect(env.HTTPS_PROXY).toBe('http://127.0.0.1:9')+})++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,+ templateStamp: '1', look: { name: 'vscode', dir: '/t', stamp: '0' },+ }+ expect(renderKey({ ...o, base: undefined })).toBe(renderKey(o))+ expect(renderKey({ ...o, base: '/t/docs' })).not.toBe(renderKey(o))+ expect(renderKey({ ...o, base: '/t/docs' })).not.toBe(renderKey({ ...o, base: '/t/other' }))+})+test('the [Image #N] marks of a prompt, each once', () => {expect(pastedNumbers('[Image #5] what is this')).toEqual([5])expect(pastedNumbers('[Image #2] and [Image #3], again [Image #2]')).toEqual([2, 3])@@ -72,38 +150,120 @@ const PASTED = '/private/tmp/claude-501/-w-app/sid-1/images'// A Mac with kitty (pictures drawn), uid 501, session sid-1 in /w/app. `files`// are the files that exist, by path: their first bytes as od prints them.-function world(on: any, o: { vars?: Record<string, string>; files?: Record<string, string>; dirs?: string[]; projects?: string[] } = {}) {+// `texts` are text files (a Markdown file Claude sends), `mtimes` the files'+// mtimes (1 when not set). `typst`: Typst is found; it makes a PNG of a JPEG+// or WebP (unless `failConvert`; `mv` moves it, unless `failMove`), and+// compiles Markdown to one page.+// `holdConvert`: a conversion ends only once its file had that many stats+// (other rows reached it while it runs). `holdCompile`: a Markdown compile+// ends only when this settles.+function world(on: any, o: {+ vars?: Record<string, string>+ files?: Record<string, string>+ texts?: Record<string, string>+ mtimes?: Record<string, number>+ dirs?: string[]+ projects?: string[]+ typst?: boolean+ failConvert?: boolean+ failMove?: boolean+ holdConvert?: number+ holdCompile?: Promise<void>+} = {}) {mock.store(on)const clock = mock.clock(on)mock.env(on, { HOME: '/h', TERM: 'xterm-kitty', ...o.vars })const files = o.files ?? {}+ const texts = o.texts ?? {}+ const mtimes = o.mtimes ?? {}+ const written = new Map<string, string>()const dirs = new Set(o.dirs ?? [])const heads: string[] = []const reads: string[] = []+ const converts: string[][] = []+ const moves: string[][] = []+ const docs: any[] = []+ const logs: string[] = []+ const stats = new Map<string, number>()+ const waits: { path: string; done: () => void }[] = []+ const statted = (path: string) => {+ stats.set(path, (stats.get(path) ?? 0) + 1)+ for (const w of waits.filter(w => w.path === path && stats.get(path)! >= (o.holdConvert ?? 0))) {+ waits.splice(waits.indexOf(w), 1)+ w.done()+ }+ }on('process.run', async ($: any, e: any) => {const argv: string[] = e.argvconst cmd = argv.join(' ')if (/md-preview-/.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') {+ moves.push(argv)+ if (o.failMove || !(argv[2]! in files)) return ok('', 1)+ files[argv[3]!] = files[argv[2]!]!+ delete files[argv[2]!]+ return ok('')+ }+ if (argv[0] === '/usr/bin/typst' && argv[1] === 'compile' && argv.at(-2)!.endsWith('/render/convert.typ')) {+ converts.push(argv)+ const file = argv.find(a => a.startsWith('f='))!.slice(2)+ if ((stats.get(file) ?? 0) < (o.holdConvert ?? 0)) await new Promise<void>(done => waits.push({ path: file, done }))+ if (o.failConvert) return ok('', 1)+ files[argv.at(-1)!] = HEAD+ return ok('')+ }+ if (argv[0] === '/usr/bin/typst' && argv[1] === 'compile') {+ const doc = argv.find(a => a.startsWith('doc='))!.slice(4)+ docs.push(JSON.parse(written.get(doc)!))+ await o.holdCompile+ return ok('')+ }if (cmd.includes('od -An')) {- const file = argv.at(-1)!- heads.push(file)- return ok(`${files[file] ?? ''}\n@\n`)+ const all = argv.slice(4)+ heads.push(...all)+ return ok(all.map(f => `${files[f] ?? (f.startsWith('/c/') ? HEAD : '')}\n@\n`).join(''))+ }+ if (cmd.includes('debug.log')) {+ logs.push(e.init?.stdin ?? '')+ return ok('')}return ok('', 1)})on('session.id', async () => ({ value: '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) =>- e.path in files ? { value: { kind: 'file', size: 1000, mtimeMs: 1, isLink: false } } : e.path.startsWith('/t/') || e.path.startsWith('/private/') ? { deny: 'ENOENT' } : next(e))- on('fs.exists', async ($: any, e: any, next: any) => (e.path.startsWith('/private/') ? { value: dirs.has(e.path) } : next(e)))- on('fs.list', async ($: any, e: any, next: any) =>- e.path === '/private/tmp/claude-501' ? { value: (o.projects ?? []).map(name => ({ name, kind: 'dir', size: 0, mtimeMs: 1, isLink: false })) } : next(e))- on('fs.read', async ($: any, e: any, next: any) => (e.as === 'bytes' && e.path in files ? (reads.push(e.path), { value: { base64: PNG } }) : next(e)))+ on('fs.stat', async ($: any, e: any, next: any) => {+ statted(e.path)+ const size = e.path in files ? 1000 : e.path in texts ? texts[e.path]!.length : -1+ if (size >= 0) return { value: { kind: 'file', size, mtimeMs: mtimes[e.path] ?? 1, isLink: false } }+ return e.path.startsWith('/t/') || 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) }+ if (e.path.startsWith('/t/')) return { value: e.path in files || e.path in texts }+ // Typst only where `typst` says (not the one on this computer).+ return e.path.endsWith('/typst') ? { value: false } : next(e)+ })+ on('fs.list', async ($: any, e: any, next: any) => {+ if (e.path === '/private/tmp/claude-501') return { value: (o.projects ?? []).map(name => ({ name, kind: 'dir', size: 0, mtimeMs: 1, isLink: false })) }+ return e.path.startsWith('/c/') ? { value: [{ name: 'a-1.png', kind: 'file', size: 1, mtimeMs: 1, isLink: false }] } : next(e)+ })+ on('fs.write', async ($: any, e: any) => {+ written.set(e.path, e.text)+ return { value: undefined }+ })+ on('fs.read', async ($: any, e: any, next: any) => {+ if (e.as === 'bytes' && e.path in files) return (reads.push(e.path), { value: { base64: PNG } })+ if (e.as !== 'bytes' && e.path in texts) return (reads.push(e.path), { value: texts[e.path] })+ if (written.has(e.path)) return { value: written.get(e.path) }+ return e.path.startsWith('/c/') || e.path.startsWith('/t/') ? { deny: 'ENOENT' } : next(e)+ })on('ui.toast', async () => ({ value: undefined }))on('ui.render', () => ENGINE as any)- return { clock, heads, reads }+ return { clock, heads, reads, converts, moves, docs, logs, files, texts, mtimes, written }}const sent = (output: unknown, isErrored = false, id = 'tu-1') =>@@ -112,6 +272,8 @@ const sent = (output: unknown, isErrored = false, id = 'tu-1') =>props: { tool_use_id: id, tool: 'SendUserFile', output, isErrored }, viewport: { columns: 100, rows: 40 },}) as anyconst attach = (path: string, isImage = true) => ({ attachments: [{ path, size: 1000, isImage, ...(isImage ? { media_type: 'image/png' } : {}) }] })+// Several attachments: an image by its name (no media type), else a file.+const attachAll = (...paths: string[]) => ({ attachments: paths.map(path => ({ path, size: 1000, isImage: /\.(png|jpe?g|webp)$/i.test(path) })) })const prompt = (text: string, origin: any = { kind: 'composer' }, id = 'u-1') =>({plugin: 'md-preview', surface: 'terminal', component: 'UserMessage', requestId: id,@@ -156,6 +318,193 @@ test('a file that is not an image, a JPEG and a missing file leave the row as it}})+test('a JPEG and a WebP Claude sends are made PNGs by Typst once, and draw under the row', async ($, on) => {+ const { converts, moves, heads } = world(on, { typst: true, files: { '/t/photo.jpg': JPEG, '/t/shot.webp': '' } })+ await ready($)+ const output = { attachments: [+ { path: '/t/photo.jpg', size: 1000, isImage: true, media_type: 'image/jpeg' },+ { path: '/t/shot.webp', size: 1000, isImage: true, media_type: 'image/webp' },+ ] }+ const ui = await $.ui.mount(sent(output))+ const tree: any = await ui.drawn()+ expect(tree.children[0]).toMatchObject(ENGINE)+ const shown = images(tree)+ expect(shown.map(i => i.props.alt)).toEqual(['photo.jpg', 'shot.webp'])+ expect(shown[0].props).toMatchObject({ columns: 40, rows: 10 })+ expect(shown[0].props.source.file).toMatch(/^\/c\/[0-9a-f]{16}\/image\.png$/)+ expect(shown[0].props.source.file).not.toBe(shown[1].props.source.file)+ expect(converts.map(argv => argv.find(a => a.startsWith('f=')))).toEqual(['f=/t/photo.jpg', 'f=/t/shot.webp'])+ // Typst writes a part file; only a whole one is moved to image.png.+ const out = shown[0].props.source.file+ expect(converts[0]!.at(-1)).toBe(out.replace(/image\.png$/, 'image.part.png'))+ expect(moves[0]).toEqual(['mv', '-f', converts[0]!.at(-1), out])+ // A redraw converts nothing again, and the JPEG's own bytes are never read as a PNG.+ await ui.redraw(sent(output).props)+ expect(images(await ui.drawn()).length).toBe(2)+ expect(converts.length).toBe(2)+ expect(heads).not.toContain('/t/photo.jpg')+})++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 } })+ await ready($)+ const [one, two] = await Promise.all([$.ui.mount(sent(attachAll('/t/a.JPG'), false, 'tu-1')), $.ui.mount(sent(attachAll('/t/a.JPG'), false, 'tu-2'))])+ const first = images(await one.drawn())[0].props.source.file+ expect(images(await two.drawn())[0].props.source.file).toBe(first)+ expect(converts.length).toBe(1)+ mtimes['/t/a.JPG'] = 5+ const three = await $.ui.mount(sent(attachAll('/t/a.JPG'), false, 'tu-3'))+ expect(images(await three.drawn())[0].props.source.file).not.toBe(first)+ expect(converts.length).toBe(2)+})++test('over ssh, a converted JPEG goes as bytes', async ($, on) => {+ const { reads } = world(on, { typst: true, vars: { SSH_CONNECTION: '10.0.0.2 50000 10.0.0.1 22' }, files: { '/t/photo.jpg': JPEG } })+ await ready($)+ const ui = await $.ui.mount(sent(attachAll('/t/photo.jpg')))+ expect(images(await ui.drawn())[0].props.source).toEqual({ png: PNG })+ expect(reads.length).toBe(1)+ expect(reads[0]).toMatch(/^\/c\/[0-9a-f]{16}\/image\.png$/)+})++test('with no Typst, or a conversion that fails, a JPEG leaves the row as it is', async ($, on) => {+ const { converts, moves, logs, files } = world(on, { typst: true, failConvert: true, files: { '/t/photo.jpg': JPEG } })+ await ready($)+ const ui = await $.ui.mount(sent(attachAll('/t/photo.jpg')))+ expect(await ui.drawn()).toMatchObject(ENGINE)+ expect(converts.length).toBe(1)+ expect(logs.join('')).toContain('convert /t/photo.jpg failed')+ // Nothing is moved, so no image.png is there for a later load.+ expect(moves).toEqual([])+ expect(Object.keys(files).filter(f => f.endsWith('/image.png'))).toEqual([])+ // The failure is kept for this stamp: no second run.+ await ui.redraw(sent(attachAll('/t/photo.jpg')).props)+ expect(converts.length).toBe(1)+})++test('a part file that can not be moved draws no picture; an image.png made before is used with no run', async ($, on) => {+ const { converts, logs, files } = world(on, { typst: true, failMove: true, files: { '/t/photo.jpg': JPEG, '/t/old.jpg': JPEG } })+ await ready($)+ const ui = await $.ui.mount(sent(attachAll('/t/photo.jpg'), false, 'tu-1'))+ expect(await ui.drawn()).toMatchObject(ENGINE)+ expect(converts.length).toBe(1)+ expect(logs.join('')).toContain('convert /t/photo.jpg: could not move')+ expect(Object.keys(files).filter(f => f.endsWith('/image.png'))).toEqual([])+ // An earlier load made the PNG of old.jpg (same stamp): no run, it draws.+ files[convertedPath('/c', '/t/old.jpg', '1:1000')] = HEAD+ const old = await $.ui.mount(sent(attachAll('/t/old.jpg'), false, 'tu-2'))+ expect(images(await old.drawn())[0].props.source.file).toBe(convertedPath('/c', '/t/old.jpg', '1:1000'))+ expect(converts.length).toBe(1)+})++test('with no Typst, a JPEG and a Markdown file leave the row as it is; a PNG still draws', async ($, on) => {+ const { converts } = world(on, { files: { '/t/photo.jpg': JPEG, '/t/icon.png': HEAD }, texts: { '/t/notes.md': '# Notes' } })+ await ready($)+ const ui = await $.ui.mount(sent(attachAll('/t/photo.jpg', '/t/notes.md', '/t/icon.png')))+ const shown = images(await ui.drawn())+ expect(shown.map(i => i.props.alt)).toEqual(['icon.png'])+ expect(converts).toEqual([])+})++test('a Markdown file Claude sends draws as pictures under the row, its images by its own folder', async ($, on) => {+ const text = '# Notes\n\n and '+ const { clock, docs } = world(on, { typst: true, files: { '/t/docs/pic.png': HEAD }, texts: { '/t/docs/notes.md': text } })+ await ready($)+ const ui = await $.ui.mount(sent(attachAll('/t/docs/notes.md')))+ await clock.settle()+ await ui.redraw(sent(attachAll('/t/docs/notes.md')).props)+ const tree: any = await ui.drawn()+ expect(tree.children[0]).toMatchObject(ENGINE)+ const [page] = images(tree)+ expect(page.props.columns).toBe(98)+ expect(page.props.source.file).toMatch(/^\/c\/[0-9a-f]{16}\/a-1\.png$/)+ expect(docs).toEqual([{ base: '/t/docs', segments: [text], images: ['pic.png', '/t/docs/pic.png'] }])+})++test('the same Markdown in two folders compiles twice; an answer still uses the session folder', async ($, on) => {+ const { clock, docs } = world(on, { typst: true, texts: { '/t/a/n.md': '# Same', '/t/b/n.md': '# Same' } })+ await ready($)+ const a = await $.ui.mount(sent(attachAll('/t/a/n.md'), false, 'tu-a'))+ const b = await $.ui.mount(sent(attachAll('/t/b/n.md'), false, 'tu-b'))+ await clock.settle()+ await a.redraw(sent(attachAll('/t/a/n.md'), false, 'tu-a').props)+ await b.redraw(sent(attachAll('/t/b/n.md'), false, 'tu-b').props)+ expect(images(await a.drawn())[0].props.source.file).not.toBe(images(await b.drawn())[0].props.source.file)+ const answer = { plugin: 'md-preview', surface: 'terminal', component: 'AssistantMessage', requestId: 'r-1', props: { text: '# Same', isFirstOfReply: true }, viewport: { columns: 100, rows: 40 } } as any+ await $.ui.mount(answer)+ await clock.settle()+ expect(docs.map(d => d.base)).toEqual(['/t/a', '/t/b', '/w/app'])+})++test('while a Markdown file compiles: an empty space, then for a moment the row alone, then its pictures', async ($, on) => {+ let release = () => {}+ const holdCompile = new Promise<void>(done => (release = done))+ const { clock } = world(on, { typst: true, holdCompile, files: { '/t/one.png': HEAD }, texts: { '/t/notes.md': '# Notes' } })+ await ready($)+ const output = attachAll('/t/notes.md', '/t/one.png')+ const ui = await $.ui.mount(sent(output))+ const blank: any = await ui.drawn()+ expect(blank.children[0]).toMatchObject(ENGINE)+ expect(blank.children[1].children[0]).toMatchObject({ type: 'Box', props: { key: 'blank-0' } })+ expect(images(blank).map(i => i.props.alt)).toEqual(['one.png'])+ // Not ready after 1 s: the Markdown file draws nothing, the image stays.+ await clock.advance(1000)+ await ui.redraw(sent(output).props)+ const text: any = await ui.drawn()+ expect(text.children[1].children.length).toBe(1)+ expect(images(text).map(i => i.props.alt)).toEqual(['one.png'])+ release()+ await clock.settle()+ await ui.redraw(sent(output).props)+ expect(images(await ui.drawn()).map(i => i.props.alt)).toEqual(['Notes', 'one.png'])+})++test('images and Markdown files draw in the attachments order', async ($, on) => {+ const { clock } = world(on, { typst: true, files: { '/t/one.png': HEAD, '/t/two.jpg': JPEG }, texts: { '/t/notes.md': '# Notes' } })+ await ready($)+ const output = attachAll('/t/one.png', '/t/notes.md', '/t/two.jpg')+ const ui = await $.ui.mount(sent(output))+ await clock.settle()+ await ui.redraw(sent(output).props)+ const shown = images(await ui.drawn())+ expect(shown.length).toBe(3)+ expect(shown[0].props.source.file).toBe('/t/one.png')+ expect(shown[1].props.source.file).toMatch(/\/a-1\.png$/)+ expect(shown[2].props.alt).toBe('two.jpg')+ // Each Image has a key of its own in the tree.+ expect(new Set(shown.map(i => i.props.key)).size).toBe(3)+})++test('a Markdown file that is empty, too large, gone or not Markdown leaves the row as it is', async ($, on) => {+ const { clock, docs, reads } = world(on, {+ typst: true, texts: { '/t/empty.md': ' \n\n', '/t/big.md': `# Big\n${'x'.repeat(256 * 1024)}`, '/t/notes.txt': '# Text' },+ })+ await ready($)+ for (const [i, path] of ['/t/empty.md', '/t/big.md', '/t/gone.md', '/t/notes.txt'].entries()) {+ const ui = await $.ui.mount(sent(attachAll(path), false, `tu-${i}`))+ await clock.settle()+ expect(await ui.drawn()).toMatchObject(ENGINE)+ }+ expect(docs).toEqual([])+ expect(reads).toEqual(['/t/empty.md'])+})++test('a Markdown file is read again only when its stat changes', async ($, on) => {+ const { clock, docs, reads, texts, mtimes } = world(on, { typst: true, texts: { '/t/n.md': '# One' } })+ await ready($)+ const ui = await $.ui.mount(sent(attachAll('/t/n.md')))+ await clock.settle()+ await ui.redraw(sent(attachAll('/t/n.md')).props)+ expect(reads).toEqual(['/t/n.md'])+ texts['/t/n.md'] = '# Two'+ mtimes['/t/n.md'] = 2+ await ui.redraw(sent(attachAll('/t/n.md')).props)+ await clock.settle()+ expect(reads).toEqual(['/t/n.md', '/t/n.md'])+ expect(docs.map(d => d.segments.join(''))).toEqual(['# One', '# Two'])+})+test('an errored SendUserFile call leaves the row as it is', async ($, on) => {world(on, { files: { '/t/icon.png': HEAD } })await ready($)