Skip to content

Claude's answers, rendered: Markdown, math, charts and diagrams drawn in the Claude Code terminal. Independent project, not affiliated with Anthropic.

TypeScript claude-code-mod

Resize and scroll without jitter; one Frame, one swap per change

razorback1684d21245e517
diff --git a/README.md b/README.md
index 673006b..0ec7c0e 100644
--- a/README.md
+++ b/README.md
@@ -18,7 +18,7 @@ Only the drawing changes. The saved answer stays Markdown.
#import "@preview/fletcher:0.5.8" as fletcher: diagram, node, edge
```
- 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.
+ 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. `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 and WebP images. Typst changes a JPEG or WebP 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.
- 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.
@@ -26,7 +26,7 @@ Only the drawing changes. The saved answer stays Markdown.
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. The height setting (`/md-preview height`) sets the most rows that they can use: by default, half the screen and not more than 24 rows. The mod draws PNG, JPEG and WebP images only. Other image types (for example GIF and SVG) stay as the normal row.
+ These pictures are not larger than the image. They are not wider than the transcript. The height setting (`/md-preview 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 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).
## Requirements
@@ -76,7 +76,7 @@ To try it from a clone without installing: `claude --plugin-dir /path/to/claude-
| `/md-preview width` | Shows the width: the most columns that a picture can use |
| `/md-preview width <40–400>` | Sets the most columns that a picture can use (kept for later sessions) |
| `/md-preview width full` | Pictures use the full width of the terminal, the same as the text of Claude Code (kept for later sessions). This is the default. A picture is never wider than 255 columns. |
-| `/md-preview height` | Shows the image height: the most rows that an image can use. This applies to images that Claude sends and to images that you paste, not to answers. |
+| `/md-preview height` | Shows the image height: the most rows that an image can use. This applies to images (sent or pasted) and to Typst drawings in answers. |
| `/md-preview height half` | An image uses half the terminal height, from 6 to 24 rows (kept for later sessions). This is the default. |
| `/md-preview height full` | An image uses the terminal height less 16 rows (kept for later sessions). The 16 rows are for the row of the file, the text around it and the prompt. |
| `/md-preview height <6–200>` | Sets the most rows that an image can use (kept for later sessions). An image is never taller than with `full`. |
diff --git a/hooks/lib/answer.ts b/hooks/lib/answer.ts
index dd156a4..66eab93 100644
--- a/hooks/lib/answer.ts
+++ b/hooks/lib/answer.ts
@@ -5,44 +5,148 @@
// 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'
-import { finalized, lastText, live, pending, results, S, shown, type Cell, type Env, type Job, type Result } from './state'
-import { fontFit, hashOf, inlineOf, renderKey } from './draw'
+import { BLANK_AFTER_LIVE_MS, BLANK_RESUMED_MS, DEFAULT_THEME, LIVE_STILL_MS, RESULTS_KEPT, SETTLE_MS } from './settings'
+import { epochOpen, finalized, keep, lastKey, lastText, live, pending, results, S, type Env, type Frame, type Job, type Result, type Room } from './state'
+import { fontFit, hashOf, inlineOf, renderKey, sizing } from './draw'
+import { needsRoom } from './markdown'
+import { pictureColumns } from './frame'
+import { pictureRowsFor } from './images'
+import { designInMemory, designKey, loadDesign } from './designs'
+import { resultOf, touchLater } from './typst'
import { enqueue, finalize, forget, waitBlank } from './stream'
+import { extendEpoch } from './epoch'
// `pages`: draw these (with `bytes` over ssh); `blank`: draw an empty box;
// `text`: draw the engine's own row.
-export type Drawing = { kind: 'pages'; result: Result; px: Cell; bytes?: string[] } | { kind: 'blank' } | { kind: 'text' }
+export type Drawing = { kind: 'pages'; result: Result; bytes?: string[] } | { kind: 'blank' } | { kind: 'text' }
-// `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. `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 } = o
- const px = S.cell ?? DEFAULT_CELL
- const textHash = hashOf([text])
+export type PagesInput = {
+ // Keys the text's place (its message, its row).
+ id: string
+ text: string
+ // The terminal now (frameFor): the picture's columns, its cell, the rows
+ // a drawing has room for.
+ frame: Frame
+ env: Env
+ // The text may still grow (an answer); a plan is final when it is drawn,
+ // so it never waits as live.
+ canStream: boolean
+ // The folder relative images start from (a Markdown file's); else the session's.
+ base?: string
+ // Its row is on screen (e.props.onScreen): true compiles first; false is
+ // known off screen (its job does not hold an epoch's commit); undefined:
+ // not known.
+ onScreen?: boolean | undefined
+}
+
+const pt = (v: number) => Math.round(v * 100) / 100
+
+// The keys whose folder was touched in this load (bounded). Not the same as
+// touchLater's set: that one empties at each flush, this one stops a redraw
+// from noting the key again after it.
+const TOUCHED_KEPT = 4096
+const touched = new Set<string>()
+
+// Per id: its text's hash and whether it needs a room, so a redraw of the
+// same text (a scroll) does not hash or scan it again. Bounded as `results`.
+const texts = new Map<string, { text: string; textHash: string; hasRoom: boolean }>()
+function textOf(id: string, text: string) {
+ const was = texts.get(id)
+ if (was && was.text === text) return was
+ const now = { text, textHash: hashOf([text]), hasRoom: needsRoom(text) }
+ keep(texts, id, now, RESULTS_KEPT)
+ return now
+}
+
+// The room for a text's drawings, when it needs one: the room height now,
+// and its design (kept on disk; when missing, the space now, factor 1). A
+// text that is still live reads no file (it changes at each piece): the
+// design in memory, else the space now, recorded only once a final compile
+// of that text succeeds.
+async function roomOf($: EngineInterface, o: { hasRoom: boolean; textHash: string; base?: string; env: Env; rows: number; widthPt: number; rowPt: number; isLive: boolean }): Promise<Room | undefined> {
+ if (!o.hasRoom) return undefined
+ const heightPt = pt(pictureRowsFor(o.rows, S.height) * o.rowPt)
+ const key = designKey(o.textHash, o.base)
+ const kept = o.isLive ? (designInMemory(key) ?? null) : await loadDesign($, o.env.designs, key).catch(() => null)
+ const design = kept ?? { widthPt: pt(o.widthPt), heightPt }
+ return { heightPt, design, designKey: key, isNew: !kept }
+}
+
+// A key compiled in an earlier load (S.onDisk): its pages.json read at once,
+// with no queue and no blank. Null when it can not be read.
+async function fromDisk($: EngineInterface, env: Env, key: string): Promise<Result | null> {
+ if (!S.onDisk.has(key)) return null
+ const dir = `${env.cache}/${key}`
+ const text = await $.fs.read(`${dir}/pages.json`).catch(() => null)
+ const got = text ? resultOf(text) : null
+ if (!got) {
+ S.onDisk.delete(key)
+ return null
+ }
+ touchLater($, dir)
+ keep(results, key, got, RESULTS_KEPT)
+ return got
+}
+
+export async function pagesOf($: EngineInterface, o: PagesInput): Promise<Drawing> {
+ const { id, text, env, base, frame } = o
+ // A row drawn in an open epoch: its rows still come (extendEpoch).
+ if (epochOpen()) extendEpoch($)
+ const { cell, rows } = frame
+ const columns = pictureColumns(frame, env.inline)
+ const { textHash, hasRoom } = textOf(id, text)
const active = S.look ?? { name: DEFAULT_THEME, dir: `${env.root}/render/themes/${DEFAULT_THEME}`, stamp: '0' }
+ const { columnPt } = fontFit(env.metrics, S.size)
+ const { widthPt, rowPt } = sizing(columns, cell, columnPt)
+ // Live (see below), as known before the design is read.
+ const liveNow = () => {
+ const seen = lastText.get(id)
+ return o.canStream && (live.has(id) || (seen !== text && !finalized.has(id) && (S.stepsLive > 0 || seen !== undefined)))
+ }
+ const room = await roomOf($, { hasRoom, textHash, base, env, rows, widthPt, rowPt, isLive: liveNow() })
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, base,
+ textHash, columns, cell, size: S.size, mode: S.theme, termFont: env.termFont,
+ columnPt, templateStamp: env.stamp, look: active, inline: env.inline, base, room,
})
const seen = lastText.get(id)
const changed = seen !== text
lastText.set(id, text)
- const got = results.get(key)
+ const job: Job = {
+ key, requestId: id, text, columns, cell, theme: S.theme, size: S.size, themeDir: active.dir, env, epoch: S.epoch,
+ ...(base ? { base } : {}), ...(room ? { room } : {}), ...(o.onScreen !== undefined ? { onScreen: o.onScreen } : {}),
+ }
+ // The picture drawn last for the same text, at another key.
+ const was = lastKey.get(id)
+ const old = was && was.textHash === textHash && was.key !== key ? results.get(was.key) : undefined
+ // An epoch is open: the row keeps its old picture (at its own box) until
+ // the commit, so all rows swap in one redraw. The target compiles now
+ // (or is read from disk); a result for it, even 'failed', waits.
+ if (epochOpen() && old && old !== 'failed') {
+ if (!results.has(key) && !(await fromDisk($, env, key))) {
+ forget(id)
+ enqueue($, job)
+ }
+ const drawing = await withBytes($, env, old)
+ if (drawing.kind === 'pages') return drawing
+ }
+ const inMemory = results.get(key)
+ const got = inMemory ?? (await fromDisk($, env, key))
if (got === 'failed') {
forget(id)
return { kind: 'text' }
}
if (got) {
+ // A key in use: its folder is touched once per load (the 2-day cleanup
+ // goes by use); fromDisk and compile touch the folders they read.
+ if (inMemory && !touched.has(key)) {
+ if (touched.size >= TOUCHED_KEPT) touched.clear()
+ touched.add(key)
+ touchLater($, `${env.cache}/${key}`)
+ }
forget(id)
- shown.set(id, { textHash, result: got })
- if (!env.inline) return { kind: 'pages', result: got, px }
- const bytes = await inlineOf($, got)
- return bytes ? { kind: 'pages', result: got, px, bytes } : { kind: 'text' }
+ keep(lastKey, id, { key, textHash }, RESULTS_KEPT)
+ return withBytes($, env, got)
}
- 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).
@@ -58,16 +162,21 @@ export async function pagesOf($: EngineInterface, o: { id: string; text: string;
pending.delete(id)
return { kind: 'blank' }
}
- // Final and not drawn yet: compile at once. Same text at another width:
- // the old picture until the new one is ready; else blank for a moment,
- // then the text.
+ // Final and not drawn yet: compile at once. Same text at another size:
+ // the old picture (at its own box) until the new one is ready; else blank
+ // for a moment, then the text.
enqueue($, job)
- const was = shown.get(id)
- if (was && was.textHash === textHash) {
- if (!env.inline) return { kind: 'pages', result: was.result, px }
- const bytes = await inlineOf($, was.result)
- if (bytes) return { kind: 'pages', result: was.result, px, bytes }
+ if (old && old !== 'failed') {
+ const drawing = await withBytes($, env, old)
+ if (drawing.kind === 'pages') return drawing
}
waitBlank($, id, textHash, finalized.has(id) ? BLANK_AFTER_LIVE_MS : BLANK_RESUMED_MS)
return pending.get(id)?.showText ? { kind: 'text' } : { kind: 'blank' }
}
+
+// The pages to draw: over ssh with their bytes (the text when a page can not go).
+async function withBytes($: EngineInterface, env: Env, result: Result): Promise<Drawing> {
+ if (!env.inline) return { kind: 'pages', result }
+ const bytes = await inlineOf($, result)
+ return bytes ? { kind: 'pages', result, bytes } : { kind: 'text' }
+}
diff --git a/hooks/lib/command.ts b/hooks/lib/command.ts
index 0e9642a..988f2ce 100644
--- a/hooks/lib/command.ts
+++ b/hooks/lib/command.ts
@@ -56,7 +56,7 @@ const SUBCOMMANDS = [
{ name: 'off', description: 'show answers as text' },
{ name: 'size', description: `text size, ${MIN_SIZE}-${MAX_SIZE}%` },
{ name: 'width', description: `the most columns a picture takes, ${MIN_WIDTH}-${MAX_WIDTH} or full` },
- { name: 'height', description: `the most rows an image takes, ${MIN_HEIGHT}-${MAX_HEIGHT}, half or full` },
+ { name: 'height', description: `the most rows an image or a Typst drawing takes, ${MIN_HEIGHT}-${MAX_HEIGHT}, half or full` },
{ name: 'theme', description: 'list the themes, or switch to one' },
{ name: 'setup', description: 'iTerm2: add the shell line that turns pictures on' },
] as const
@@ -125,7 +125,7 @@ export function commandSuggestions(
export async function registerCommand($: EngineInterface) {
await $.command.register({
name: 'md-preview',
- description: "Draw Claude's answers as rendered Markdown pictures: on, off, size <80-200> (text size in % of the terminal's), width [40-400|full] (the most columns a picture takes), height [6-200|half|full] (the most rows an image takes), theme [name] (list or switch themes)",
+ description: "Draw Claude's answers as rendered Markdown pictures: on, off, size <80-200> (text size in % of the terminal's), width [40-400|full] (the most columns a picture takes), height [6-200|half|full] (the most rows an image or a Typst drawing takes), theme [name] (list or switch themes)",
argumentHint: '[on|off|size <percent>|width [columns|full]|height [rows|half|full]|theme [name]]',
}).catch(() => undefined)
}
diff --git a/hooks/lib/designs.ts b/hooks/lib/designs.ts
new file mode 100644
index 0000000..ccb5415
--- /dev/null
+++ b/hooks/lib/designs.ts
@@ -0,0 +1,100 @@
+// Designs: the drawing space in pt (page width, room height) at the first
+// compile of a text, so its live Typst blocks keep their share of the screen
+// at any later size, also in a session opened later. One small file per
+// design, named by its hash: `${dir}/<key[0:2]>/<key>`, text `W0 H0`.
+//
+// Host functions:
+// - loadDesign($, dir, key): Promise<Design | null>: the memory map first,
+// else one fs.read of designPath (a read that fails is missing); touch the
+// file (touchLater: batched) when it is read the first time in a load.
+// - noteDesign(key, design): a first compile's design in memory as its job
+// is queued, so a render during the compile uses the same design.
+// - recordDesign($, dir, key, design): Promise<void>: one fs.write only when
+// the file is missing, after the compile ends; a file that is there wins.
+import type { EngineInterface } from 'claude-code'
+
+import { keep, type Design } from './state'
+import { hashOf } from './draw'
+import { touchLater } from './typst'
+
+export type { Design } from './state'
+
+// The key of a text's design: by its text hash and its images' folder.
+export const designKey = (textHash: string, base?: string): string => hashOf(['design', textHash, base ?? ''])
+
+// The file of a design under `dir`, in a folder of its first 2 hex digits.
+export const designPath = (dir: string, key: string): string => `${dir}/${key.slice(0, 2)}/${key}`
+
+// A design file's text `W0 H0` (pt); null when it is not two numbers over 0.
+export function parseDesign(text: string): Design | null {
+ const parts = text.trim().split(/\s+/)
+ if (parts.length !== 2) return null
+ const [widthPt, heightPt] = parts.map(Number)
+ if (!Number.isFinite(widthPt) || !Number.isFinite(heightPt) || widthPt! <= 0 || heightPt! <= 0) return null
+ return { widthPt: widthPt!, heightPt: heightPt! }
+}
+
+// A design as its file's text.
+export const designText = (d: Design): string => `${d.widthPt} ${d.heightPt}`
+
+// The designs known in this load (null: the file is missing). Bounded.
+export const DESIGNS_IN_MEMORY = 4096
+const known = new Map<string, Design | null>()
+// The designs in `known` that a job uses but that are not on disk yet
+// (noteDesign); recordDesign saves them.
+const unsaved = new Set<string>()
+
+// Clears the memory map (for tests).
+export const forgetDesigns = () => {
+ known.clear()
+ unsaved.clear()
+}
+
+// The design of a key in memory only (no read): for a text that is still
+// live, which must not wait for the disk. Undefined when not known.
+export const designInMemory = (key: string): Design | null | undefined => known.get(key)
+
+// A first compile's design, put in memory as the job is queued (before its
+// file is written), so a later render of the same text (a resize while it
+// compiles) uses the same design and not a design of its own.
+export function noteDesign(key: string, design: Design) {
+ if (known.get(key)) return
+ keep(known, key, design, DESIGNS_IN_MEMORY)
+ unsaved.add(key)
+ if (unsaved.size > DESIGNS_IN_MEMORY) unsaved.delete(unsaved.values().next().value!)
+}
+
+// The design of a key: from memory, else one read of its file. A read that
+// fails, or a bad text, is missing. A file read the first time in this load
+// is touched (batched), so the cleanup of old files goes by use.
+export async function loadDesign($: EngineInterface, dir: string, key: string): Promise<Design | null> {
+ if (known.has(key)) return known.get(key) ?? null
+ const path = designPath(dir, key)
+ const text = await $.fs.read(path).catch(() => null)
+ const design = typeof text === 'string' ? parseDesign(text) : null
+ keep(known, key, design, DESIGNS_IN_MEMORY)
+ if (design) touchLater($, path)
+ return design
+}
+
+// Saves a design when its file is missing, after a compile ends. When the
+// file is there (another session wrote it first), the file wins: its design
+// goes in memory instead. Never throws.
+export async function recordDesign($: EngineInterface, dir: string, key: string, design: Design): Promise<void> {
+ try {
+ if (known.get(key) && !unsaved.has(key)) return
+ const path = designPath(dir, key)
+ if (await $.fs.exists(path).catch(() => false)) {
+ const text = await $.fs.read(path).catch(() => null)
+ const kept = typeof text === 'string' ? parseDesign(text) : null
+ if (kept) {
+ keep(known, key, kept, DESIGNS_IN_MEMORY)
+ unsaved.delete(key)
+ return
+ }
+ }
+ await $.fs.write(path, designText(design))
+ keep(known, key, design, DESIGNS_IN_MEMORY)
+ unsaved.delete(key)
+ } catch {}
+}
diff --git a/hooks/lib/draw.tsx b/hooks/lib/draw.tsx
index 7ada607..066ca30 100644
--- a/hooks/lib/draw.tsx
+++ b/hooks/lib/draw.tsx
@@ -1,13 +1,13 @@
// The pictures of an answer: the key of its inputs, the page width and ppi
// that match the terminal's text, where its first line sits, and the
// drawing of its pages beside the reply bullet.
-import type { EngineInterface, RenderComponent, ResolveInput } from 'claude-code'
+import type { EngineInterface, RenderComponent, RenderViewport, ResolveInput } from 'claude-code'
import type { MdPreviewTheme } from '../../types'
-import { BODY_PT, bulletOf, GUTTER, MARGIN_TOP, MAX_IMAGE_ROWS, TEMPLATE_VERSION } from './settings'
-import { INLINE_KEPT, inlined, S, type Cell, type Look, type Metrics, type Result } from './state'
+import { BODY_PT, bulletOf, GUTTER, MARGIN_TOP, TEMPLATE_VERSION } from './settings'
+import { INLINE_KEPT, inlined, S, type Cell, type Look, type Metrics, type Result, type Room } from './state'
import { FENCE } from './markdown'
-import { fitsInline } from './terminal'
+import { fitBox, fitsInline, roomColumns } from './terminal'
// FNV-1a over the parts, twice with different offsets: 16 hex digits.
export function hashOf(parts: readonly (string | number)[]): string {
@@ -66,11 +66,17 @@ export function renderKey(o: {
// 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
+ // Only for a text with a live Typst block or a local image (needsRoom):
+ // the room height and the design. A plain text's key does not change
+ // with the rows.
+ room?: Room
}): string {
+ const { room } = o
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] : []),
+ ...(room ? ['room', room.heightPt, room.design.widthPt, room.design.heightPt] : []),
])
}
@@ -109,13 +115,6 @@ export function alignFirstLine(kind: FirstLine, rowPt: number): { topPt: number;
return { topPt: Math.round(((bulletRow + 0.5) * rowPt - centre) * 100) / 100, bulletRow }
}
-// The rows an Image of this PNG takes when it is drawn `columns` wide. The
-// template pads each page to whole rows, so this rounds (no stretch).
-export function rowsFor(page: { width: number; height: number }, columns: number, px: Cell): number {
- const scale = Math.min(1, (columns * px.width) / page.width)
- return Math.max(1, Math.min(MAX_IMAGE_ROWS, Math.round((page.height * scale) / px.height)))
-}
-
// Over ssh: every page's PNG as base64 for a `{ png }` source, or null when
// a page cannot go (over INLINE_MAX_SIDE or INLINE_MAX_BYTES, or not read),
// so the message shows as text.
@@ -147,26 +146,41 @@ export async function inlineOf($: EngineInterface, result: Result): Promise<stri
// `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 = {}) {
+// The bullet's row when the page is drawn `factor` as wide.
+export function scaledBulletRow(bulletRow: number, factor: number): number {
+ if (factor >= 1) return bulletRow
+ return Math.max(0, Math.round((bulletRow + 0.5) * factor - 0.5))
+}
+
+// `inline`: each page's PNG as base64 (over ssh); else the terminal reads the
+// file. Each page draws at its own box, never stretched. A page wider than
+// the room now (an old one in an open epoch) draws smaller to fit, the
+// bullet scaled too: the engine shifts a wider Image, it does not clip it.
+export function drawPages(
+ $: EngineInterface, e: ResolveInput<RenderComponent, 'terminal'> & { viewport?: RenderViewport }, result: Result, inline?: readonly string[], layout: PagesLayout = {},
+) {
const { Box, Text, Image } = $.ui.resolve(e)
const gutter = layout.gutter ?? GUTTER
+ const room = roomColumns(e.viewport)
+ const first = result.pages[0]
+ const factor = first && first.columns > room ? room / first.columns : 1
return (
<Box flexDirection="row" marginTop={layout.marginTop ?? MARGIN_TOP}>
{gutter > 0 ? (
- <Box width={gutter} flexShrink={0} marginTop={result.bulletRow}>
+ <Box width={gutter} flexShrink={0} marginTop={scaledBulletRow(result.bulletRow, factor)}>
<Text>{layout.bullet ? bulletOf(S.env?.isMac ?? true) : ' '}</Text>
</Box>
) : null}
- <Box flexDirection="column">
+ <Box flexDirection="column" flexShrink={0}>
{result.pages.map((page, i) => {
- const rows = rowsFor(page, columns, px)
+ const box = fitBox(page, room)
+ const shrunk = box.columns !== page.columns
return (
<Image
key={`${layout.keys ?? ''}p${i}`}
- source={inline ? { png: inline[i]! } : { file: page.file, format: 'png', generation: columns * 1000 + rows }}
- columns={columns}
- rows={rows}
+ source={inline ? { png: inline[i]! } : { file: page.file, format: 'png', ...(shrunk ? { generation: box.columns * 1000 + box.rows } : {}) }}
+ columns={box.columns}
+ rows={box.rows}
alt={page.alt}
/>
)
diff --git a/hooks/lib/env.ts b/hooks/lib/env.ts
index a2cbb50..bcf82d0 100644
--- a/hooks/lib/env.ts
+++ b/hooks/lib/env.ts
@@ -1,11 +1,10 @@
// The Env, once per load: the cache folder, Typst, the terminal, its font
-// and cell, the theme and the mode; and the cell measured again when the
-// viewport changes.
+// and Frame (then kept by the Frame watcher), the theme and the mode.
import { atom, update } from 'claude-code'
import type { EngineInterface } from 'claude-code'
import {
- BASE_THEME, DEFAULT_HEIGHT, DEFAULT_SIZE, DEFAULT_THEME, DEFAULT_WIDTH, MAX_HEIGHT, MAX_SIZE, MAX_WIDTH, MIN_HEIGHT, MIN_SIZE, MIN_WIDTH, NO_TYPST,
+ BASE_THEME, DEFAULT_HEIGHT, DEFAULT_SIZE, DESIGNS_KEPT_DAYS, DEFAULT_THEME, DEFAULT_WIDTH, MAX_HEIGHT, MAX_SIZE, MAX_WIDTH, MIN_HEIGHT, MIN_SIZE, MIN_WIDTH, NO_TYPST,
} from './settings'
import { DEFAULT_METRICS, refresh, S, type Env } from './state'
import { resolveMode, settingOf } from './mode'
@@ -14,7 +13,8 @@ import { canDrawIn, isSet } from './terminal'
import { claudeTmpOf } from './images'
import { applyTheme } from './themes'
import { registerCommand } from './command'
-import { measureCell, readHostMode, termFontOf, watchHost } from './host'
+import { readHostMode, termFontOf, watchHost } from './host'
+import { readFrame, setFrame, watchFrame } from './frame'
import { offerSetup } from './setup'
import { findTypst, measureFonts } from './typst'
@@ -22,9 +22,11 @@ import { findTypst, measureFonts } from './typst'
// copy of its own: see state.ts).
const isOn = atom({ plugin: 'md-preview', key: 'isOn' } as const, true)
-// Makes the cache folder, drops key folders not touched for 2 days, and
-// prints the folder and the OS name.
-const CACHE_SH = `d="\${TMPDIR:-/tmp}"; d="\${d%/}/md-preview-$(id -u)"; mkdir -p "$d" && chmod 700 "$d" && { find "$d" -mindepth 1 -maxdepth 1 -type d -mtime +2 ! -name pkg-cache -exec rm -rf {} + 2>/dev/null; printf '%s\\n%s\\n' "$d" "$(uname -s)"; }`
+// Makes the cache folder, drops key folders not touched for 2 days, makes
+// the designs folder (outside the tmp cache) and drops design files not
+// touched for DESIGNS_KEPT_DAYS; prints the cache folder, the OS name and
+// the designs folder.
+const CACHE_SH = `d="\${TMPDIR:-/tmp}"; d="\${d%/}/md-preview-$(id -u)"; g="\${XDG_CACHE_HOME:-$HOME/.cache}/md-preview/designs"; mkdir -p "$d" && chmod 700 "$d" && { find "$d" -mindepth 1 -maxdepth 1 -type d -mtime +2 ! -name pkg-cache -exec rm -rf {} + 2>/dev/null; mkdir -p "$g" 2>/dev/null && find "$g" -type f -mtime +${DESIGNS_KEPT_DAYS} -delete 2>/dev/null; printf '%s\\n%s\\n%s\\n' "$d" "$(uname -s)" "$g"; }`
// Once per load: the cache folder, Typst, the terminal and its font, the
// theme, the cell. A failed setup is tried again on the next call.
@@ -32,8 +34,11 @@ export function setUp($: EngineInterface): Promise<Env> {
S.envLoading ??= (async () => {
await registerCommand($)
const made = await $.process.run(['sh', '-c', CACHE_SH]).catch(() => null)
- const [made1 = '', os = ''] = (made?.stdout ?? '').split('\n')
+ const [made1 = '', os = '', made3 = ''] = (made?.stdout ?? '').split('\n')
const cache = made1.trim() || '/tmp/md-preview'
+ // The key folders on disk now: a key found here is read back at once.
+ const listed = await $.fs.list(cache).catch(() => [])
+ S.onDisk = new Set(listed.filter(entry => entry.kind === 'dir' && entry.name !== 'pkg-cache').map(entry => entry.name))
const program = (await $.env.get('TERM_PROGRAM')) ?? ''
const term = (await $.env.get('TERM')) ?? ''
const ssh = !!(await $.env.get('SSH_CONNECTION')) || !!(await $.env.get('SSH_TTY'))
@@ -59,6 +64,7 @@ export function setUp($: EngineInterface): Promise<Env> {
S.itermProfile = (await $.env.get('ITERM_PROFILE')) || undefined
S.isKitty = /kitty/i.test(term) || !!(await $.env.get('KITTY_WINDOW_ID')) || !!(await $.env.get('KITTY_PID'))
S.isRemote = ssh
+ S.debug = isSet(await $.env.get('MD_PREVIEW_DEBUG'))
S.isIterm = isItermIn({
program,
profile: S.itermProfile,
@@ -82,7 +88,8 @@ export function setUp($: EngineInterface): Promise<Env> {
: Number.isInteger(height) && Number(height) >= MIN_HEIGHT && Number(height) <= MAX_HEIGHT ? Number(height) : DEFAULT_HEIGHT
if ((await $.store.get('enabled').catch(() => undefined)) === false) await update($, isOn, () => false).catch(() => undefined)
const isMac = os.trim() === 'Darwin'
- S.cell = await measureCell($)
+ setFrame(await readFrame($))
+ if (canDraw) watchFrame($)
const typst = await findTypst($)
if (!typst) {
try {
@@ -91,6 +98,7 @@ export function setUp($: EngineInterface): Promise<Env> {
}
const termFont = await termFontOf($, program, isMac).catch(() => '')
const home = (await $.env.get('HOME')) ?? ''
+ const designs = made3.trim() || (home ? `${home}/.cache/md-preview/designs` : `${cache}/designs`)
const stored = await $.store.get('theme-name').catch(() => undefined)
const wanted = typeof stored === 'string' && stored ? stored : DEFAULT_THEME
const applied = await applyTheme($, root, home, wanted).catch(() => null)
@@ -116,6 +124,7 @@ export function setUp($: EngineInterface): Promise<Env> {
isMac,
}),
termFont,
+ designs,
metrics: typst ? await measureFonts($, typst, root, cache, termFont, S.look?.dir ?? `${root}/render/themes/${BASE_THEME}`) : DEFAULT_METRICS,
}
refresh($)
@@ -126,21 +135,3 @@ export function setUp($: EngineInterface): Promise<Env> {
})
return S.envLoading
}
-
-// A changed viewport may mean a changed font size: measure the cell again,
-// at most once a second, and redraw only when it really changed.
-export function noteViewport($: EngineInterface, view: { columns: number; rows: number }) {
- const seen = `${view.columns}x${view.rows}`
- if (seen === S.lastView) return
- const isFirst = S.lastView === ''
- S.lastView = seen
- if (isFirst || !S.env) return
- S.measureTimer?.cancel()
- S.measureTimer = $.clock.after(1000, () => {
- void measureCell($).then(next => {
- if (next?.width === S.cell?.width && next?.height === S.cell?.height) return
- S.cell = next
- refresh($)
- })
- })
-}
diff --git a/hooks/lib/epoch.ts b/hooks/lib/epoch.ts
new file mode 100644
index 0000000..fc31d3a
--- /dev/null
+++ b/hooks/lib/epoch.ts
@@ -0,0 +1,126 @@
+// The epoch: one for each new target (a settled resize, a font size change,
+// a setting, the light or dark mode). It stops the compiles of the old
+// target, and its pictures swap in all at once: a job of the open epoch that
+// ends does not redraw; the epoch commits (S.shown = S.frame, with the
+// height setting of the target, one redraw) when its jobs on screen are done. A burst (a drag not quiet yet) holds the
+// jobs and the commit.
+import type { EngineInterface } from 'claude-code'
+
+import { COMMIT_MAX_MS, COMMIT_MIN_MS } from './settings'
+import { converting, epochOpen, queue, refresh, running, S, type Frame, type Job } from './state'
+import { traceDebug } from './log'
+
+// The open epoch: `ready` once COMMIT_MIN_MS passed with no new activity
+// (a row drawn, a job enqueued: extendEpoch), `overdue` once COMMIT_MAX_MS
+// passed since it began (it commits with jobs still running). A new epoch
+// has new flags and cancels the old timers.
+let ready = false
+let overdue = false
+let minTimer: { cancel: () => void } | null = null
+let maxTimer: { cancel: () => void } | null = null
+// For the trace: when the open epoch began, and the jobs enqueued in it.
+let begunAt = 0
+let jobsIn = 0
+
+// Begins a new epoch for `frame` (else the target now): stops every compile
+// that runs (it does not wait for them), empties the queue, sets the target
+// and redraws once. The rows draw their old pictures and enqueue the target.
+export function beginEpoch($: EngineInterface, frame?: Frame | null) {
+ S.resizing = false
+ S.missed = false
+ const cancelled = running.size
+ const dropped = queue.length
+ for (const { cancel } of running.values()) {
+ try {
+ cancel()
+ } catch {}
+ }
+ queue.length = 0
+ const target = frame ?? S.frame
+ if (target) S.frame = { ...target }
+ const epoch = ++S.epoch
+ begunAt = Date.now()
+ jobsIn = 0
+ const f = S.frame
+ traceDebug($, `epoch ${epoch} begin: target ${f ? `${f.columns}x${f.rows} cell ${f.cell.width}x${f.cell.height}` : 'none'}; cancelled ${cancelled} running, dropped ${dropped} queued`)
+ ready = false
+ overdue = false
+ maxTimer?.cancel()
+ maxTimer = $.clock.after(COMMIT_MAX_MS, () => {
+ if (S.epoch !== epoch) return
+ overdue = true
+ maybeCommit($)
+ })
+ armReady($)
+ refresh($)
+}
+
+// The rows of the open epoch still come (each draws again after the
+// epoch's redraw, after round trips to the host): its COMMIT_MIN_MS starts
+// again, so a row drawn late still swaps at the commit. COMMIT_MAX_MS still
+// counts from the begin. Nothing once it is ready.
+export function extendEpoch($: EngineInterface) {
+ if (epochOpen() && !ready) armReady($)
+}
+
+// A job was enqueued (for the trace).
+export function jobQueued(job: Job) {
+ if (job.epoch === S.epoch && epochOpen()) jobsIn++
+}
+
+// (Re)starts the open epoch's COMMIT_MIN_MS timer.
+function armReady($: EngineInterface) {
+ const epoch = S.epoch
+ minTimer?.cancel()
+ minTimer = $.clock.after(COMMIT_MIN_MS, () => {
+ if (S.epoch !== epoch) return
+ ready = true
+ maybeCommit($)
+ })
+}
+
+// A burst began: no job starts and the epoch does not commit until
+// releaseJobs.
+export function holdJobs() {
+ S.resizing = true
+}
+
+// The burst ended with no new target: a job that ended during it redraws
+// now (with no epoch open), and a commit that came due happens now.
+export function releaseJobs($: EngineInterface) {
+ S.resizing = false
+ if (S.missed && !epochOpen()) refresh($)
+ S.missed = false
+ maybeCommit($)
+}
+
+// A job ended (its result is stored): during a burst it is noted; in an open
+// epoch the epoch may commit; else its row redraws.
+export function jobDone($: EngineInterface) {
+ if (S.resizing) S.missed = true
+ else if (epochOpen()) maybeCommit($)
+ else refresh($)
+}
+
+// A job holds the commit when it is of the open epoch and its row is not
+// known to be off screen.
+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 or WebP
+// converts.
+function maybeCommit($: EngineInterface) {
+ if (S.resizing || !epochOpen()) return
+ if (!overdue) {
+ if (!ready || converting.size > 0 || queue.some(holds)) return
+ for (const { job } of running.values()) if (holds(job)) return
+ }
+ if (S.debug) {
+ const left = (jobs: Iterable<Job>) => [...jobs].filter(job => job.epoch === S.epoch).length
+ traceDebug($, `epoch ${S.epoch} commit after ${Date.now() - begunAt} ms (${overdue ? 'overdue' : 'ready'}): ${jobsIn} jobs queued, ${left(queue)} waiting, ${left([...running.values()].map(r => r.job))} running, ${converting.size} converting`)
+ }
+ S.shown = S.frame
+ S.shownHeight = S.height
+ S.shownEpoch = S.epoch
+ refresh($)
+}
diff --git a/hooks/lib/frame.ts b/hooks/lib/frame.ts
new file mode 100644
index 0000000..a978742
--- /dev/null
+++ b/hooks/lib/frame.ts
@@ -0,0 +1,255 @@
+// The Frame: the terminal's columns, rows and cell, the one source of truth
+// for every size. A small watcher prints the tty size (TIOCGWINSZ) at each
+// SIGWINCH that changed it; the render hooks note the viewport (the
+// transcript can be narrower than the tty). Both restart one quiet timer:
+// during a burst no job starts, and once it is quiet one tty read settles
+// it. A changed Frame begins an epoch (epoch.ts), so a drag or a font size
+// change compiles once and its pictures swap in one redraw.
+import type { EngineInterface } from 'claude-code'
+
+import { BASE_THEME, DEFAULT_CELL, RESIZE_QUIET_MS } from './settings'
+import { DEFAULT_METRICS, S, type Frame, type Metrics } from './state'
+import { beginEpoch, holdJobs, releaseJobs } from './epoch'
+import { pump } from './stream'
+import { columnsFor, sizeOf } from './terminal'
+import { CELL_SH, FRAME_PL, termFontOf } from './host'
+import { measureFonts } from './typst'
+
+export type { Cell, Frame } from './state'
+
+// The viewport a render hook gives: its columns and rows.
+export type View = { columns: number; rows: number }
+
+// One watcher line `rows cols xpixel ypixel` as a Frame; null when it is not
+// 4 whole numbers or its cell can not be right (the rule of sizeOf: no
+// pixels, or a cell under 4 or over 64 px wide).
+export function frameOfLine(line: string): Frame | null {
+ if (!/^\d+ \d+ \d+ \d+$/.test(line.trim())) return null
+ const size = sizeOf(line)
+ return size?.cell ? { columns: size.columns, rows: size.rows, cell: size.cell } : null
+}
+
+// What changed from `a` to `b`: the cell (a font size change), else the
+// columns, else the rows. No `a` (the first read) is a cell change.
+export function frameChange(a: Frame | null, b: Frame): 'none' | 'cell' | 'columns' | 'rows' {
+ if (!a || a.cell.width !== b.cell.width || a.cell.height !== b.cell.height) return 'cell'
+ if (a.columns !== b.columns) return 'columns'
+ if (a.rows !== b.rows) return 'rows'
+ return 'none'
+}
+
+// Joins a child's output pieces into lines: each call gives the lines that
+// the piece ends, and keeps the rest for the next piece.
+export function lineSplitter(): (piece: string) => string[] {
+ let rest = ''
+ return piece => {
+ const lines = (rest + piece).split('\n')
+ rest = lines.pop() ?? ''
+ return lines.map(line => line.replace(/\r$/, ''))
+ }
+}
+
+// The target Frame (S.frame): keys and compiles use it. With no Frame yet:
+// the viewport (else 80 x 48) and DEFAULT_CELL.
+export function frameFor(view?: View): Frame {
+ return S.frame ?? composeFrame(null, view ?? null)
+}
+
+// The Frame whose pictures are on screen (S.shown): a picture drawn now
+// sizes from it, so all of them swap together when the epoch commits.
+export function shownFor(view?: View): Frame {
+ return S.shown ?? frameFor(view)
+}
+
+// The columns a Markdown picture (an answer, a plan, a sent file) takes in
+// `frame`: columnsFor with /md-preview width; over ssh (`inline`) also at
+// most what a `{ png }` source can be wide in its cell.
+export const pictureColumns = (frame: Frame, inline: boolean): number =>
+ columnsFor(frame.columns, S.width, inline ? frame.cell : null)
+
+// The Frame of a tty read and a viewport: the tty's with its columns at
+// most the viewport's. With no tty: the viewport (else 80 x 48) and
+// DEFAULT_CELL.
+export function composeFrame(tty: Frame | null, view: View | null): Frame {
+ if (!tty) return { columns: view?.columns ?? 80, rows: view?.rows ?? 48, cell: DEFAULT_CELL }
+ return view && view.columns < tty.columns ? { ...tty, columns: view.columns } : tty
+}
+
+// The last viewport a render hook noted; null before the first.
+const viewNow = (): View | null => (S.viewColumns === null ? null : { columns: S.viewColumns, rows: S.viewRows ?? 48 })
+
+// One read of the tty size as a Frame; null when it fails (no tty, no
+// pixels).
+export async function readFrame($: EngineInterface): Promise<Frame | null> {
+ const tty = await $.process.run(['sh', '-c', CELL_SH], { timeoutMs: 5000 }).catch(() => null)
+ return tty?.exitCode === 0 ? frameOfLine(tty.stdout) : null
+}
+
+// Sets the tty's Frame at once, as the target and the Frame on screen
+// (setUp's first read, before anything draws: no epoch), with the height
+// setting read; a later change is settled first (noteTty).
+export function setFrame(frame: Frame | null) {
+ S.shownHeight = S.height
+ if (!frame) return
+ S.tty = frame
+ S.frame = S.shown = composeFrame(frame, viewNow())
+}
+
+// The quiet timer, with the clock given: the first input of a burst calls
+// `onStart`; each input waits `ms` again; when none came for `ms`,
+// `onQuiet`. Its `stale()` is true once a newer input came (that input's
+// quiet settles instead).
+export function quietTimer(o: {
+ ms: number
+ after: (ms: number, fn: () => void) => { cancel: () => void }
+ onStart: () => void
+ onQuiet: (stale: () => boolean) => void
+}): () => void {
+ let wait: { cancel: () => void } | null = null
+ let inputs = 0
+ return () => {
+ inputs++
+ if (!wait) o.onStart()
+ wait?.cancel()
+ wait = o.after(o.ms, () => {
+ wait = null
+ const seen = inputs
+ o.onQuiet(() => inputs !== seen)
+ })
+ }
+}
+
+// The one quiet timer of the tty and the viewport (started with the module).
+let poke: (() => void) | null = null
+function burst($: EngineInterface) {
+ poke ??= quietTimer({
+ ms: RESIZE_QUIET_MS,
+ after: (ms, fn) => $.clock.after(ms, fn),
+ onStart: holdJobs,
+ onQuiet: stale => void settle($, stale),
+ })
+ poke()
+}
+
+// A font change found while a newer input came: the next settle begins an
+// epoch for it even when its Frame is the same.
+let refonted = false
+
+// The burst is quiet: one tty read (none with no tty), the Frame of it and
+// the viewport, and the compare. A new cell (a font size change) reads the
+// fonts first, so it is one epoch. A changed Frame or font begins an epoch;
+// else the held jobs go on (pump). When a newer input came during a read,
+// it stops: that input's quiet settles.
+async function settle($: EngineInterface, stale: () => boolean) {
+ try {
+ const tty = S.tty ? ((await readFrame($).catch(() => null)) ?? S.tty) : null
+ if (stale()) return
+ S.tty = tty
+ const target = composeFrame(tty, viewNow())
+ const change = frameChange(S.frame, target)
+ if (change === 'cell' && S.frame) {
+ refonted = (await refont($).catch(() => false)) || refonted
+ if (stale()) return
+ }
+ if (change !== 'none' || refonted) {
+ refonted = false
+ beginEpoch($, target)
+ } else releaseJobs($)
+ } catch {
+ if (stale()) return
+ releaseJobs($)
+ }
+ pump($)
+}
+
+// A new tty value from the watcher; a bad one (null) and the value known
+// (the watcher's first line) are dropped.
+export function noteTty($: EngineInterface, frame: Frame | null) {
+ if (!frame || (S.tty && frameChange(S.tty, frame) === 'none')) return
+ S.tty = frame
+ burst($)
+}
+
+// The viewport, from a render hook. The first one applies at once (nothing
+// was drawn with a viewport yet); a change is settled with the tty's, so the
+// hooks draw the settled Frame until then. With a tty, only its columns
+// count (the rows are the tty's).
+export function noteView($: EngineInterface, view: View) {
+ if (view.columns === S.viewColumns && (S.tty || view.rows === S.viewRows)) return
+ const first = S.viewColumns === null || !S.frame
+ const counts = first || !S.tty || view.columns !== S.viewColumns
+ S.viewColumns = view.columns
+ S.viewRows = view.rows
+ if (first) S.frame = S.shown = composeFrame(S.tty, view)
+ else if (counts) burst($)
+}
+
+// The watcher (started once per load: a hot reload kills the child with the
+// old module).
+let watching = false
+
+// Starts the Frame watcher: one long-lived child (the engine kills it when
+// the module unloads). When it can not start, or it ends, nothing takes its
+// place: a viewport change still reads the tty once it is quiet.
+export function watchFrame($: EngineInterface) {
+ if (watching) return
+ watching = true
+ try {
+ void followWatcher($.process.spawn({ argv: ['perl', '-e', FRAME_PL] }), f => noteTty($, f))
+ } catch {}
+}
+
+// Reads the watcher's pieces as lines, each to `note` as a Frame (null when
+// bad), until it ends: 'no tty' when it exits 1, else 'failed' (it did not
+// start: the first pull rejects; or it ended in another way).
+export async function followWatcher(
+ child: AsyncIterator<{ stream: 'stdout' | 'stderr'; text: string }, { code: number | null } | undefined>,
+ note: (frame: Frame | null) => void,
+): Promise<'no tty' | 'failed'> {
+ const lines = lineSplitter()
+ try {
+ for (;;) {
+ const got = await child.next()
+ if (got.done) return got.value?.code === 1 ? 'no tty' : 'failed'
+ if (got.value.stream !== 'stdout') continue
+ for (const line of lines(got.value.text)) note(frameOfLine(line))
+ }
+ } catch {
+ return 'failed'
+ }
+}
+
+// The cell changed: read the terminal's font and the fonts' metrics again.
+// True when either changed (the caller begins the epoch). A failed read
+// ('' or the defaults of measureFonts) keeps the value known. One read at a
+// time; a change while it runs reads once more.
+let fonting: Promise<boolean> | null = null
+let fontAgain = false
+export function refont($: EngineInterface): Promise<boolean> {
+ if (fonting) {
+ fontAgain = true
+ return fonting
+ }
+ fonting = (async () => {
+ let changed = false
+ do {
+ fontAgain = false
+ const env = S.env
+ if (!env) return changed
+ const termFont = (await termFontOf($, S.termProgram, env.isMac).catch(() => '')) || env.termFont
+ const themeDir = S.look?.dir ?? `${env.root}/render/themes/${BASE_THEME}`
+ const read = env.typst ? await measureFonts($, env.typst, env.root, env.cache, termFont, themeDir).catch(() => DEFAULT_METRICS) : env.metrics
+ const metrics = read === DEFAULT_METRICS ? env.metrics : read
+ if (termFont === env.termFont && sameMetrics(metrics, env.metrics)) continue
+ env.termFont = termFont
+ env.metrics = metrics
+ changed = true
+ } while (fontAgain)
+ return changed
+ })().finally(() => {
+ fonting = null
+ })
+ return fonting
+}
+
+const sameMetrics = (a: Metrics, b: Metrics) => JSON.stringify(a) === JSON.stringify(b)
diff --git a/hooks/lib/host.ts b/hooks/lib/host.ts
index d2c6862..99d51a5 100644
--- a/hooks/lib/host.ts
+++ b/hooks/lib/host.ts
@@ -1,11 +1,12 @@
-// Work on the host: the shell snippets md-preview runs, the cell size, the
-// terminal's font, and light or dark for auto (the terminal's settings, then
+// Work on the host: the shell snippets md-preview runs, the tty size (one
+// read, and the Frame watcher's loop), the terminal's font, and light or dark for auto (the terminal's settings, then
// COLORFGBG, then the OS appearance), read again by a poll.
import type { EngineInterface } from 'claude-code'
import type { MdPreviewTheme } from '../../types'
import { HOST_CHECK_MS, HOST_POLL_MS, MODES } from './settings'
-import { refresh, S, type Cell } from './state'
+import { S } from './state'
+import { beginEpoch } from './epoch'
import { luminanceOf, modeOfColorFgBg, modeOfGnome, modeOfLuminance, modeOfMacAppearance, parseOsc11, resolveMode, type HostMode } from './mode'
import {
cmuxAppearanceOf, cmuxSettingsOf, ghosttyBackgroundOf, ghosttyFontOf, ghosttyHasColors, ghosttyThemePaths, ghosttyThemesOf,
@@ -13,10 +14,36 @@ import {
kittyConfigDirsOf, kittyEntriesOf, kittyFontOf, kittySchemeOfGnome, kittyValueOf, parseFontSpec, rioBackgroundOf,
rioConfigDirOf, rioFontOf, rioForcedOf, rioThemeNamesOf, rioThemePath, tomlStringsOf, type KittyEntries,
} from './terminals'
-import { cellOf } from './terminal'
import { firstLine } from './markdown'
-const CELL_SH = `perl -e 'open(T, "</dev/tty") or exit 1; my $w = " " x 8; ioctl(T, ($^O eq "darwin" ? 0x40087468 : 0x5413), $w) or exit 1; print join(" ", unpack("S4", $w))'`
+// One tty size read: `rows cols xpixel ypixel` (TIOCGWINSZ); exit 1 with no tty.
+export const CELL_SH = `perl -e 'open(T, "</dev/tty") or exit 1; my $w = " " x 8; ioctl(T, ($^O eq "darwin" ? 0x40087468 : 0x5413), $w) or exit 1; print join(" ", unpack("S4", $w))'`
+// The Frame watcher (frame.ts): prints a line `rows cols xpixel ypixel`
+// at start and at each change. It sleeps in sigsuspend with SIGWINCH and
+// SIGALRM blocked outside it, so a SIGWINCH that comes while it reads is
+// kept for the next sleep (never lost), and it does no work between
+// signals: no poll. Each 10 s an alarm wakes it to see that its parent
+// still runs. Exit 1 when /dev/tty does not open; exit 0 when the parent
+// dies (its parent id changes) or stdout breaks.
+export const FRAME_PL = [
+ 'use POSIX (); use Config;',
+ 'my %n; @n{split " ", $Config{sig_name}} = split " ", $Config{sig_num};',
+ 'open(my $t, "<", "/dev/tty") or exit 1;',
+ 'my $req = $^O eq "darwin" ? 0x40087468 : 0x5413;',
+ 'my $parent = getppid(); my $last = ""; $| = 1;',
+ '$SIG{PIPE} = sub { exit 0 }; $SIG{WINCH} = sub {}; $SIG{ALRM} = sub {};',
+ 'POSIX::sigprocmask(POSIX::SIG_BLOCK(), POSIX::SigSet->new($n{WINCH}, $n{ALRM}));',
+ 'my $none = POSIX::SigSet->new();',
+ 'while (1) {',
+ ' my $w = " " x 8;',
+ ' if (ioctl($t, $req, $w)) {',
+ ' my $line = join(" ", unpack("S4", $w));',
+ ' if ($line ne $last) { print "$line\\n" or exit 0; $last = $line; }',
+ ' }',
+ ' exit 0 if getppid() != $parent;',
+ ' alarm(10); POSIX::sigsuspend($none);',
+ '}',
+].join(' ')
const ITERM_BOOKMARKS_SH = `defaults export com.googlecode.iterm2 - | plutil -extract "New Bookmarks" json -o - -`
const ITERM_DEFAULT_SH = `defaults read com.googlecode.iterm2 "Default Bookmark Guid"`
// A PostScript name (argv[0]) to its family name.
@@ -46,11 +73,6 @@ export const USE_OSC11 = false
export const PROBE_RUNS = 5
export const HEADERS_SH = `for f in "$@"; do head -c 24 "$f" | od -An -v -tx1; echo @; done`
-export async function measureCell($: EngineInterface): Promise<Cell | null> {
- const tty = await $.process.run(['sh', '-c', CELL_SH], { timeoutMs: 5000 }).catch(() => null)
- return tty?.exitCode === 0 ? cellOf(tty.stdout) : null
-}
-
// The terminal's font family: iTerm2's profile font, Ghostty's font-family,
// kitty's font_family, Rio's [fonts] family; '' elsewhere or when it can't
// be read.
@@ -290,12 +312,13 @@ export async function pollHost($: EngineInterface) {
showMode($)
}
-// Draws in the mode the setting and the OS give, when it changed.
+// Draws in the mode the setting and the OS give, when it changed: a new
+// epoch, so all pictures swap to the new mode in one redraw.
export function showMode($: EngineInterface) {
const next = resolveMode(S.setting, S.host)
if (next === S.theme) return
S.theme = next
- refresh($)
+ beginEpoch($)
}
// Polls the OS appearance while the setting is auto, and only then.
diff --git a/hooks/lib/images.ts b/hooks/lib/images.ts
index bfc232a..6283c65 100644
--- a/hooks/lib/images.ts
+++ b/hooks/lib/images.ts
@@ -6,17 +6,22 @@ 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'
-// The most rows a picture under a row takes, by `height` (/md-preview
-// height): half the viewport within PICTURE_MIN_ROWS to PICTURE_MAX_ROWS
-// (half); the viewport less PICTURE_ROOM_ROWS (full); or a number, at most
-// as much as full. Never under PICTURE_MIN_ROWS or over MAX_IMAGE_ROWS.
-export function pictureRowsFor(viewportRows: number | undefined, height: Height): number {
- const view = viewportRows ?? 2 * PICTURE_MAX_ROWS
+// The most rows a picture under a row (or a drawing's room) takes in a
+// terminal of `terminalRows` rows (frameFor(...).rows), by `height` (/md-preview
+// height): half the rows within PICTURE_MIN_ROWS to PICTURE_MAX_ROWS
+// (half); the rows less PICTURE_ROOM_ROWS (full); or a number, at most as
+// much as full. Never under PICTURE_MIN_ROWS or over MAX_IMAGE_ROWS.
+export function pictureRowsFor(terminalRows: number | undefined, height: Height): number {
+ const view = terminalRows ?? 2 * PICTURE_MAX_ROWS
const full = view - PICTURE_ROOM_ROWS
const rows = height === 'half' ? Math.min(PICTURE_MAX_ROWS, Math.floor(view / 2)) : height === 'full' ? full : Math.min(height, full)
return Math.min(MAX_IMAGE_ROWS, Math.max(PICTURE_MIN_ROWS, rows))
}
+// A row's onScreen (e.props.onScreen) as a job's: null (the terminal holds
+// the row off screen) is false, a range is true, none is not known.
+export const onScreenOf = (v: unknown): boolean | undefined => (v === null ? false : v ? true : undefined)
+
// The cells a picture of `size` pixels takes: its own size or smaller (never
// larger), at most `columns` wide and `rows` tall, the aspect kept.
export function pictureCells(size: { width: number; height: number }, columns: number, rows: number, px: Cell): { columns: number; rows: number } {
diff --git a/hooks/lib/log.ts b/hooks/lib/log.ts
new file mode 100644
index 0000000..f42498d
--- /dev/null
+++ b/hooks/lib/log.ts
@@ -0,0 +1,14 @@
+// The debug log: `debug.log` in the cache folder.
+import type { EngineInterface } from 'claude-code'
+
+import { S } from './state'
+
+export async function logDebug($: EngineInterface, cache: string, text: string) {
+ const stamp = new Date().toISOString()
+ await $.process.run(['sh', '-c', 'cat >> "$1"', 'sh', `${cache}/debug.log`], { stdin: `[${stamp}] ${text.trimEnd()}\n` }).catch(() => undefined)
+}
+
+// A trace line, only with MD_PREVIEW_DEBUG set (S.debug, read in setUp).
+export function traceDebug($: EngineInterface, text: string) {
+ if (S.debug && S.env) void logDebug($, S.env.cache, text)
+}
diff --git a/hooks/lib/markdown.ts b/hooks/lib/markdown.ts
index 2e7cc46..26db1fa 100644
--- a/hooks/lib/markdown.ts
+++ b/hooks/lib/markdown.ts
@@ -58,14 +58,17 @@ export function blocksOf(md: string): Block[] {
return blocks
}
-// A rough count of the rows a block takes once drawn `columns` wide.
-export function rowsOfBlock(block: Block, columns: number): number {
+// A rough count of the rows a block takes once drawn `columns` wide, its
+// text at `size` percent (/md-preview size): fewer characters a row, and
+// taller lines.
+export function rowsOfBlock(block: Block, columns: number, size = 100): number {
const isCode = !!block.fence
- const perRow = columns * (isCode ? 1.0 : 1.15)
+ const scale = size / 100
+ const perRow = (columns / scale) * (isCode ? 1.0 : 1.15)
let rows = 1
for (const line of block.lines) {
- rows += Math.ceil(Math.max(1, line.length) / perRow) * (isCode ? 1.1 : 1.3)
- if (/^#{1,2}\s/.test(line)) rows += 1.5
+ rows += Math.ceil(Math.max(1, line.length) / perRow) * (isCode ? 1.1 : 1.3) * scale
+ if (/^#{1,2}\s/.test(line)) rows += 1.5 * scale
}
if (block.fence && isTypstInfo(block.fence.info)) rows += 20
return rows
@@ -79,7 +82,8 @@ const FOOTNOTE_DEF = /^ {0,3}\[\^[^\]]+\]:/
// fences of the same language; a typst fence always stays whole. A block that
// starts indented (a list item's continuation) never starts a segment. Text
// with footnotes stays one segment; link definitions go into every segment.
-export function splitSegments(md: string, columns: number, budget = SEGMENT_ROWS): string[] {
+// `size`: the text size percent the rows are counted at.
+export function splitSegments(md: string, columns: number, budget = SEGMENT_ROWS, size = 100): string[] {
const blocks = blocksOf(md)
if (!blocks.length) return []
const outside = blocks.filter(b => !b.fence).flatMap(b => b.lines)
@@ -89,9 +93,9 @@ export function splitSegments(md: string, columns: number, budget = SEGMENT_ROWS
const pieces: Block[] = []
for (const block of blocks) {
const { fence } = block
- if (fence && !isTypstInfo(fence.info) && rowsOfBlock(block, columns) > budget && block.lines.length > 2) {
+ if (fence && !isTypstInfo(fence.info) && rowsOfBlock(block, columns, size) > budget && block.lines.length > 2) {
const body = block.lines.slice(1, -1)
- const per = Math.max(1, Math.floor(budget / Math.max(1.1, rowsOfBlock(block, columns) / block.lines.length)) - 2)
+ const per = Math.max(1, Math.floor(budget / Math.max(1.1, rowsOfBlock(block, columns, size) / block.lines.length)) - 2)
for (let i = 0; i < body.length; i += per) {
pieces.push({ lines: [block.lines[0]!, ...body.slice(i, i + per), fence.mark], fence })
}
@@ -101,7 +105,7 @@ export function splitSegments(md: string, columns: number, budget = SEGMENT_ROWS
const segments: Block[][] = [[]]
let used = 0
for (const piece of pieces) {
- const need = rowsOfBlock(piece, columns)
+ const need = rowsOfBlock(piece, columns, size)
const canCut = !/^\s/.test(piece.lines[0] ?? '')
if (used + need > budget && segments.at(-1)!.length && canCut) {
segments.push([])
@@ -115,6 +119,23 @@ export function splitSegments(md: string, columns: number, budget = SEGMENT_ROWS
return texts.map(t => `${t}\n\n${defs.filter(d => !t.includes(d)).join('\n')}`.trimEnd())
}
+// A segment whose page came out taller than an Image can be, cut in two by
+// the same rules (at half its rows); one piece when it can not be cut.
+export function splitInTwo(md: string, columns: number, size = 100): string[] {
+ const rows = blocksOf(md).reduce((n, block) => n + rowsOfBlock(block, columns, size), 0)
+ return splitSegments(md, columns, Math.max(1, Math.ceil(rows / 2)), size)
+}
+
+// Whether a text needs the room height (it is then in its key): it has a
+// live Typst block or a local image, whose size follows the room.
+export function needsRoom(md: string): boolean {
+ const hasTypst = md.split('\n').some(line => {
+ const m = FENCE.exec(line)
+ return !!m && isTypstInfo(m[3] ?? '')
+ })
+ return hasTypst || localImages(md).length > 0
+}
+
// The local image paths Markdown names outside code fences.
const IMAGE = /!\[([^\]]*)\]\(\s*<?([^)\s>]+)>?(?:\s+"[^"]*")?\s*\)/g
diff --git a/hooks/lib/pictures.tsx b/hooks/lib/pictures.tsx
index 5356e3b..44ad87e 100644
--- a/hooks/lib/pictures.tsx
+++ b/hooks/lib/pictures.tsx
@@ -2,29 +2,55 @@
// 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 type { EngineInterface, FsStat, ImageSource, RenderElement, RenderInput } from 'claude-code'
-import { COMPILE_TIMEOUT_MS, DEFAULT_CELL, GUTTER, PICTURES_KEPT, SENT_TEXT_MAX_BYTES } from './settings'
-import { converted, converting, INLINE_KEPT, inlined, lastConverted, pasteDirs, pictures, refresh, S, sentTexts, type Env } from './state'
-import { columnsFor, fitsInline, INLINE_MAX_BYTES } from './terminal'
-import { convertBox, convertedPath, folderOf, pasteDirOf, pictureCells, pictureRowsFor, type PixelBox, type SentFile } from './images'
+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 { 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 { 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'
+import { frameFor, pictureColumns, shownFor, type Frame } from './frame'
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 }
+// pages (`blank`: an empty space while they compile; an older, wider page
+// draws smaller to fit).
+export type Under = Shown | { drawing: Exclude<Drawing, { kind: 'text' }> }
export type RowInput = RenderInput<'ToolResult' | 'UserMessage', 'terminal'>
+// Where a stat is read: the `done` value the row read and the row's
+// requestId. A row that draws again with no new `done` (a scroll step, a new
+// onScreen) reads each stat once; a new row (the same file sent again)
+// reads it anew. With none given, the file is stat'ed each time.
+export type StatAt = { done: number; row: string }
+const STATS_KEPT = 4096
+let statsDone: number | undefined
+const stats = new Map<string, Promise<FsStat | null>>()
+function statOf($: EngineInterface, file: string, at?: StatAt): Promise<FsStat | null> {
+ if (!at) return $.fs.stat(file).catch(() => null)
+ if (statsDone !== at.done || stats.size >= STATS_KEPT) {
+ stats.clear()
+ statsDone = at.done
+ }
+ const key = `${at.row}\n${file}`
+ let got = stats.get(key)
+ if (!got) {
+ got = $.fs.stat(file).catch(() => null)
+ stats.set(key, got)
+ }
+ return got
+}
+
// A PNG's pixel size from its first 24 bytes, read again only when its stat
// changes; null for a file that is gone or not a PNG.
-export async function pictureOf($: EngineInterface, file: string): Promise<Picture | null> {
- const st = await $.fs.stat(file).catch(() => null)
+export async function pictureOf($: EngineInterface, file: string, at?: StatAt): Promise<Picture | null> {
+ const st = await statOf($, file, at)
if (!st || st.kind !== 'file') return null
const stamp = `${st.mtimeMs}:${st.size}`
let kept = pictures.get(file)
@@ -59,27 +85,32 @@ export async function pictureBytes($: EngineInterface, p: Picture): Promise<stri
return base64
}
-// 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[]> {
+// The Images for the files that are PNGs, sized to the Frame on screen.
+// `at`: as statOf.
+export async function shownOf($: EngineInterface, e: RowInput, ready: Env, files: readonly string[], at?: StatAt): Promise<Shown[]> {
const shown: Shown[] = []
for (const file of new Set(files)) {
- const s = await shownOne($, e, ready, file)
+ const s = await shownOne($, e, ready, file, nameOf(file), at)
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)
+// One PNG's Image, sized to the Frame and the height setting on screen
+// (shownFor, S.shownHeight: a new size shows when its epoch commits, with
+// every other picture), and at most as wide as the room now; null when it is not a PNG. `alt` is the file's name
+// (the name of the file it was made of). Its generation follows the file's
+// stat alone: a new box is not a new file.
+export async function shownOne($: EngineInterface, e: RowInput, ready: Env, file: string, alt = nameOf(file), at?: StatAt): Promise<Shown | null> {
+ const p = await pictureOf($, file, at)
if (!p) return null
- const fit = pictureCells(p, columnsFor(e.viewport?.columns, S.width), pictureRowsFor(e.viewport?.rows, S.height), S.cell ?? DEFAULT_CELL)
+ const frame = shownFor(e.viewport)
+ const fit = fitBox(pictureCells(p, pictureColumns(frame, false), pictureRowsFor(frame.rows, S.shownHeight), frame.cell), roomColumns(e.viewport))
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)
+ const generation = Number.parseInt(hashOf([p.stamp]).slice(0, 8), 16)
return { source: { file, format: 'png', generation }, ...fit, alt }
}
@@ -88,15 +119,15 @@ const nameOf = (file: string) => file.split('/').pop() || 'image'
// A JPEG or WebP 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 a refresh
-// draws it. Null with no Typst, or when it fails (the row stays as is).
-export async function convertedOf($: EngineInterface, ready: Env, file: string, box: PixelBox): Promise<string | null> {
+// 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> {
if (!ready.typst) return null
- const st = await $.fs.stat(file).catch(() => null)
+ const st = await statOf($, file, at)
if (!st || st.kind !== 'file') return null
const stamp = `${st.mtimeMs}:${st.size}`
- const last = lastConverted.get(file)
- const before = last?.stamp === stamp ? last.png : null
+ const before = lastPngOf(file, stamp)
const key = `${file}@${stamp}@${box.width}x${box.height}`
if (converted.has(key)) return converted.get(key) ?? before
let run = converting.get(key)
@@ -106,13 +137,28 @@ export async function convertedOf($: EngineInterface, ready: Env, file: string,
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)
- // The refresh one tick later: a run that ends while this row still draws
- // must not be lost.
- if (before) void run.then(() => void $.clock.after(0, () => refresh($)), () => undefined)
+ // 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.
+ if (before || epochOpen()) void run.then(() => void $.clock.after(0, () => jobDone($)), () => undefined)
}
return before ?? run
}
+// The last PNG made of `file` at its stat stamp in this load (any box); 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> {
+ const st = await statOf($, file, at)
+ return !!st && st.kind === 'file' && !!lastPngOf(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)
// Made before (an earlier load): the same file, stamp and box.
@@ -138,63 +184,71 @@ async function convertOnce($: EngineInterface, ready: Env, file: string, stamp:
png = null
}
}
- keep(converted, key, png)
- if (png) keep(lastConverted, file, { stamp, png })
+ keep(converted, key, png, PICTURES_KEPT)
+ if (png) keep(lastConverted, file, { stamp, png }, PICTURES_KEPT)
return png
}
-// Sets a cache entry as the newest; the oldest go past PICTURES_KEPT.
-function keep<T>(cache: Map<string, T>, key: string, value: T) {
- cache.delete(key)
- cache.set(key, value)
- for (const old of cache.keys()) {
- if (cache.size <= PICTURES_KEPT) break
- cache.delete(old)
- }
-}
-
// 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)
+export async function sentTextOf($: EngineInterface, file: string, at?: StatAt): Promise<string | null> {
+ const st = await statOf($, file, at)
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
- keep(sentTexts, file, { stamp, text })
+ keep(sentTexts, file, { stamp, text }, PICTURES_KEPT)
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.
+// 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 or WebP 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 },
+ $: EngineInterface, e: RowInput, o: { ready: Env; markdown: Env | null; files: readonly SentFile[]; id: string; at?: StatAt },
): Promise<Under[]> {
- // Over ssh a Markdown file's page must stay INLINE_MAX_SIDE pixels wide at most.
- const columns = columnsFor(e.viewport?.columns, S.width, o.ready.inline ? (S.cell ?? DEFAULT_CELL) : null)
- // The space a picture takes (as in shownOne), which a JPEG or WebP is made to fit.
- const box = convertBox(columns, pictureRowsFor(e.viewport?.rows, S.height), S.cell ?? DEFAULT_CELL)
+ const shown = shownFor(e.viewport)
+ const target = epochOpen() ? frameFor(e.viewport) : null
+ const box = boxOf(shown, o.ready.inline, S.shownHeight)
+ const next = target ? boxOf(target, o.ready.inline, S.height) : null
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
+ const text = o.markdown ? await sentTextOf($, full, o.at) : 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 })
+ const drawing = await pagesOf($, {
+ id: `file:${o.id}:${f.path}`, text, frame: frameFor(e.viewport), env: o.markdown, canStream: false, base: folderOf(full),
+ onScreen: onScreenOf(e.props.onScreen),
+ })
+ if (drawing.kind !== 'text') under.push({ drawing })
continue
}
- const png = f.kind === 'png' ? full : await convertedOf($, o.ready, full, box)
- const shown = png ? await shownOne($, e, o.ready, png, nameOf(full)) : null
- if (shown) under.push(shown)
+ 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
+ }
+ const png = f.kind === 'png' ? full : await convertedOf($, o.ready, full, box, o.at)
+ const picture = png ? await shownOne($, e, o.ready, png, nameOf(full), o.at) : null
+ if (picture) under.push(picture)
}
return under
}
+// The space a picture takes in `frame` with the height setting `height`
+// (as in shownOne), which a JPEG or WebP 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 engine's row, then the pictures under it.
export function underRow($: EngineInterface, e: RowInput, row: RenderElement, under: readonly Under[]) {
const { Box, Image } = $.ui.resolve(e)
@@ -204,11 +258,11 @@ export function underRow($: EngineInterface, e: RowInput, row: RenderElement, un
<Box flexDirection="column" marginLeft={GUTTER}>
{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
+ const { drawing } = 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}-` })}
+ {drawPages($, e, drawing.result, drawing.bytes, { gutter: 0, marginTop: 0, keys: `file${i}-` })}
</Box>
)
})}
diff --git a/hooks/lib/plan.tsx b/hooks/lib/plan.tsx
index 462baf7..199220a 100644
--- a/hooks/lib/plan.tsx
+++ b/hooks/lib/plan.tsx
@@ -8,7 +8,7 @@
// engine's dialog never shows. An allow is honoured for this tool only with
// `updatedInput`, and its `setMode` ends plan mode. The rendered plan is in
// the ExitPlanMode ToolUse row, which the engine draws above the question.
-import type { EngineInterface, PermissionRequestDecision, RenderComponent, RenderElement, ResolveInput } from 'claude-code'
+import type { EngineInterface, PermissionRequestDecision, RenderComponent, RenderElement, RenderViewport, ResolveInput } from 'claude-code'
import { GUTTER, bulletOf } from './settings'
import { S, writesLive } from './state'
@@ -238,18 +238,18 @@ export function scheduleClear($: EngineInterface, plan: string, turnId: string)
// ---- Drawing ------------------------------------------------------------------
-type Terminal = ResolveInput<RenderComponent, 'terminal'>
+type Terminal = ResolveInput<RenderComponent, 'terminal'> & { viewport?: RenderViewport }
// The ExitPlanMode ToolUse row: the engine's row, then the plan's pages (a
// dim line while they compile; the engine's row alone when they fail).
-export function drawPlanUse($: EngineInterface, e: Terminal, row: RenderElement, drawing: Drawing, columns: number): RenderElement {
+export function drawPlanUse($: EngineInterface, e: Terminal, row: RenderElement, drawing: Drawing): RenderElement {
if (drawing.kind === 'text') return row
const { Box, Text } = $.ui.resolve(e)
return (
<Box flexDirection="column">
{row}
{drawing.kind === 'pages' ? (
- drawPages($, e, drawing.result, columns, drawing.px, drawing.bytes, { bullet: true })
+ drawPages($, e, drawing.result, drawing.bytes, { bullet: true })
) : (
<Box marginTop={1} marginLeft={GUTTER}>
<Text dimColor>{PLAN_DRAWING}</Text>
diff --git a/hooks/lib/settings.ts b/hooks/lib/settings.ts
index 288fec4..59e3a60 100644
--- a/hooks/lib/settings.ts
+++ b/hooks/lib/settings.ts
@@ -47,7 +47,11 @@ export const MAX_IMAGE_ROWS = 255
// wide is not trusted.
export const DEFAULT_CELL: Cell = { width: 16, height: 32 }
// Part of every key: bump it when the interface with the template changes.
-export const TEMPLATE_VERSION = '7'
+// The template's inputs for the room of a drawing (all in pt): `height` the
+// room height now, `design-w` and `design-h` the design (the space at the
+// first compile of the text). Its live Typst blocks scale by
+// min(content width / design-w, height / design-h).
+export const TEMPLATE_VERSION = '8'
export const COMPILE_TIMEOUT_MS = 20000
export const ALT_CHARS = 200
// Where Typst is when the login shell's PATH does not find it. `~` is $HOME.
@@ -66,14 +70,16 @@ export const BASE_THEME = 'vscode'
export const DEFAULT_THEME = 'vscode-modern'
// The two modes a theme has syntax colours for.
export const MODES = ['dark', 'light'] as const
-// A picture under a row (an image Claude sends, an image the user pastes):
-// at most this many rows tall, and at most half the viewport.
+// A picture under a row (an image Claude sends, an image the user pastes)
+// and a drawing's room: at most this many rows tall, and at most half the
+// terminal's rows.
export const PICTURE_MAX_ROWS = 24
export const PICTURE_MIN_ROWS = 6
-// `/md-preview height`: the most rows an image takes (sent or pasted; not a
-// Markdown page). `half`, the default: as above. `full`: the viewport less
-// PICTURE_ROOM_ROWS. A number: that many rows, at most as many as `full`.
-// Never under PICTURE_MIN_ROWS.
+// `/md-preview height`: the most rows an image (sent or pasted) or a Typst
+// drawing (the room of a live block or a local image in Markdown; not a
+// whole Markdown page) takes. `half`, the default: as above. `full`: the
+// terminal's rows less PICTURE_ROOM_ROWS. A number: that many rows, at most
+// as many as `full`. Never under PICTURE_MIN_ROWS.
export type Height = number | 'half' | 'full'
export const DEFAULT_HEIGHT: Height = 'half'
export const MIN_HEIGHT = PICTURE_MIN_ROWS
@@ -87,6 +93,21 @@ export const heightText = (height: Height) =>
: height === 'full' ? `full (the terminal height less ${PICTURE_ROOM_ROWS} rows)`
: `${height} rows`
export const PICTURES_KEPT = 64
+// The compile results kept in memory (an LRU); the oldest go past this.
+export const RESULTS_KEPT = 1024
+// A resize or a font size change is settled when no new tty line and no
+// new viewport came for this long (one compile wave for each drag).
+export const RESIZE_QUIET_MS = 450
+// An epoch (a new target Frame, theme or setting) shows its pictures all at
+// once: when its jobs on screen are done, at least COMMIT_MIN_MS after it
+// began, or at COMMIT_MAX_MS whatever is still running.
+export const COMMIT_MIN_MS = 100
+export const COMMIT_MAX_MS = 5000
+// The cache folders and design files read are touched together this often
+// (one `touch -c` for all), not at each read.
+export const TOUCH_FLUSH_MS = 5000
+// A design file not read in this many days is deleted.
+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
@@ -102,8 +123,8 @@ Packages available offline:
#import "@preview/cetz:0.5.2"
#import "@preview/cetz-plot:0.1.4": plot, chart
#import "@preview/fletcher:0.5.8" as fletcher: diagram, node, edge
-A \`theme\` dictionary is in scope: theme.fg, theme.muted, theme.link, theme.border, theme.accent, theme.bg, theme.code-bg, theme.red/green/blue/yellow/orange/purple, theme.palette (6 colours), theme.width (content width), theme.dark (bool).
-Default strokes in cetz, fletcher and cetz-plot are black and invisible on a dark theme, so always pass theme colours: cetz \`set-style(stroke: theme.fg)\`; fletcher \`diagram(node-stroke: theme.fg, edge-stroke: theme.fg, ...)\`; cetz-plot \`set-style(axes: (stroke: theme.fg, tick: (stroke: theme.fg)), legend: (fill: theme.bg, stroke: theme.border))\`; fills like \`theme.blue.transparentize(70%)\`; size drawings to theme.width at most.
+A \`theme\` dictionary is in scope: theme.fg, theme.muted, theme.link, theme.border, theme.accent, theme.bg, theme.code-bg, theme.red/green/blue/yellow/orange/purple, theme.palette (6 colours), theme.width (content width), theme.height (the height a drawing should fit in), theme.dark (bool).
+Default strokes in cetz, fletcher and cetz-plot are black and invisible on a dark theme, so always pass theme colours: cetz \`set-style(stroke: theme.fg)\`; fletcher \`diagram(node-stroke: theme.fg, edge-stroke: theme.fg, ...)\`; cetz-plot \`set-style(axes: (stroke: theme.fg, tick: (stroke: theme.fg)), legend: (fill: theme.bg, stroke: theme.border))\`; fills like \`theme.blue.transparentize(70%)\`; size drawings to fit theme.width × theme.height; md-preview scales them when the terminal changes.
Inside a typst block, #page, #pagebreak and #set page are errors. If a block fails to compile, it is shown as code instead.
A plan (the plan file you write in plan mode) is drawn the same way when ExitPlanMode asks for approval, so the same Markdown, $math$ and typst blocks work there.
The stored text stays Markdown, so keep replies readable as plain text too.`
diff --git a/hooks/lib/state.ts b/hooks/lib/state.ts
index a995069..8ca2051 100644
--- a/hooks/lib/state.ts
+++ b/hooks/lib/state.ts
@@ -16,6 +16,16 @@ import { DEFAULT_HEIGHT, DEFAULT_SIZE, DEFAULT_WIDTH, type Height, type Width }
const done = atom({ plugin: 'md-preview', key: 'done' } as const, 0)
export type Cell = { width: number; height: number }
+// The terminal now (one TIOCGWINSZ read): its columns, rows and cell in
+// device pixels. A font size change is a change of the cell.
+export type Frame = { columns: number; rows: number; cell: Cell }
+// The drawing space in pt at the first compile of a text: the page width
+// (the template's `width`) and the room height. Its live Typst blocks scale from it.
+export type Design = { widthPt: number; heightPt: number }
+// The room for a drawing: its height in pt now, and the design of the text.
+// `designKey` names the design's file; `isNew`: no file yet (the design is
+// the space now, recorded once a final compile succeeds).
+export type Room = { heightPt: number; design: Design; designKey: string; isNew: boolean }
// Per 1 em (render/measure.typ): `adv` the width of "0", `xh` the x-height,
// `avg` the mean advance over a lowercase pangram.
export type FontMetrics = { adv: number; xh: number; avg: number }
@@ -44,9 +54,13 @@ export type Env = {
// The terminal's font family ('' when not known) and the fonts' metrics.
termFont: string
metrics: Metrics
+ // The designs folder (designs.ts), outside the 2-day tmp cleanup.
+ designs: string
}
-export type Page = { file: string; width: number; height: number; alt: string }
-export type Result = { pages: Page[]; columns: number; bulletRow: number; note?: string }
+// `columns` and `rows`: the cell box the page was compiled for (it is drawn
+// at that box, never stretched).
+export type Page = { file: string; width: number; height: number; alt: string; columns: number; rows: number }
+export type Result = { pages: Page[]; bulletRow: number; note?: string }
export type Job = {
key: string
requestId: string
@@ -59,6 +73,16 @@ export type Job = {
env: Env
// The folder relative images start from (a Markdown file's); else env.cwd.
base?: string
+ // The room for its drawings (a text with a live Typst block or a local image).
+ room?: Room
+ // The epoch (S.epoch) it was enqueued in: only the open epoch's jobs hold
+ // its commit (set by enqueue).
+ epoch: number
+ // The queue's order: a row on screen first, then the newest (`order`, set
+ // by enqueue). `onScreen` false: the row is known to be off screen (it
+ // does not hold the commit); undefined: not known.
+ onScreen?: boolean
+ order?: number
}
// The active theme: its name, folder, and the mtimes of its files and the
// base theme's, which are part of every key.
@@ -70,18 +94,41 @@ export type Look = { name: string; dir: string; stamp: string }
export const S = {
env: null as Env | null,
envLoading: null as Promise<Env> | null,
- cell: null as Cell | null,
+ // The target: the terminal now, settled (the tty's Frame with its columns
+ // at most the viewport's). Keys and compiles use it. Only frame.ts and
+ // beginEpoch set it. Null until the first read.
+ frame: null as Frame | null,
+ // The Frame whose pictures are on screen: the target once its epoch
+ // committed (all its pictures swap in one redraw). Pictures size from it.
+ shown: null as Frame | null,
+ // The epoch: one for each new target (a settled resize, a setting, a mode).
+ // It is open while `epoch` is not `shownEpoch` (epochOpen).
+ epoch: 0,
+ shownEpoch: 0,
+ // A burst of tty lines or viewports is not quiet yet: no job starts, and
+ // the epoch does not commit. `missed`: a job ended while it was so.
+ resizing: false,
+ missed: false,
+ // The last good tty read and the last viewport a render hook saw, not
+ // settled yet (frame.ts settles them into `frame`).
+ tty: null as Frame | null,
+ viewColumns: null as number | null,
+ viewRows: null as number | null,
+ // The key folders in the cache at setUp: a key found there is read back
+ // at once (a reopened session), with no queue and no blank.
+ onDisk: new Set<string>(),
theme: 'dark' as MdPreviewTheme,
size: DEFAULT_SIZE,
// `/md-preview width`: the most columns a picture takes, or full.
width: DEFAULT_WIDTH as Width,
- // `/md-preview height`: the most rows an image takes (half, full or a number).
+ // `/md-preview height`: the most rows an image or a Typst drawing takes (half, full or a number).
height: DEFAULT_HEIGHT as Height,
+ // The height setting of the pictures on screen: `height` once its epoch
+ // committed (with `shown`), so an image box changes in one step.
+ shownHeight: DEFAULT_HEIGHT as Height,
look: null as Look | null,
// The usable themes the last scan found, for the typeahead.
themeChoices: [] as ThemeInfo[],
- lastView: '',
- measureTimer: null as { cancel: () => void } | null,
// Claude Code's theme setting as set (`settingRaw`) and read (`setting`); with
// auto, `host` is the OS appearance last read and `watch` the poll timer. A
// hot reload cancels the old module's timers (`$.clock` docs), so `watch`
@@ -102,6 +149,8 @@ export const S = {
// Over ssh (set in setUp): the terminal's config and the OS appearance here
// are the remote computer's, not those of the user's screen.
isRemote: false,
+ // MD_PREVIEW_DEBUG is set (setUp): trace lines go to the debug log.
+ debug: false,
// iTerm2 with the engine's pictures off at start: /md-preview setup can help
// (`setupNeeded`); the question is asked once per load (`setupAsked`).
setupNeeded: false,
@@ -119,6 +168,7 @@ export const S = {
planAsking: '',
planCode: null as string | null,
}
+// The compile results by key (an LRU: set with `keep` at RESULTS_KEPT).
export const results = new Map<string, Result | 'failed'>()
// Streaming: model requests of the main loop in flight (`S.stepsLive`), the
// blocks drawn blank while their text streams (with the job to compile once
@@ -128,11 +178,17 @@ export const live = new Map<string, { job: Job; still: { cancel: () => void } }>
export const finalized = new Set<string>()
// A final block not drawn yet: blank until `showText` (its deadline passed).
export const pending = new Map<string, { textHash: string; showText: boolean; timer: { cancel: () => void } }>()
+// The jobs waiting, and the jobs that compile now by key (with the cancel
+// of each: beginEpoch stops them; and its signal: an entry cancelled still
+// holds its slot until its compile ends, but its key may be enqueued again).
export const queue: Job[] = []
-export const running = new Set<string>()
-// The last result drawn per message, so a width change keeps the old picture
-// (scaled) until the new one is ready instead of falling back to text.
-export const shown = new Map<string, { textHash: string; result: Result }>()
+export const running = new Map<string, { job: Job; cancel: () => void; signal: AbortSignal }>()
+// An epoch is open: its target is not on screen yet.
+export const epochOpen = () => S.epoch !== S.shownEpoch
+// The key last drawn per message (and its text), so a new size keeps the old
+// picture (at its own box) until the new one is ready instead of the text.
+// The oldest go past RESULTS_KEPT, as `results`.
+export const lastKey = new Map<string, { key: string; textHash: string }>()
// Over ssh: each page file's PNG as base64 (null: too large to send), read
// once so a redraw does not read it again; the oldest go past INLINE_KEPT.
export const inlined = new Map<string, string | null>()
@@ -159,6 +215,16 @@ export const subagentPlans = new Set<string>()
// waits for its file's).
export const writesLive = new Map<string, number>()
+// Sets a cache entry as the newest; the oldest go past `max`.
+export function keep<T>(cache: Map<string, T>, key: string, value: T, max: number) {
+ cache.delete(key)
+ cache.set(key, value)
+ for (const old of cache.keys()) {
+ if (cache.size <= max) break
+ cache.delete(old)
+ }
+}
+
// Redraws every reader of `done`; an invalidate where the write is refused.
export function refresh($: EngineInterface) {
void update($, done, n => n + 1).catch(() => $.ui.invalidate('ui.render'))
diff --git a/hooks/lib/stream.ts b/hooks/lib/stream.ts
index 2d05776..f5e80d0 100644
--- a/hooks/lib/stream.ts
+++ b/hooks/lib/stream.ts
@@ -1,37 +1,84 @@
// Streaming and the compile queue: a block is blank while its text streams,
// final when its request moves on (or its text is still), then compiled, at
-// most MAX_RUNNING at once.
+// most MAX_RUNNING at once: rows on screen first, then the newest. No job
+// starts during a burst (S.resizing); a job that ends calls jobDone (no
+// redraw while an epoch is open: the epoch commits).
import type { EngineInterface } from 'claude-code'
-import { BLANK_AFTER_LIVE_MS, MAX_RUNNING } from './settings'
-import { finalized, live, pending, queue, refresh, results, running, type Job } from './state'
+import { BLANK_AFTER_LIVE_MS, MAX_RUNNING, RESULTS_KEPT } from './settings'
+import { finalized, keep, live, pending, queue, refresh, results, running, S, type Job } from './state'
import { hashOf } from './draw'
+import { noteDesign, recordDesign } from './designs'
import { compile, logDebug } from './typst'
+import { extendEpoch, jobDone, jobQueued } from './epoch'
+
+// The order of enqueue calls: a higher `order` is newer.
+let enqueued = 0
+
+// The queue's next job: one on screen first, then one not known (onScreen
+// undefined), then one known off screen; among them the newest.
+const rankOf = (j: Job) => (j.onScreen === true ? 2 : j.onScreen === false ? 0 : 1)
+export function nextJob(jobs: readonly Job[]): number {
+ let best = -1
+ for (let i = 0; i < jobs.length; i++) {
+ const j = jobs[i]!
+ const b = jobs[best]
+ if (!b || (rankOf(j) !== rankOf(b) ? rankOf(j) > rankOf(b) : (j.order ?? 0) > (b.order ?? 0))) best = i
+ }
+ return best
+}
export function pump($: EngineInterface) {
+ if (S.resizing) return
while (running.size < MAX_RUNNING && queue.length) {
- const job = queue.shift()!
- running.add(job.key)
- void compile($, job)
+ const job = queue.splice(nextJob(queue), 1)[0]!
+ const controller = new AbortController()
+ const entry = { job, cancel: () => controller.abort(), signal: controller.signal }
+ running.set(job.key, entry)
+ void compile($, job, controller.signal)
.catch(async (err: unknown) => {
await logDebug($, job.env.cache, `compile ${job.key} threw: ${String(err)}`)
return 'failed' as const
})
- .then(result => {
- results.set(job.key, result)
- running.delete(job.key)
- refresh($)
+ .then(async result => {
+ // A cancelled compile keeps nothing: no result, no design.
+ if (result !== 'cancelled') {
+ // A first compile of a final text keeps its design (a job compiles
+ // only once its text is final). Any job of the text saves it: the
+ // first job may have been replaced in the queue by a later one with
+ // the same design (recordDesign does nothing once it is saved).
+ if (result !== 'failed' && job.room) {
+ await recordDesign($, job.env.designs, job.room.designKey, job.room.design).catch(() => undefined)
+ }
+ keep(results, job.key, result, RESULTS_KEPT)
+ }
+ // A new run of the same key may have taken the entry.
+ if (running.get(job.key) === entry) running.delete(job.key)
+ // A cancelled compile draws nothing new: no redraw.
+ if (result !== 'cancelled') jobDone($)
pump($)
})
}
}
+// A newer text of the same message replaces its job still waiting; the same
+// job again takes its new place (on screen or not, and newest).
export function enqueue($: EngineInterface, job: Job) {
- if (results.has(job.key) || running.has(job.key)) return
- // A newer text of the same message replaces its job still waiting.
+ // A first compile's design is in memory at once, so a render of the same
+ // text while it compiles (a resize) uses it too.
+ if (job.room?.isNew) noteDesign(job.room.designKey, job.room.design)
+ if (results.has(job.key)) return
+ // A run cancelled (by beginEpoch) still ends; its key compiles again.
+ const runs = running.get(job.key)
+ if (runs && !runs.signal.aborted) return
const stale = queue.findIndex(j => j.requestId === job.requestId || j.key === job.key)
if (stale >= 0) queue.splice(stale, 1)
+ job.epoch = S.epoch
+ job.order = ++enqueued
queue.push(job)
+ jobQueued(job)
+ // A job of the open epoch: its rows still come, the commit waits for them.
+ extendEpoch($)
pump($)
}
diff --git a/hooks/lib/terminal.ts b/hooks/lib/terminal.ts
index 4b23584..0991251 100644
--- a/hooks/lib/terminal.ts
+++ b/hooks/lib/terminal.ts
@@ -1,6 +1,6 @@
// What the terminal can draw: its columns and cell size, whether the engine
// draws pictures there, and how large a picture sent as bytes (over ssh) can be.
-import type { Cell } from './state'
+import { S, type Cell } from './state'
import { GUTTER, IMAGE_MAX_COLUMNS, SEGMENT_ROWS, type Width } from './settings'
// The columns a picture takes: the viewport less the bullet, at most `width`
@@ -12,16 +12,34 @@ export function columnsFor(viewportColumns: number | undefined, width: Width, in
return Math.max(20, Math.min(...caps, (viewportColumns ?? 80) - GUTTER))
}
-// The cell in device pixels from `rows cols xpixel ypixel` (TIOCGWINSZ).
-// iTerm2 (3.5+), Ghostty, kitty and WezTerm report device pixels already, so
-// there is no backing-scale step. Null where the tty reports no pixels or a
-// cell that can't be right (under 4 or over 64 px wide).
-export function cellOf(stdout: string): Cell | null {
+// The columns a picture has room for now: the viewport at most the tty's,
+// less the bullet (as pictureColumns, with no width or ssh cap).
+export function roomColumns(view?: { columns: number } | null): number {
+ const v = view?.columns ?? S.viewColumns ?? S.frame?.columns
+ const tty = S.tty?.columns
+ const columns = v === undefined ? tty : tty === undefined ? v : Math.min(v, tty)
+ return columnsFor(columns, 'full')
+}
+
+// A box at most `room` columns wide, the aspect kept; never larger.
+export function fitBox(box: { columns: number; rows: number }, room: number): { columns: number; rows: number } {
+ if (box.columns <= room) return { columns: box.columns, rows: box.rows }
+ return { columns: room, rows: Math.max(1, Math.round((box.rows * room) / box.columns)) }
+}
+
+// The size from `rows cols xpixel ypixel` (TIOCGWINSZ): the rows, the
+// columns and the cell in device pixels. iTerm2 (3.5+), Ghostty, kitty and
+// WezTerm report device pixels already, so there is no backing-scale step.
+// `cell` is null where the tty reports no pixels or a cell that can't be
+// right (under 4 or over 64 px wide); the whole is null with no rows or
+// columns.
+export function sizeOf(stdout: string): { rows: number; columns: number; cell: Cell | null } | null {
const [rows, columns, x, y] = stdout.trim().split(/\s+/).map(Number)
- if (!rows || !columns || !x || !y) return null
+ if (!rows || !columns || !Number.isInteger(rows) || !Number.isInteger(columns)) return null
+ if (!x || !y) return { rows, columns, cell: null }
const width = x / columns
const height = y / rows
- return width >= 4 && width <= 64 && height >= 4 ? { width, height } : null
+ return { rows, columns, cell: width >= 4 && width <= 64 && height >= 4 ? { width, height } : null }
}
// A set flag: anything but empty, 0, false, no or off.
diff --git a/hooks/lib/typst.ts b/hooks/lib/typst.ts
index 6471023..9ab56ed 100644
--- a/hooks/lib/typst.ts
+++ b/hooks/lib/typst.ts
@@ -2,12 +2,13 @@
// 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 { DEFAULT_METRICS, type FontMetrics, type Job, type Metrics, type Result } from './state'
-import { firstLine, imagePathOf, localImages, plainOf, splitSegments } from './markdown'
+import { COMPILE_TIMEOUT_MS, MAX_IMAGE_ROWS, NO_NETWORK, SEGMENT_ROWS, TOUCH_FLUSH_MS, TYPST_FALLBACKS } from './settings'
+import { DEFAULT_METRICS, type Cell, type FontMetrics, type Job, type Metrics, type Page, type Result } from './state'
+import { firstLine, imagePathOf, localImages, plainOf, splitInTwo, splitSegments } from './markdown'
import { inlineBudget } from './terminal'
import { alignFirstLine, firstLineOf, fontFit, sizing } from './draw'
import { HEADERS_SH } from './host'
+import { logDebug } from './log'
// The typst command and its environment. Network off (see NO_NETWORK) and a
// package cache of our own, so only the vendored packages load.
@@ -132,10 +133,7 @@ export async function measureFonts($: EngineInterface, typst: string, root: stri
return DEFAULT_METRICS
}
-export async function logDebug($: EngineInterface, cache: string, text: string) {
- const stamp = new Date().toISOString()
- await $.process.run(['sh', '-c', 'cat >> "$1"', 'sh', `${cache}/debug.log`], { stdin: `[${stamp}] ${text.trimEnd()}\n` }).catch(() => undefined)
-}
+export { logDebug } from './log'
// The images that exist, for the template's allow-list: it draws any other
// as its alt, so one bad path doesn't fail the page.
@@ -148,7 +146,136 @@ export async function existingImages($: EngineInterface, segments: readonly stri
return found
}
-export async function runTypst($: EngineInterface, job: Job, segments: readonly string[], dir: string, tag: string, isSafe: boolean) {
+// The template's inputs for the room of a drawing (pt): the room height, and
+// the design's page width and room height.
+export function roomInputs(room: Job['room']): Record<string, number> {
+ if (!room) return {}
+ const pt = (v: number) => Math.round(v * 100) / 100
+ return { height: pt(room.heightPt), 'design-w': pt(room.design.widthPt), 'design-h': pt(room.design.heightPt) }
+}
+
+// The rows a page of `height` pixels takes in cells of `cell` (the template
+// pads each page to whole rows, so this rounds).
+export const pageRowsOf = (height: number, cell: Cell) => Math.max(1, Math.round(height / cell.height))
+
+// A kept pages.json as a Result; null when it is not one (an older format).
+export function resultOf(text: string): Result | null {
+ try {
+ const r = JSON.parse(text) as Result
+ const isPage = (p: Page) => !!p && typeof p.file === 'string' && p.columns > 0 && p.rows > 0
+ return Array.isArray(r.pages) && r.pages.length > 0 && r.pages.every(isPage) ? r : null
+ } catch {
+ return null
+ }
+}
+
+// Paths in use (key folders, design files): their mtime is set to now, so
+// the cleanups go by use. touchLater only notes the path (no process in a
+// render path); one `touch -c` runs per TOUCH_FLUSH_MS for at most
+// TOUCH_BATCH paths, the rest wait for the next run.
+export const TOUCH_BATCH = 200
+const TOUCH_KEPT = 4096
+// The paths not touched yet (empty after each flush; answer.ts keeps the
+// keys touched in this load, so a redraw does not note them again).
+const toTouch = new Set<string>()
+let touchTimer: { cancel: () => void } | null = null
+
+export function touchLater($: EngineInterface, path: string) {
+ if (toTouch.size >= TOUCH_KEPT && !toTouch.has(path)) return
+ toTouch.add(path)
+ if (touchTimer) return
+ touchTimer = $.clock.after(TOUCH_FLUSH_MS, () => {
+ touchTimer = null
+ const paths = [...toTouch].slice(0, TOUCH_BATCH)
+ for (const each of paths) toTouch.delete(each)
+ if (paths.length) void Promise.resolve($.process.run(['touch', '-c', ...paths], { timeoutMs: 5000 })).catch(() => undefined)
+ if (toTouch.size) touchLater($, toTouch.values().next().value!)
+ })
+}
+
+// Clears the paths not touched yet and the timer (for tests).
+export function forgetTouches() {
+ touchTimer?.cancel()
+ touchTimer = null
+ toTouch.clear()
+}
+
+// A command with a PID line first: `sh` writes its own PID, then becomes
+// the command (exec keeps the PID), so `kill <pid>` stops the command.
+export const wrapPid = (argv: readonly string[]): string[] => ['sh', '-c', 'echo $$; exec "$@"', 'sh', ...argv]
+
+// How a run ended: `isCancelled` when `signal` stopped it (its output does
+// not count).
+export type Ran = { exitCode: number; stdout: string; stderr: string; isCancelled?: boolean }
+
+// Runs `argv` through wrapPid with $.process.spawn: its stdout (less the PID
+// line) and stderr, and its exit code (1 when a signal ended it). `signal`
+// and the timeout (`timeoutMs`, on $.clock) kill it by its PID; a timeout
+// ends with exit 1 and stderr `timed out`.
+export async function runKillable(
+ $: EngineInterface,
+ argv: readonly string[],
+ o: { env?: Record<string, string>; signal?: AbortSignal; timeoutMs: number },
+): Promise<Ran> {
+ if (o.signal?.aborted) return { exitCode: 1, stdout: '', stderr: 'cancelled', isCancelled: true }
+ let pid = ''
+ let head = ''
+ let stdout = ''
+ let stderr = ''
+ let why: 'cancel' | 'timeout' | null = null
+ let isKillSent = false
+ const killNow = () => {
+ if (!why || !pid || isKillSent) return
+ isKillSent = true
+ void Promise.resolve($.process.run(['kill', pid], { timeoutMs: 5000 })).catch(() => undefined)
+ }
+ const stop = (reason: 'cancel' | 'timeout') => {
+ if (why) return
+ why = reason
+ killNow()
+ }
+ const onAbort = () => stop('cancel')
+ o.signal?.addEventListener('abort', onAbort, { once: true })
+ const timer = $.clock.after(o.timeoutMs, () => stop('timeout'))
+ let code: number | null = 1
+ try {
+ const child = $.process.spawn({ argv: wrapPid(argv), ...(o.env ? { env: o.env } : {}) })
+ for (;;) {
+ const got = await child.next()
+ if (got.done) {
+ code = got.value?.code ?? 1
+ break
+ }
+ const { stream, text } = got.value
+ if (stream === 'stderr') stderr += text
+ else if (pid) stdout += text
+ else {
+ head += text
+ const at = head.indexOf('\n')
+ if (at >= 0) {
+ pid = head.slice(0, at).trim()
+ stdout += head.slice(at + 1)
+ head = ''
+ if (!/^\d+$/.test(pid)) pid = ''
+ killNow()
+ }
+ }
+ }
+ } catch (err: unknown) {
+ stderr += `${stderr ? '\n' : ''}typst did not run: ${String(err)}`
+ code = 1
+ } finally {
+ timer.cancel()
+ o.signal?.removeEventListener('abort', onAbort)
+ }
+ // A cancel that came after typst ended (before its end was read) drops a
+ // whole result too: the key compiles again (rare, and accepted).
+ if (why === 'cancel') return { exitCode: 1, stdout, stderr, isCancelled: true }
+ if (why === 'timeout') return { exitCode: 1, stdout, stderr: 'timed out' }
+ return { exitCode: code, stdout, stderr }
+}
+
+export async function runTypst($: EngineInterface, job: Job, segments: readonly string[], dir: string, tag: string, isSafe: boolean, signal?: AbortSignal): Promise<Ran> {
const fit = fontFit(job.env.metrics, job.size)
const { widthPt, ppi, rowPt } = sizing(job.columns, job.cell, fit.columnPt)
const { topPt } = alignFirstLine(firstLineOf(segments[0] ?? ''), rowPt)
@@ -166,56 +293,95 @@ export async function runTypst($: EngineInterface, job: Job, segments: readonly
...(job.env.termFont ? { 'term-font': job.env.termFont } : {}),
'theme-dir': job.themeDir,
doc: `${dir}/doc.json`,
+ ...roomInputs(job.room),
...(isSafe ? { safe: 1 } : {}),
},
out: `${dir}/${tag}-{0p}.png`,
})
- return $.process
- .run(argv, { timeoutMs: COMPILE_TIMEOUT_MS, env: vars })
- .catch((err: unknown) => ({ exitCode: 1, stdout: '', stderr: `typst did not run: ${String(err)}` }))
+ return runKillable($, argv, { env: vars, timeoutMs: COMPILE_TIMEOUT_MS, ...(signal ? { signal } : {}) })
}
-export async function compile($: EngineInterface, job: Job): Promise<Result | 'failed'> {
+// The pages of one run: its PNGs (by tag) in order, with their sizes and
+// the box each takes. Null when there are none or a size can not be read.
+async function pagesOfRun($: EngineInterface, job: Job, dir: string, tag: string, segments: readonly string[]): Promise<Page[] | null> {
+ const files = (await $.fs.list(dir))
+ .filter(f => f.kind === 'file' && f.name.startsWith(`${tag}-`) && f.name.endsWith('.png'))
+ .map(f => f.name)
+ .sort((x, y) => Number(x.replace(/\D/g, '')) - Number(y.replace(/\D/g, '')))
+ .map(name => `${dir}/${name}`)
+ if (!files.length) return null
+ const heads = await $.process.run(['sh', '-c', HEADERS_SH, 'sh', ...files])
+ const sizes = parseOd(heads.stdout).map(pngSize)
+ if (sizes.length !== files.length || sizes.some(s => !s)) {
+ await logDebug($, job.env.cache, `compile ${job.key}: could not read PNG sizes`)
+ return null
+ }
+ return files.map((file, i) => ({
+ file, ...sizes[i]!, alt: plainOf(segments[i] ?? job.text), columns: job.columns, rows: pageRowsOf(sizes[i]!.height, job.cell),
+ }))
+}
+
+// Compiles a job's text to its pages (kept in its key folder). `signal`
+// stops it: a run killed by it, or a retry not begun, is 'cancelled' (not a
+// result: nothing is kept).
+export async function compile($: EngineInterface, job: Job, signal?: AbortSignal): Promise<Result | 'failed' | 'cancelled'> {
const dir = `${job.env.cache}/${job.key}`
const kept = await $.fs.read(`${dir}/pages.json`).catch(() => null)
- if (kept) return JSON.parse(kept) as Result
+ const keptResult = kept ? resultOf(kept) : null
+ if (keptResult) {
+ touchLater($, dir)
+ return keptResult
+ }
+ if (signal?.aborted) return 'cancelled'
- const segments = splitSegments(job.text, job.columns, job.env.inline ? inlineBudget(job.cell) : SEGMENT_ROWS)
+ let segments = splitSegments(job.text, job.columns, job.env.inline ? inlineBudget(job.cell) : SEGMENT_ROWS, job.size)
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)
+ let isSafe = false
+ let ran = await runTypst($, job, segments, dir, tag, false, signal)
let note: string | undefined
+ if (ran.isCancelled) return 'cancelled'
if (ran.exitCode !== 0) {
+ if (signal?.aborted) return 'cancelled'
await logDebug($, job.env.cache, `compile ${job.key} failed:\n${ran.stderr}`)
if (!shouldRetrySafe(ran.exitCode)) return 'failed'
note = firstLine(ran.stderr.split('\n').find(l => /error:/i.test(l)) ?? ran.stderr).replace(/^.*error:\s*/i, '')
tag = 'b'
- ran = await runTypst($, job, segments, dir, tag, true)
+ isSafe = true
+ ran = await runTypst($, job, segments, dir, tag, true, signal)
+ if (ran.isCancelled) return 'cancelled'
if (ran.exitCode !== 0) {
await logDebug($, job.env.cache, `compile ${job.key} with safe=1 failed:\n${ran.stderr}`)
return 'failed'
}
}
- const files = (await $.fs.list(dir))
- .filter(f => f.kind === 'file' && f.name.startsWith(`${tag}-`) && f.name.endsWith('.png'))
- .map(f => f.name)
- .sort((x, y) => Number(x.replace(/\D/g, '')) - Number(y.replace(/\D/g, '')))
- .map(name => `${dir}/${name}`)
- if (!files.length) return 'failed'
- const heads = await $.process.run(['sh', '-c', HEADERS_SH, 'sh', ...files])
- const sizes = parseOd(heads.stdout).map(pngSize)
- if (sizes.length !== files.length || sizes.some(s => !s)) {
- await logDebug($, job.env.cache, `compile ${job.key}: could not read PNG sizes`)
- return 'failed'
+ let pages = await pagesOfRun($, job, dir, tag, segments)
+ if (!pages) return 'failed'
+ // A page taller than an Image can be (the row estimate was short): its
+ // segment is cut in two and the whole text compiled once more. If that
+ // fails, the first pages stay (drawn at most MAX_IMAGE_ROWS tall).
+ if (pages.some(p => p.rows > MAX_IMAGE_ROWS)) {
+ const cut = segments.flatMap((seg, i) => (pages![i]!.rows > MAX_IMAGE_ROWS ? splitInTwo(seg, job.columns, job.size) : [seg]))
+ if (cut.length > segments.length) {
+ if (signal?.aborted) return 'cancelled'
+ await $.fs.write(`${dir}/doc.json`, JSON.stringify({ base, segments: cut, images }))
+ const again = await runTypst($, job, cut, dir, isSafe ? 'd' : 'c', isSafe, signal)
+ if (again.isCancelled) return 'cancelled'
+ const split = again.exitCode === 0 ? await pagesOfRun($, job, dir, isSafe ? 'd' : 'c', cut) : null
+ if (split) {
+ pages = split
+ segments = cut
+ } else await logDebug($, job.env.cache, `compile ${job.key}: the split retry failed:\n${again.stderr}`)
+ }
+ pages = pages.map(p => ({ ...p, rows: Math.min(MAX_IMAGE_ROWS, p.rows) }))
}
- const pages = files.map((file, i) => ({ file, ...sizes[i]!, alt: plainOf(segments[i] ?? job.text) }))
const { rowPt } = sizing(job.columns, job.cell, fontFit(job.env.metrics, job.size).columnPt)
const { bulletRow } = alignFirstLine(firstLineOf(segments[0] ?? ''), rowPt)
- const result: Result = { pages, columns: job.columns, bulletRow, ...(note ? { note } : {}) }
+ const result: Result = { pages, bulletRow, ...(note ? { note } : {}) }
await $.fs.write(`${dir}/pages.json`, JSON.stringify(result))
return result
}
diff --git a/hooks/register.tsx b/hooks/register.tsx
index 763e6c2..b4550ea 100644
--- a/hooks/register.tsx
+++ b/hooks/register.tsx
@@ -19,10 +19,10 @@ import { atom, read, update } from 'claude-code'
import type { EngineInterface, Register, RenderElement, RenderViewport } from 'claude-code'
import {
- DEFAULT_CELL, DEFAULT_THEME, heightText, IMAGE_MAX_COLUMNS, MAX_HEIGHT, MAX_SIZE, MAX_WIDTH, MIN_HEIGHT, MIN_SIZE, MIN_WIDTH, TYPST_PROMPT, widthText,
+ DEFAULT_THEME, heightText, IMAGE_MAX_COLUMNS, MAX_HEIGHT, MAX_SIZE, MAX_WIDTH, MIN_HEIGHT, MIN_SIZE, MIN_WIDTH, RESULTS_KEPT, TYPST_PROMPT, widthText,
} from './lib/settings'
-import { editedPlans, refresh, S, subagentPlans, writesLive, type Env } from './lib/state'
-import { columnsFor } from './lib/terminal'
+import { editedPlans, keep, queue, refresh, running, S, subagentPlans, writesLive, type Env } from './lib/state'
+import { beginEpoch } from './lib/epoch'
import { escapeControls, luminanceOf, modeLine, modeOfLuminance, parseOsc11, settingOf } from './lib/mode'
import { applyTheme, themeListing, userThemesOf } from './lib/themes'
import { commandSuggestions, parseCommand, registerCommand } from './lib/command'
@@ -31,9 +31,11 @@ import { pollHost, PROBE_RUNS, probeOsc11, showMode, USE_OSC11, watchHost } from
import { measureFonts } from './lib/typst'
import { drawPages } from './lib/draw'
import { finalizeAll } from './lib/stream'
-import { pagesOf } from './lib/answer'
-import { noteViewport, setUp } from './lib/env'
-import { pastedImagePath, pastedNumbers, sentFiles } from './lib/images'
+import { pagesOf, type Drawing } from './lib/answer'
+import { setUp } from './lib/env'
+import { frameFor, noteView } from './lib/frame'
+import { roomColumns } from './lib/terminal'
+import { onScreenOf, 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,
@@ -44,10 +46,15 @@ import {
export {
BASE_THEME, DEFAULT_CELL, DEFAULT_HEIGHT, DEFAULT_SIZE, DEFAULT_THEME, DEFAULT_WIDTH, heightText, IMAGE_MAX_COLUMNS, MAX_HEIGHT, MAX_SIZE, MAX_WIDTH,
MIN_HEIGHT, MIN_SIZE, MIN_WIDTH, PICTURE_MAX_ROWS, PICTURE_MIN_ROWS, PICTURE_ROOM_ROWS, SEGMENT_ROWS, TYPST_PROMPT, widthText, type Height, type Width,
+ COMMIT_MAX_MS, COMMIT_MIN_MS, DESIGNS_KEPT_DAYS, RESIZE_QUIET_MS, RESULTS_KEPT, TOUCH_FLUSH_MS,
} from './lib/settings'
-export { DEFAULT_METRICS, type Cell, type FontMetrics, type Look, type Metrics } from './lib/state'
+export { DEFAULT_METRICS, keep, type Cell, type Design, type FontMetrics, type Frame, type Look, type Metrics, type Room } from './lib/state'
export {
- blocksOf, firstLine, imagePathOf, isTypstInfo, localImages, plainOf, rowsOfBlock, splitSegments, type Block,
+ composeFrame, followWatcher, frameChange, frameFor, frameOfLine, lineSplitter, noteTty, pictureColumns, quietTimer, shownFor, type View,
+} from './lib/frame'
+export { designKey, designPath, designText, loadDesign, parseDesign, recordDesign } from './lib/designs'
+export {
+ blocksOf, firstLine, imagePathOf, isTypstInfo, localImages, needsRoom, plainOf, rowsOfBlock, splitInTwo, splitSegments, type Block,
} from './lib/markdown'
export * from './lib/terminal'
export * from './lib/mode'
@@ -59,8 +66,11 @@ 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 { convertCall, measureCall, noNetworkEnv, parseOd, pngSize, shouldRetrySafe, typstCall } from './lib/typst'
-export { alignFirstLine, firstLineOf, fontFit, hashOf, renderKey, rowsFor, sizing, type FirstLine } from './lib/draw'
+export {
+ convertCall, measureCall, noNetworkEnv, pageRowsOf, parseOd, pngSize, resultOf, roomInputs, shouldRetrySafe, typstCall,
+} from './lib/typst'
+export { alignFirstLine, firstLineOf, fontFit, hashOf, renderKey, scaledBulletRow, sizing, type FirstLine } from './lib/draw'
+export { nextJob } from './lib/stream'
export * from './lib/images'
export {
choiceOf, decisionOf, editorArgv, feedbackOf, isPlanQuestion, normalPath, PLAN_ASK_LINE, PLAN_AUTO, PLAN_CLEAR, PLAN_DRAWING, PLAN_EDIT,
@@ -75,27 +85,87 @@ const done = atom({ plugin: 'md-preview', key: 'done' } as const, 0)
// ---- Pictures under rows ----------------------------------------------------
// The env to draw pictures with: md-preview on, in a terminal that draws;
-// null otherwise (no Typst needed). Here and not in pictures.tsx, as it
-// reads the atoms.
-async function pictureEnv($: EngineInterface, e: { viewport?: RenderViewport }): Promise<Env | null> {
+// null otherwise (no Typst needed), with the `done` value read. Here and not
+// in pictures.tsx, as it reads the atoms. The sizes come from the Frame
+// (frameFor, shownFor); the viewport is noted for it (a change is settled
+// with the tty's).
+async function pictureEnv($: EngineInterface, e: { viewport?: RenderViewport }): Promise<{ env: Env; done: number } | null> {
if (!(await read($, isOn))) return null
- // Read so the end of setUp draws this row again.
- await read($, done)
+ if (e.viewport) noteView($, e.viewport)
+ // Read so the end of setUp, a compile and a commit draw this row again.
+ const now = await read($, done)
if (!S.env) {
void setUp($).catch(() => undefined)
return null
}
- if (!S.env.canDraw) return null
- if (e.viewport) noteViewport($, e.viewport)
- return S.env
+ return S.env.canDraw ? { env: S.env, done: now } : null
}
// The env to draw Markdown pictures with (an answer, a plan): as
-// pictureEnv, and Typst found. Reading `done` draws the reader again when a
-// render finishes.
-async function answerEnv($: EngineInterface, e: { viewport?: RenderViewport }): Promise<Env | null> {
+// pictureEnv, and Typst found.
+async function answerEnv($: EngineInterface, e: { viewport?: RenderViewport }): Promise<{ env: Env; done: number } | null> {
const ready = await pictureEnv($, e)
- return ready?.typst ? ready : null
+ return ready?.env.typst ? ready : null
+}
+
+// ---- Rows drawn before ----------------------------------------------------------
+
+// What a drawn row depends on besides its own inputs: `done` (every result
+// stored, setting, theme, mode and commit redraws through it), the epochs
+// (the target and shown Frames change only with them, but at setFrame and
+// at the first viewport noted, both before a row is kept), the env, and the
+// viewport's columns (the room: the engine draws every row again once a
+// width change settles; a scroll keeps them).
+const stampOf = (ready: { env: Env; done: number }, view?: RenderViewport) =>
+ `${ready.done}|${S.epoch}|${S.shownEpoch}|${ready.env.inline ? 1 : 0}|${view?.columns ?? ''}|${roomColumns(view)}`
+
+// Each row's last drawing, by its requestId: a redraw with the same inputs
+// and the same stamp (a scroll step, a new onScreen) returns the same thing,
+// with no hash, no file and no process. Only drawn pictures are kept (a
+// blank or a text row runs the pipeline again: its timers move it on).
+// `text` the row's text (a string kept as given, so the compare is mostly
+// one pointer), `extra` its other inputs.
+type Memo<T> = { text: string; extra: string; stamp: string; onScreen: boolean | undefined; value: T }
+const answers = new Map<string, Memo<RenderElement>>()
+const plans = new Map<string, Memo<Drawing>>()
+const unders = new Map<string, Memo<Under[]>>()
+const pasted = new Map<string, Memo<Shown[]>>()
+
+// The kept value when the inputs and the stamp are the same. A new onScreen
+// is given to the row's jobs that wait or run (their order and whether they
+// hold the commit), with nothing drawn again. `isJob`: which jobs are the
+// row's, by their requestId (by default the row's id).
+type MemoKey = { text: string; extra: string; stamp: string; onScreen: boolean | undefined }
+function memoOf<T>(memo: Map<string, Memo<T>>, id: string, k: MemoKey, isJob = (requestId: string) => requestId === id): T | undefined {
+ const kept = memo.get(id)
+ if (!kept || kept.text !== k.text || kept.extra !== k.extra || kept.stamp !== k.stamp) return undefined
+ const { onScreen } = k
+ if (kept.onScreen !== onScreen) {
+ kept.onScreen = onScreen
+ for (const job of queue) if (isJob(job.requestId)) job.onScreen = onScreen
+ for (const { job } of running.values()) if (isJob(job.requestId)) job.onScreen = onScreen
+ }
+ return kept.value
+}
+
+function memoSet<T>(memo: Map<string, Memo<T>>, id: string, k: MemoKey, value: T) {
+ keep(memo, id, { ...k, value }, RESULTS_KEPT)
+}
+
+// A plan's drawing (both its rows: ToolUse and ToolResult), kept while it
+// is drawn pages (memoOf).
+async function planDrawing(
+ $: EngineInterface, e: { viewport?: RenderViewport; props: { onScreen?: unknown } }, toolUseId: string, plan: string, ready: { env: Env; done: number },
+): Promise<Drawing> {
+ const id = `plan:${toolUseId}`
+ const onScreen = onScreenOf(e.props.onScreen)
+ const k = { text: plan, extra: '', stamp: stampOf(ready, e.viewport), onScreen }
+ const kept = memoOf(plans, id, k)
+ if (kept) return kept
+ const drawing = await pagesOf($, { id, text: plan, frame: frameFor(e.viewport), env: ready.env, canStream: false, onScreen })
+ if (drawing.kind === 'pages') memoSet(plans, id, k, drawing)
+ else plans.delete(id)
+ return drawing
}
// md-preview's own plan question: only on the main loop of a session drawn
@@ -136,17 +206,19 @@ export const register: Register = on => {
return { text: `md-preview is ${asked.kind}.` }
}
if (asked.kind === 'size') {
+ // The epoch begins with the setting, so no row draws it with no epoch
+ // open (the store write waits for the host).
S.size = asked.percent
+ beginEpoch($)
await $.store.set('size', S.size)
- refresh($)
return { text: `md-preview draws text at ${S.size}% of the terminal's text size (100% matches it).` }
}
if (asked.kind === 'width') {
if (asked.width === undefined) await setUp($).catch(() => null)
else {
S.width = asked.width
+ beginEpoch($)
await $.store.set('width', S.width)
- refresh($)
}
const most = typeof S.width === 'number' && S.width > IMAGE_MAX_COLUMNS ? ` (a picture is ${IMAGE_MAX_COLUMNS} columns at most)` : ''
const head = asked.width === undefined ? 'The most columns a picture takes' : 'md-preview pictures now take at most'
@@ -156,11 +228,11 @@ export const register: Register = on => {
if (asked.height === undefined) await setUp($).catch(() => null)
else {
S.height = asked.height
+ beginEpoch($)
await $.store.set('height', S.height)
- refresh($)
}
- const head = asked.height === undefined ? 'The most rows an image takes' : 'md-preview images now take at most'
- return { text: `${head}: ${heightText(S.height)}. Use /md-preview height half (the default), /md-preview height full, or /md-preview height <${MIN_HEIGHT}-${MAX_HEIGHT}> (never more than full).` }
+ const head = asked.height === undefined ? 'The most rows an image or a Typst drawing takes' : 'md-preview images and Typst drawings now take at most'
+ return { text: `${head}: ${heightText(S.height)}. This applies to images (sent or pasted) and to Typst drawings in answers. Use /md-preview height half (the default), /md-preview height full, or /md-preview height <${MIN_HEIGHT}-${MAX_HEIGHT}> (never more than full).` }
}
if (asked.kind === 'setup') {
await setUp($).catch(() => null)
@@ -188,12 +260,12 @@ export const register: Register = on => {
const names = [...themes.keys()].sort().join(', ') || 'none'
return { text: `No usable theme named ${asked.name}. Themes: ${names}.\n${themeListing(themes, problems, was?.name ?? DEFAULT_THEME, userThemesOf(ready.home))}` }
}
- if (asked.name) await $.store.set('theme-name', chosen.name)
if (S.look?.name !== was?.name || S.look?.dir !== was?.dir || S.look?.stamp !== was?.stamp) {
// The theme's fonts set the column width and the code size.
if (ready.typst && S.look) ready.metrics = await measureFonts($, ready.typst, ready.root, ready.cache, ready.termFont, S.look.dir)
- refresh($)
+ beginEpoch($)
}
+ if (asked.name) await $.store.set('theme-name', chosen.name)
const head = asked.name ? `md-preview uses the theme ${chosen.name}.\n` : ''
return { text: `${head}${themeListing(themes, problems, chosen.name, userThemesOf(ready.home))}` }
}
@@ -207,7 +279,7 @@ export const register: Register = on => {
const tried = S.setupNeeded ? ' In iTerm2, run /md-preview setup once to show pictures.' : ''
const usage = `Use /md-preview on, /md-preview off, /md-preview size <${MIN_SIZE}-${MAX_SIZE}>, /md-preview width <${MIN_WIDTH}-${MAX_WIDTH}|full>, /md-preview height <${MIN_HEIGHT}-${MAX_HEIGHT}|half|full>, or /md-preview theme [name].`
const bad = asked.kind === 'bad' ? `Not understood: "${e.args.trim()}". ` : ''
- return { text: `${bad}md-preview is ${state}, theme ${S.look?.name ?? DEFAULT_THEME}, ${modeLine(S.theme, S.setting, S.settingRaw, S.host)}, text size ${S.size}%, width ${widthText(S.width)}, image height ${heightText(S.height)}, ${font}. ${typst}; ${terminal}.${tried} ${usage}` }
+ return { text: `${bad}md-preview is ${state}, theme ${S.look?.name ?? DEFAULT_THEME}, ${modeLine(S.theme, S.setting, S.settingRaw, S.host)}, text size ${S.size}%, width ${widthText(S.width)}, image and drawing height ${heightText(S.height)}, ${font}. ${typst}; ${terminal}.${tried} ${usage}` }
})
on('config.set', { key: 'theme' }, async ($, e, next) => {
@@ -288,9 +360,18 @@ export const register: Register = on => {
if (e.surface !== 'terminal' || e.props.isSummary || !e.props.text.trim()) return next(e)
const ready = await answerEnv($, e)
if (!ready) return next(e)
- const columns = columnsFor(e.viewport?.columns, S.width, ready.inline ? (S.cell ?? DEFAULT_CELL) : null)
- const drawing = await pagesOf($, { id: e.requestId, text: e.props.text, columns, env: ready, canStream: true })
- if (drawing.kind === 'pages') return drawPages($, e, drawing.result, columns, drawing.px, drawing.bytes, { bullet: !!e.props.isFirstOfReply })
+ const bullet = !!e.props.isFirstOfReply
+ const onScreen = onScreenOf(e.props.onScreen)
+ const k = { text: e.props.text, extra: bullet ? 'bullet' : '', stamp: stampOf(ready, e.viewport), onScreen }
+ const kept = memoOf(answers, e.requestId, k)
+ if (kept) return kept
+ const drawing = await pagesOf($, { id: e.requestId, text: e.props.text, frame: frameFor(e.viewport), env: ready.env, canStream: true, onScreen })
+ if (drawing.kind === 'pages') {
+ const tree = drawPages($, e, drawing.result, drawing.bytes, { bullet })
+ memoSet(answers, e.requestId, k, tree)
+ return tree
+ }
+ answers.delete(e.requestId)
if (drawing.kind === 'text') return next(e)
const { Box } = $.ui.resolve(e)
return <Box />
@@ -307,8 +388,20 @@ export const register: Register = on => {
try {
const files = sentFiles(e.props.output)
const ready = files.length ? await pictureEnv($, e) : null
- 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 })
+ if (ready) {
+ const markdown = files.some(f => f.kind === 'markdown') && ready.env.typst ? ready.env : null
+ const id = e.props.tool_use_id
+ const onScreen = onScreenOf(e.props.onScreen)
+ const k = { text: files.map(f => `${f.kind}:${f.path}`).join('\n'), extra: '', 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}:`))
+ if (kept) under = kept
+ else {
+ under = await sentOf($, e, { ready: ready.env, markdown, files, id, at: { done: ready.done, row: e.requestId } })
+ if (under.length && under.every(u => !('drawing' in u) || u.drawing.kind === 'pages')) memoSet(unders, id, k, under)
+ else unders.delete(id)
+ }
+ }
} catch {
under = []
}
@@ -330,8 +423,15 @@ export const register: Register = on => {
let shown: Shown[] = []
try {
const ready = await pictureEnv($, e)
- const dir = ready ? await pasteDir($, ready) : ''
- if (ready && dir) shown = await shownOf($, e, ready, numbers.map(n => pastedImagePath(dir, n)))
+ const k = { text: e.props.text, extra: '', stamp: ready ? stampOf(ready, e.viewport) : '', onScreen: undefined }
+ const kept = ready ? memoOf(pasted, e.requestId, k, () => false) : undefined
+ if (kept) shown = kept
+ else if (ready) {
+ const dir = await pasteDir($, ready.env)
+ if (dir) shown = await shownOf($, e, ready.env, numbers.map(n => pastedImagePath(dir, n)), { done: ready.done, row: e.requestId })
+ if (shown.length) memoSet(pasted, e.requestId, k, shown)
+ else pasted.delete(e.requestId)
+ }
} catch {
shown = []
}
@@ -363,9 +463,8 @@ export const register: Register = on => {
const plan = planShownOf(editedPlans.get(e.props.tool_use_id), e.props.output, e.props.input)
const ready = plan ? await answerEnv($, e) : null
if (!ready) return row
- const columns = columnsFor(e.viewport?.columns, S.width, ready.inline ? (S.cell ?? DEFAULT_CELL) : null)
- const drawing = await pagesOf($, { id: `plan:${e.props.tool_use_id}`, text: plan, columns, env: ready, canStream: false })
- return drawPlanUse($, e, row, drawing, columns)
+ const drawing = await planDrawing($, e, e.props.tool_use_id, plan, ready)
+ return drawPlanUse($, e, row, drawing)
} catch {
return row
}
@@ -381,8 +480,7 @@ export const register: Register = on => {
try {
const plan = planOf(e.props.output) ? planShownOf(editedPlans.get(e.props.tool_use_id), e.props.output, undefined) : ''
const ready = plan ? await answerEnv($, e) : null
- const columns = columnsFor(e.viewport?.columns, S.width, ready?.inline ? (S.cell ?? DEFAULT_CELL) : null)
- const drawing = ready ? await pagesOf($, { id: `plan:${e.props.tool_use_id}`, text: plan, columns, env: ready, canStream: false }) : null
+ const drawing = ready ? await planDrawing($, e, e.props.tool_use_id, plan, ready) : null
const filePath = (e.props.output as { filePath?: unknown }).filePath
if (drawing && drawing.kind !== 'text') drawn = drawPlanResult($, e, typeof filePath === 'string' ? filePath : undefined)
} catch {
diff --git a/marketing/build.sh b/marketing/build.sh
index da3c865..d90978d 100755
--- a/marketing/build.sh
+++ b/marketing/build.sh
@@ -1,43 +1,120 @@
#!/bin/sh
# Renders the sample answers with md-preview's own template, then frames them.
# Usage: marketing/build.sh (needs typst 0.15)
+#
+# The template gets the inputs the mod gives it (hooks/lib/typst.ts runTypst,
+# draw.tsx sizing/fontFit/alignFirstLine, answer.ts roomOf) for a terminal of
+# COLS picture columns and ROWS rows, with CELL_W x CELL_H px cells (2x
+# Retina), MesloLGS NF as the terminal font and `/md-preview height` on half.
+# Only the PNG resolution (PPI) is higher than the mod's, for crisp images.
set -eu
here=$(cd "$(dirname "$0")" && pwd)
root=$(dirname "$here")
out="$here/out"; work="$here/.work"
mkdir -p "$out/raw" "$work/pkg-cache"
export TYPST_PACKAGE_CACHE_PATH="$work/pkg-cache"
-width=${WIDTH:-560}; ppi=${PPI:-288}
-for md in "$here"/samples/*.md; do
- name=$(basename "$md" .md)
- python3 -c 'import json,sys; print(json.dumps({"base": sys.argv[2], "segments": [open(sys.argv[1]).read()]}))' "$md" "$here/samples" > "$work/$name.json"
+cols=${COLS:-118}; rows=${ROWS:-50}; cell_w=${CELL_W:-16}; cell_h=${CELL_H:-32}
+ppi=${PPI:-288}; font=${TERM_FONT:-MesloLGS NF}; img_w=${IMG_W:-600}
+theme_dir="$root/render/themes/vscode-modern"
+
+# The font fit: the pt of one column and the code size (draw.tsx fontFit).
+metrics=$(typst eval 'query(<m>).first().value' --in "$root/render/measure.typ" --root / \
+ --input "term-font=$font" --input "theme-dir=$theme_dir" 2>/dev/null)
+
+# Sizes for one sample (python3): sizes <md> <columns> prints
+# `width row code height top bullet`.
+# width, row: draw.tsx sizing; code: fontFit; height: the room height
+# (images.ts pictureRowsFor, half: min(24, rows/2), 6 to rows-16, rows of
+# `row` pt); top, bullet: alignFirstLine for the first line, and the
+# frame's bullet offset (pt) at that row's centre with the picture shown
+# IMG_W pt wide.
+sizes() {
+ python3 - "$1" "$metrics" "$2" "$rows" "$cell_w" "$cell_h" "$img_w" <<'EOF'
+import json, math, re, sys
+md, m, cols, rows, cw, ch, img_w = open(sys.argv[1]).read(), json.loads(sys.argv[2]), *map(float, sys.argv[3:])
+t, b = m["term"] or m["menlo"], m["body"]
+ratio = math.sqrt((t["xh"] / b["xh"]) * (t["avg"] / b["avg"]))
+column = round(11 * t["adv"] / ratio, 4)
+code = round(1 / ratio, 4)
+width = round(cols * column, 2)
+ppi = round(cols * cw) / (width / 72)
+row = ch * 72 / ppi
+pic_rows = min(24, math.floor(rows / 2))
+pic_rows = min(255, max(6, min(pic_rows, rows - 16)))
+height = round(pic_rows * row, 2)
+first = {"para": (7.45, 2.55), "h1": (20.36, 5.82), "h2": (13.09, 3.64), "h3": (9.09, 2.55), "h4": (7.27, 2.18),
+ "quote": (13.45, 8.36), "code": (17.09, 12.36), "table": (11.27, 6.18)}
+line = next((l for l in md.split("\n") if l.strip()), "")
+h = re.match(r"^ {0,3}(#{1,6})\s", line)
+kind = (["h1", "h2", "h3"][len(h.group(1)) - 1] if len(h.group(1)) <= 3 else "h4") if h else \
+ "quote" if re.match(r"^ {0,3}>", line) else "code" if re.match(r"^ {0,3}(```|~~~)", line) else \
+ "table" if re.match(r"^ {0,3}\|", line) else "para"
+centre, ink = first[kind]
+bullet_row = max(0, math.ceil((centre - ink + 0.5) / row - 0.5 - 1e-9))
+top = round((bullet_row + 0.5) * row - centre, 2)
+# The frame's ● (8 pt) sits 4.2 pt above its move offset's centre line.
+bullet = round((bullet_row + 0.5) * row * img_w / width - 4.2, 2)
+print(width, round(row, 4), code, height, top, bullet)
+EOF
+}
+
+# Renders one sample: render <md> <name> <columns>.
+render() {
+ python3 -c 'import json,sys; print(json.dumps({"base": sys.argv[2], "segments": [open(sys.argv[1]).read()]}))' "$1" "$here/samples" > "$work/$2.json"
+ name=$2
+ set -- $(sizes "$1" "$3")
+ echo "$5 $6" > "$work/$name.top"
for mode in dark light; do
+ rm -f "$out/raw/$name-$mode-"*.png
typst compile --root / --package-path "$root/render/packages" --format png --diagnostic-format short --ppi "$ppi" \
- --input theme=$mode --input width=$width --input doc="$work/$name.json" \
- --input theme-dir="$root/render/themes/vscode-modern" --input term-font="${TERM_FONT:-MesloLGS NF}" \
- --input top=6 --input row=0 --input code=0.9 \
+ --input theme=$mode --input width=$1 --input doc="$work/$name.json" \
+ --input theme-dir="$theme_dir" --input term-font="$font" \
+ --input top=$5 --input row=$2 --input code=$3 \
+ --input height=$4 --input design-w=$1 --input design-h=$4 \
"$root/render/md.typ" "$out/raw/$name-$mode-{0p}.png"
done
-done
+}
+for md in "$here"/samples/*.md; do render "$md" "$(basename "$md" .md)" "$cols"; done
+# The hero's windows are narrower: the same answer in a terminal of HERO_COLS.
+hero=3-mandelbrot; hero_cols=${HERO_COLS:-96}; hero_w=${HERO_W:-520}
+render "$here/samples/$hero.md" hero "$hero_cols"
ls "$out/raw"
+# The bullet offset of a sample (pt), from sizes().
+bullet() { cut -d' ' -f2 "$work/$1.top"; }
+
# Frames: headline, subline and the prompt for each sample.
-frame() { # name title sub ask bullet-offset-pt
+frame() { # name title sub ask
for mode in dark light; do
- typst compile --root / --ppi 216 --input img="$out/raw/$1-$mode-1.png" --input mode=$mode --input bullet="$5" \
- --input title="$2" --input sub="$3" --input ask="$4" "$here/frame.typ" "$out/$1-$mode.png" 2>/dev/null
+ typst compile --root / --ppi 216 --input img="$out/raw/$1-$mode-1.png" --input mode=$mode --input bullet="$(bullet "$1")" \
+ --input img-w="$img_w" --input title="$2" --input sub="$3" --input ask="$4" "$here/frame.typ" "$out/$1-$mode.png" 2>/dev/null
done
}
-frame 1-overview "Real Markdown, right in the terminal" "Tables, task lists, quotes and footnotes, drawn like VS Code's preview." "what is left for the v0.2.0 release?" 15
-frame 2-code "Syntax colours in your own font" "Code blocks use the terminal's font and size, with VS Code colours." "how should we pick light or dark mode?" 9
-frame 3-math "LaTeX math that reads like a paper" "Inline and display math, set by Typst." "why is 0.4 the cut-off?" 9
-frame 4-typst "Live diagrams and plots" "Claude writes Typst; md-preview draws it, offline." "show me how auto mode decides" 9
+frame 1-overview "Real Markdown, right in the terminal" \
+ "Tables, task lists, quotes and math, drawn like VS Code's preview." \
+ "show me what Markdown you can draw"
+frame 2-math "LaTeX math that reads like a paper" \
+ "Inline and display math, matrices and cases, set by Typst." \
+ "write out Maxwell's equations"
+frame 3-mandelbrot "A fractal, calculated as it draws" \
+ "Claude writes the code; Typst runs it and paints 4,000 cells." \
+ "draw the Mandelbrot set"
+frame 4-fractal "Recursion and colour, live" \
+ "A 2,047-branch tree and a 720-segment curve, drawn with CeTZ." \
+ "draw a fractal tree next to a Lissajous curve"
+frame 5-plot "Plots with axes and a legend" \
+ "cetz-plot draws functions in your theme's colours." \
+ "plot a damped oscillator"
+frame 6-diagrams "Flow charts and commutative diagrams" \
+ "fletcher draws boxes, arrows and maths from a few lines of text." \
+ "diagram the agent loop and the first isomorphism theorem"
ls "$out"
# Hero: the same answer in a dark and a light terminal.
-typst compile --root / --ppi 180 --input layout=hero --input mode=dark --input bullet=7 \
- --input img-dark="$out/raw/4-typst-dark-1.png" --input img-light="$out/raw/4-typst-light-1.png" \
+typst compile --root / --ppi 180 --input layout=hero --input mode=dark --input img-w="$hero_w" \
+ --input bullet="$(python3 -c 'import sys; print(round((float(sys.argv[1]) + 4.2) * float(sys.argv[2]) / float(sys.argv[3]) - 4.2, 2))' "$(bullet hero)" "$hero_w" "$img_w")" \
+ --input img-dark="$out/raw/hero-dark-1.png" --input img-light="$out/raw/hero-light-1.png" \
--input title="Claude's answers, rendered" \
- --input sub="Markdown, math and live Typst diagrams, in the colours of your terminal." \
- --input ask="show me how auto mode decides" "$here/frame.typ" "$out/0-hero.png" 2>/dev/null
+ --input sub="Markdown, math and live Typst drawings, in the colours of your terminal." \
+ --input ask="Demonstrate some insane capabilities of md-preview" "$here/frame.typ" "$out/0-hero.png" 2>/dev/null
ls "$out"
diff --git a/marketing/out/0-hero.png b/marketing/out/0-hero.png
index 29dae57..9b726cc 100644
Binary files a/marketing/out/0-hero.png and b/marketing/out/0-hero.png differ
diff --git a/marketing/out/1-overview-dark.png b/marketing/out/1-overview-dark.png
index bbb9584..37d3a7c 100644
Binary files a/marketing/out/1-overview-dark.png and b/marketing/out/1-overview-dark.png differ
diff --git a/marketing/out/1-overview-light.png b/marketing/out/1-overview-light.png
index 3ea76c9..2d69472 100644
Binary files a/marketing/out/1-overview-light.png and b/marketing/out/1-overview-light.png differ
diff --git a/marketing/out/2-code-dark.png b/marketing/out/2-code-dark.png
deleted file mode 100644
index 7114e34..0000000
Binary files a/marketing/out/2-code-dark.png and /dev/null differ
diff --git a/marketing/out/2-code-light.png b/marketing/out/2-code-light.png
deleted file mode 100644
index 956c281..0000000
Binary files a/marketing/out/2-code-light.png and /dev/null differ
diff --git a/marketing/out/2-math-dark.png b/marketing/out/2-math-dark.png
new file mode 100644
index 0000000..cf92cb2
Binary files /dev/null and b/marketing/out/2-math-dark.png differ
diff --git a/marketing/out/2-math-light.png b/marketing/out/2-math-light.png
new file mode 100644
index 0000000..f36c7a0
Binary files /dev/null and b/marketing/out/2-math-light.png differ
diff --git a/marketing/out/3-mandelbrot-dark.png b/marketing/out/3-mandelbrot-dark.png
new file mode 100644
index 0000000..4934558
Binary files /dev/null and b/marketing/out/3-mandelbrot-dark.png differ
diff --git a/marketing/out/3-mandelbrot-light.png b/marketing/out/3-mandelbrot-light.png
new file mode 100644
index 0000000..43bd350
Binary files /dev/null and b/marketing/out/3-mandelbrot-light.png differ
diff --git a/marketing/out/3-math-dark.png b/marketing/out/3-math-dark.png
deleted file mode 100644
index b5d9b05..0000000
Binary files a/marketing/out/3-math-dark.png and /dev/null differ
diff --git a/marketing/out/3-math-light.png b/marketing/out/3-math-light.png
deleted file mode 100644
index 283560f..0000000
Binary files a/marketing/out/3-math-light.png and /dev/null differ
diff --git a/marketing/out/4-fractal-dark.png b/marketing/out/4-fractal-dark.png
new file mode 100644
index 0000000..25d649e
Binary files /dev/null and b/marketing/out/4-fractal-dark.png differ
diff --git a/marketing/out/4-fractal-light.png b/marketing/out/4-fractal-light.png
new file mode 100644
index 0000000..593286d
Binary files /dev/null and b/marketing/out/4-fractal-light.png differ
diff --git a/marketing/out/4-typst-dark.png b/marketing/out/4-typst-dark.png
deleted file mode 100644
index 0c2c6d0..0000000
Binary files a/marketing/out/4-typst-dark.png and /dev/null differ
diff --git a/marketing/out/4-typst-light.png b/marketing/out/4-typst-light.png
deleted file mode 100644
index f1e3625..0000000
Binary files a/marketing/out/4-typst-light.png and /dev/null differ
diff --git a/marketing/out/5-plot-dark.png b/marketing/out/5-plot-dark.png
new file mode 100644
index 0000000..98c353f
Binary files /dev/null and b/marketing/out/5-plot-dark.png differ
diff --git a/marketing/out/5-plot-light.png b/marketing/out/5-plot-light.png
new file mode 100644
index 0000000..78c3674
Binary files /dev/null and b/marketing/out/5-plot-light.png differ
diff --git a/marketing/out/6-diagrams-dark.png b/marketing/out/6-diagrams-dark.png
new file mode 100644
index 0000000..eca871d
Binary files /dev/null and b/marketing/out/6-diagrams-dark.png differ
diff --git a/marketing/out/6-diagrams-light.png b/marketing/out/6-diagrams-light.png
new file mode 100644
index 0000000..7d482cc
Binary files /dev/null and b/marketing/out/6-diagrams-light.png differ
diff --git a/marketing/samples/1-overview.md b/marketing/samples/1-overview.md
index 18b6846..59be8e2 100644
--- a/marketing/samples/1-overview.md
+++ b/marketing/samples/1-overview.md
@@ -1,18 +1,18 @@
-## Release checklist for v0.2.0
+## Markdown basics
-All **four** terminals now pick the right colours. Here is what changed and what is left:
+| Feature | Syntax | Status |
+|:--|:--:|--:|
+| Tables with alignment | `\|:--\|:--:\|--:\|` | ✅ |
+| Task lists | `- [x]` | ✅ |
+| Inline + display math | `$…$`, `$$…$$` | ✅ |
+| Live Typst drawings | ` ```typst ` | ✅ |
-| Terminal | Mode source | Font source | Status |
-|---|---|---|---|
-| iTerm2 | profile background | profile font | ✅ done |
-| Ghostty | config and theme files | `font-family` | ✅ done |
-| kitty | `kitty.conf` and includes | `font_family` | ✅ done |
-| cmux | adaptive theme | Ghostty config | ✅ done |
+- [x] Render Markdown
+- [x] Render LaTeX math
+- [x] Compile Typst live
+- [ ] Make coffee
-- [x] Read the terminal background before the OS appearance
-- [x] Send pictures as bytes over **ssh**
-- [ ] Test Rio on a real machine
+> **Note**
+> > Nested quotes also work.
-> **Note:** the saved answer stays plain Markdown, so `/copy` still gives you the source.[^1]
-
-[^1]: Only the drawing changes. Use `/copy` to copy an answer as Markdown.
+Euler's identity: $e^{i\pi} + 1 = 0$. The Gaussian integral: $\int_{-\infty}^{\infty} e^{-x^2}\,dx = \sqrt{\pi}$.
diff --git a/marketing/samples/2-code.md b/marketing/samples/2-code.md
deleted file mode 100644
index 05729b5..0000000
--- a/marketing/samples/2-code.md
+++ /dev/null
@@ -1,24 +0,0 @@
-### Pick the mode from the terminal, not the OS
-
-The terminal knows its own background, so ask it first:
-
-```ts
-export function itermModeOf(p: Profile, look: Mode): Mode {
- const key = p.separate
- ? `Background Color (${cap(look)})`
- : 'Background Color'
- return modeOfLuminance(luminanceOf(p[key])) // > 0.4: light
-}
-```
-
-```python
-def luminance(r: float, g: float, b: float) -> float:
- lin = lambda v: v / 12.92 if v <= 0.04045 else ((v + 0.055) / 1.055) ** 2.4
- return 0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b)
-```
-
-```diff
-- const os = await readOsMode($)
-+ const term = await readItermMode($) ?? await readGhosttyMode($)
-+ if (term) return term
-```
diff --git a/marketing/samples/2-math.md b/marketing/samples/2-math.md
new file mode 100644
index 0000000..356a047
--- /dev/null
+++ b/marketing/samples/2-math.md
@@ -0,0 +1,22 @@
+## Math typesetting
+
+Euler's identity: $e^{i\pi} + 1 = 0$. The Gaussian integral:
+
+$$\int_{-\infty}^{\infty} e^{-x^2}\,dx = \sqrt{\pi}$$
+
+Maxwell's equations in differential form:
+
+$$
+\nabla \cdot \mathbf{E} = \frac{\rho}{\varepsilon_0}, \qquad
+\nabla \cdot \mathbf{B} = 0, \qquad
+\nabla \times \mathbf{E} = -\frac{\partial \mathbf{B}}{\partial t}, \qquad
+\nabla \times \mathbf{B} = \mu_0 \mathbf{J} + \mu_0 \varepsilon_0 \frac{\partial \mathbf{E}}{\partial t}
+$$
+
+A matrix and a piecewise function:
+
+$$
+R(\theta) = \begin{pmatrix} \cos\theta & -\sin\theta \\ \sin\theta & \cos\theta \end{pmatrix},
+\qquad
+\lvert x \rvert = \begin{cases} x & x \ge 0 \\ -x & x < 0 \end{cases}
+$$
diff --git a/marketing/samples/3-mandelbrot.md b/marketing/samples/3-mandelbrot.md
new file mode 100644
index 0000000..7f35b2a
--- /dev/null
+++ b/marketing/samples/3-mandelbrot.md
@@ -0,0 +1,37 @@
+## A Mandelbrot set, calculated in Typst
+
+Typst calculates each pixel at render time: 4,000 cells and up to 50 iterations per cell.
+
+```typst
+#let W = 80
+#let H = 50
+#let maxit = 50
+#let cell = calc.min(theme.width / W, theme.height / H)
+#let grad = gradient.linear(..color.map.magma)
+#let mandel(cx, cy) = {
+ let x = 0.0
+ let y = 0.0
+ let i = 0
+ while i < maxit and x * x + y * y <= 4.0 {
+ let xt = x * x - y * y + cx
+ y = 2.0 * x * y + cy
+ x = xt
+ i += 1
+ }
+ i
+}
+#align(center, grid(
+ columns: (cell,) * W,
+ rows: (cell,) * H,
+ gutter: 0pt,
+ ..for j in range(H) {
+ for i in range(W) {
+ let n = mandel(-2.2 + 3.2 * i / W, -1.0 + 2.0 * j / H)
+ let c = if n == maxit { black } else {
+ grad.sample((0.12 + 0.88 * calc.sqrt(n / maxit)) * 100%)
+ }
+ (box(width: cell, height: cell, fill: c),)
+ }
+ }
+))
+```
diff --git a/marketing/samples/3-math.md b/marketing/samples/3-math.md
deleted file mode 100644
index 3fe0bc9..0000000
--- a/marketing/samples/3-math.md
+++ /dev/null
@@ -1,17 +0,0 @@
-### Why 0.4 is the light/dark cut-off
-
-Relative luminance weights the linear sRGB channels:
-
-$$
-L = 0.2126\,R_{\text{lin}} + 0.7152\,G_{\text{lin}} + 0.0722\,B_{\text{lin}},
-\qquad
-C_{\text{lin}} =
-\begin{cases}
-\dfrac{C}{12.92} & C \le 0.04045 \\
-\left(\dfrac{C + 0.055}{1.055}\right)^{2.4} & \text{otherwise}
-\end{cases}
-$$
-
-The contrast of text on a background is $\dfrac{L_1 + 0.05}{L_2 + 0.05}$. At $L = 0.4$, black text has a contrast of $9.0$ and white text only $2.3$. So a background above $0.4$ reads as **light**.
-
-For Ghostty's default `#282c34`: $L \approx 0.025$, so the mode is **dark**.
diff --git a/marketing/samples/4-fractal.md b/marketing/samples/4-fractal.md
new file mode 100644
index 0000000..70f7cdf
--- /dev/null
+++ b/marketing/samples/4-fractal.md
@@ -0,0 +1,33 @@
+## Recursive fractal tree and Lissajous curve (CeTZ)
+
+The tree is a recursive function with 2,047 branches. The curve has 720 segments, each with its own color.
+
+```typst
+#import "@preview/cetz:0.5.2"
+#let g = gradient.linear(theme.orange, theme.green)
+#let rb = gradient.linear(..color.map.rainbow)
+#align(center, cetz.canvas(length: theme.height / 7.5, {
+ import cetz.draw: *
+ let tree(x, y, ang, len, d) = {
+ if d > 0 {
+ let x2 = x + len * calc.cos(ang)
+ let y2 = y + len * calc.sin(ang)
+ line((x, y), (x2, y2),
+ stroke: (paint: g.sample((11 - d) * 10%), thickness: d * 0.35pt, cap: "round"))
+ tree(x2, y2, ang + 22deg, len * 0.74, d - 1)
+ tree(x2, y2, ang - 28deg, len * 0.70, d - 1)
+ }
+ }
+ tree(0, 0, 90deg, 1.6, 11)
+
+ let N = 720
+ let pt(k) = {
+ let t = 2 * calc.pi * k / N
+ (10 + 3 * calc.sin(3 * t + calc.pi / 2), 3.2 + 3 * calc.sin(4 * t))
+ }
+ for k in range(N) {
+ line(pt(k), pt(k + 1),
+ stroke: (paint: rb.sample(k / N * 100%), thickness: 1.4pt, cap: "round"))
+ }
+}))
+```
diff --git a/marketing/samples/4-typst.md b/marketing/samples/4-typst.md
deleted file mode 100644
index a6f8d82..0000000
--- a/marketing/samples/4-typst.md
+++ /dev/null
@@ -1,39 +0,0 @@
-### How `auto` finds the mode
-
-```typst
-#import "@preview/fletcher:0.5.8" as fletcher: diagram, node, edge
-#set text(fill: theme.fg, size: 10pt)
-#diagram(
- node-stroke: theme.fg, edge-stroke: theme.fg, spacing: (14mm, 9mm),
- node-corner-radius: 4pt,
- node((0, 0), [Claude Code\ theme = auto], fill: theme.accent.transparentize(75%)),
- edge("-|>"),
- node((1, 0), [Terminal config\ iTerm2 · Ghostty · kitty · Rio · cmux], fill: theme.blue.transparentize(75%)),
- edge("-|>", [none]),
- node((2, 0), [COLORFGBG], fill: theme.purple.transparentize(75%)),
- edge("-|>", [none]),
- node((3, 0), [OS appearance], fill: theme.orange.transparentize(75%)),
- edge((1, 0), (1, 1), "-|>", [found], label-side: left),
- node((1, 1), [light / dark], fill: theme.green.transparentize(70%)),
- edge((2, 0), (1, 1), "-|>"),
- edge((3, 0), (1, 1), "-|>"),
-)
-```
-
-```typst
-#import "@preview/cetz:0.5.2"
-#import "@preview/cetz-plot:0.1.4": plot
-#set text(fill: theme.fg, size: 9pt)
-#cetz.canvas({
- import cetz.draw: *
- set-style(axes: (stroke: theme.fg, tick: (stroke: theme.fg)), legend: (fill: theme.bg, stroke: theme.border))
- plot.plot(size: (11, 4.2), x-label: [sRGB channel value], y-label: [linear value],
- legend: "inner-north-west", {
- plot.add(domain: (0, 1), samples: 80,
- x => if x <= 0.04045 { x / 12.92 } else { calc.pow((x + 0.055) / 1.055, 2.4) },
- style: (stroke: 2pt + theme.blue), label: [sRGB decode])
- plot.add(domain: (0, 1), x => x, style: (stroke: (paint: theme.muted, dash: "dashed")), label: [identity])
- plot.add-hline(0.4, style: (stroke: 1pt + theme.orange), label: [light cut-off])
- })
-})
-```
diff --git a/marketing/samples/5-plot.md b/marketing/samples/5-plot.md
new file mode 100644
index 0000000..ce318fc
--- /dev/null
+++ b/marketing/samples/5-plot.md
@@ -0,0 +1,27 @@
+## Function plot (cetz-plot)
+
+A damped oscillator with its exponential envelope:
+
+```typst
+#import "@preview/cetz:0.5.2"
+#import "@preview/cetz-plot:0.1.4": plot
+#set text(fill: theme.fg, size: 9pt)
+#align(center, cetz.canvas(length: theme.width / 15, {
+ import cetz.draw: *
+ set-style(
+ axes: (stroke: theme.fg, tick: (stroke: theme.fg)),
+ legend: (fill: theme.bg, stroke: theme.border),
+ )
+ plot.plot(
+ size: (12, 4.5), x-label: $t$, y-label: $y(t)$,
+ x-tick-step: 2, y-tick-step: 0.5, legend: "inner-north-east",
+ {
+ plot.add(domain: (0, 12), samples: 100, t => calc.exp(-t / 4),
+ style: (stroke: (paint: theme.muted, dash: "dashed")), label: $plus.minus e^(-t\/4)$)
+ plot.add(domain: (0, 12), samples: 100, t => -calc.exp(-t / 4),
+ style: (stroke: (paint: theme.muted, dash: "dashed")))
+ plot.add(domain: (0, 12), samples: 400, t => calc.exp(-t / 4) * calc.cos(3 * t),
+ style: (stroke: (paint: theme.accent, thickness: 1.5pt)), label: $e^(-t\/4) cos 3t$)
+ })
+}))
+```
diff --git a/marketing/samples/6-diagrams.md b/marketing/samples/6-diagrams.md
new file mode 100644
index 0000000..f488884
--- /dev/null
+++ b/marketing/samples/6-diagrams.md
@@ -0,0 +1,36 @@
+## Flow diagram (fletcher): an agent loop
+
+```typst
+#import "@preview/fletcher:0.5.8" as fletcher: diagram, node, edge
+#set text(fill: theme.fg, size: 10pt)
+#align(center, diagram(
+ node-stroke: theme.fg, edge-stroke: theme.fg,
+ spacing: (18mm, 12mm), node-corner-radius: 4pt, node-inset: 8pt,
+ node((0, 0), [User prompt], fill: theme.blue.transparentize(70%)),
+ edge("-|>"),
+ node((1, 0), [*Model*], fill: theme.purple.transparentize(65%), shape: fletcher.shapes.hexagon),
+ edge("-|>", [tool call], label-side: left),
+ node((2, 0), [Tool], fill: theme.orange.transparentize(70%)),
+ edge((2, 0), (1, 0), "-|>", [result], bend: 50deg),
+ edge((1, 0), (1, 1), "-|>", [done]),
+ node((1, 1), [Answer], fill: theme.green.transparentize(70%), shape: fletcher.shapes.pill),
+ edge((2, 0), (2, 1), "--|>", [log]),
+ node((2, 1), [Memory], fill: theme.yellow.transparentize(70%), shape: fletcher.shapes.cylinder),
+))
+```
+
+## Commutative diagram: the First Isomorphism Theorem
+
+Plain LaTeX math cannot draw this diagram. Fletcher draws it from math-mode syntax:
+
+```typst
+#import "@preview/fletcher:0.5.8" as fletcher: diagram, node, edge
+#set text(fill: theme.fg, size: 12pt)
+#align(center, diagram(
+ edge-stroke: theme.fg, cell-size: 15mm,
+ $
+ G edge(f, ->) edge("d", pi, ->>) & im(f) \
+ G slash ker(f) edge("ur", tilde(f), "hook-->")
+ $
+))
+```
diff --git a/render/md.typ b/render/md.typ
index 46bdc08..1c09102 100644
--- a/render/md.typ
+++ b/render/md.typ
@@ -2,10 +2,32 @@
// (the colours come from the theme). One segment = one page = one PNG.
//
// typst compile --root / --package-path <render>/packages --format png --ppi <ppi>
-// --input theme=dark|light --input width=<page width in pt>
-// --input doc=<absolute path of JSON> [--input safe=1]
-// --input theme-dir=<absolute theme folder> (themes/README.md; merged over vscode)
-// <render>/md.typ <outdir>/<a|b>-{0p}.png
+// <render>/md.typ <outdir>/<a|b>-{0p}.png, with these inputs (pt values are
+// plain numbers as strings):
+// theme=dark|light the colour scheme (default dark)
+// theme-dir=<folder> the active theme's absolute folder (themes/README.md;
+// merged over vscode)
+// doc=<path> the absolute path of the doc JSON (below)
+// width=<pt> the page width (default 600)
+// top=<pt> the first page's top margin (default 6)
+// row=<pt> one terminal row; each page is padded to whole rows
+// (default 0 = no padding)
+// code=<fraction> code size as a fraction of the body text (default 0.9)
+// term-font=<family> the terminal's font, used first for code (optional)
+// height=<pt> the room height of one drawing now (default 0 =
+// unknown: no height limit and no height factor)
+// design-w=<pt> the design page width: the `width` at the first
+// compile of the text (default = width)
+// design-h=<pt> the design room height: the `height` at the first
+// compile of the text (default = height)
+// safe=1 the retry mode (optional; below)
+//
+// Live ```typst blocks are laid out in the design space (theme.width,
+// theme.height, theme.page-width are the design values) and drawn scaled by
+// one factor for the page: f = min(content width / design content width,
+// height / design-h), without the height term when the height is unknown.
+// A block that is still wider than its space after f is made smaller to fit
+// (never larger than f); a tall block is never made smaller (the page grows).
//
// doc JSON: { "base": "/dir/for/relative/images", "segments": ["md", ...],
// "images": ["/abs/path.png", ...] (optional allow-list) }
@@ -14,7 +36,7 @@
// code (no eval), math is shown as code (no mitex), images are alt boxes.
#import "@preview/cmarker:0.1.6"
-#import "@preview/mitex:0.2.7": mitex
+#import "@preview/mitex:0.2.7": mitex-convert, mitex-scope
// ---------- inputs ----------
#let inp = sys.inputs
@@ -34,6 +56,19 @@
// Code size as a fraction of the body text (the hooks module sets it so code
// in the terminal's font is the terminal's own size).
#let code-scale = float(inp.at("code", default: "0.9"))
+// A pt input: its number in pt, else `default` (absent, empty or bad).
+#let pt-in(key, default) = {
+ let v = str(inp.at(key, default: "")).trim()
+ if v.match(regex("^[0-9]+(\\.[0-9]+)?$")) == none { default } else { float(v) * 1pt }
+}
+// The room height of one drawing now; 0pt = unknown.
+#let room-h = pt-in("height", 0pt)
+// The design: the space at the first compile of the text.
+#let design-page-w = {
+ let w = pt-in("design-w", page-w)
+ if w > margin-left + margin-right { w } else { page-w }
+}
+#let design-h = pt-in("design-h", room-h)
#let doc = if "doc" in inp { json(inp.doc) } else {
(base: "", segments: ("*md-preview:* no `doc` input given.",))
}
@@ -57,6 +92,13 @@
#let term-font = inp.at("term-font", default: "")
#let mono = if term-font != "" and T.fonts.use-terminal-font { (term-font,) + mono-base } else { mono-base }
#let content-w = page-w - margin-left - margin-right
+#let design-content-w = design-page-w - margin-left - margin-right
+// The one factor of the page's live blocks (> 0).
+#let factor = {
+ let f = content-w / design-content-w
+ if room-h > 0pt and design-h > 0pt { f = calc.min(f, room-h / design-h) }
+ if f > 0 { f } else { 1.0 }
+}
// Code size as a fraction of the body text: the theme's number, or
// "terminal" for the hooks module's `code` input (terminal-sized code).
#let code-size(v) = if v == "terminal" { code-scale } else if type(v) in (int, float) { float(v) } else { code-scale }
@@ -80,12 +122,21 @@
purple: C.purple,
palette: (C.blue, C.orange, C.green, C.red, C.purple, C.yellow),
width: content-w,
+ // The room height of a drawing (when it is unknown: 3/4 of the width).
+ height: if room-h > 0pt { room-h } else { content-w * 0.75 },
page-width: page-w,
text-size: 11pt,
sans: sans,
mono: mono,
)
+// What the code of a live block sees: the design space.
+#let live-theme = theme + (
+ width: design-content-w,
+ height: if design-h > 0pt { design-h } else { design-content-w * 0.75 },
+ page-width: design-page-w,
+)
+
// ---------- page and text ----------
#set document(title: "md-preview")
#set page(width: page-w, height: auto, margin: (left: margin-left, right: margin-right, y: margin-y), fill: none)
@@ -158,6 +209,10 @@
let desc = measure(text(top-edge: "baseline", bottom-edge: "descender", "x")).height
let pad-x = IC.pad-x-px * px
let pad-y = IC.pad-y-px * px
+ // A zero-width strut of the body text: a line with only code (a table
+ // cell, a list item) gets the body's line box, so its baseline is where
+ // the text next to it has its baseline (the code font is smaller).
+ text(font: sans, size: text.size, top-edge: "ascender", bottom-edge: "descender", sym.zwj)
h(pad-x)
highlight(
fill: C.inline-code-bg, extent: pad-x, radius: IC.radius-px * px,
@@ -180,10 +235,15 @@
}
// ---------- block quotes ----------
+// Typst's quote adds its own space around the block (a paragraph then a
+// quote had twice the paragraph gap, and a nested quote a large gap after
+// the text above it), so the gaps are set here: the paragraph gap, like
+// every other block.
#show quote.where(block: true): it => {
let Q = E.quote
block(
width: 100%, fill: C.quote-bg, radius: Q.radius-px * px,
+ above: E.text.paragraph-em * 1em, below: E.text.paragraph-em * 1em,
stroke: (left: Q.bar-px * px + C.quote-border),
inset: (left: (Q.pad-left-px + Q.bar-px) * px, right: Q.pad-right-px * px, y: Q.pad-y-em * 1em),
it.body,
@@ -248,6 +308,10 @@
want * size.width
} else { want }
let w = calc.min(w, size.width)
+ // Never taller than the room of a drawing (when it is known).
+ let w = if room-h > 0pt and nat.width > 0pt and w * (nat.height / nat.width) > room-h {
+ room-h * (nat.width / nat.height)
+ } else { w }
image(full, width: w, alt: alt)
}))
}
@@ -462,15 +526,50 @@
// ---------- ```typst fences: live Typst ----------
#let live-langs = ("typst", "typ")
+// The width that content `c` needs when it is laid out in the width `w`:
+// more than `w` only when a part with a fixed size (a canvas, a rect) is
+// wider. In Typst 0.15, measure(c, width: w) never gives more than `w`, and
+// measure(c) (no limit) gives the length of unwrapped text lines too, so:
+// content wider than `w` without a limit that does not reflow between `w`
+// and that width (the same height) needs that width; else its direct parts
+// are checked one by one (depth 1 at most: text wraps, so it never needs
+// more than `w`).
+#let needed-width(c, w, depth: 0) = {
+ if type(c) != content { return 0pt }
+ let free = measure(c).width
+ if free <= w { return free }
+ if calc.abs((measure(c, width: w).height - measure(c, width: free).height).pt()) < 0.01 { return free }
+ if depth >= 1 { return 0pt }
+ let f = c.fields()
+ let kids = if "children" in f { f.children } else if "child" in f { (f.child,) } else if "body" in f { (f.body,) } else { () }
+ kids.fold(0pt, (acc, k) => calc.max(acc, needed-width(k, w, depth: depth + 1)))
+}
#let md-raw(src, block: false, lang: none, ..args) = {
let l = if lang == none { "" } else { lower(str(lang).trim()) }
if block and not safe and l in live-langs {
// Inside a block, so #pagebreak() and #set page() are errors (one
// segment must stay one page); a column break is dropped.
- std.block(width: 100%, above: 1.2em, below: 1.2em, {
+ let drawing = {
show colbreak: none
- eval(src, mode: "markup", scope: (theme: theme))
- })
+ eval(src, mode: "markup", scope: (theme: live-theme))
+ }
+ std.block(width: 100%, above: 1.2em, below: 1.2em, layout(size => {
+ // The space here (less than the content width in a list or a quote).
+ let space = if size.width.pt() < 1e6 { size.width } else { content-w }
+ // Lay the code out in the design width (in design units: the space / f
+ // when that is less, so 100% widths fill the space here).
+ let w = calc.min(design-content-w, space / factor)
+ // Fit guard: a part with a fixed size wider than w gets a smaller
+ // factor, so it is never cut. A tall drawing is never made smaller
+ // (the page grows; the factor has the height ratio already).
+ let k = factor
+ let wide = needed-width(drawing, w)
+ if wide > w { k = calc.min(k, space / wide) }
+ // Lay a too-wide drawing out in the width it needs: in the width w, an
+ // align(center, ..) puts the extra width left of the block, where the
+ // scale cannot bring it back (it is cut off at the page edge).
+ scale(k * 100%, origin: top + left, reflow: true, std.block(width: calc.max(w, wide), drawing))
+ }))
} else if block and safe and l in live-langs {
// Retry mode: show the source, with a note that it was not drawn.
std.block(above: 1.2em, below: 0pt, sticky: true,
@@ -482,9 +581,86 @@
}
// ---------- math ----------
+// Math is drawn larger than the body text, as in VS Code's preview (KaTeX):
+// display math by the theme's math-scale, inline math by math-inline-scale.
+#let math-scale(key, default) = {
+ let v = T.at(key, default: default)
+ if type(v) in (int, float) and v > 0 and v <= 4 { float(v) } else { default }
+}
+#let display-scale = math-scale("math-scale", 1.2)
+#let inline-scale = math-scale("math-inline-scale", 1.1)
+
+// In LaTeX a bare | (and \vert, \|, \Vert) is an ordinary symbol: |x| and
+// P(A|B) are tight. mitex gives Typst a bare `|`, which Typst spaces like a
+// relation ("| x |"). So each one that is not a delimiter of \left, \right
+// or \middle becomes \mathord{|}, and \big| (\Big, \bigg, \Bigg) becomes
+// \mathord{\big|} (\bigl: \mathopen, \bigr: \mathclose, \bigm: \mathrel), as
+// in LaTeX. Text arguments (\text{a|b}, ...) are left as they are.
+#let bars = ("|", "\\vert", "\\|", "\\Vert")
+#let big-class = (l: "mathopen", r: "mathclose", m: "mathrel")
+#let latex-bars(src) = {
+ if bars.all(b => not src.contains(b)) { return src }
+ let out = ""
+ let last = 0
+ let delim = false // the token before was \left, \right or \middle
+ let big = none // the token before was \big...: (start, class)
+ let text-arg = false // the next { opens a text argument
+ let depth = 0 // brace depth inside a text argument (0 = not in one)
+ for m in src.matches(regex("\\\\([A-Za-z]+|[\\s\\S])|\\S")) {
+ let t = m.text
+ if depth > 0 {
+ if t == "{" { depth += 1 } else if t == "}" { depth -= 1 }
+ continue
+ }
+ if t == "{" and text-arg { depth = 1 }
+ if t in bars and big != none {
+ out += src.slice(last, big.at(0)) + "{\\" + big.at(1) + "{" + src.slice(big.at(0), m.end) + "}}"
+ last = m.end
+ } else if t in bars and not delim {
+ out += src.slice(last, m.start) + "{\\mathord{" + t + "}}"
+ last = m.end
+ }
+ let name = if t.starts-with("\\") { t.slice(1) } else { "" }
+ delim = name in ("left", "right", "middle")
+ let b = name.match(regex("^[bB]igg?([lrm]?)$"))
+ big = if b == none { none } else { (m.start, big-class.at(b.captures.at(0), default: "mathord")) }
+ text-arg = name.match(regex("^(text[a-z]*|mbox|hbox|emph)$")) != none
+ }
+ out + src.slice(last)
+}
+
+// LaTeX's cases is an array `@{}l@{\quad}l@{}`: every column left-aligned,
+// a quad between columns. Typst's cases puts `&` columns right, left, right,
+// ... with no gap, so mitex's `cases(x & x >= 0, ...)` reads "x x≥0". Each
+// row x & y becomes `& x && quad y`: its cells in the left-aligned columns.
+#let amp = $&$.body // an alignment point (Typst has no constructor for it)
+#let latex-row(row) = {
+ let kids = if type(row) == content and row.func() == [].func() { row.children } else { (row,) }
+ let cells = ((),)
+ for k in kids {
+ if type(k) == content and k.func() == amp.func() { cells.push(()) } else { cells.last().push(k) }
+ }
+ let cells = cells.map(c => c.join())
+ (amp, cells.first(), ..cells.slice(1).map(c => (amp, amp, h(1em), c)).flatten()).join()
+}
+#let latex-cases(..args) = math.cases(..args.named(), ..args.pos().map(latex-row))
+#let latex-scope = mitex-scope + (
+ cases: latex-cases,
+ rcases: latex-cases.with(reverse: true),
+ // mitex draws \lVert x \rVert as two bars "||"; LaTeX draws one ‖.
+ lVert: math.class("opening", sym.bar.v.double),
+ rVert: math.class("closing", sym.bar.v.double),
+)
+
#let md-math = if safe {
(src, block: false) => if block { raw(src, block: true, lang: "latex") } else { raw(src) }
-} else { mitex }
+} else {
+ (src, block: false) => {
+ let typ = mitex-convert(latex-bars(if type(src) == str { src } else { src.text }))
+ set text(size: (if block { display-scale } else { inline-scale }) * 1em)
+ math.equation(block: block, eval("$" + typ + "$", scope: latex-scope))
+ }
+}
#let kbd(attrs, body) = box(
stroke: px + C.border, inset: (x: 3pt, y: 1pt), outset: (y: 1pt), radius: 3pt,
diff --git a/render/themes/README.md b/render/themes/README.md
index 50dcfa0..b063f40 100644
--- a/render/themes/README.md
+++ b/render/themes/README.md
@@ -42,6 +42,7 @@ Example: pink inline code, rounder boxes.
| `fonts.use-terminal-font` | `true` | Put the terminal's own font first for code |
| `dark.*`, `light.*` | see `vscode/theme.json` | Colours: `fg`, `muted`, `link`, `accent` (checked boxes), `bg` (the page colour that live Typst blocks get as `theme.bg`), `border` (h1/h2 rules, hr, table rows), `th-border`, `inline-code-fg`, `inline-code-bg`, `code-fg`, `code-bg`, `code-border`, `quote-bg`, `quote-border`, `check` (tick in a checked box), `red`, `green`, `blue`, `yellow`, `orange`, `purple` (for drawings) |
| `text.leading-em` / `text.paragraph-em` | `0.38` / `1.2` | Gap between lines / between paragraphs |
+| `math-scale`, `math-inline-scale` | `1.2`, `1.1` | Size of display / inline LaTeX math, as a fraction of the text size. Live Typst blocks do not change. |
| `heading.size-em` | `[2, 1.5, 1.25, 1, 0.875, 0.85]` | h1–h6 sizes |
| `heading.weight` | `600` | |
| `heading.leading-em`, `above-em`, `below-em` | `0.2`, `[1.4, 1.6, 1.5, …]`, `[1.0, 1.0, 0.9, …]` | Spacing (arrays are per level; the last entry repeats) |
diff --git a/render/themes/vscode-modern/theme.json b/render/themes/vscode-modern/theme.json
index 63db8d9..4027e9c 100644
--- a/render/themes/vscode-modern/theme.json
+++ b/render/themes/vscode-modern/theme.json
@@ -28,5 +28,7 @@
"code-border": "#e5e5e5",
"quote-bg": "#00000007",
"quote-border": "#e5e5e5"
- }
+ },
+ "math-scale": 1.2,
+ "math-inline-scale": 1.1
}
diff --git a/render/themes/vscode/theme.json b/render/themes/vscode/theme.json
index 59c88cd..eaf5b18 100644
--- a/render/themes/vscode/theme.json
+++ b/render/themes/vscode/theme.json
@@ -61,6 +61,8 @@
"leading-em": 0.38,
"paragraph-em": 1.2
},
+ "math-scale": 1.2,
+ "math-inline-scale": 1.1,
"heading": {
"size-em": [2, 1.5, 1.25, 1, 0.875, 0.85],
"weight": 600,
diff --git a/tests/designs.test.ts b/tests/designs.test.ts
new file mode 100644
index 0000000..34707b6
--- /dev/null
+++ b/tests/designs.test.ts
@@ -0,0 +1,138 @@
+import { expect, test } from 'claude-code/testing'
+
+import { designKey, designPath, designText, hashOf, loadDesign, parseDesign, recordDesign } from '../hooks/register'
+import { forgetTouches, TOUCH_BATCH } from '../hooks/lib/typst'
+import { TOUCH_FLUSH_MS } from '../hooks/lib/settings'
+
+test('a design key comes from the text hash and the images folder', () => {
+ const textHash = hashOf(['# A diagram'])
+ expect(designKey(textHash)).toBe(hashOf(['design', textHash, '']))
+ expect(designKey(textHash, '/docs')).toBe(hashOf(['design', textHash, '/docs']))
+ expect(designKey(textHash)).toBe(designKey(textHash, ''))
+ expect(designKey(textHash, '/docs') === designKey(textHash)).toBe(false)
+ expect(designKey(textHash)).toMatch(/^[0-9a-f]{16}$/)
+})
+
+test('a design file is in a folder of its first 2 hex digits', () => {
+ expect(designPath('/cache/designs', '0a1b2c3d4e5f6071')).toBe('/cache/designs/0a/0a1b2c3d4e5f6071')
+})
+
+test('a design is the text "W0 H0" in pt', () => {
+ expect(designText({ widthPt: 512.5, heightPt: 300 })).toBe('512.5 300')
+ expect(parseDesign('512.5 300')).toEqual({ widthPt: 512.5, heightPt: 300 })
+ expect(parseDesign(' 512.5\t300\n')).toEqual({ widthPt: 512.5, heightPt: 300 })
+ const d = { widthPt: 1 / 3, heightPt: 123.456789 }
+ expect(parseDesign(designText(d))).toEqual(d)
+})
+
+test('a bad or empty design file is missing', () => {
+ for (const text of ['', '512', '512 300 1', 'a b', '0 300', '512 -1', 'NaN 300', 'Infinity 300', '512 300x']) {
+ expect(parseDesign(text)).toBe(null)
+ }
+})
+
+// ---- Host functions ---------------------------------------------------------
+
+// A fake engine with an in-memory fs: the files, and what the host did.
+// Its clock runs a timer only at `advance` (by the time asked of it).
+function disk(files: Record<string, string>) {
+ forgetTouches()
+ const seen = { reads: [] as string[], writes: [] as string[], touches: [] as string[], runs: [] as string[][] }
+ let timers: Array<{ ms: number; fn: () => void; isOff: boolean }> = []
+ const advance = (ms: number) => {
+ const due = timers.filter(t => !t.isOff && t.ms <= ms)
+ timers = timers.filter(t => !due.includes(t))
+ for (const t of due) t.fn()
+ }
+ const $ = {
+ clock: {
+ after: (ms: number, fn: () => void) => {
+ const t = { ms, fn, isOff: false }
+ timers.push(t)
+ return { cancel: () => (t.isOff = true) }
+ },
+ },
+ fs: {
+ read: async (path: string) => {
+ seen.reads.push(path)
+ if (!(path in files)) throw new Error('ENOENT')
+ return files[path]
+ },
+ exists: async (path: string) => path in files,
+ write: async (path: string, text: string) => {
+ seen.writes.push(path)
+ files[path] = text
+ },
+ },
+ process: {
+ run: async (argv: string[]) => {
+ seen.runs.push(argv)
+ if (argv[0] === 'touch' && argv[1] === '-c') seen.touches.push(...argv.slice(2))
+ return { exitCode: 0, stdout: '', stderr: '' }
+ },
+ },
+ } as any
+ return { $, seen, advance }
+}
+
+test('a missing design is null, and the miss is read once', async () => {
+ const { $, seen } = disk({})
+ expect(await loadDesign($, '/d', 'aa00000000000001')).toBe(null)
+ expect(await loadDesign($, '/d', 'aa00000000000001')).toBe(null)
+ expect(seen.reads).toEqual(['/d/aa/aa00000000000001'])
+ expect(seen.touches).toEqual([])
+})
+
+test('a design file loads once, then comes from memory, and is touched later in one batch', async () => {
+ const path = designPath('/d', 'bb00000000000002')
+ const other = designPath('/d', 'bb00000000000003')
+ const { $, seen, advance } = disk({ [path]: '500 300', [other]: '400 200' })
+ expect(await loadDesign($, '/d', 'bb00000000000002')).toEqual({ widthPt: 500, heightPt: 300 })
+ expect(await loadDesign($, '/d', 'bb00000000000002')).toEqual({ widthPt: 500, heightPt: 300 })
+ expect(await loadDesign($, '/d', 'bb00000000000003')).toEqual({ widthPt: 400, heightPt: 200 })
+ expect(seen.reads.length).toBe(2)
+ // No process while it loads (a render path): one touch after TOUCH_FLUSH_MS.
+ expect(seen.runs).toEqual([])
+ advance(TOUCH_FLUSH_MS)
+ expect(seen.runs).toEqual([['touch', '-c', path, other]])
+})
+
+test('touches go at most TOUCH_BATCH paths a run, the rest at the next run', async () => {
+ const files = Object.fromEntries(Array.from({ length: TOUCH_BATCH + 5 }, (_, i) => [designPath('/d', `ab${String(i).padStart(14, '0')}`), '1 1']))
+ const { $, seen, advance } = disk(files)
+ for (const path of Object.keys(files)) await loadDesign($, '/d', path.slice(-16))
+ advance(TOUCH_FLUSH_MS)
+ expect(seen.runs.length).toBe(1)
+ expect(seen.runs[0]!.length).toBe(2 + TOUCH_BATCH)
+ advance(TOUCH_FLUSH_MS)
+ expect(seen.runs.length).toBe(2)
+ expect(seen.touches.sort()).toEqual(Object.keys(files).sort())
+})
+
+test('a bad design text is missing', async () => {
+ const { $ } = disk({ [designPath('/d', 'cc00000000000003')]: 'junk' })
+ expect(await loadDesign($, '/d', 'cc00000000000003')).toBe(null)
+})
+
+test('record writes a design once', async () => {
+ const { $, seen } = disk({})
+ const d = { widthPt: 400, heightPt: 250 }
+ await recordDesign($, '/d', 'dd00000000000004', d)
+ await recordDesign($, '/d', 'dd00000000000004', { widthPt: 1, heightPt: 1 })
+ expect(seen.writes).toEqual(['/d/dd/dd00000000000004'])
+})
+
+test('record does not overwrite an existing file', async () => {
+ const path = designPath('/d', 'ee00000000000005')
+ const { $, seen } = disk({ [path]: '500 300' })
+ await recordDesign($, '/d', 'ee00000000000005', { widthPt: 1, heightPt: 1 })
+ expect(seen.writes).toEqual([])
+})
+
+test('record then load gives the value without a read', async () => {
+ const { $, seen } = disk({})
+ const d = { widthPt: 400, heightPt: 250 }
+ await recordDesign($, '/d', 'ff00000000000006', d)
+ expect(await loadDesign($, '/d', 'ff00000000000006')).toEqual(d)
+ expect(seen.reads).toEqual([])
+})
diff --git a/tests/draw.test.ts b/tests/draw.test.ts
index 90073d7..473966e 100644
--- a/tests/draw.test.ts
+++ b/tests/draw.test.ts
@@ -1,6 +1,8 @@
import { expect, mock, test } from 'claude-code/testing'
-import { base64Bytes, canDrawIn, DEFAULT_CELL, fitsInline, INLINE_MAX_BYTES, INLINE_MAX_SIDE, inlineBudget, renderKey, SEGMENT_ROWS } from '../hooks/register'
+import {
+ scaledBulletRow, base64Bytes, canDrawIn, COMMIT_MIN_MS, DEFAULT_CELL, fitsInline, INLINE_MAX_BYTES, INLINE_MAX_SIDE, inlineBudget, renderKey, RESIZE_QUIET_MS, SEGMENT_ROWS,
+} from '../hooks/register'
// ---- Where pictures draw ----------------------------------------------------
@@ -69,8 +71,19 @@ const TALL = '89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 06 40 00 00
// The first 33 bytes of the 1600 x 64 PNG, base64.
const PNG = 'iVBORw0KGgoAAAANSUhEUgAABkAAAABACAYAAAAAAAAA'
-// `stored`: what md-preview kept in its store before (a setting).
-function world(on: any, vars: Record<string, string>, head = HEAD, stored: Record<string, unknown> = {}) {
+// The tty, for a world with one: `line` what a read of its size prints
+// (none: the read fails); `emit` sets a new one and the Frame watcher prints
+// it (as at a SIGWINCH). `watcher`: the watcher's exit code at once instead
+// (1: no tty). `metrics` what a font measure prints (by its count, from 1).
+// With no tty, the watcher exits 1 at once.
+type Tty = { line?: string; watcher?: number; metrics?: (n: number) => string }
+
+// The PID wrapper md-preview runs Typst through (typst.ts wrapPid).
+const WRAP = 'echo $$; exec "$@"'
+
+// `stored`: what md-preview kept in its store before (a setting); `design`:
+// the text of every design file (none: they are missing).
+function world(on: any, vars: Record<string, string>, head = HEAD, stored: Record<string, unknown> = {}, design?: string, tty?: Tty) {
// md-preview's store in memory (as mock.store), and its writes by key.
const store = new Map(Object.entries(stored))
const kept: Record<string, unknown> = {}
@@ -84,31 +97,119 @@ function world(on: any, vars: Record<string, string>, head = HEAD, stored: Recor
mock.env(on, { HOME: '/h', ...vars })
const reads: string[] = []
const files = new Map<string, string>()
+ // Each compile's inputs; `hold` makes the compiles wait until `release`
+ // (with `only`: the compiles whose text has it). `kills`: the PIDs killed.
+ const compiles: Record<string, string>[] = []
+ let gate: Promise<void> | null = null
+ let gated: string | undefined
+ let open = () => {}
+ const hold = (only?: string) => {
+ gated = only
+ gate = new Promise<void>(r => (open = r))
+ }
+ const release = () => {
+ gate = null
+ open()
+ }
+ const kills: string[] = []
+ // What went to the debug log, a write each.
+ const logs: string[] = []
+ const killers = new Map<string, () => void>()
+ let pids = 4242
+ // Every call md-preview makes to a process or a file (counted by kind).
+ const calls: string[] = []
+ // The tty: its size reads (each one's time), and a new size.
+ const sizeReads: number[] = []
+ const watchers: Array<(line: string) => void> = []
+ const emit = (line: string) => {
+ tty!.line = line
+ for (const say of watchers) say(line)
+ }
+ let measures = 0
+ on('process.spawn', async function* ($: any, e: any) {
+ const argv: string[] = e.argv
+ calls.push(`spawn ${argv[0]}`)
+ if (argv[0] === 'perl') {
+ if (!tty || tty.watcher !== undefined) return { value: { code: tty?.watcher ?? 1, signal: null } }
+ // The watcher prints the size at its start, then at each change.
+ const lines: string[] = tty.line ? [tty.line] : []
+ let wake = () => {}
+ watchers.push(line => {
+ lines.push(line)
+ wake()
+ })
+ for (;;) {
+ while (lines.length) yield { stream: 'stdout', text: `${lines.shift()}\n` }
+ await new Promise<void>(r => (wake = r))
+ }
+ }
+ if (argv[0] === 'sh' && argv[2] === WRAP && argv[4] === '/usr/bin/typst' && argv[5] === 'compile') {
+ const typst = argv.slice(4)
+ const pid = String(pids++)
+ let killed = false
+ const dead = new Promise<void>(r => killers.set(pid, () => ((killed = true), r())))
+ yield { stream: 'stdout', text: `${pid}\n` }
+ compiles.push(Object.fromEntries(typst.flatMap((a, i) => (typst[i - 1] === '--input' ? [a.split(/=(.*)/s).slice(0, 2)] : []))))
+ const doc = files.get(typst.find(a => a.startsWith('doc='))?.slice(4) ?? '') ?? ''
+ if (gate && (gated === undefined || doc.includes(gated))) await Promise.race([gate, dead])
+ killers.delete(pid)
+ return { value: killed ? { code: null, signal: 'SIGTERM' } : { code: 0, signal: null } }
+ }
+ return { value: { code: 1, signal: null } }
+ })
on('process.run', async ($: any, e: any) => {
const argv: string[] = e.argv
const cmd = argv.join(' ')
+ calls.push(`run ${argv[0]}`)
+ if (argv[0] === 'kill') {
+ kills.push(argv[1]!)
+ killers.get(argv[1]!)?.()
+ return ok('')
+ }
+ if (tty && argv[0] === 'sh' && cmd.includes('ioctl(T')) {
+ sizeReads.push(clock.now())
+ return tty.line ? ok(tty.line) : ok('', 1)
+ }
+ if (tty?.metrics && argv[0] === '/usr/bin/typst' && argv[1] === 'eval') return ok(tty.metrics(++measures))
+ if (cmd.includes('debug.log')) {
+ logs.push(e.init?.stdin ?? '')
+ return ok('')
+ }
if (/md-preview-/.test(cmd)) return ok('/c\nDarwin\n')
if (cmd.includes('command -v typst')) return ok('/usr/bin/typst\n')
if (argv[0] === '/usr/bin/typst' && argv[1] === 'eval') return ok('{}')
- if (argv[0] === '/usr/bin/typst' && argv[1] === 'compile') return ok('')
if (cmd.includes('od -An')) return ok(`${head}\n@\n`)
return ok('', 1)
})
on('fs.write', async ($: any, e: any) => {
+ calls.push('fs.write')
files.set(e.path, e.text)
return { value: undefined }
})
on('fs.read', async ($: any, e: any, next: any) => {
+ calls.push('fs.read')
if (e.as === 'bytes') {
reads.push(e.path)
return { value: { base64: PNG } }
}
+ if (e.path.includes('/designs/')) return design === undefined ? { deny: 'ENOENT' } : { value: design }
return files.has(e.path) ? { value: files.get(e.path) } : e.path.startsWith('/c/') ? { deny: 'ENOENT' } : next(e)
})
- on('fs.list', async ($: any, e: any, next: any) => (e.path.startsWith('/c/') ? { value: [{ name: 'a-1.png', kind: 'file', size: 1, mtimeMs: 1, isLink: false }] } : next(e)))
+ on('fs.exists', async ($: any, e: any, next: any) => {
+ calls.push('fs.exists')
+ return e.path.includes('/designs/') ? { value: design !== undefined || files.has(e.path) } : next(e)
+ })
+ on('fs.list', async ($: any, e: any, next: any) => {
+ calls.push('fs.list')
+ return e.path.startsWith('/c/') ? { value: [{ name: 'a-1.png', kind: 'file', size: 1, mtimeMs: 1, isLink: false }] } : next(e)
+ })
+ on('fs.stat', async ($: any, e: any, next: any) => {
+ calls.push('fs.stat')
+ return next(e)
+ })
on('ui.toast', async () => ({ value: undefined }))
on('ui.render', () => ENGINE as any)
- return { clock, reads, kept }
+ return { clock, reads, kept, compiles, files, hold, release, emit, sizeReads, kills, calls, logs }
}
const ENGINE = { type: 'Text', props: {}, children: ['engine drawing'] }
@@ -172,7 +273,7 @@ test('in tmux with the engine forced, answers stay text', async ($, on) => {
const wide = (requestId: string, text: string) => ({ ...message(requestId, text), viewport: { columns: 300, rows: 40 } })
-test('a kept width caps the pictures; width full draws at the terminal width at once, 255 columns at most', async ($, on) => {
+test('a kept width caps the pictures; width full draws at the terminal width once its epoch commits, 255 columns at most', async ($, on) => {
const { clock, kept } = world(on, { TERM: 'xterm-kitty' }, HEAD, { width: 160 })
const ran = await $.command.run({ command: 'md-preview', args: '' } as any)
expect(ran.text).toContain('width 160 columns')
@@ -184,8 +285,10 @@ test('a kept width caps the pictures; width full draws at the terminal width at
const set = await $.command.run({ command: 'md-preview', args: 'width full' } as any)
expect(set.text).toContain('full (the terminal width)')
expect(kept.width).toBe('full')
- // Another key (the columns are in it): compiled again, then drawn wider.
+ // Another key (the columns are in it): compiled again, then drawn wider
+ // when the epoch commits.
await clock.settle()
+ await clock.advance(COMMIT_MIN_MS)
await ui.redraw(props('Some **bold** text.'))
const [now] = images(await ui.drawn())
expect(now.props.columns).toBe(255)
@@ -203,3 +306,413 @@ test('width with no value shows it; a bad value is refused; a bad kept value is
expect(set.text).toContain('400 columns (a picture is 255 columns at most)')
expect(kept.width).toBe(400)
})
+
+// ---- The box of a page ---------------------------------------------------------
+
+test('while a new size compiles, the old picture draws at its own box, never stretched', async ($, on) => {
+ const { clock, hold, release } = world(on, { TERM: 'xterm-kitty' }, HEAD, { width: 160 })
+ await $.command.run({ command: 'md-preview', args: '' } as any)
+ const ui = await $.ui.mount(wide('box-1', 'Some **bold** text.'))
+ await clock.settle()
+ await ui.redraw(props('Some **bold** text.'))
+ const [first] = images(await ui.drawn())
+ expect(first.props.columns).toBe(160)
+ expect(first.props.source.generation).toBe(undefined)
+ hold()
+ await $.command.run({ command: 'md-preview', args: 'width full' } as any)
+ await clock.settle()
+ await clock.advance(COMMIT_MIN_MS)
+ await ui.redraw(props('Some **bold** text.'))
+ const [stale] = images(await ui.drawn())
+ expect(stale.props.source.file).toBe(first.props.source.file)
+ expect(stale.props.columns).toBe(160)
+ expect(stale.props.rows).toBe(first.props.rows)
+ release()
+ await clock.settle()
+ await ui.redraw(props('Some **bold** text.'))
+ const [now] = images(await ui.drawn())
+ expect(now.props.columns).toBe(255)
+ expect(now.props.source.file).not.toBe(first.props.source.file)
+})
+
+test('the pages column never shrinks: the layout never squeezes a page (fitBox sizes it)', async ($, on) => {
+ const { clock } = world(on, { TERM: 'xterm-kitty' })
+ await $.command.run({ command: 'md-preview', args: '' } as any)
+ const ui = await $.ui.mount(message('shrink-1', 'Some **bold** text.'))
+ await clock.settle()
+ await ui.redraw(props('Some **bold** text.'))
+ const tree: any = await ui.drawn()
+ const column = tree.children.find((c: any) => c.type === 'Box' && images(c).length && c.props.flexDirection === 'column')
+ expect(column.props.flexShrink).toBe(0)
+})
+
+// ---- The Frame -------------------------------------------------------------------
+
+// A tty of 120 columns and 40 rows, cell 16 x 32; the same with cell 19 x 38.
+const TTY = '40 120 1920 1280'
+const TTY_BIG_FONT = '40 120 2280 1520'
+const sized = (requestId: string, text: string, columns: number, rows = 40) => ({ ...message(requestId, text), viewport: { columns, rows } })
+
+test('after the viewport gets narrower, nothing compiles until it is quiet; meanwhile the old picture fits the room, its aspect kept', async ($, on) => {
+ const { clock, compiles } = world(on, { TERM: 'xterm-kitty' }, HEAD, {}, undefined, { line: TTY })
+ await $.command.run({ command: 'md-preview', args: '' } as any)
+ const ui = await $.ui.mount(sized('f-1', 'Some **bold** text.', 120))
+ await clock.settle()
+ await ui.redraw(props('Some **bold** text.'))
+ const [first] = images(await ui.drawn())
+ expect(first.props.columns).toBe(118)
+ expect(compiles.length).toBe(1)
+ // The engine draws the row again at 100 columns at once.
+ await ui.unmount()
+ const narrow = await $.ui.mount(sized('f-1', 'Some **bold** text.', 100))
+ await clock.settle()
+ await narrow.redraw(props('Some **bold** text.'))
+ const [stale] = images(await narrow.drawn())
+ expect(compiles.length).toBe(1)
+ expect(stale.props.source.file).toBe(first.props.source.file)
+ expect(stale.props.columns).toBe(98)
+ expect(stale.props.rows).toBe(Math.max(1, Math.round((first.props.rows * 98) / 118)))
+ // Quiet: one compile at the new width; it shows when the epoch commits.
+ await clock.advance(RESIZE_QUIET_MS)
+ expect(compiles.length).toBe(2)
+ await clock.advance(COMMIT_MIN_MS)
+ await narrow.redraw(props('Some **bold** text.'))
+ const [now] = images(await narrow.drawn())
+ expect(compiles.length).toBe(2)
+ expect(now.props.columns).toBe(98)
+ expect(now.props.source.file).not.toBe(first.props.source.file)
+ // A page of the target is never drawn smaller.
+ expect(now.props.source.generation).toBe(undefined)
+})
+
+// The bullet's row in a drawn answer (the gutter Box's marginTop).
+const bulletOf = (tree: any): number => tree.children.find((c: any) => c.type === 'Box' && !images(c).length).props.marginTop
+
+test('an old page wider than the room after a narrowing draws at the room, its aspect kept and its bullet scaled', async ($, on) => {
+ const { clock, hold } = world(on, { TERM: 'xterm-kitty' }, HEAD, {}, undefined, { line: '40 213 3408 1360' })
+ await $.command.run({ command: 'md-preview', args: '' } as any)
+ const text = '# A title\n\nSome **bold** text.'
+ const ui = await $.ui.mount(sized('room-1', text, 213))
+ await clock.settle()
+ await ui.redraw(props(text))
+ const tree: any = await ui.drawn()
+ const [first] = images(tree)
+ expect(first.props.columns).toBe(211)
+ const bullet = bulletOf(tree)
+ expect(bullet).toBeGreaterThan(0)
+ // Narrower, and the new compile held past the commit's wait.
+ hold()
+ await ui.unmount()
+ const narrow = await $.ui.mount(sized('room-1', text, 120))
+ await narrow.redraw(props(text))
+ await clock.advance(RESIZE_QUIET_MS)
+ await clock.advance(COMMIT_MIN_MS)
+ await narrow.redraw(props(text))
+ const small: any = await narrow.drawn()
+ const [old] = images(small)
+ expect(old.props.source.file).toBe(first.props.source.file)
+ expect(old.props.columns).toBe(118)
+ expect(old.props.rows).toBe(Math.max(1, Math.round((first.props.rows * 118) / 211)))
+ expect(old.props.source.generation).toBe(118 * 1000 + old.props.rows)
+ expect(bulletOf(small)).toBe(scaledBulletRow(bullet, 118 / 211))
+})
+
+test('an old page narrower than the room draws at its own box', async ($, on) => {
+ const { clock, hold } = world(on, { TERM: 'xterm-kitty' }, HEAD, { width: 160 })
+ await $.command.run({ command: 'md-preview', args: '' } as any)
+ const ui = await $.ui.mount(wide('own-1', 'Some **bold** text.'))
+ await clock.settle()
+ await ui.redraw(props('Some **bold** text.'))
+ const [first] = images(await ui.drawn())
+ expect(first.props.columns).toBe(160)
+ hold()
+ await ui.unmount()
+ const narrower = await $.ui.mount(sized('own-1', 'Some **bold** text.', 200))
+ await narrower.redraw(props('Some **bold** text.'))
+ const [old] = images(await narrower.drawn())
+ expect(old.props).toEqual(first.props)
+})
+
+test('the row memo misses when the viewport columns change, and hits when only onScreen changes', async ($, on) => {
+ const { clock, calls } = world(on, { TERM: 'xterm-kitty' })
+ await $.command.run({ command: 'md-preview', args: '' } as any)
+ const ui = await $.ui.mount(message('memo-1', 'Some **bold** text.'))
+ await clock.settle()
+ await ui.redraw(props('Some **bold** text.'))
+ const [first] = images(await ui.drawn())
+ expect(first.props.columns).toBe(98)
+ // The engine draws every row again at the new width, before it is quiet:
+ // a new tree, its page fit to the room.
+ await ui.unmount()
+ const narrow = await $.ui.mount(sized('memo-1', 'Some **bold** text.', 80))
+ const [fit] = images(await narrow.drawn())
+ expect(fit.props.columns).toBe(78)
+ const before = calls.length
+ for (const onScreen of [{ first: 0, last: 3, of: 9 }, null, undefined]) {
+ await narrow.redraw({ ...props('Some **bold** text.'), onScreen })
+ expect(images(await narrow.drawn())[0].props).toEqual(fit.props)
+ }
+ expect(calls.slice(before)).toEqual([])
+})
+
+// The epoch trace lines a size change writes to the debug log.
+async function traceOf($: any, on: any, vars: Record<string, string>): Promise<string[]> {
+ const { clock, logs } = world(on, vars)
+ await $.command.run({ command: 'md-preview', args: '' } as any)
+ const ui = await $.ui.mount(message('trace-1', 'Some **bold** text.'))
+ await clock.settle()
+ await ui.redraw(props('Some **bold** text.'))
+ await $.command.run({ command: 'md-preview', args: 'size 120' } as any)
+ await ui.redraw(props('Some **bold** text.'))
+ await clock.settle()
+ await clock.advance(COMMIT_MIN_MS)
+ return logs.filter(l => / epoch \d+ /.test(l))
+}
+
+test('with MD_PREVIEW_DEBUG, an epoch writes one trace line at its begin and one at its commit', async ($, on) => {
+ const trace = await traceOf($, on, { TERM: 'xterm-kitty', MD_PREVIEW_DEBUG: '1' })
+ expect(trace.length).toBe(2)
+ expect(trace[0]).toMatch(/epoch \d+ begin: target 100x40 cell \d+(\.\d+)?x\d+(\.\d+)?; cancelled 0 running, dropped 0 queued/)
+ expect(trace[1]).toMatch(/epoch \d+ commit after \d+ ms \(ready\): 1 jobs queued, 0 waiting, 0 running, 0 converting/)
+})
+
+test('with no MD_PREVIEW_DEBUG, an epoch writes no trace line', async ($, on) => {
+ expect(await traceOf($, on, { TERM: 'xterm-kitty' })).toEqual([])
+})
+
+test('a drag (5 watcher lines in a row) compiles nothing and reads no tty until it is quiet, then once', async ($, on) => {
+ const { clock, compiles, emit, sizeReads } = world(on, { TERM: 'xterm-kitty' }, HEAD, {}, undefined, { line: TTY })
+ await $.command.run({ command: 'md-preview', args: '' } as any)
+ const ui = await $.ui.mount(sized('drag-1', 'Some **bold** text.', 200))
+ await clock.settle()
+ await ui.redraw(props('Some **bold** text.'))
+ const [first] = images(await ui.drawn())
+ expect(first.props.columns).toBe(118)
+ expect(compiles.length).toBe(1)
+ const reads = sizeReads.length
+ for (const columns of [115, 110, 105, 100, 95]) {
+ emit(`40 ${columns} ${columns * 16} 1280`)
+ await clock.advance(RESIZE_QUIET_MS - 50)
+ await ui.redraw(props('Some **bold** text.'))
+ expect(compiles.length).toBe(1)
+ expect(sizeReads.length).toBe(reads)
+ expect(images(await ui.drawn())[0].props.source.file).toBe(first.props.source.file)
+ }
+ await clock.advance(50)
+ expect(sizeReads.length).toBe(reads + 1)
+ await clock.advance(COMMIT_MIN_MS)
+ await ui.redraw(props('Some **bold** text.'))
+ expect(compiles.length).toBe(2)
+ expect(images(await ui.drawn())[0].props.columns).toBe(93)
+})
+
+test('two rows, one compile held: both keep the old picture, then both swap in one redraw', async ($, on) => {
+ const { clock, compiles, hold, release } = world(on, { TERM: 'xterm-kitty' }, HEAD, { width: 160 })
+ // The `done` writes (each one a redraw of every row), counted from the
+ // width command.
+ let redraws = 0
+ on('state.set', async ($: any, e: any, next: any) => {
+ if (e.key === 'done') redraws++
+ return next(e)
+ })
+ await $.command.run({ command: 'md-preview', args: '' } as any)
+ const a = await $.ui.mount(wide('two-a', 'First **answer**.'))
+ const b = await $.ui.mount(wide('two-b', 'Second **answer**.'))
+ await clock.settle()
+ await a.redraw(props('First **answer**.'))
+ await b.redraw(props('Second **answer**.'))
+ const oldA = images(await a.drawn())[0].props.source.file
+ const oldB = images(await b.drawn())[0].props.source.file
+ expect(compiles.length).toBe(2)
+ redraws = 0
+ hold('Second')
+ await $.command.run({ command: 'md-preview', args: 'width full' } as any)
+ await clock.settle()
+ await clock.advance(COMMIT_MIN_MS)
+ await a.redraw(props('First **answer**.'))
+ await b.redraw(props('Second **answer**.'))
+ // A's new picture is ready, but the epoch waits for B's.
+ expect(compiles.length).toBe(4)
+ expect(images(await a.drawn())[0].props.source.file).toBe(oldA)
+ expect(images(await b.drawn())[0].props.source.file).toBe(oldB)
+ release()
+ await clock.settle()
+ // The commit's one refresh drew both rows again (no redraw by the test).
+ const nowA = images(await a.drawn())[0].props
+ const nowB = images(await b.drawn())[0].props
+ expect(nowA.source.file).not.toBe(oldA)
+ expect(nowB.source.file).not.toBe(oldB)
+ expect([nowA.columns, nowB.columns]).toEqual([255, 255])
+ // One redraw at the begin of the epoch, one at its commit.
+ expect(redraws).toBe(2)
+})
+
+test('a redraw with a new onScreen makes no file or process call and draws the same picture', async ($, on) => {
+ const { clock, calls } = world(on, { TERM: 'xterm-kitty' })
+ await $.command.run({ command: 'md-preview', args: '' } as any)
+ const ui = await $.ui.mount(message('scroll-1', 'Some **bold** text.'))
+ await clock.settle()
+ await ui.redraw(props('Some **bold** text.'))
+ const [first] = images(await ui.drawn())
+ const before = calls.length
+ for (const onScreen of [{ first: 0, last: 3, of: 9 }, null, { first: 2, last: 8, of: 9 }, undefined]) {
+ await ui.redraw({ ...props('Some **bold** text.'), onScreen })
+ expect(images(await ui.drawn())[0].props).toEqual(first.props)
+ }
+ expect(calls.slice(before)).toEqual([])
+})
+
+test('a font size change with the same columns compiles once, with a new key', async ($, on) => {
+ const { clock, compiles, emit } = world(on, { TERM: 'xterm-kitty' }, HEAD, {}, undefined, { line: TTY })
+ await $.command.run({ command: 'md-preview', args: '' } as any)
+ const ui = await $.ui.mount(sized('f-2', 'Some **bold** text.', 120))
+ await clock.settle()
+ await ui.redraw(props('Some **bold** text.'))
+ const [first] = images(await ui.drawn())
+ expect(compiles.length).toBe(1)
+ // The watcher prints the new size at the SIGWINCH; nothing until quiet.
+ emit(TTY_BIG_FONT)
+ await clock.settle()
+ await ui.redraw(props('Some **bold** text.'))
+ expect(compiles.length).toBe(1)
+ await clock.advance(RESIZE_QUIET_MS)
+ await clock.advance(COMMIT_MIN_MS)
+ await ui.redraw(props('Some **bold** text.'))
+ const [now] = images(await ui.drawn())
+ // The fonts measured again give the same metrics: no second wave.
+ await clock.advance(1000)
+ await ui.redraw(props('Some **bold** text.'))
+ expect(compiles.length).toBe(2)
+ expect(now.props.source.file).not.toBe(first.props.source.file)
+ expect(now.props.columns).toBe(118)
+})
+
+test('a font size change that changes the font metrics is still one compile wave, with the new metrics', async ($, on) => {
+ const other = '{"term":null,"menlo":{"adv":0.6,"xh":0.5,"avg":0.6},"body":{"adv":0.6,"xh":0.5,"avg":0.5}}'
+ const { clock, compiles, emit } = world(on, { TERM: 'xterm-kitty' }, HEAD, {}, undefined, { line: TTY, metrics: n => (n === 1 ? '{}' : other) })
+ await $.command.run({ command: 'md-preview', args: '' } as any)
+ const ui = await $.ui.mount(sized('f-3', 'Some **bold** text.', 120))
+ await clock.settle()
+ await ui.redraw(props('Some **bold** text.'))
+ expect(compiles.length).toBe(1)
+ emit(TTY_BIG_FONT)
+ await clock.advance(RESIZE_QUIET_MS)
+ await clock.advance(COMMIT_MIN_MS)
+ await ui.redraw(props('Some **bold** text.'))
+ await clock.advance(1000)
+ await ui.redraw(props('Some **bold** text.'))
+ expect(compiles.length).toBe(2)
+ expect(compiles[1]!.code).not.toBe(compiles[0]!.code)
+})
+
+test('a height change only compiles a message with a Typst block again, not a plain one', async ($, on) => {
+ const { clock, compiles, emit } = world(on, { TERM: 'xterm-kitty' }, HEAD, {}, undefined, { line: TTY })
+ await $.command.run({ command: 'md-preview', args: '' } as any)
+ const diagram = await $.ui.mount(sized('h-1', DIAGRAM, 120))
+ const plain = await $.ui.mount(sized('h-2', 'Some **bold** text.', 120))
+ await clock.settle()
+ await diagram.redraw(props(DIAGRAM))
+ await plain.redraw(props('Some **bold** text.'))
+ expect(compiles.length).toBe(2)
+ const before = compiles.find(c => c.height !== undefined)!
+ emit('50 120 1920 1600')
+ await clock.advance(RESIZE_QUIET_MS)
+ await clock.advance(COMMIT_MIN_MS)
+ await diagram.redraw(props(DIAGRAM))
+ await plain.redraw(props('Some **bold** text.'))
+ expect(compiles.length).toBe(3)
+ expect(Number(compiles[2]!.height)).toBeGreaterThan(Number(before.height))
+ // Same design: the first one.
+ expect(compiles[2]!['design-h']).toBe(before['design-h'])
+})
+
+test('a watcher that exits 1 (no tty) starts no reads', async ($, on) => {
+ const { clock, sizeReads } = world(on, { TERM: 'xterm-kitty' }, HEAD, {}, undefined, { watcher: 1 })
+ await $.command.run({ command: 'md-preview', args: '' } as any)
+ await clock.advance(30000)
+ expect(sizeReads.length).toBe(1)
+})
+
+// ---- The room of a drawing ------------------------------------------------------
+
+const DIAGRAM = 'A plot:\n\n```typst\n#rect(width: theme.width, height: theme.height)\n```'
+
+test('a first render of a diagram: the design is the space now (factor 1), kept once the compile ends', async ($, on) => {
+ const { clock, compiles, files } = world(on, { TERM: 'xterm-kitty' })
+ await $.command.run({ command: 'md-preview', args: '' } as any)
+ const ui = await $.ui.mount(message('room-1', DIAGRAM))
+ await clock.settle()
+ await ui.redraw(props(DIAGRAM))
+ expect(images(await ui.drawn()).length).toBe(1)
+ const [inputs] = compiles
+ expect(Number(inputs!.height)).toBeGreaterThan(0)
+ expect(inputs!['design-w']).toBe(inputs!.width)
+ expect(inputs!['design-h']).toBe(inputs!.height)
+ const kept = [...files].filter(([path]) => path.includes('/designs/'))
+ expect(kept.length).toBe(1)
+ expect(kept[0]![1]).toBe(`${inputs!.width} ${inputs!.height}`)
+ // A plain answer gets no room: its key does not follow the rows.
+ const plain = await $.ui.mount(message('room-2', 'Some **bold** text.'))
+ await clock.settle()
+ await plain.redraw(props('Some **bold** text.'))
+ expect(compiles[1]!.height).toBe(undefined)
+ expect(compiles[1]!['design-w']).toBe(undefined)
+})
+
+test('a first render at any width sends design-w equal to width (factor exactly 1)', async ($, on) => {
+ const { clock, compiles } = world(on, { TERM: 'xterm-kitty' })
+ await $.command.run({ command: 'md-preview', args: '' } as any)
+ for (const [i, columns] of [117, 83, 251].entries()) {
+ // A plain row settles the new viewport first (it has no design).
+ const settle = await $.ui.mount({ ...message(`room-pre-${i}`, `Plain ${i}.`), viewport: { columns, rows: 37 } })
+ await clock.advance(RESIZE_QUIET_MS)
+ await clock.advance(COMMIT_MIN_MS)
+ await settle.unmount()
+ const ui = await $.ui.mount({ ...message(`room-w-${i}`, `${DIAGRAM}\n\n${i}`), viewport: { columns, rows: 37 } })
+ await clock.settle()
+ await ui.redraw(props(`${DIAGRAM}\n\n${i}`))
+ await ui.unmount()
+ const inputs = compiles.filter(c => c['design-w'] !== undefined)[i]!
+ expect(Number(inputs.width)).toBeGreaterThan(0)
+ expect(inputs['design-w']).toBe(inputs.width)
+ expect(inputs['design-h']).toBe(inputs.height)
+ }
+})
+
+test('a resize while the first compile runs: the compile is killed, the next uses the same design, one design file', async ($, on) => {
+ const { clock, compiles, files, hold, release, kills } = world(on, { TERM: 'xterm-kitty' })
+ await $.command.run({ command: 'md-preview', args: '' } as any)
+ hold()
+ const ui = await $.ui.mount(sized('race-1', DIAGRAM, 100))
+ await clock.settle()
+ await ui.unmount()
+ const resized = await $.ui.mount(sized('race-1', DIAGRAM, 90))
+ await clock.settle()
+ expect(compiles.length).toBe(1)
+ // Quiet: the epoch kills the compile at 100 columns and compiles at 90.
+ await clock.advance(RESIZE_QUIET_MS)
+ expect(kills.length).toBe(1)
+ expect(compiles.length).toBe(2)
+ release()
+ await clock.settle()
+ await clock.advance(COMMIT_MIN_MS)
+ await resized.redraw(props(DIAGRAM))
+ expect(images(await resized.drawn()).length).toBe(1)
+ expect(compiles.length).toBe(2)
+ expect(compiles[1]!['design-w']).toBe(compiles[0]!['design-w'])
+ expect(compiles[1]!['design-w']).toBe(compiles[0]!.width)
+ expect(compiles[1]!.width).not.toBe(compiles[0]!.width)
+ expect([...files.keys()].filter(path => path.includes('/designs/')).length).toBe(1)
+})
+
+test('a diagram with a kept design scales from it, and the design is not written again', async ($, on) => {
+ const { clock, compiles, files } = world(on, { TERM: 'xterm-kitty' }, HEAD, {}, '500 200')
+ await $.command.run({ command: 'md-preview', args: '' } as any)
+ const ui = await $.ui.mount(message('room-3', DIAGRAM))
+ await clock.settle()
+ await ui.redraw(props(DIAGRAM))
+ expect(images(await ui.drawn()).length).toBe(1)
+ expect(compiles[0]!['design-w']).toBe('500')
+ expect(compiles[0]!['design-h']).toBe('200')
+ expect([...files.keys()].filter(path => path.includes('/designs/'))).toEqual([])
+})
diff --git a/tests/epoch.test.ts b/tests/epoch.test.ts
new file mode 100644
index 0000000..3cdf9ae
--- /dev/null
+++ b/tests/epoch.test.ts
@@ -0,0 +1,254 @@
+import { expect, test } from 'claude-code/testing'
+
+// This file's own copy of the modules: the epoch and the state it reads.
+import { beginEpoch, extendEpoch, holdJobs, jobDone, releaseJobs } from '../hooks/lib/epoch'
+import { COMMIT_MAX_MS, COMMIT_MIN_MS, DEFAULT_CELL } from '../hooks/lib/settings'
+import { converting, epochOpen, queue, running, S, type Frame, type Job } from '../hooks/lib/state'
+
+const frame = (columns: number, rows = 40): Frame => ({ columns, rows, cell: DEFAULT_CELL })
+
+// A timer in memory: `advance` runs each wait that comes due, in order.
+function fakeClock() {
+ let now = 0
+ let waits: Array<{ due: number; fn: () => void; live: boolean }> = []
+ return {
+ after: (ms: number, fn: () => void) => {
+ const wait = { due: now + ms, fn, live: true }
+ waits.push(wait)
+ return { cancel: () => void (wait.live = false) }
+ },
+ advance: async (ms: number) => {
+ const end = now + ms
+ for (;;) {
+ const next = waits.filter(w => w.live && w.due <= end).sort((a, b) => a.due - b.due)[0]
+ if (!next) break
+ now = next.due
+ next.live = false
+ next.fn()
+ }
+ now = end
+ waits = waits.filter(w => w.live)
+ await flush()
+ },
+ }
+}
+// Lets the redraws asked for (a promise each) arrive.
+const flush = async () => {
+ for (let i = 0; i < 50; i++) await Promise.resolve()
+}
+
+// A `$` with the clock in memory; each refresh ends as an invalidate here
+// (the `done` write is refused for this `$`), counted in `redraws`.
+const clock = fakeClock()
+const seen = { redraws: 0 }
+const $ = { clock: { after: clock.after }, ui: { invalidate: () => void seen.redraws++ } } as any
+const redraws = async () => {
+ await flush()
+ return seen.redraws
+}
+
+// A fresh start: the old epoch's timers ran out, nothing open, waiting or
+// running, the Frame on screen is the target.
+async function fresh() {
+ await clock.advance(COMMIT_MAX_MS * 2)
+ S.shownEpoch = S.epoch
+ S.frame = S.shown = frame(100)
+ S.resizing = S.missed = false
+ queue.length = 0
+ running.clear()
+ converting.clear()
+ await flush()
+ seen.redraws = 0
+}
+
+// A running entry's signal (never aborted here).
+const SIGNAL = new AbortController().signal
+
+const job = (key: string, o: { epoch?: number; onScreen?: boolean } = {}) =>
+ ({ key, requestId: key, text: key, epoch: o.epoch ?? S.epoch, onScreen: o.onScreen }) as unknown as Job
+
+test('a new epoch cancels the compiles that run, empties the queue, sets the target and redraws once', async () => {
+ await fresh()
+ const cancelled: string[] = []
+ running.set('a', { job: job('a'), cancel: () => cancelled.push('a'), signal: SIGNAL })
+ running.set('b', { job: job('b'), cancel: () => cancelled.push('b'), signal: SIGNAL })
+ queue.push(job('c'), job('d'))
+ const target = frame(80)
+ beginEpoch($, target)
+ expect(cancelled).toEqual(['a', 'b'])
+ expect(queue.length).toBe(0)
+ expect(S.frame).toEqual(target)
+ // A copy: the caller's object is not the target.
+ expect(S.frame).not.toBe(target)
+ expect(epochOpen()).toBe(true)
+ expect(S.shown).toEqual(frame(100))
+ expect(await redraws()).toBe(1)
+})
+
+test('an epoch with no jobs commits COMMIT_MIN_MS after it began, not before', async () => {
+ await fresh()
+ beginEpoch($, frame(80))
+ await clock.advance(COMMIT_MIN_MS - 1)
+ expect(epochOpen()).toBe(true)
+ expect(S.shown).toEqual(frame(100))
+ await clock.advance(1)
+ expect(epochOpen()).toBe(false)
+ expect(S.shown).toEqual(frame(80))
+ // One redraw at the begin, one at the commit.
+ expect(await redraws()).toBe(2)
+})
+
+test('activity in the epoch (a row, a job) starts COMMIT_MIN_MS again; COMMIT_MAX_MS still counts from the begin', async () => {
+ await fresh()
+ beginEpoch($, frame(80))
+ await clock.advance(COMMIT_MIN_MS - 10)
+ extendEpoch($)
+ await clock.advance(COMMIT_MIN_MS - 10)
+ expect(epochOpen()).toBe(true)
+ await clock.advance(10)
+ expect(epochOpen()).toBe(false)
+ // Once committed, nothing to extend: no timer, no redraw.
+ extendEpoch($)
+ await clock.advance(COMMIT_MIN_MS)
+ expect(await redraws()).toBe(2)
+ // Activity with no end: the epoch commits at COMMIT_MAX_MS.
+ beginEpoch($, frame(70))
+ for (let t = 0; t < COMMIT_MAX_MS; t += COMMIT_MIN_MS / 2) {
+ expect(epochOpen()).toBe(true)
+ extendEpoch($)
+ await clock.advance(COMMIT_MIN_MS / 2)
+ }
+ expect(epochOpen()).toBe(false)
+ expect(S.shown).toEqual(frame(70))
+})
+
+test('with no Frame given, an epoch keeps the target (a mode or a setting changed)', async () => {
+ await fresh()
+ S.frame = frame(90)
+ beginEpoch($)
+ expect(S.frame).toEqual(frame(90))
+ await clock.advance(COMMIT_MIN_MS)
+ expect(S.shown).toEqual(frame(90))
+})
+
+test('a job of the epoch on screen (or not known) holds the commit; its end commits, with one redraw for all', async () => {
+ await fresh()
+ beginEpoch($, frame(80))
+ const a = job('a', { onScreen: true })
+ const b = job('b')
+ queue.push(a)
+ running.set('b', { job: b, cancel: () => {}, signal: SIGNAL })
+ await clock.advance(COMMIT_MIN_MS)
+ expect(epochOpen()).toBe(true)
+ // `a` starts: it holds the commit while it runs.
+ queue.length = 0
+ running.set('a', { job: a, cancel: () => {}, signal: SIGNAL })
+ running.delete('b')
+ jobDone($)
+ expect(epochOpen()).toBe(true)
+ running.delete('a')
+ jobDone($)
+ expect(epochOpen()).toBe(false)
+ expect(S.shown).toEqual(frame(80))
+ // The begin and the commit: the jobs that ended did not redraw.
+ expect(await redraws()).toBe(2)
+})
+
+test('a job known off screen and a job of an old epoch do not hold the commit', async () => {
+ await fresh()
+ const old = S.epoch
+ beginEpoch($, frame(80))
+ queue.push(job('off', { onScreen: false }))
+ running.set('old', { job: job('old', { epoch: old }), cancel: () => {}, signal: SIGNAL })
+ await clock.advance(COMMIT_MIN_MS)
+ expect(epochOpen()).toBe(false)
+ expect(S.shown).toEqual(frame(80))
+})
+
+test('a JPEG or WebP convert holds the commit', async () => {
+ await fresh()
+ beginEpoch($, frame(80))
+ converting.set('x', Promise.resolve(null))
+ await clock.advance(COMMIT_MIN_MS)
+ expect(epochOpen()).toBe(true)
+ converting.delete('x')
+ jobDone($)
+ expect(epochOpen()).toBe(false)
+})
+
+test('at COMMIT_MAX_MS the epoch commits with its jobs still running', async () => {
+ await fresh()
+ beginEpoch($, frame(80))
+ running.set('slow', { job: job('slow', { onScreen: true }), cancel: () => {}, signal: SIGNAL })
+ await clock.advance(COMMIT_MAX_MS - 1)
+ expect(epochOpen()).toBe(true)
+ await clock.advance(1)
+ expect(epochOpen()).toBe(false)
+ expect(S.shown).toEqual(frame(80))
+})
+
+test('a new epoch has new timers: the old one\'s do not commit it early', async () => {
+ await fresh()
+ beginEpoch($, frame(80))
+ await clock.advance(COMMIT_MIN_MS / 2)
+ beginEpoch($, frame(70))
+ await clock.advance(COMMIT_MIN_MS / 2)
+ expect(epochOpen()).toBe(true)
+ await clock.advance(COMMIT_MIN_MS / 2)
+ expect(epochOpen()).toBe(false)
+ expect(S.shown).toEqual(frame(70))
+})
+
+test('a burst holds the commit; a commit that came due during it happens at its release', async () => {
+ await fresh()
+ beginEpoch($, frame(80))
+ holdJobs()
+ await clock.advance(COMMIT_MIN_MS)
+ expect(epochOpen()).toBe(true)
+ releaseJobs($)
+ expect(epochOpen()).toBe(false)
+ expect(S.shown).toEqual(frame(80))
+})
+
+test('the COMMIT_MAX_MS commit that came due during a burst happens at its release', async () => {
+ await fresh()
+ beginEpoch($, frame(80))
+ running.set('slow', { job: job('slow', { onScreen: true }), cancel: () => {}, signal: SIGNAL })
+ await clock.advance(COMMIT_MIN_MS)
+ holdJobs()
+ await clock.advance(COMMIT_MAX_MS)
+ expect(epochOpen()).toBe(true)
+ releaseJobs($)
+ expect(epochOpen()).toBe(false)
+})
+
+test('a burst that begins a new epoch drops the old one\'s flags', async () => {
+ await fresh()
+ beginEpoch($, frame(80))
+ holdJobs()
+ await clock.advance(COMMIT_MIN_MS)
+ // The quiet found a new Frame.
+ beginEpoch($, frame(70))
+ expect(S.resizing).toBe(false)
+ expect(epochOpen()).toBe(true)
+ await clock.advance(COMMIT_MIN_MS)
+ expect(S.shown).toEqual(frame(70))
+})
+
+test('a job that ends with no epoch open redraws; during a burst it redraws once at the release', async () => {
+ await fresh()
+ jobDone($)
+ expect(await redraws()).toBe(1)
+ holdJobs()
+ jobDone($)
+ jobDone($)
+ expect(S.missed).toBe(true)
+ expect(await redraws()).toBe(1)
+ releaseJobs($)
+ expect(S.missed).toBe(false)
+ expect(await redraws()).toBe(2)
+ // A burst with no job that ended: no redraw.
+ holdJobs()
+ releaseJobs($)
+ expect(await redraws()).toBe(2)
+})
diff --git a/tests/frame.test.ts b/tests/frame.test.ts
new file mode 100644
index 0000000..d4c49c4
--- /dev/null
+++ b/tests/frame.test.ts
@@ -0,0 +1,358 @@
+import { expect, test } from 'claude-code/testing'
+
+import {
+ composeFrame, followWatcher, frameChange, frameFor, frameOfLine, lineSplitter, noteTty, noteView, pictureColumns, quietTimer, setFrame, shownFor,
+ type Frame,
+} from '../hooks/lib/frame'
+import { COMMIT_MIN_MS, DEFAULT_CELL, IMAGE_MAX_COLUMNS, RESIZE_QUIET_MS } from '../hooks/lib/settings'
+import { INLINE_MAX_SIDE } from '../hooks/lib/terminal'
+import { FRAME_PL } from '../hooks/lib/host'
+// The module state the Frame reads and sets (this file's copy of the
+// modules is the one imported above).
+import { converting, queue, running, S } from '../hooks/lib/state'
+
+const frame = (columns: number, rows: number, width = 16, height = 32): Frame => ({ columns, rows, cell: { width, height } })
+
+test('the same frame is no change', () => {
+ expect(frameChange(frame(100, 40), frame(100, 40))).toBe('none')
+})
+
+test('the first read and a new cell are a cell change, also with the same columns', () => {
+ expect(frameChange(null, frame(100, 40))).toBe('cell')
+ expect(frameChange(frame(100, 40), frame(100, 40, 18, 36))).toBe('cell')
+ expect(frameChange(frame(100, 40), frame(100, 40, 16, 34))).toBe('cell')
+ // The cell goes first when the columns change too (a font size change).
+ expect(frameChange(frame(100, 40), frame(90, 36, 18, 36))).toBe('cell')
+})
+
+test('columns go before rows; rows only is a rows change', () => {
+ expect(frameChange(frame(100, 40), frame(120, 40))).toBe('columns')
+ expect(frameChange(frame(100, 40), frame(120, 50))).toBe('columns')
+ expect(frameChange(frame(100, 40), frame(100, 50))).toBe('rows')
+})
+
+// ---- One watcher line ---------------------------------------------------------
+
+test('a watcher line is rows, columns and the cell in device pixels', () => {
+ expect(frameOfLine('50 120 2040 1700')).toEqual(frame(120, 50, 17, 34))
+ expect(frameOfLine('40 200 3200 1360\n')).toEqual(frame(200, 40, 16, 34))
+})
+
+test('a line with no pixels (tmux, a relay) is no Frame', () => {
+ expect(frameOfLine('50 200 0 0')).toBe(null)
+ expect(frameOfLine('0 0 0 0')).toBe(null)
+})
+
+test('an absurd or broken line is no Frame', () => {
+ // A cell under 4 or over 64 px wide.
+ expect(frameOfLine('50 200 600 1700')).toBe(null)
+ expect(frameOfLine('50 20 1700 1700')).toBe(null)
+ expect(frameOfLine('')).toBe(null)
+ expect(frameOfLine('50 120 2040')).toBe(null)
+ expect(frameOfLine('50 120 2040 1700 9')).toBe(null)
+ expect(frameOfLine('50 120 20x0 1700')).toBe(null)
+ expect(frameOfLine('-50 120 2040 1700')).toBe(null)
+})
+
+// ---- Pieces to lines ----------------------------------------------------------
+
+test('pieces join into lines across their borders', () => {
+ const split = lineSplitter()
+ expect(split('50 12')).toEqual([])
+ expect(split('0 2040 1700\n40 2')).toEqual(['50 120 2040 1700'])
+ expect(split('00 3200 1360\n')).toEqual(['40 200 3200 1360'])
+ expect(split('1 2 3 4\n5 6 7 8\n')).toEqual(['1 2 3 4', '5 6 7 8'])
+ expect(split('9 9 9 9\r\n')).toEqual(['9 9 9 9'])
+})
+
+const pieces = (texts: Array<{ stream?: 'stdout' | 'stderr'; text: string }>, code: number | null) =>
+ (async function* () {
+ for (const p of texts) yield { stream: p.stream ?? ('stdout' as const), text: p.text }
+ return { code, signal: null }
+ })()
+
+test('the watcher lines go to noteTty as Frames; a bad line goes as null', async () => {
+ const seen: Array<Frame | null> = []
+ const ended = await followWatcher(pieces([{ text: '50 120 20' }, { text: '40 1700\n' }, { stream: 'stderr', text: '1 1 1 1\n' }, { text: 'junk\n40 200 3200 1360\n' }], 0), f => seen.push(f))
+ expect(seen).toEqual([frame(120, 50, 17, 34), null, frame(200, 40, 16, 34)])
+ expect(ended).toBe('failed')
+})
+
+test('a watcher that exits 1 has no tty; one that can not start failed', async () => {
+ expect(await followWatcher(pieces([], 1), () => undefined)).toBe('no tty')
+ const broken = (async function* (): AsyncGenerator<{ stream: 'stdout'; text: string }, { code: number }> {
+ throw new Error('ENOENT')
+ })()
+ expect(await followWatcher(broken, () => undefined)).toBe('failed')
+})
+
+// ---- The watcher -----------------------------------------------------------------
+
+test('FRAME_PL sleeps in sigsuspend with SIGWINCH blocked outside it: no select, no poll', () => {
+ expect(FRAME_PL).toContain('POSIX::sigsuspend(')
+ expect(FRAME_PL).toContain('POSIX::sigprocmask(POSIX::SIG_BLOCK()')
+ expect(FRAME_PL).toContain('$n{WINCH}')
+ // The alarm only finds a dead parent.
+ expect(FRAME_PL).toContain('alarm(10)')
+ expect(FRAME_PL).not.toContain('select')
+ expect(FRAME_PL).not.toContain('sleep')
+})
+
+// ---- The quiet timer ----------------------------------------------------------------
+
+// A timer in memory: `advance` runs each wait that comes due, in order.
+function fakeClock() {
+ let now = 0
+ let waits: Array<{ due: number; fn: () => void; live: boolean }> = []
+ return {
+ after: (ms: number, fn: () => void) => {
+ const wait = { due: now + ms, fn, live: true }
+ waits.push(wait)
+ return { cancel: () => void (wait.live = false) }
+ },
+ advance: async (ms: number) => {
+ const end = now + ms
+ for (;;) {
+ const next = waits.filter(w => w.live && w.due <= end).sort((a, b) => a.due - b.due)[0]
+ if (!next) break
+ now = next.due
+ next.live = false
+ next.fn()
+ await flush()
+ }
+ now = end
+ waits = waits.filter(w => w.live)
+ await flush()
+ },
+ }
+}
+// Lets the promises started settle.
+const flush = async () => {
+ for (let i = 0; i < 50; i++) await Promise.resolve()
+}
+
+function quiet() {
+ const clock = fakeClock()
+ const seen: string[] = []
+ const stales: Array<() => boolean> = []
+ const poke = quietTimer({
+ ms: 450,
+ after: clock.after,
+ onStart: () => seen.push('start'),
+ onQuiet: stale => {
+ seen.push('quiet')
+ stales.push(stale)
+ },
+ })
+ return { clock, poke, seen, stales }
+}
+
+test('a drag gives one start and one quiet, 450 ms after its last input', async () => {
+ const q = quiet()
+ for (let i = 0; i < 10; i++) {
+ q.poke()
+ await q.clock.advance(100)
+ }
+ expect(q.seen).toEqual(['start'])
+ await q.clock.advance(349)
+ expect(q.seen).toEqual(['start'])
+ await q.clock.advance(1)
+ expect(q.seen).toEqual(['start', 'quiet'])
+ // A new burst starts again.
+ q.poke()
+ await q.clock.advance(450)
+ expect(q.seen).toEqual(['start', 'quiet', 'start', 'quiet'])
+})
+
+test('a quiet is stale once a newer input came', async () => {
+ const q = quiet()
+ q.poke()
+ await q.clock.advance(450)
+ expect(q.stales[0]!()).toBe(false)
+ q.poke()
+ expect(q.stales[0]!()).toBe(true)
+ expect(q.seen).toEqual(['start', 'quiet', 'start'])
+})
+
+// ---- Composing the Frame --------------------------------------------------------------
+
+test('the Frame is the tty\'s, at most the viewport wide; its rows are the tty\'s', () => {
+ expect(composeFrame(frame(200, 50, 17, 34), { columns: 150, rows: 40 })).toEqual(frame(150, 50, 17, 34))
+ expect(composeFrame(frame(200, 50, 17, 34), { columns: 300, rows: 60 })).toEqual(frame(200, 50, 17, 34))
+ expect(composeFrame(frame(200, 50, 17, 34), null)).toEqual(frame(200, 50, 17, 34))
+})
+
+test('with no tty, the Frame is the viewport (else 80 x 48) and DEFAULT_CELL', () => {
+ expect(composeFrame(null, { columns: 120, rows: 30 })).toEqual({ columns: 120, rows: 30, cell: DEFAULT_CELL })
+ expect(composeFrame(null, null)).toEqual({ columns: 80, rows: 48, cell: DEFAULT_CELL })
+})
+
+test('the Frame for a drawing is the target; a picture drawn now sizes from the Frame on screen', () => {
+ const was = { frame: S.frame, shown: S.shown }
+ try {
+ S.frame = frame(200, 50, 17, 34)
+ S.shown = frame(160, 50, 17, 34)
+ expect(frameFor({ columns: 150, rows: 40 })).toEqual(frame(200, 50, 17, 34))
+ expect(frameFor()).toEqual(frame(200, 50, 17, 34))
+ expect(shownFor({ columns: 150, rows: 40 })).toEqual(frame(160, 50, 17, 34))
+ // Nothing on screen yet: the target.
+ S.shown = null
+ expect(shownFor()).toEqual(frame(200, 50, 17, 34))
+ // No Frame at all: the viewport.
+ S.frame = null
+ expect(frameFor({ columns: 120, rows: 30 })).toEqual({ columns: 120, rows: 30, cell: DEFAULT_CELL })
+ expect(shownFor()).toEqual({ columns: 80, rows: 48, cell: DEFAULT_CELL })
+ } finally {
+ S.frame = was.frame
+ S.shown = was.shown
+ }
+})
+
+test('a picture takes the Frame\'s columns less the gutter, capped by the width setting and, over ssh, by the cell', () => {
+ const was = S.width
+ try {
+ S.width = 'full'
+ expect(pictureColumns(frame(120, 40), false)).toBe(118)
+ // Over ssh a { png } source is INLINE_MAX_SIDE px wide at most.
+ expect(pictureColumns(frame(400, 40), true)).toBe(Math.min(IMAGE_MAX_COLUMNS, Math.floor(INLINE_MAX_SIDE / 16)))
+ S.width = 60
+ expect(pictureColumns(frame(120, 40), false)).toBe(60)
+ } finally {
+ S.width = was
+ }
+})
+
+// ---- Settling a burst ------------------------------------------------------------------
+
+// One `$` for the settle tests (the quiet timer keeps the first one): a
+// clock in memory, a tty read the test sets (and may hold), and the redraws.
+const clock = fakeClock()
+const tty = { line: '50 200 3400 1700', reads: 0, gate: null as Promise<void> | null, refreshes: 0 }
+const $ = {
+ clock: { after: clock.after },
+ process: {
+ run: async () => {
+ tty.reads++
+ if (tty.gate) await tty.gate
+ return { exitCode: 0, stdout: tty.line, stderr: '' }
+ },
+ },
+ ui: { invalidate: () => void tty.refreshes++ },
+} as any
+
+// A load with this tty read at setUp (no epoch open, nothing held).
+async function loaded(line: string | null) {
+ await clock.advance(10000)
+ S.shownEpoch = S.epoch
+ S.frame = S.shown = S.tty = null
+ S.viewColumns = S.viewRows = null
+ S.resizing = S.missed = false
+ queue.length = 0
+ running.clear()
+ converting.clear()
+ if (line) tty.line = line
+ setFrame(line ? frameOfLine(line) : null)
+ tty.reads = 0
+ tty.refreshes = 0
+}
+
+test('setUp\'s read is the target and the Frame on screen; the first viewport applies at once', async () => {
+ await loaded('50 200 3400 1700')
+ expect(S.frame).toEqual(frame(200, 50, 17, 34))
+ expect(S.shown).toEqual(frame(200, 50, 17, 34))
+ noteView($, { columns: 150, rows: 50 })
+ expect(S.frame).toEqual(frame(150, 50, 17, 34))
+ expect(S.shown).toEqual(frame(150, 50, 17, 34))
+ expect(S.resizing).toBe(false)
+ // The watcher's first line is the value known: no burst.
+ noteTty($, frameOfLine('50 200 3400 1700'))
+ expect(S.resizing).toBe(false)
+ await clock.advance(1000)
+ expect(tty.reads).toBe(0)
+})
+
+test('a drag holds the jobs, then one read sets the target; the pictures follow at the commit', async () => {
+ await loaded('50 200 3400 1700')
+ noteView($, { columns: 200, rows: 50 })
+ const epoch = S.epoch
+ for (let c = 190; c >= 120; c -= 10) {
+ if (c < 190) await clock.advance(100)
+ noteTty($, frameOfLine(`50 ${c} ${c * 17} 1700`))
+ expect(S.resizing).toBe(true)
+ }
+ expect(tty.reads).toBe(0)
+ expect(S.frame).toEqual(frame(200, 50, 17, 34))
+ // The tty read at quiet wins over the last line.
+ tty.line = '50 118 2006 1700'
+ await clock.advance(RESIZE_QUIET_MS)
+ expect(tty.reads).toBe(1)
+ expect(S.resizing).toBe(false)
+ expect(S.epoch).toBe(epoch + 1)
+ expect(S.frame).toEqual(frame(118, 50, 17, 34))
+ expect(S.shown).toEqual(frame(200, 50, 17, 34))
+ await clock.advance(COMMIT_MIN_MS)
+ expect(S.shown).toEqual(frame(118, 50, 17, 34))
+})
+
+test('a burst that ends at the same Frame begins no epoch and lets the jobs go on', async () => {
+ await loaded('50 200 3400 1700')
+ noteView($, { columns: 200, rows: 50 })
+ const epoch = S.epoch
+ noteTty($, frameOfLine('50 180 3060 1700'))
+ noteTty($, frameOfLine('50 200 3400 1700'))
+ expect(S.resizing).toBe(true)
+ await clock.advance(RESIZE_QUIET_MS)
+ expect(tty.reads).toBe(1)
+ expect(S.resizing).toBe(false)
+ expect(S.epoch).toBe(epoch)
+})
+
+test('a narrower viewport settles like a tty line; viewport rows alone do not count with a tty', async () => {
+ await loaded('50 200 3400 1700')
+ noteView($, { columns: 200, rows: 50 })
+ const epoch = S.epoch
+ noteView($, { columns: 200, rows: 30 })
+ expect(S.resizing).toBe(false)
+ noteView($, { columns: 160, rows: 30 })
+ expect(S.resizing).toBe(true)
+ expect(S.frame).toEqual(frame(200, 50, 17, 34))
+ await clock.advance(RESIZE_QUIET_MS)
+ expect(S.epoch).toBe(epoch + 1)
+ expect(S.frame).toEqual(frame(160, 50, 17, 34))
+})
+
+test('with no tty, the viewport is the Frame and a change settles with no read', async () => {
+ await loaded(null)
+ noteView($, { columns: 120, rows: 30 })
+ expect(S.frame).toEqual({ columns: 120, rows: 30, cell: DEFAULT_CELL })
+ const epoch = S.epoch
+ noteView($, { columns: 120, rows: 40 })
+ expect(S.resizing).toBe(true)
+ await clock.advance(RESIZE_QUIET_MS)
+ expect(tty.reads).toBe(0)
+ expect(S.epoch).toBe(epoch + 1)
+ expect(S.frame).toEqual({ columns: 120, rows: 40, cell: DEFAULT_CELL })
+})
+
+test('an input during the quiet read stops that settle: the newer quiet settles once', async () => {
+ await loaded('50 200 3400 1700')
+ noteView($, { columns: 200, rows: 50 })
+ const epoch = S.epoch
+ let open = () => {}
+ tty.gate = new Promise<void>(r => (open = r))
+ tty.line = '50 150 2550 1700'
+ noteTty($, frameOfLine('50 150 2550 1700'))
+ await clock.advance(RESIZE_QUIET_MS)
+ expect(tty.reads).toBe(1)
+ noteTty($, frameOfLine('50 140 2380 1700'))
+ tty.gate = null
+ tty.line = '50 140 2380 1700'
+ open()
+ await flush()
+ expect(S.epoch).toBe(epoch)
+ expect(S.resizing).toBe(true)
+ await clock.advance(RESIZE_QUIET_MS)
+ expect(tty.reads).toBe(2)
+ expect(S.epoch).toBe(epoch + 1)
+ expect(S.frame).toEqual(frame(140, 50, 17, 34))
+})
diff --git a/tests/images.test.ts b/tests/images.test.ts
index 224ed8c..b57a549 100644
--- a/tests/images.test.ts
+++ b/tests/images.test.ts
@@ -2,7 +2,7 @@ import { expect, mock, test } from 'claude-code/testing'
import {
claudeTmpOf, convertBox, convertCall, convertedPath, DEFAULT_CELL, folderOf, imageKindOf, isMarkdownPath, pasteDirOf, pastedImagePath, pastedNumbers,
- DEFAULT_HEIGHT, parseCommand, PICTURE_MAX_ROWS, PICTURE_ROOM_ROWS, pictureCells, pictureRowsFor, projectSlug, renderKey, sentFiles, sentImages,
+ COMMIT_MIN_MS, DEFAULT_HEIGHT, parseCommand, RESIZE_QUIET_MS, PICTURE_MAX_ROWS, PICTURE_ROOM_ROWS, pictureCells, pictureRowsFor, projectSlug, renderKey, sentFiles, sentImages,
} from '../hooks/register'
// ---- Pure helpers -----------------------------------------------------------
@@ -216,13 +216,23 @@ function world(on: any, o: {
holdRun?: { at: number; until: Promise<void> }
holdCompile?: Promise<void>
} = {}) {
- // md-preview's store in memory (as mock.store), and its writes by key.
+ // md-preview's store in memory (as mock.store), and its writes by key;
+ // `redrawsAt`: by key, the `done` writes (redraws) made when its write ended.
const store = new Map(Object.entries(o.stored ?? {}))
const kept: Record<string, unknown> = {}
+ const redrawsAt: Record<string, number> = {}
+ let redraws = 0
+ on('state.set', async ($: any, e: any, next: any) => {
+ if (e.key === 'done') redraws++
+ return next(e)
+ })
on('store.get', async ($: any, e: any) => ({ value: store.get(e.key) }))
on('store.set', async ($: any, e: any) => {
store.set(e.key, e.value)
kept[e.key] = e.value
+ // A write to the host takes a while: what was asked before it lands.
+ for (let i = 0; i < 50; i++) await Promise.resolve()
+ redrawsAt[e.key] = redraws
return { value: undefined }
})
const clock = mock.clock(on)
@@ -247,9 +257,24 @@ function world(on: any, o: {
w.done()
}
}
+ // The children md-preview spawns: the Frame watcher (it exits 1: no tty)
+ // and a Markdown compile through the PID wrapper (typst.ts wrapPid).
+ let pids = 4242
+ on('process.spawn', async function* ($: any, e: any) {
+ const argv: string[] = e.argv
+ if (argv[0] === 'sh' && argv[2] === 'echo $$; exec "$@"' && argv[4] === '/usr/bin/typst' && argv[5] === 'compile') {
+ yield { stream: 'stdout', text: `${pids++}\n` }
+ const doc = argv.find(a => a.startsWith('doc='))!.slice(4)
+ docs.push(JSON.parse(written.get(doc)!))
+ await o.holdCompile
+ return { value: { code: 0, signal: null } }
+ }
+ return { value: { code: 1, signal: null } }
+ })
on('process.run', async ($: any, e: any) => {
const argv: string[] = e.argv
const cmd = argv.join(' ')
+ if (argv[0] === 'kill') return ok('')
if (/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)
@@ -270,12 +295,6 @@ function world(on: any, o: {
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 all = argv.slice(4)
heads.push(...all)
@@ -318,7 +337,7 @@ function world(on: any, o: {
})
on('ui.toast', async () => ({ value: undefined }))
on('ui.render', () => ENGINE as any)
- return { clock, heads, reads, converts, moves, docs, logs, files, texts, mtimes, written, kept }
+ return { clock, heads, reads, converts, moves, docs, logs, files, texts, mtimes, written, kept, redrawsAt, redraws: () => redraws }
}
const sent = (output: unknown, isErrored = false, id = 'tu-1') =>
@@ -417,30 +436,37 @@ test('a JPEG by its name; two rows at once convert it once; a changed file conve
expect(converts.length).toBe(2)
})
-test('a new box: the last PNG draws at once, a run for the box starts, and its refresh draws the new PNG', async ($, on) => {
+test('a new box: the last PNG draws until the epoch commits; the PNG for the target is made meanwhile and the commit waits for it', async ($, on) => {
let release = () => {}
const until = new Promise<void>(done => (release = done))
const { clock, converts } = world(on, { typst: true, holdRun: { at: 2, until }, files: { '/t/photo.jpg': JPEG } })
await ready($)
const wide = await $.ui.mount(sent(attachAll('/t/photo.jpg'), false, 'tu-1'))
const first = images(await wide.drawn())[0].props.source.file
- // The same file in a narrower row: 58 columns, so another box.
- const narrow = await $.ui.mount({ ...sent(attachAll('/t/photo.jpg'), false, 'tu-2'), viewport: { columns: 60, rows: 40 } })
+ expect(converts.length).toBe(1)
+ // The transcript gets narrower (58 columns, so another box): nothing runs
+ // until it is quiet.
+ await wide.unmount()
+ const narrow = await $.ui.mount({ ...sent(attachAll('/t/photo.jpg'), false, 'tu-1'), viewport: { columns: 60, rows: 40 } })
+ expect(images(await narrow.drawn())[0].props.source.file).toBe(first)
+ expect(converts.length).toBe(1)
+ // Quiet: the epoch begins; the old PNG draws, the target's is made.
+ await clock.advance(RESIZE_QUIET_MS)
expect(images(await narrow.drawn())[0].props.source.file).toBe(first)
expect(converts.length).toBe(2)
expect(converts[1]).toContain('maxw=928')
- // While it runs, the narrow row and a third box do not wait or run again.
- await narrow.redraw(sent(attachAll('/t/photo.jpg'), false, 'tu-2').props)
- const other = await $.ui.mount({ ...sent(attachAll('/t/photo.jpg'), false, 'tu-3'), viewport: { columns: 80, rows: 40 } })
- expect(images(await other.drawn())[0].props.source.file).toBe(first)
+ // While it runs, a redraw does not run it again, and the epoch waits.
+ await clock.advance(COMMIT_MIN_MS)
+ await narrow.redraw(sent(attachAll('/t/photo.jpg'), false, 'tu-1').props)
+ expect(images(await narrow.drawn())[0].props.source.file).toBe(first)
+ expect(images(await narrow.drawn())[0].props.columns).toBe(40)
expect(converts.length).toBe(2)
release()
await clock.settle()
- // The refresh drew the rows again: the narrow row has its own PNG now.
+ // The commit drew the row again: its own PNG now.
const now = images(await narrow.drawn())[0].props.source.file
- expect(now).not.toBe(first)
expect(now).toBe(convertedPath('/c', '/t/photo.jpg', '1:1000', { width: 928, height: 640 }))
- expect(images(await wide.drawn())[0].props.source.file).toBe(first)
+ expect(converts.length).toBe(2)
})
test('a failed run for a new box keeps the last PNG', async ($, on) => {
@@ -449,15 +475,35 @@ test('a failed run for a new box keeps the last PNG', async ($, on) => {
await ready($)
const wide = await $.ui.mount(sent(attachAll('/t/photo.jpg'), false, 'tu-1'))
const first = images(await wide.drawn())[0].props.source.file
- const narrow = await $.ui.mount({ ...sent(attachAll('/t/photo.jpg'), false, 'tu-2'), viewport: { columns: 60, rows: 40 } })
- expect(images(await narrow.drawn())[0].props.source.file).toBe(first)
- await clock.settle()
- await narrow.redraw(sent(attachAll('/t/photo.jpg'), false, 'tu-2').props)
+ await wide.unmount()
+ const narrow = await $.ui.mount({ ...sent(attachAll('/t/photo.jpg'), false, 'tu-1'), viewport: { columns: 60, rows: 40 } })
+ await clock.advance(RESIZE_QUIET_MS)
+ await clock.advance(COMMIT_MIN_MS)
+ await narrow.redraw(sent(attachAll('/t/photo.jpg'), false, 'tu-1').props)
expect(images(await narrow.drawn())[0].props.source.file).toBe(first)
expect(converts.length).toBe(2)
expect(logs.join('')).toContain('convert /t/photo.jpg failed')
})
+test('a sent PNG keeps its generation when the viewport changes; only its box follows', async ($, on) => {
+ // 3136 x 640 px: wider than the transcript.
+ const WIDE = '89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 0c 40 00 00 02 80'
+ const { clock } = world(on, { files: { '/t/wide.png': WIDE } })
+ await ready($)
+ const ui = await $.ui.mount(sent(attach('/t/wide.png')))
+ const [before] = images(await ui.drawn())
+ expect(before.props.columns).toBe(98)
+ await ui.unmount()
+ const narrow = await $.ui.mount({ ...sent(attach('/t/wide.png')), viewport: { columns: 60, rows: 40 } })
+ // Not quiet yet: the box on screen, made smaller to fit the room.
+ expect(images(await narrow.drawn())[0].props.columns).toBe(58)
+ await clock.advance(RESIZE_QUIET_MS)
+ await clock.advance(COMMIT_MIN_MS)
+ const [after] = images(await narrow.drawn())
+ expect(after.props.columns).toBe(58)
+ expect(after.props.source.generation).toBe(before.props.source.generation)
+})
+
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($)
@@ -559,6 +605,38 @@ test('while a Markdown file compiles: an empty space, then for a moment the row
expect(images(await ui.drawn()).map(i => i.props.alt)).toEqual(['Notes', 'one.png'])
})
+test('a kept SendUserFile row gives a new onScreen to its Markdown files\' jobs: one known off screen does not hold the commit', async ($, on) => {
+ // 3136 x 640 px: its box follows the columns, so it shows the commit.
+ const WIDE = '89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 0c 40 00 00 02 80'
+ const o: Parameters<typeof world>[1] = { typst: true, files: { '/t/wide.png': WIDE }, texts: { '/t/notes.md': '# Notes' } }
+ const { clock, redraws } = world(on, o)
+ await ready($)
+ const output = attachAll('/t/wide.png', '/t/notes.md')
+ const ui = await $.ui.mount(sent(output))
+ await clock.settle()
+ await ui.redraw(sent(output).props)
+ expect(images(await ui.drawn()).map(i => i.props.columns)).toEqual([98, 98])
+ // Narrower: the epoch's compile of the Markdown file is held.
+ let release = () => {}
+ o.holdCompile = new Promise<void>(done => (release = done))
+ await ui.unmount()
+ const narrow = await $.ui.mount({ ...sent(output), viewport: { columns: 60, rows: 40 } })
+ await clock.advance(RESIZE_QUIET_MS)
+ await narrow.redraw(sent(output).props)
+ // The old boxes, made smaller to fit the room.
+ expect(images(await narrow.drawn()).map(i => i.props.columns)).toEqual([58, 58])
+ // Scrolled off screen: the kept row, and its job no longer holds the commit
+ // (its one redraw).
+ await narrow.redraw({ ...sent(output).props, onScreen: null })
+ const before = redraws()
+ await clock.advance(COMMIT_MIN_MS)
+ expect(redraws()).toBe(before + 1)
+ await narrow.redraw(sent(output).props)
+ expect(images(await narrow.drawn())[0].props.columns).toBe(58)
+ release()
+ await clock.settle()
+})
+
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($)
@@ -589,7 +667,7 @@ test('a Markdown file that is empty, too large, gone or not Markdown leaves the
expect(reads).toEqual(['/t/empty.md'])
})
-test('a Markdown file is read again only when its stat changes', async ($, on) => {
+test('a Markdown file is read again only when its stat changes, seen at the next refresh', 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')))
@@ -598,6 +676,13 @@ test('a Markdown file is read again only when its stat changes', async ($, on) =
expect(reads).toEqual(['/t/n.md'])
texts['/t/n.md'] = '# Two'
mtimes['/t/n.md'] = 2
+ // A redraw with nothing new (a scroll step) reads no file.
+ await ui.redraw(sent(attachAll('/t/n.md')).props)
+ await clock.settle()
+ expect(reads).toEqual(['/t/n.md'])
+ // A refresh (here a setting) draws the row anew: the new stat is seen.
+ await $.command.run({ command: 'md-preview', args: 'size 100' } as any)
+ await clock.settle()
await ui.redraw(sent(attachAll('/t/n.md')).props)
await clock.settle()
expect(reads).toEqual(['/t/n.md', '/t/n.md'])
@@ -664,10 +749,10 @@ test('in a terminal that draws no pictures, rows stay as they are', async ($, on
// ---- The height setting -------------------------------------------------------
-test('a kept height caps sent and pasted images; height full draws them taller at once', async ($, on) => {
- const { kept } = world(on, { stored: { height: 12 }, files: { '/t/tall.png': TALL, [`${PASTED}/5.png`]: TALL }, dirs: [PASTED] })
+test('a kept height caps sent and pasted images; height full draws them taller at the commit', async ($, on) => {
+ const { clock, kept } = world(on, { stored: { height: 12 }, files: { '/t/tall.png': TALL, [`${PASTED}/5.png`]: TALL }, dirs: [PASTED] })
const ran = await ready($)
- expect(ran.text).toContain('image height 12 rows')
+ expect(ran.text).toContain('image and drawing height 12 rows')
const ui = await $.ui.mount(sent(attach('/t/tall.png')))
expect(images(await ui.drawn())[0].props.rows).toBe(12)
const pasted = await $.ui.mount(prompt('[Image #5] tall'))
@@ -675,7 +760,11 @@ test('a kept height caps sent and pasted images; height full draws them taller a
const set = await $.command.run({ command: 'md-preview', args: 'height full' } as any)
expect(set.text).toContain('full (the terminal height less 16 rows)')
expect(kept.height).toBe('full')
- // 40 rows less 16.
+ // The epoch is open: the box on screen stays.
+ await ui.redraw(sent(attach('/t/tall.png')).props)
+ expect(images(await ui.drawn())[0].props.rows).toBe(12)
+ // It commits: 40 rows less 16.
+ await clock.advance(COMMIT_MIN_MS)
await ui.redraw(sent(attach('/t/tall.png')).props)
expect(images(await ui.drawn())[0].props.rows).toBe(24)
await pasted.redraw(prompt('[Image #5] tall').props)
@@ -683,14 +772,75 @@ test('a kept height caps sent and pasted images; height full draws them taller a
// A number is never more than full.
await $.command.run({ command: 'md-preview', args: 'height 36' } as any)
expect(kept.height).toBe(36)
+ await clock.advance(COMMIT_MIN_MS)
await ui.redraw(sent(attach('/t/tall.png')).props)
expect(images(await ui.drawn())[0].props.rows).toBe(24)
// Half, the default: half of 40 rows.
await $.command.run({ command: 'md-preview', args: 'height half' } as any)
+ await clock.advance(COMMIT_MIN_MS)
await ui.redraw(sent(attach('/t/tall.png')).props)
expect(images(await ui.drawn())[0].props.rows).toBe(20)
})
+test('a height command while an epoch is open keeps the image box until the commit', async ($, on) => {
+ let release = () => {}
+ const until = new Promise<void>(done => (release = done))
+ // The second convert (the JPEG for the new height) holds the commit.
+ const { clock, converts } = world(on, { typst: true, stored: { height: 12 }, holdRun: { at: 2, until }, files: { '/t/tall.png': TALL, '/t/photo.jpg': JPEG } })
+ await ready($)
+ const output = attachAll('/t/tall.png', '/t/photo.jpg')
+ const ui = await $.ui.mount(sent(output))
+ expect(images(await ui.drawn()).map(i => i.props.rows)).toEqual([12, 10])
+ // An epoch is open (a new text size), then the height changes.
+ await $.command.run({ command: 'md-preview', args: 'size 90' } as any)
+ await $.command.run({ command: 'md-preview', args: 'height full' } as any)
+ await ui.redraw(sent(output).props)
+ expect(images(await ui.drawn())[0].props.rows).toBe(12)
+ expect(converts[1]).toContain('maxh=768')
+ // Past COMMIT_MIN_MS the convert still runs: the box stays.
+ await clock.advance(COMMIT_MIN_MS)
+ await ui.redraw(sent(output).props)
+ expect(images(await ui.drawn())[0].props.rows).toBe(12)
+ // It ends: the epoch commits, the PNG and the JPEG change together.
+ release()
+ await clock.settle()
+ const [png, jpeg] = images(await ui.drawn())
+ expect(png.props.rows).toBe(24)
+ expect(jpeg.props.source.file).toBe(convertedPath('/c', '/t/photo.jpg', '1:1000', { width: 1568, height: 768 }))
+ expect(converts.length).toBe(2)
+})
+
+test('in an open epoch a JPEG with no PNG made in this load (a resumed session) is converted once, for the target, and draws at the commit', async ($, on) => {
+ let release = () => {}
+ const until = new Promise<void>(done => (release = done))
+ const { clock, converts } = world(on, { typst: true, holdRun: { at: 1, until }, files: { '/t/photo.jpg': JPEG } })
+ await ready($)
+ await $.command.run({ command: 'md-preview', args: 'height full' } as any)
+ const ui = await $.ui.mount(sent(attachAll('/t/photo.jpg')))
+ // Nothing under the row for it until the commit; only the target's PNG is made.
+ expect(images(await ui.drawn()).length).toBe(0)
+ expect(converts.length).toBe(1)
+ expect(converts[0]).toContain('maxh=768')
+ await clock.advance(COMMIT_MIN_MS)
+ await ui.redraw(sent(attachAll('/t/photo.jpg')).props)
+ expect(images(await ui.drawn()).length).toBe(0)
+ expect(converts.length).toBe(1)
+ release()
+ await clock.settle()
+ expect(images(await ui.drawn())[0].props.source.file).toBe(convertedPath('/c', '/t/photo.jpg', '1:1000', { width: 1568, height: 768 }))
+ expect(converts.length).toBe(1)
+})
+
+test('a size, width or height command begins its epoch (one redraw) before the setting is stored', async ($, on) => {
+ const { redrawsAt, redraws } = world(on)
+ await ready($)
+ for (const [args, key] of [['size 90', 'size'], ['width 80', 'width'], ['height full', 'height']] as const) {
+ const before = redraws()
+ await $.command.run({ command: 'md-preview', args } as any)
+ expect(redrawsAt[key]).toBe(before + 1)
+ }
+})
+
test('a new height makes a new PNG of a JPEG in the background; the last one draws meanwhile', async ($, on) => {
let release = () => {}
const until = new Promise<void>(done => (release = done))
@@ -704,9 +854,10 @@ test('a new height makes a new PNG of a JPEG in the background; the last one dra
expect(images(await ui.drawn())[0].props.source.file).toBe(first)
// 24 rows of 32 px.
expect(converts[1]).toContain('maxh=768')
- // The run ends: its refresh draws the row again, with the new PNG.
+ // The run ends: the epoch commits, its refresh draws the row again, with the new PNG.
release()
await clock.settle()
+ await clock.advance(COMMIT_MIN_MS)
expect(images(await ui.drawn())[0].props.source.file).toBe(convertedPath('/c', '/t/photo.jpg', '1:1000', { width: 1568, height: 768 }))
})
@@ -719,6 +870,7 @@ test('a background run that ends while the row draws still draws its PNG', async
await ui.redraw(sent(attachAll('/t/photo.jpg')).props)
expect(converts.length).toBe(2)
await clock.settle()
+ await clock.advance(COMMIT_MIN_MS)
const now = images(await ui.drawn())[0].props.source.file
expect(now).not.toBe(first)
expect(now).toBe(convertedPath('/c', '/t/photo.jpg', '1:1000', { width: 1568, height: 768 }))
@@ -727,7 +879,8 @@ test('a background run that ends while the row draws still draws its PNG', async
test('height with no value shows it; a bad value is refused; a bad kept value is the default', async ($, on) => {
const { kept } = world(on, { stored: { height: 3 } })
const shown = await $.command.run({ command: 'md-preview', args: 'height' } as any)
- expect(shown.text).toContain('The most rows an image takes: half (half the terminal, 6 to 24 rows)')
+ expect(shown.text).toContain('The most rows an image or a Typst drawing takes: half (half the terminal, 6 to 24 rows)')
+ expect(shown.text).toContain('This applies to images (sent or pasted) and to Typst drawings in answers.')
const bad = await $.command.run({ command: 'md-preview', args: 'height 5' } as any)
expect(bad.text).toContain('Not understood: "height 5"')
expect(kept.height).toBe(undefined)
diff --git a/tests/plan.test.ts b/tests/plan.test.ts
index c2359c7..d19e43a 100644
--- a/tests/plan.test.ts
+++ b/tests/plan.test.ts
@@ -136,19 +136,31 @@ function world($: any, on: any, o: {
let engineAsks = 0
const answers = [...(o.answers ?? [])]
const files = new Map<string, string>([[FILE, PLAN]])
+ // The children md-preview spawns: the Frame watcher (it exits 1: no tty)
+ // and a compile through the PID wrapper (typst.ts wrapPid).
+ let pids = 4242
+ on('process.spawn', async function* ($: any, e: any) {
+ const argv: string[] = e.argv
+ if (argv[0] === 'sh' && argv[2] === 'echo $$; exec "$@"' && argv[4] === '/usr/bin/typst' && argv[5] === 'compile') {
+ yield { stream: 'stdout', text: `${pids++}\n` }
+ if (o.failCompile) {
+ yield { stream: 'stderr', text: 'error: boom' }
+ return { value: { code: 1, signal: null } }
+ }
+ const doc = argv.find(a => a.startsWith('doc='))!.slice(4)
+ compiled.push(JSON.parse(files.get(doc)!).segments.join('\n\n'))
+ return { value: { code: 0, signal: null } }
+ }
+ return { value: { code: 1, signal: null } }
+ })
on('process.run', async ($: any, e: any) => {
const argv: string[] = e.argv
const cmd = argv.join(' ')
+ if (argv[0] === 'kill') return ok('')
if (/md-preview-/.test(cmd)) return ok('/c\nDarwin\n')
if (cmd.includes('command -v typst')) return ok('/usr/bin/typst\n')
if (cmd.includes('command -v code')) return o.code ? ok('/usr/local/bin/code\n') : ok('', 1)
if (argv[0] === '/usr/bin/typst' && argv[1] === 'eval') return ok('{}')
- if (argv[0] === '/usr/bin/typst' && argv[1] === 'compile') {
- if (o.failCompile) return ok('', 1)
- const doc = argv.find(a => a.startsWith('doc='))!.slice(4)
- compiled.push(JSON.parse(files.get(doc)!).segments.join('\n\n'))
- return ok('')
- }
if (cmd.includes('od -An')) return ok(`${HEAD}\n@\n`)
if (argv.includes(FILE)) {
edits.push(argv)
@@ -252,6 +264,26 @@ test('the ExitPlanMode row draws the plan as pictures under the engine row, at a
expect(texts(tree).join('\n')).not.toContain(PLAN_DRAWING)
})
+test('a redraw of the plan row with a new onScreen draws the engine row again and compiles nothing', async ($, on) => {
+ let rows = 0
+ on('ui.render', { component: 'ToolUse' }, async ($: any, e: any, next: any) => (rows++, next(e)))
+ const { clock, compiled } = world($, on)
+ await ready($)
+ const ui = await $.ui.mount(use())
+ await clock.settle()
+ await ui.redraw(use().props)
+ const [first] = images(await ui.drawn())
+ const seen = rows
+ for (const onScreen of [{ first: 0, last: 4, of: 9 }, null, undefined]) {
+ await ui.redraw({ ...use().props, onScreen })
+ const tree: any = await ui.drawn()
+ expect(tree.children[0]).toMatchObject(ENGINE)
+ expect(images(tree)[0].props).toEqual(first.props)
+ }
+ expect(rows).toBe(seen + 3)
+ expect(compiled).toEqual([PLAN])
+})
+
test('a plan that fails to compile, a rejected call and a subagent call keep the engine row', async ($, on) => {
const { clock } = world($, on, { failCompile: true })
await ready($)
diff --git a/tests/pure.test.ts b/tests/pure.test.ts
index 1900151..aea75cc 100644
--- a/tests/pure.test.ts
+++ b/tests/pure.test.ts
@@ -2,13 +2,16 @@ import { expect, test } from 'claude-code/testing'
import {
alignFirstLine, DEFAULT_METRICS, DEFAULT_SIZE, firstLineOf, fontFit, ghosttyFontOf, itermFontOf, parseCommand, parseFontSpec, typstCall,
- blocksOf, canDrawIn, cellOf, columnsFor, DEFAULT_CELL, hashOf, imagePathOf, isSet, localImages, DEFAULT_WIDTH, IMAGE_MAX_COLUMNS,
- parseOd, plainOf, pngSize, rowsFor, shouldRetrySafe, sizing, splitSegments, themeOf, TYPST_PROMPT,
+ blocksOf, canDrawIn, columnsFor, DEFAULT_CELL, hashOf, imagePathOf, isSet, localImages, DEFAULT_WIDTH, IMAGE_MAX_COLUMNS,
+ parseOd, plainOf, pngSize, shouldRetrySafe, sizeOf, sizing, splitSegments, themeOf, TYPST_PROMPT,
escapeControls, luminanceOf, modeOfLuminance, OSC11_PL, parseOsc11, pickProfile, itermAppearanceOf, itermModeOf,
GHOSTTY_DEFAULT_BG, ghosttyBackgroundOf, ghosttyThemePaths, ghosttyThemesOf, ghosttyValueOf, hexColorOf,
modeLine, modeOfColorFgBg, modeOfGnome, modeOfMacAppearance, resolveMode, settingOf,
BASE_THEME, DEFAULT_THEME, chooseTheme, isSyntaxPath, isThemeName, measureCall, pickThemes, renderKey, themeEntry, themeFiles, themeListing,
+ needsRoom, nextJob, pageRowsOf, resultOf, roomInputs, splitInTwo,
+ composeFrame, fitBox, pictureColumns, roomColumns, scaledBulletRow,
} from '../hooks/register'
+import { wrapPid } from '../hooks/lib/typst'
const para = (i: number) => `Paragraph ${i} ${'word '.repeat(40)}`.trim()
const fence = (info: string, lines: number) => ['```' + info, ...Array.from({ length: lines }, (_, i) => `line ${i}`), '```'].join('\n')
@@ -210,28 +213,100 @@ test('the first line of text is centred on the bullet row', () => {
}
})
-test('pages are padded to whole rows, so rows round', () => {
+test('pages are padded to whole rows, so rows round; a page keeps the box it was compiled for', () => {
const px = { width: 16, height: 32 }
- expect(rowsFor({ width: 1600, height: 320 }, 100, px)).toBe(10)
- expect(rowsFor({ width: 1600, height: 321 }, 100, px)).toBe(10)
- expect(rowsFor({ width: 1600, height: 319 }, 100, px)).toBe(10)
- expect(rowsFor({ width: 1600, height: 10 }, 100, px)).toBe(1)
- expect(rowsFor({ width: 1600, height: 100000 }, 100, px)).toBe(255)
- // Drawn at half the width (a narrower window before the new render), half the rows.
- expect(rowsFor({ width: 1600, height: 640 }, 50, px)).toBe(10)
+ expect(pageRowsOf(320, px)).toBe(10)
+ expect(pageRowsOf(321, px)).toBe(10)
+ expect(pageRowsOf(319, px)).toBe(10)
+ expect(pageRowsOf(10, px)).toBe(1)
+ // Not capped here: a page over 255 rows is cut in two by compile.
+ expect(pageRowsOf(100000, px)).toBe(3125)
expect(DEFAULT_CELL.height / DEFAULT_CELL.width).toBe(2)
+ // A kept pages.json without the box (an older format) is not used.
+ const page = { file: '/c/k/a-1.png', width: 1600, height: 320, alt: 'x', columns: 100, rows: 10 }
+ expect(resultOf(JSON.stringify({ pages: [page], bulletRow: 0 }))).toMatchObject({ pages: [page] })
+ expect(resultOf(JSON.stringify({ pages: [{ ...page, columns: undefined, rows: undefined }], bulletRow: 0 }))).toBe(null)
+ expect(resultOf('not json')).toBe(null)
+})
+
+test('a text needs the room height only with a live Typst block or a local image', () => {
+ expect(needsRoom('# Title\n\nSome text.')).toBe(false)
+ expect(needsRoom('```js\nx()\n```')).toBe(false)
+ expect(needsRoom('```typst\n#rect()\n```')).toBe(true)
+ expect(needsRoom('Text\n\n```typ\n#rect()\n```')).toBe(true)
+ // In a list item too (the template draws it live there as well).
+ expect(needsRoom('- item\n\n ```typst\n #rect()\n ```')).toBe(true)
+ expect(needsRoom('See ![a plot](./plot.png).')).toBe(true)
+ expect(needsRoom('See ![a plot](https://x.org/plot.png).')).toBe(false)
+ expect(needsRoom('```md\n![a plot](./plot.png)\n```')).toBe(false)
+})
+
+test('the room height is in the key only when it is given (a text that needs it)', () => {
+ 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' },
+ }
+ const room = { heightPt: 300, design: { widthPt: 596, heightPt: 300 }, designKey: 'd', isNew: true }
+ const plain = renderKey(o)
+ expect(renderKey({ ...o, room: undefined })).toBe(plain)
+ const roomed = renderKey({ ...o, room })
+ expect(roomed).not.toBe(plain)
+ // Whether the design is new is not in the key: the same space either way.
+ expect(renderKey({ ...o, room: { ...room, isNew: false, designKey: 'e' } })).toBe(roomed)
+ expect(renderKey({ ...o, room: { ...room, heightPt: 200 } })).not.toBe(roomed)
+ expect(renderKey({ ...o, room: { ...room, design: { widthPt: 500, heightPt: 300 } } })).not.toBe(roomed)
+})
+
+test('the room goes to the template in pt: the design page width and room height', () => {
+ expect(roomInputs(undefined)).toEqual({})
+ // A first render: the design is the space now, so the factor is 1 (design-w = width).
+ const width = 600
+ const room = { heightPt: 352.123, design: { widthPt: width, heightPt: 352.123 }, designKey: 'd', isNew: true }
+ expect(roomInputs(room)).toEqual({ height: 352.12, 'design-w': width, 'design-h': 352.12 })
+})
+
+test('rows are counted at the text size: at 200% a long answer is cut into more segments', () => {
+ const md = Array.from({ length: 60 }, (_, i) => para(i)).join('\n\n')
+ const at100 = splitSegments(md, 100)
+ const at200 = splitSegments(md, 100, undefined, 200)
+ expect(at200.length).toBeGreaterThanOrEqual(at100.length * 2)
+ expect(words(at200.join('\n\n'))).toEqual(words(md))
+})
+
+test('a segment too tall for an Image is cut in two by the same rules; one block stays whole', () => {
+ const md = Array.from({ length: 12 }, (_, i) => para(i)).join('\n\n')
+ const two = splitInTwo(md, 100)
+ expect(two.length).toBe(2)
+ expect(words(two.join('\n\n'))).toEqual(words(md))
+ expect(splitInTwo(para(1), 100)).toEqual([para(1)])
+})
+
+test('the queue takes a job on screen first, then the newest', () => {
+ const job = (key: string, order: number, onScreen?: boolean) => ({ key, order, ...(onScreen ? { onScreen } : {}) }) as any
+ expect(nextJob([])).toBe(-1)
+ expect(nextJob([job('a', 1), job('b', 3), job('c', 2)])).toBe(1)
+ expect(nextJob([job('a', 1, true), job('b', 3), job('c', 2, true)])).toBe(2)
+ expect(nextJob([job('a', 5), job('b', 4, true)])).toBe(1)
+ // Known off screen: after any other, the newest of them first.
+ const off = (key: string, order: number) => ({ key, order, onScreen: false }) as any
+ expect(nextJob([job('a', 1), off('b', 9)])).toBe(0)
+ expect(nextJob([off('a', 1), off('b', 2)])).toBe(1)
+})
+
+test('a compile runs through a shell that prints its PID, then becomes typst', () => {
+ expect(wrapPid(['/usr/bin/typst', 'compile', 'a b.typ'])).toEqual(['sh', '-c', 'echo $$; exec "$@"', 'sh', '/usr/bin/typst', 'compile', 'a b.typ'])
})
test('the cell comes from the tty in device pixels, with no scale step', () => {
// iTerm2 on Retina, 14 pt Meslo: 2040 x 1700 px for 120 x 50 cells.
- expect(cellOf('50 120 2040 1700')).toEqual({ width: 17, height: 34 })
+ expect(sizeOf('50 120 2040 1700')).toEqual({ rows: 50, columns: 120, cell: { width: 17, height: 34 } })
// Ghostty on Retina reports device pixels too.
- expect(cellOf('40 200 3200 1360')).toEqual({ width: 16, height: 34 })
- expect(cellOf('50 200 0 0')).toBe(null)
- expect(cellOf('')).toBe(null)
+ expect(sizeOf('40 200 3200 1360')).toEqual({ rows: 40, columns: 200, cell: { width: 16, height: 34 } })
+ expect(sizeOf('50 200 0 0')).toEqual({ rows: 50, columns: 200, cell: null })
+ expect(sizeOf('')).toBe(null)
// Not believable: under 4 or over 64 px a cell.
- expect(cellOf('50 200 600 1700')).toBe(null)
- expect(cellOf('50 20 1700 1700')).toBe(null)
+ expect(sizeOf('50 200 600 1700')?.cell).toBe(null)
+ expect(sizeOf('50 20 1700 1700')?.cell).toBe(null)
})
test('the terminal font is read from iTerm2 and Ghostty settings', () => {
@@ -579,3 +654,29 @@ test('the probe output is shown with its control characters spelled out', () =>
expect(OSC11_PL).toContain('O_NONBLOCK')
expect(OSC11_PL).not.toContain('stty')
})
+
+// ---- The room of a picture ----------------------------------------------------
+
+test('a box wider than its room is drawn at the room, the aspect kept; a box that fits is never grown', () => {
+ expect(fitBox({ columns: 211, rows: 40 }, 118)).toEqual({ columns: 118, rows: 22 })
+ expect(fitBox({ columns: 200, rows: 1 }, 50)).toEqual({ columns: 50, rows: 1 })
+ expect(fitBox({ columns: 98, rows: 12 }, 118)).toEqual({ columns: 98, rows: 12 })
+ expect(fitBox({ columns: 118, rows: 12 }, 118)).toEqual({ columns: 118, rows: 12 })
+})
+
+test('the bullet row scales with the page; at factor 1 it stays', () => {
+ expect(scaledBulletRow(0, 0.5)).toBe(0)
+ expect(scaledBulletRow(2, 1)).toBe(2)
+ expect(scaledBulletRow(2, 0.56)).toBe(1)
+ expect(scaledBulletRow(3, 0.5)).toBe(1)
+})
+
+test('a picture of the target always fits the room of the same viewport', () => {
+ for (const columns of [10, 22, 60, 100, 120, 213, 257, 300, 400]) {
+ for (const width of ['full', 40, 100, 160] as const) {
+ const frame = composeFrame(null, { columns, rows: 40 })
+ expect(columnsFor(frame.columns, width)).toBeLessThanOrEqual(roomColumns({ columns }))
+ expect(pictureColumns(frame, true)).toBeLessThanOrEqual(roomColumns({ columns }))
+ }
+ }
+})
diff --git a/tests/stream.test.ts b/tests/stream.test.ts
index c816bf3..e981d4a 100644
--- a/tests/stream.test.ts
+++ b/tests/stream.test.ts
@@ -1,16 +1,31 @@
import { expect, mock, test } from 'claude-code/testing'
+import { DEFAULT_CELL, DEFAULT_METRICS, DEFAULT_THEME, fontFit, hashOf, nextJob, renderKey } from '../hooks/register'
+// This file's own copy of the pipeline (the plugin's module is another one),
+// driven with this test's `$`: pagesOf and the queue and results it fills
+// are module state, which register.tsx does not export.
+import { epochOpen, lastKey, queue, results, running, S, type Env } from '../hooks/lib/state'
+import { pagesOf } from '../hooks/lib/answer'
+import { beginEpoch } from '../hooks/lib/epoch'
+import { forgetTouches } from '../hooks/lib/typst'
+import { COMMIT_MIN_MS, TOUCH_FLUSH_MS } from '../hooks/lib/settings'
+
// The world beneath the mod for one compile: a cache folder, a typst whose
// compile the test lets finish (or fail), and the PNG it "wrote".
const ok = (stdout: string, exitCode = 0) => ({ value: { exitCode, stdout, stderr: exitCode ? 'error: boom' : '', isStdoutTruncated: false, isStderrTruncated: false } })
// The first 24 bytes of a 1600 x 64 PNG, as `od -An -v -tx1` prints them.
const HEAD = '89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 06 40 00 00 00 40'
+// 1600 x 9000: over 255 rows of 32 px.
+const TALL = '89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 06 40 00 00 23 28'
-function world(on: any, o: { fail?: boolean; slow?: Promise<void> } = {}) {
+// `tall`: the first run's pages are TALL (the split retry's are not).
+function world(on: any, o: { fail?: boolean; slow?: Promise<void>; tall?: boolean } = {}) {
mock.store(on)
const clock = mock.clock(on)
mock.env(on, { HOME: '/h', CLAUDE_CODE_FORCE_TERMINAL_IMAGES: '1' })
const compiled: string[] = []
+ // The segments of each compile.
+ const counts: number[] = []
const files = new Map<string, string>()
on('process.run', async ($: any, e: any, next: any) => {
const argv: string[] = e.argv
@@ -18,25 +33,42 @@ function world(on: any, o: { fail?: boolean; slow?: Promise<void> } = {}) {
if (/md-preview-/.test(cmd)) return ok('/c\nDarwin\n')
if (cmd.includes('command -v typst')) return ok('/usr/bin/typst\n')
if (argv[0] === '/usr/bin/typst' && argv[1] === 'eval') return ok('{}')
- if (argv[0] === '/usr/bin/typst' && argv[1] === 'compile') {
- const doc = argv.find(a => a.startsWith('doc='))!.slice(4)
- compiled.push(JSON.parse(files.get(doc)!).segments.join('\n\n'))
- if (o.slow) await o.slow
- return o.fail ? ok('', 1) : ok('')
+ if (argv[0] === 'kill') return ok('')
+ if (cmd.includes('od -An')) {
+ const pngs = argv.filter(a => a.endsWith('.png'))
+ return ok(pngs.map(f => `${o.tall && /\/a-\d+\.png$/.test(f) ? TALL : HEAD}\n@\n`).join(''))
}
- if (cmd.includes('od -An')) return ok(`${HEAD}\n@\n`)
if (argv[0] === 'sh' && cmd.includes('debug.log')) return ok('')
if (argv[0] === 'defaults') return ok('', 1)
return ok('', 1)
})
+ // Typst runs through the PID wrapper (wrapPid): its first stdout line is
+ // the PID. Any other child (the tty watcher) ends at once.
+ on('process.spawn', async function* ($: any, e: any) {
+ const argv: string[] = e.argv
+ if (argv[0] !== 'sh' || argv[2] !== 'echo $$; exec "$@"' || argv[4] !== '/usr/bin/typst' || argv[5] !== 'compile') {
+ return { value: { code: 2, signal: null } }
+ }
+ yield { stream: 'stdout', text: '4242\n' }
+ const doc = argv.find(a => a.startsWith('doc='))!.slice(4)
+ const { segments } = JSON.parse(files.get(doc)!)
+ compiled.push(segments.join('\n\n'))
+ counts.push(segments.length)
+ if (o.slow) await o.slow
+ if (o.fail) yield { stream: 'stderr', text: 'error: boom' }
+ return { value: { code: o.fail ? 1 : 0, signal: null } }
+ })
on('fs.write', async ($: any, e: any) => {
files.set(e.path, e.text)
return { value: undefined }
})
on('fs.read', async ($: any, e: any, next: any) => (files.has(e.path) ? { value: files.get(e.path) } : e.path.startsWith('/c/') ? { deny: 'ENOENT' } : next(e)))
- on('fs.list', async ($: any, e: any, next: any) => (e.path.startsWith('/c/') ? { value: [{ name: 'a-1.png', kind: 'file', size: 1, mtimeMs: 1, isLink: false }] } : next(e)))
+ const png = (name: string) => ({ name, kind: 'file', size: 1, mtimeMs: 1, isLink: false })
+ on('fs.list', async ($: any, e: any, next: any) => (e.path.startsWith('/c/') ? { value: ['a-1.png', 'c-1.png', 'c-2.png'].map(png) } : next(e)))
+ on('fs.exists', async ($: any, e: any, next: any) => (e.path.includes('/designs/') ? { value: files.has(e.path) } : next(e)))
on('ui.toast', async () => ({ value: undefined }))
- return { clock, compiled }
+ const designs = () => [...files.keys()].filter(path => path.includes('/designs/'))
+ return { clock, compiled, counts, files, designs }
}
const message = (requestId: string, text: string) =>
@@ -48,6 +80,8 @@ const props = (text: string) => ({ text, isFirstOfReply: true }) as any
const kinds = (tree: any): string[] => (tree && typeof tree === 'object' ? [tree.type, ...(tree.children ?? []).flatMap(kinds)] : [])
const isBlank = (tree: any) => tree.type === 'Box' && !(tree.children ?? []).length
const ENGINE = { type: 'Text', props: {}, children: ['engine drawing'] }
+const images = (tree: any): any[] =>
+ tree && typeof tree === 'object' ? [...(tree.type === 'Image' ? [tree] : []), ...(tree.children ?? []).flatMap(images)] : []
// A model request the test streams chunk by chunk; `release` ends it.
function request(on: any, more: unknown[] = []) {
@@ -153,3 +187,390 @@ test('a text block is final when its request moves on to a tool call, before the
end()
await stream.next()
})
+
+test('a diagram keeps its design only after its final text compiled, never while it streams', async ($, on) => {
+ const { clock, compiled, designs } = world(on)
+ on('ui.render', () => ENGINE as any)
+ const end = request(on)
+ await $.command.run({ command: 'md-preview', args: '' } as any)
+ const stream = ($ as any).turn.step({ turnId: 't', index: 0, model: 'm', messageCount: 1 })
+ await stream.next()
+ const text = '# Title\n\n```typst\n#rect(width: theme.width)\n```'
+ const ui = await $.ui.mount(message('design-1', '# Title\n\n```typst\n#rect('))
+ await ui.redraw(props(text))
+ await clock.advance(1500)
+ expect(compiled).toEqual([])
+ expect(designs()).toEqual([])
+ end()
+ const done = stream.next()
+ await clock.settle()
+ await done
+ expect(compiled).toEqual([text])
+ expect(designs().length).toBe(1)
+})
+
+test('a page over 255 rows: its segment is cut in two and compiled once more', async ($, on) => {
+ const { clock, counts } = world(on, { tall: true })
+ on('ui.render', () => ENGINE as any)
+ await $.command.run({ command: 'md-preview', args: '' } as any)
+ const text = Array.from({ length: 12 }, (_, i) => `Paragraph ${i} ${'word '.repeat(40)}`.trim()).join('\n\n')
+ const ui = await $.ui.mount(message('tall-1', text))
+ await clock.settle()
+ await ui.redraw(props(text))
+ expect(counts).toEqual([1, 2])
+ const pages = images(await ui.drawn())
+ expect(pages.length).toBe(2)
+ expect(pages.map(p => p.props.source.file.replace(/^.*\//, ''))).toEqual(['c-1.png', 'c-2.png'])
+ for (const p of pages) expect(p.props.rows).toBeLessThanOrEqual(255)
+})
+
+// ---- The pipeline on its own ----------------------------------------------------
+
+const ENV: Env = {
+ typst: '/usr/bin/typst', canDraw: true, inline: false, cache: '/c', cwd: '/w', root: '/mod', isMac: true, stamp: '1', home: '/h',
+ claudeTmp: '', termFont: '', metrics: DEFAULT_METRICS, designs: '/h/designs',
+}
+const FRAME = { columns: 100, rows: 40, cell: DEFAULT_CELL }
+// The key pagesOf makes for a plain text in FRAME with the defaults.
+const keyOf = (text: string) =>
+ renderKey({
+ textHash: hashOf([text]), columns: 98, cell: DEFAULT_CELL, size: 100, mode: 'dark', termFont: '', columnPt: fontFit(DEFAULT_METRICS, 100).columnPt,
+ templateStamp: '1', look: { name: DEFAULT_THEME, dir: `/mod/render/themes/${DEFAULT_THEME}`, stamp: '0' }, inline: false,
+ })
+const PAGE = { file: '', width: 1568, height: 64, alt: 'x', columns: 98, rows: 2 }
+
+// A `$` of the plugin's kind for this copy: pages.json of any key reads
+// back, every process fails (and is noted), the clock runs only at `advance`.
+function pipeline() {
+ const runs: string[][] = []
+ const clock = fakeClock()
+ const $ = {
+ fs: {
+ read: async (path: string) => {
+ const m = /^\/c\/([0-9a-f]{16})\/pages\.json$/.exec(path)
+ if (!m) throw new Error('ENOENT')
+ return JSON.stringify({ pages: [{ ...PAGE, file: `/c/${m[1]}/a-1.png` }], bulletRow: 0 })
+ },
+ },
+ process: {
+ run: async (argv: string[]) => {
+ runs.push(argv)
+ return { exitCode: 1, stdout: '', stderr: '' }
+ },
+ },
+ clock: clock.clock,
+ } as any
+ fresh()
+ // No compile starts: the queue is only read.
+ const signal = new AbortController().signal
+ running.set('x', { job: {} as any, cancel: () => {}, signal }).set('y', { job: {} as any, cancel: () => {}, signal })
+ return { $, runs, advance: clock.advance }
+}
+
+// The module state of this copy as at a first render: no jobs, no results,
+// the epoch closed, FRAME shown.
+function fresh() {
+ forgetTouches()
+ queue.length = 0
+ results.clear()
+ running.clear()
+ lastKey.clear()
+ S.onDisk = new Set()
+ S.resizing = false
+ S.missed = false
+ S.frame = FRAME
+ S.shown = FRAME
+ S.shownEpoch = S.epoch
+}
+
+// A clock whose timers run only at `advance` (in order of their time).
+function fakeClock() {
+ let now = 0
+ let timers: Array<{ at: number; fn: () => void; isOff: boolean }> = []
+ return {
+ clock: {
+ after: (ms: number, fn: () => void) => {
+ const t = { at: now + ms, fn, isOff: false }
+ timers.push(t)
+ return { cancel: () => (t.isOff = true) }
+ },
+ },
+ advance: (ms: number) => {
+ now += ms
+ for (;;) {
+ const due = timers.filter(t => !t.isOff && t.at <= now).sort((a, b) => a.at - b.at)[0]
+ if (!due) break
+ timers = timers.filter(t => t !== due)
+ due.fn()
+ }
+ },
+ }
+}
+
+// Lets the promise chains run (a compile is many awaits).
+const drain = async () => {
+ for (let i = 0; i < 200; i++) await Promise.resolve()
+}
+
+// A `$` that compiles for real through this copy's queue: an in-memory fs,
+// typst through the PID wrapper with spawn (each run waits until the test
+// ends it, or `kill <pid>` kills it), and a count of the redraws.
+function compiler() {
+ const files = new Map<string, string>()
+ const clock = fakeClock()
+ const runs: { argv: string[]; key: string; end: (code: number | null) => void }[] = []
+ const kills: string[] = []
+ let redraws = 0
+ let pid = 1000
+ const $ = {
+ fs: {
+ read: async (path: string) => {
+ if (!files.has(path)) throw new Error('ENOENT')
+ return files.get(path)!
+ },
+ write: async (path: string, text: string) => {
+ files.set(path, text)
+ },
+ exists: async (path: string) => files.has(path),
+ list: async () => [{ name: 'a-1.png', kind: 'file', size: 1, mtimeMs: 1, isLink: false }],
+ },
+ process: {
+ run: async (argv: string[]) => {
+ if (argv[0] === 'kill') {
+ kills.push(argv[1]!)
+ runs.find(r => r.argv.includes(`pid=${argv[1]}`))?.end(null)
+ return { exitCode: 0, stdout: '', stderr: '' }
+ }
+ if (argv.join(' ').includes('od -An')) return { exitCode: 0, stdout: `${HEAD}\n@\n`, stderr: '' }
+ return { exitCode: 1, stdout: '', stderr: '' }
+ },
+ spawn: (request: { argv: string[] }) => {
+ const argv = [...request.argv, `pid=${++pid}`]
+ const key = /\/c\/([0-9a-f]{16})\//.exec(argv.find(a => a.startsWith('doc=')) ?? '')?.[1] ?? ''
+ let end!: (code: number | null) => void
+ const ended = new Promise<number | null>(r => (end = r))
+ runs.push({ argv, key, end })
+ const mine = pid
+ return (async function* () {
+ yield { stream: 'stdout' as const, text: `${mine}\n` }
+ const code = await ended
+ return { code, signal: code === null ? 'SIGTERM' : null }
+ })()
+ },
+ },
+ state: {
+ get: async () => {
+ throw new Error('no store')
+ },
+ },
+ ui: {
+ invalidate: () => {
+ redraws++
+ },
+ },
+ clock: clock.clock,
+ } as any
+ fresh()
+ return { $, runs, kills, files, advance: clock.advance, redraws: () => redraws }
+}
+
+test('a key found on disk at setUp (a reopened session) draws at once: no queue, no blank; its folder is touched', async () => {
+ const { $, runs, advance } = pipeline()
+ const key = keyOf('An old answer.')
+ S.onDisk = new Set([key])
+ const drawing = await pagesOf($, { id: 'disk-1', text: 'An old answer.', frame: FRAME, env: ENV, canStream: true })
+ expect(drawing).toMatchObject({ kind: 'pages', result: { pages: [{ file: `/c/${key}/a-1.png`, columns: 98, rows: 2 }] } })
+ expect(queue.length).toBe(0)
+ expect(results.has(key)).toBe(true)
+ // Touched later, in one batch (no process in a render path).
+ expect(runs.some(argv => argv[0] === 'touch')).toBe(false)
+ advance(TOUCH_FLUSH_MS)
+ expect(runs).toContainEqual(['touch', '-c', `/c/${key}`])
+ // Not on disk: it waits in the queue, blank.
+ S.onDisk = new Set()
+ const other = await pagesOf($, { id: 'disk-2', text: 'A new answer.', frame: FRAME, env: ENV, canStream: true, onScreen: true })
+ expect(other.kind).toBe('blank')
+ expect(queue.map(j => [j.key, j.onScreen])).toEqual([[keyOf('A new answer.'), true]])
+})
+
+test('the queue: rows on screen first, then the newest; a job enqueued again takes its new place', async () => {
+ const { $ } = pipeline()
+ S.onDisk = new Set()
+ const draw = (id: string, onScreen?: boolean) => pagesOf($, { id, text: `Text of ${id}.`, frame: FRAME, env: ENV, canStream: false, onScreen })
+ await draw('a', true)
+ await draw('b')
+ await draw('c')
+ expect(queue[nextJob(queue)]!.requestId).toBe('a')
+ // Scrolled away, then drawn again: now only the newest.
+ await draw('a')
+ expect(queue.length).toBe(3)
+ expect(queue[nextJob(queue)]!.requestId).toBe('a')
+ await draw('b')
+ expect(queue[nextJob(queue)]!.requestId).toBe('b')
+ await draw('c', true)
+ await draw('b')
+ expect(queue[nextJob(queue)]!.requestId).toBe('c')
+})
+
+test('a cancelled compile is killed by its PID, keeps nothing, frees its slot, and its key compiles again', async () => {
+ const { $, runs, kills } = compiler()
+ const draw = (id: string) => pagesOf($, { id, text: `Text of ${id}.`, frame: FRAME, env: ENV, canStream: false, onScreen: true })
+ await draw('k1')
+ await draw('k2')
+ await draw('k3')
+ await drain()
+ // Two run (MAX_RUNNING), through the PID wrapper; one waits.
+ expect(runs.length).toBe(2)
+ expect(runs[0]!.argv.slice(0, 6)).toEqual(['sh', '-c', 'echo $$; exec "$@"', 'sh', '/usr/bin/typst', 'compile'])
+ expect(queue.length).toBe(1)
+ // A new epoch stops both and empties the queue.
+ beginEpoch($)
+ expect(queue.length).toBe(0)
+ // The key of k1 is wanted again while its killed run still ends.
+ await draw('k1')
+ expect(queue.map(j => j.key)).toEqual([keyOf('Text of k1.')])
+ await drain()
+ expect(kills.length).toBe(2)
+ expect(results.has(keyOf('Text of k1.'))).toBe(false)
+ expect(results.has(keyOf('Text of k2.'))).toBe(false)
+ // Its slot is free: k1 runs again, in the new epoch.
+ expect(runs.length).toBe(3)
+ expect(runs[2]!.key).toBe(keyOf('Text of k1.'))
+ expect(running.get(keyOf('Text of k1.'))?.job.epoch).toBe(S.epoch)
+ runs[2]!.end(0)
+ await drain()
+ expect(results.get(keyOf('Text of k1.'))).toMatchObject({ pages: [{ columns: 98 }] })
+ expect(running.size).toBe(0)
+})
+
+test('in an open epoch a row keeps its old picture; no redraw as jobs end; all swap at the commit', async () => {
+ const { $, runs, advance, redraws } = compiler()
+ const text = 'An answer.'
+ const draw = (id: string, t: string, frame: typeof FRAME) => pagesOf($, { id, text: t, frame, env: ENV, canStream: false, onScreen: true })
+ // The first picture, with no epoch open: its row redraws when it ends.
+ await draw('e1', text, FRAME)
+ await drain()
+ runs[0]!.end(0)
+ await drain()
+ expect(redraws()).toBe(1)
+ const first = await draw('e1', text, FRAME)
+ expect(first).toMatchObject({ kind: 'pages', result: { pages: [{ columns: 98 }] } })
+ // A new target, 80 columns.
+ const narrow = { ...FRAME, columns: 80 }
+ beginEpoch($, narrow)
+ expect(epochOpen()).toBe(true)
+ await drain()
+ // Its own one redraw (the rows draw their old pictures and enqueue).
+ expect(redraws()).toBe(2)
+ const before = redraws()
+ const held = await draw('e1', text, narrow)
+ expect(held).toEqual(first)
+ // A new row (no old picture) waits blank.
+ expect((await draw('n1', 'A new answer.', narrow)).kind).toBe('blank')
+ await drain()
+ expect(runs.length).toBe(3)
+ runs[1]!.end(0)
+ runs[2]!.end(0)
+ await drain()
+ // Both done: no redraw for a job; the epoch is not ready yet.
+ expect(redraws()).toBe(before)
+ expect(await draw('e1', text, narrow)).toEqual(first)
+ // A row with no old picture draws its target as soon as it is there.
+ expect(await draw('n1', 'A new answer.', narrow)).toMatchObject({ kind: 'pages', result: { pages: [{ columns: 78 }] } })
+ // COMMIT_MIN_MS: the commit, one redraw; then the target.
+ advance(COMMIT_MIN_MS)
+ expect(epochOpen()).toBe(false)
+ await drain()
+ expect(redraws()).toBe(before + 1)
+ expect(await draw('e1', text, narrow)).toMatchObject({ kind: 'pages', result: { pages: [{ columns: 78 }] } })
+})
+
+test('in an open epoch a failed target waits too: the old picture until the commit, then the text', async () => {
+ const { $, runs, advance } = compiler()
+ const text = 'Another answer.'
+ const draw = (frame: typeof FRAME) => pagesOf($, { id: 'f1', text, frame, env: ENV, canStream: false, onScreen: true })
+ await draw(FRAME)
+ await drain()
+ runs[0]!.end(0)
+ await drain()
+ const first = await draw(FRAME)
+ expect(first.kind).toBe('pages')
+ const narrow = { ...FRAME, columns: 80 }
+ beginEpoch($, narrow)
+ await draw(narrow)
+ await drain()
+ // The run and its safe retry fail.
+ runs[1]!.end(1)
+ await drain()
+ runs[2]!.end(1)
+ await drain()
+ expect(await draw(narrow)).toEqual(first)
+ advance(COMMIT_MIN_MS)
+ expect(await draw(narrow)).toEqual({ kind: 'text' })
+})
+
+
+test('a cancelled compile does not redraw, even when it ends after the epoch committed', async () => {
+ const { $, runs, kills, advance, redraws } = compiler()
+ await pagesOf($, { id: 'c1', text: 'Text of c1.', frame: FRAME, env: ENV, canStream: false, onScreen: true })
+ await drain()
+ expect(runs.length).toBe(1)
+ // A new epoch stops it; nothing of the epoch waits, so it commits before
+ // the killed run's end is read.
+ beginEpoch($)
+ expect(kills.length).toBe(1)
+ advance(COMMIT_MIN_MS)
+ expect(epochOpen()).toBe(false)
+ await drain()
+ expect(running.size).toBe(0)
+ // The begin and the commit only.
+ expect(redraws()).toBe(2)
+})
+
+test('a row drawn late in an epoch (150 ms after its begin) still swaps at the commit, with one redraw', async () => {
+ const { $, runs, advance, redraws } = compiler()
+ const draw = (id: string, frame: typeof FRAME) => pagesOf($, { id, text: `Text of ${id}.`, frame, env: ENV, canStream: false, onScreen: true })
+ const ids = ['l1', 'l2', 'l3']
+ for (const [i, id] of ids.entries()) {
+ await draw(id, FRAME)
+ await drain()
+ runs[i]!.end(0)
+ await drain()
+ }
+ const firsts = await Promise.all(ids.map(id => draw(id, FRAME)))
+ expect(firsts.every(d => d.kind === 'pages')).toBe(true)
+ const narrow = { ...FRAME, columns: 80 }
+ beginEpoch($, narrow)
+ await drain()
+ const before = redraws()
+ // l1 draws at once; its job ends at 50 ms.
+ expect(await draw('l1', narrow)).toEqual(firsts[0])
+ await drain()
+ advance(50)
+ runs[3]!.end(0)
+ await drain()
+ // l2 draws at 80 ms (the rows come after round trips to the host).
+ advance(30)
+ expect(await draw('l2', narrow)).toEqual(firsts[1])
+ await drain()
+ runs[4]!.end(0)
+ await drain()
+ // At 100 ms nothing waits, but the epoch is not ready: its last row came at 80 ms.
+ advance(20)
+ expect(epochOpen()).toBe(true)
+ // l3 draws at 150 ms: its old picture still, and its job holds the commit.
+ advance(50)
+ expect(await draw('l3', narrow)).toEqual(firsts[2])
+ await drain()
+ runs[5]!.end(0)
+ await drain()
+ expect(redraws()).toBe(before)
+ advance(COMMIT_MIN_MS - 1)
+ expect(epochOpen()).toBe(true)
+ advance(1)
+ expect(epochOpen()).toBe(false)
+ await drain()
+ // The commit's one redraw; all three swap.
+ expect(redraws()).toBe(before + 1)
+ for (const id of ids) expect(await draw(id, narrow)).toMatchObject({ kind: 'pages', result: { pages: [{ columns: 78 }] } })
+})