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
Split md-preview into modules; draw images and plans, own plan approval
razorback16e4af7aef3aa6
diff --git a/README.md b/README.mdindex 68eb773..efcf3fb 100644--- a/README.md+++ b/README.md@@ -7,7 +7,7 @@ Only the drawing changes. The saved answer stays Markdown.## What it draws- Headings, lists, task lists, tables, block quotes, links, footnotes and horizontal rules-- Code blocks with syntax colours, in your terminal's font (found for iTerm2 and Ghostty; else Menlo, SF Mono or DejaVu Sans Mono)+- Code blocks with syntax colours, in your terminal's font (found for iTerm2, Ghostty, kitty and Rio; else Menlo, SF Mono or DejaVu Sans Mono)- Math (`$…$` and `$$…$$`, LaTeX syntax, through mitex)- Images from ``. A relative path starts from the session's folder. Remote images show as an alt-text box.- Live Typst: a fenced block with the language `typst` (or `typ`) is rendered, not shown as code. These packages are in the mod and work offline:@@ -19,6 +19,11 @@ Only the drawing changes. The saved answer stays Markdown.```A `theme` dictionary (`theme.fg`, `theme.muted`, `theme.blue`, `theme.palette`, `theme.width`, …) is in scope, so drawings match the terminal's colours. The mod tells Claude about this in a short part of the system prompt.+- Images that Claude sends to you as files (the SendUserFile tool). The mod draws each PNG image under the row that shows the file.+- Images that you paste into the prompt (`[Image #N]`). The mod draws each image under your prompt.++ These pictures are not larger than the image. They are not wider than the transcript, and not taller than 24 rows or half the screen. The mod draws PNG images only. Other image types stay as the normal row.+- 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@@ -26,9 +31,13 @@ Only the drawing changes. The saved answer stays Markdown.- [Typst](https://typst.app) 0.15 (tested on 0.15.1)- macOS (tested). Linux can work, but it is not tested.- A terminal where Claude Code draws pictures:- - **Ghostty and kitty:** pictures work with no setting.- - **iTerm2 (3.7.5 tested), WezTerm, Warp, Konsole:** set `CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1` before you start Claude Code.- - Not inside tmux or screen (unless forced), and not over ssh. Set `MD_PREVIEW_FORCE=1` to try anyway.+ - **kitty (0.28 or later) and Ghostty:** pictures work with no setting.+ - **iTerm2 3.6 or later (3.7.5 tested):** Claude Code needs `CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1` when it starts. A mod cannot set it early enough. The first time the mod runs in iTerm2, it asks to add one line to your shell's start file (`~/.zshrc`, `~/.bash_profile` or a fish `conf.d` file). The line sets the variable in iTerm2 only, not in tmux or screen. Then close the tab, open a new iTerm2 tab, and start Claude Code there. You can also run `/md-preview setup` (undo: `/md-preview setup remove`).+ - **Rio 0.5.27 or later (not tested):** set `CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1` before you start Claude Code.+ - Do not put the variable in the `env` of `~/.claude/settings.json`. It then applies in every terminal, also where pictures cannot show.+ - **Not supported:** WezTerm, Warp and Konsole do not draw kitty pictures with Unicode placeholders, so they show no pictures, also with the variable set. Alacritty, Terminal.app, Windows Terminal, GNOME Terminal (and other VTE terminals), foot, VS Code, Tabby, Hyper and JetBrains terminals have no kitty pictures.+ - **tmux and screen:** no pictures. Claude Code does not send pictures through tmux or screen, also with the variable set. Set `MD_PREVIEW_FORCE=1` to try anyway.+ - **ssh:** pictures work when the terminal on your computer is kitty or Ghostty (`TERM` must come through ssh), or when you set `CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1` on the remote computer. The mod sends each picture as data, because the terminal cannot read files on the remote computer. A page larger than 4096 pixels on a side or 2 MiB shows as text. An image of that size does not show.- Background sessions (agent view, forks, `claude attach`) cannot draw pictures.Where pictures cannot draw, the mod shows the normal text.@@ -58,10 +67,30 @@ To try it from a clone without installing: `claude --plugin-dir /path/to/claude-|---|---|| `/md-preview` | Shows the state, the text size and the terminal font that the mod found || `/md-preview on` / `off` | Turns the pictures on or off (kept for later sessions) |+| `/md-preview setup` / `setup remove` | iTerm2: adds or removes the shell line that turns pictures on (then close the tab and open a new one) || `/md-preview size <80–200>` | Text size in percent. 100 is the same visual size as your terminal text. || `/md-preview theme` | Lists the themes, shows which one is in use, and shows the folder for your own themes || `/md-preview theme <name>` | Changes to that theme (kept for later sessions) |+### Plan approval++When Claude exits plan mode, the mod draws the plan as a picture in the transcript. Under the picture, the mod shows its own question, "Approve this plan?", in place of the Claude Code dialog. A dim line above the question tells you that the rendered plan is above. The question has these options:++| Option | What it does |+|---|---|+| Yes, auto-accept edits | Approves the plan. Claude Code then accepts file edits with no question (`acceptEdits` mode). |+| Yes, manually approve edits | Approves the plan. Claude Code then asks you before each file edit (`default` mode). |+| Yes, clear context + auto-accept | Approves the plan, stops the turn and runs `/clear`. Then the mod sends "Implement this plan:" and the plan as a new prompt, in `acceptEdits` mode. |+| Edit the plan | Opens the plan file in an editor. The mod waits until you close the file (10 minutes at most). Then it asks "Approve the edited plan?". When you approve, Claude gets the edited plan. |+| Type something | Sends your text to Claude as changes to the plan. Claude stays in plan mode and writes a new plan. |+| Esc | Rejects the plan and stops the turn. |++The editor is VS Code (`code --wait`) when the `code` command is on your PATH. If `code` is not on the PATH, macOS uses TextEdit (`open -W -t`). In that case, quit TextEdit when you complete the edit. Over ssh and on Linux with no `code` command, the "Edit the plan" option does not show.++The mod shows the plan file as it is when the question opens. Claude can write the plan file and exit plan mode in the same message. Then Claude Code sends the plan from before that write. In this case, the mod waits for the write to complete (5 seconds at most) and reads the file again. You approve the plan that you see, and Claude gets that plan.++The mod uses this flow only when it can draw the plan: the mod is on, Typst is installed, the terminal draws pictures, and the plan is from the main conversation (not from a subagent). In all other conditions, Claude Code shows its own dialog, as with no mod. If the flow fails, Claude Code also shows its own dialog.+## ThemesA theme sets the colours, fonts and spacing of the picture. Two themes are in the mod:@@ -102,23 +131,43 @@ The `vscode` and `vscode-modern` values come from VS Code (MIT licence, Copyrigh## How it works1. A `ui.render` hook on `AssistantMessage` gets each block of the answer as Markdown.-2. When the text stops changing for 400 ms, the mod writes the block to a JSON file and runs `typst compile` with `render/md.typ`. Long answers are cut at block boundaries into pages. One page is one PNG.+2. While Claude writes a block, the block is hidden. The block is final when the model request starts its next block (a tool call, more text) or ends. If the mod did not see the request, the block is final after its text stops changing for 400 ms. Then the mod writes the block to a JSON file and runs `typst compile` with `render/md.typ`. Long answers are cut at block boundaries into pages. One page is one PNG.3. The hook draws one `Image` per PNG, in place of the text.-4. Text size: the mod finds the terminal font (iTerm2 profile, Ghostty config, else Menlo metrics) and the cell size in pixels. Typst then measures both fonts so that 100% looks as large as the terminal text.+4. Text size: the mod finds the terminal font (iTerm2 profile, Ghostty, kitty or Rio config, else Menlo metrics) and the cell size in pixels. Typst then measures both fonts so that 100% looks as large as the terminal text.5. If a compile fails (a bad Typst block or an unknown LaTeX command), the mod compiles once more in safe mode: Typst blocks and math show as code. A dim line under the picture names the error. If that also fails, the normal text shows.6. Pictures are kept in `${TMPDIR}/md-preview-<uid>/`. Folders older than 2 days are deleted at start.+7. The plan: a `ui.render` hook on the ExitPlanMode `ToolUse` row draws the plan through the same steps. Claude Code shows that row above the approval question. The approved result row then shows only its header, so the plan does not show two times. A `tool.call` hook on ExitPlanMode asks the mod's question (`$.ui.ask`) before Claude Code asks for permission. Then a `classic.PermissionRequest` hook gives the answer to Claude Code at once, so the Claude Code dialog does not show. For an approval, the hook sends the plan (`updatedInput`) and the new permission mode (`setMode`). For the person's text, the `tool.call` hook refuses the call with that text.++### How `auto` is resolved++Claude Code finds the light or dark mode for `auto` by asking the terminal for its background colour (OSC 11). A mod cannot see that answer, so md-preview uses these sources, in this order. The first source that gives an answer is used:++1. **The iTerm2 profile:** the background colour of the profile in use (`ITERM_PROFILE`, else the default profile). md-preview finds iTerm2 by `TERM_PROGRAM`. If `TERM_PROGRAM` is not set, `ITERM_PROFILE`, `ITERM_SESSION_ID` or `LC_TERMINAL=iTerm2` also show iTerm2. If the profile has separate colours for light and dark mode, md-preview uses the set for iTerm2's theme (Settings > Appearance). If that theme is Automatic, Minimal or Compact, it uses the set for the OS appearance.+2. **The Ghostty config:** the `background` that `ghostty +show-config` gives. With a `theme = light:A,dark:B`, md-preview reads the background from the theme file for the OS appearance. With no theme and no `background`, it uses Ghostty's default (`#282c34`, dark).+ - **cmux** (Ghostty inside, found by its `CMUX_*` variables) reads the same Ghostty config. If that config sets no `theme`, `background`, `foreground` or `palette`, cmux uses its adaptive default theme. md-preview then uses cmux's appearance: `app.appearance` in `~/.config/cmux/cmux.json`, else the value in cmux's Settings. If that appearance is System, md-preview uses the OS appearance. If `terminal.adaptiveDefaultTheme` is `false` in `cmux.json`, md-preview uses the Ghostty rules above.+3. **The kitty config:** the `background` in `kitty.conf` and in the files that it includes (`include` lines only). The themes kitten writes such an include. If the config folder has `dark-theme.auto.conf`, `light-theme.auto.conf` or `no-preference-theme.auto.conf` (kitty 0.38 and later), md-preview uses the file for the OS appearance, as kitty does. With no `background`, it uses kitty's default (`#000000`, dark). The config folder is `KITTY_CONFIG_DIRECTORY`. If that is not set, it is the first of `$XDG_CONFIG_HOME/kitty`, `~/.config/kitty` and (on macOS) `~/Library/Preferences/kitty` that has a `kitty.conf`.+4. **The Rio config:** `config.toml` in `RIO_CONFIG_HOME`, else in `~/.config/rio` (on Linux, `$XDG_CONFIG_HOME/rio` if that is set). With an `[adaptive-theme]`, md-preview reads the theme file for `force-theme`, else for the OS appearance. Else it reads the file for `theme`, else the `[colors] background`. Theme files are in the `themes` folder. With no background, it uses Rio's default (`#0F0D0E`, dark).+5. **`COLORFGBG`**, as it was when Claude Code started. Ghostty does not set it.+6. **The OS appearance:** macOS Dark or Light, or GNOME's `color-scheme` on Linux.+7. **Dark.**++The terminal comes before the OS: a dark terminal on a light Mac is dark.++md-preview checks every 3 s. After a change, each mode's pictures compile once. `/md-preview probe` asks the terminal for its background with OSC 11 (5 times) and shows the raw answers. This is a test of whether the answer can reach the mod. The 3 s check does not use OSC 11 yet.## Limitations- **Copying text from a picture does not work.** A picture fills its cells with kitty placeholder characters (U+10EEEE plus combining marks). Claude Code's mouse selection copies those cells directly to the clipboard, and no mod hook runs before that copy. So a paste gives strange characters, not the text. Use Claude Code's `/copy` to copy the last answer as Markdown (`/copy 2` for the one before it; it shows a picker for the full answer or one code block, unless "Skip the /copy picker" is on in `/config`), or turn the mod off (`/md-preview off`) to select text. To stop the clipboard write on select, set `copyOnSelect` to `false` in `/config`.- **Search does not find text in a picture.**-- **While Claude writes**, the answer shows as normal text. The picture comes about 0.4 s after the text stops changing, plus 0.15–0.6 s to compile.+- **While Claude writes**, the block is hidden, and Claude Code's spinner shows the progress. When the block is final, its picture shows after the compile (0.15–0.6 s). A long answer shows only when it is done. If the picture is not ready 2 s after the block is final, the normal text shows until the picture is ready. If the compile fails, the normal text stays. An earlier answer that is not in the cache (for example, after a resume) is blank for up to 1 s, then shows as text until its picture is ready.- **Short summaries** between tool calls stay as text.+- **Plan approval:** a mod cannot draw the Claude Code approval dialog, so the mod shows its own question. That question can have 4 options at most. Thus it has no option to keep planning (use Type something or Esc). The edit option cannot use a terminal editor (vim, nano), because a mod has no terminal. Where an organization manages Claude Code, `classic.PermissionRequest` hooks of a plugin that you install do not run. Then the Claude Code dialog shows after the mod's question.- **Typst blocks:** `#page`, `#pagebreak` and `#set page` are errors. A package that is not in the mod cannot be downloaded (the network is blocked for Typst), so its block shows as code.- **Security:** Typst runs with `--root /`, so a Typst block can read any file that you can read and draw it in the picture. Nothing leaves the computer.- **The look is close to VS Code, not exact:** Typst does not use CSS. Raw HTML in Markdown is shown in a simple form or dropped. Loose lists have tight spacing.- **A picture that the terminal dropped from its image memory** (after many large pictures) is not sent again when you scroll back to it.-- **`auto` theme** is drawn as dark.+- **Over ssh**, the mod cannot read the terminal's config on your computer. So it uses Menlo metrics for the text size, and `auto` uses `COLORFGBG` if ssh sends it. Else `auto` is dark. The mod does not use the OS appearance of the remote computer. Pages are shorter, so that each one is at most 4096 pixels tall. In tmux or screen on the remote computer, no pictures show.+- **`auto` theme** reads the iTerm2 profile, the Ghostty, kitty and Rio configs, and the cmux settings directly. It does not read kitty's `globinclude`, `envinclude` and `geninclude` lines, or colours that you set while kitty runs. In other terminals, it uses `COLORFGBG` (set only when the terminal starts), then the OS appearance. If you change the theme of such a terminal and the OS appearance does not change, md-preview does not see it. A change shows after up to 3 s.## Develop@@ -133,6 +182,8 @@ claude plugin validate .`.claude-plugin/types/` is not in git. `tsconfig.json` extends the `tsconfig.json` in it, so run Claude Code with the folder once before `tsc`.+The hooks module is `hooks/register.tsx`. It connects the hooks to the modules in `hooks/lib/`. Each module has one topic, for example `markdown.ts` (blocks and segments), `mode.ts` (light or dark), `typst.ts` (compile) `draw.tsx` (the pages of an answer), `answer.ts` (one text through the compile and cache steps) and `plan.tsx` (the plan approval question and the plan rows). The values that change are in one object, `S`, in `state.ts`. The tests import from `hooks/register.tsx`, which exports the names that they use.+## LicenceMIT, see [`LICENSE`](LICENSE). The vendored Typst packages and the VS Code theme values keep their own licences: see [`THIRD-PARTY-NOTICES.md`](THIRD-PARTY-NOTICES.md).diff --git a/hooks/lib/answer.ts b/hooks/lib/answer.tsnew file mode 100644index 0000000..34a080e--- /dev/null+++ b/hooks/lib/answer.ts@@ -0,0 +1,71 @@+// One Markdown text through the answer pipeline: its key, the compiled+// pages, and the states before they are ready (blank while it streams or+// compiles, then the engine's text). The AssistantMessage hook and the plan+// (its ExitPlanMode rows) all draw through it.+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 { enqueue, finalize, forget, waitBlank } from './stream'++// `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' }++// `id` keys the text's place (its message, its row), `columns` is+// the picture width. `canStream`: the text may still grow (an answer); a+// plan is final when it is drawn, so it never waits as live.+export async function pagesOf($: EngineInterface, o: { id: string; text: string; columns: number; env: Env; canStream: boolean }): Promise<Drawing> {+ const { id, text, columns, env } = o+ const px = S.cell ?? DEFAULT_CELL+ const textHash = hashOf([text])+ const active = S.look ?? { name: DEFAULT_THEME, dir: `${env.root}/render/themes/${DEFAULT_THEME}`, stamp: '0' }+ const key = renderKey({+ textHash, columns, cell: px, size: S.size, mode: S.theme, termFont: env.termFont,+ columnPt: fontFit(env.metrics, S.size).columnPt, templateStamp: env.stamp, look: active, inline: env.inline,+ })+ const seen = lastText.get(id)+ const changed = seen !== text+ lastText.set(id, text)+ const got = results.get(key)+ if (got === 'failed') {+ forget(id)+ return { kind: 'text' }+ }+ if (got) {+ 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' }+ }+ const job: Job = { key, requestId: id, text, columns, cell: px, theme: S.theme, size: S.size, themeDir: active.dir, env }+ // 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).+ const isLive = o.canStream && (live.has(id) || (changed && !finalized.has(id) && (S.stepsLive > 0 || seen !== undefined)))+ if (isLive) {+ const was = live.get(id)+ if (!was || changed) {+ was?.still.cancel()+ const still = $.clock.after(S.stepsLive > 0 ? LIVE_STILL_MS : SETTLE_MS, () => finalize($, id, false))+ live.set(id, { job, still })+ } else live.set(id, { job, still: was.still })+ pending.get(id)?.timer.cancel()+ 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.+ 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 }+ }+ waitBlank($, id, textHash, finalized.has(id) ? BLANK_AFTER_LIVE_MS : BLANK_RESUMED_MS)+ return pending.get(id)?.showText ? { kind: 'text' } : { kind: 'blank' }+}diff --git a/hooks/lib/command.ts b/hooks/lib/command.tsnew file mode 100644index 0000000..9ea11a9--- /dev/null+++ b/hooks/lib/command.ts@@ -0,0 +1,86 @@+// The /md-preview command: its arguments, the typeahead rows for them, and+// its registration.+import type { EngineInterface } from 'claude-code'++import { DEFAULT_SIZE, MAX_SIZE, MIN_SIZE } from './settings'+import { isThemeName, type ThemeInfo } from './themes'++// `/md-preview` arguments: on, off, size <80-200>, or nothing (show state).+export type Command =+ | { kind: 'on' | 'off' | 'show' | 'probe' }+ | { kind: 'size'; percent: number }+ | { kind: 'theme'; name?: string }+ | { kind: 'setup'; remove: boolean }+ | { kind: 'bad' }+export function parseCommand(args: string): Command {+ const typed = args.trim().split(/\s+/).filter(Boolean)+ const words = typed.map(w => w.toLowerCase())+ if (!words.length) return { kind: 'show' }+ if (words[0] === 'theme') {+ if (typed.length === 1) return { kind: 'theme' }+ if (typed.length === 2 && isThemeName(typed[1]!)) return { kind: 'theme', name: typed[1]! }+ return { kind: 'bad' }+ }+ if (words.length === 1 && (words[0] === 'on' || words[0] === 'off' || words[0] === 'probe')) return { kind: words[0] }+ if (words[0] === 'setup' && words.length === 1) return { kind: 'setup', remove: false }+ if (words[0] === 'setup' && words.length === 2 && words[1] === 'remove') return { kind: 'setup', remove: true }+ if (words[0] === 'size' && words.length === 2 && /^\d+%?$/.test(words[1]!)) {+ const percent = Number.parseInt(words[1]!, 10)+ if (percent >= MIN_SIZE && percent <= MAX_SIZE) return { kind: 'size', percent }+ }+ return { kind: 'bad' }+}++// The /md-preview arguments, and the sizes the typeahead offers.+const SUBCOMMANDS = [+ { name: 'on', description: 'draw answers as pictures' },+ { name: 'off', description: 'show answers as text' },+ { name: 'size', description: `text size, ${MIN_SIZE}-${MAX_SIZE}%` },+ { name: 'theme', description: 'list the themes, or switch to one' },+ { name: 'setup', description: 'iTerm2: add the shell line that turns pictures on' },+] as const+const SIZES = [80, 90, 100, 110, 120, 125, 150, 175, 200]++// Typeahead rows for `/md-preview` arguments: the word at the cursor (`token`,+// starting at `start` in `text`) completed as a subcommand, a theme name or a+// size. Right after `theme` or `size`, rows hold the word and its argument,+// since the typeahead asks only while a word is at the cursor.+export type Suggestion = { text: string; label?: string; description?: string }+export function commandSuggestions(+ text: string, token: string, start: number,+ o: { themes: readonly ThemeInfo[]; active: string; size: number },+): Suggestion[] {+ const head = /^\s*\/md-preview\s+/.exec(text)+ if (!head || start < head[0].length) return []+ const before = text.slice(head[0].length, start).trim().split(/\s+/).filter(Boolean).map(w => w.toLowerCase())+ const word = token.toLowerCase()+ const themeRows = (prefix: string, lead: string) => [...o.themes]+ .filter(t => t.name.toLowerCase().startsWith(prefix))+ .sort((a, b) => a.name.localeCompare(b.name))+ .map(t => ({+ text: `${lead}${t.name}`,+ label: t.name,+ description: `${t.isUser ? 'user' : 'built-in'}${t.name === o.active ? ', active' : ''}${t.description ? `: ${t.description}` : ''}`,+ }))+ const sizeRows = (prefix: string, lead: string) => SIZES+ .filter(n => String(n).startsWith(prefix))+ .map(n => ({ text: `${lead}${n}`, label: `${n}%`, description: n === o.size ? 'current' : n === DEFAULT_SIZE ? 'the terminal text size' : undefined }))+ if (before.length === 0) {+ if (word === 'theme') return themeRows('', 'theme ')+ if (word === 'size') return sizeRows('', 'size ')+ return SUBCOMMANDS.filter(c => c.name.startsWith(word)).map(c => ({ text: c.name, description: c.description }))+ }+ if (before.length === 1 && before[0] === 'theme') return themeRows(word, '')+ if (before.length === 1 && before[0] === 'size') return sizeRows(word.replace(/%$/, ''), '')+ return []+}++// /md-preview; registered at session start and again in setUp, so it is+// there after a hot reload too.+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), theme [name] (list or switch themes)",+ argumentHint: '[on|off|size <percent>|theme [name]]',+ }).catch(() => undefined)+}diff --git a/hooks/lib/draw.tsx b/hooks/lib/draw.tsxnew file mode 100644index 0000000..981c4f6--- /dev/null+++ b/hooks/lib/draw.tsx@@ -0,0 +1,173 @@+// 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 { 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 { FENCE } from './markdown'+import { fitsInline } from './terminal'++// FNV-1a over the parts, twice with different offsets: 16 hex digits.+export function hashOf(parts: readonly (string | number)[]): string {+ const s = parts.join('\u0000')+ let a = 0x811c9dc5+ let b = 0x050c5d1f+ for (let i = 0; i < s.length; i++) {+ const c = s.charCodeAt(i)+ a = Math.imul(a ^ c, 0x01000193) >>> 0+ b = Math.imul(b ^ c, 0x01000193) >>> 0+ }+ return a.toString(16).padStart(8, '0') + b.toString(16).padStart(8, '0')+}++// How wide a column is in the page's pt so the template's 11 pt body text+// looks as big as the terminal's text, `sizePercent` on top. A terminal em is+// a cell / the advance of its font; the body font is matched to it by+// x-height and average width together (sqrt of the two ratios), since a+// proportional font at the same em looks smaller. Code is set in the+// terminal's font at the terminal's size: `code` is its size / body size.+// The template uses `code` only for a theme that sets "size": "terminal"+// for code; the vscode themes draw code at body size, as VS Code does.+export function fontFit(m: Metrics, sizePercent = 100) {+ const t = m.term ?? m.menlo+ const ratio = Math.sqrt((t.xh / m.body.xh) * (t.avg / m.body.avg))+ const scale = sizePercent / 100+ return {+ columnPt: Math.round(((BODY_PT * t.adv) / (ratio * scale)) * 10000) / 10000,+ code: Math.round((1 / ratio) * 10000) / 10000,+ ratio,+ }+}++// The page width in pt and the ppi that make the PNG exactly as wide as the+// box in device pixels; `rowPt` is one terminal row in the page's pt.+export function sizing(columns: number, px: Cell, columnPt: number) {+ const widthPt = Math.round(columns * columnPt * 100) / 100+ const widthPx = Math.round(columns * px.width)+ const ppi = widthPx / (widthPt / 72)+ return { widthPt, widthPx, ppi, rowPt: (px.height * 72) / ppi }+}++// Every input a picture depends on, as one key.+export function renderKey(o: {+ textHash: string+ columns: number+ cell: Cell+ size: number+ mode: MdPreviewTheme+ termFont: string+ columnPt: number+ templateStamp: string+ look: Look+ // Over ssh: pages are cut shorter (inlineBudget), so they are other PNGs.+ inline?: boolean+}): string {+ return hashOf([+ o.textHash, o.columns, o.cell.width, o.cell.height, o.size, o.mode, o.termFont, o.columnPt,+ o.templateStamp, o.look.name, o.look.dir, o.look.stamp, TEMPLATE_VERSION, ...(o.inline ? ['inline'] : []),+ ])+}++// Where the first line of a page's text lies with no top margin, in the+// template's pt (measured from its PNGs at 11 pt body text): the centre of+// its ink, and the top of its ink. By what the answer starts with.+export type FirstLine = 'para' | 'h1' | 'h2' | 'h3' | 'h4' | 'quote' | 'code' | 'table'+const FIRST_LINE: Record<FirstLine, { centre: number; inkTop: number }> = {+ para: { centre: 7.45, inkTop: 2.55 },+ h1: { centre: 20.36, inkTop: 5.82 },+ h2: { centre: 13.09, inkTop: 3.64 },+ h3: { centre: 9.09, inkTop: 2.55 },+ h4: { centre: 7.27, inkTop: 2.18 },+ quote: { centre: 13.45, inkTop: 8.36 },+ code: { centre: 17.09, inkTop: 12.36 },+ table: { centre: 11.27, inkTop: 6.18 },+}++export function firstLineOf(md: string): FirstLine {+ const line = md.split('\n').find(l => l.trim()) ?? ''+ const heading = /^ {0,3}(#{1,6})\s/.exec(line)+ if (heading) return (['h1', 'h2', 'h3'] as const)[heading[1]!.length - 1] ?? 'h4'+ if (/^ {0,3}>/.test(line)) return 'quote'+ if (FENCE.test(line)) return 'code'+ if (/^ {0,3}\|/.test(line)) return 'table'+ return 'para'+}++// The first page's top margin (pt, may be negative) that puts the centre of+// the first line of text on the centre of a terminal row, and which row that+// is: row 0 when the line fits there, else the first row its ink can reach+// without being cut at the picture's top. The bullet is drawn on that row.+export function alignFirstLine(kind: FirstLine, rowPt: number): { topPt: number; bulletRow: number } {+ const { centre, inkTop } = FIRST_LINE[kind]+ const bulletRow = Math.max(0, Math.ceil((centre - inkTop + 0.5) / rowPt - 0.5 - 1e-9))+ 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.+export async function inlineOf($: EngineInterface, result: Result): Promise<string[] | null> {+ const out: string[] = []+ for (const page of result.pages) {+ if (!fitsInline(page)) return null+ if (!inlined.has(page.file)) {+ const got = await $.fs.read(page.file, { as: 'bytes' }).catch(() => null)+ const base64 = got && fitsInline(page, got.base64) ? got.base64 : null+ if (got) inlined.set(page.file, base64)+ for (const old of inlined.keys()) {+ if (inlined.size <= INLINE_KEPT) break+ inlined.delete(old)+ }+ if (!base64) return null+ out.push(base64)+ continue+ }+ const base64 = inlined.get(page.file)+ if (!base64) return null+ out.push(base64)+ }+ return out+}++// How a set of pages sits: `bullet` the reply bullet in the gutter (on the+// first line's row), `gutter` its width (0: none), `marginTop` the rows above.+export type PagesLayout = { bullet?: boolean; gutter?: number; marginTop?: number }++// `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 = {}) {+ const { Box, Text, Image } = $.ui.resolve(e)+ const gutter = layout.gutter ?? GUTTER+ return (+ <Box flexDirection="row" marginTop={layout.marginTop ?? MARGIN_TOP}>+ {gutter > 0 ? (+ <Box width={gutter} flexShrink={0} marginTop={result.bulletRow}>+ <Text>{layout.bullet ? bulletOf(S.env?.isMac ?? true) : ' '}</Text>+ </Box>+ ) : null}+ <Box flexDirection="column">+ {result.pages.map((page, i) => {+ const rows = rowsFor(page, columns, px)+ return (+ <Image+ key={`p${i}`}+ source={inline ? { png: inline[i]! } : { file: page.file, format: 'png', generation: columns * 1000 + rows }}+ columns={columns}+ rows={rows}+ alt={page.alt}+ />+ )+ })}+ {result.note ? <Text dimColor wrap="truncate-end">Typst error: {result.note}</Text> : null}+ </Box>+ </Box>+ )+}diff --git a/hooks/lib/env.ts b/hooks/lib/env.tsnew file mode 100644index 0000000..b3a9e55--- /dev/null+++ b/hooks/lib/env.ts@@ -0,0 +1,139 @@+// 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.+import { atom, update } from 'claude-code'+import type { EngineInterface } from 'claude-code'++import { BASE_THEME, DEFAULT_SIZE, DEFAULT_THEME, MAX_SIZE, MIN_SIZE, NO_TYPST } from './settings'+import { DEFAULT_METRICS, refresh, S, type Env } from './state'+import { resolveMode, settingOf } from './mode'+import { isItermIn } from './terminals'+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 { offerSetup } from './setup'+import { findTypst, measureFonts } from './typst'++// The `isOn` atom, which setUp turns off when the stored setting says so (a+// 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)"; }`++// 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.+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 cache = made1.trim() || '/tmp/md-preview'+ 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'))+ const canDraw = canDrawIn({+ program,+ term,+ kitty: !!(await $.env.get('KITTY_WINDOW_ID')),+ tmux: !!(await $.env.get('TMUX')) || !!(await $.env.get('STY')) || /^tmux|^screen/i.test(term),+ ssh,+ background: (await $.env.get('CLAUDE_CODE_SESSION_KIND')) === 'bg',+ engineForced: isSet(await $.env.get('CLAUDE_CODE_FORCE_TERMINAL_IMAGES')),+ modForced: isSet(await $.env.get('MD_PREVIEW_FORCE')),+ })+ const root = $.plugin.root+ const template = await $.fs.stat(`${root}/render/md.typ`).catch(() => null)+ const rows = await $.config.list().catch(() => [])+ const raw = rows.find(row => row.key === 'theme')?.value+ S.settingRaw = typeof raw === 'string' ? raw : ''+ S.setting = settingOf(raw)+ S.hostOs = os.trim()+ S.termProgram = program+ S.termName = term+ 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.isIterm = isItermIn({+ program,+ profile: S.itermProfile,+ session: (await $.env.get('ITERM_SESSION_ID')) || undefined,+ lcTerminal: (await $.env.get('LC_TERMINAL')) || undefined,+ })+ S.setupNeeded = S.isIterm && !canDraw && !ssh && S.hostOs === 'Darwin' &&+ !(await $.env.get('TMUX')) && !(await $.env.get('STY')) && (await $.env.get('CLAUDE_CODE_SESSION_KIND')) !== 'bg'+ if (S.setupNeeded) void offerSetup($).catch(() => undefined)+ S.isCmux = !!(await $.env.get('CMUX_SURFACE_ID')) || !!(await $.env.get('CMUX_WORKSPACE_ID')) || !!(await $.env.get('CMUX_SOCKET_PATH'))+ S.colorFgBg = (await $.env.get('COLORFGBG')) ?? ''+ if (S.setting === 'auto') S.host = (await readHostMode($).catch(() => null)) ?? S.host+ S.theme = resolveMode(S.setting, S.host)+ watchHost($)+ const kept = Number(await $.store.get('size').catch(() => undefined))+ S.size = kept >= MIN_SIZE && kept <= MAX_SIZE ? kept : DEFAULT_SIZE+ if ((await $.store.get('enabled').catch(() => undefined)) === false) await update($, isOn, () => false).catch(() => undefined)+ const isMac = os.trim() === 'Darwin'+ S.cell = await measureCell($)+ const typst = await findTypst($)+ if (!typst) {+ try {+ $.ui.toast(NO_TYPST, { timeoutMs: 8000 })+ } catch {}+ }+ const termFont = await termFontOf($, program, isMac).catch(() => '')+ const home = (await $.env.get('HOME')) ?? ''+ 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)+ if (!applied) S.look = { name: BASE_THEME, dir: `${root}/render/themes/${BASE_THEME}`, stamp: '0' }+ else if (applied.chosen.isFallback) {+ try {+ $.ui.toast(`md-preview: theme ${wanted} not found, using ${applied.chosen.name}`, { timeoutMs: 8000 })+ } catch {}+ }+ S.env = {+ typst,+ canDraw,+ inline: ssh && canDraw,+ cache,+ cwd: await $.session.cwd().catch(() => '/'),+ root,+ isMac,+ stamp: String(template?.mtimeMs ?? 0),+ home,+ claudeTmp: claudeTmpOf({+ tmpdir: (await $.env.get('CLAUDE_CODE_TMPDIR')) || undefined,+ uid: await $.process.run(['id', '-u']).then(r => (r.exitCode === 0 ? r.stdout : ''), () => ''),+ isMac,+ }),+ termFont,+ metrics: typst ? await measureFonts($, typst, root, cache, termFont, S.look?.dir ?? `${root}/render/themes/${BASE_THEME}`) : DEFAULT_METRICS,+ }+ refresh($)+ return S.env+ })().catch((err: unknown) => {+ S.envLoading = null+ throw err+ })+ 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/host.ts b/hooks/lib/host.tsnew file mode 100644index 0000000..d2c6862--- /dev/null+++ b/hooks/lib/host.ts@@ -0,0 +1,313 @@+// 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+// 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 { luminanceOf, modeOfColorFgBg, modeOfGnome, modeOfLuminance, modeOfMacAppearance, parseOsc11, resolveMode, type HostMode } from './mode'+import {+ cmuxAppearanceOf, cmuxSettingsOf, ghosttyBackgroundOf, ghosttyFontOf, ghosttyHasColors, ghosttyThemePaths, ghosttyThemesOf,+ ghosttyValueOf, hexColorOf, itermAppearanceOf, itermFontOf, itermModeOf, jsoncOf, kittyAutoFileOf, kittyBackgroundOf,+ 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))'`+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.+const FAMILY_JXA = 'function run(argv) { ObjC.import("AppKit"); var f = $.NSFont.fontWithNameSize(argv[0], 12); return f.isNil() ? "" : f.familyName.js }'+// iTerm2's appearance, the default profile's GUID and the profiles, split by "@" lines.+const ITERM_MODE_SH = `defaults read com.googlecode.iterm2 TabStyleWithAutomaticOption 2>/dev/null; echo @; ${ITERM_DEFAULT_SH} 2>/dev/null; echo @; ${ITERM_BOOKMARKS_SH}`+const GHOSTTY_SH = `"\${GHOSTTY_BIN_DIR:+\$GHOSTTY_BIN_DIR/}ghostty" +show-config`+// Asks the terminal for its background (OSC 11) and prints the answer. It+// opens the tty itself, non-blocking, changes no tty mode, and waits 300 ms at+// most. Claude Code reads the same tty, so the answer may go to it instead.+export const OSC11_PL = [+ 'use Fcntl; use IO::Select; use Time::HiRes qw(time);',+ 'sysopen(my $t, "/dev/tty", O_RDWR | O_NONBLOCK | O_NOCTTY) or exit 1;',+ 'syswrite($t, "\\e]11;?\\a");',+ 'my $s = IO::Select->new($t); my $r = ""; my $end = time + 0.3;',+ 'while ((my $left = $end - time) > 0) {',+ ' last unless $s->can_read($left);',+ ' my $n = sysread($t, my $b, 256);',+ ' last if !defined $n && !$!{EAGAIN}; last if defined $n && $n == 0;',+ ' $r .= $b if $n; last if $r =~ /\\a|\\e\\\\/;',+ '}',+ 'print $r;',+].join(' ')+// Off until /md-preview probe shows the answer reaches the mod: the poll+// then asks the terminal (source 1 of auto) every period.+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.+export async function termFontOf($: EngineInterface, program: string, isMac: boolean): Promise<string> {+ // Over ssh, a config here is not the one of the user's terminal.+ if (S.isRemote) return ''+ if (S.isIterm && isMac) {+ const profile = await $.env.get('ITERM_PROFILE')+ const [marks, guid] = await Promise.all([+ $.process.run(['sh', '-c', ITERM_BOOKMARKS_SH], { timeoutMs: 5000 }).catch(() => null),+ $.process.run(['sh', '-c', ITERM_DEFAULT_SH], { timeoutMs: 5000 }).catch(() => null),+ ])+ const spec = parseFontSpec(itermFontOf(marks?.stdout ?? '', profile, guid?.stdout ?? '') ?? '')+ if (!spec) return ''+ const named = await $.process.run(['osascript', '-l', 'JavaScript', '-e', FAMILY_JXA, spec.name], { timeoutMs: 5000 }).catch(() => null)+ return named?.exitCode === 0 ? firstLine(named.stdout) : ''+ }+ if (/ghostty/i.test(program)) {+ const shown = await $.process.run(['sh', '-c', GHOSTTY_SH], { timeoutMs: 5000 }).catch(() => null)+ return ghosttyFontOf(shown?.stdout ?? '') ?? ''+ }+ if (S.isKitty) {+ // A family name as is; a PostScript name to its family (macOS); the+ // system's monospace from fontconfig (Linux; on macOS it is Menlo).+ const font = kittyFontOf(kittyValueOf((await readKittyConfig($)).entries, 'font_family'))+ if (font && 'family' in font) return font.family+ if (font && isMac) {+ const named = await $.process.run(['osascript', '-l', 'JavaScript', '-e', FAMILY_JXA, font.postscript], { timeoutMs: 5000 }).catch(() => null)+ return named?.exitCode === 0 ? firstLine(named.stdout) : ''+ }+ if (!font && !isMac) {+ const got = await $.process.run(['fc-match', 'monospace', '-f', '%{family}'], { timeoutMs: 5000 }).catch(() => null)+ return got?.exitCode === 0 ? (got.stdout.split(',')[0] ?? '').trim() : ''+ }+ return ''+ }+ if (isRioHere()) return rioFontOf((await readRioConfig($)).config)+ return ''+}++// The mode for auto now, or null when nothing can be read (keep the last+// one): 1. the terminal's OSC 11 answer (off, see USE_OSC11); 2. the+// terminal's own settings (iTerm2's profile, Ghostty's, kitty's or Rio's+// config); 3. COLORFGBG at start; 4. the+// OS appearance; 5. dark (resolveMode). The terminal comes before the OS: a+// dark terminal on a light Mac is dark. Over ssh, only COLORFGBG (when ssh+// sends it): the configs and the OS here are the remote computer's.+export async function readHostMode($: EngineInterface): Promise<HostMode | null> {+ if (USE_OSC11) {+ const bg = parseOsc11((await probeOsc11($))?.reply ?? '')+ if (bg) return { mode: modeOfLuminance(luminanceOf(bg)), source: 'terminal', detail: 'OSC 11 background' }+ }+ if (S.isRemote) {+ const mode = modeOfColorFgBg(S.colorFgBg)+ return mode ? { mode, source: 'COLORFGBG' } : null+ }+ const term =+ (await readItermMode($).catch(() => null)) ??+ (await readGhosttyMode($).catch(() => null)) ??+ (await readKittyMode($).catch(() => null)) ??+ (await readRioMode($).catch(() => null))+ if (term) return term+ const mode = modeOfColorFgBg(S.colorFgBg)+ if (mode) return { mode, source: 'COLORFGBG' }+ return readOsMode($).catch(() => null)+}++// The background of the iTerm2 profile in use, on a Mac.+async function readItermMode($: EngineInterface): Promise<HostMode | null> {+ if (!S.isIterm || S.hostOs !== 'Darwin') return null+ const got = await $.process.run(['sh', '-c', ITERM_MODE_SH], { timeoutMs: HOST_CHECK_MS }).catch(() => null)+ if (!got || got.exitCode !== 0) return null+ const [style = '', guid = '', marks = ''] = got.stdout.split(/^@\n/m)+ const appearance = itermAppearanceOf(style) ?? (await readOsMode($).catch(() => null))?.mode ?? null+ const mode = itermModeOf(marks, S.itermProfile, guid, appearance)+ return mode ? { mode, source: 'iTerm2', detail: `profile ${S.itermProfile || 'default'} background` } : null+}++// One OSC 11 question to the terminal: its raw answer ('' for none), or null+// when the tty could not be opened.+export async function probeOsc11($: EngineInterface): Promise<{ reply: string } | null> {+ const got = await $.process.run(['perl', '-e', OSC11_PL], { timeoutMs: HOST_CHECK_MS }).catch(() => null)+ return got && got.exitCode === 0 ? { reply: got.stdout } : null+}++// The background of Ghostty's config. A `light:A,dark:B` theme follows the OS.+async function readGhosttyMode($: EngineInterface): Promise<HostMode | null> {+ if (!/ghostty/i.test(S.termProgram + S.termName)) return null+ const got = await $.process.run(['sh', '-c', GHOSTTY_SH], { timeoutMs: HOST_CHECK_MS }).catch(() => null)+ if (!got || got.exitCode !== 0) return null+ if (S.isCmux && !ghosttyHasColors(got.stdout)) {+ const adaptive = await readCmuxMode($).catch(() => null)+ if (adaptive) return adaptive+ }+ const pair = ghosttyThemesOf(ghosttyValueOf(got.stdout, 'theme'))+ const themeBg: { light?: string; dark?: string } = {}+ let appearance: MdPreviewTheme | null = null+ if (pair) {+ appearance = (await readOsMode($).catch(() => null))?.mode ?? null+ const where = {+ xdgConfig: (await $.env.get('XDG_CONFIG_HOME')) || undefined,+ home: (await $.env.get('HOME')) ?? '',+ resources: (await $.env.get('GHOSTTY_RESOURCES_DIR')) || undefined,+ }+ for (const mode of MODES) {+ for (const path of ghosttyThemePaths(pair[mode], where)) {+ const text = await $.fs.read(path).catch(() => null)+ if (typeof text !== 'string') continue+ themeBg[mode] = ghosttyValueOf(text, 'background')+ break+ }+ }+ }+ const bg = hexColorOf(ghosttyBackgroundOf(got.stdout, appearance, themeBg) ?? '')+ if (!bg) return null+ const shown = ghosttyValueOf(got.stdout, 'background')+ const detail = `${!shown ? 'default' : pair && appearance ? `theme ${pair[appearance]}` : 'config'} background`+ return { mode: modeOfLuminance(luminanceOf(bg)), source: 'Ghostty', detail }+}++// cmux with no colours in the Ghostty config: its adaptive default theme+// (terminal.adaptiveDefaultTheme, on unless cmux.json turns it off) follows+// cmux's appearance, the OS's when that is system. Null when it is off.+async function readCmuxMode($: EngineInterface): Promise<HostMode | null> {+ const home = (await $.env.get('HOME')) ?? ''+ const settings = cmuxSettingsOf(jsoncOf((await readText($, `${home}/.config/cmux/cmux.json`)) ?? ''))+ if (settings.adaptive === false) return null+ let saved = ''+ if (!settings.appearance && S.hostOs === 'Darwin') {+ const got = await $.process.run(['defaults', 'read', 'com.cmuxterm.app', 'appearanceMode'], { timeoutMs: HOST_CHECK_MS }).catch(() => null)+ saved = got?.exitCode === 0 ? got.stdout : ''+ }+ const appearance = cmuxAppearanceOf(settings.appearance, saved)+ const mode = appearance === 'system' ? ((await readOsMode($).catch(() => null))?.mode ?? null) : appearance+ return mode ? { mode, source: 'cmux', detail: `adaptive default theme, appearance ${appearance}` } : null+}++// Rio sets TERM_PROGRAM=rio, and TERM=rio when its terminfo is installed.+const isRioHere = () => /^rio$/i.test(S.termProgram) || /^rio$/i.test(S.termName)++// A file's text, or null when it can't be read.+export async function readText($: EngineInterface, path: string): Promise<string | null> {+ const text = await $.fs.read(path).catch(() => null)+ return typeof text === 'string' ? text : null+}++// kitty's config folder and kitty.conf with its includes: the first folder+// that has a kitty.conf, else the first folder (auto theme files can be there).+async function readKittyConfig($: EngineInterface): Promise<{ dir: string; entries: KittyEntries; home: string }> {+ const home = (await $.env.get('HOME')) ?? ''+ const dirs = kittyConfigDirsOf({+ kittyDir: (await $.env.get('KITTY_CONFIG_DIRECTORY')) || undefined,+ xdgConfig: (await $.env.get('XDG_CONFIG_HOME')) || undefined,+ home,+ isMac: S.hostOs === 'Darwin',+ })+ const o = { home, vars: { KITTY_OS: S.hostOs === 'Darwin' ? 'macos' : S.hostOs.toLowerCase() } }+ for (const dir of dirs) {+ if (!(await $.fs.exists(`${dir}/kitty.conf`).catch(() => false))) continue+ return { dir, entries: await kittyEntriesOf(`${dir}/kitty.conf`, path => readText($, path), o), home }+ }+ return { dir: dirs[0]!, entries: [], home }+}++// The background of kitty's config. Auto theme files (kitty 0.38+) follow+// the OS: the OS is read only when one of them exists.+async function readKittyMode($: EngineInterface): Promise<HostMode | null> {+ if (!S.isKitty) return null+ const { dir, entries, home } = await readKittyConfig($)+ const schemes = ['dark', 'light', 'no-preference'] as const+ const found = await Promise.all(schemes.map(s => $.fs.exists(`${dir}/${kittyAutoFileOf(s)}`).catch(() => false)))+ let auto: { file: string; entries: KittyEntries } | null = null+ if (found.some(Boolean)) {+ let scheme: (typeof schemes)[number] | null = null+ if (S.hostOs === 'Linux') {+ const got = await $.process.run(['gsettings', 'get', 'org.gnome.desktop.interface', 'color-scheme'], { timeoutMs: HOST_CHECK_MS }).catch(() => null)+ scheme = got && got.exitCode === 0 ? kittySchemeOfGnome(got.stdout) : null+ } else scheme = (await readOsMode($).catch(() => null))?.mode ?? null+ if (scheme && found[schemes.indexOf(scheme)]) {+ const file = kittyAutoFileOf(scheme)+ auto = { file, entries: await kittyEntriesOf(`${dir}/${file}`, path => readText($, path), { home }) }+ }+ }+ const got = kittyBackgroundOf(entries, auto)+ const bg = hexColorOf(got.bg)+ return bg ? { mode: modeOfLuminance(luminanceOf(bg)), source: 'kitty', detail: got.detail } : null+}++// Rio's config folder and its config.toml's string values.+async function readRioConfig($: EngineInterface): Promise<{ dir: string; config: Record<string, string> }> {+ const dir = rioConfigDirOf({+ rioHome: (await $.env.get('RIO_CONFIG_HOME')) || undefined,+ xdgConfig: (await $.env.get('XDG_CONFIG_HOME')) || undefined,+ home: (await $.env.get('HOME')) ?? '',+ isMac: S.hostOs === 'Darwin',+ })+ return { dir, config: tomlStringsOf((await readText($, `${dir}/config.toml`)) ?? '') }+}++// The background of Rio's config. An `[adaptive-theme]` follows the OS+// unless `force-theme` is set: the OS is read only then.+async function readRioMode($: EngineInterface): Promise<HostMode | null> {+ if (!isRioHere()) return null+ const { dir, config } = await readRioConfig($)+ const themes: Record<string, string | null> = {}+ for (const name of rioThemeNamesOf(config)) themes[name] = await readText($, rioThemePath(dir, name))+ const adaptive = !!config['adaptive-theme.light'] && !!config['adaptive-theme.dark'] && !rioForcedOf(config)+ const appearance = adaptive ? ((await readOsMode($).catch(() => null))?.mode ?? null) : null+ const got = rioBackgroundOf(config, appearance, themes)+ const bg = hexColorOf(got.bg)+ return bg ? { mode: modeOfLuminance(luminanceOf(bg)), source: 'Rio', detail: got.detail } : null+}++// The OS appearance: macOS, or GNOME's colour scheme on Linux.+async function readOsMode($: EngineInterface): Promise<HostMode | null> {+ if (S.hostOs === 'Darwin') {+ const got = await $.process.run(['defaults', 'read', '-g', 'AppleInterfaceStyle'], { timeoutMs: HOST_CHECK_MS }).catch(() => null)+ return got ? { mode: modeOfMacAppearance(got.exitCode, got.stdout), source: 'macOS' } : null+ }+ if (S.hostOs === 'Linux') {+ const got = await $.process.run(['gsettings', 'get', 'org.gnome.desktop.interface', 'color-scheme'], { timeoutMs: HOST_CHECK_MS }).catch(() => null)+ const mode = got && got.exitCode === 0 ? modeOfGnome(got.stdout) : null+ if (mode) return { mode, source: 'GNOME' }+ }+ return null+}++// One read of the OS appearance (never two at once); a changed mode redraws.+export async function pollHost($: EngineInterface) {+ if (S.checking || S.setting !== 'auto') return+ S.checking = true+ try {+ S.host = (await readHostMode($).catch(() => null)) ?? S.host+ } finally {+ S.checking = false+ }+ showMode($)+}++// Draws in the mode the setting and the OS give, when it changed.+export function showMode($: EngineInterface) {+ const next = resolveMode(S.setting, S.host)+ if (next === S.theme) return+ S.theme = next+ refresh($)+}++// Polls the OS appearance while the setting is auto, and only then.+export function watchHost($: EngineInterface) {+ if (S.setting === 'auto' && !S.watch) {+ try {+ S.watch = $.clock.every(HOST_POLL_MS, () => void pollHost($).catch(() => undefined))+ } catch {+ S.watch = null+ }+ } else if (S.setting !== 'auto' && S.watch) {+ S.watch.cancel()+ S.watch = null+ }+}diff --git a/hooks/lib/images.ts b/hooks/lib/images.tsnew file mode 100644index 0000000..ae148b3--- /dev/null+++ b/hooks/lib/images.ts@@ -0,0 +1,60 @@+// Pictures under rows (pure): which images a SendUserFile result or a prompt+// names, where Claude Code keeps pasted images, and the cells a picture takes.+// The drawing on the host is in pictures.tsx.+import type { Cell } from './state'+import { MAX_IMAGE_ROWS, PICTURE_MAX_ROWS, PICTURE_MIN_ROWS } from './settings'++// The most rows a picture under a row takes: half the viewport, within+// PICTURE_MIN_ROWS to PICTURE_MAX_ROWS.+export function pictureRowsFor(viewportRows: number | undefined): number {+ return Math.max(PICTURE_MIN_ROWS, Math.min(PICTURE_MAX_ROWS, Math.floor((viewportRows ?? 2 * PICTURE_MAX_ROWS) / 2)))+}++// 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 } {+ const scale = Math.min(1, (columns * px.width) / size.width, (rows * px.height) / size.height)+ return {+ columns: Math.max(1, Math.min(MAX_IMAGE_ROWS, columns, Math.round((size.width * scale) / px.width))),+ rows: Math.max(1, Math.min(MAX_IMAGE_ROWS, rows, Math.round((size.height * scale) / px.height))),+ }+}++// The image paths of a SendUserFile result that can be PNGs (the engine's+// Image draws PNG only; the header read tells for sure).+export function sentImages(output: unknown): string[] {+ const list = output && typeof output === 'object' ? (output as { attachments?: unknown }).attachments : undefined+ if (!Array.isArray(list)) return []+ return list+ .filter((a): a is { path: string; isImage: true; media_type?: unknown } =>+ !!a && typeof a === 'object' && a.isImage === true && typeof a.path === 'string' && a.path !== '')+ .filter(a => typeof a.media_type !== 'string' || /^image\/png$/i.test(a.media_type))+ .map(a => a.path)+}++// The numbers of the `[Image #N]` marks in a prompt, each once, in order.+export function pastedNumbers(text: string): number[] {+ const found: number[] = []+ for (const m of text.matchAll(/\[Image #(\d+)\]/g)) {+ const n = Number(m[1])+ if (n > 0 && !found.includes(n)) found.push(n)+ }+ return found+}++// Claude Code's folder name for a project: every character but a letter or a+// digit is `-` (/Users/me/app → -Users-me-app).+export const projectSlug = (dir: string) => dir.replace(/[^A-Za-z0-9]/g, '-')++// Claude Code's temp folder of this user: <CLAUDE_CODE_TMPDIR or /tmp>/claude-<uid>+// (/tmp is /private/tmp on macOS); '' when the uid is not known.+export function claudeTmpOf(o: { tmpdir?: string; uid: string; isMac: boolean }): string {+ const uid = o.uid.trim()+ if (!/^\d+$/.test(uid)) return ''+ const base = (o.tmpdir?.trim() || (o.isMac ? '/private/tmp' : '/tmp')).replace(/\/+$/, '')+ return `${base}/claude-${uid}`+}++// Where Claude Code keeps the images pasted in a session, and image N there.+export const pasteDirOf = (claudeTmp: string, cwd: string, sessionId: string) => `${claudeTmp}/${projectSlug(cwd)}/${sessionId}/images`+export const pastedImagePath = (dir: string, n: number) => `${dir}/${n}.png`diff --git a/hooks/lib/markdown.ts b/hooks/lib/markdown.tsnew file mode 100644index 0000000..2e7cc46--- /dev/null+++ b/hooks/lib/markdown.ts@@ -0,0 +1,155 @@+// Markdown as md-preview reads it: blocks, fences, the segments an answer is+// cut into, the images it names, and a plain text of it for an Image's alt.+import { ALT_CHARS, SEGMENT_ROWS } from './settings'++export const FENCE = /^( {0,3})(`{3,}|~{3,})\s*([^\s`]*)/+export const isTypstInfo = (info: string) => /^(typst|typ)$/i.test(info)++// One block of Markdown: lines between blank lines outside fences, or one+// fenced block that starts at the margin.+export type Block = { lines: string[]; fence?: { mark: string; info: string }; isMath?: boolean }++export function blocksOf(md: string): Block[] {+ const blocks: Block[] = []+ let cur: Block | null = null+ let open: { char: string; len: number } | null = null+ let inMath = false+ const close = () => {+ if (cur && cur.lines.length) blocks.push(cur)+ cur = null+ }+ for (const line of md.replace(/\r\n?/g, '\n').split('\n')) {+ if (open) {+ cur!.lines.push(line)+ const m = FENCE.exec(line)+ if (m && m[2]![0] === open.char && m[2]!.length >= open.len && line.trim() === m[2]) {+ open = null+ if (cur!.fence) close()+ }+ continue+ }+ if (inMath) {+ cur!.lines.push(line)+ if (line.trim() === '$$') inMath = false+ continue+ }+ const m = FENCE.exec(line)+ if (m) {+ open = { char: m[2]![0]!, len: m[2]!.length }+ // A fence at the margin is a block of its own; an indented one (in a+ // list item) stays with the item.+ if (m[1] === '') {+ close()+ cur = { lines: [line], fence: { mark: m[2]!, info: m[3] ?? '' } }+ } else (cur ??= { lines: [] }).lines.push(line)+ continue+ }+ if (line.trim() === '') {+ close()+ continue+ }+ ;(cur ??= { lines: [] }).lines.push(line)+ if (line.trim() === '$$') {+ inMath = true+ cur.isMath = true+ }+ }+ close()+ return blocks+}++// A rough count of the rows a block takes once drawn `columns` wide.+export function rowsOfBlock(block: Block, columns: number): number {+ const isCode = !!block.fence+ const perRow = columns * (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+ }+ if (block.fence && isTypstInfo(block.fence.info)) rows += 20+ return rows+}++const LINK_DEF = /^ {0,3}\[(?!\^)[^\]]+\]:\s*\S/+const FOOTNOTE_DEF = /^ {0,3}\[\^[^\]]+\]:/++// Splits an answer into segments of about `budget` rows at block boundaries.+// A fence is never split, but a long plain code fence is cut into several+// 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[] {+ const blocks = blocksOf(md)+ if (!blocks.length) return []+ const outside = blocks.filter(b => !b.fence).flatMap(b => b.lines)+ if (outside.some(line => FOOTNOTE_DEF.test(line))) return [md]+ const defs = outside.filter(line => LINK_DEF.test(line))++ const pieces: Block[] = []+ for (const block of blocks) {+ const { fence } = block+ if (fence && !isTypstInfo(fence.info) && rowsOfBlock(block, columns) > 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)+ for (let i = 0; i < body.length; i += per) {+ pieces.push({ lines: [block.lines[0]!, ...body.slice(i, i + per), fence.mark], fence })+ }+ } else pieces.push(block)+ }++ const segments: Block[][] = [[]]+ let used = 0+ for (const piece of pieces) {+ const need = rowsOfBlock(piece, columns)+ const canCut = !/^\s/.test(piece.lines[0] ?? '')+ if (used + need > budget && segments.at(-1)!.length && canCut) {+ segments.push([])+ used = 0+ }+ segments.at(-1)!.push(piece)+ used += need+ }+ const texts = segments.map(seg => seg.map(b => b.lines.join('\n')).join('\n\n'))+ if (texts.length < 2 || !defs.length) return texts+ return texts.map(t => `${t}\n\n${defs.filter(d => !t.includes(d)).join('\n')}`.trimEnd())+}++// The local image paths Markdown names outside code fences.+const IMAGE = /!\[([^\]]*)\]\(\s*<?([^)\s>]+)>?(?:\s+"[^"]*")?\s*\)/g++export function localImages(md: string): string[] {+ const found: string[] = []+ let open: { char: string; len: number } | null = null+ for (const line of md.split('\n')) {+ const m = FENCE.exec(line)+ if (open) {+ if (m && m[2]![0] === open.char && m[2]!.length >= open.len && line.trim() === m[2]) open = null+ } else if (m) open = { char: m[2]![0]!, len: m[2]!.length }+ else for (const ref of line.matchAll(IMAGE)) if (!/^[a-z][a-z0-9+.-]*:/i.test(ref[2]!) || /^file:/i.test(ref[2]!)) found.push(ref[2]!)+ }+ return found+}++// Where an image path leads, as the template resolves it: `file://` dropped,+// `%20` a space, a relative path joined to `base`.+export function imagePathOf(path: string, base: string): string {+ const plain = path.trim().replace(/^file:\/\//i, '').replace(/%20/g, ' ')+ return plain.startsWith('/') ? plain : `${base.replace(/\/+$/, '')}/${plain.replace(/^\.\//, '')}`+}++// A short one-line plain text of some Markdown, for an Image's alt.+export function plainOf(md: string, max = ALT_CHARS): string {+ const flat = md+ .replace(/^ {0,3}(`{3,}|~{3,}).*$/gm, ' ')+ .replace(/!\[([^\]]*)\]\([^)]*\)/g, '$1')+ .replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')+ .replace(/<[^>]+>/g, ' ')+ .replace(/^\s{0,3}(#{1,6}|>+|[-*+]|\d+[.)])\s+/gm, '')+ .replace(/[*_`~|]+/g, '')+ .replace(/\s+/g, ' ')+ .trim()+ return flat.length > max ? `${flat.slice(0, max - 1).trimEnd()}…` : flat || ' '+}++export const firstLine = (text: string) => text.split('\n').find(l => l.trim())?.trim() ?? ''diff --git a/hooks/lib/mode.ts b/hooks/lib/mode.tsnew file mode 100644index 0000000..eb55738--- /dev/null+++ b/hooks/lib/mode.ts@@ -0,0 +1,82 @@+// Light or dark: Claude Code's theme setting, the OS appearance, COLORFGBG,+// a colour's luminance and the terminal's OSC 11 answer (pure; the reads on+// the host are in host.ts).+import type { MdPreviewTheme } from '../../types'++export function themeOf(value: unknown): MdPreviewTheme {+ return typeof value === 'string' && /light/i.test(value) ? 'light' : 'dark'+}++// Claude Code's theme setting: dark, light, dark-daltonized, light-ansi, …+// are fixed; `auto`, or any other text, follows the OS. No value is Claude+// Code's default, dark.+export type ThemeSetting = MdPreviewTheme | 'auto'+export function settingOf(value: unknown): ThemeSetting {+ if (typeof value !== 'string' || !value.trim()) return 'dark'+ if (/light/i.test(value)) return 'light'+ if (/dark/i.test(value)) return 'dark'+ return 'auto'+}++// The OS appearance, and where it was read.+export type HostMode = { mode: MdPreviewTheme; source: 'terminal' | 'iTerm2' | 'Ghostty' | 'cmux' | 'kitty' | 'Rio' | 'macOS' | 'GNOME' | 'COLORFGBG'; detail?: string }++// `defaults read -g AppleInterfaceStyle`: "Dark" in dark mode; in light mode+// the key does not exist and the command fails.+export function modeOfMacAppearance(exitCode: number, stdout: string): MdPreviewTheme {+ return exitCode === 0 && /^\s*dark\s*$/i.test(stdout) ? 'dark' : 'light'+}++// `gsettings get org.gnome.desktop.interface color-scheme`: 'prefer-dark',+// 'prefer-light' or 'default'; null for anything else.+export function modeOfGnome(stdout: string): MdPreviewTheme | null {+ const v = stdout.trim().replace(/^'|'$/g, '')+ if (v === 'prefer-dark') return 'dark'+ if (v === 'prefer-light' || v === 'default') return 'light'+ return null+}++// COLORFGBG, "fg;bg" or "fg;x;bg": the last field is the background colour+// index. 0-6 and 8 are dark, 7 and 15 light; anything else is not known.+export function modeOfColorFgBg(value: string | undefined): MdPreviewTheme | null {+ const last = (value ?? '').split(';').pop()?.trim() ?? ''+ if (!/^\d+$/.test(last)) return null+ const bg = Number(last)+ if ((bg >= 0 && bg <= 6) || bg === 8) return 'dark'+ if (bg === 7 || bg === 15) return 'light'+ return null+}++// The mode to draw: a fixed setting as set; auto as the OS is, dark when it+// was never read.+export function resolveMode(setting: ThemeSetting, seen: HostMode | null): MdPreviewTheme {+ return setting === 'auto' ? (seen?.mode ?? 'dark') : setting+}++// What the status line says about the mode.+export function modeLine(mode: MdPreviewTheme, setting: ThemeSetting, raw: string, seen: HostMode | null): string {+ if (setting !== 'auto') return `mode ${mode} (Claude Code theme ${raw || mode})`+ return `mode ${mode} (auto, ${seen ? `from ${seen.source}${seen.detail ? `: ${seen.detail}` : ''}` : 'OS appearance not known, dark assumed'})`+}++export type Rgb = { r: number; g: number; b: number }+// Relative luminance of an sRGB colour (components 0..1).+export function luminanceOf(c: Rgb): number {+ const lin = (v: number) => (v <= 0.04045 ? v / 12.92 : ((v + 0.055) / 1.055) ** 2.4)+ return 0.2126 * lin(c.r) + 0.7152 * lin(c.g) + 0.0722 * lin(c.b)+}+export const modeOfLuminance = (l: number): MdPreviewTheme => (l > 0.4 ? 'light' : 'dark')++// A terminal's answer to OSC 11 (`ESC ] 11 ; ?`), the query Claude Code+// itself sends: `ESC ] 11 ; rgb:R/G/B` with 1-4 hex digits per channel,+// ended by BEL or ST (`ESC \`). The colour in 0..1, or null.+export function parseOsc11(text: string): Rgb | null {+ const m = /\x1b\]11;rgba?:([0-9a-f]{1,4})\/([0-9a-f]{1,4})\/([0-9a-f]{1,4})(?:\/[0-9a-f]{1,4})?(?:\x07|\x1b\\)/i.exec(text)+ if (!m) return null+ const part = (h: string) => parseInt(h, 16) / (16 ** h.length - 1)+ return { r: part(m[1]!), g: part(m[2]!), b: part(m[3]!) }+}++// Control characters shown as text (\e, \a, \xNN), for /md-preview probe.+export const escapeControls = (text: string) =>+ text.replace(/[\x00-\x1f\x7f]/g, c => (c === '\x1b' ? '\\e' : c === '\x07' ? '\\a' : `\\x${c.charCodeAt(0).toString(16).padStart(2, '0')}`))diff --git a/hooks/lib/pictures.tsx b/hooks/lib/pictures.tsxnew file mode 100644index 0000000..14b9cc0--- /dev/null+++ b/hooks/lib/pictures.tsx@@ -0,0 +1,112 @@+// Pictures under rows: the PNGs Claude sends (SendUserFile) and the images+// the user pastes are drawn under their row, at their own size or smaller.+// The pure parts are in images.ts.+import type { EngineInterface, ImageSource, RenderElement, RenderInput } from 'claude-code'++import { DEFAULT_CELL, GUTTER, PICTURES_KEPT } from './settings'+import { INLINE_KEPT, inlined, pasteDirs, pictures, S, type Env } from './state'+import { columnsFor, fitsInline, INLINE_MAX_BYTES } from './terminal'+import { pasteDirOf, pictureCells, pictureRowsFor } from './images'+import { hashOf } from './draw'+import { parseOd, pngSize } from './typst'+import { HEADERS_SH } from './host'++export type Picture = { file: string; stamp: string; bytes: number; width: number; height: number }+export type Shown = { source: ImageSource; columns: number; rows: number; alt: string }+export type RowInput = RenderInput<'ToolResult' | 'UserMessage', 'terminal'>++// 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)+ if (!st || st.kind !== 'file') return null+ const stamp = `${st.mtimeMs}:${st.size}`+ let kept = pictures.get(file)+ if (kept?.stamp !== stamp) {+ const head = await $.process.run(['sh', '-c', HEADERS_SH, 'sh', file]).catch(() => null)+ if (!head || head.exitCode !== 0) return null+ kept = { stamp, size: pngSize(parseOd(head.stdout)[0] ?? []) }+ pictures.delete(file)+ pictures.set(file, kept)+ for (const old of pictures.keys()) {+ if (pictures.size <= PICTURES_KEPT) break+ pictures.delete(old)+ }+ }+ return kept.size ? { file, stamp, bytes: st.size, ...kept.size } : null+}++// Over ssh: the PNG as base64, read once per stat; null when it is too large+// for a `{ png }` source.+export async function pictureBytes($: EngineInterface, p: Picture): Promise<string | null> {+ if (!fitsInline(p) || p.bytes > INLINE_MAX_BYTES) return null+ const key = `${p.file}@${p.stamp}`+ if (inlined.has(key)) return inlined.get(key) ?? null+ const got = await $.fs.read(p.file, { as: 'bytes' }).catch(() => null)+ if (!got) return null+ const base64 = fitsInline(p, got.base64) ? got.base64 : null+ inlined.set(key, base64)+ for (const old of inlined.keys()) {+ if (inlined.size <= INLINE_KEPT) break+ inlined.delete(old)+ }+ 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[]> {+ const columns = columnsFor(e.viewport?.columns)+ const rows = pictureRowsFor(e.viewport?.rows)+ const px = S.cell ?? DEFAULT_CELL+ const shown: Shown[] = []+ for (const file of new Set(files)) {+ const p = await pictureOf($, file)+ if (!p) continue+ const fit = pictureCells(p, columns, rows, px)+ const alt = file.split('/').pop() || 'image'+ if (ready.inline) {+ const png = await pictureBytes($, p)+ if (png) shown.push({ source: { png }, ...fit, alt })+ continue+ }+ const generation = Number.parseInt(hashOf([p.stamp, fit.columns, fit.rows]).slice(0, 8), 16)+ shown.push({ source: { file, format: 'png', generation }, ...fit, alt })+ }+ return shown+}++// The engine's row, then the pictures under it.+export function underRow($: EngineInterface, e: RowInput, row: RenderElement, shown: readonly Shown[]) {+ const { Box, Image } = $.ui.resolve(e)+ return (+ <Box flexDirection="column">+ {row}+ <Box flexDirection="column" marginLeft={GUTTER}>+ {shown.map((s, i) => <Image key={`picture-${i}`} source={s.source} columns={s.columns} rows={s.rows} alt={s.alt} />)}+ </Box>+ </Box>+ )+}++// The folder of the images pasted in this session: by the session's cwd or+// root, else the one folder under claudeTmp that holds the session (a long+// cwd's folder name is cut). Kept once found; '' while there is none.+export async function pasteDir($: EngineInterface, ready: Env): Promise<string> {+ if (!ready.claudeTmp) return ''+ const id = await $.session.id()+ const kept = pasteDirs.get(id)+ if (kept) return kept+ const found = async (dirs: Iterable<string>) => {+ for (const dir of dirs) {+ if (!(await $.fs.exists(dir).catch(() => false))) continue+ pasteDirs.set(id, dir)+ return dir+ }+ return ''+ }+ const root = await $.session.root().catch(() => ready.cwd)+ const named = await found(new Set([ready.cwd, root].map(dir => pasteDirOf(ready.claudeTmp, dir, id))))+ if (named) return named+ const projects = (await $.fs.list(ready.claudeTmp).catch(() => [])).filter(f => f.kind === 'dir')+ return found(projects.map(f => `${ready.claudeTmp}/${f.name}/${id}/images`))+}diff --git a/hooks/lib/plan.tsx b/hooks/lib/plan.tsxnew file mode 100644index 0000000..462baf7--- /dev/null+++ b/hooks/lib/plan.tsx@@ -0,0 +1,300 @@+// The plan of plan mode: md-preview's own approval flow for the main loop's+// ExitPlanMode, and the plan drawn as pictures in its transcript row.+//+// The engine's approval dialog cannot be drawn by a plugin, so md-preview asks+// first: the `tool.call` hook on ExitPlanMode asks its own question (decidePlan)+// before the engine raises PermissionRequest, and keeps the verdict. The+// PermissionRequest hook then answers with it at once (decisionOf), so the+// 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 { GUTTER, bulletOf } from './settings'+import { S, writesLive } from './state'+import { firstLine } from './markdown'+import type { Drawing } from './answer'+import { drawPages } from './draw'++// The question's chip and its two wordings.+export const PLAN_HEADER = 'Plan'+export const PLAN_QUESTION = 'Approve this plan?'+export const PLAN_QUESTION_EDITED = 'Approve the edited plan?'+// The options, in order (4 is the most the dialog takes).+export const PLAN_AUTO = 'Yes, auto-accept edits'+export const PLAN_MANUAL = 'Yes, manually approve edits'+export const PLAN_CLEAR = 'Yes, clear context + auto-accept'+export const PLAN_EDIT = 'Edit the plan'+// The line above md-preview's question (the dialog takes 12 rows at most+// around it, so the plan itself is in the ToolUse row above).+export const PLAN_ASK_LINE = 'md-preview: the rendered plan is above'+// The line in the ToolUse row while the plan's pictures compile.+export const PLAN_DRAWING = 'md-preview: drawing the plan...'+// What the model reads when the person rejects the plan (Esc) or types changes.+export const PLAN_REJECTED = 'The user rejected the plan.'+export const PLAN_FEEDBACK = 'The user wants changes to the plan:'+// The prompt that starts the new context of "clear context".+export const PLAN_IMPLEMENT = 'Implement this plan:'+// How long an editor may keep the plan file open (10 minutes, process.run's most).+export const EDIT_TIMEOUT_MS = 600000+// How long the plan waits for a Write or Edit of its file still running.+export const PLAN_WRITE_WAIT_MS = 5000+export const PLAN_WRITE_POLL_MS = 25+// The delay before "clear context" acts: `$.command.run` rejects inside a hook+// the turn waits on, so it runs detached once the call has resolved.+export const CLEAR_DELAY_MS = 50++// ---- Pure helpers -------------------------------------------------------------++// A path with `.`, `..` and repeated `/` resolved (no file system call).+export function normalPath(path: string): string {+ const isAbsolute = path.startsWith('/')+ const parts: string[] = []+ for (const part of path.split('/')) {+ if (part === '' || part === '.') continue+ if (part === '..') {+ if (parts.length && parts.at(-1) !== '..') parts.pop()+ else if (!isAbsolute) parts.push('..')+ continue+ }+ parts.push(part)+ }+ return (isAbsolute ? '/' : '') + parts.join('/')+}++// The plan an ExitPlanMode result shows, or null: none, an empty one, a+// subagent's or a teammate's (sent to its lead, not approved here).+export function planOf(output: unknown): string | null {+ if (!output || typeof output !== 'object') return null+ const o = output as { plan?: unknown; isAgent?: unknown; awaitingLeaderApproval?: unknown }+ if (o.isAgent === true || o.awaitingLeaderApproval === true) return null+ return typeof o.plan === 'string' && o.plan.trim() ? o.plan : null+}++// The plan an ExitPlanMode call carries (the engine adds it to the call, and+// to the row's input, before it asks), or '' when there is none.+export function planInputOf(input: unknown): string {+ const plan = input && typeof input === 'object' ? (input as { plan?: unknown }).plan : undefined+ return typeof plan === 'string' && plan.trim() ? plan : ''+}++// The plan file an ExitPlanMode call names, or ''.+export function planFileOf(input: unknown): string {+ const file = input && typeof input === 'object' ? (input as { planFilePath?: unknown }).planFilePath : undefined+ return typeof file === 'string' && file.startsWith('/') ? file : ''+}++// The plan a row of the call shows: the text edited in md-preview's flow, else+// the result's, else the call's; '' for none and for a subagent's or a+// teammate's result.+export function planShownOf(edited: string | undefined, output: unknown, input: unknown): string {+ if (edited?.trim()) return edited+ if (output && typeof output === 'object') {+ const o = output as { isAgent?: unknown; awaitingLeaderApproval?: unknown }+ if (o.isAgent === true || o.awaitingLeaderApproval === true) return ''+ }+ return planOf(output) ?? planInputOf(input)+}++// A path as the person reads it: `~/...` under the home folder.+export function shortPath(path: string, home: string): string {+ const h = normalPath(home)+ return home && h !== '/' && path.startsWith(`${h}/`) ? `~${path.slice(h.length)}` : path+}++// The question's options: the edit option only when an editor can open the file.+export const planOptions = (canEdit: boolean): string[] => [PLAN_AUTO, PLAN_MANUAL, PLAN_CLEAR, ...(canEdit ? [PLAN_EDIT] : [])]++// What an answer means. Any other answer (the dialog's "Type something",+// "Chat about this") is the person's words about the plan.+export type PlanChoice = { kind: 'auto' | 'manual' | 'clear' | 'edit' } | { kind: 'feedback'; text: string }+export function choiceOf(answer: string, canEdit: boolean): PlanChoice {+ if (answer === PLAN_AUTO) return { kind: 'auto' }+ if (answer === PLAN_MANUAL) return { kind: 'manual' }+ if (answer === PLAN_CLEAR) return { kind: 'clear' }+ if (answer === PLAN_EDIT && canEdit) return { kind: 'edit' }+ return { kind: 'feedback', text: answer.trim() }+}++// The deny reason the model reads for the person's words: it stays in plan+// mode and revises.+export const feedbackOf = (text: string) => (text ? `${PLAN_FEEDBACK} ${text}` : `${PLAN_FEEDBACK.slice(0, -1)}.`)++// The verdict md-preview's question gave, kept for the PermissionRequest that+// follows: approve (in a mode, with the plan, edited or not; `clear` starts a+// new context once the call resolves), or reject and stop the turn (Esc).+export type PlanVerdict =+ | { kind: 'allow'; mode: 'acceptEdits' | 'default'; plan: string; isEdited: boolean; clear: boolean }+ | { kind: 'deny'; message: string }++export function verdictOf(choice: PlanChoice, plan: string, isEdited: boolean): PlanVerdict | null {+ if (choice.kind === 'auto' || choice.kind === 'clear') return { kind: 'allow', mode: 'acceptEdits', plan, isEdited, clear: choice.kind === 'clear' }+ if (choice.kind === 'manual') return { kind: 'allow', mode: 'default', plan, isEdited, clear: false }+ return null+}++// The PermissionRequest decision of a verdict. An allow carries the input+// (the engine honours an allow of this tool only with `updatedInput`), the+// edited plan in it, and the mode that ends plan mode.+export function decisionOf(verdict: PlanVerdict, toolInput: unknown): PermissionRequestDecision {+ if (verdict.kind === 'deny') return { behavior: 'deny', message: verdict.message, interrupt: true }+ const input = toolInput && typeof toolInput === 'object' ? { ...(toolInput as Record<string, unknown>) } : {}+ if (verdict.isEdited) input.plan = verdict.plan+ return { behavior: 'allow', updatedInput: input, updatedPermissions: [{ type: 'setMode', mode: verdict.mode, destination: 'session' }] }+}++// The editor that opens the plan file and waits until it is closed: VS Code+// (`code --wait`) when it is on the PATH, else TextEdit on a Mac (`open -W`+// waits until TextEdit quits). Not over ssh, where TextEdit is the remote+// computer's. A mod has no terminal, so no terminal editor.+export function editorArgv(o: { code: string; isMac: boolean; isRemote: boolean }, file: string): string[] | null {+ if (o.code) return [o.code, '--wait', file]+ if (o.isMac && !o.isRemote) return ['open', '-W', '-t', file]+ return null+}++// ---- The flow -----------------------------------------------------------------++// The `code` command's path ('' when none), looked up once per load.+async function findCode($: EngineInterface): Promise<string> {+ if (S.planCode !== null) return S.planCode+ let found = ''+ for (const flag of ['-lc', '-c']) {+ const got = await $.process.run(['sh', flag, 'command -v code'], { timeoutMs: 5000 }).catch(() => null)+ const path = got?.exitCode === 0 ? firstLine(got.stdout) : ''+ if (path.startsWith('/')) {+ found = path+ break+ }+ }+ S.planCode = found+ return found+}++// What md-preview's question decided: a verdict for the PermissionRequest, or+// the person's words (a deny of the call: Claude revises the plan).+export type PlanOutcome = { kind: 'verdict'; verdict: PlanVerdict } | { kind: 'feedback'; message: string }++// Asks md-preview's question about the plan, as often as the person edits it.+// `plan` is the text to ask about, `callPlan` the one the call carried (an+// approval sends `plan` when they differ). `onEdited` gets each edited text+// (the ToolUse row draws it). Esc (the ask rejects; in a terminal session+// that is a dismissal) rejects the plan.+export async function decidePlan(+ $: EngineInterface,+ o: { plan: string; callPlan: string; file: string; isMac: boolean; isRemote: boolean; onEdited: (plan: string) => void },+): Promise<PlanOutcome> {+ const argv = o.file ? editorArgv({ code: await findCode($), isMac: o.isMac, isRemote: o.isRemote }, o.file) : null+ const canEdit = !!argv+ let plan = o.plan+ let isEdited = false+ for (;;) {+ const question = isEdited ? PLAN_QUESTION_EDITED : PLAN_QUESTION+ let answer: string+ S.planAsking = question+ try {+ answer = await $.ui.ask(question, { header: PLAN_HEADER, options: planOptions(canEdit) })+ } catch {+ return { kind: 'verdict', verdict: { kind: 'deny', message: PLAN_REJECTED } }+ } finally {+ S.planAsking = ''+ }+ const choice = choiceOf(answer, canEdit)+ if (choice.kind === 'feedback') return { kind: 'feedback', message: feedbackOf(choice.text) }+ if (choice.kind !== 'edit') return { kind: 'verdict', verdict: verdictOf(choice, plan, plan !== o.callPlan)! }+ await $.process.run(argv!, { timeoutMs: EDIT_TIMEOUT_MS }).catch(() => null)+ const text = await $.fs.read(o.file).catch(() => null)+ if (typeof text === 'string' && text.trim() && text !== plan) {+ plan = text+ isEdited = text !== o.plan+ o.onEdited(plan)+ }+ }+}++// The plan file's text once no Write or Edit of it is still running (at most+// PLAN_WRITE_WAIT_MS): Claude may write the plan and call ExitPlanMode in one+// message, and the call then carries the file as it was before the write.+// `fallback` when the file can't be read.+export async function currentPlan($: EngineInterface, file: string, fallback: string): Promise<string> {+ if (!file) return fallback+ for (let waited = 0; (writesLive.get(file) ?? 0) > 0 && waited < PLAN_WRITE_WAIT_MS; waited += PLAN_WRITE_POLL_MS) {+ await new Promise<void>(resolve => $.clock.after(PLAN_WRITE_POLL_MS, resolve))+ }+ const text = await $.fs.read(file).catch(() => null)+ return typeof text === 'string' && text.trim() ? text : fallback+}++// "Clear context": once the approved call has resolved, ends the turn, runs+// /clear and sends the plan as the new context's first prompt. Detached, as+// `$.command.run` rejects inside a hook the turn waits on.+export function scheduleClear($: EngineInterface, plan: string, turnId: string) {+ $.clock.after(CLEAR_DELAY_MS, async () => {+ if (turnId) await $.turn.abort({ turnId }).catch(() => undefined)+ await $.command.run({ command: 'clear' }).catch(() => undefined)+ await $.prompt.submit({ text: `${PLAN_IMPLEMENT}\n\n${plan}`, asUser: true }).catch(() => undefined)+ })+}++// ---- Drawing ------------------------------------------------------------------++type Terminal = ResolveInput<RenderComponent, 'terminal'>++// 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 {+ 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 })+ ) : (+ <Box marginTop={1} marginLeft={GUTTER}>+ <Text dimColor>{PLAN_DRAWING}</Text>+ </Box>+ )}+ </Box>+ )+}++// The approved plan's result row without the plan (the ToolUse row above+// draws it): the engine's header and the plan file's path.+export function drawPlanResult($: EngineInterface, e: Terminal, filePath?: string): RenderElement {+ const { Box, Text } = $.ui.resolve(e)+ const saved = filePath ? shortPath(filePath, S.env?.home ?? '') : ''+ return (+ <Box flexDirection="column" marginTop={1}>+ <Box flexDirection="row">+ <Box width={GUTTER} flexShrink={0}>+ <Text>{bulletOf(S.env?.isMac ?? true)}</Text>+ </Box>+ <Text>User approved Claude's plan</Text>+ </Box>+ {saved ? (+ <Box marginLeft={GUTTER}>+ <Text dimColor wrap="truncate-end">{`Plan saved to: ${saved} · /plan to edit`}</Text>+ </Box>+ ) : null}+ </Box>+ )+}++// The line md-preview adds above its own question.+export function drawAskLine($: EngineInterface, e: ResolveInput<'AskUserQuestion', 'terminal'>, dialog: RenderElement): RenderElement {+ const { Box, Text } = $.ui.resolve(e)+ return (+ <Box flexDirection="column">+ <Text dimColor wrap="truncate-end">{PLAN_ASK_LINE}</Text>+ {dialog}+ </Box>+ )+}++// Whether an AskUserQuestion dialog is md-preview's plan question now asked.+export function isPlanQuestion(questions: unknown, asking: string): boolean {+ if (!asking || !Array.isArray(questions) || questions.length !== 1) return false+ const q = questions[0] as { question?: unknown; header?: unknown } | null+ return !!q && q.question === asking && q.header === PLAN_HEADER+}diff --git a/hooks/lib/settings.ts b/hooks/lib/settings.tsnew file mode 100644index 0000000..690e75c--- /dev/null+++ b/hooks/lib/settings.ts@@ -0,0 +1,78 @@+// md-preview's settings: sizes, limits, timings and the text it adds to+// Claude's system prompt.+import type { Cell } from './state'++// ---- Settings -------------------------------------------------------------++// The widest picture, in terminal columns.+export const MAX_COLUMNS = 120+// The bullet column to the left of an answer.+export const GUTTER = 2+// Claude Code's own reply bullet: ⏺ on macOS, ● elsewhere.+export const bulletOf = (isMac: boolean) => (isMac ? '⏺' : '●')+// The engine's answer row has a blank row above it; ours keeps it.+export const MARGIN_TOP = 1+// The template's body text size in pt; the page width is chosen so that this+// text looks as big as the terminal's own (see fontFit).+export const BODY_PT = 11+// `/md-preview size`: a percent on top of that match.+export const DEFAULT_SIZE = 100+export const MIN_SIZE = 80+export const MAX_SIZE = 200+// A block whose text changes outside a model request we saw (a hot reload+// mid-stream) is final once its text has been still this long.+export const SETTLE_MS = 400+// Inside a request, a block whose text has been still this long is final+// too (a stalled stream never keeps it hidden).+export const LIVE_STILL_MS = 2000+// How long a final block that is not drawn yet stays blank before its text+// shows: after it streamed, and when it was never live (a resumed transcript).+export const BLANK_AFTER_LIVE_MS = 2000+export const BLANK_RESUMED_MS = 1000+export const MAX_RUNNING = 2+// A segment is cut to be about this many rows; an Image is 255 rows at most.+export const SEGMENT_ROWS = 160+export const MAX_IMAGE_ROWS = 255+// The cell in device pixels when the tty reports none (tmux, a relay): an+// 8 x 16 point cell at Retina scale 2. A reported cell outside 4 to 64 px+// 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'+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.+export const TYPST_FALLBACKS = ['/opt/homebrew/bin/typst', '/usr/local/bin/typst', '/usr/bin/typst', '/snap/bin/typst', '~/.cargo/bin/typst', '~/.local/bin/typst']+export const NO_TYPST = 'md-preview: install Typst (brew install typst) to see rendered answers'+// Typst downloads a package it doesn't find under --package-path; a proxy+// nobody listens on makes that fail at once, so a live block never fetches.+export const NO_NETWORK = 'http://127.0.0.1:9'+// With Claude Code's theme on auto: how often the OS appearance is read, and+// how long one read may take.+export const HOST_POLL_MS = 3000+export const HOST_CHECK_MS = 2000+// The base every theme merges over (its theme.json and syntax files).+export const BASE_THEME = 'vscode'+// The theme used when none is chosen, or when the chosen one is not usable.+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.+export const PICTURE_MAX_ROWS = 24+export const PICTURE_MIN_ROWS = 6+export const PICTURES_KEPT = 64++// What Claude is told while the mod draws its answers (a system prompt+// section, added last).+export const TYPST_PROMPT = `Your replies in this terminal are drawn as rendered Markdown pictures (VS Code preview look), so use Markdown freely: headings, tables, task lists, code blocks, $math$ (LaTeX), images by absolute path.+For anything Markdown can't show well — diagrams, flow charts, plots, coloured tables, complex layouts or math — write a fenced \`\`\`typst block: it is rendered live with Typst 0.15 (full Typst markup; begin code lines with #).+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.+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/setup.ts b/hooks/lib/setup.tsnew file mode 100644index 0000000..b0a9f28--- /dev/null+++ b/hooks/lib/setup.ts@@ -0,0 +1,109 @@+// iTerm2 setup: the marked block /md-preview setup adds to (or removes from)+// the shell's start file, and the question asked once per load.+import type { EngineInterface } from 'claude-code'++import { S } from './state'+import { readText } from './host'++// Claude Code turns pictures on by itself in kitty and Ghostty only; iTerm2+// needs CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1 when Claude Code starts (a mod's+// $.env.set comes after its terminal check, too late). So the setup adds a+// marked block to the shell's start file that sets it in iTerm2 alone, not in+// tmux or screen (Claude Code cannot draw there).+export const SETUP_START = '# >>> md-preview: Claude Code pictures in iTerm2 >>>'+export const SETUP_END = '# <<< md-preview <<<'+export type ShellRc = { path: string; kind: 'sh' | 'fish' }+// The start file the setup writes for the login shell (`SHELL`); null for a+// shell it does not know. iTerm2 starts login shells: bash reads+// .bash_profile on macOS. fish gets a file of its own in conf.d.+export function shellRcOf(o: { shell: string; home: string; zdotdir?: string; xdgConfig?: string; isMac: boolean }): ShellRc | null {+ const name = o.shell.split('/').pop() ?? ''+ if (name === 'zsh') return { path: `${o.zdotdir || o.home}/.zshrc`, kind: 'sh' }+ if (name === 'bash') return { path: `${o.home}/${o.isMac ? '.bash_profile' : '.bashrc'}`, kind: 'sh' }+ if (name === 'fish') return { path: `${o.xdgConfig || `${o.home}/.config`}/fish/conf.d/md-preview.fish`, kind: 'fish' }+ return null+}+export function setupBlock(kind: ShellRc['kind']): string {+ const line = kind === 'fish'+ ? 'if test "$TERM_PROGRAM" = "iTerm.app"; and not set -q TMUX; and not set -q STY; set -gx CLAUDE_CODE_FORCE_TERMINAL_IMAGES 1; end'+ : 'if [ "$TERM_PROGRAM" = "iTerm.app" ] && [ -z "$TMUX" ] && [ -z "$STY" ]; then export CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1; fi'+ return `${SETUP_START}\n${line}\n${SETUP_END}\n`+}+export const hasSetup = (text: string) => text.includes(SETUP_START)+// The text with no setup block (and no blank line left where it was).+export function withoutSetup(text: string): string {+ const lines = text.split('\n')+ const out: string[] = []+ for (let i = 0; i < lines.length; i++) {+ if (lines[i] !== SETUP_START) {+ out.push(lines[i]!)+ continue+ }+ const end = lines.indexOf(SETUP_END, i)+ if (end < 0) {+ out.push(lines[i]!)+ continue+ }+ if (out.length && out[out.length - 1] === '') out.pop()+ i = end+ }+ return out.join('\n')+}+// The text with one setup block at its end.+export function withSetup(text: string, kind: ShellRc['kind']): string {+ const base = withoutSetup(text).replace(/\n*$/, '')+ return `${base}${base ? '\n\n' : ''}${setupBlock(kind)}`+}++// The shell start file for this user, or null when the shell is not known.+async function shellRc($: EngineInterface): Promise<ShellRc | null> {+ return shellRcOf({+ shell: (await $.env.get('SHELL')) ?? '',+ home: (await $.env.get('HOME')) ?? '',+ zdotdir: (await $.env.get('ZDOTDIR')) || undefined,+ xdgConfig: (await $.env.get('XDG_CONFIG_HOME')) || undefined,+ isMac: S.hostOs === 'Darwin',+ })+}++// Adds (or removes) the setup block. Returns what to tell the person.+export async function runSetup($: EngineInterface, remove: boolean): Promise<string> {+ const rc = await shellRc($)+ const manual = `export CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1 (only in iTerm2, not in tmux or screen)`+ if (!rc) return `md-preview does not know your shell, so it changed no file. Add this to your shell's start file: ${manual}`+ const text = (await readText($, rc.path)) ?? ''+ const restart = 'Close this tab, open a new iTerm2 tab, and start Claude Code there to see pictures.'+ if (remove) {+ if (!hasSetup(text)) return `${rc.path} has no md-preview block.`+ await $.fs.write(rc.path, withoutSetup(text))+ return `Removed the md-preview block from ${rc.path}. New iTerm2 tabs show answers as text.`+ }+ if (hasSetup(text)) return `${rc.path} already has the md-preview block. ${restart}`+ if (rc.kind === 'fish') await $.process.run(['mkdir', '-p', rc.path.replace(/\/[^/]*$/, '')]).catch(() => null)+ await $.fs.write(rc.path, withSetup(text, rc.kind))+ return `Added the md-preview block to ${rc.path}. ${restart} Undo with /md-preview setup remove.`+}++// Asks once per load whether to add the setup block; "Never ask" is kept.+export async function offerSetup($: EngineInterface) {+ if (S.setupAsked) return+ S.setupAsked = true+ if ((await $.store.get('setup').catch(() => undefined)) === 'never') return+ const rc = await shellRc($)+ if (rc && hasSetup((await readText($, rc.path)) ?? '')) return+ const file = rc ? rc.path.replace((await $.env.get('HOME')) ?? '\u0000', '~') : "your shell's start file"+ const answer = await $.ui.ask(+ `md-preview draws answers as pictures, but in iTerm2 Claude Code needs CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1 when it starts. Add one line to ${file} that sets it in iTerm2 only (not in tmux or screen)?`,+ { header: 'md-preview', options: ['Add the line', 'Not now', 'Never ask'] },+ )+ if (answer === 'Never ask') await $.store.set('setup', 'never')+ if (answer !== 'Add the line') return+ const said = await runSetup($, false)+ // The toast box is small: a short line there, the whole text in the transcript.+ try {+ $.ui.log(said)+ } catch {}+ try {+ $.ui.toast(said.startsWith('Added') ? 'Close this tab and open a new iTerm2 tab to see pictures.' : 'See the transcript for the setup.', { timeoutMs: 10000 })+ } catch {}+}diff --git a/hooks/lib/state.ts b/hooks/lib/state.tsnew file mode 100644index 0000000..fb08ef1--- /dev/null+++ b/hooks/lib/state.ts@@ -0,0 +1,150 @@+// md-preview's state: the types the modules share, the values that change+// (`S`), the caches, and refresh (the `done` atom).+import { atom, update } from 'claude-code'+import type { EngineInterface } from 'claude-code'++import type { MdPreviewTheme } from '../../types'+import type { ThemeInfo } from './themes'+import type { HostMode, ThemeSetting } from './mode'+import type { PlanVerdict } from './plan'+import { DEFAULT_SIZE } from './settings'++// The `done` atom (see types/index.d.ts) for refresh. The state scan of+// `claude plugin validate` reads an atom only from a const in the file that+// reads or writes it, so each such file has a copy of its own (atom() is a+// plain description: the copies are one value).+const done = atom({ plugin: 'md-preview', key: 'done' } as const, 0)++export type Cell = { width: number; height: number }+// 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 }+// `term` the terminal's font (null when unknown or not installed), `menlo`+// the template's code font, `body` its text font.+export type Metrics = { term: FontMetrics | null; menlo: FontMetrics; body: FontMetrics }+// Measured with Typst on macOS: Menlo and SF Pro Text.+export const DEFAULT_METRICS: Metrics = {+ term: null,+ menlo: { adv: 0.602, xh: 0.547, avg: 0.602 },+ body: { adv: 0.63, xh: 0.526, avg: 0.483 },+}+export type Env = {+ typst: string | null+ canDraw: boolean+ // Over ssh: pictures go as `{ png }` bytes, not as a file name.+ inline: boolean+ cache: string+ cwd: string+ root: string+ isMac: boolean+ stamp: string+ home: string+ // Claude Code's temp folder of this user (claudeTmpOf; '' when not known).+ claudeTmp: string+ // The terminal's font family ('' when not known) and the fonts' metrics.+ termFont: string+ metrics: Metrics+}+export type Page = { file: string; width: number; height: number; alt: string }+export type Result = { pages: Page[]; columns: number; bulletRow: number; note?: string }+export type Job = {+ key: string+ requestId: string+ text: string+ columns: number+ cell: Cell+ theme: MdPreviewTheme+ size: number+ themeDir: string+ env: Env+}+// The active theme: its name, folder, and the mtimes of its files and the+// base theme's, which are part of every key.+export type Look = { name: string; dir: string; stamp: string }++// Module state: lost on a hot reload, which is fine. The PNGs stay on disk+// with a pages.json beside them, so a key compiled before is read back.+// The values that change are in one object, so every module sees the same.+export const S = {+ env: null as Env | null,+ envLoading: null as Promise<Env> | null,+ cell: null as Cell | null,+ theme: 'dark' as MdPreviewTheme,+ size: DEFAULT_SIZE,+ 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`+ // starts empty with the module and at most one poll runs (`checking`).+ setting: 'dark' as ThemeSetting,+ settingRaw: '',+ host: null as HostMode | null,+ hostOs: '',+ colorFgBg: '',+ termProgram: '',+ termName: '',+ itermProfile: undefined as string | undefined,+ // kitty: TERM=xterm-kitty, or its KITTY_WINDOW_ID / KITTY_PID (set in setUp).+ isKitty: false,+ // iTerm2 (isItermIn) and cmux (Ghostty inside, with its CMUX_* variables), set in setUp.+ isIterm: false,+ isCmux: false,+ // 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,+ // 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,+ setupAsked: false,+ watch: null as { cancel: () => void } | null,+ checking: false,+ // Streaming: model requests of the main loop in flight.+ stepsLive: 0,+ // The plan (plan.tsx): the main loop's running turn (`turn.start`), the+ // verdict md-preview's question gave for the PermissionRequest that follows+ // (null: none, the engine's dialog asks), the question asked now ('': none),+ // and the `code` command's path (null: not looked up yet; '': none).+ mainTurnId: '',+ planVerdict: null as PlanVerdict | null,+ planAsking: '',+ planCode: null as string | null,+}+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+// final), and the blocks a request made final (they stay final).+export const lastText = new Map<string, string>()+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 } }>()+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 }>()+// 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>()+export const INLINE_KEPT = 64+// Pictures under rows: each file's PNG size by its stat stamp (null: not a+// PNG), and the pasted-images folder of each session once found.+export const pictures = new Map<string, { stamp: string; size: { width: number; height: number } | null }>()+export const pasteDirs = new Map<string, string>()+// The plan: the text edited in md-preview's flow, by the call's tool_use_id+// (its rows draw it), and the ExitPlanMode calls of subagents (drawn as the+// engine draws them).+export const editedPlans = new Map<string, string>()+export const subagentPlans = new Set<string>()+// The main loop's Write and Edit calls still running, by file path (the plan+// waits for its file's).+export const writesLive = new Map<string, number>()++// 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.tsnew file mode 100644index 0000000..2d05776--- /dev/null+++ b/hooks/lib/stream.ts@@ -0,0 +1,74 @@+// 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.+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 { hashOf } from './draw'+import { compile, logDebug } from './typst'++export function pump($: EngineInterface) {+ while (running.size < MAX_RUNNING && queue.length) {+ const job = queue.shift()!+ running.add(job.key)+ void compile($, job)+ .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($)+ pump($)+ })+ }+}++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.+ const stale = queue.findIndex(j => j.requestId === job.requestId || j.key === job.key)+ if (stale >= 0) queue.splice(stale, 1)+ queue.push(job)+ pump($)+}++// Marks a live block final: it compiles at once, and stays blank for at most+// BLANK_AFTER_LIVE_MS while it does. `isForGood`: the request moved past it,+// so later text changes do not hide it again.+export function finalize($: EngineInterface, requestId: string, isForGood: boolean) {+ const was = live.get(requestId)+ if (!was) return+ was.still.cancel()+ live.delete(requestId)+ if (isForGood) finalized.add(requestId)+ enqueue($, was.job)+ waitBlank($, requestId, hashOf([was.job.text]), BLANK_AFTER_LIVE_MS)+ refresh($)+}++export function finalizeAll($: EngineInterface) {+ for (const requestId of [...live.keys()]) finalize($, requestId, true)+}++// Keeps a final block blank until its pictures are ready or `ms` passed;+// then its text shows until they are.+export function waitBlank($: EngineInterface, requestId: string, textHash: string, ms: number) {+ if (pending.get(requestId)?.textHash === textHash) return+ pending.get(requestId)?.timer.cancel()+ const entry = { textHash, showText: false, timer: { cancel: () => {} } }+ entry.timer = $.clock.after(ms, () => {+ entry.showText = true+ refresh($)+ })+ pending.set(requestId, entry)+}++export function forget(requestId: string) {+ live.get(requestId)?.still.cancel()+ live.delete(requestId)+ pending.get(requestId)?.timer.cancel()+ pending.delete(requestId)+}diff --git a/hooks/lib/terminal.ts b/hooks/lib/terminal.tsnew file mode 100644index 0000000..5a0bba6--- /dev/null+++ b/hooks/lib/terminal.ts@@ -0,0 +1,54 @@+// 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 { GUTTER, MAX_COLUMNS, SEGMENT_ROWS } from './settings'++// The columns a picture takes: the viewport less the bullet, MAX_COLUMNS at most.+export function columnsFor(viewportColumns: number | undefined): number {+ return Math.max(20, Math.min(MAX_COLUMNS, (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 {+ const [rows, columns, x, y] = stdout.trim().split(/\s+/).map(Number)+ if (!rows || !columns || !x || !y) return null+ const width = x / columns+ const height = y / rows+ return width >= 4 && width <= 64 && height >= 4 ? { width, height } : null+}++// A set flag: anything but empty, 0, false, no or off.+export const isSet = (value: string | undefined) => !!value && !/^(0|false|no|off)$/i.test(value.trim())++// Whether the engine draws pictures here; elsewhere an Image shows only its+// alt, so the text is better. Claude Code turns kitty graphics on by itself+// only for kitty and Ghostty; any other terminal draws only when+// CLAUDE_CODE_FORCE_TERMINAL_IMAGES is set. A background session never+// draws. In tmux or screen the engine draws none even when forced (it does+// not wrap them for passthrough), so only MD_PREVIEW_FORCE tries. Over ssh+// TERM_PROGRAM and KITTY_WINDOW_ID do not come through, so TERM tells; the+// pictures then go as bytes (Env.inline), as the terminal can't read our files.+export function canDrawIn(env: { program: string; term: string; kitty: boolean; tmux: boolean; ssh: boolean; background: boolean; engineForced: boolean; modForced: boolean }): boolean {+ if (env.background) return false+ if (env.tmux) return env.modForced+ if (env.engineForced || env.modForced) return true+ if (env.ssh) return /ghostty|kitty/i.test(env.term)+ return /ghostty/i.test(env.program + env.term) || /kitty/i.test(env.term) || env.kitty+}++// The most an Image's `{ png }` source holds: 2 MiB decoded, 1 to 4096+// pixels a side (the engine refuses the tree past that).+export const INLINE_MAX_BYTES = 2 * 1024 * 1024+export const INLINE_MAX_SIDE = 4096+// The bytes a standard padded base64 text decodes to.+export const base64Bytes = (text: string) => Math.floor((text.length * 3) / 4) - (text.endsWith('==') ? 2 : text.endsWith('=') ? 1 : 0)+// Whether a page can go as `{ png }` bytes: by its pixels, and by its bytes once read.+export const fitsInline = (page: { width: number; height: number }, base64?: string) =>+ page.width >= 1 && page.width <= INLINE_MAX_SIDE && page.height >= 1 && page.height <= INLINE_MAX_SIDE &&+ (base64 === undefined || base64Bytes(base64) <= INLINE_MAX_BYTES)+// Over ssh, a segment's budget in rows so that its page stays under+// INLINE_MAX_SIDE pixels tall (with room for the rough row count).+export const inlineBudget = (px: Cell) => Math.max(20, Math.min(SEGMENT_ROWS, Math.floor((INLINE_MAX_SIDE / px.height) * 0.75)))diff --git a/hooks/lib/terminals.ts b/hooks/lib/terminals.tsnew file mode 100644index 0000000..7e83abe--- /dev/null+++ b/hooks/lib/terminals.ts@@ -0,0 +1,399 @@+// The terminals' own settings (iTerm2, Ghostty, kitty, Rio, cmux): their+// backgrounds and fonts from their config files and profiles (pure; the+// reads on the host are in host.ts).+import type { MdPreviewTheme } from '../../types'+import { luminanceOf, modeOfLuminance, type Rgb } from './mode'++// An iTerm2 profile ("New Bookmarks" entry): the one named as ITERM_PROFILE+// says, else the default one.+export type ItermMark = Record<string, unknown>+export function pickProfile(marks: readonly unknown[], profile: string | undefined, defaultGuid: string): ItermMark | null {+ const list = marks.filter((x): x is ItermMark => !!x && typeof x === 'object' && !Array.isArray(x))+ return (profile ? list.find(b => b.Name === profile) : undefined) ?? list.find(b => b.Guid === defaultGuid.trim()) ?? null+}++// iTerm2's own appearance (Settings > Appearance > Theme, the+// TabStyleWithAutomaticOption default): 0 and 2 light, 1 and 3 dark;+// Automatic (4), Minimal (5), Compact (6) or no value follow the OS (null).+export function itermAppearanceOf(stdout: string): MdPreviewTheme | null {+ const v = stdout.trim()+ if (v === '0' || v === '2') return 'light'+ if (v === '1' || v === '3') return 'dark'+ return null+}++// An iTerm2 colour ({ "Red Component": 0..1, … }), or null.+function itermColorOf(value: unknown): Rgb | null {+ if (!value || typeof value !== 'object') return null+ const c = value as Record<string, unknown>+ const [r, g, b] = [c['Red Component'], c['Green Component'], c['Blue Component']]+ return typeof r === 'number' && typeof g === 'number' && typeof b === 'number' ? { r, g, b } : null+}++// The mode of the iTerm2 profile's background: the profile named as+// ITERM_PROFILE says, else the default one. A profile with separate colours+// for light and dark mode uses the set `appearance` gives (the OS's when+// iTerm2 follows it; null when that is not known). `bookmarks` is the JSON of+// the plist's "New Bookmarks" array.+export function itermModeOf(bookmarks: string, profile: string | undefined, defaultGuid: string, appearance: MdPreviewTheme | null): MdPreviewTheme | null {+ let list: unknown+ try {+ list = JSON.parse(bookmarks)+ } catch {+ return null+ }+ if (!Array.isArray(list)) return null+ const mark = pickProfile(list, profile, defaultGuid)+ if (!mark) return null+ const separate = mark['Use Separate Colors for Light and Dark Mode'] === true+ if (separate && !appearance) return null+ const key = separate ? `Background Color (${appearance === 'dark' ? 'Dark' : 'Light'})` : 'Background Color'+ const bg = itermColorOf(mark[key]) ?? itermColorOf(mark['Background Color'])+ return bg ? modeOfLuminance(luminanceOf(bg)) : null+}++// "MesloLGS-NF-Regular 14" (iTerm2's Normal Font) → PostScript name and size.+export function parseFontSpec(spec: string): { name: string; size: number } | null {+ const m = /^\s*(\S.*?)\s+(\d+(?:\.\d+)?)\s*$/.exec(spec)+ return m ? { name: m[1]!, size: Number(m[2]) } : null+}++// The Normal Font of the iTerm2 profile in use: the bookmark named+// ITERM_PROFILE, else the default bookmark. `bookmarks` is the JSON of the+// plist's "New Bookmarks" array.+export function itermFontOf(bookmarks: string, profile: string | undefined, defaultGuid: string): string | null {+ let list: unknown+ try {+ list = JSON.parse(bookmarks)+ } catch {+ return null+ }+ if (!Array.isArray(list)) return null+ const font = pickProfile(list, profile, defaultGuid)?.['Normal Font']+ return typeof font === 'string' && font.trim() ? font.trim() : null+}++// Ghostty's background when its config sets none and no theme.+export const GHOSTTY_DEFAULT_BG = '#282c34'++// `#rrggbb` or `rrggbb` in 0..1, or null (X11 colour names are not known).+export function hexColorOf(text: string): Rgb | null {+ const m = /^\s*#?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})\s*$/i.exec(text)+ return m ? { r: parseInt(m[1]!, 16) / 255, g: parseInt(m[2]!, 16) / 255, b: parseInt(m[3]!, 16) / 255 } : null+}++// The last value of `key = value` in a Ghostty config or theme file, or ''.+export function ghosttyValueOf(config: string, key: string): string {+ let value = ''+ for (const line of config.split('\n')) {+ const m = /^\s*([\w-]+)\s*=\s*(.*?)\s*$/.exec(line)+ if (m && m[1] === key) value = m[2]!.replace(/^"(.*)"$/, '$1')+ }+ return value+}++// Ghostty's `theme`: one name, or `light:A,dark:B` (in either order).+export function ghosttyThemesOf(value: string): { light: string; dark: string } | null {+ const pair: Record<string, string> = {}+ for (const part of value.split(',')) {+ const m = /^\s*(light|dark)\s*:\s*(.*?)\s*$/i.exec(part)+ if (m && m[2]) pair[m[1]!.toLowerCase()] = m[2]+ }+ return pair.light && pair.dark ? { light: pair.light, dark: pair.dark } : null+}++// The files a Ghostty theme name can be: an absolute path as is, else the+// user's themes folder, then the themes Ghostty ships.+export function ghosttyThemePaths(name: string, o: { xdgConfig?: string; home: string; resources?: string }): string[] {+ if (name.startsWith('/')) return [name]+ if (name.startsWith('~/')) return [`${o.home}${name.slice(1)}`]+ const config = o.xdgConfig || `${o.home}/.config`+ return [+ `${config}/ghostty/themes/${name}`,+ `${o.home}/Library/Application Support/com.mitchellh.ghostty/themes/${name}`,+ ...(o.resources ? [`${o.resources}/themes/${name}`] : []),+ `/Applications/Ghostty.app/Contents/Resources/ghostty/themes/${name}`,+ `/usr/share/ghostty/themes/${name}`,+ ]+}++// The background Ghostty draws, from `ghostty +show-config` (which prints the+// values that differ from the defaults, a single theme's colours merged in).+// With `light:A,dark:B` the shown background is one theme's, so the one for+// `appearance` is taken from `themeBg` (each theme file's background) unless+// the config sets a background of its own (it then matches neither theme).+// Null when the appearance is needed but not known.+export function ghosttyBackgroundOf(config: string, appearance: MdPreviewTheme | null, themeBg: { light?: string; dark?: string }): string | null {+ const shown = ghosttyValueOf(config, 'background')+ const pair = ghosttyThemesOf(ghosttyValueOf(config, 'theme'))+ if (!pair) return shown || GHOSTTY_DEFAULT_BG+ const same = (a?: string, b?: string) => !!a && !!b && a.replace('#', '').toLowerCase() === b.replace('#', '').toLowerCase()+ const fromTheme = !shown || same(shown, themeBg.light) || same(shown, themeBg.dark)+ if (!fromTheme) return shown+ if (!appearance) return null+ return themeBg[appearance] || null+}++// The first `font-family = X` of `ghostty +show-config`.+export function ghosttyFontOf(config: string): string | null {+ for (const line of config.split('\n')) {+ const m = /^\s*font-family\s*=\s*(.*?)\s*$/.exec(line)+ const family = m?.[1]?.replace(/^"(.*)"$/, '$1').trim()+ if (family) return family+ }+ return null+}++// kitty's background when no config or auto theme sets one.+export const KITTY_DEFAULT_BG = '#000000'+// At most this many kitty config files are read (kitty.conf and its includes).+const KITTY_MAX_FILES = 32+export type KittyEntries = [key: string, value: string][]++// The `key value` lines of a kitty config file, in order. A comment is a+// line that starts with `#`.+export function kittyLinesOf(text: string): KittyEntries {+ const out: KittyEntries = []+ for (const raw of text.split('\n')) {+ const m = /^([a-zA-Z][a-zA-Z0-9_-]*)\s+(.+)$/.exec(raw.trim())+ if (m) out.push([m[1]!, m[2]!.trim()])+ }+ return out+}++// The last value of `key` in kitty config entries, or ''.+export function kittyValueOf(entries: KittyEntries, key: string): string {+ let value = ''+ for (const [k, v] of entries) if (k === key) value = v+ return value+}++// The file an `include` names: `~` is the home folder, `$X` / `${X}` come+// from `vars` (others stay), and a relative path starts at the folder of the+// file that has the line.+export function kittyIncludePath(value: string, dir: string, o: { home: string; vars?: Readonly<Record<string, string>> }): string {+ const vars = o.vars ?? {}+ let path = value.trim().replace(/\$(?:\{(\w+)\}|(\w+))/g, (all: string, a?: string, b?: string) => vars[a ?? b ?? ''] ?? all)+ if (path === '~' || path.startsWith('~/')) path = `${o.home}${path.slice(1)}`+ return path.startsWith('/') ? path : `${dir.replace(/\/+$/, '')}/${path}`+}++// A kitty config file with its `include` files in place (as kitty reads+// them: each file once, so no loops). `globinclude`, `envinclude` and+// `geninclude` are skipped. `readText` gives null for a file it can't read.+export async function kittyEntriesOf(+ path: string,+ readText: (path: string) => Promise<string | null>,+ o: { home: string; vars?: Readonly<Record<string, string>> },+ seen = new Set<string>(),+): Promise<KittyEntries> {+ if (seen.has(path) || seen.size >= KITTY_MAX_FILES) return []+ seen.add(path)+ const text = await readText(path)+ if (text === null) return []+ const dir = path.replace(/\/[^/]*$/, '') || '/'+ const out: KittyEntries = []+ for (const [key, value] of kittyLinesOf(text)) {+ if (key === 'include') out.push(...(await kittyEntriesOf(kittyIncludePath(value, dir, o), readText, o, seen)))+ else out.push([key, value])+ }+ return out+}++// The folders kitty looks in for kitty.conf, in order: KITTY_CONFIG_DIRECTORY+// alone when set; else XDG_CONFIG_HOME's, ~/.config's, and on macOS+// ~/Library/Preferences's.+export function kittyConfigDirsOf(o: { kittyDir?: string; xdgConfig?: string; home: string; isMac: boolean }): string[] {+ if (o.kittyDir) return [o.kittyDir]+ const dirs = [...(o.xdgConfig ? [`${o.xdgConfig}/kitty`] : []), `${o.home}/.config/kitty`, ...(o.isMac ? [`${o.home}/Library/Preferences/kitty`] : [])]+ return [...new Set(dirs)]+}++// kitty's `font_family`: a family name, `family="…" style=…` (kitty 0.36+),+// or `postscript_name=…`. Null for the system's monospace font (`monospace`,+// `auto`, or no value).+export function kittyFontOf(value: string): { family: string } | { postscript: string } | null {+ const v = value.trim()+ const unquote = (s: string) => s.replace(/^(["'])(.*)\1$/, '$2').trim()+ const isSystem = (s: string) => !s || /^(monospace|auto)$/i.test(s)+ if (/^[a-z_]+=/.test(v)) {+ const pairs: Record<string, string> = {}+ for (const m of v.matchAll(/([a-z_]+)=("[^"]*"|'[^']*'|\S+)/g)) pairs[m[1]!] = unquote(m[2]!)+ if (pairs.family !== undefined) return isSystem(pairs.family) ? null : { family: pairs.family }+ return pairs.postscript_name ? { postscript: pairs.postscript_name } : null+ }+ const name = unquote(v)+ return isSystem(name) ? null : { family: name }+}++// The OS colour scheme as kitty sees it, from GNOME's `color-scheme`:+// 'default' is no preference. Null for anything else.+export function kittySchemeOfGnome(stdout: string): 'dark' | 'light' | 'no-preference' | null {+ const v = stdout.trim().replace(/^'|'$/g, '')+ return v === 'prefer-dark' ? 'dark' : v === 'prefer-light' ? 'light' : v === 'default' ? 'no-preference' : null+}++// The auto theme file kitty (0.38+) uses for an OS colour scheme, when it+// exists in the config folder. Its colours replace all others.+export const kittyAutoFileOf = (scheme: 'dark' | 'light' | 'no-preference') => `${scheme}-theme.auto.conf`++// The background kitty draws: the auto theme file's (kitty's defaults+// first, then the file) when one applies, else kitty.conf's with its+// includes, else kitty's default.+export function kittyBackgroundOf(conf: KittyEntries, auto: { file: string; entries: KittyEntries } | null): { bg: string; detail: string } {+ if (auto) return { bg: kittyValueOf(auto.entries, 'background') || KITTY_DEFAULT_BG, detail: `${auto.file} background` }+ const own = kittyValueOf(conf, 'background')+ return { bg: own || KITTY_DEFAULT_BG, detail: own ? 'config background' : 'default background' }+}++// Rio's background when neither its config nor a theme sets one.+export const RIO_DEFAULT_BG = '#0f0d0e'+// Rio's font when the config names none (the Cascadia Code it carries).+export const RIO_DEFAULT_FONT = 'Cascadia Code'++// The string values of a TOML file by dotted path (`[fonts.regular]` then+// `family = "X"` is `fonts.regular.family`). Only what Rio's few keys need:+// tables, dotted and quoted keys, one-line strings, one-line inline tables+// of strings, and `#` comments. Other values are skipped.+export function tomlStringsOf(text: string): Record<string, string> {+ const out: Record<string, string> = {}+ const KEY = String.raw`(?:[\w-]+|"[^"]*"|'[^']*')`+ const pathOf = (key: string) => [...key.matchAll(new RegExp(KEY, 'g'))].map(m => m[0].replace(/^(["'])(.*)\1$/, '$2')).join('.')+ const stringOf = (value: string) => {+ const m = /^"((?:[^"\\]|\\.)*)"|^'([^']*)'/.exec(value)+ if (!m) return null+ return m[2] ?? m[1]!.replace(/\\(["\\])/g, '$1')+ }+ const head = new RegExp(String.raw`^\[\[?\s*(${KEY}(?:\s*\.\s*${KEY})*)\s*\]\]?\s*(?:#.*)?$`)+ const entry = new RegExp(String.raw`^(${KEY}(?:\s*\.\s*${KEY})*)\s*=\s*(.*)$`)+ const pair = new RegExp(String.raw`(${KEY})\s*=\s*("(?:[^"\\]|\\.)*"|'[^']*')`, 'g')+ let table = ''+ for (const raw of text.split('\n')) {+ const line = raw.trim()+ const h = head.exec(line)+ if (h) {+ table = pathOf(h[1]!)+ continue+ }+ const m = entry.exec(line)+ if (!m) continue+ const key = [table, pathOf(m[1]!)].filter(Boolean).join('.')+ const value = m[2]!+ if (value.startsWith('{')) {+ for (const p of value.matchAll(pair)) {+ const s = stringOf(p[2]!)+ if (s !== null) out[`${key}.${pathOf(p[1]!)}`] = s+ }+ } else {+ const s = stringOf(value)+ if (s !== null) out[key] = s+ }+ }+ return out+}++// Rio's config folder: RIO_CONFIG_HOME, else (not on macOS) XDG_CONFIG_HOME's+// rio, else ~/.config/rio.+export function rioConfigDirOf(o: { rioHome?: string; xdgConfig?: string; home: string; isMac: boolean }): string {+ if (o.rioHome) return o.rioHome+ return `${!o.isMac && o.xdgConfig ? o.xdgConfig : `${o.home}/.config`}/rio`+}++// A Rio theme's file: `themes/<name>` in the config folder, with its+// extension made `.toml` (as Rio does).+export function rioThemePath(dir: string, name: string): string {+ const file = `${name.replace(/(\/[^/.]+|^[^/.]+)\.[^./]*$/, '$1')}.toml`+ return file.startsWith('/') ? file : `${dir}/themes/${file}`+}++// The theme names a Rio config uses: `theme`, and both `[adaptive-theme]`+// names when the config has the two.+export function rioThemeNamesOf(config: Readonly<Record<string, string>>): string[] {+ const { theme, 'adaptive-theme.light': light, 'adaptive-theme.dark': dark } = config+ return [...new Set([...(theme ? [theme] : []), ...(light && dark ? [light, dark] : [])])]+}++// Rio's `force-theme`, when it is dark or light.+export const rioForcedOf = (config: Readonly<Record<string, string>>): MdPreviewTheme | null => {+ const v = config['force-theme']+ return v === 'dark' || v === 'light' ? v : null+}++// The background Rio draws. With both `[adaptive-theme]` files found, the one+// for `force-theme`, else for `appearance` (the OS); else the `theme` file's;+// else the config's `[colors] background`. A theme file replaces all the+// config's colours. `themes` holds each file's text by name (null: not found).+export function rioBackgroundOf(config: Readonly<Record<string, string>>, appearance: MdPreviewTheme | null, themes: Readonly<Record<string, string | null>>): { bg: string; detail: string } {+ // #rrggbbaa: the alpha is dropped.+ const opaque = (bg: string) => bg.replace(/^(#?[0-9a-f]{6})[0-9a-f]{2}$/i, '$1')+ const has = (name: string | undefined): name is string => !!name && typeof themes[name] === 'string'+ const bgOf = (name: string) => ({ bg: opaque(tomlStringsOf(themes[name]!)['colors.background'] || RIO_DEFAULT_BG), detail: `theme ${name} background` })+ const { 'adaptive-theme.light': light, 'adaptive-theme.dark': dark, theme } = config+ const which = rioForcedOf(config) ?? appearance+ if (has(light) && has(dark) && which) return bgOf(which === 'dark' ? dark : light)+ if (has(theme)) return bgOf(theme)+ const own = config['colors.background']+ return { bg: opaque(own || RIO_DEFAULT_BG), detail: own ? 'config background' : 'default background' }+}++// Rio's font: `[fonts] family` (it sets every style), else `[fonts.regular]+// family`, else the one Rio carries.+export function rioFontOf(config: Readonly<Record<string, string>>): string {+ const family = (config['fonts.family'] || config['fonts.regular.family'] || '').trim()+ return !family || family.replace(/\s/g, '').toLowerCase() === 'cascadiacode' ? RIO_DEFAULT_FONT : family+}++// iTerm2: TERM_PROGRAM says so; with no TERM_PROGRAM (it is not always+// passed on), ITERM_PROFILE, ITERM_SESSION_ID or LC_TERMINAL=iTerm2 say so.+// Another TERM_PROGRAM always wins.+export function isItermIn(env: { program: string; profile?: string; session?: string; lcTerminal?: string }): boolean {+ if (env.program) return /^iTerm/i.test(env.program)+ return !!env.profile || !!env.session || /^iTerm2$/i.test(env.lcTerminal ?? '')+}++// A JSONC file (JSON with // and /* */ comments and trailing commas) as a+// value; null when it is not valid.+export function jsoncOf(text: string): unknown {+ const plain = text+ .replace(/"(?:[^"\\]|\\.)*"|\/\/[^\n]*|\/\*[\s\S]*?\*\//g, m => (m.startsWith('"') ? m : ''))+ .replace(/"(?:[^"\\]|\\.)*"|,(\s*[}\]])/g, (m, tail?: string) => tail ?? m)+ try {+ return JSON.parse(plain)+ } catch {+ return null+ }+}++export type CmuxAppearance = 'system' | 'light' | 'dark'+// The cmux settings md-preview needs, from cmux.json: `app.appearance` and+// `terminal.adaptiveDefaultTheme` (nested objects, or dotted keys).+export function cmuxSettingsOf(json: unknown): { appearance?: CmuxAppearance; adaptive?: boolean } {+ const at = (path: string): unknown => {+ if (!json || typeof json !== 'object') return undefined+ const flat = (json as Record<string, unknown>)[path]+ if (flat !== undefined) return flat+ let v: unknown = json+ for (const part of path.split('.')) v = v && typeof v === 'object' ? (v as Record<string, unknown>)[part] : undefined+ return v+ }+ const appearance = at('app.appearance')+ const adaptive = at('terminal.adaptiveDefaultTheme')+ return {+ ...(appearance === 'system' || appearance === 'light' || appearance === 'dark' ? { appearance } : {}),+ ...(typeof adaptive === 'boolean' ? { adaptive } : {}),+ }+}++// cmux's appearance: cmux.json's value wins over the one saved in Settings+// (`defaults read com.cmuxterm.app appearanceMode`); else system.+export function cmuxAppearanceOf(file: CmuxAppearance | undefined, saved: string): CmuxAppearance {+ const v = saved.trim().toLowerCase()+ return file ?? (v === 'light' || v === 'dark' ? v : 'system')+}++// Whether `ghostty +show-config` shows colours of the user's own (a theme,+// a background, a foreground or a palette). cmux then uses them; else its+// adaptive default theme follows cmux's appearance.+export function ghosttyHasColors(config: string): boolean {+ return ['theme', 'background', 'foreground', 'palette'].some(key => ghosttyValueOf(config, key) !== '')+}diff --git a/hooks/lib/themes.ts b/hooks/lib/themes.tsnew file mode 100644index 0000000..bb08e23--- /dev/null+++ b/hooks/lib/themes.ts@@ -0,0 +1,157 @@+// Themes: a theme folder's theme.json, the built-in and user themes, the one+// to draw with, what `/md-preview theme` lists, and the scan on the host.+import type { EngineInterface } from 'claude-code'++import { BASE_THEME, DEFAULT_THEME, MODES } from './settings'+import { S } from './state'++// A theme folder's name: letters, digits, `.`, `_`, `-`.+export const isThemeName = (name: string) => /^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(name)++// `syntax`: the tmTheme file theme.json names for a mode, relative to the+// theme folder; a mode it does not name uses the base theme's file.+export type ThemeSyntax = Partial<Record<(typeof MODES)[number], string>>+export type ThemeInfo = { name: string; dir: string; isUser: boolean; title: string; description: string; syntax: ThemeSyntax }+export type ThemeProblem = { name: string; dir: string; isUser: boolean; reason: string }++// One theme folder from its theme.json text: usable, or why not.+export function themeEntry(name: string, dir: string, isUser: boolean, json: string): ThemeInfo | ThemeProblem {+ if (!isThemeName(name)) return { name, dir, isUser, reason: 'the folder name has characters other than letters, digits, ., _ and -' }+ let data: unknown+ try {+ data = JSON.parse(json)+ } catch (err) {+ return { name, dir, isUser, reason: `theme.json is not valid JSON (${err instanceof Error ? err.message : String(err)})` }+ }+ if (!data || typeof data !== 'object' || Array.isArray(data)) return { name, dir, isUser, reason: 'theme.json is not a JSON object' }+ const field = (key: string) => {+ const v = (data as Record<string, unknown>)[key]+ return typeof v === 'string' ? v : ''+ }+ const named = (data as Record<string, unknown>).syntax+ const syntax: ThemeSyntax = {}+ if (named !== undefined) {+ if (!named || typeof named !== 'object' || Array.isArray(named)) return { name, dir, isUser, reason: '"syntax" is not an object of file names' }+ for (const mode of MODES) {+ const file = (named as Record<string, unknown>)[mode]+ if (file === undefined) continue+ if (!isSyntaxPath(file)) return { name, dir, isUser, reason: `"syntax.${mode}" must be a file name in the theme folder (no "/" at the start, no "..")` }+ syntax[mode] = file+ }+ }+ return { name, dir, isUser, title: field('name') || name, description: field('description'), syntax }+}++// A tmTheme path in theme.json: relative to the theme folder and inside it.+export const isSyntaxPath = (file: unknown): file is string =>+ typeof file === 'string' && file.trim() !== '' && !file.startsWith('/') && !file.includes('\\') && !file.split('/').includes('..')++// The files a theme's pictures depend on: its theme.json, the base+// theme.json it merges over, and for each mode the tmTheme it names, else+// the base theme's. A missing `theme` (not found yet) counts as the base.+export function themeFiles(theme: ThemeInfo | undefined, base: ThemeInfo | undefined, root: string): string[] {+ const baseDir = base?.dir ?? `${root}/render/themes/${BASE_THEME}`+ const files = [`${theme?.dir ?? baseDir}/theme.json`, `${baseDir}/theme.json`]+ for (const mode of MODES) {+ const own = theme?.syntax[mode]+ files.push(own ? `${theme!.dir}/${own}` : `${baseDir}/${base?.syntax[mode] ?? `${mode}.tmTheme`}`)+ }+ return files+}++// Built-in themes, then user themes: a usable user theme replaces the+// built-in of the same name; a broken one is only reported.+export function pickThemes(found: readonly (ThemeInfo | ThemeProblem)[]): { themes: Map<string, ThemeInfo>; problems: ThemeProblem[] } {+ const themes = new Map<string, ThemeInfo>()+ const problems: ThemeProblem[] = []+ for (const isUser of [false, true]) {+ for (const one of found) {+ if (one.isUser !== isUser) continue+ if ('reason' in one) problems.push(one)+ else themes.set(one.name, one)+ }+ }+ return { themes, problems }+}++// The theme to draw with: the wanted one, else the default theme, else the+// base theme (`isFallback`). The base theme's own folder is used even before+// it is found on disk.+export function chooseTheme(themes: ReadonlyMap<string, ThemeInfo>, wanted: string, root: string): { name: string; dir: string; isFallback: boolean } {+ const got = themes.get(wanted)+ if (got) return { name: got.name, dir: got.dir, isFallback: false }+ const fallback = themes.get(DEFAULT_THEME)+ if (fallback) return { name: fallback.name, dir: fallback.dir, isFallback: true }+ const base = themes.get(BASE_THEME)+ return { name: BASE_THEME, dir: base?.dir ?? `${root}/render/themes/${BASE_THEME}`, isFallback: wanted !== BASE_THEME }+}++// What `/md-preview theme` lists.+export function themeListing(themes: ReadonlyMap<string, ThemeInfo>, problems: readonly ThemeProblem[], active: string, userDir: string): string {+ const lines = [...themes.values()]+ .sort((a, b) => a.name.localeCompare(b.name))+ .map(t => `${t.name === active ? '*' : '-'} ${t.name} (${t.isUser ? 'user' : 'built-in'})${t.description ? `: ${t.description}` : ''}`)+ const skipped = problems.map(p => ` skipped ${p.name} (${p.isUser ? 'user' : 'built-in'}): ${p.reason}`)+ return [+ `Themes (* = active):`,+ ...(lines.length ? lines : ['- none found']),+ ...skipped,+ `User themes go in ${userDir}/<name>/theme.json. Switch with /md-preview theme <name>.`,+ ].join('\n')+}++// The built-in themes under render/themes and the user's under+// ~/.claude/md-preview/themes, read fresh each call.+export async function scanThemes($: EngineInterface, root: string, home: string) {+ const found: (ThemeInfo | ThemeProblem)[] = []+ for (const [base, isUser] of [[`${root}/render/themes`, false], [userThemesOf(home), true]] as const) {+ const entries = await $.fs.list(base).catch(() => [])+ for (const entry of entries) {+ if (entry.kind === 'file') continue+ const dir = `${base}/${entry.name}`+ const json = await $.fs.read(`${dir}/theme.json`).catch(() => null)+ if (json === null) continue+ const one = themeEntry(entry.name, dir, isUser, json)+ const lost = 'reason' in one ? [] : await missingSyntax($, one)+ found.push(lost.length ? { name: one.name, dir, isUser, reason: `theme.json names syntax files that do not exist: ${lost.join(', ')}` } : one)+ }+ }+ return pickThemes(found)+}++// The syntax files a theme names that are not on disk (they fail the compile).+export async function missingSyntax($: EngineInterface, theme: ThemeInfo) {+ const lost: string[] = []+ for (const mode of MODES) {+ const file = theme.syntax[mode]+ if (file && !(await $.fs.exists(`${theme.dir}/${file}`).catch(() => false))) lost.push(file)+ }+ return lost+}++export const userThemesOf = (home: string) => `${home || '~'}/.claude/md-preview/themes`++// The mtimes of the files a theme's pictures depend on (themeFiles): a+// change to any of them makes new keys.+export async function stampTheme($: EngineInterface, files: readonly string[]): Promise<string> {+ const times: string[] = []+ for (const file of files) {+ const stat = await $.fs.stat(file).catch(() => null)+ times.push(String(stat?.mtimeMs ?? 0))+ }+ return times.join(',')+}++// Picks the stored theme (or the default one), sets `look`, and says when the+// stored one was not usable.+export async function applyTheme($: EngineInterface, root: string, home: string, wanted: string) {+ const { themes, problems } = await scanThemes($, root, home)+ S.themeChoices = [...themes.values()]+ const chosen = chooseTheme(themes, wanted, root)+ // theme.typ always merges over the built-in vscode, also when a user theme+ // has that name, so the stamp uses the built-in one.+ const builtIn = themes.get(BASE_THEME)+ const files = themeFiles(themes.get(chosen.name), builtIn?.isUser ? undefined : builtIn, root)+ S.look = { name: chosen.name, dir: chosen.dir, stamp: await stampTheme($, files) }+ return { themes, problems, chosen }+}diff --git a/hooks/lib/typst.ts b/hooks/lib/typst.tsnew file mode 100644index 0000000..4c34178--- /dev/null+++ b/hooks/lib/typst.ts@@ -0,0 +1,194 @@+// Typst on the host: finding it, measuring the fonts, and compiling an+// 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 { inlineBudget } from './terminal'+import { alignFirstLine, firstLineOf, fontFit, sizing } from './draw'+import { HEADERS_SH } from './host'++// The typst command and its environment. Network off (see NO_NETWORK) and a+// package cache of our own, so only the vendored packages load.+export function typstCall(o: {+ typst: string+ root: string+ cache: string+ ppi: number+ inputs: Readonly<Record<string, string | number>>+ out: string+}): { argv: string[]; env: Record<string, string> } {+ const argv = [+ o.typst, 'compile',+ '--root', '/',+ '--package-path', `${o.root}/render/packages`,+ '--format', 'png',+ '--diagnostic-format', 'short',+ '--ppi', o.ppi.toFixed(4),+ ...Object.entries(o.inputs).flatMap(([k, v]) => ['--input', `${k}=${v}`]),+ `${o.root}/render/md.typ`,+ o.out,+ ]+ return { argv, env: noNetworkEnv(o.cache) }+}++export function noNetworkEnv(cache: string): Record<string, string> {+ return {+ HTTPS_PROXY: NO_NETWORK,+ HTTP_PROXY: NO_NETWORK,+ ALL_PROXY: NO_NETWORK,+ https_proxy: NO_NETWORK,+ http_proxy: NO_NETWORK,+ all_proxy: NO_NETWORK,+ NO_PROXY: '',+ no_proxy: '',+ TYPST_PACKAGE_CACHE_PATH: `${cache}/pkg-cache`,+ }+}++// Width and height from a PNG's first 24 bytes (signature, then IHDR).+export function pngSize(bytes: readonly number[]): { width: number; height: number } | null {+ const sig = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]+ if (bytes.length < 24 || sig.some((v, i) => bytes[i] !== v)) return null+ const at = (i: number) => ((bytes[i]! << 24) | (bytes[i + 1]! << 16) | (bytes[i + 2]! << 8) | bytes[i + 3]!) >>> 0+ const width = at(16)+ const height = at(20)+ return width && height ? { width, height } : null+}++// `od -An -v -tx1` output for several files, each followed by a line `@`.+export function parseOd(stdout: string): number[][] {+ return stdout+ .split(/^@$/m)+ .slice(0, -1)+ .map(part => part.split(/\s+/).filter(Boolean).map(hex => Number.parseInt(hex, 16)))+}++// Any failed compile is tried once more with `safe=1`: the template then+// shows typst fences and math as code and images as alt boxes, which is how+// a bad typst block or an unknown LaTeX command still draws.+export function shouldRetrySafe(exitCode: number): boolean {+ return exitCode !== 0+}++export async function findTypst($: EngineInterface): Promise<string | null> {+ for (const flag of ['-lc', '-c']) {+ const got = await $.process.run(['sh', flag, 'command -v typst'], { timeoutMs: 5000 }).catch(() => null)+ const path = got?.exitCode === 0 ? firstLine(got.stdout) : ''+ if (path.startsWith('/')) return path+ }+ const home = (await $.env.get('HOME').catch(() => undefined)) ?? ''+ for (const each of TYPST_FALLBACKS) {+ if (each.startsWith('~/') && !home) continue+ const path = each.startsWith('~/') ? `${home}${each.slice(1)}` : each+ if (await $.fs.exists(path).catch(() => false)) return path+ }+ return null+}++// The argv that measures the fonts: the active theme's body and code fonts+// (theme.typ reads theme.json, which needs `--root /`).+export const measureCall = (typst: string, root: string, family: string, themeDir: string) => [+ typst, 'eval', 'query(<m>).first().value', '--in', `${root}/render/measure.typ`, '--root', '/',+ '--input', `term-font=${family}`, '--input', `theme-dir=${themeDir}`,+]++// The fonts' metrics from render/measure.typ; the macOS defaults when that fails.+export async function measureFonts($: EngineInterface, typst: string, root: string, cache: string, family: string, themeDir: string): Promise<Metrics> {+ const argv = measureCall(typst, root, family, themeDir)+ const got = await $.process.run(argv, { timeoutMs: 10000, env: noNetworkEnv(cache) }).catch(() => null)+ try {+ const m = JSON.parse(got?.stdout ?? '') as Metrics+ const ok = (x: FontMetrics | null | undefined) => !!x && x.adv > 0 && x.xh > 0 && x.avg > 0+ if (ok(m.menlo) && ok(m.body)) return { term: ok(m.term) ? m.term : null, menlo: m.menlo, body: m.body }+ } catch {}+ 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)+}++// 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.+export async function existingImages($: EngineInterface, segments: readonly string[], base: string): Promise<string[]> {+ const found: string[] = []+ for (const path of new Set(segments.flatMap(localImages))) {+ const full = imagePathOf(path, base)+ if (await $.fs.exists(full).catch(() => false)) found.push(path, full)+ }+ return found+}++export async function runTypst($: EngineInterface, job: Job, segments: readonly string[], dir: string, tag: string, isSafe: boolean) {+ 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)+ const { argv, env: vars } = typstCall({+ typst: job.env.typst!,+ root: job.env.root,+ cache: job.env.cache,+ ppi,+ inputs: {+ theme: job.theme,+ width: widthPt,+ top: topPt,+ row: Math.round(rowPt * 10000) / 10000,+ code: fit.code,+ ...(job.env.termFont ? { 'term-font': job.env.termFont } : {}),+ 'theme-dir': job.themeDir,+ doc: `${dir}/doc.json`,+ ...(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)}` }))+}++export async function compile($: EngineInterface, job: Job): Promise<Result | 'failed'> {+ 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 segments = splitSegments(job.text, job.columns, job.env.inline ? inlineBudget(job.cell) : SEGMENT_ROWS)+ const images = await existingImages($, segments, job.env.cwd)+ await $.fs.write(`${dir}/doc.json`, JSON.stringify({ base: job.env.cwd, segments, images }))++ let tag = 'a'+ let ran = await runTypst($, job, segments, dir, tag, false)+ let note: string | undefined+ if (ran.exitCode !== 0) {+ 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)+ 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'+ }+ 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 } : {}) }+ await $.fs.write(`${dir}/pages.json`, JSON.stringify(result))+ return result+}diff --git a/hooks/register.tsx b/hooks/register.tsxindex a5693bc..ae89ab7 100644--- a/hooks/register.tsx+++ b/hooks/register.tsx@@ -3,1021 +3,109 @@// The stored message never changes; only its drawing does.//// Flow: the render hook makes a key from the text, the width, the cell size,-// the theme and the template. A known key draws its PNGs. An unknown key-// draws the plain text and starts a timer; when the text has been still for-// SETTLE_MS the key is compiled (at most MAX_RUNNING at once), and the `done`-// atom goes up so every reader draws again and finds the PNGs.+// the theme and the template. A known key draws its PNGs. A block whose text+// is still streaming ("live") draws nothing; it is final when its model+// request (`turn.step`) moves on to another block or ends, or, with no step+// seen, when its text has been still for SETTLE_MS. A final block's key is+// compiled at once (at most MAX_RUNNING at once), and the `done` atom goes up+// so every reader draws again and finds the PNGs.+//+// The work is in ./lib, one topic per module: settings, state (the shared+// mutable state `S`), markdown, terminal, terminals, mode, themes, command,+// setup, host, typst, draw, stream, answer (one text through the pipeline),+// env, images, pictures and plan (the plan approval flow). This file joins+// them to the hooks, and gives the tests the names they import.import { atom, read, update } from 'claude-code'-import type { EngineInterface, Register, RenderInput } from 'claude-code'--import type { MdPreviewTheme } from '../types'--// ---- Settings ---------------------------------------------------------------// The widest picture, in terminal columns.-export const MAX_COLUMNS = 120-// The bullet column to the left of an answer.-const GUTTER = 2-// Claude Code's own reply bullet: ⏺ on macOS, ● elsewhere.-const bulletOf = (isMac: boolean) => (isMac ? '⏺' : '●')-// The engine's answer row has a blank row above it; ours keeps it.-const MARGIN_TOP = 1-// The template's body text size in pt; the page width is chosen so that this-// text looks as big as the terminal's own (see fontFit).-const BODY_PT = 11-// `/md-preview size`: a percent on top of that match.-export const DEFAULT_SIZE = 100-export const MIN_SIZE = 80-export const MAX_SIZE = 200-// Wait this long after the last change of a block's text before compiling.-const SETTLE_MS = 400-const MAX_RUNNING = 2-// A segment is cut to be about this many rows; an Image is 255 rows at most.-export const SEGMENT_ROWS = 160-const MAX_IMAGE_ROWS = 255-// The cell in device pixels when the tty reports none (tmux, a relay): an-// 8 x 16 point cell at Retina scale 2. A reported cell outside 4 to 64 px-// 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.-const TEMPLATE_VERSION = '7'-const COMPILE_TIMEOUT_MS = 20000-const ALT_CHARS = 200-// Where Typst is when the login shell's PATH does not find it. `~` is $HOME.-const TYPST_FALLBACKS = ['/opt/homebrew/bin/typst', '/usr/local/bin/typst', '/usr/bin/typst', '/snap/bin/typst', '~/.cargo/bin/typst', '~/.local/bin/typst']-const NO_TYPST = 'md-preview: install Typst (brew install typst) to see rendered answers'-// Typst downloads a package it doesn't find under --package-path; a proxy-// nobody listens on makes that fail at once, so a live block never fetches.-const NO_NETWORK = 'http://127.0.0.1:9'-// The base every theme merges over (its theme.json and syntax files).-export const BASE_THEME = 'vscode'-// The theme used when none is chosen, or when the chosen one is not usable.-export const DEFAULT_THEME = 'vscode-modern'-// The two modes a theme has syntax colours for.-const MODES = ['dark', 'light'] as const--// What Claude is told while the mod draws its answers (a system prompt-// section, added last).-export const TYPST_PROMPT = `Your replies in this terminal are drawn as rendered Markdown pictures (VS Code preview look), so use Markdown freely: headings, tables, task lists, code blocks, $math$ (LaTeX), images by absolute path.-For anything Markdown can't show well — diagrams, flow charts, plots, coloured tables, complex layouts or math — write a fenced \`\`\`typst block: it is rendered live with Typst 0.15 (full Typst markup; begin code lines with #).-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.-Inside a typst block, #page, #pagebreak and #set page are errors. If a block fails to compile, it is shown as code instead.-The stored text stays Markdown, so keep replies readable as plain text too.`--// ---- State -----------------------------------------------------------------+import type { EngineInterface, Register, RenderElement, RenderViewport } from 'claude-code'++import { DEFAULT_THEME, MAX_SIZE, MIN_SIZE, TYPST_PROMPT } from './lib/settings'+import { editedPlans, refresh, S, subagentPlans, writesLive, type Env } from './lib/state'+import { imagePathOf } from './lib/markdown'+import { columnsFor } from './lib/terminal'+import { escapeControls, luminanceOf, modeLine, modeOfLuminance, parseOsc11, settingOf } from './lib/mode'+import { applyTheme, themeListing, userThemesOf } from './lib/themes'+import { commandSuggestions, parseCommand, registerCommand } from './lib/command'+import { runSetup } from './lib/setup'+import { pollHost, PROBE_RUNS, probeOsc11, showMode, USE_OSC11, watchHost } from './lib/host'+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, sentImages } from './lib/images'+import { pasteDir, shownOf, underRow, type Shown } from './lib/pictures'+import {+ currentPlan, decidePlan, decisionOf, drawAskLine, drawPlanResult, drawPlanUse, isPlanQuestion, planFileOf, planInputOf, planOf,+ planShownOf, scheduleClear, type PlanVerdict,+} from './lib/plan'++// The names this module exported before the split (the tests import them).+export {+ BASE_THEME, DEFAULT_CELL, DEFAULT_SIZE, DEFAULT_THEME, MAX_COLUMNS, MAX_SIZE, MIN_SIZE, PICTURE_MAX_ROWS, SEGMENT_ROWS, TYPST_PROMPT,+} from './lib/settings'+export { DEFAULT_METRICS, type Cell, type FontMetrics, type Look, type Metrics } from './lib/state'+export {+ blocksOf, firstLine, imagePathOf, isTypstInfo, localImages, plainOf, rowsOfBlock, splitSegments, type Block,+} from './lib/markdown'+export * from './lib/terminal'+export * from './lib/mode'+export * from './lib/terminals'+export {+ chooseTheme, isSyntaxPath, isThemeName, pickThemes, themeEntry, themeFiles, themeListing,+ type ThemeInfo, type ThemeProblem, type ThemeSyntax,+} from './lib/themes'+export { commandSuggestions, parseCommand, type Command, type Suggestion } from './lib/command'+export { hasSetup, SETUP_END, SETUP_START, setupBlock, shellRcOf, withoutSetup, withSetup, type ShellRc } from './lib/setup'+export { OSC11_PL } from './lib/host'+export { measureCall, noNetworkEnv, parseOd, pngSize, shouldRetrySafe, typstCall } from './lib/typst'+export { alignFirstLine, firstLineOf, fontFit, hashOf, renderKey, rowsFor, sizing, type FirstLine } from './lib/draw'+export * from './lib/images'+export {+ choiceOf, decisionOf, editorArgv, feedbackOf, isPlanQuestion, normalPath, PLAN_ASK_LINE, PLAN_AUTO, PLAN_CLEAR, PLAN_DRAWING, PLAN_EDIT,+ PLAN_FEEDBACK, PLAN_HEADER, PLAN_IMPLEMENT, PLAN_MANUAL, PLAN_QUESTION, PLAN_QUESTION_EDITED, PLAN_REJECTED, planFileOf, planInputOf,+ planOf, planOptions, planShownOf, shortPath, verdictOf, type PlanChoice, type PlanVerdict,+} from './lib/plan'++// The atoms the hooks read and write (a copy of each in this file: see state.ts).const isOn = atom({ plugin: 'md-preview', key: 'isOn' } as const, true)const done = atom({ plugin: 'md-preview', key: 'done' } as const, 0)-export type Cell = { width: number; height: number }-// 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 }-// `term` the terminal's font (null when unknown or not installed), `menlo`-// the template's code font, `body` its text font.-export type Metrics = { term: FontMetrics | null; menlo: FontMetrics; body: FontMetrics }-// Measured with Typst on macOS: Menlo and SF Pro Text.-export const DEFAULT_METRICS: Metrics = {- term: null,- menlo: { adv: 0.602, xh: 0.547, avg: 0.602 },- body: { adv: 0.63, xh: 0.526, avg: 0.483 },-}-type Env = {- typst: string | null- canDraw: boolean- cache: string- cwd: string- root: string- isMac: boolean- stamp: string- home: string- // The terminal's font family ('' when not known) and the fonts' metrics.- termFont: string- metrics: Metrics-}-type Page = { file: string; width: number; height: number; alt: string }-type Result = { pages: Page[]; columns: number; bulletRow: number; note?: string }-type Job = {- key: string- requestId: string- text: string- columns: number- cell: Cell- theme: MdPreviewTheme- size: number- themeDir: string- env: Env-}-// The active theme: its name, folder, and the mtimes of its files and the-// base theme's, which are part of every key.-export type Look = { name: string; dir: string; stamp: string }--// Module state: lost on a hot reload, which is fine. The PNGs stay on disk-// with a pages.json beside them, so a key compiled before is read back.-let env: Env | null = null-let envLoading: Promise<Env> | null = null-let cell: Cell | null = null-let theme: MdPreviewTheme = 'dark'-let size = DEFAULT_SIZE-let look: Look | null = null-let lastView = ''-let measureTimer: { cancel: () => void } | null = null-const results = new Map<string, Result | 'failed'>()-const timers = new Map<string, { key: string; cancel: () => void }>()-const queue: Job[] = []-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.-const shown = new Map<string, { textHash: string; result: Result }>()-// ---- Pure functions (tested) ------------------------------------------------// FNV-1a over the parts, twice with different offsets: 16 hex digits.-export function hashOf(parts: readonly (string | number)[]): string {- const s = parts.join('\u0000')- let a = 0x811c9dc5- let b = 0x050c5d1f- for (let i = 0; i < s.length; i++) {- const c = s.charCodeAt(i)- a = Math.imul(a ^ c, 0x01000193) >>> 0- b = Math.imul(b ^ c, 0x01000193) >>> 0- }- return a.toString(16).padStart(8, '0') + b.toString(16).padStart(8, '0')-}--export function themeOf(value: unknown): MdPreviewTheme {- return typeof value === 'string' && /light/i.test(value) ? 'light' : 'dark'-}--// The columns a picture takes: the viewport less the bullet, MAX_COLUMNS at most.-export function columnsFor(viewportColumns: number | undefined): number {- return Math.max(20, Math.min(MAX_COLUMNS, (viewportColumns ?? 80) - GUTTER))-}--// How wide a column is in the page's pt so the template's 11 pt body text-// looks as big as the terminal's text, `sizePercent` on top. A terminal em is-// a cell / the advance of its font; the body font is matched to it by-// x-height and average width together (sqrt of the two ratios), since a-// proportional font at the same em looks smaller. Code is set in the-// terminal's font at the terminal's size: `code` is its size / body size.-// The template uses `code` only for a theme that sets "size": "terminal"-// for code; the vscode themes draw code at body size, as VS Code does.-export function fontFit(m: Metrics, sizePercent = 100) {- const t = m.term ?? m.menlo- const ratio = Math.sqrt((t.xh / m.body.xh) * (t.avg / m.body.avg))- const scale = sizePercent / 100- return {- columnPt: Math.round(((BODY_PT * t.adv) / (ratio * scale)) * 10000) / 10000,- code: Math.round((1 / ratio) * 10000) / 10000,- ratio,- }-}--// The page width in pt and the ppi that make the PNG exactly as wide as the-// box in device pixels; `rowPt` is one terminal row in the page's pt.-export function sizing(columns: number, px: Cell, columnPt: number) {- const widthPt = Math.round(columns * columnPt * 100) / 100- const widthPx = Math.round(columns * px.width)- const ppi = widthPx / (widthPt / 72)- return { widthPt, widthPx, ppi, rowPt: (px.height * 72) / ppi }-}--// `/md-preview` arguments: on, off, size <80-200>, or nothing (show state).-export type Command =- | { kind: 'on' | 'off' | 'show' }- | { kind: 'size'; percent: number }- | { kind: 'theme'; name?: string }- | { kind: 'bad' }-export function parseCommand(args: string): Command {- const typed = args.trim().split(/\s+/).filter(Boolean)- const words = typed.map(w => w.toLowerCase())- if (!words.length) return { kind: 'show' }- if (words[0] === 'theme') {- if (typed.length === 1) return { kind: 'theme' }- if (typed.length === 2 && isThemeName(typed[1]!)) return { kind: 'theme', name: typed[1]! }- return { kind: 'bad' }- }- if (words.length === 1 && (words[0] === 'on' || words[0] === 'off')) return { kind: words[0] }- if (words[0] === 'size' && words.length === 2 && /^\d+%?$/.test(words[1]!)) {- const percent = Number.parseInt(words[1]!, 10)- if (percent >= MIN_SIZE && percent <= MAX_SIZE) return { kind: 'size', percent }- }- return { kind: 'bad' }-}--// A theme folder's name: letters, digits, `.`, `_`, `-`.-export const isThemeName = (name: string) => /^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(name)--// `syntax`: the tmTheme file theme.json names for a mode, relative to the-// theme folder; a mode it does not name uses the base theme's file.-export type ThemeSyntax = Partial<Record<(typeof MODES)[number], string>>-export type ThemeInfo = { name: string; dir: string; isUser: boolean; title: string; description: string; syntax: ThemeSyntax }-export type ThemeProblem = { name: string; dir: string; isUser: boolean; reason: string }--// One theme folder from its theme.json text: usable, or why not.-export function themeEntry(name: string, dir: string, isUser: boolean, json: string): ThemeInfo | ThemeProblem {- if (!isThemeName(name)) return { name, dir, isUser, reason: 'the folder name has characters other than letters, digits, ., _ and -' }- let data: unknown- try {- data = JSON.parse(json)- } catch (err) {- return { name, dir, isUser, reason: `theme.json is not valid JSON (${err instanceof Error ? err.message : String(err)})` }- }- if (!data || typeof data !== 'object' || Array.isArray(data)) return { name, dir, isUser, reason: 'theme.json is not a JSON object' }- const field = (key: string) => {- const v = (data as Record<string, unknown>)[key]- return typeof v === 'string' ? v : ''- }- const named = (data as Record<string, unknown>).syntax- const syntax: ThemeSyntax = {}- if (named !== undefined) {- if (!named || typeof named !== 'object' || Array.isArray(named)) return { name, dir, isUser, reason: '"syntax" is not an object of file names' }- for (const mode of MODES) {- const file = (named as Record<string, unknown>)[mode]- if (file === undefined) continue- if (!isSyntaxPath(file)) return { name, dir, isUser, reason: `"syntax.${mode}" must be a file name in the theme folder (no "/" at the start, no "..")` }- syntax[mode] = file- }- }- return { name, dir, isUser, title: field('name') || name, description: field('description'), syntax }-}--// A tmTheme path in theme.json: relative to the theme folder and inside it.-export const isSyntaxPath = (file: unknown): file is string =>- typeof file === 'string' && file.trim() !== '' && !file.startsWith('/') && !file.includes('\\') && !file.split('/').includes('..')--// The files a theme's pictures depend on: its theme.json, the base-// theme.json it merges over, and for each mode the tmTheme it names, else-// the base theme's. A missing `theme` (not found yet) counts as the base.-export function themeFiles(theme: ThemeInfo | undefined, base: ThemeInfo | undefined, root: string): string[] {- const baseDir = base?.dir ?? `${root}/render/themes/${BASE_THEME}`- const files = [`${theme?.dir ?? baseDir}/theme.json`, `${baseDir}/theme.json`]- for (const mode of MODES) {- const own = theme?.syntax[mode]- files.push(own ? `${theme!.dir}/${own}` : `${baseDir}/${base?.syntax[mode] ?? `${mode}.tmTheme`}`)- }- return files-}--// Built-in themes, then user themes: a usable user theme replaces the-// built-in of the same name; a broken one is only reported.-export function pickThemes(found: readonly (ThemeInfo | ThemeProblem)[]): { themes: Map<string, ThemeInfo>; problems: ThemeProblem[] } {- const themes = new Map<string, ThemeInfo>()- const problems: ThemeProblem[] = []- for (const isUser of [false, true]) {- for (const one of found) {- if (one.isUser !== isUser) continue- if ('reason' in one) problems.push(one)- else themes.set(one.name, one)- }- }- return { themes, problems }-}--// The theme to draw with: the wanted one, else the default theme, else the-// base theme (`isFallback`). The base theme's own folder is used even before-// it is found on disk.-export function chooseTheme(themes: ReadonlyMap<string, ThemeInfo>, wanted: string, root: string): { name: string; dir: string; isFallback: boolean } {- const got = themes.get(wanted)- if (got) return { name: got.name, dir: got.dir, isFallback: false }- const fallback = themes.get(DEFAULT_THEME)- if (fallback) return { name: fallback.name, dir: fallback.dir, isFallback: true }- const base = themes.get(BASE_THEME)- return { name: BASE_THEME, dir: base?.dir ?? `${root}/render/themes/${BASE_THEME}`, isFallback: wanted !== BASE_THEME }-}--// What `/md-preview theme` lists.-export function themeListing(themes: ReadonlyMap<string, ThemeInfo>, problems: readonly ThemeProblem[], active: string, userDir: string): string {- const lines = [...themes.values()]- .sort((a, b) => a.name.localeCompare(b.name))- .map(t => `${t.name === active ? '*' : '-'} ${t.name} (${t.isUser ? 'user' : 'built-in'})${t.description ? `: ${t.description}` : ''}`)- const skipped = problems.map(p => ` skipped ${p.name} (${p.isUser ? 'user' : 'built-in'}): ${p.reason}`)- return [- `Themes (* = active):`,- ...(lines.length ? lines : ['- none found']),- ...skipped,- `User themes go in ${userDir}/<name>/theme.json. Switch with /md-preview theme <name>.`,- ].join('\n')-}--// Every input a picture depends on, as one key.-export function renderKey(o: {- textHash: string- columns: number- cell: Cell- size: number- mode: MdPreviewTheme- termFont: string- columnPt: number- templateStamp: string- look: Look-}): string {- return hashOf([- o.textHash, o.columns, o.cell.width, o.cell.height, o.size, o.mode, o.termFont, o.columnPt,- o.templateStamp, o.look.name, o.look.dir, o.look.stamp, TEMPLATE_VERSION,- ])-}--// Where the first line of a page's text lies with no top margin, in the-// template's pt (measured from its PNGs at 11 pt body text): the centre of-// its ink, and the top of its ink. By what the answer starts with.-export type FirstLine = 'para' | 'h1' | 'h2' | 'h3' | 'h4' | 'quote' | 'code' | 'table'-const FIRST_LINE: Record<FirstLine, { centre: number; inkTop: number }> = {- para: { centre: 7.45, inkTop: 2.55 },- h1: { centre: 20.36, inkTop: 5.82 },- h2: { centre: 13.09, inkTop: 3.64 },- h3: { centre: 9.09, inkTop: 2.55 },- h4: { centre: 7.27, inkTop: 2.18 },- quote: { centre: 13.45, inkTop: 8.36 },- code: { centre: 17.09, inkTop: 12.36 },- table: { centre: 11.27, inkTop: 6.18 },-}--export function firstLineOf(md: string): FirstLine {- const line = md.split('\n').find(l => l.trim()) ?? ''- const heading = /^ {0,3}(#{1,6})\s/.exec(line)- if (heading) return (['h1', 'h2', 'h3'] as const)[heading[1]!.length - 1] ?? 'h4'- if (/^ {0,3}>/.test(line)) return 'quote'- if (FENCE.test(line)) return 'code'- if (/^ {0,3}\|/.test(line)) return 'table'- return 'para'-}--// The first page's top margin (pt, may be negative) that puts the centre of-// the first line of text on the centre of a terminal row, and which row that-// is: row 0 when the line fits there, else the first row its ink can reach-// without being cut at the picture's top. The bullet is drawn on that row.-export function alignFirstLine(kind: FirstLine, rowPt: number): { topPt: number; bulletRow: number } {- const { centre, inkTop } = FIRST_LINE[kind]- const bulletRow = Math.max(0, Math.ceil((centre - inkTop + 0.5) / rowPt - 0.5 - 1e-9))- 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)))-}--// 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 {- const [rows, columns, x, y] = stdout.trim().split(/\s+/).map(Number)- if (!rows || !columns || !x || !y) return null- const width = x / columns- const height = y / rows- return width >= 4 && width <= 64 && height >= 4 ? { width, height } : null-}--// "MesloLGS-NF-Regular 14" (iTerm2's Normal Font) → PostScript name and size.-export function parseFontSpec(spec: string): { name: string; size: number } | null {- const m = /^\s*(\S.*?)\s+(\d+(?:\.\d+)?)\s*$/.exec(spec)- return m ? { name: m[1]!, size: Number(m[2]) } : null-}+// ---- Pictures under rows -----------------------------------------------------// The Normal Font of the iTerm2 profile in use: the bookmark named-// ITERM_PROFILE, else the default bookmark. `bookmarks` is the JSON of the-// plist's "New Bookmarks" array.-export function itermFontOf(bookmarks: string, profile: string | undefined, defaultGuid: string): string | null {- let list: unknown- try {- list = JSON.parse(bookmarks)- } catch {+// 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> {+ if (!(await read($, isOn))) return null+ // Read so the end of setUp draws this row again.+ await read($, done)+ if (!S.env) {+ void setUp($).catch(() => undefined)return null}- if (!Array.isArray(list)) return null- type Mark = { Name?: unknown; Guid?: unknown; 'Normal Font'?: unknown }- const marks = list.filter((x): x is Mark => !!x && typeof x === 'object')- const mark = (profile ? marks.find(b => b.Name === profile) : undefined) ?? marks.find(b => b.Guid === defaultGuid.trim())- const font = mark?.['Normal Font']- return typeof font === 'string' && font.trim() ? font.trim() : null-}--// The first `font-family = X` of `ghostty +show-config`.-export function ghosttyFontOf(config: string): string | null {- for (const line of config.split('\n')) {- const m = /^\s*font-family\s*=\s*(.*?)\s*$/.exec(line)- const family = m?.[1]?.replace(/^"(.*)"$/, '$1').trim()- if (family) return family- }- return null-}--// The typst command and its environment. Network off (see NO_NETWORK) and a-// package cache of our own, so only the vendored packages load.-export function typstCall(o: {- typst: string- root: string- cache: string- ppi: number- inputs: Readonly<Record<string, string | number>>- out: string-}): { argv: string[]; env: Record<string, string> } {- const argv = [- o.typst, 'compile',- '--root', '/',- '--package-path', `${o.root}/render/packages`,- '--format', 'png',- '--diagnostic-format', 'short',- '--ppi', o.ppi.toFixed(4),- ...Object.entries(o.inputs).flatMap(([k, v]) => ['--input', `${k}=${v}`]),- `${o.root}/render/md.typ`,- o.out,- ]- return { argv, env: noNetworkEnv(o.cache) }-}--export function noNetworkEnv(cache: string): Record<string, string> {- return {- HTTPS_PROXY: NO_NETWORK,- HTTP_PROXY: NO_NETWORK,- ALL_PROXY: NO_NETWORK,- https_proxy: NO_NETWORK,- http_proxy: NO_NETWORK,- all_proxy: NO_NETWORK,- NO_PROXY: '',- no_proxy: '',- TYPST_PACKAGE_CACHE_PATH: `${cache}/pkg-cache`,- }-}--// Width and height from a PNG's first 24 bytes (signature, then IHDR).-export function pngSize(bytes: readonly number[]): { width: number; height: number } | null {- const sig = [0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a]- if (bytes.length < 24 || sig.some((v, i) => bytes[i] !== v)) return null- const at = (i: number) => ((bytes[i]! << 24) | (bytes[i + 1]! << 16) | (bytes[i + 2]! << 8) | bytes[i + 3]!) >>> 0- const width = at(16)- const height = at(20)- return width && height ? { width, height } : null-}--// `od -An -v -tx1` output for several files, each followed by a line `@`.-export function parseOd(stdout: string): number[][] {- return stdout- .split(/^@$/m)- .slice(0, -1)- .map(part => part.split(/\s+/).filter(Boolean).map(hex => Number.parseInt(hex, 16)))-}--// A set flag: anything but empty, 0, false, no or off.-export const isSet = (value: string | undefined) => !!value && !/^(0|false|no|off)$/i.test(value.trim())--// Whether the engine draws pictures here; elsewhere an Image shows only its-// alt, so the text is better. Claude Code turns kitty graphics on by itself-// only for kitty and Ghostty; any other terminal draws only when-// CLAUDE_CODE_FORCE_TERMINAL_IMAGES is set, and tmux or screen only then.-// Over ssh the terminal can't read our files, so only MD_PREVIEW_FORCE draws.-export function canDrawIn(env: { program: string; term: string; kitty: boolean; tmux: boolean; ssh: boolean; engineForced: boolean; modForced: boolean }): boolean {- if (env.ssh) return env.modForced- if (env.engineForced || env.modForced) return true- if (env.tmux) return false- return /ghostty/i.test(env.program + env.term) || /kitty/i.test(env.term) || env.kitty-}--const FENCE = /^( {0,3})(`{3,}|~{3,})\s*([^\s`]*)/-export const isTypstInfo = (info: string) => /^(typst|typ)$/i.test(info)-// Any failed compile is tried once more with `safe=1`: the template then-// shows typst fences and math as code and images as alt boxes, which is how-// a bad typst block or an unknown LaTeX command still draws.-export function shouldRetrySafe(exitCode: number): boolean {- return exitCode !== 0-}--// One block of Markdown: lines between blank lines outside fences, or one-// fenced block that starts at the margin.-export type Block = { lines: string[]; fence?: { mark: string; info: string }; isMath?: boolean }--export function blocksOf(md: string): Block[] {- const blocks: Block[] = []- let cur: Block | null = null- let open: { char: string; len: number } | null = null- let inMath = false- const close = () => {- if (cur && cur.lines.length) blocks.push(cur)- cur = null- }- for (const line of md.replace(/\r\n?/g, '\n').split('\n')) {- if (open) {- cur!.lines.push(line)- const m = FENCE.exec(line)- if (m && m[2]![0] === open.char && m[2]!.length >= open.len && line.trim() === m[2]) {- open = null- if (cur!.fence) close()- }- continue- }- if (inMath) {- cur!.lines.push(line)- if (line.trim() === '$$') inMath = false- continue- }- const m = FENCE.exec(line)- if (m) {- open = { char: m[2]![0]!, len: m[2]!.length }- // A fence at the margin is a block of its own; an indented one (in a- // list item) stays with the item.- if (m[1] === '') {- close()- cur = { lines: [line], fence: { mark: m[2]!, info: m[3] ?? '' } }- } else (cur ??= { lines: [] }).lines.push(line)- continue- }- if (line.trim() === '') {- close()- continue- }- ;(cur ??= { lines: [] }).lines.push(line)- if (line.trim() === '$$') {- inMath = true- cur.isMath = true- }- }- close()- return blocks-}--// A rough count of the rows a block takes once drawn `columns` wide.-export function rowsOfBlock(block: Block, columns: number): number {- const isCode = !!block.fence- const perRow = columns * (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- }- if (block.fence && isTypstInfo(block.fence.info)) rows += 20- return rows-}--const LINK_DEF = /^ {0,3}\[(?!\^)[^\]]+\]:\s*\S/-const FOOTNOTE_DEF = /^ {0,3}\[\^[^\]]+\]:/--// Splits an answer into segments of about `budget` rows at block boundaries.-// A fence is never split, but a long plain code fence is cut into several-// 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[] {- const blocks = blocksOf(md)- if (!blocks.length) return []- const outside = blocks.filter(b => !b.fence).flatMap(b => b.lines)- if (outside.some(line => FOOTNOTE_DEF.test(line))) return [md]- const defs = outside.filter(line => LINK_DEF.test(line))-- const pieces: Block[] = []- for (const block of blocks) {- const { fence } = block- if (fence && !isTypstInfo(fence.info) && rowsOfBlock(block, columns) > 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)- for (let i = 0; i < body.length; i += per) {- pieces.push({ lines: [block.lines[0]!, ...body.slice(i, i + per), fence.mark], fence })- }- } else pieces.push(block)- }-- const segments: Block[][] = [[]]- let used = 0- for (const piece of pieces) {- const need = rowsOfBlock(piece, columns)- const canCut = !/^\s/.test(piece.lines[0] ?? '')- if (used + need > budget && segments.at(-1)!.length && canCut) {- segments.push([])- used = 0- }- segments.at(-1)!.push(piece)- used += need- }- const texts = segments.map(seg => seg.map(b => b.lines.join('\n')).join('\n\n'))- if (texts.length < 2 || !defs.length) return texts- return texts.map(t => `${t}\n\n${defs.filter(d => !t.includes(d)).join('\n')}`.trimEnd())-}--// The local image paths Markdown names outside code fences.-const IMAGE = /!\[([^\]]*)\]\(\s*<?([^)\s>]+)>?(?:\s+"[^"]*")?\s*\)/g--export function localImages(md: string): string[] {- const found: string[] = []- let open: { char: string; len: number } | null = null- for (const line of md.split('\n')) {- const m = FENCE.exec(line)- if (open) {- if (m && m[2]![0] === open.char && m[2]!.length >= open.len && line.trim() === m[2]) open = null- } else if (m) open = { char: m[2]![0]!, len: m[2]!.length }- else for (const ref of line.matchAll(IMAGE)) if (!/^[a-z][a-z0-9+.-]*:/i.test(ref[2]!) || /^file:/i.test(ref[2]!)) found.push(ref[2]!)- }- return found-}--// Where an image path leads, as the template resolves it: `file://` dropped,-// `%20` a space, a relative path joined to `base`.-export function imagePathOf(path: string, base: string): string {- const plain = path.trim().replace(/^file:\/\//i, '').replace(/%20/g, ' ')- return plain.startsWith('/') ? plain : `${base.replace(/\/+$/, '')}/${plain.replace(/^\.\//, '')}`-}--// A short one-line plain text of some Markdown, for an Image's alt.-export function plainOf(md: string, max = ALT_CHARS): string {- const flat = md- .replace(/^ {0,3}(`{3,}|~{3,}).*$/gm, ' ')- .replace(/!\[([^\]]*)\]\([^)]*\)/g, '$1')- .replace(/\[([^\]]*)\]\([^)]*\)/g, '$1')- .replace(/<[^>]+>/g, ' ')- .replace(/^\s{0,3}(#{1,6}|>+|[-*+]|\d+[.)])\s+/gm, '')- .replace(/[*_`~|]+/g, '')- .replace(/\s+/g, ' ')- .trim()- return flat.length > max ? `${flat.slice(0, max - 1).trimEnd()}…` : flat || ' '-}--export const firstLine = (text: string) => text.split('\n').find(l => l.trim())?.trim() ?? ''--// ---- Work on the host -------------------------------------------------------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))'`-// 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)"; }`-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.-const FAMILY_JXA = 'function run(argv) { ObjC.import("AppKit"); var f = $.NSFont.fontWithNameSize(argv[0], 12); return f.isNil() ? "" : f.familyName.js }'-const GHOSTTY_SH = `"\${GHOSTTY_BIN_DIR:+\$GHOSTTY_BIN_DIR/}ghostty" +show-config`-const HEADERS_SH = `for f in "$@"; do head -c 24 "$f" | od -An -v -tx1; echo @; done`--// /md-preview; registered at session start and again in setUp, so it is-// there after a hot reload too.-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), theme [name] (list or switch themes)",- argumentHint: '[on|off|size <percent>|theme [name]]',- }).catch(() => undefined)-}--// Redraws every reader of `done`; an invalidate where the write is refused.-function refresh($: EngineInterface) {- void update($, done, n => n + 1).catch(() => $.ui.invalidate('ui.render'))-}--async function findTypst($: EngineInterface): Promise<string | null> {- for (const flag of ['-lc', '-c']) {- const got = await $.process.run(['sh', flag, 'command -v typst'], { timeoutMs: 5000 }).catch(() => null)- const path = got?.exitCode === 0 ? firstLine(got.stdout) : ''- if (path.startsWith('/')) return path- }- const home = (await $.env.get('HOME').catch(() => undefined)) ?? ''- for (const each of TYPST_FALLBACKS) {- if (each.startsWith('~/') && !home) continue- const path = each.startsWith('~/') ? `${home}${each.slice(1)}` : each- if (await $.fs.exists(path).catch(() => false)) return path- }- return null-}--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;-// '' elsewhere or when it can't be read.-async function termFontOf($: EngineInterface, program: string, isMac: boolean): Promise<string> {- if (/^iTerm/i.test(program) && isMac) {- const profile = await $.env.get('ITERM_PROFILE')- const [marks, guid] = await Promise.all([- $.process.run(['sh', '-c', ITERM_BOOKMARKS_SH], { timeoutMs: 5000 }).catch(() => null),- $.process.run(['sh', '-c', ITERM_DEFAULT_SH], { timeoutMs: 5000 }).catch(() => null),- ])- const spec = parseFontSpec(itermFontOf(marks?.stdout ?? '', profile, guid?.stdout ?? '') ?? '')- if (!spec) return ''- const named = await $.process.run(['osascript', '-l', 'JavaScript', '-e', FAMILY_JXA, spec.name], { timeoutMs: 5000 }).catch(() => null)- return named?.exitCode === 0 ? firstLine(named.stdout) : ''- }- if (/ghostty/i.test(program)) {- const shown = await $.process.run(['sh', '-c', GHOSTTY_SH], { timeoutMs: 5000 }).catch(() => null)- return ghosttyFontOf(shown?.stdout ?? '') ?? ''- }- return ''-}--// The argv that measures the fonts: the active theme's body and code fonts-// (theme.typ reads theme.json, which needs `--root /`).-export const measureCall = (typst: string, root: string, family: string, themeDir: string) => [- typst, 'eval', 'query(<m>).first().value', '--in', `${root}/render/measure.typ`, '--root', '/',- '--input', `term-font=${family}`, '--input', `theme-dir=${themeDir}`,-]--// The fonts' metrics from render/measure.typ; the macOS defaults when that fails.-async function measureFonts($: EngineInterface, typst: string, root: string, cache: string, family: string, themeDir: string): Promise<Metrics> {- const argv = measureCall(typst, root, family, themeDir)- const got = await $.process.run(argv, { timeoutMs: 10000, env: noNetworkEnv(cache) }).catch(() => null)- try {- const m = JSON.parse(got?.stdout ?? '') as Metrics- const ok = (x: FontMetrics | null | undefined) => !!x && x.adv > 0 && x.xh > 0 && x.avg > 0- if (ok(m.menlo) && ok(m.body)) return { term: ok(m.term) ? m.term : null, menlo: m.menlo, body: m.body }- } catch {}- return DEFAULT_METRICS-}--// The built-in themes under render/themes and the user's under-// ~/.claude/md-preview/themes, read fresh each call.-async function scanThemes($: EngineInterface, root: string, home: string) {- const found: (ThemeInfo | ThemeProblem)[] = []- for (const [base, isUser] of [[`${root}/render/themes`, false], [userThemesOf(home), true]] as const) {- const entries = await $.fs.list(base).catch(() => [])- for (const entry of entries) {- if (entry.kind === 'file') continue- const dir = `${base}/${entry.name}`- const json = await $.fs.read(`${dir}/theme.json`).catch(() => null)- if (json === null) continue- const one = themeEntry(entry.name, dir, isUser, json)- const lost = 'reason' in one ? [] : await missingSyntax($, one)- found.push(lost.length ? { name: one.name, dir, isUser, reason: `theme.json names syntax files that do not exist: ${lost.join(', ')}` } : one)- }- }- return pickThemes(found)-}--// The syntax files a theme names that are not on disk (they fail the compile).-async function missingSyntax($: EngineInterface, theme: ThemeInfo) {- const lost: string[] = []- for (const mode of MODES) {- const file = theme.syntax[mode]- if (file && !(await $.fs.exists(`${theme.dir}/${file}`).catch(() => false))) lost.push(file)- }- return lost-}--const userThemesOf = (home: string) => `${home || '~'}/.claude/md-preview/themes`--// The mtimes of the files a theme's pictures depend on (themeFiles): a-// change to any of them makes new keys.-async function stampTheme($: EngineInterface, files: readonly string[]): Promise<string> {- const times: string[] = []- for (const file of files) {- const stat = await $.fs.stat(file).catch(() => null)- times.push(String(stat?.mtimeMs ?? 0))- }- return times.join(',')-}--// Picks the stored theme (or the default one), sets `look`, and says when the-// stored one was not usable.-async function applyTheme($: EngineInterface, root: string, home: string, wanted: string) {- const { themes, problems } = await scanThemes($, root, home)- const chosen = chooseTheme(themes, wanted, root)- // theme.typ always merges over the built-in vscode, also when a user theme- // has that name, so the stamp uses the built-in one.- const builtIn = themes.get(BASE_THEME)- const files = themeFiles(themes.get(chosen.name), builtIn?.isUser ? undefined : builtIn, root)- look = { name: chosen.name, dir: chosen.dir, stamp: await stampTheme($, files) }- return { themes, problems, chosen }-}--// 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.-function setUp($: EngineInterface): Promise<Env> {- envLoading ??= (async () => {- await registerCommand($)- const made = await $.process.run(['sh', '-c', CACHE_SH]).catch(() => null)- const [made1 = '', os = ''] = (made?.stdout ?? '').split('\n')- const cache = made1.trim() || '/tmp/md-preview'- const program = (await $.env.get('TERM_PROGRAM')) ?? ''- const term = (await $.env.get('TERM')) ?? ''- const canDraw = canDrawIn({- program,- term,- kitty: !!(await $.env.get('KITTY_WINDOW_ID')),- tmux: !!(await $.env.get('TMUX')) || /^tmux|^screen/i.test(term),- ssh: !!(await $.env.get('SSH_CONNECTION')) || !!(await $.env.get('SSH_TTY')),- engineForced: isSet(await $.env.get('CLAUDE_CODE_FORCE_TERMINAL_IMAGES')),- modForced: isSet(await $.env.get('MD_PREVIEW_FORCE')),- })- const root = $.plugin.root- const template = await $.fs.stat(`${root}/render/md.typ`).catch(() => null)- const rows = await $.config.list().catch(() => [])- theme = themeOf(rows.find(row => row.key === 'theme')?.value)- const kept = Number(await $.store.get('size').catch(() => undefined))- size = kept >= MIN_SIZE && kept <= MAX_SIZE ? kept : DEFAULT_SIZE- if ((await $.store.get('enabled').catch(() => undefined)) === false) await update($, isOn, () => false).catch(() => undefined)- const isMac = os.trim() === 'Darwin'- cell = await measureCell($)- const typst = await findTypst($)- if (!typst) {- try {- $.ui.toast(NO_TYPST, { timeoutMs: 8000 })- } catch {}- }- const termFont = await termFontOf($, program, isMac).catch(() => '')- const home = (await $.env.get('HOME')) ?? ''- 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)- if (!applied) look = { name: BASE_THEME, dir: `${root}/render/themes/${BASE_THEME}`, stamp: '0' }- else if (applied.chosen.isFallback) {- try {- $.ui.toast(`md-preview: theme ${wanted} not found, using ${applied.chosen.name}`, { timeoutMs: 8000 })- } catch {}- }- env = {- typst,- canDraw,- cache,- cwd: await $.session.cwd().catch(() => '/'),- root,- isMac,- stamp: String(template?.mtimeMs ?? 0),- home,- termFont,- metrics: typst ? await measureFonts($, typst, root, cache, termFont, look?.dir ?? `${root}/render/themes/${BASE_THEME}`) : DEFAULT_METRICS,- }- refresh($)- return env- })().catch((err: unknown) => {- envLoading = null- throw err- })- return 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.-function noteViewport($: EngineInterface, view: { columns: number; rows: number }) {- const seen = `${view.columns}x${view.rows}`- if (seen === lastView) return- const isFirst = lastView === ''- lastView = seen- if (isFirst || !env) return- measureTimer?.cancel()- measureTimer = $.clock.after(1000, () => {- void measureCell($).then(next => {- if (next?.width === cell?.width && next?.height === cell?.height) return- cell = next- refresh($)- })- })-}--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)-}--// 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.-async function existingImages($: EngineInterface, segments: readonly string[], base: string): Promise<string[]> {- const found: string[] = []- for (const path of new Set(segments.flatMap(localImages))) {- const full = imagePathOf(path, base)- if (await $.fs.exists(full).catch(() => false)) found.push(path, full)- }- return found-}--async function runTypst($: EngineInterface, job: Job, segments: readonly string[], dir: string, tag: string, isSafe: boolean) {- 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)- const { argv, env: vars } = typstCall({- typst: job.env.typst!,- root: job.env.root,- cache: job.env.cache,- ppi,- inputs: {- theme: job.theme,- width: widthPt,- top: topPt,- row: Math.round(rowPt * 10000) / 10000,- code: fit.code,- ...(job.env.termFont ? { 'term-font': job.env.termFont } : {}),- 'theme-dir': job.themeDir,- doc: `${dir}/doc.json`,- ...(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)}` }))-}--async function compile($: EngineInterface, job: Job): Promise<Result | 'failed'> {- 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 segments = splitSegments(job.text, job.columns)- const images = await existingImages($, segments, job.env.cwd)- await $.fs.write(`${dir}/doc.json`, JSON.stringify({ base: job.env.cwd, segments, images }))-- let tag = 'a'- let ran = await runTypst($, job, segments, dir, tag, false)- let note: string | undefined- if (ran.exitCode !== 0) {- 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)- 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'- }- 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 } : {}) }- await $.fs.write(`${dir}/pages.json`, JSON.stringify(result))- return result+ if (!S.env.canDraw) return null+ if (e.viewport) noteViewport($, e.viewport)+ return S.env}-function pump($: EngineInterface) {- while (running.size < MAX_RUNNING && queue.length) {- const job = queue.shift()!- running.add(job.key)- void compile($, job)- .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($)- pump($)- })- }-}--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.- const stale = queue.findIndex(j => j.requestId === job.requestId || j.key === job.key)- if (stale >= 0) queue.splice(stale, 1)- queue.push(job)- pump($)+// 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> {+ const ready = await pictureEnv($, e)+ return ready?.typst ? ready : null}-// Compiles once the message's text has been still for SETTLE_MS.-function schedule($: EngineInterface, job: Job) {- const was = timers.get(job.requestId)- if (was?.key === job.key) return- was?.cancel()- const timer = $.clock.after(SETTLE_MS, () => {- timers.delete(job.requestId)- enqueue($, job)- })- timers.set(job.requestId, { key: job.key, cancel: () => timer.cancel() })-}--type Drawn = RenderInput<'AssistantMessage', 'terminal'>--function drawPages($: EngineInterface, e: Drawn, result: Result, columns: number, px: Cell) {- const { Box, Text, Image } = $.ui.resolve(e)- return (- <Box flexDirection="row" marginTop={MARGIN_TOP}>- <Box width={GUTTER} flexShrink={0} marginTop={result.bulletRow}>- <Text>{e.props.isFirstOfReply ? bulletOf(env?.isMac ?? true) : ' '}</Text>- </Box>- <Box flexDirection="column">- {result.pages.map((page, i) => {- const rows = rowsFor(page, columns, px)- return (- <Image- key={`p${i}`}- source={{ file: page.file, format: 'png', generation: columns * 1000 + rows }}- columns={columns}- rows={rows}- alt={page.alt}- />- )- })}- {result.note ? <Text dimColor wrap="truncate-end">Typst error: {result.note}</Text> : null}- </Box>- </Box>- )+// md-preview's own plan question: only on the main loop of a session drawn+// in a terminal, with md-preview on, Typst found and a terminal that draws+// (the plan's pictures need all of them). Null otherwise: the engine's+// dialog asks, as with no mod.+async function planEnv($: EngineInterface): Promise<Env | null> {+ if (!(await read($, isOn))) return null+ const surfaces = await $.session.surfaces().catch(() => [] as readonly string[])+ if (!surfaces.includes('terminal')) return null+ const ready = S.env ?? (await setUp($).catch(() => null))+ return ready?.typst && ready.canDraw ? ready : null}// ---- Hooks ----------------------------------------------------------------@@ -1029,6 +117,15 @@ export const register: Register = on => {return next(e)})+ // Typeahead for /md-preview arguments; the theme list is the last scan's.+ on('prompt.autocomplete', async ($, e, next) => {+ const got = await next(e)+ if (!/^\s*\/md-preview\s/.test(e.text)) return got+ if (!S.themeChoices.length) await setUp($).catch(() => null)+ const mine = commandSuggestions(e.text, e.token, e.start, { themes: S.themeChoices, active: S.look?.name ?? DEFAULT_THEME, size: S.size })+ return mine.length ? { suggestions: [...got.suggestions, ...mine] } : got+ })+on('command.run', { command: 'md-preview' }, async ($, e) => {const asked = parseCommand(e.args)if (asked.kind === 'on' || asked.kind === 'off') {@@ -1037,25 +134,41 @@ export const register: Register = on => {return { text: `md-preview is ${asked.kind}.` }}if (asked.kind === 'size') {- size = asked.percent- await $.store.set('size', size)+ S.size = asked.percent+ await $.store.set('size', S.size)refresh($)- return { text: `md-preview draws text at ${size}% of the terminal's text size (100% matches it).` }+ return { text: `md-preview draws text at ${S.size}% of the terminal's text size (100% matches it).` }+ }+ if (asked.kind === 'setup') {+ await setUp($).catch(() => null)+ return { text: await runSetup($, asked.remove) }+ }+ if (asked.kind === 'probe') {+ // A debug check: does the terminal's OSC 11 answer reach the mod?+ const lines: string[] = []+ for (let i = 1; i <= PROBE_RUNS; i++) {+ const got = await probeOsc11($)+ const bg = got ? parseOsc11(got.reply) : null+ const what = !got ? 'could not open /dev/tty' : !got.reply ? 'no answer in 300 ms' : `"${escapeControls(got.reply)}"`+ const mode = bg ? ` -> luminance ${luminanceOf(bg).toFixed(3)}, ${modeOfLuminance(luminanceOf(bg))}` : got?.reply ? ' -> not an OSC 11 answer' : ''+ lines.push(`${i}: ${what}${mode}`)+ }+ return { text: `OSC 11 probe (the terminal's background), ${PROBE_RUNS} runs:\n${lines.join('\n')}\nThe poll uses it: ${USE_OSC11 ? 'yes' : 'no (off)'}.` }}if (asked.kind === 'theme') {const ready = await setUp($)- const was = look- const wanted = asked.name ?? look?.name ?? DEFAULT_THEME+ const was = S.look+ const wanted = asked.name ?? S.look?.name ?? DEFAULT_THEMEconst { themes, problems, chosen } = await applyTheme($, ready.root, ready.home, wanted)if (asked.name && chosen.isFallback) {- if (was) look = was+ if (was) S.look = wasconst 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 (look?.name !== was?.name || look?.dir !== was?.dir || look?.stamp !== was?.stamp) {+ 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 && look) ready.metrics = await measureFonts($, ready.typst, ready.root, ready.cache, ready.termFont, look.dir)+ if (ready.typst && S.look) ready.metrics = await measureFonts($, ready.typst, ready.root, ready.cache, ready.termFont, S.look.dir)refresh($)}const head = asked.name ? `md-preview uses the theme ${chosen.name}.\n` : ''@@ -1065,58 +178,279 @@ export const register: Register = on => {const ready = await setUp($)const font = ready.termFont ? `terminal font ${ready.termFont}` : 'terminal font not known (Menlo assumed)'const typst = ready.typst ? `Typst: ${ready.typst}` : 'Typst: not found (brew install typst)'- const terminal = ready.canDraw ? 'this terminal draws pictures' : 'Claude Code draws no pictures here (it does in kitty and Ghostty, elsewhere with CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1, never in tmux or over ssh), so answers stay text'+ const terminal = ready.canDraw+ ? `this terminal draws pictures${ready.inline ? ' (over ssh, sent as bytes)' : ''}`+ : 'Claude Code draws no pictures here (it does in kitty and Ghostty, in iTerm2 3.6+ and Rio 0.5.27+ with CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1, over ssh when TERM names kitty or Ghostty or with that variable; never in tmux, screen or a background session; not in WezTerm, Warp, Konsole or others), so answers stay text'+ 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}>, or /md-preview theme [name].`const bad = asked.kind === 'bad' ? `Not understood: "${e.args.trim()}". ` : ''- return { text: `${bad}md-preview is ${state}, theme ${look?.name ?? DEFAULT_THEME}, text size ${size}%, ${font}. ${typst}; ${terminal}. ${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}%, ${font}. ${typst}; ${terminal}.${tried} ${usage}` }})on('config.set', { key: 'theme' }, async ($, e, next) => {const set = await next(e)- if (set.value !== undefined && themeOf(set.value) !== theme) {- theme = themeOf(set.value)- refresh($)- }+ if (set.value === undefined) return set+ S.settingRaw = typeof set.value === 'string' ? set.value : ''+ S.setting = settingOf(set.value)+ // Not awaited: the setting is saved at once; the OS read redraws later.+ if (S.setting === 'auto') void pollHost($).catch(() => undefined)+ else showMode($)+ watchHost($)return set}).catch(($, e, next) => next(e))on('prompt.compose', async ($, e, next) => {const composed = await next(e)if (!e.surfaces.includes('terminal') || !(await read($, isOn))) return composed- const ready = env ?? (await setUp($).catch(() => null))+ const ready = S.env ?? (await setUp($).catch(() => null))if (!ready?.typst || !ready.canDraw) return composedreturn { sections: [...composed.sections, { id: 'md-preview:typst', text: TYPST_PROMPT, scope: 'session' as const }] }})+ // A main-loop model request: its text blocks are final when the next block+ // (another text block, a tool call, thinking, the stop) starts, and all of+ // them when the request ends, fails or is aborted.+ on('turn.step', async function* ($, e, next) {+ if (e.agentId) return yield* next(e)+ S.stepsLive+++ let textIndex = -1+ let isDone = false+ // Never let md-preview's own work break Claude's stream.+ const settleAll = () => {+ try {+ finalizeAll($)+ } catch {}+ }+ const stream = next(e)+ try {+ for (;;) {+ const step = await stream.next()+ if (step.done) {+ isDone = true+ return step.value+ }+ const chunk = step.value+ if (chunk.kind === 'text') {+ if (textIndex >= 0 && chunk.index !== textIndex) settleAll()+ textIndex = chunk.index+ } else if (chunk.kind !== 'engine' && textIndex >= 0) {+ settleAll()+ textIndex = -1+ }+ yield chunk+ }+ } finally {+ // Closed early (Esc, an error below): close the stream beneath too, as+ // `yield*` would.+ if (!isDone) {+ try {+ await stream.return?.(undefined as never)+ } catch {}+ }+ S.stepsLive = Math.max(0, S.stepsLive - 1)+ settleAll()+ }+ })++ // Esc: the cut block is final too (the step's own end also says so).+ on('turn.abort', async ($, e, next) => {+ const aborted = await next(e)+ try {+ finalizeAll($)+ } catch {}+ return aborted+ }).catch(($, e, next) => next(e))+on('ui.render', { component: 'AssistantMessage' }, async ($, e, next) => {if (e.surface !== 'terminal' || e.props.isSummary || !e.props.text.trim()) return next(e)- if (!(await read($, isOn))) return next(e)- // Read so a finished render draws this message again.- await read($, done)- if (!env) {- void setUp($).catch(() => undefined)- return next(e)+ const ready = await answerEnv($, e)+ if (!ready) return next(e)+ const columns = columnsFor(e.viewport?.columns)+ 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 })+ if (drawing.kind === 'text') return next(e)+ const { Box } = $.ui.resolve(e)+ return <Box />+ })++ // The PNGs Claude sends with SendUserFile, under the result row that lists+ // them. Its ToolUse row draws no attachments, and the tool is never in a+ // ToolGroup, so only ToolResult is hooked and no picture draws twice.+ on('ui.render', { component: 'ToolResult' }, async ($, e, next) => {+ if (e.surface !== 'terminal' || e.props.tool !== 'SendUserFile' || e.props.isErrored) return next(e)+ let shown: Shown[] = []+ try {+ const files = sentImages(e.props.output)+ const ready = files.length ? await pictureEnv($, e) : null+ if (ready) shown = await shownOf($, e, ready, files.map(f => imagePathOf(f, ready.cwd)))+ } catch {+ shown = []}- if (!env.typst || !env.canDraw) return next(e)- if (e.viewport) noteViewport($, e.viewport)+ const row = await next(e)+ if (!shown.length) return row+ try {+ return underRow($, e, row, shown)+ } catch {+ return row+ }+ })- const columns = columnsFor(e.viewport?.columns)- const px = cell ?? DEFAULT_CELL- const textHash = hashOf([e.props.text])- const active = look ?? { name: DEFAULT_THEME, dir: `${env.root}/render/themes/${DEFAULT_THEME}`, stamp: '0' }- const key = renderKey({- textHash, columns, cell: px, size, mode: theme, termFont: env.termFont,- columnPt: fontFit(env.metrics, size).columnPt, templateStamp: env.stamp, look: active,- })- const got = results.get(key)- if (got === 'failed') return next(e)- if (got) {- shown.set(e.requestId, { textHash, result: got })- return drawPages($, e, got, columns, px)+ // The images the user pasted (`[Image #N]`), under the prompt row. Only the+ // user's own prompts: a notification's or another agent's row stays as is.+ on('ui.render', { component: 'UserMessage' }, async ($, e, next) => {+ if (e.surface !== 'terminal' || e.props.origin?.kind !== 'composer' || e.props.from || e.props.task) return next(e)+ const numbers = pastedNumbers(e.props.text)+ if (!numbers.length) return next(e)+ 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)))+ } catch {+ shown = []+ }+ const row = await next(e)+ if (!shown.length) return row+ try {+ return underRow($, e, row, shown)+ } catch {+ return row}- schedule($, { key, requestId: e.requestId, text: e.props.text, columns, cell: px, theme, size, themeDir: active.dir, env })- // Same text at another width: the old picture until the new one is ready.- const was = shown.get(e.requestId)- return was && was.textHash === textHash ? drawPages($, e, was.result, columns, px) : next(e)})++ // ---- The plan --------------------------------------------------------------++ // The main loop's running turn, which "clear context" ends.+ on('turn.start', async ($, e, next) => {+ if (e.agentId === undefined) S.mainTurnId = e.turnId+ return next(e)+ }).catch(($, e, next) => next(e))++ // The ExitPlanMode row, above the question: the engine's row, then the plan+ // as pictures, through the answers' pipeline at an answer's width (the+ // edited text once edited in md-preview's flow). A rejected, aborted or+ // subagent call, and a plan that fails to compile, stay as the engine draws.+ on('ui.render', { component: 'ToolUse', props: { tool: 'ExitPlanMode' } }, async ($, e, next) => {+ const row = await next(e)+ if (e.surface !== 'terminal' || e.props.isErrored || e.props.isInterrupted || subagentPlans.has(e.props.tool_use_id)) return row+ try {+ 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)+ const drawing = await pagesOf($, { id: `plan:${e.props.tool_use_id}`, text: plan, columns, env: ready, canStream: false })+ return drawPlanUse($, e, row, drawing, columns)+ } catch {+ return row+ }+ })++ // The approved plan's result row: the engine's repeats the plan as text+ // under its header, so while the ToolUse row draws the pictures this row+ // keeps the header alone. An errored call (a rejected plan), an empty plan+ // and a subagent's stay as the engine draws them.+ on('ui.render', { component: 'ToolResult', props: { tool: 'ExitPlanMode' } }, async ($, e, next) => {+ if (e.surface !== 'terminal' || e.props.isErrored) return next(e)+ let drawn: RenderElement | null = null+ 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)+ const drawing = ready ? await pagesOf($, { id: `plan:${e.props.tool_use_id}`, text: plan, columns, env: ready, canStream: false }) : null+ const filePath = (e.props.output as { filePath?: unknown }).filePath+ if (drawing && drawing.kind !== 'text') drawn = drawPlanResult($, e, typeof filePath === 'string' ? filePath : undefined)+ } catch {+ drawn = null+ }+ return drawn ?? next(e)+ })++ // One dim line above md-preview's own question (the dialog takes at most 12+ // rows around it, so the plan is in the row above). Any other question+ // stays as the engine draws it.+ on('ui.render', { component: 'AskUserQuestion' }, async ($, e, next) => {+ const dialog = await next(e)+ if (e.surface !== 'terminal' || !isPlanQuestion(e.props.questions, S.planAsking)) return dialog+ try {+ return drawAskLine($, e, dialog)+ } catch {+ return dialog+ }+ })++ // The main loop's Write and Edit calls while they run: the plan waits for+ // a write of its file that Claude sent with ExitPlanMode in one message.+ on('tool.call', { tool: ['Write', 'Edit'] }, async ($, e, next) => {+ const file = !e.agentId && typeof e.file_path === 'string' ? e.file_path : ''+ if (!file) return next(e)+ writesLive.set(file, (writesLive.get(file) ?? 0) + 1)+ try {+ return await next(e)+ } finally {+ const left = (writesLive.get(file) ?? 1) - 1+ if (left > 0) writesLive.set(file, left)+ else writesLive.delete(file)+ }+ }).catch(($, e, next) => next(e))++ // The main loop's ExitPlanMode: md-preview asks first (the engine shows its+ // dialog while PermissionRequest hooks run, so a question asked there waits+ // behind it). The person's words deny the call (Claude revises the plan);+ // a verdict waits for the PermissionRequest below, and is dropped once the+ // call resolves, so it never reaches a later call. No env, no plan, or a+ // failure: no verdict, and the engine's dialog asks.+ on('tool.call', { tool: 'ExitPlanMode' }, async ($, e, next) => {+ if (e.agentId) {+ subagentPlans.add(e.tool_use_id)+ return next(e)+ }+ S.planVerdict = null+ let verdict: PlanVerdict | null = null+ try {+ const ready = await planEnv($)+ const callPlan = ready ? planInputOf(e) : ''+ if (ready && callPlan) {+ const id = e.tool_use_id+ const file = planFileOf(e)+ const plan = await currentPlan($, file, callPlan)+ if (plan !== callPlan) {+ editedPlans.set(id, plan)+ refresh($)+ }+ const outcome = await decidePlan($, {+ plan, callPlan, file, isMac: ready.isMac, isRemote: S.isRemote,+ onEdited: text => {+ editedPlans.set(id, text)+ refresh($)+ },+ })+ if (outcome.kind === 'feedback') return { deny: outcome.message }+ verdict = outcome.verdict+ }+ } catch {+ verdict = null+ }+ S.planVerdict = verdict+ const turnId = S.mainTurnId+ let got: Awaited<ReturnType<typeof next>>+ try {+ got = await next(e)+ } finally {+ S.planVerdict = null+ }+ // The call has run: a failure to schedule changes nothing of its result.+ try {+ if (verdict?.kind === 'allow' && verdict.clear && got && typeof got === 'object' && !('deny' in got)) scheduleClear($, verdict.plan, turnId)+ } catch {}+ return got+ }).catch(($, e, next) => next(e))++ // The PermissionRequest of that call: md-preview's verdict at once (the+ // engine's dialog never shows), else the engine's flow.+ on('classic.PermissionRequest', async ($, e, next) => {+ if (e.tool_name !== 'ExitPlanMode' || e.agent_id || !S.planVerdict) return next(e)+ const verdict = S.planVerdict+ S.planVerdict = null+ return { decision: decisionOf(verdict, e.tool_input) }+ }).catch(($, e, next) => next(e))}diff --git a/tests/command.test.ts b/tests/command.test.tsnew file mode 100644index 0000000..71fff92--- /dev/null+++ b/tests/command.test.ts@@ -0,0 +1,60 @@+import { expect, mock, test } from 'claude-code/testing'++import { commandSuggestions, type ThemeInfo } from '../hooks/register'++const theme = (name: string, isUser = false, description = ''): ThemeInfo => ({ name, dir: `/t/${name}`, isUser, title: name, description, syntax: {} })+const themes = [theme('vscode-modern', false, 'default look'), theme('vscode'), theme('nord', true, 'my nord'), theme('github-light')]+const o = { themes, active: 'vscode-modern', size: 100 }+// The token at the end of `text`, as the engine gives it.+const at = (text: string) => {+ const token = /\S+$/.exec(text)?.[0] ?? ''+ return commandSuggestions(text, token, text.length - token.length, o)+}++test('the first word completes as a subcommand', () => {+ expect(at('/md-preview t').map(r => r.text)).toEqual(['theme'])+ expect(at('/md-preview o').map(r => r.text)).toEqual(['on', 'off'])+ expect(at('/md-preview S').map(r => r.text)).toEqual(['size', 'setup'])+ expect(at('/md-preview x')).toEqual([])+ expect(at('/md-preview t')[0]!.description).toBe('list the themes, or switch to one')+})++test('right after theme or size, rows hold the word and its argument', () => {+ const rows = at('/md-preview theme')+ expect(rows.map(r => r.text)).toEqual(['theme github-light', 'theme nord', 'theme vscode', 'theme vscode-modern'])+ expect(rows.map(r => r.label)).toEqual(['github-light', 'nord', 'vscode', 'vscode-modern'])+ expect(rows[3]!.description).toBe('built-in, active: default look')+ expect(rows[1]!.description).toBe('user: my nord')+ expect(at('/md-preview size').map(r => r.text)).toContain('size 150')+})++test('a theme name or size completes after its word', () => {+ expect(at('/md-preview theme vs').map(r => r.text)).toEqual(['vscode', 'vscode-modern'])+ expect(at('/md-preview theme N').map(r => r.text)).toEqual(['nord'])+ expect(at('/md-preview size 1').map(r => r.text)).toEqual(['100', '110', '120', '125', '150', '175'])+ expect(at('/md-preview size 10')[0]!.description).toBe('current')+ expect(at('/md-preview theme nord extra')).toEqual([])+})++test('other prompts and the command name itself get no rows', () => {+ expect(at('/md-preview')).toEqual([])+ expect(at('/md-previewx t')).toEqual([])+ expect(at('tell me about /md-preview t')).toEqual([])+ expect(at('/other theme')).toEqual([])+})++test('the hook adds theme rows from the themes found at start', async ($, on) => {+ mock.store(on)+ mock.env(on, { HOME: '/fake-home' })+ // The engine's core answers no rows.+ on('prompt.autocomplete', async () => ({ suggestions: [] }))+ on('fs.list', async ($: any, e: any, next: any) =>+ e.path.endsWith('/render/themes') ? { value: ['vscode', 'vscode-modern', 'nord'].map(name => ({ name, kind: 'dir', size: 0, mtimeMs: 0, isLink: false })) } : next(e))+ on('fs.read', async ($: any, e: any, next: any) =>+ /\/render\/themes\/[^/]+\/theme\.json$/.test(e.path) ? { value: '{"description":"d"}' } : next(e))+ const text = '/md-preview theme n'+ const got = await ($ as any).prompt.autocomplete({ text, cursor: text.length, token: 'n', start: text.length - 1 })+ expect(got.suggestions.map((r: any) => r.text)).toEqual(['nord'])+ const other = await ($ as any).prompt.autocomplete({ text: 'hello', cursor: 5, token: 'hello', start: 0 })+ expect(other.suggestions).toEqual([])+})diff --git a/tests/draw.test.ts b/tests/draw.test.tsnew file mode 100644index 0000000..f2dfd9b--- /dev/null+++ b/tests/draw.test.ts@@ -0,0 +1,160 @@+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'++// ---- Where pictures draw ----------------------------------------------------++const base = { program: '', term: 'xterm-256color', kitty: false, tmux: false, ssh: false, background: false, engineForced: false, modForced: false }++test('tmux and screen draw no pictures, even with the engine forced; only MD_PREVIEW_FORCE tries', () => {+ expect(canDrawIn({ ...base, term: 'xterm-kitty', tmux: true })).toBe(false)+ expect(canDrawIn({ ...base, program: 'ghostty', tmux: true, engineForced: true })).toBe(false)+ expect(canDrawIn({ ...base, term: 'screen-256color', tmux: true, engineForced: true })).toBe(false)+ expect(canDrawIn({ ...base, tmux: true, modForced: true })).toBe(true)+})++test('a background session never draws pictures, not even with MD_PREVIEW_FORCE', () => {+ expect(canDrawIn({ ...base, program: 'ghostty', background: true })).toBe(false)+ expect(canDrawIn({ ...base, term: 'xterm-kitty', background: true, engineForced: true, modForced: true })).toBe(false)+})++test('over ssh, TERM tells: kitty or Ghostty draws, an unknown terminal only when forced', () => {+ expect(canDrawIn({ ...base, ssh: true, term: 'xterm-kitty' })).toBe(true)+ expect(canDrawIn({ ...base, ssh: true, term: 'xterm-ghostty' })).toBe(true)+ expect(canDrawIn({ ...base, ssh: true })).toBe(false)+ expect(canDrawIn({ ...base, ssh: true, program: 'ghostty' })).toBe(false)+ expect(canDrawIn({ ...base, ssh: true, engineForced: true })).toBe(true)+ expect(canDrawIn({ ...base, ssh: true, modForced: true })).toBe(true)+ expect(canDrawIn({ ...base, ssh: true, term: 'xterm-kitty', tmux: true })).toBe(false)+})++// ---- Pages as bytes ---------------------------------------------------------++test('a page goes as bytes only within 4096 px a side and 2 MiB decoded', () => {+ expect(base64Bytes('')).toBe(0)+ expect(base64Bytes('YQ==')).toBe(1)+ expect(base64Bytes('YWI=')).toBe(2)+ expect(base64Bytes('YWJj')).toBe(3)+ expect(fitsInline({ width: 1600, height: 4096 })).toBe(true)+ expect(fitsInline({ width: INLINE_MAX_SIDE + 1, height: 64 })).toBe(false)+ expect(fitsInline({ width: 1600, height: 5000 })).toBe(false)+ expect(fitsInline({ width: 0, height: 64 })).toBe(false)+ const max = 'A'.repeat(Math.ceil(INLINE_MAX_BYTES / 3) * 4 + 4)+ expect(fitsInline({ width: 10, height: 10 }, 'AAAA')).toBe(true)+ expect(fitsInline({ width: 10, height: 10 }, max)).toBe(false)+})++test('over ssh a segment is cut so its page stays under 4096 px tall', () => {+ expect(inlineBudget(DEFAULT_CELL)).toBe(96)+ expect(inlineBudget({ width: 8, height: 16 })).toBe(SEGMENT_ROWS)+ expect(inlineBudget({ width: 40, height: 200 })).toBe(20)+ expect(inlineBudget(DEFAULT_CELL) * DEFAULT_CELL.height).toBeLessThan(INLINE_MAX_SIDE)+})++test('pages cut for ssh have keys of their own; local keys do not change', () => {+ const o = {+ textHash: 'h', columns: 100, cell: DEFAULT_CELL, size: 100, mode: 'dark' as const, termFont: '', columnPt: 6,+ templateStamp: '1', look: { name: 'vscode', dir: '/t', stamp: '0' },+ }+ expect(renderKey({ ...o, inline: false })).toBe(renderKey(o))+ expect(renderKey({ ...o, inline: true })).not.toBe(renderKey(o))+})++// ---- The Image source -------------------------------------------------------++const ok = (stdout: string, exitCode = 0) => ({ value: { exitCode, stdout, stderr: exitCode ? 'error: boom' : '', isStdoutTruncated: false, isStderrTruncated: false } })+// `od -An -v -tx1` of a PNG's first 24 bytes: 1600 x 64, and 1600 x 5000.+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'+const TALL = '89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 06 40 00 00 13 88'+// The first 33 bytes of the 1600 x 64 PNG, base64.+const PNG = 'iVBORw0KGgoAAAANSUhEUgAABkAAAABACAYAAAAAAAAA'++function world(on: any, vars: Record<string, string>, head = HEAD) {+ mock.store(on)+ const clock = mock.clock(on)+ mock.env(on, { HOME: '/h', ...vars })+ const reads: string[] = []+ const files = new Map<string, string>()+ on('process.run', async ($: any, e: any) => {+ const argv: string[] = e.argv+ const cmd = argv.join(' ')+ 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) => {+ files.set(e.path, e.text)+ return { value: undefined }+ })+ on('fs.read', async ($: any, e: any, next: any) => {+ if (e.as === 'bytes') {+ reads.push(e.path)+ return { value: { base64: PNG } }+ }+ 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('ui.toast', async () => ({ value: undefined }))+ on('ui.render', () => ENGINE as any)+ return { clock, reads }+}++const ENGINE = { type: 'Text', props: {}, children: ['engine drawing'] }+const message = (requestId: string, text: string) =>+ ({+ plugin: 'md-preview', surface: 'terminal', component: 'AssistantMessage', requestId,+ props: { text, isFirstOfReply: true }, viewport: { columns: 100, rows: 40 },+ }) as any+const props = (text: string) => ({ text, isFirstOfReply: true }) as any+const images = (tree: any): any[] =>+ tree && typeof tree === 'object' ? [...(tree.type === 'Image' ? [tree] : []), ...(tree.children ?? []).flatMap(images)] : []++test('over ssh in kitty, a page goes as PNG bytes, read once', async ($, on) => {+ const { clock, reads } = world(on, { SSH_CONNECTION: '10.0.0.2 50000 10.0.0.1 22', TERM: 'xterm-kitty' })+ const ran = await $.command.run({ command: 'md-preview', args: '' } as any)+ expect(ran.text).toContain('over ssh, sent as bytes')+ const ui = await $.ui.mount(message('ssh-1', 'Some **bold** text.'))+ await clock.settle()+ await ui.redraw(props('Some **bold** text.'))+ const [image] = images(await ui.drawn())+ expect(image.props.source).toEqual({ png: PNG })+ await ui.redraw(props('Some **bold** text.'))+ expect(images(await ui.drawn())[0].props.source).toEqual({ png: PNG })+ expect(reads.length).toBe(1)+ expect(reads[0]).toMatch(/^\/c\/[0-9a-f]{16}\/a-1\.png$/)+})++test('over ssh, a page over 4096 px tall draws as text', async ($, on) => {+ const { clock, reads } = world(on, { SSH_TTY: '/dev/pts/1', TERM: 'xterm-ghostty' }, TALL)+ await $.command.run({ command: 'md-preview', args: '' } as any)+ const ui = await $.ui.mount(message('ssh-2', 'Some **bold** text.'))+ await clock.settle()+ await ui.redraw(props('Some **bold** text.'))+ expect(await ui.drawn()).toMatchObject(ENGINE)+ expect(reads).toEqual([])+})++test('locally, a page goes as a file name', async ($, on) => {+ const { clock, reads } = world(on, { TERM: 'xterm-kitty' })+ await $.command.run({ command: 'md-preview', args: '' } as any)+ const ui = await $.ui.mount(message('local-1', 'Some **bold** text.'))+ await clock.settle()+ await ui.redraw(props('Some **bold** text.'))+ const [image] = images(await ui.drawn())+ expect(image.props.source).toMatchObject({ format: 'png' })+ expect(image.props.source.file).toMatch(/^\/c\/[0-9a-f]{16}\/a-1\.png$/)+ expect(reads).toEqual([])+})++test('in tmux with the engine forced, answers stay text', async ($, on) => {+ const { clock } = world(on, { TMUX: '/tmp/tmux-501/default,1,0', TERM: 'tmux-256color', CLAUDE_CODE_FORCE_TERMINAL_IMAGES: '1' })+ const ran = await $.command.run({ command: 'md-preview', args: '' } as any)+ expect(ran.text).toContain('Claude Code draws no pictures here')+ const ui = await $.ui.mount(message('tmux-1', 'Some **bold** text.'))+ await clock.settle()+ await ui.redraw(props('Some **bold** text.'))+ expect(await ui.drawn()).toMatchObject(ENGINE)+})diff --git a/tests/images.test.ts b/tests/images.test.tsnew file mode 100644index 0000000..520f2ac--- /dev/null+++ b/tests/images.test.ts@@ -0,0 +1,215 @@+import { expect, mock, test } from 'claude-code/testing'++import {+ claudeTmpOf, DEFAULT_CELL, pasteDirOf, pastedImagePath, pastedNumbers, PICTURE_MAX_ROWS, pictureCells, pictureRowsFor,+ projectSlug, sentImages,+} from '../hooks/register'++// ---- Pure helpers -----------------------------------------------------------++test('a picture keeps its aspect, is never made larger, and fits the box', () => {+ // 640 x 320 px at 16 x 32 px cells: 40 x 10 cells, its own size.+ expect(pictureCells({ width: 640, height: 320 }, 98, 24, DEFAULT_CELL)).toEqual({ columns: 40, rows: 10 })+ // Too wide: cut to 98 columns, the rows follow.+ expect(pictureCells({ width: 3136, height: 640 }, 98, 24, DEFAULT_CELL)).toEqual({ columns: 98, rows: 10 })+ expect(pictureCells({ width: 2000, height: 838 }, 98, 24, DEFAULT_CELL)).toEqual({ columns: 98, rows: 21 })+ // Too tall: cut to 24 rows, the columns follow.+ expect(pictureCells({ width: 1000, height: 1600 }, 98, 24, DEFAULT_CELL)).toEqual({ columns: 30, rows: 24 })+ // A tiny icon is at least one cell.+ expect(pictureCells({ width: 4, height: 4 }, 98, 24, DEFAULT_CELL)).toEqual({ columns: 1, rows: 1 })+})++test('a picture takes at most half the viewport, within 6 and 24 rows', () => {+ expect(pictureRowsFor(undefined)).toBe(PICTURE_MAX_ROWS)+ expect(pictureRowsFor(100)).toBe(PICTURE_MAX_ROWS)+ expect(pictureRowsFor(30)).toBe(15)+ expect(pictureRowsFor(8)).toBe(6)+})++test('only image attachments that can be PNGs are drawn', () => {+ expect(sentImages({+ attachments: [+ { path: '/t/a.png', size: 1, isImage: true, media_type: 'image/png' },+ { path: '/t/b.png', size: 1, isImage: true },+ { path: '/t/c.jpg', size: 1, isImage: true, media_type: 'image/jpeg' },+ { path: '/t/d.pdf', size: 1, isImage: false },+ { size: 1, isImage: true },+ ],+ })).toEqual(['/t/a.png', '/t/b.png'])+ expect(sentImages(undefined)).toEqual([])+ expect(sentImages('error text')).toEqual([])+ expect(sentImages({ attachments: 'x' })).toEqual([])+})++test('the [Image #N] marks of a prompt, each once', () => {+ expect(pastedNumbers('[Image #5] what is this')).toEqual([5])+ expect(pastedNumbers('[Image #2] and [Image #3], again [Image #2]')).toEqual([2, 3])+ expect(pastedNumbers('no image, [Image #x], [image #4]')).toEqual([])+})++test('the pasted-image path follows Claude Code folder names', () => {+ expect(projectSlug('/Users/subhagato/Development/apps/claude-md-preview')).toBe('-Users-subhagato-Development-apps-claude-md-preview')+ expect(projectSlug('/home/me/my_app.v2')).toBe('-home-me-my-app-v2')+ expect(claudeTmpOf({ uid: '501\n', isMac: true })).toBe('/private/tmp/claude-501')+ expect(claudeTmpOf({ uid: '1000', isMac: false })).toBe('/tmp/claude-1000')+ expect(claudeTmpOf({ tmpdir: '/scratch/', uid: '1000', isMac: false })).toBe('/scratch/claude-1000')+ expect(claudeTmpOf({ uid: '', isMac: true })).toBe('')+ const dir = pasteDirOf('/private/tmp/claude-501', '/Users/subhagato/Development/apps/claude-md-preview', 'f8bb4b84-0e51-456a-9e49-8e5db49500ae')+ expect(pastedImagePath(dir, 5)).toBe('/private/tmp/claude-501/-Users-subhagato-Development-apps-claude-md-preview/f8bb4b84-0e51-456a-9e49-8e5db49500ae/images/5.png')+})++// ---- The render hooks -------------------------------------------------------++const ok = (stdout: string, exitCode = 0) => ({ value: { exitCode, stdout, stderr: exitCode ? 'error: boom' : '', isStdoutTruncated: false, isStderrTruncated: false } })+// `od -An -v -tx1` of a PNG's first 24 bytes: 640 x 320.+const HEAD = '89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 02 80 00 00 01 40'+// The first bytes of a JPEG: not a PNG.+const JPEG = 'ff d8 ff e0 00 10 4a 46 49 46 00 01 01 00 00 01 00 01 00 00 ff db 00 43'+// The first 33 bytes of a PNG, base64.+const PNG = 'iVBORw0KGgoAAAANSUhEUgAABkAAAABACAYAAAAAAAAA'+const ENGINE = { type: 'Text', props: {}, children: ['engine drawing'] }+const PASTED = '/private/tmp/claude-501/-w-app/sid-1/images'++// A Mac with kitty (pictures drawn), uid 501, session sid-1 in /w/app. `files`+// are the files that exist, by path: their first bytes as od prints them.+function world(on: any, o: { vars?: Record<string, string>; files?: Record<string, string>; dirs?: string[]; projects?: string[] } = {}) {+ mock.store(on)+ const clock = mock.clock(on)+ mock.env(on, { HOME: '/h', TERM: 'xterm-kitty', ...o.vars })+ const files = o.files ?? {}+ const dirs = new Set(o.dirs ?? [])+ const heads: string[] = []+ const reads: string[] = []+ on('process.run', async ($: any, e: any) => {+ const argv: string[] = e.argv+ const cmd = argv.join(' ')+ if (/md-preview-/.test(cmd)) return ok('/c\nDarwin\n')+ if (argv[0] === 'id' && argv[1] === '-u') return ok('501\n')+ if (cmd.includes('od -An')) {+ const file = argv.at(-1)!+ heads.push(file)+ return ok(`${files[file] ?? ''}\n@\n`)+ }+ return ok('', 1)+ })+ on('session.id', async () => ({ value: 'sid-1' }))+ on('session.cwd', async () => ({ value: '/w/app' }))+ on('session.root', async () => ({ value: '/w/app' }))+ on('fs.stat', async ($: any, e: any, next: any) =>+ e.path in files ? { value: { kind: 'file', size: 1000, mtimeMs: 1, isLink: false } } : e.path.startsWith('/t/') || e.path.startsWith('/private/') ? { deny: 'ENOENT' } : next(e))+ on('fs.exists', async ($: any, e: any, next: any) => (e.path.startsWith('/private/') ? { value: dirs.has(e.path) } : next(e)))+ on('fs.list', async ($: any, e: any, next: any) =>+ e.path === '/private/tmp/claude-501' ? { value: (o.projects ?? []).map(name => ({ name, kind: 'dir', size: 0, mtimeMs: 1, isLink: false })) } : next(e))+ on('fs.read', async ($: any, e: any, next: any) => (e.as === 'bytes' && e.path in files ? (reads.push(e.path), { value: { base64: PNG } }) : next(e)))+ on('ui.toast', async () => ({ value: undefined }))+ on('ui.render', () => ENGINE as any)+ return { clock, heads, reads }+}++const sent = (output: unknown, isErrored = false, id = 'tu-1') =>+ ({+ plugin: 'md-preview', surface: 'terminal', component: 'ToolResult', requestId: id,+ props: { tool_use_id: id, tool: 'SendUserFile', output, isErrored }, viewport: { columns: 100, rows: 40 },+ }) as any+const attach = (path: string, isImage = true) => ({ attachments: [{ path, size: 1000, isImage, ...(isImage ? { media_type: 'image/png' } : {}) }] })+const prompt = (text: string, origin: any = { kind: 'composer' }, id = 'u-1') =>+ ({+ plugin: 'md-preview', surface: 'terminal', component: 'UserMessage', requestId: id,+ props: { text, origin, isExpanded: true }, viewport: { columns: 100, rows: 40 },+ }) as any+const images = (tree: any): any[] =>+ tree && typeof tree === 'object' ? [...(tree.type === 'Image' ? [tree] : []), ...(tree.children ?? []).flatMap(images)] : []+// Sets the mod up (as the first answer would) before a row draws.+const ready = ($: any) => $.command.run({ command: 'md-preview', args: '' } as any)++test('a PNG Claude sends draws under its row, at its own size', async ($, on) => {+ const { heads } = world(on, { files: { '/t/icon.png': HEAD } })+ await ready($)+ const ui = await $.ui.mount(sent(attach('/t/icon.png')))+ const tree: any = await ui.drawn()+ expect(tree.children[0]).toMatchObject(ENGINE)+ const [image] = images(tree)+ expect(image.props).toMatchObject({ columns: 40, rows: 10, alt: 'icon.png' })+ expect(image.props.source).toMatchObject({ file: '/t/icon.png', format: 'png' })+ // A redraw does not read the header again.+ await ui.redraw(sent(attach('/t/icon.png')).props)+ expect(images(await ui.drawn()).length).toBe(1)+ expect(heads).toEqual(['/t/icon.png'])+})++test('over ssh, a PNG Claude sends goes as bytes', async ($, on) => {+ const { reads } = world(on, { vars: { SSH_CONNECTION: '10.0.0.2 50000 10.0.0.1 22' }, files: { '/t/icon.png': HEAD } })+ await ready($)+ const ui = await $.ui.mount(sent(attach('/t/icon.png')))+ expect(images(await ui.drawn())[0].props.source).toEqual({ png: PNG })+ expect(reads).toEqual(['/t/icon.png'])+})++test('a file that is not an image, a JPEG and a missing file leave the row as it is', async ($, on) => {+ world(on, { files: { '/t/notes.txt': HEAD, '/t/photo.png': JPEG } })+ await ready($)+ const outputs = [attach('/t/notes.txt', false), attach('/t/photo.png'), attach('/t/gone.png')]+ for (const [i, output] of outputs.entries()) {+ const ui = await $.ui.mount(sent(output, false, `tu-${i}`))+ expect(await ui.drawn()).toMatchObject(ENGINE)+ expect(images(await ui.drawn())).toEqual([])+ }+})++test('an errored SendUserFile call leaves the row as it is', async ($, on) => {+ world(on, { files: { '/t/icon.png': HEAD } })+ await ready($)+ const ui = await $.ui.mount(sent(attach('/t/icon.png'), true))+ expect(await ui.drawn()).toMatchObject(ENGINE)+})++test('an image the user pastes draws under the prompt', async ($, on) => {+ world(on, { files: { [`${PASTED}/5.png`]: HEAD }, dirs: [PASTED] })+ await ready($)+ const ui = await $.ui.mount(prompt('[Image #5] what is this'))+ const tree: any = await ui.drawn()+ expect(tree.children[0]).toMatchObject(ENGINE)+ const [image] = images(tree)+ expect(image.props.source).toMatchObject({ file: `${PASTED}/5.png`, format: 'png' })+ expect(image.props).toMatchObject({ columns: 40, rows: 10 })+})++test('a pasted image is found when the folder name is not the plain slug', async ($, on) => {+ const cut = '/private/tmp/claude-501/-w-app-cut-1a2b/sid-1/images'+ world(on, { files: { [`${cut}/2.png`]: HEAD }, dirs: [cut], projects: ['-other', '-w-app-cut-1a2b'] })+ await ready($)+ const ui = await $.ui.mount(prompt('look: [Image #2]'))+ expect(images(await ui.drawn())[0].props.source.file).toBe(`${cut}/2.png`)+})++test('a pasted image whose file is gone leaves the prompt as it is', async ($, on) => {+ world(on, { dirs: [PASTED] })+ await ready($)+ const ui = await $.ui.mount(prompt('[Image #7] and this'))+ expect(await ui.drawn()).toMatchObject(ENGINE)+})++test('a message from another agent or a notification is not changed', async ($, on) => {+ world(on, { files: { [`${PASTED}/5.png`]: HEAD }, dirs: [PASTED] })+ await ready($)+ for (const input of [prompt('[Image #5]', { kind: 'peer' }, 'u-1'), prompt('[Image #5]', { kind: 'task-notification' }, 'u-2')]) {+ const ui = await $.ui.mount(input)+ expect(await ui.drawn()).toMatchObject(ENGINE)+ }+})++test('with md-preview off, rows stay as they are', async ($, on) => {+ world(on, { files: { '/t/icon.png': HEAD, [`${PASTED}/5.png`]: HEAD }, dirs: [PASTED] })+ await ready($)+ await $.command.run({ command: 'md-preview', args: 'off' } as any)+ expect(await (await $.ui.mount(sent(attach('/t/icon.png')))).drawn()).toMatchObject(ENGINE)+ expect(await (await $.ui.mount(prompt('[Image #5] hi'))).drawn()).toMatchObject(ENGINE)+})++test('in a terminal that draws no pictures, rows stay as they are', async ($, on) => {+ world(on, { vars: { TERM: 'xterm-256color' }, files: { '/t/icon.png': HEAD, [`${PASTED}/5.png`]: HEAD }, dirs: [PASTED] })+ const shown = await ready($)+ expect(shown.text).toContain('Claude Code draws no pictures here')+ expect(await (await $.ui.mount(sent(attach('/t/icon.png')))).drawn()).toMatchObject(ENGINE)+ expect(await (await $.ui.mount(prompt('[Image #5] hi'))).drawn()).toMatchObject(ENGINE)+})diff --git a/tests/mode.test.ts b/tests/mode.test.tsnew file mode 100644index 0000000..68594b6--- /dev/null+++ b/tests/mode.test.ts@@ -0,0 +1,270 @@+import { expect, mock, test } from 'claude-code/testing'++// Claude Code's theme on auto, on a Mac in light mode: the OS read gives light.+test('with the theme on auto, the mode comes from the OS appearance, read every 3 s', async ($, on) => {+ mock.store(on)+ const clock = mock.clock(on)+ let osDark = false+ mock.env(on, { HOME: '/fake-home' })+ const reads: string[] = []+ on('config.list', async () => ({ value: [{ key: 'theme', value: 'auto' }] as any }))+ on('config.set', async ($: any, e: any) => ({ value: e.value }))+ on('process.run', async ($: any, e: any, next: any) => {+ const argv: string[] = e.argv+ if (argv[0] === 'sh' && /md-preview-/.test(argv.join(' '))) return { value: { exitCode: 0, stdout: '/tmp/mdp\nDarwin\n', stderr: '', isStdoutTruncated: false, isStderrTruncated: false } }+ if (argv[0] === 'defaults' && argv.includes('AppleInterfaceStyle')) {+ reads.push('macOS')+ return { value: osDark+ ? { exitCode: 0, stdout: 'Dark\n', stderr: '', isStdoutTruncated: false, isStderrTruncated: false }+ : { exitCode: 1, stdout: '', stderr: 'does not exist', isStdoutTruncated: false, isStderrTruncated: false } }+ }+ return next(e)+ })+ const ran = await $.command.run({ command: 'md-preview', args: '' } as any)+ expect(ran.text).toContain('mode light (auto, from macOS)')+ expect(reads.length).toBe(1)+ // The OS goes dark: the next poll, 3 s on, sees it; one read per period.+ osDark = true+ await clock.advance(3000)+ expect(reads.length).toBe(2)+ const later = await $.command.run({ command: 'md-preview', args: '' } as any)+ expect(later.text).toContain('mode dark (auto, from macOS)')+ await clock.advance(6000)+ expect(reads.length).toBe(4)+ // A fixed theme stops the polling; auto starts it again, with one read at once.+ await $.config.set({ key: 'theme', value: 'light-daltonized' } as any)+ await clock.advance(9000)+ expect(reads.length).toBe(4)+ const fixed = await $.command.run({ command: 'md-preview', args: '' } as any)+ expect(fixed.text).toContain('mode light (Claude Code theme light-daltonized)')+ await $.config.set({ key: 'theme', value: 'auto' } as any)+ await clock.settle()+ expect(reads.length).toBe(5)+ await clock.advance(3000)+ expect(reads.length).toBe(6)+ const again = await $.command.run({ command: 'md-preview', args: '' } as any)+ expect(again.text).toContain('mode dark (auto, from macOS)')+})++// /md-preview probe asks the terminal 5 times and shows each raw answer.+test('/md-preview probe shows the raw OSC 11 answers and the mode they give', async ($, on) => {+ mock.store(on)+ mock.env(on, { HOME: '/fake-home' })+ const answers = ['\x1b]11;rgb:ffff/ffff/ffff\x07', '', 'x', null, '\x1b]11;rgb:1d1d/2525/2a2a\x1b\\']+ let i = 0+ on('process.run', async ($: any, e: any, next: any) => {+ if (e.argv[0] !== 'perl' || !String(e.argv[2]).includes('11;?')) return next(e)+ const a = answers[i++]+ return { value: { exitCode: a === null ? 1 : 0, stdout: a ?? '', stderr: '', isStdoutTruncated: false, isStderrTruncated: false } }+ })+ const ran = await $.command.run({ command: 'md-preview', args: 'probe' } as any)+ expect(i).toBe(5)+ expect(ran.text).toContain('1: "\\e]11;rgb:ffff/ffff/ffff\\a" -> luminance 1.000, light')+ expect(ran.text).toContain('2: no answer in 300 ms')+ expect(ran.text).toContain('3: "x" -> not an OSC 11 answer')+ expect(ran.text).toContain('4: could not open /dev/tty')+ expect(ran.text).toContain('5: "\\e]11;rgb:1d1d/2525/2a2a\\e\\" -> luminance 0.018, dark')+ expect(ran.text).toContain(', dark')+ expect(ran.text).toContain('The poll uses it: no (off).')+})++// iTerm2 set to Dark on a Mac in light mode, a profile with separate colours:+// the terminal is dark, so the mode is dark (the OS is not asked first).+test('with the theme on auto, a dark iTerm2 profile on a light Mac draws dark', async ($, on) => {+ mock.store(on)+ const clock = mock.clock(on)+ mock.env(on, { HOME: '/fake-home', TERM_PROGRAM: 'iTerm.app', ITERM_PROFILE: 'Default', COLORFGBG: '0;15' })+ on('config.list', async () => ({ value: [{ key: 'theme', value: 'auto' }] as any }))+ const dark = { 'Red Component': 0.11, 'Green Component': 0.15, 'Blue Component': 0.17 }+ const white = { 'Red Component': 1, 'Green Component': 1, 'Blue Component': 1 }+ const marks = JSON.stringify([{ Name: 'Default', Guid: 'G1', 'Use Separate Colors for Light and Dark Mode': true, 'Background Color': dark, 'Background Color (Dark)': dark, 'Background Color (Light)': white }])+ let style = '1\n'+ const ok = (stdout: string, exitCode = 0) => ({ value: { exitCode, stdout, stderr: '', isStdoutTruncated: false, isStderrTruncated: false } })+ on('process.run', async ($: any, e: any, next: any) => {+ const argv: string[] = e.argv+ const cmd = argv.join(' ')+ if (argv[0] === 'sh' && /md-preview-/.test(cmd)) return ok('/tmp/mdp\nDarwin\n')+ if (argv[0] === 'sh' && cmd.includes('TabStyleWithAutomaticOption')) return ok(`${style}@\nG1\n@\n${marks}\n`)+ if (argv[0] === 'defaults' && argv.includes('AppleInterfaceStyle')) return ok('', 1)+ return next(e)+ })+ const ran = await $.command.run({ command: 'md-preview', args: '' } as any)+ expect(ran.text).toContain('mode dark (auto, from iTerm2: profile Default background)')+ // iTerm2 on Automatic follows the light Mac: the profile's light colours.+ style = '4\n'+ await clock.advance(3000)+ const later = await $.command.run({ command: 'md-preview', args: '' } as any)+ expect(later.text).toContain('mode light (auto, from iTerm2: profile Default background)')+})++// Ghostty on a light Mac: no theme is Ghostty's dark default; a light:A,dark:B+// theme follows the OS; COLORFGBG (Ghostty sets none) is not needed.+test('with the theme on auto, Ghostty draws as its background is', async ($, on) => {+ mock.store(on)+ const clock = mock.clock(on)+ mock.env(on, { HOME: '/h', TERM_PROGRAM: 'ghostty', TERM: 'xterm-ghostty', GHOSTTY_RESOURCES_DIR: '/R' })+ on('config.list', async () => ({ value: [{ key: 'theme', value: 'auto' }] as any }))+ let config = 'font-family = Menlo\n'+ let osDark = false+ const ok = (stdout: string, exitCode = 0) => ({ value: { exitCode, stdout, stderr: '', isStdoutTruncated: false, isStderrTruncated: false } })+ on('process.run', async ($: any, e: any, next: any) => {+ const argv: string[] = e.argv+ const cmd = argv.join(' ')+ if (argv[0] === 'sh' && /md-preview-/.test(cmd)) return ok('/tmp/mdp\nDarwin\n')+ if (argv[0] === 'sh' && cmd.includes('+show-config')) return ok(config)+ if (argv[0] === 'defaults' && argv.includes('AppleInterfaceStyle')) return osDark ? ok('Dark\n') : ok('', 1)+ return next(e)+ })+ const files: Record<string, string> = { '/R/themes/Day': 'background = #f7f7f7\n', '/h/.config/ghostty/themes/Night': 'background = #191724\n' }+ on('fs.read', async ($: any, e: any, next: any) => (e.path in files ? { value: files[e.path] } : e.path.includes('ghostty') || e.path.startsWith('/R/') ? { deny: 'no such file' } as any : next(e)))+ const ran = await $.command.run({ command: 'md-preview', args: '' } as any)+ expect(ran.text).toContain('mode dark (auto, from Ghostty: default background)')+ config = 'theme = light:Day,dark:Night\nbackground = #f7f7f7\n'+ await clock.advance(3000)+ expect((await $.command.run({ command: 'md-preview', args: '' } as any)).text).toContain('mode light (auto, from Ghostty: theme Day background)')+ osDark = true+ await clock.advance(3000)+ expect((await $.command.run({ command: 'md-preview', args: '' } as any)).text).toContain('mode dark (auto, from Ghostty: theme Night background)')+})++// kitty on a light Mac: kitty.conf's included theme is dark; once auto theme+// files exist, the one for the OS scheme is used.+test('with the theme on auto, kitty draws as its config or auto theme is', async ($, on) => {+ mock.store(on)+ const clock = mock.clock(on)+ mock.env(on, { HOME: '/h', TERM: 'xterm-kitty', KITTY_WINDOW_ID: '1' })+ on('config.list', async () => ({ value: [{ key: 'theme', value: 'auto' }] as any }))+ let osDark = false+ const ok = (stdout: string, exitCode = 0) => ({ value: { exitCode, stdout, stderr: '', isStdoutTruncated: false, isStderrTruncated: false } })+ on('process.run', async ($: any, e: any, next: any) => {+ const argv: string[] = e.argv+ if (argv[0] === 'sh' && /md-preview-/.test(argv.join(' '))) return ok('/tmp/mdp\nDarwin\n')+ if (argv[0] === 'defaults' && argv.includes('AppleInterfaceStyle')) return osDark ? ok('Dark\n') : ok('', 1)+ return next(e)+ })+ const files: Record<string, string> = {+ '/h/.config/kitty/kitty.conf': 'font_family family="JetBrains Mono" style=Regular\ninclude current-theme.conf\n',+ '/h/.config/kitty/current-theme.conf': 'background #1e1e2e\n',+ }+ const inKitty = (path: string) => path.includes('kitty')+ on('fs.exists', async ($: any, e: any, next: any) => (inKitty(e.path) ? { value: e.path in files } : next(e)))+ on('fs.read', async ($: any, e: any, next: any) => (e.path in files ? { value: files[e.path] } : inKitty(e.path) ? ({ deny: 'no such file' } as any) : next(e)))+ const ran = await $.command.run({ command: 'md-preview', args: '' } as any)+ expect(ran.text).toContain('mode dark (auto, from kitty: config background)')+ expect(ran.text).toContain('terminal font JetBrains Mono')+ files['/h/.config/kitty/dark-theme.auto.conf'] = 'background #191724\n'+ files['/h/.config/kitty/light-theme.auto.conf'] = 'background #fafafa\n'+ await clock.advance(3000)+ expect((await $.command.run({ command: 'md-preview', args: '' } as any)).text).toContain('mode light (auto, from kitty: light-theme.auto.conf background)')+ osDark = true+ await clock.advance(3000)+ expect((await $.command.run({ command: 'md-preview', args: '' } as any)).text).toContain('mode dark (auto, from kitty: dark-theme.auto.conf background)')+})++// Rio on a dark Mac with an [adaptive-theme]: the OS picks the theme file;+// force-theme wins over the OS.+test('with the theme on auto, Rio draws as its adaptive theme is', async ($, on) => {+ mock.store(on)+ const clock = mock.clock(on)+ mock.env(on, { HOME: '/h', TERM_PROGRAM: 'rio', TERM: 'xterm-256color' })+ on('config.list', async () => ({ value: [{ key: 'theme', value: 'auto' }] as any }))+ const ok = (stdout: string, exitCode = 0) => ({ value: { exitCode, stdout, stderr: '', isStdoutTruncated: false, isStderrTruncated: false } })+ on('process.run', async ($: any, e: any, next: any) => {+ const argv: string[] = e.argv+ if (argv[0] === 'sh' && /md-preview-/.test(argv.join(' '))) return ok('/tmp/mdp\nDarwin\n')+ if (argv[0] === 'defaults' && argv.includes('AppleInterfaceStyle')) return ok('Dark\n')+ return next(e)+ })+ const files: Record<string, string> = {+ '/h/.config/rio/config.toml': '[fonts]\nfamily = "Iosevka"\n\n[adaptive-theme]\nlight = "day"\ndark = "night"\n',+ '/h/.config/rio/themes/day.toml': '[colors]\nbackground = "#FFFFFF"\n',+ '/h/.config/rio/themes/night.toml': '[colors]\nbackground = "#191724"\n',+ }+ on('fs.read', async ($: any, e: any, next: any) => (e.path in files ? { value: files[e.path] } : e.path.includes('/rio/') ? ({ deny: 'no such file' } as any) : next(e)))+ const ran = await $.command.run({ command: 'md-preview', args: '' } as any)+ expect(ran.text).toContain('mode dark (auto, from Rio: theme night background)')+ expect(ran.text).toContain('terminal font Iosevka')+ files['/h/.config/rio/config.toml'] = 'force-theme = "light"\n' + files['/h/.config/rio/config.toml']+ await clock.advance(3000)+ expect((await $.command.run({ command: 'md-preview', args: '' } as any)).text).toContain('mode light (auto, from Rio: theme day background)')+})++// Over ssh the configs and the OS here are the remote computer's: auto uses+// only COLORFGBG, else dark, and the terminal font is not read.+for (const colorFgBg of [undefined, '0;15']) {+ test(`with the theme on auto over ssh, kitty's config and the OS are not read (COLORFGBG ${colorFgBg ?? 'not set'})`, async ($, on) => {+ mock.store(on)+ mock.clock(on)+ mock.env(on, { HOME: '/h', TERM: 'xterm-kitty', SSH_CONNECTION: '10.0.0.2 50000 10.0.0.1 22', ...(colorFgBg ? { COLORFGBG: colorFgBg } : {}) })+ on('config.list', async () => ({ value: [{ key: 'theme', value: 'auto' }] as any }))+ const asked: string[] = []+ const ok = (stdout: string, exitCode = 0) => ({ value: { exitCode, stdout, stderr: '', isStdoutTruncated: false, isStderrTruncated: false } })+ on('process.run', async ($: any, e: any, next: any) => {+ const argv: string[] = e.argv+ if (argv[0] === 'sh' && /md-preview-/.test(argv.join(' '))) return ok('/tmp/mdp\nDarwin\n')+ if (argv[0] === 'defaults' && argv.includes('AppleInterfaceStyle')) {+ asked.push('macOS')+ return ok('', 1)+ }+ return next(e)+ })+ on('fs.exists', async ($: any, e: any, next: any) => (e.path.includes('kitty') ? (asked.push(e.path), { value: false }) : next(e)))+ on('fs.read', async ($: any, e: any, next: any) => (e.path.includes('kitty') ? (asked.push(e.path), { deny: 'no such file' } as any) : next(e)))+ const ran = await $.command.run({ command: 'md-preview', args: '' } as any)+ expect(ran.text).toContain(colorFgBg ? 'mode light (auto, from COLORFGBG)' : 'mode dark (auto, OS appearance not known, dark assumed)')+ expect(ran.text).toContain('terminal font not known (Menlo assumed)')+ expect(asked).toEqual([])+ })+}++// cmux (Ghostty inside) with no colours in the Ghostty config: its adaptive+// default theme follows cmux's appearance; turned off, Ghostty's dark default.+test('with the theme on auto, cmux draws as its appearance is', async ($, on) => {+ mock.store(on)+ const clock = mock.clock(on)+ mock.env(on, { HOME: '/h', TERM_PROGRAM: 'ghostty', TERM: 'xterm-ghostty', CMUX_SURFACE_ID: 'S1' })+ on('config.list', async () => ({ value: [{ key: 'theme', value: 'auto' }] as any }))+ let saved = 'system\n'+ const ok = (stdout: string, exitCode = 0) => ({ value: { exitCode, stdout, stderr: '', isStdoutTruncated: false, isStderrTruncated: false } })+ on('process.run', async ($: any, e: any, next: any) => {+ const argv: string[] = e.argv+ const cmd = argv.join(' ')+ if (argv[0] === 'sh' && /md-preview-/.test(cmd)) return ok('/tmp/mdp\nDarwin\n')+ if (argv[0] === 'sh' && cmd.includes('+show-config')) return ok('font-family = Menlo\n')+ if (argv[0] === 'defaults' && argv.includes('com.cmuxterm.app')) return ok(saved)+ if (argv[0] === 'defaults' && argv.includes('AppleInterfaceStyle')) return ok('', 1)+ return next(e)+ })+ let cmuxJson: string | null = null+ on('fs.read', async ($: any, e: any, next: any) => (e.path === '/h/.config/cmux/cmux.json' ? (cmuxJson === null ? ({ deny: 'no such file' } as any) : { value: cmuxJson }) : next(e)))+ const ran = await $.command.run({ command: 'md-preview', args: '' } as any)+ expect(ran.text).toContain('mode light (auto, from cmux: adaptive default theme, appearance system)')+ saved = 'dark\n'+ await clock.advance(3000)+ expect((await $.command.run({ command: 'md-preview', args: '' } as any)).text).toContain('mode dark (auto, from cmux: adaptive default theme, appearance dark)')+ saved = 'system\n'+ cmuxJson = '{\n // off\n "terminal": { "adaptiveDefaultTheme": false, },\n}'+ await clock.advance(3000)+ expect((await $.command.run({ command: 'md-preview', args: '' } as any)).text).toContain('mode dark (auto, from Ghostty: default background)')+})++// iTerm2 whose TERM_PROGRAM did not come through: ITERM_PROFILE says iTerm2.+test('with the theme on auto, iTerm2 with no TERM_PROGRAM is found by ITERM_PROFILE', async ($, on) => {+ mock.store(on)+ mock.clock(on)+ mock.env(on, { HOME: '/fake-home', TERM: 'xterm-256color', ITERM_PROFILE: 'Default', LC_TERMINAL_VERSION: '3.7.5' })+ on('config.list', async () => ({ value: [{ key: 'theme', value: 'auto' }] as any }))+ const dark = { 'Red Component': 0.11, 'Green Component': 0.15, 'Blue Component': 0.17 }+ const marks = JSON.stringify([{ Name: 'Default', Guid: 'G1', 'Background Color': dark }])+ const ok = (stdout: string, exitCode = 0) => ({ value: { exitCode, stdout, stderr: '', isStdoutTruncated: false, isStderrTruncated: false } })+ on('process.run', async ($: any, e: any, next: any) => {+ const argv: string[] = e.argv+ const cmd = argv.join(' ')+ if (argv[0] === 'sh' && /md-preview-/.test(cmd)) return ok('/tmp/mdp\nDarwin\n')+ if (argv[0] === 'sh' && cmd.includes('TabStyleWithAutomaticOption')) return ok(`1\n@\nG1\n@\n${marks}\n`)+ if (argv[0] === 'defaults' && argv.includes('AppleInterfaceStyle')) return ok('', 1)+ return next(e)+ })+ const ran = await $.command.run({ command: 'md-preview', args: '' } as any)+ expect(ran.text).toContain('mode dark (auto, from iTerm2: profile Default background)')+})diff --git a/tests/plan.test.ts b/tests/plan.test.tsnew file mode 100644index 0000000..c2359c7--- /dev/null+++ b/tests/plan.test.ts@@ -0,0 +1,485 @@+import { expect, mock, test } from 'claude-code/testing'++import {+ choiceOf, decisionOf, editorArgv, feedbackOf, isPlanQuestion, normalPath, PLAN_ASK_LINE, PLAN_AUTO, PLAN_CLEAR, PLAN_DRAWING, PLAN_EDIT,+ PLAN_HEADER, PLAN_MANUAL, PLAN_QUESTION, PLAN_QUESTION_EDITED, PLAN_REJECTED, planFileOf, planInputOf, planOf, planOptions,+ planShownOf, shortPath, TYPST_PROMPT, verdictOf,+} from '../hooks/register'++// ---- Pure helpers -----------------------------------------------------------++test('paths are made plain with no file system call', () => {+ expect(normalPath('/h//.claude/./plans/../plans/p.md')).toBe('/h/.claude/plans/p.md')+ expect(normalPath('/../a')).toBe('/a')+ expect(normalPath('a/../../b')).toBe('../b')+})++test('the plan and the plan file an ExitPlanMode call carries', () => {+ expect(planInputOf({ plan: '# Plan', planFilePath: '/h/.claude/plans/p.md' })).toBe('# Plan')+ expect(planInputOf({ plan: ' \n' })).toBe('')+ expect(planInputOf({ allowedPrompts: [] })).toBe('')+ expect(planInputOf(undefined)).toBe('')+ expect(planFileOf({ planFilePath: '/h/.claude/plans/p.md' })).toBe('/h/.claude/plans/p.md')+ expect(planFileOf({ planFilePath: 'p.md' })).toBe('')+ expect(planFileOf({})).toBe('')+})++test('the plan of an ExitPlanMode result: a non-empty one of the main loop only', () => {+ expect(planOf({ plan: '# Plan\n\n1. Do it', isAgent: false })).toBe('# Plan\n\n1. Do it')+ expect(planOf({ plan: ' \n', isAgent: false })).toBe(null)+ expect(planOf({ plan: null, isAgent: false })).toBe(null)+ expect(planOf({ plan: '# Plan', isAgent: true })).toBe(null)+ expect(planOf({ plan: '# Plan', isAgent: false, awaitingLeaderApproval: true })).toBe(null)+ expect(planOf('User rejected the plan')).toBe(null)+ expect(planOf(undefined)).toBe(null)+})++test('the plan a row shows: the edited text, else the result, else the call', () => {+ expect(planShownOf('# Edited', { plan: '# Done', isAgent: false }, { plan: '# Asked' })).toBe('# Edited')+ expect(planShownOf(undefined, { plan: '# Done', isAgent: false }, { plan: '# Asked' })).toBe('# Done')+ expect(planShownOf(undefined, undefined, { plan: '# Asked' })).toBe('# Asked')+ expect(planShownOf(undefined, { plan: '# Done', isAgent: true }, { plan: '# Asked' })).toBe('')+ expect(planShownOf(undefined, undefined, {})).toBe('')+})++test('a short path', () => {+ expect(shortPath('/h/.claude/plans/p.md', '/h')).toBe('~/.claude/plans/p.md')+ expect(shortPath('/other/p.md', '/h')).toBe('/other/p.md')+ expect(shortPath('/h/p.md', '')).toBe('/h/p.md')+})++test('the question: four options, the edit option only with an editor; any other answer is feedback', () => {+ expect(planOptions(true)).toEqual([PLAN_AUTO, PLAN_MANUAL, PLAN_CLEAR, PLAN_EDIT])+ expect(planOptions(false)).toEqual([PLAN_AUTO, PLAN_MANUAL, PLAN_CLEAR])+ expect(choiceOf(PLAN_AUTO, true)).toEqual({ kind: 'auto' })+ expect(choiceOf(PLAN_MANUAL, true)).toEqual({ kind: 'manual' })+ expect(choiceOf(PLAN_CLEAR, true)).toEqual({ kind: 'clear' })+ expect(choiceOf(PLAN_EDIT, true)).toEqual({ kind: 'edit' })+ expect(choiceOf(PLAN_EDIT, false)).toEqual({ kind: 'feedback', text: PLAN_EDIT })+ expect(choiceOf(' add tests ', true)).toEqual({ kind: 'feedback', text: 'add tests' })+ expect(feedbackOf('add tests')).toBe('The user wants changes to the plan: add tests')+ expect(feedbackOf('')).toBe('The user wants changes to the plan.')+})++test('a verdict becomes the PermissionRequest decision', () => {+ const input = { plan: '# Plan', planFilePath: '/h/p.md' }+ const auto = verdictOf({ kind: 'auto' }, '# Plan', false)!+ expect(decisionOf(auto, input)).toEqual({+ behavior: 'allow', updatedInput: input, updatedPermissions: [{ type: 'setMode', mode: 'acceptEdits', destination: 'session' }],+ })+ const manual = verdictOf({ kind: 'manual' }, '# Edited', true)!+ expect(decisionOf(manual, input)).toEqual({+ behavior: 'allow', updatedInput: { ...input, plan: '# Edited' }, updatedPermissions: [{ type: 'setMode', mode: 'default', destination: 'session' }],+ })+ expect(verdictOf({ kind: 'clear' }, '# Plan', false)).toMatchObject({ kind: 'allow', mode: 'acceptEdits', clear: true })+ expect(verdictOf({ kind: 'edit' }, '# Plan', false)).toBe(null)+ expect(decisionOf({ kind: 'deny', message: PLAN_REJECTED }, input)).toEqual({ behavior: 'deny', message: 'The user rejected the plan.', interrupt: true })+})++test('the editor: VS Code when found, else TextEdit on a local Mac, else none', () => {+ expect(editorArgv({ code: '/usr/local/bin/code', isMac: true, isRemote: false }, '/h/p.md')).toEqual(['/usr/local/bin/code', '--wait', '/h/p.md'])+ expect(editorArgv({ code: '', isMac: true, isRemote: false }, '/h/p.md')).toEqual(['open', '-W', '-t', '/h/p.md'])+ expect(editorArgv({ code: '', isMac: true, isRemote: true }, '/h/p.md')).toBe(null)+ expect(editorArgv({ code: '', isMac: false, isRemote: false }, '/h/p.md')).toBe(null)+})++test('only the question md-preview asks now is the plan question', () => {+ const q = (question: string, header = PLAN_HEADER) => [{ question, header, options: [], multiSelect: false }]+ expect(isPlanQuestion(q(PLAN_QUESTION), PLAN_QUESTION)).toBe(true)+ expect(isPlanQuestion(q(PLAN_QUESTION), '')).toBe(false)+ expect(isPlanQuestion(q(PLAN_QUESTION, 'Other'), PLAN_QUESTION)).toBe(false)+ expect(isPlanQuestion(q('Which one?'), PLAN_QUESTION)).toBe(false)+ expect(isPlanQuestion([...q(PLAN_QUESTION), ...q(PLAN_QUESTION)], PLAN_QUESTION)).toBe(false)+})++test('Claude is told that a plan is drawn like an answer', () => {+ expect(TYPST_PROMPT).toContain('A plan (the plan file you write in plan mode) is drawn the same way when ExitPlanMode asks for approval')+ expect(TYPST_PROMPT).not.toContain('do not use typst blocks')+ expect(TYPST_PROMPT.endsWith('keep replies readable as plain text too.')).toBe(true)+})++// ---- The hooks ----------------------------------------------------------------++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'+const ENGINE = { type: 'Text', props: {}, children: ['engine drawing'] }+const PLANS = '/h/.claude/plans'+const FILE = `${PLANS}/p.md`+const PLAN = '# Plan\n\n1. Read the code.\n2. Change it.'+const EDITED = '# Plan\n\n1. Read the code.\n2. Change it.\n3. Test it.'++// A Mac terminal that draws (forced), with Typst, session sid-1 in /w/app.+// `answers` answer md-preview's questions in order (null: Esc). The engine's+// ExitPlanMode raises PermissionRequest as the engine does: md-preview's+// decision, else the engine's dialog (`engineAsks`, which approves).+function world($: any, on: any, o: {+ vars?: Record<string, string>+ answers?: (string | null)[]+ code?: boolean+ surfaces?: string[]+ edit?: string+ failCompile?: boolean+ raise?: boolean+ onAsk?: () => Promise<void>+} = {}) {+ mock.store(on)+ const clock = mock.clock(on)+ mock.env(on, { HOME: '/h', CLAUDE_CODE_FORCE_TERMINAL_IMAGES: '1', ...o.vars })+ const compiled: string[] = []+ const asked: any[] = []+ const edits: string[][] = []+ const decisions: any[] = []+ const aborts: string[] = []+ const commands: string[] = []+ const submits: any[] = []+ let engineAsks = 0+ const answers = [...(o.answers ?? [])]+ const files = new Map<string, string>([[FILE, PLAN]])+ on('process.run', async ($: any, e: any) => {+ const argv: string[] = e.argv+ const cmd = argv.join(' ')+ 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)+ if (o.edit !== undefined) files.set(FILE, o.edit)+ return ok('')+ }+ return ok('', 1)+ })+ on('session.id', async () => ({ value: 'sid-1' }))+ on('session.cwd', async () => ({ value: '/w/app' }))+ on('session.root', async () => ({ value: '/w/app' }))+ on('session.surfaces', async () => ({ value: o.surfaces ?? ['terminal'] }))+ 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) => {+ if (files.has(e.path)) return { value: files.get(e.path) }+ return e.path.startsWith('/c/') || e.path.startsWith('/h/') || e.path.startsWith('/w/') ? { deny: 'ENOENT' } : next(e)+ })+ on('fs.list', async ($: any, e: any, next: any) => {+ if (e.path.startsWith('/c/')) return { value: [{ name: 'a-1.png', kind: 'file', size: 1, mtimeMs: 1, isLink: false }] }+ return e.path.startsWith('/h/') || e.path.startsWith('/w/') ? { deny: 'ENOENT' } : next(e)+ })+ on('ui.toast', async () => ({ value: undefined }))+ on('turn.abort', async ($: any, e: any) => (aborts.push(e.turnId), { value: undefined }))+ on('command.run', { command: 'clear' }, async ($: any, e: any) => (commands.push(e.command), { text: '' }))+ on('prompt.submit', async ($: any, e: any) => (submits.push(e), { text: e.text }))+ // $.ui.ask runs as a call of the AskUserQuestion tool.+ on('tool.call', { tool: 'AskUserQuestion' }, async ($: any, e: any) => {+ const qs = e.questions+ asked.push(qs[0])+ await o.onAsk?.()+ const answer = answers.shift()+ if (answer === null || answer === undefined) return { deny: 'dismissed' }+ return { result: { questions: qs, answers: { [qs[0].question]: answer } } }+ })+ on('classic.PermissionRequest', async () => {+ engineAsks+++ return {}+ })+ on('tool.call', { tool: 'ExitPlanMode' }, async (_: any, e: any) => {+ if (o.raise === false) return { result: { plan: e.plan, isAgent: false, filePath: FILE } }+ const got: any = await $.classic.PermissionRequest({+ tool_name: 'ExitPlanMode', tool_input: { plan: e.plan, planFilePath: e.planFilePath }, permission_mode: 'plan',+ ...(e.agentId ? { agent_id: e.agentId } : {}),+ })+ decisions.push(got.decision)+ if (got.decision?.behavior === 'deny') return { deny: got.decision.message }+ return { result: { plan: got.decision?.updatedInput?.plan ?? e.plan, isAgent: false, filePath: FILE } }+ })+ // The dialog is the engine's own node (a dialog tree must hold it once).+ on('ui.render', ($: any, e: any) => (e.component === 'AskUserQuestion' ? { type: 'engine', ref: 0 } : ENGINE))+ return { clock, compiled, asked, edits, decisions, aborts, commands, submits, files, engineAsks: () => engineAsks }+}++const use = (o: { id?: string; input?: unknown; output?: unknown; isRunning?: boolean; isErrored?: boolean } = {}) =>+ ({+ plugin: 'md-preview', surface: 'terminal', component: 'ToolUse', requestId: o.id ?? 'tu-plan',+ props: {+ tool_use_id: o.id ?? 'tu-plan', tool: 'ExitPlanMode', input: o.input ?? { plan: PLAN, planFilePath: FILE },+ isRunning: o.isRunning ?? true, isErrored: o.isErrored ?? false, isInterrupted: false, output: o.output,+ },+ viewport: { columns: 100, rows: 40 },+ }) as any+const result = (output: unknown, isErrored = false, id = 'tu-plan') =>+ ({+ plugin: 'md-preview', surface: 'terminal', component: 'ToolResult', requestId: id,+ props: { tool_use_id: id, tool: 'ExitPlanMode', output, isErrored }, viewport: { columns: 100, rows: 40 },+ }) as any+const dialog = (question: string, header = PLAN_HEADER, id = 'tu-ask') =>+ ({+ plugin: 'md-preview', surface: 'terminal', component: 'AskUserQuestion', requestId: id,+ props: { tool: 'AskUserQuestion', questions: [{ question, header, options: [{ label: 'A', description: '' }, { label: 'B', description: '' }], multiSelect: false }] },+ viewport: { columns: 100, rows: 40 },+ }) as any+const approved = { plan: PLAN, isAgent: false, filePath: FILE }+const images = (tree: any): any[] =>+ tree && typeof tree === 'object' ? [...(tree.type === 'Image' ? [tree] : []), ...(tree.children ?? []).flatMap(images)] : []+const texts = (tree: any): string[] =>+ typeof tree === 'string' ? [tree] : tree && typeof tree === 'object' ? (tree.children ?? []).flatMap(texts) : []+// Sets the mod up (as the first answer would) before a row draws.+const ready = ($: any) => $.command.run({ command: 'md-preview', args: '' } as any)+// ExitPlanMode as the engine calls it: the plan and its file on the envelope.+const exitPlan = ($: any, more: Record<string, unknown> = {}) =>+ $.tool.call({ tool: 'ExitPlanMode', tool_use_id: 'tu-plan', plan: PLAN, planFilePath: FILE, ...more } as any)+const setMode = (mode: string) => [{ type: 'setMode', mode, destination: 'session' }]++test('the ExitPlanMode row draws the plan as pictures under the engine row, at an answer width', async ($, on) => {+ const { clock, compiled } = world($, on)+ await ready($)+ const ui = await $.ui.mount(use())+ await clock.settle()+ expect(compiled).toEqual([PLAN])+ await ui.redraw(use().props)+ const tree: any = await ui.drawn()+ expect(tree.children[0]).toMatchObject(ENGINE)+ const [image] = images(tree)+ expect(image.props.columns).toBe(98)+ expect(image.props.source).toMatchObject({ format: 'png' })+ expect(texts(tree).join('\n')).not.toContain(PLAN_DRAWING)+})++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($)+ const ui = await $.ui.mount(use())+ await clock.settle()+ await clock.advance(5000)+ await ui.redraw(use().props)+ expect(await ui.drawn()).toMatchObject(ENGINE)+ expect(await (await $.ui.mount(use({ id: 'tu-2', isErrored: true, isRunning: false }))).drawn()).toMatchObject(ENGINE)+ await exitPlan($, { tool_use_id: 'tu-sub', agentId: 'agent-1' })+ expect(await (await $.ui.mount(use({ id: 'tu-sub' }))).drawn()).toMatchObject(ENGINE)+ expect(await (await $.ui.mount(use({ id: 'tu-3', output: { plan: PLAN, isAgent: true }, isRunning: false }))).drawn()).toMatchObject(ENGINE)+})++test('the approved result keeps the header alone, as the ToolUse row draws the plan', async ($, on) => {+ const { clock } = world($, on)+ await ready($)+ await $.ui.mount(use())+ await clock.settle()+ const tree: any = await (await $.ui.mount(result(approved))).drawn()+ const shown = texts(tree).join('\n')+ expect(shown).toContain("User approved Claude's plan")+ expect(shown).toContain('Plan saved to: ~/.claude/plans/p.md · /plan to edit')+ expect(shown).not.toContain('Read the code.')+ expect(images(tree)).toEqual([])+})++test('an errored, empty or subagent result stays as the engine draws it', async ($, on) => {+ const { clock, compiled } = world($, on)+ await ready($)+ const rows = [+ result(approved, true, 'tu-1'),+ result({ plan: '', isAgent: false }, false, 'tu-2'),+ result({ plan: null, isAgent: false }, false, 'tu-3'),+ result({ plan: PLAN, isAgent: true }, false, 'tu-4'),+ ]+ for (const row of rows) expect(await (await $.ui.mount(row)).drawn()).toMatchObject(ENGINE)+ await clock.settle()+ expect(compiled).toEqual([])+})++test('approve with auto-accept: the PermissionRequest allows with the input and acceptEdits, no engine dialog', async ($, on) => {+ const w = world($, on, { answers: [PLAN_AUTO], code: true })+ await ready($)+ const got: any = await exitPlan($)+ expect(w.asked).toMatchObject([{ question: PLAN_QUESTION, header: PLAN_HEADER }])+ expect(w.asked[0].options.map((x: any) => x.label)).toEqual([PLAN_AUTO, PLAN_MANUAL, PLAN_CLEAR, PLAN_EDIT])+ expect(w.decisions).toEqual([{ behavior: 'allow', updatedInput: { plan: PLAN, planFilePath: FILE }, updatedPermissions: setMode('acceptEdits') }])+ expect(w.engineAsks()).toBe(0)+ expect(got.result.plan).toBe(PLAN)+ expect(w.aborts).toEqual([])+})++test('approve with manual edits: the mode is default; with no editor the edit option is left out', async ($, on) => {+ const w = world($, on, { answers: [PLAN_MANUAL], vars: { SSH_CONNECTION: '1 2 3 4' } })+ await ready($)+ await exitPlan($)+ expect(w.asked[0].options.map((x: any) => x.label)).toEqual([PLAN_AUTO, PLAN_MANUAL, PLAN_CLEAR])+ expect(w.decisions).toMatchObject([{ behavior: 'allow', updatedPermissions: setMode('default') }])+})++test('typed words deny the call with feedback, and no verdict is left', async ($, on) => {+ const w = world($, on, { answers: ['Also add tests'] })+ await ready($)+ const got: any = await exitPlan($)+ expect(JSON.stringify(got)).toContain('The user wants changes to the plan: Also add tests')+ expect(w.decisions).toEqual([])+ await $.classic.PermissionRequest({ tool_name: 'ExitPlanMode', tool_input: { plan: PLAN }, permission_mode: 'plan' } as any)+ expect(w.engineAsks()).toBe(1)+})++test('Esc rejects the plan: the PermissionRequest denies and interrupts', async ($, on) => {+ const w = world($, on, { answers: [null] })+ await ready($)+ const got: any = await exitPlan($)+ expect(w.decisions).toEqual([{ behavior: 'deny', message: PLAN_REJECTED, interrupt: true }])+ expect(JSON.stringify(got)).toContain(PLAN_REJECTED)+ expect(w.engineAsks()).toBe(0)+})++test('a plan written in the same message waits for the write, then the new text is asked, sent and drawn', async ($, on) => {+ const w = world($, on, { answers: [PLAN_AUTO], code: true })+ // Claude's Write of the plan file, still running when ExitPlanMode starts.+ on('tool.call', { tool: 'Write' }, async (_: any, e: any) => {+ await w.clock.sleep(100)+ w.files.set(e.file_path, EDITED)+ return { result: { type: 'update', filePath: e.file_path, content: e.content, structuredPatch: [], originalFile: PLAN } }+ })+ await ready($)+ const writing = $.tool.call({ tool: 'Write', file_path: FILE, content: EDITED } as any)+ await w.clock.settle()+ // The call carries the file as it was before the write.+ const call = exitPlan($)+ await w.clock.settle()+ expect(w.asked).toEqual([])+ await w.clock.advance(100)+ await writing+ const got: any = await call+ expect(w.asked.map(q => q.question)).toEqual([PLAN_QUESTION])+ expect(w.decisions).toMatchObject([{ behavior: 'allow', updatedInput: { plan: EDITED, planFilePath: FILE } }])+ expect(got.result.plan).toBe(EDITED)+ await $.ui.mount(use())+ await w.clock.settle()+ expect(w.compiled).toEqual([EDITED])+})++test('the plan waits at most 5 s for a write that does not end', async ($, on) => {+ const w = world($, on, { answers: [PLAN_AUTO] })+ on('tool.call', { tool: 'Write' }, async () => new Promise(() => undefined))+ await ready($)+ void $.tool.call({ tool: 'Write', file_path: FILE, content: EDITED } as any)+ await w.clock.settle()+ const call = exitPlan($)+ await w.clock.advance(4900)+ expect(w.asked).toEqual([])+ await w.clock.advance(200)+ const got: any = await call+ expect(w.asked.length).toBe(1)+ expect(got.result.plan).toBe(PLAN)+})++test('edit: VS Code opens the file, the edited plan is asked again, sent and drawn', async ($, on) => {+ const w = world($, on, { answers: [PLAN_EDIT, PLAN_AUTO], code: true, edit: EDITED })+ await ready($)+ const got: any = await exitPlan($)+ expect(w.edits).toEqual([['/usr/local/bin/code', '--wait', FILE]])+ expect(w.asked.map(q => q.question)).toEqual([PLAN_QUESTION, PLAN_QUESTION_EDITED])+ expect(w.decisions).toMatchObject([{ behavior: 'allow', updatedInput: { plan: EDITED, planFilePath: FILE } }])+ expect(got.result.plan).toBe(EDITED)+ // The row draws the edited text, the call's input notwithstanding.+ await $.ui.mount(use())+ await w.clock.settle()+ expect(w.compiled).toEqual([EDITED])+})++test('edit with no VS Code on a Mac uses TextEdit', async ($, on) => {+ const w = world($, on, { answers: [PLAN_EDIT, PLAN_MANUAL], edit: PLAN })+ await ready($)+ await exitPlan($)+ expect(w.edits).toEqual([['open', '-W', '-t', FILE]])+ // The file did not change: the same question, and the plan as it was.+ expect(w.asked.map(q => q.question)).toEqual([PLAN_QUESTION, PLAN_QUESTION])+ expect(w.decisions).toMatchObject([{ behavior: 'allow', updatedInput: { plan: PLAN } }])+})++test('clear context: once approved, the turn ends, /clear runs and the plan is sent', async ($, on) => {+ const w = world($, on, { answers: [PLAN_CLEAR] })+ await ready($)+ await $.turn.start({ text: 'plan it', turnId: 'turn-1' } as any).catch(() => undefined)+ await exitPlan($)+ expect(w.decisions).toMatchObject([{ behavior: 'allow', updatedPermissions: setMode('acceptEdits') }])+ expect(w.commands).toEqual([])+ await w.clock.advance(100)+ await w.clock.settle()+ expect(w.aborts).toEqual(['turn-1'])+ expect(w.commands).toEqual(['clear'])+ expect(w.submits).toMatchObject([{ text: `Implement this plan:\n\n${PLAN}`, origin: { kind: 'plugin', asUser: true } }])+})++test('with md-preview off, the engine dialog asks and the row stays as the engine draws it', async ($, on) => {+ const off = world($, on, { answers: [PLAN_AUTO] })+ await ready($)+ await $.command.run({ command: 'md-preview', args: 'off' } as any)+ const got: any = await exitPlan($)+ expect(got.result.plan).toBe(PLAN)+ expect(off.asked).toEqual([])+ expect(off.engineAsks()).toBe(1)+ expect(await (await $.ui.mount(use())).drawn()).toMatchObject(ENGINE)+})++test('in a terminal that draws no pictures, the engine dialog asks', async ($, on) => {+ const w = world($, on, { answers: [PLAN_AUTO], vars: { CLAUDE_CODE_FORCE_TERMINAL_IMAGES: '', TERM: 'xterm-256color' } })+ await ready($)+ await exitPlan($)+ expect(w.asked).toEqual([])+ expect(w.engineAsks()).toBe(1)+})++test('with no terminal surface, the engine dialog asks', async ($, on) => {+ const w = world($, on, { answers: [PLAN_AUTO], surfaces: [] })+ await ready($)+ await exitPlan($)+ expect(w.asked).toEqual([])+ expect(w.engineAsks()).toBe(1)+})++test('a subagent ExitPlanMode is not asked about', async ($, on) => {+ const w = world($, on, { answers: [PLAN_AUTO] })+ await ready($)+ await exitPlan($, { tool_use_id: 'tu-sub', agentId: 'agent-1' })+ expect(w.asked).toEqual([])+ expect(w.engineAsks()).toBe(1)+})++test('a call with no plan is not asked about', async ($, on) => {+ const w = world($, on, { answers: [PLAN_AUTO] })+ await ready($)+ await exitPlan($, { plan: '' })+ expect(w.asked).toEqual([])+ expect(w.engineAsks()).toBe(1)+})++test('a verdict whose PermissionRequest never came does not reach a later call', async ($, on) => {+ const w = world($, on, { answers: [PLAN_AUTO], raise: false })+ await ready($)+ await exitPlan($)+ expect(w.asked.length).toBe(1)+ await $.classic.PermissionRequest({ tool_name: 'ExitPlanMode', tool_input: { plan: PLAN }, permission_mode: 'plan' } as any)+ expect(w.engineAsks()).toBe(1)+})++test('the line above the dialog is for the md-preview question alone', async ($, on) => {+ let during: any = null+ let other: any = null+ // Draws the dialogs while md-preview's question is asked.+ const w = world($, on, {+ answers: [PLAN_AUTO],+ onAsk: async () => {+ during = await (await $.ui.mount(dialog(PLAN_QUESTION))).drawn()+ other = await (await $.ui.mount(dialog('Which one?', 'Pick', 'tu-ask-2'))).drawn()+ },+ })+ await ready($)+ await exitPlan($)+ expect(w.asked.length).toBe(1)+ expect(texts(during)[0]).toBe(PLAN_ASK_LINE)+ expect(during.children[1]).toMatchObject({ type: 'engine' })+ expect(other).toMatchObject({ type: 'engine' })+ // Once answered, the same question draws as the engine's.+ expect(await (await $.ui.mount(dialog(PLAN_QUESTION, PLAN_HEADER, 'tu-ask-3'))).drawn()).toMatchObject({ type: 'engine' })+})diff --git a/tests/pure.test.ts b/tests/pure.test.tsindex e0bb63e..1455c46 100644--- a/tests/pure.test.ts+++ b/tests/pure.test.ts@@ -4,6 +4,9 @@ import {alignFirstLine, DEFAULT_METRICS, DEFAULT_SIZE, firstLineOf, fontFit, ghosttyFontOf, itermFontOf, parseCommand, parseFontSpec, typstCall,blocksOf, canDrawIn, cellOf, columnsFor, DEFAULT_CELL, hashOf, imagePathOf, isSet, localImages, MAX_COLUMNS,parseOd, plainOf, pngSize, rowsFor, shouldRetrySafe, 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,} from '../hooks/register'@@ -139,6 +142,8 @@ test('the size command takes 80 to 200 percent', () => {expect(parseCommand('size')).toEqual({ kind: 'bad' })expect(parseCommand('size big')).toEqual({ kind: 'bad' })expect(parseCommand('bigger')).toEqual({ kind: 'bad' })+ expect(parseCommand('probe')).toEqual({ kind: 'probe' })+ expect(parseCommand('probe 3')).toEqual({ kind: 'bad' })})test('the first line of an answer is told by how it starts', () => {@@ -272,7 +277,7 @@ test('the alt is one short plain line', () => {})test('pictures draw where Claude Code draws them: kitty and Ghostty, or forced', () => {- const base = { program: '', term: 'xterm-256color', kitty: false, tmux: false, ssh: false, engineForced: false, modForced: false }+ const base = { program: '', term: 'xterm-256color', kitty: false, tmux: false, ssh: false, background: false, engineForced: false, modForced: false }expect(canDrawIn({ ...base, program: 'ghostty' })).toBe(true)expect(canDrawIn({ ...base, term: 'xterm-ghostty' })).toBe(true)expect(canDrawIn({ ...base, term: 'xterm-kitty' })).toBe(true)@@ -284,9 +289,9 @@ test('pictures draw where Claude Code draws them: kitty and Ghostty, or forced',expect(canDrawIn({ ...base, program: 'WarpTerminal' })).toBe(false)expect(canDrawIn({ ...base, program: 'Apple_Terminal' })).toBe(false)expect(canDrawIn({ ...base, program: 'ghostty', tmux: true })).toBe(false)- expect(canDrawIn({ ...base, program: 'ghostty', tmux: true, engineForced: true })).toBe(true)+ expect(canDrawIn({ ...base, program: 'ghostty', tmux: true, engineForced: true })).toBe(false)expect(canDrawIn({ ...base, program: 'ghostty', ssh: true })).toBe(false)- expect(canDrawIn({ ...base, program: 'iTerm.app', ssh: true, engineForced: true })).toBe(false)+ expect(canDrawIn({ ...base, program: 'iTerm.app', ssh: true, engineForced: true })).toBe(true)expect(canDrawIn({ ...base, ssh: true, modForced: true })).toBe(true)expect(canDrawIn({ ...base, modForced: true })).toBe(true)})@@ -418,3 +423,127 @@ test('the font measure reads the active theme, with the root at /', () => {expect(argv).toContain('theme-dir=/u/nord')expect(argv).toContain('term-font=MesloLGS NF')})++test('the Claude Code theme setting is fixed light, fixed dark, or auto', () => {+ for (const v of ['light', 'light-daltonized', 'light-ansi']) expect(settingOf(v)).toBe('light')+ for (const v of ['dark', 'dark-daltonized', 'dark-ansi', undefined, '', true]) expect(settingOf(v)).toBe('dark')+ for (const v of ['auto', 'system', 'something-new']) expect(settingOf(v)).toBe('auto')+})++test('the OS appearance is read from macOS, GNOME and COLORFGBG', () => {+ expect(modeOfMacAppearance(0, 'Dark\n')).toBe('dark')+ expect(modeOfMacAppearance(1, '')).toBe('light')+ expect(modeOfMacAppearance(0, '')).toBe('light')+ expect(modeOfGnome("'prefer-dark'\n")).toBe('dark')+ expect(modeOfGnome("'prefer-light'")).toBe('light')+ expect(modeOfGnome("'default'")).toBe('light')+ expect(modeOfGnome('No such key')).toBe(null)+ expect(modeOfColorFgBg('15;0')).toBe('dark')+ expect(modeOfColorFgBg('0;15')).toBe('light')+ expect(modeOfColorFgBg('0;default;7')).toBe('light')+ expect(modeOfColorFgBg('7;8')).toBe('dark')+ expect(modeOfColorFgBg('0;11')).toBe(null)+ expect(modeOfColorFgBg('')).toBe(null)+ expect(modeOfColorFgBg(undefined)).toBe(null)+})++test("iTerm2's appearance and its profile's background give the mode", () => {+ expect(itermAppearanceOf('1\n')).toBe('dark')+ expect(itermAppearanceOf('3')).toBe('dark')+ expect(itermAppearanceOf('0')).toBe('light')+ expect(itermAppearanceOf('2')).toBe('light')+ for (const v of ['4', '5', '6', '']) expect(itermAppearanceOf(v)).toBe(null)+ const dark = { 'Red Component': 0.11, 'Green Component': 0.15, 'Blue Component': 0.17 }+ const white = { 'Red Component': 1, 'Green Component': 1, 'Blue Component': 1 }+ const marks = JSON.stringify([+ { Name: 'Default', Guid: 'G1', 'Use Separate Colors for Light and Dark Mode': true, 'Background Color': dark, 'Background Color (Dark)': dark, 'Background Color (Light)': white },+ { Name: 'Paper', Guid: 'G2', 'Background Color': white },+ ])+ // Separate colours: the set for iTerm2's appearance (the OS's, when it follows it).+ expect(itermModeOf(marks, 'Default', 'G1', 'dark')).toBe('dark')+ expect(itermModeOf(marks, 'Default', 'G1', 'light')).toBe('light')+ expect(itermModeOf(marks, 'Default', 'G1', null)).toBe(null)+ // One set of colours: the appearance does not matter.+ expect(itermModeOf(marks, 'Paper', 'G1', 'dark')).toBe('light')+ expect(itermModeOf(marks, undefined, 'G2\n', null)).toBe('light')+ expect(itermModeOf(marks, 'Gone', 'nope', 'dark')).toBe(null)+ expect(itermModeOf('not json', 'Default', 'G1', 'dark')).toBe(null)+})++test("Ghostty's background comes from its config, its theme, or its default", () => {+ expect(hexColorOf('#282c34')).toEqual({ r: 0x28 / 255, g: 0x2c / 255, b: 0x34 / 255 })+ expect(hexColorOf('FFFFFF')).toEqual({ r: 1, g: 1, b: 1 })+ expect(hexColorOf('black')).toBe(null)+ expect(ghosttyValueOf('background = #111111\nfont-family = "A B"\nbackground = #222222', 'background')).toBe('#222222')+ expect(ghosttyValueOf('font-family = "A B"', 'font-family')).toBe('A B')+ expect(ghosttyValueOf('', 'theme')).toBe('')+ expect(ghosttyThemesOf('light:3024 Day,dark:Rose Pine')).toEqual({ light: '3024 Day', dark: 'Rose Pine' })+ expect(ghosttyThemesOf(' dark: Rose Pine , light: Rose Pine Dawn ')).toEqual({ light: 'Rose Pine Dawn', dark: 'Rose Pine' })+ expect(ghosttyThemesOf('Rose Pine')).toBe(null)+ expect(ghosttyThemesOf('light:Only')).toBe(null)+ const where = { home: '/h', resources: '/R' }+ expect(ghosttyThemePaths('Nord', where)).toEqual([+ '/h/.config/ghostty/themes/Nord', '/h/Library/Application Support/com.mitchellh.ghostty/themes/Nord', '/R/themes/Nord',+ '/Applications/Ghostty.app/Contents/Resources/ghostty/themes/Nord', '/usr/share/ghostty/themes/Nord',+ ])+ expect(ghosttyThemePaths('Nord', { ...where, xdgConfig: '/x' })[0]).toBe('/x/ghostty/themes/Nord')+ expect(ghosttyThemePaths('/t/Mine', where)).toEqual(['/t/Mine'])+ expect(ghosttyThemePaths('~/t/Mine', where)).toEqual(['/h/t/Mine'])+ // No theme, no background: the default. A single theme: show-config merged it in.+ expect(ghosttyBackgroundOf('font-size = 13', null, {})).toBe(GHOSTTY_DEFAULT_BG)+ expect(ghosttyBackgroundOf('theme = Rose Pine Dawn\nbackground = #faf4ed', null, {})).toBe('#faf4ed')+ // light:A,dark:B: the shown background is one theme's; the OS picks the theme.+ const pair = 'theme = light:3024 Day,dark:Rose Pine\nbackground = #f7f7f7'+ const bgs = { light: '#f7f7f7', dark: '#191724' }+ expect(ghosttyBackgroundOf(pair, 'dark', bgs)).toBe('#191724')+ expect(ghosttyBackgroundOf(pair, 'light', bgs)).toBe('#f7f7f7')+ expect(ghosttyBackgroundOf(pair, null, bgs)).toBe(null)+ // A background of the config's own wins over both themes.+ expect(ghosttyBackgroundOf('theme = light:3024 Day,dark:Rose Pine\nbackground = #112233', 'light', bgs)).toBe('#112233')+})++test('auto draws as the OS is; a fixed setting ignores the OS', () => {+ const lightMac = { mode: 'light' as const, source: 'macOS' as const }+ expect(resolveMode('auto', lightMac)).toBe('light')+ expect(resolveMode('auto', null)).toBe('dark')+ expect(resolveMode('dark', lightMac)).toBe('dark')+ expect(resolveMode('light', null)).toBe('light')+ expect(modeLine('light', 'auto', 'auto', lightMac)).toBe('mode light (auto, from macOS)')+ expect(modeLine('dark', 'auto', 'auto', null)).toBe('mode dark (auto, OS appearance not known, dark assumed)')+ expect(modeLine('dark', 'dark', 'dark-ansi', null)).toBe('mode dark (Claude Code theme dark-ansi)')+})++test('the iTerm2 profile for the font is the one ITERM_PROFILE names, else the default one', () => {+ const marks = [{ Name: 'Default', Guid: 'G1' }, { Name: 'tmux', Guid: 'G2' }, 'not a profile']+ expect(pickProfile(marks, 'tmux', 'G1')?.Guid).toBe('G2')+ expect(pickProfile(marks, 'gone', 'G1')?.Name).toBe('Default')+ expect(pickProfile(marks, undefined, ' G2\n')?.Name).toBe('tmux')+ expect(pickProfile(marks, 'gone', 'G9')).toBe(null)+})++test("the terminal's OSC 11 answer is read with BEL or ST and 1-4 hex digits", () => {+ expect(parseOsc11('\x1b]11;rgb:ffff/ffff/ffff\x07')).toEqual({ r: 1, g: 1, b: 1 })+ expect(parseOsc11('\x1b]11;rgb:28/2c/34\x1b\\')).toEqual({ r: 0x28 / 255, g: 0x2c / 255, b: 0x34 / 255 })+ expect(parseOsc11('junk\x1b]11;rgb:1d1d/2525/2a2a\x07more')).toEqual({ r: 0x1d1d / 65535, g: 0x2525 / 65535, b: 0x2a2a / 65535 })+ expect(parseOsc11('\x1b]11;rgb:f/0/8\x07')).toEqual({ r: 1, g: 0, b: 8 / 15 })+ expect(parseOsc11('\x1b]11;rgba:ffff/ffff/ffff/ffff\x07')).toEqual({ r: 1, g: 1, b: 1 })+ for (const bad of ['', 'rgb:ffff/ffff/ffff', '\x1b]11;rgb:ffff/ffff\x07', '\x1b]11;rgb:fffff/0/0\x07', '\x1b]11;rgb:ffff/ffff/ffff', '\x1b]10;rgb:ffff/ffff/ffff\x07']) {+ expect(parseOsc11(bad)).toBe(null)+ }+})++test('luminance gives the mode: light above 0.4', () => {+ const near1 = (a: number, b: number) => expect(Math.abs(a - b)).toBeLessThan(1e-3)+ near1(luminanceOf({ r: 1, g: 1, b: 1 }), 1)+ near1(luminanceOf({ r: 0.5, g: 0.5, b: 0.5 }), 0.214)+ expect(modeOfLuminance(luminanceOf(parseOsc11('\x1b]11;rgb:ffff/ffff/ffff\x07')!))).toBe('light')+ expect(modeOfLuminance(luminanceOf(parseOsc11('\x1b]11;rgb:1d1d/2525/2a2a\x07')!))).toBe('dark')+ expect(modeOfLuminance(luminanceOf({ r: 0.75, g: 0.75, b: 0.75 }))).toBe('light')+})++test('the probe output is shown with its control characters spelled out', () => {+ expect(escapeControls('\x1b]11;rgb:ffff/ffff/ffff\x07')).toBe('\\e]11;rgb:ffff/ffff/ffff\\a')+ expect(escapeControls('a\x1b\\\x01')).toBe('a\\e\\\\x01')+ expect(OSC11_PL).toContain('O_NONBLOCK')+ expect(OSC11_PL).not.toContain('stty')+})diff --git a/tests/setup.test.ts b/tests/setup.test.tsnew file mode 100644index 0000000..db6b41f--- /dev/null+++ b/tests/setup.test.ts@@ -0,0 +1,98 @@+import { expect, mock, test } from 'claude-code/testing'++import { hasSetup, parseCommand, SETUP_END, SETUP_START, setupBlock, shellRcOf, withoutSetup, withSetup } from '../hooks/register'++test('the setup writes the start file of the login shell', () => {+ expect(shellRcOf({ shell: '/bin/zsh', home: '/h', isMac: true })).toEqual({ path: '/h/.zshrc', kind: 'sh' })+ expect(shellRcOf({ shell: '/bin/zsh', home: '/h', zdotdir: '/z', isMac: true })!.path).toBe('/z/.zshrc')+ expect(shellRcOf({ shell: '/bin/bash', home: '/h', isMac: true })!.path).toBe('/h/.bash_profile')+ expect(shellRcOf({ shell: '/bin/bash', home: '/h', isMac: false })!.path).toBe('/h/.bashrc')+ expect(shellRcOf({ shell: '/opt/homebrew/bin/fish', home: '/h', isMac: true })).toEqual({ path: '/h/.config/fish/conf.d/md-preview.fish', kind: 'fish' })+ expect(shellRcOf({ shell: '/bin/tcsh', home: '/h', isMac: true })).toBe(null)+})++test('the block sets the variable in iTerm2 only, not in tmux or screen', () => {+ const sh = setupBlock('sh')+ expect(sh.startsWith(`${SETUP_START}\n`)).toBe(true)+ expect(sh.endsWith(`${SETUP_END}\n`)).toBe(true)+ expect(sh).toContain('[ "$TERM_PROGRAM" = "iTerm.app" ] && [ -z "$TMUX" ] && [ -z "$STY" ]; then export CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1; fi')+ expect(setupBlock('fish')).toContain('set -gx CLAUDE_CODE_FORCE_TERMINAL_IMAGES 1')+})++test('adding the block twice keeps one; removing it gives the file back', () => {+ const rc = 'export PATH=/x:$PATH\nalias ll="ls -l"\n'+ const once = withSetup(rc, 'sh')+ expect(hasSetup(once)).toBe(true)+ expect(withSetup(once, 'sh')).toBe(once)+ expect(once.split(SETUP_START).length).toBe(2)+ expect(withoutSetup(once)).toBe('export PATH=/x:$PATH\nalias ll="ls -l"\n')+ expect(withSetup('', 'sh')).toBe(setupBlock('sh'))+ // A start marker with no end marker is left as it is.+ expect(withoutSetup(`a\n${SETUP_START}\nb`)).toBe(`a\n${SETUP_START}\nb`)+})++test('/md-preview setup and setup remove are commands', () => {+ expect(parseCommand('setup')).toEqual({ kind: 'setup', remove: false })+ expect(parseCommand('Setup Remove')).toEqual({ kind: 'setup', remove: true })+ expect(parseCommand('setup now')).toEqual({ kind: 'bad' })+})++// An iTerm2 session on a Mac with the engine's pictures off and a zsh user.+const iterm = (on: any, files: Record<string, string>, answer: string | null) => {+ mock.store(on)+ const clock = mock.clock(on)+ mock.env(on, { HOME: '/h', SHELL: '/bin/zsh', TERM_PROGRAM: 'iTerm.app', ITERM_PROFILE: 'Default' })+ const asked: string[] = []+ // $.ui.ask runs as a call of the AskUserQuestion tool.+ on('tool.call', { tool: 'AskUserQuestion' }, async ($: any, e: any) => {+ const qs = e.questions+ asked.push(qs[0].question)+ if (answer === null) return { deny: 'dismissed' }+ return { result: { questions: qs, answers: { [qs[0].question]: answer } } }+ })+ const toasts: string[] = []+ const logs: string[] = []+ on('ui.toast', async ($: any, e: any) => (toasts.push(e.text), { value: undefined }))+ on('ui.log', async ($: any, e: any) => (logs.push(e.text), { value: undefined }))+ on('process.run', async ($: any, e: any, next: any) =>+ e.argv[0] === 'sh' && /md-preview-/.test(e.argv.join(' '))+ ? { value: { exitCode: 0, stdout: '/tmp/mdp\nDarwin\n', stderr: '', isStdoutTruncated: false, isStderrTruncated: false } }+ : next(e))+ on('fs.read', async ($: any, e: any, next: any) => (e.path in files ? { value: files[e.path] } : e.path.startsWith('/h/') ? { deny: 'no such file' } : next(e)))+ on('fs.exists', async ($: any, e: any, next: any) => (e.path.startsWith('/h/') ? { value: e.path in files } : next(e)))+ on('fs.write', async ($: any, e: any, next: any) => {+ if (!e.path.startsWith('/h/')) return next(e)+ files[e.path] = e.text+ return { value: undefined }+ })+ return { asked, clock, toasts, logs }+}++test('in iTerm2 with pictures off, the plugin asks once and adds the block on yes', async ($, on) => {+ const files: Record<string, string> = { '/h/.zshrc': 'export A=1\n' }+ const { asked, clock, toasts, logs } = iterm(on, files, 'Add the line')+ const shown = await $.command.run({ command: 'md-preview', args: '' } as any)+ expect(shown.text).toContain('run /md-preview setup once')+ await clock.settle()+ expect(asked.length).toBe(1)+ expect(asked[0]).toContain('~/.zshrc')+ expect(hasSetup(files['/h/.zshrc']!)).toBe(true)+ expect(Object.keys(files)).toEqual(['/h/.zshrc'])+ expect(toasts.filter(t => /tab/.test(t))).toEqual(['Close this tab and open a new iTerm2 tab to see pictures.'])+ expect(logs.some(l => l.includes('Added the md-preview block to /h/.zshrc') && l.includes('Close this tab'))).toBe(true)+ const again = await $.command.run({ command: 'md-preview', args: 'setup' } as any)+ expect(again.text).toContain('already has the md-preview block')+ expect(again.text).toContain('Close this tab, open a new iTerm2 tab')+ const removed = await $.command.run({ command: 'md-preview', args: 'setup remove' } as any)+ expect(removed.text).toContain('Removed the md-preview block from /h/.zshrc')+ expect(files['/h/.zshrc']).toBe('export A=1\n')+})++test('a dismissed question changes no file', async ($, on) => {+ const files: Record<string, string> = { '/h/.zshrc': 'export A=1\n' }+ const { asked, clock } = iterm(on, files, null)+ await $.command.run({ command: 'md-preview', args: '' } as any)+ await clock.settle()+ expect(asked.length).toBe(1)+ expect(files['/h/.zshrc']).toBe('export A=1\n')+})diff --git a/tests/stream.test.ts b/tests/stream.test.tsnew file mode 100644index 0000000..c816bf3--- /dev/null+++ b/tests/stream.test.ts@@ -0,0 +1,155 @@+import { expect, mock, test } from 'claude-code/testing'++// 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'++function world(on: any, o: { fail?: boolean; slow?: Promise<void> } = {}) {+ mock.store(on)+ const clock = mock.clock(on)+ mock.env(on, { HOME: '/h', CLAUDE_CODE_FORCE_TERMINAL_IMAGES: '1' })+ const compiled: string[] = []+ const files = new Map<string, string>()+ on('process.run', async ($: any, e: any, next: any) => {+ const argv: string[] = e.argv+ const cmd = argv.join(' ')+ 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 (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)+ })+ 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)))+ on('ui.toast', async () => ({ value: undefined }))+ return { clock, compiled }+}++const message = (requestId: string, text: string) =>+ ({+ plugin: 'md-preview', surface: 'terminal', component: 'AssistantMessage', requestId,+ props: { text, isFirstOfReply: true }, viewport: { columns: 100, rows: 40 },+ }) as any+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'] }++// A model request the test streams chunk by chunk; `release` ends it.+function request(on: any, more: unknown[] = []) {+ let release!: () => void+ const gate = new Promise<void>(r => (release = r))+ on('turn.step', async function* () {+ yield { kind: 'text', index: 0, text: '# Title' }+ for (const chunk of more) yield chunk+ await gate+ return { turnId: 't', index: 0, answer: '# Title', toolUses: [], stopReason: 'end_turn' }+ })+ return () => release()+}++test('a block draws nothing while it streams, and its picture once the request ends, with no 400 ms wait', async ($, on) => {+ const { clock, compiled } = world(on)+ on('ui.render', () => ENGINE as any)+ const end = request(on)+ // Ready the mod (setUp) before the stream starts.+ 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 ui = await $.ui.mount(message('live-1', '# Ti'))+ expect(isBlank(await ui.drawn())).toBe(true)+ await ui.redraw(props('# Title\n\nSome'))+ expect(isBlank(await ui.drawn())).toBe(true)+ await clock.advance(1500)+ expect(compiled).toEqual([])+ await ui.redraw(props('# Title\n\nSome text.'))+ expect(isBlank(await ui.drawn())).toBe(true)+ end()+ const done = stream.next()+ await clock.settle()+ await done+ expect(compiled).toEqual(['# Title\n\nSome text.'])+ await ui.redraw(props('# Title\n\nSome text.'))+ expect(kinds(await ui.drawn())).toContain('Image')+})++test('a block whose compile fails draws as text', async ($, on) => {+ const { clock } = world(on, { fail: true })+ on('ui.render', () => ENGINE as any)+ await $.command.run({ command: 'md-preview', args: '' } as any)+ const ui = await $.ui.mount(message('fail-1', 'Some **bold** text.'))+ await clock.settle()+ await ui.redraw(props('Some **bold** text.'))+ expect(await ui.drawn()).toMatchObject(ENGINE)+})++test('with no request seen, a changing block is final after 400 ms still', async ($, on) => {+ const { clock, compiled } = world(on)+ on('ui.render', () => ENGINE as any)+ await $.command.run({ command: 'md-preview', args: '' } as any)+ const ui = await $.ui.mount(message('reload-1', 'One'))+ await clock.settle()+ // Seen once (resumed, so final at once); a change outside a request is live.+ await ui.redraw(props('One two'))+ expect(isBlank(await ui.drawn())).toBe(true)+ await clock.advance(300)+ await ui.redraw(props('One two three'))+ await clock.advance(300)+ expect(compiled).toEqual(['One'])+ await clock.advance(150)+ expect(compiled).toEqual(['One', 'One two three'])+ await ui.redraw(props('One two three'))+ expect(kinds(await ui.drawn())).toContain('Image')+})++test('a resumed block compiles at once, blank for at most 1 s, then its text until the picture is ready', async ($, on) => {+ let finish!: () => void+ const slow = new Promise<void>(r => (finish = r))+ const { clock, compiled } = world(on, { slow })+ on('ui.render', () => ENGINE as any)+ await $.command.run({ command: 'md-preview', args: '' } as any)+ const ui = await $.ui.mount(message('old-1', 'An old answer.'))+ expect(isBlank(await ui.drawn())).toBe(true)+ await clock.settle()+ expect(compiled).toEqual(['An old answer.'])+ await clock.advance(1000)+ await ui.redraw(props('An old answer.'))+ expect(await ui.drawn()).toMatchObject(ENGINE)+ finish()+ await clock.settle()+ await ui.redraw(props('An old answer.'))+ expect(kinds(await ui.drawn())).toContain('Image')+})++test('a text block is final when its request moves on to a tool call, before the request ends', async ($, on) => {+ const { clock, compiled } = world(on)+ on('ui.render', () => ENGINE as any)+ const end = request(on, [{ kind: 'tool', index: 1, id: 'toolu_1', name: 'Write' }])+ 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 ui = await $.ui.mount(message('tool-1', 'Let me write the file.'))+ expect(isBlank(await ui.drawn())).toBe(true)+ // The tool chunk: the text block is done though the request goes on.+ await stream.next()+ await clock.settle()+ expect(compiled).toEqual(['Let me write the file.'])+ await ui.redraw(props('Let me write the file.'))+ expect(kinds(await ui.drawn())).toContain('Image')+ end()+ await stream.next()+})diff --git a/tests/terminals.test.ts b/tests/terminals.test.tsnew file mode 100644index 0000000..38982ed--- /dev/null+++ b/tests/terminals.test.ts@@ -0,0 +1,203 @@+import { expect, test } from 'claude-code/testing'++import {+ cmuxAppearanceOf, cmuxSettingsOf, ghosttyHasColors, isItermIn, jsoncOf,+ KITTY_DEFAULT_BG, kittyAutoFileOf, kittyBackgroundOf, kittyConfigDirsOf, kittyEntriesOf, kittyFontOf, kittyIncludePath, kittyLinesOf,+ kittySchemeOfGnome, kittyValueOf,+ RIO_DEFAULT_BG, RIO_DEFAULT_FONT, rioBackgroundOf, rioConfigDirOf, rioFontOf, rioForcedOf, rioThemeNamesOf, rioThemePath, tomlStringsOf,+} from '../hooks/register'++// ---- kitty ------------------------------------------------------------------++test('kitty config lines: key and value, comments and blank lines skipped, the last value wins', () => {+ const lines = kittyLinesOf('# a comment\n\nfont_family JetBrains Mono\n background #1e1e2e \nbackground #ffffff\n9bad x\nnovalue\n')+ expect(lines).toEqual([['font_family', 'JetBrains Mono'], ['background', '#1e1e2e'], ['background', '#ffffff']])+ expect(kittyValueOf(lines, 'background')).toBe('#ffffff')+ expect(kittyValueOf(lines, 'foreground')).toBe('')+})++test('a kitty include: relative to the file that has it, ~ and ${KITTY_OS} expanded', () => {+ const o = { home: '/h', vars: { KITTY_OS: 'macos' } }+ expect(kittyIncludePath('current-theme.conf', '/h/.config/kitty', o)).toBe('/h/.config/kitty/current-theme.conf')+ expect(kittyIncludePath('themes/x.conf', '/h/.config/kitty/', o)).toBe('/h/.config/kitty/themes/x.conf')+ expect(kittyIncludePath('~/k.conf', '/d', o)).toBe('/h/k.conf')+ expect(kittyIncludePath('/abs/k.conf', '/d', o)).toBe('/abs/k.conf')+ expect(kittyIncludePath('${KITTY_OS}.conf', '/d', o)).toBe('/d/macos.conf')+ expect(kittyIncludePath('$KITTY_OS.conf', '/d', o)).toBe('/d/macos.conf')+ expect(kittyIncludePath('${UNKNOWN}.conf', '/d', o)).toBe('/d/${UNKNOWN}.conf')+})++test('kitty includes are read in place, each file once (no loops); other include kinds are skipped', async () => {+ const files: Record<string, string> = {+ '/k/kitty.conf': 'background #111111\ninclude current-theme.conf\nglobinclude kitty.d/*.conf\nfont_size 12\ninclude sub/a.conf\n',+ '/k/current-theme.conf': 'background #eeeeee\n',+ '/k/sub/a.conf': 'include b.conf\ninclude /k/kitty.conf\n',+ '/k/sub/b.conf': 'foreground #000000\ninclude a.conf\n',+ }+ const read: string[] = []+ const entries = await kittyEntriesOf('/k/kitty.conf', async p => (read.push(p), files[p] ?? null), { home: '/h' })+ expect(entries).toEqual([['background', '#111111'], ['background', '#eeeeee'], ['globinclude', 'kitty.d/*.conf'], ['font_size', '12'], ['foreground', '#000000']])+ expect(read).toEqual(['/k/kitty.conf', '/k/current-theme.conf', '/k/sub/a.conf', '/k/sub/b.conf'])+ expect(kittyValueOf(entries, 'background')).toBe('#eeeeee')+ // A missing file is nothing.+ expect(await kittyEntriesOf('/none', async () => null, { home: '/h' })).toEqual([])+})++test('kitty config folders: KITTY_CONFIG_DIRECTORY alone, else XDG, ~/.config, and on macOS ~/Library/Preferences', () => {+ expect(kittyConfigDirsOf({ kittyDir: '/x', xdgConfig: '/xdg', home: '/h', isMac: true })).toEqual(['/x'])+ expect(kittyConfigDirsOf({ home: '/h', isMac: false })).toEqual(['/h/.config/kitty'])+ expect(kittyConfigDirsOf({ xdgConfig: '/xdg', home: '/h', isMac: true })).toEqual(['/xdg/kitty', '/h/.config/kitty', '/h/Library/Preferences/kitty'])+ expect(kittyConfigDirsOf({ xdgConfig: '/h/.config', home: '/h', isMac: false })).toEqual(['/h/.config/kitty'])+})++test('kitty font_family: a family, family="…" style=…, postscript_name=…, or the system font', () => {+ expect(kittyFontOf('JetBrains Mono')).toEqual({ family: 'JetBrains Mono' })+ expect(kittyFontOf('family="JetBrains Mono" style=Light')).toEqual({ family: 'JetBrains Mono' })+ expect(kittyFontOf("family='Fira Code' features=+zero")).toEqual({ family: 'Fira Code' })+ expect(kittyFontOf('family=Iosevka')).toEqual({ family: 'Iosevka' })+ expect(kittyFontOf('postscript_name=FiraCode-Retina')).toEqual({ postscript: 'FiraCode-Retina' })+ expect(kittyFontOf('monospace')).toBe(null)+ expect(kittyFontOf('auto')).toBe(null)+ expect(kittyFontOf('family=monospace')).toBe(null)+ expect(kittyFontOf('')).toBe(null)+})++test('kitty auto themes: the file for the OS scheme, GNOME default is no preference', () => {+ expect(kittyAutoFileOf('dark')).toBe('dark-theme.auto.conf')+ expect(kittyAutoFileOf('no-preference')).toBe('no-preference-theme.auto.conf')+ expect(kittySchemeOfGnome("'prefer-dark'\n")).toBe('dark')+ expect(kittySchemeOfGnome("'prefer-light'")).toBe('light')+ expect(kittySchemeOfGnome("'default'")).toBe('no-preference')+ expect(kittySchemeOfGnome('')).toBe(null)+})++test("kitty's background: the auto theme's, else kitty.conf's, else #000000", () => {+ const conf: [string, string][] = [['background', '#fafafa']]+ expect(kittyBackgroundOf(conf, null)).toEqual({ bg: '#fafafa', detail: 'config background' })+ expect(kittyBackgroundOf([], null)).toEqual({ bg: KITTY_DEFAULT_BG, detail: 'default background' })+ expect(kittyBackgroundOf(conf, { file: 'dark-theme.auto.conf', entries: [['background', '#1e1e2e']] })).toEqual({ bg: '#1e1e2e', detail: 'dark-theme.auto.conf background' })+ // The auto file resets colours to kitty's defaults first.+ expect(kittyBackgroundOf(conf, { file: 'light-theme.auto.conf', entries: [] }).bg).toBe(KITTY_DEFAULT_BG)+})++// ---- Rio --------------------------------------------------------------------++test('the TOML reader: tables, dotted and quoted keys, strings, inline tables, comments', () => {+ const toml = [+ '# Rio',+ 'theme = "dracula" # a comment',+ "force-theme = 'light'",+ 'line-height = 1.2',+ 'confirm-before-quit = true',+ '[fonts]',+ 'size = 14',+ 'family = "Iosevka Term"',+ '[fonts.regular]',+ 'family = "JetBrains Mono"',+ 'style = "Normal"',+ '[ "adaptive-theme" ]',+ 'light = "belafonte-day"',+ 'dark = "belafonte-night"',+ '[colors]',+ 'background = "#0F0D0E"',+ 'say = "a \\"b\\""',+ '[navigation]',+ 'mode = "Tab"',+ 'bold = { family = "X Bold", style = \'Bold\' }',+ 'renderer.backend = "Metal"',+ ].join('\n')+ const v = tomlStringsOf(toml)+ expect(v.theme).toBe('dracula')+ expect(v['force-theme']).toBe('light')+ expect(v['line-height']).toBe(undefined)+ expect(v['confirm-before-quit']).toBe(undefined)+ expect(v['fonts.family']).toBe('Iosevka Term')+ expect(v['fonts.size']).toBe(undefined)+ expect(v['fonts.regular.family']).toBe('JetBrains Mono')+ expect(v['adaptive-theme.light']).toBe('belafonte-day')+ expect(v['adaptive-theme.dark']).toBe('belafonte-night')+ expect(v['colors.background']).toBe('#0F0D0E')+ expect(v['colors.say']).toBe('a "b"')+ expect(v['navigation.bold.family']).toBe('X Bold')+ expect(v['navigation.bold.style']).toBe('Bold')+ expect(v['navigation.renderer.backend']).toBe('Metal')+})++test('Rio config folder and theme files', () => {+ expect(rioConfigDirOf({ rioHome: '/r', xdgConfig: '/xdg', home: '/h', isMac: false })).toBe('/r')+ expect(rioConfigDirOf({ xdgConfig: '/xdg', home: '/h', isMac: false })).toBe('/xdg/rio')+ // macOS: no XDG.+ expect(rioConfigDirOf({ xdgConfig: '/xdg', home: '/h', isMac: true })).toBe('/h/.config/rio')+ expect(rioConfigDirOf({ home: '/h', isMac: false })).toBe('/h/.config/rio')+ expect(rioThemePath('/c', 'dracula')).toBe('/c/themes/dracula.toml')+ expect(rioThemePath('/c', 'dracula.toml')).toBe('/c/themes/dracula.toml')+ expect(rioThemePath('/c', 'sub/x')).toBe('/c/themes/sub/x.toml')+ expect(rioThemePath('/c', '/abs/t')).toBe('/abs/t.toml')+ expect(rioThemeNamesOf({ theme: 'a', 'adaptive-theme.light': 'l', 'adaptive-theme.dark': 'd' })).toEqual(['a', 'l', 'd'])+ expect(rioThemeNamesOf({ 'adaptive-theme.light': 'l' })).toEqual([])+ expect(rioForcedOf({ 'force-theme': 'dark' })).toBe('dark')+ expect(rioForcedOf({ 'force-theme': 'auto' })).toBe(null)+})++test("Rio's background: adaptive theme (force-theme, else the OS), else theme, else [colors], else the default", () => {+ const themes = { day: '[colors]\nbackground = "#FFFFFF"\n', night: '[colors]\nbackground = "#191724"\n', plain: '[colors]\nforeground = "#000000"\n', gone: null }+ const adaptive = { theme: 'night', 'adaptive-theme.light': 'day', 'adaptive-theme.dark': 'night', 'colors.background': '#ffffff' }+ expect(rioBackgroundOf(adaptive, 'light', themes)).toEqual({ bg: '#FFFFFF', detail: 'theme day background' })+ expect(rioBackgroundOf(adaptive, 'dark', themes)).toEqual({ bg: '#191724', detail: 'theme night background' })+ expect(rioBackgroundOf({ ...adaptive, 'force-theme': 'dark' }, 'light', themes).detail).toBe('theme night background')+ // The OS not known: the plain theme.+ expect(rioBackgroundOf(adaptive, null, themes).detail).toBe('theme night background')+ // One adaptive file missing: adaptive is off.+ expect(rioBackgroundOf({ ...adaptive, 'adaptive-theme.light': 'gone' }, 'light', themes).detail).toBe('theme night background')+ // A theme with no background: Rio's default (the config's colours are replaced).+ expect(rioBackgroundOf({ theme: 'plain', 'colors.background': '#ffffff' }, null, themes)).toEqual({ bg: RIO_DEFAULT_BG, detail: 'theme plain background' })+ // A theme not found: the config's colours.+ expect(rioBackgroundOf({ theme: 'gone', 'colors.background': '#ffffff80' }, null, themes)).toEqual({ bg: '#ffffff', detail: 'config background' })+ expect(rioBackgroundOf({}, 'light', themes)).toEqual({ bg: RIO_DEFAULT_BG, detail: 'default background' })+})++test("Rio's font: [fonts] family, else [fonts.regular] family, else Cascadia Code", () => {+ expect(rioFontOf({ 'fonts.family': 'Iosevka', 'fonts.regular.family': 'JetBrains Mono' })).toBe('Iosevka')+ expect(rioFontOf({ 'fonts.regular.family': 'JetBrains Mono' })).toBe('JetBrains Mono')+ expect(rioFontOf({})).toBe(RIO_DEFAULT_FONT)+ expect(rioFontOf({ 'fonts.family': 'cascadiacode' })).toBe('Cascadia Code')+})++// ---- iTerm2 and cmux ------------------------------------------------------------++test('iTerm2: TERM_PROGRAM, else (no TERM_PROGRAM) ITERM_PROFILE, ITERM_SESSION_ID or LC_TERMINAL', () => {+ expect(isItermIn({ program: 'iTerm.app' })).toBe(true)+ expect(isItermIn({ program: '', profile: 'Default' })).toBe(true)+ expect(isItermIn({ program: '', session: 'w0t0p0:ABC' })).toBe(true)+ expect(isItermIn({ program: '', lcTerminal: 'iTerm2' })).toBe(true)+ expect(isItermIn({ program: '' })).toBe(false)+ expect(isItermIn({ program: '', lcTerminal: 'other' })).toBe(false)+ // Another terminal started from iTerm2 keeps its variables: TERM_PROGRAM wins.+ expect(isItermIn({ program: 'ghostty', profile: 'Default', lcTerminal: 'iTerm2' })).toBe(false)+})++test('JSONC: comments and trailing commas go, strings stay', () => {+ const text = '{\n "$schema": "https://x/y.json", // a comment\n /* block\n */ "app": { "appearance": "light", },\n "s": "a // b /* c */",\n}'+ expect(jsoncOf(text)).toEqual({ $schema: 'https://x/y.json', app: { appearance: 'light' }, s: 'a // b /* c */' })+ expect(jsoncOf('{ bad')).toBe(null)+ expect(jsoncOf('')).toBe(null)+})++test("cmux settings: app.appearance and terminal.adaptiveDefaultTheme, nested or dotted; the file's appearance wins", () => {+ expect(cmuxSettingsOf({ app: { appearance: 'dark' }, terminal: { adaptiveDefaultTheme: false } })).toEqual({ appearance: 'dark', adaptive: false })+ expect(cmuxSettingsOf({ 'app.appearance': 'light' })).toEqual({ appearance: 'light' })+ expect(cmuxSettingsOf({ app: { appearance: 'blue' }, terminal: { adaptiveDefaultTheme: 'yes' } })).toEqual({})+ expect(cmuxSettingsOf(null)).toEqual({})+ expect(cmuxAppearanceOf(undefined, 'dark\n')).toBe('dark')+ expect(cmuxAppearanceOf(undefined, 'system\n')).toBe('system')+ expect(cmuxAppearanceOf(undefined, '')).toBe('system')+ expect(cmuxAppearanceOf('light', 'dark')).toBe('light')+})++test('Ghostty colours of your own: a theme, background, foreground or palette', () => {+ expect(ghosttyHasColors('font-family = Menlo\n')).toBe(false)+ expect(ghosttyHasColors('theme = Night\n')).toBe(true)+ expect(ghosttyHasColors('background = #ffffff\n')).toBe(true)+ expect(ghosttyHasColors('foreground = #000000\n')).toBe(true)+ expect(ghosttyHasColors('palette = 0=#000000\n')).toBe(true)+})