Skip to content

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

TypeScript claude-code-mod

Merge branch 'herdr-support' into release-0.3.3

razorback16849f056644ae
diff --cc CHANGELOG.md
index 540b911,71ad131..0121e1d
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@@ -2,28 -2,28 +2,42 @@@
All releases of Intelligent UI for Claude Code (`cc-intelligent-ui`). Claude Code finds a new version by the `version` in `.claude-plugin/plugin.json`. To get it, refer to [Update](docs/install.md#update).
-## Unreleased
+## 0.3.3 (2026-10-22)
+ ### New
+
+ - **herdr support** (the terminal multiplexer). In a herdr pane, Claude Code needs `CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1` to show pictures. The mod asks one time to add the shell line, as in iTerm2. `/iui setup` also adds it. Then close the pane and open a new herdr pane. herdr must run in a terminal that shows kitty pictures (kitty, Ghostty or iTerm2). Refer to [Terminals](docs/install.md#terminals).
+ - **herdr in iTerm2.** iTerm2 shows each row of a herdr picture from the bottom of the image, so the rows of a page showed in the wrong order. When the herdr client in use is iTerm2, the mod stores the bands of rows of each page and picture in reverse order. Then iTerm2 shows them in the correct order. `/iui details` shows `pages and pictures stored upside down by rows` when this is on. It does not work with `herdr --remote` in iTerm2.
+ - `/iui setup` works in herdr on Linux too.
+ - `/iui details` names herdr, its version, the terminal that it runs in and how the mod found that terminal, for example `herdr 0.9.5 (in kitty, the terminal in front)`. If the mod uses the variables of the herdr server, it shows `(in Ghostty, from the server's start)`.
+
-### Changed
-
-- The shell line of `/iui setup` sets the variable in iTerm2 and in herdr. `/iui setup` replaces the line of an older version. In herdr, the mod asks to update an older line. In iTerm2, the older line still works, and the mod does not ask.
-- In herdr, pages are shorter, so that each page is at most 16 MiB as pixels.
-
### Fixed
+- **The newest copy wins.** A click, a picture selection's up, `/iui grab` and the `ui.copy` change of picture cells each read their text first. An older one that was still reading wrote the clipboard over a newer copy. Now it writes nothing when a newer copy came: a newer click or up, a `$.ui.copy` (another plugin's, or the command button of a link row), Claude Code's own copy of a selection, or a copy in another app. A `ui.copy` change that lost its turn is refused. `/iui grab`, a click on no target and an up with no text copy nothing and cancel no other copy. An older copy (a click, an up, `/iui grab` or a `ui.copy` change) waits for a newer click or up that still reads its text, so it never writes first and is then overwritten. A copy in another app counts from the time the clipboard changed, not from the time the mod read it.
+- **A password manager's copy is never read.** On macOS the mod reads the clipboard with a short `perl` script (PerlObjCBridge) in place of `pbpaste`, and stops at a copy with a concealed or transient type. On Linux, `xclip`, `wl-paste` and GTK look for the `x-kde-passwordManagerHint` target before and after the read. On Wayland, a copy marked sensitive was skipped already.
+- **The code in an answer can read no other file.** Each compile of an answer or a plan had `/` as its Typst root, so a Typst block could read any file (`read`, `include`, `image`, `json`, `csv`), and `read("/dev/zero")` used all the memory. Now each compile runs in a root of its own, with only the template, the theme and the answer's images. The skill's `check.sh` does the same, and it stops with an error when its cache folder is a link or not yours. Pictures are the same as before.
+- `/iui setup`, `/iui setup remove` and the setup question never write a shell start file that they cannot read (no permission, or too large). Before, such a file was replaced with only the Intelligent UI block. Now the mod changes no file and shows the line to add.
+- **Plan mode:** when Claude Code runs two `ExitPlanMode` calls at once, the mod does not ask its question, so the answer for one plan can not go to the other (a rejected plan was allowed). Claude Code's own dialog asks.
+- `/iui theme` runs one at a time: an older `/iui theme` that was still loading no longer sets its theme over a newer one. A setting that you change with `/iui` while the mod starts is kept (before, the start set it back to the stored value).
+- A long session no longer keeps the last text of each answer in memory: the mod keeps the newest 1,024, as it does for the compile results.
+- The picture select highlight could stop on a page whose frames went out of the page cache while its build waited. That page is now built again.
+- The watcher no longer sends `kill` to the PID of a child that ended (the PID can be another process's).
+- On Linux, the GTK clipboard read, watch and check run Python isolated (`-I`): a `gi.py` in the session's project folder no longer runs.
+- When `$.ui.selection()` fails, a `ui.copy` of picture cells and `/iui grab` copy again (before, they said that a newer copy came first).
+- A clipboard read that fails (an error or the 2 s timeout), or a late read of one of the mod's last 4 copies, no longer cancels a newer copy.
+ - In herdr, the mod now uses the font and the background of the terminal that herdr runs in (Ghostty, kitty, iTerm2, cmux or Rio). Before, it used Menlo and the OS appearance, so the text could be dark on a dark background.
+ - With the `auto` theme, the background comes from herdr: herdr gives the background of the terminal in front (OSC 11). This also works with `herdr --remote`. If an answer does not come, the mod keeps the last background for up to 2 more checks.
+ - The font comes from the herdr client that you use. You can attach to one herdr server from more than one terminal, for example from Ghostty and from kitty. On macOS, the mod uses the client in the terminal app in front. When the app in front is not a terminal (for example a browser), it keeps the last client. On Linux, and between two clients in the same app, it uses the client where you typed last. When you change to a different terminal, the mod finds it at the next check (every 1 s), reads its font and draws the pictures again. If the mod cannot find the client, it uses the variables of the terminal that started the herdr server.
+ - In herdr, a tall page of a long answer did not show (herdr does not send an image that is too large to the terminal). Refer to [Limitations](docs/limitations.md).
+ - At a page break between two blocks (for example a paragraph and a list, or a table and a heading), the next page starts with the same gap as in one page. Before, the gap was lost. With the row grid off, the gap can be up to 1 row larger.
+### Changed
+
+- On Linux, `xsel` no longer reads the clipboard: it cannot show the targets of a copy, so it cannot skip a password manager's copy. Install `xclip` (or GTK 3 for Python); `/iui details` tells you.
+- The README has a **Privacy and access** section: the network request, the clipboard reads and writes, the files, the processes and the Typst root.
++- The shell line of `/iui setup` sets the variable in iTerm2 and in herdr. `/iui setup` replaces the line of an older version. In herdr, the mod asks to update an older line. In iTerm2, the older line still works, and the mod does not ask.
++- In herdr, pages are shorter, so that each page is at most 16 MiB as pixels.
+
## 0.3.2 (2026-10-21)
### New
diff --cc docs/development.md
index 904444d,c7102e7..e195710
--- a/docs/development.md
+++ b/docs/development.md
@@@ -14,9 -14,8 +14,11 @@@ sh tests/cache-sh-test.sh # the ca
sh tests/fonts-sh-test.sh # the copy of a font out of a terminal's program (PROGRAM_FONTS_SH and _PL) with perl
sh tests/bold-sh-test.sh # the fake bold of md.typ (term-bold=0) with the real Typst and Monaco (skips with no Monaco)
sh tests/code-sh-test.sh # code blocks of md.typ (width, header, copy button mark, row grid) with the real Typst (skips with no typst)
+sh tests/root-sh-test.sh # the Typst root of a compile (STAGE_SH): answer code reads no other file, with the real Typst (its compiles skip with no typst)
+sh tests/check-sh-test.sh # the skill's check.sh: a private cache folder, and a block reads no other file (skips with no Typst 0.15)
+sh tests/footprint-sh-test.sh # release gate: the validator's footprint is whole (no [+N chars] mark, calls line of 850 characters at most)
+ sh tests/gap-sh-test.sh # the gap at a page break of md.typ (seams), on and off the row grid, with the real Typst (skips with no typst)
+ sh tests/herdr-sh-test.sh # the herdr client finder (HERDR_CLIENT_SH) with fake ps, stat, lsof and lsappinfo, in sh, dash and bash
claude plugin validate .
```
@@@ -39,7 -38,7 +41,7 @@@ Picture select writes trace lines that
## Module layout
- 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), `fonts.ts` (the lean font set: the fonts that a compile of plain text loads), `draw.tsx` (the pages of an answer and the link rows under them), `links.ts` (the links, file paths and commands of a text), `answer.ts` (one text through the compile and cache steps), `plan.tsx` (the plan approval question and the plan rows), `frame.ts` (the terminal size and the watcher process, which also reports the clipboard changes), `clipboard.ts` (how the clipboard is read and watched for the `/iui grab` toast: macOS, or the Linux tools), `copy.ts` (the text under a mouse selection of pictures), `select.ts` and `blit.ts` (picture select and its highlight), `frames.ts` (the frames of a page: the cell edges, the bands, the row pieces and the frame PNG), `pagecache.ts` (the background page cache: the build queue in slices, and the words probe), `png.ts` (PNG decode, also in steps, and the deflate pieces, in plain JavaScript), `probe.ts` (the drawn pages, and the words of a page that a copy reads, kept in memory) and `updates.ts` (the daily check for a new version). The values that change are in one object, `S`, in `state.ts`. The hook bodies in `register.tsx` call `$` themselves; every other `$` call is a wrapper with a short name in `api.ts` (for example `cat` for `$.fs.read`, `exec` for `$.process.run`). The `calls:` note of `claude plugin validate` names each method with the wrappers that call it (`via cat`), and a method that a hook body calls with none. The validator cuts a note at about 1,000 characters and marks the cut `[+N chars]`; the catalogue scan then cannot read the footprint. `tests/footprint-sh-test.sh` is the release gate for this: it fails on a `[+N chars]` mark in the text or the `--json` report, on a calls line (the text after `calls: `) of more than 850 characters, and on a `$` call in `hooks/` outside `api.ts` and `register.tsx`. The tests import from `hooks/register.tsx`, which exports the names that they use.
-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), `fonts.ts` (the lean font set: the fonts that a compile of plain text loads), `draw.tsx` (the pages of an answer and the link rows under them), `links.ts` (the links, file paths and commands of a text), `answer.ts` (one text through the compile and cache steps), `plan.tsx` (the plan approval question and the plan rows), `frame.ts` (the terminal size and the watcher process, which also reports the clipboard changes), `clipboard.ts` (how the clipboard is read and watched for the `/iui grab` toast: macOS, or the Linux tools), `copy.ts` (the text under a mouse selection of pictures), `select.ts` and `blit.ts` (picture select and its highlight), `frames.ts` (the frames of a page: the cell edges, the bands, the row pieces and the frame PNG), `pagecache.ts` (the background page cache: the build queue in slices, and the words probe), `png.ts` (PNG decode, also in steps, and the deflate pieces, in plain JavaScript), `flip.ts` (herdr in iTerm2: the pages and pictures stored with the bands of their rows moved), `probe.ts` (the drawn pages, and the words of a page that a copy reads, kept in memory) and `updates.ts` (the daily check for a new version). The values that change are in one object, `S`, in `state.ts`. Each `$` method has one call site, a wrapper in `api.ts`; the other modules call the wrappers. This keeps the `calls:` note of `claude plugin validate` short (the validator cuts a note at about 1,000 characters, and the catalogue scan then cannot read the footprint). The tests import from `hooks/register.tsx`, which exports the names that they use.
++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), `fonts.ts` (the lean font set: the fonts that a compile of plain text loads), `draw.tsx` (the pages of an answer and the link rows under them), `links.ts` (the links, file paths and commands of a text), `answer.ts` (one text through the compile and cache steps), `plan.tsx` (the plan approval question and the plan rows), `frame.ts` (the terminal size and the watcher process, which also reports the clipboard changes), `clipboard.ts` (how the clipboard is read and watched for the `/iui grab` toast: macOS, or the Linux tools), `copy.ts` (the text under a mouse selection of pictures), `select.ts` and `blit.ts` (picture select and its highlight), `frames.ts` (the frames of a page: the cell edges, the bands, the row pieces and the frame PNG), `pagecache.ts` (the background page cache: the build queue in slices, and the words probe), `png.ts` (PNG decode, also in steps, and the deflate pieces, in plain JavaScript), `flip.ts` (herdr in iTerm2: the pages and pictures stored with the bands of their rows moved), `probe.ts` (the drawn pages, and the words of a page that a copy reads, kept in memory) and `updates.ts` (the daily check for a new version). The values that change are in one object, `S`, in `state.ts`. The hook bodies in `register.tsx` call `$` themselves; every other `$` call is a wrapper with a short name in `api.ts` (for example `cat` for `$.fs.read`, `exec` for `$.process.run`). The `calls:` note of `claude plugin validate` names each method with the wrappers that call it (`via cat`), and a method that a hook body calls with none. The validator cuts a note at about 1,000 characters and marks the cut `[+N chars]`; the catalogue scan then cannot read the footprint. `tests/footprint-sh-test.sh` is the release gate for this: it fails on a `[+N chars]` mark in the text or the `--json` report, on a calls line (the text after `calls: `) of more than 850 characters, and on a `$` call in `hooks/` outside `api.ts` and `register.tsx`. The tests import from `hooks/register.tsx`, which exports the names that they use.
The skill for Claude is in `skills/intelligent-ui/`: `SKILL.md` (the contract, the workflow and an index), `references/` (one file for each topic: Typst, fletcher, CeTZ, plots and charts) and `scripts/check.sh` (the compile check, with the real template). `TYPST_PROMPT` in `hooks/lib/settings.ts` tells Claude when to load it.
diff --cc hooks/lib/answer.ts
index 0e9c4a6,7db24f9..972d017
--- a/hooks/lib/answer.ts
+++ b/hooks/lib/answer.ts
@@@ -111,10 -113,10 +113,10 @@@ export async function pagesOf($: Engine
})
const seen = lastText.get(id)
const changed = seen !== text
- lastText.set(id, text)
+ keep(lastText, id, text, RESULTS_KEPT)
const job: Job = {
key, requestId: id, text, columns, cell, theme: S.theme, size: S.size, grid: S.grid, themeDir: active.dir, env, epoch: S.epoch,
- ...(base ? { base } : {}), ...(room ? { room } : {}), ...(o.onScreen !== undefined ? { onScreen: o.onScreen } : {}),
+ ...(base ? { base } : {}), ...(room ? { room } : {}), ...(flip ? { flip } : {}), ...(o.onScreen !== undefined ? { onScreen: o.onScreen } : {}),
}
// The picture drawn last for the same text, at another key.
const was = lastKey.get(id)
diff --cc hooks/lib/api.ts
index 4c74679,e3b20db..9b81cc1
--- a/hooks/lib/api.ts
+++ b/hooks/lib/api.ts
@@@ -18,12 -13,12 +18,12 @@@ import type
export type EnvName =
| 'CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC' | 'CLAUDE_CODE_FORCE_TERMINAL_IMAGES' | 'CLAUDE_CODE_SESSION_KIND' | 'CLAUDE_CODE_TMPDIR'
| 'CMUX_SOCKET_PATH' | 'CMUX_SURFACE_ID' | 'CMUX_WORKSPACE_ID' | 'COLORFGBG' | 'DISABLE_AUTOUPDATER' | 'DISABLE_UPDATES' | 'DISPLAY'
- | 'GHOSTTY_RESOURCES_DIR' | 'HOME'
- | 'ITERM_PROFILE' | 'ITERM_SESSION_ID' | 'IUI_DEBUG' | 'IUI_FORCE' | 'KITTY_CONFIG_DIRECTORY' | 'KITTY_PID'
+ | 'GHOSTTY_BIN_DIR' | 'GHOSTTY_RESOURCES_DIR' | 'HERDR_ENV' | 'HOME'
+ | 'ITERM_PROFILE' | 'ITERM_SESSION_ID' | 'IUI_DEBUG' | 'IUI_FORCE' | 'KITTY_CONFIG_DIRECTORY' | 'KITTY_INSTALLATION_DIR' | 'KITTY_PID'
| 'KITTY_WINDOW_ID' | 'LC_TERMINAL' | 'RIO_CONFIG_HOME' | 'SHELL' | 'SSH_CONNECTION' | 'SSH_TTY' | 'STY'
- | 'TERM' | 'TERM_PROGRAM' | 'TMUX' | 'TYPST_FONT_PATHS' | 'WAYLAND_DISPLAY' | 'XDG_CONFIG_HOME' | 'XDG_CURRENT_DESKTOP' | 'ZDOTDIR'
+ | 'TERM' | 'TERM_PROGRAM' | 'TERM_PROGRAM_VERSION' | 'TMUX' | 'TYPST_FONT_PATHS' | 'WAYLAND_DISPLAY' | 'XDG_CONFIG_HOME' | 'XDG_CURRENT_DESKTOP' | 'ZDOTDIR'
-export function clockAfter($: EngineInterface, ms: number, fn: () => void) {
+export function delay($: EngineInterface, ms: number, fn: () => void) {
return $.clock.after(ms, fn)
}
diff --cc hooks/lib/blit.ts
index 6938476,5d61e79..edcbdc7
--- a/hooks/lib/blit.ts
+++ b/hooks/lib/blit.ts
@@@ -22,8 -22,9 +22,9 @@@ import { forgetPages, holdPages, keyOf
import type { DrawnPage } from './copy'
import type { SelRow } from './select'
import { perlFor } from './host'
+ import { WRITE_PL } from './flip'
import { traceDebug } from './log'
-import { clockNow, processRun, uiBlit, uiLog } from './api'
+import { nowMs, exec, paint, log } from './api'
export { bandOf, edgesOf, frameOf, framesOf, over, rgbOf, selectColor, type Frames, type Rgb } from './frames'
diff --cc hooks/lib/env.ts
index 96d77f5,1199115..ca69c04
--- a/hooks/lib/env.ts
+++ b/hooks/lib/env.ts
@@@ -6,10 -6,10 +6,10 @@@ import type { EngineInterface } from 'c
import {
BASE_THEME, DEFAULT_HEIGHT, DEFAULT_SIZE, DESIGNS_KEPT_DAYS, DEFAULT_THEME, DEFAULT_WIDTH, MAX_HEIGHT, MAX_SIZE, MAX_WIDTH, MIN_HEIGHT, MIN_SIZE, MIN_WIDTH, noTypstOf,
} from './settings'
-import { DEFAULT_METRICS, refresh, S, type Env } from './state'
+import { DEFAULT_METRICS, refresh, S, settingsSet, type Env } from './state'
import { resolveMode, settingOf } from './mode'
import { isItermIn } from './terminals'
- import { canDrawIn, isSet } from './terminal'
+ import { canDrawIn, isHerdrIn, isSet, needsSetup } from './terminal'
import { claudeTmpOf } from './images'
import { applyTheme } from './themes'
import { registerCommand } from './command'
@@@ -69,22 -69,33 +69,33 @@@ export function setUp($: EngineInterfac
S.hostOs = os.trim()
S.termProgram = program
S.termName = term
- S.itermProfile = (await getenv($, 'ITERM_PROFILE')) || undefined
- S.isKitty = /kitty/i.test(term) || !!(await getenv($, 'KITTY_WINDOW_ID')) || !!(await getenv($, 'KITTY_PID'))
- S.isHerdr = isHerdrIn({ program, herdrEnv: await envGet($, 'HERDR_ENV') })
- S.herdrVersion = S.isHerdr ? ((await envGet($, 'TERM_PROGRAM_VERSION')) ?? '').trim() : ''
++ S.isHerdr = isHerdrIn({ program, herdrEnv: await getenv($, 'HERDR_ENV') })
++ S.herdrVersion = S.isHerdr ? ((await getenv($, 'TERM_PROGRAM_VERSION')) ?? '').trim() : ''
+ // Under herdr the client in use gives the terminal (the one of before stays while the app in front has none); else (none found) the server's variables.
+ const was = S.herdrClient
+ S.herdrClient = null
+ S.osc11Kept = null
+ if (S.isHerdr) await readHerdrClient($, was).catch(() => false)
+ await setOuter($)
S.isRemote = ssh
- S.debug = isSet(await envGet($, 'IUI_DEBUG'))
+ S.debug = isSet(await getenv($, 'IUI_DEBUG'))
S.isIterm = isItermIn({
program,
- profile: S.itermProfile,
- profile: (await envGet($, 'ITERM_PROFILE')) || undefined,
- session: (await envGet($, 'ITERM_SESSION_ID')) || undefined,
- lcTerminal: (await envGet($, 'LC_TERMINAL')) || undefined,
++ profile: (await getenv($, 'ITERM_PROFILE')) || undefined,
+ session: (await getenv($, 'ITERM_SESSION_ID')) || undefined,
+ lcTerminal: (await getenv($, 'LC_TERMINAL')) || undefined,
})
- S.setupNeeded = S.isIterm && !terminalDraws && !ssh && S.hostOs === 'Darwin' &&
- !(await getenv($, 'TMUX')) && !(await getenv($, 'STY')) && (await getenv($, 'CLAUDE_CODE_SESSION_KIND')) !== 'bg'
+ S.setupNeeded = needsSetup({
+ iterm: S.isIterm,
+ herdr: S.isHerdr,
+ draws: terminalDraws,
+ ssh,
+ os: S.hostOs,
- tmux: !!(await envGet($, 'TMUX')) || !!(await envGet($, 'STY')),
- background: (await envGet($, 'CLAUDE_CODE_SESSION_KIND')) === 'bg',
++ tmux: !!(await getenv($, 'TMUX')) || !!(await getenv($, 'STY')),
++ background: (await getenv($, 'CLAUDE_CODE_SESSION_KIND')) === 'bg',
+ })
if (S.setupNeeded) void offerSetup($).catch(() => undefined)
- S.isCmux = !!(await getenv($, 'CMUX_SURFACE_ID')) || !!(await getenv($, 'CMUX_WORKSPACE_ID')) || !!(await getenv($, 'CMUX_SOCKET_PATH'))
- S.colorFgBg = (await getenv($, 'COLORFGBG')) ?? ''
- S.userFontPaths = (await envGet($, 'TYPST_FONT_PATHS')) ?? ''
+ S.userFontPaths = (await getenv($, 'TYPST_FONT_PATHS')) ?? ''
if (S.setting === 'auto') S.host = (await readHostMode($).catch(() => null)) ?? S.host
S.theme = resolveMode(S.setting, S.host)
watchHost($)
@@@ -139,8 -142,9 +150,9 @@@
typst,
canDraw,
inline: ssh && canDraw,
+ herdr: S.isHerdr,
cache,
- cwd: await sessionCwd($).catch(() => '/'),
+ cwd: await cwd($).catch(() => '/'),
root,
isMac,
stamp: String(template?.mtimeMs ?? 0),
diff --cc hooks/lib/flip.ts
index 0000000,b3d2606..04980df
mode 000000,100644..100644
--- a/hooks/lib/flip.ts
+++ b/hooks/lib/flip.ts
@@@ -1,0 -1,147 +1,147 @@@
+ // herdr in iTerm2 (flip mode): herdr draws each row of a picture (Claude
+ // Code's kitty placeholders, one virtual placement of R rows) as a kitty
+ // placement of its own with a source rectangle: row k shows source rows y =
+ // floor(k·H/R), h = floor(H/R) (herdr's ghostty-vt,
+ // kitty_virtual_placement_geometry). iTerm2 measures that rectangle's y from
+ // the image's bottom: rows [y, y + h) show rows [H − y − h, H − y). So in
+ // flip mode each PNG is stored with every row's band moved to the rows
+ // iTerm2 reads for it (flipRows). A page is first made R × B pixels tall (B
+ // whole: padRows), so the move is a reversal of its bands, its own inverse
+ // (reverseBands), and picture select's frames are their row pieces in
+ // reverse order (frames.ts).
+ import type { EngineInterface } from 'claude-code'
+
+ import { chunk, concat, decodeSteps, deflatePiece, fromBase64, headOf, tailOf, toBase64, type Piece, type Rgba } from './png'
-import { clockAfter, fsRead, processRun } from './api'
++import { delay, cat, exec } from './api'
+
+ // The source rows herdr places for row k of a picture `height` pixels tall drawn `rows` rows tall.
+ export function herdrBand(k: number, height: number, rows: number): { y: number; h: number } {
+ const y = Math.floor((k * height) / rows)
+ return { y, h: Math.max(1, Math.min(Math.floor(height / rows), height - y)) }
+ }
+
+ // The first row iTerm2 shows for a source rectangle of rows [y, y + h).
+ export const itermRowOf = (y: number, h: number, height: number) => height - y - h
+
+ // The picture stored so that herdr in iTerm2 shows it right when drawn
+ // `rows` rows tall: each row's band (herdrBand) at the rows iTerm2 reads for
+ // it. The bands never overlap; rows that no band covers stay as they are.
+ export function flipRows(img: Rgba, rows: number): Rgba {
+ const stride = img.width * 4
+ const data = img.data.slice()
+ for (let k = 0; k < rows; k++) {
+ const { y, h } = herdrBand(k, img.height, rows)
+ data.set(img.data.subarray(y * stride, (y + h) * stride), itermRowOf(y, h, img.height) * stride)
+ }
+ return { width: img.width, height: img.height, data }
+ }
+
+ // The picture `rows` × B pixels tall, B = round(height / rows) (1 at least):
+ // rows past it cut, or the last row repeated.
+ export function padRows(img: Rgba, rows: number): Rgba {
+ const height = rows * Math.max(1, Math.round(img.height / rows))
+ if (height === img.height) return img
+ const stride = img.width * 4
+ const data = new Uint8Array(height * stride)
+ const kept = Math.min(height, img.height)
+ data.set(img.data.subarray(0, kept * stride))
+ for (let y = kept; y < height; y++) data.copyWithin(y * stride, (kept - 1) * stride, kept * stride)
+ return { width: img.width, height, data }
+ }
+
+ // The bands of a picture R × B pixels tall in reverse order, in place:
+ // flipRows of it, and its inverse. False (nothing done) when the height is
+ // not a whole number of bands.
+ export function reverseBands(img: Rgba, rows: number): boolean {
+ if (rows < 1 || img.height % rows) return false
+ const band = (img.height / rows) * img.width * 4
+ const tmp = new Uint8Array(band)
+ for (let a = 0, b = rows - 1; a < b; a++, b--) {
+ tmp.set(img.data.subarray(a * band, (a + 1) * band))
+ img.data.copyWithin(a * band, b * band, (b + 1) * band)
+ img.data.set(tmp, b * band)
+ }
+ return true
+ }
+
+ // The rows of one deflate piece: few, so a step stays short.
+ const PIECE_ROWS = 16
+
+ // A picture as an RGBA PNG (filter 0, png.ts's deflate pieces), a yield after each piece.
+ export function* encodeSteps(img: Rgba): Generator<undefined, Uint8Array, void> {
+ const stride = img.width * 4
+ const line = stride + 1
+ const pieces: Piece[] = []
+ const chunks: Uint8Array[] = []
+ for (let y0 = 0; y0 < img.height; y0 += PIECE_ROWS) {
+ const y1 = Math.min(img.height, y0 + PIECE_ROWS)
+ const raw = new Uint8Array((y1 - y0) * line)
+ for (let y = y0; y < y1; y++) raw.set(img.data.subarray(y * stride, (y + 1) * stride), (y - y0) * line + 1)
+ const piece = deflatePiece(raw, 4, line)
+ pieces.push(piece)
+ chunks.push(chunk('IDAT', piece.bytes))
+ yield
+ }
+ return concat([headOf(img.width, img.height), ...chunks, tailOf(pieces)])
+ }
+
+ // A PNG stored for flip mode, in steps: decoded, made `rows` × B tall when
+ // `isPage` (padRows), its bands moved (flipRows), encoded; with its size.
+ export function* flipSteps(png: Uint8Array, rows: number, isPage: boolean): Generator<undefined, Rgba & { png: Uint8Array }, void> {
+ let img = yield* decodeSteps(png)
+ if (isPage) img = padRows(img, rows)
+ yield
+ img = flipRows(img, rows)
+ yield
+ return { ...img, png: yield* encodeSteps(img) }
+ }
+
+ // The same at once (tests).
+ export function flipPng(png: Uint8Array, rows: number, isPage: boolean): Rgba & { png: Uint8Array } {
+ const steps = flipSteps(png, rows, isPage)
+ for (;;) {
+ const got = steps.next()
+ if (got.done) return got.value
+ }
+ }
+
+ // ---- Files -------------------------------------------------------------------------
+
+ // Writes stdin's base64 to the file (its folder made, a temporary name,
+ // then renamed), and deletes the older frames named after it (blit.ts).
+ export const WRITE_PL = 'use MIME::Base64; local $/; my $b = <STDIN>; my ($f, @old) = @ARGV; my ($d) = $f =~ m{^(.*)/}; mkdir($d, 0700) unless -d $d; open(my $o, ">:raw", "$f.tmp") or die "$!\\n"; print $o decode_base64($b); close($o) or die "$!\\n"; rename("$f.tmp", $f) or die "$!\\n"; unlink(@old)'
+
+ // A slice of the steps: the hooks run between slices (clock.after(0)).
+ const SLICE_MS = 8
+
+ // Runs `steps` in slices; null when `signal` stopped them.
+ async function runSliced<T>($: EngineInterface, steps: Generator<undefined, T, void>, signal?: AbortSignal): Promise<T | null> {
+ for (;;) {
+ const t0 = performance.now()
+ for (;;) {
+ const got = steps.next()
+ if (got.done) return got.value
+ if (performance.now() - t0 >= SLICE_MS) break
+ }
+ if (signal?.aborted) return null
- await new Promise<void>(done => clockAfter($, 0, done))
++ await new Promise<void>(done => delay($, 0, done))
+ if (signal?.aborted) return null
+ }
+ }
+
+ // Stores the PNG `src` for flip mode (flipSteps) in `out` (`perl` writes
+ // it, as blit.ts's frames; `out` may be `src`): its size, or null when it
+ // fails or `signal` stopped it.
+ export async function flipFile(
+ $: EngineInterface, o: { src: string; out: string; rows: number; isPage: boolean; perl: string; signal?: AbortSignal },
+ ): Promise<{ width: number; height: number } | null> {
+ try {
- const { base64 } = await fsRead($, o.src, { as: 'bytes' })
++ const { base64 } = await cat($, o.src, { as: 'bytes' })
+ const made = await runSliced($, flipSteps(fromBase64(base64), o.rows, o.isPage), o.signal)
+ if (!made) return null
- const ran = await processRun($, [o.perl, '-e', WRITE_PL, o.out], { stdin: toBase64(made.png) })
++ const ran = await exec($, [o.perl, '-e', WRITE_PL, o.out], { stdin: toBase64(made.png) })
+ return ran.exitCode === 0 ? { width: made.width, height: made.height } : null
+ } catch {
+ return null
+ }
+ }
diff --cc hooks/lib/host.ts
index 2ed05f7,a399132..5ab346b
--- a/hooks/lib/host.ts
+++ b/hooks/lib/host.ts
@@@ -16,8 -16,12 +16,12 @@@ import
rioConfigDirOf, RIO_DEFAULT_FONT, RIO_OLD_FONT, rioFontOf, rioForcedOf, rioThemeNamesOf, rioThemePath, tomlStringsOf, type CmuxAppearance, type KittyEntries,
} from './terminals'
import { firstLine } from './markdown'
- import { isGhosttyHere } from './terminal'
- import { every, getenv, exists, cat, exec } from './api'
+ import {
+ frontKindOf, herdrClientChanged, herdrClientsOf, herdrHostOf, herdrTickOf, herdrTickPick, isCmuxIn, isFlipHere, isGhosttyHere, isGhosttyIn, isKittyIn, isRioIn, pickHerdrClient,
+ ttyNameOf, type HerdrClient, type HerdrTick, type OuterName,
+ } from './terminal'
+ import { refont } from './frame'
-import { clockEvery, clockNow, envGet, fsExists, fsRead, processRun } from './api'
++import { every, nowMs, getenv, exists, cat, exec } from './api'
// One tty size read: `rows cols xpixel ypixel` (TIOCGWINSZ); exit 1 with no tty.
export const CELL_SH = `perl -e 'open(T, "</dev/tty") or exit 1; my $w = " " x 8; ioctl(T, ($^O eq "darwin" ? 0x40087468 : 0x5413), $w) or exit 1; print join(" ", unpack("S4", $w))'`
@@@ -258,7 -333,7 +333,7 @@@ async function installedFamily($: Engin
// such font) or 'failed' (no program, or the copy failed).
async function programFont($: EngineInterface, isMac: boolean, o: { tag: string; family: string; name: string; paths: readonly string[] }): Promise<'copied' | 'none' | 'failed'> {
const argv = ['sh', '-c', PROGRAM_FONTS_SH, 'sh', perlFor(isMac), PROGRAM_FONTS_PL, o.tag, o.family, o.name, ...o.paths]
- const made = await exec($, argv, { timeoutMs: 10000 }).catch(() => null)
- const made = await processRun($, argv, { timeoutMs: 10000, ...ghosttyInit() }).catch(() => null)
++ const made = await exec($, argv, { timeoutMs: 10000, ...ghosttyInit() }).catch(() => null)
const dir = made?.exitCode === 0 ? firstLine(made.stdout) : ''
// No copy now: an older folder (maybe gone) is not given to Typst.
if (!dir) S.fontPaths = ''
@@@ -309,13 -384,99 +384,99 @@@ async function rioFont($: EngineInterfa
return (await installedFamily($, isMac, RIO_OLD_FONT)) ? RIO_OLD_FONT : RIO_DEFAULT_FONT
}
+ // iTerm2, or herdr in iTerm2 (its profile and font; S.isIterm stays false
+ // there, so the setup question for iTerm2 is not asked).
+ const isItermHere = () => S.isIterm || S.herdrHost === 'iterm'
+
+ // A variable of the terminal the user sees: under herdr the client's
+ // (S.herdrClient; not set there is not set), else this process's.
+ export function outerEnv($: EngineInterface, name: OuterName): Promise<string | undefined> {
+ const client = S.herdrClient
- return client ? Promise.resolve(client.env[name] || undefined) : envGet($, name)
++ return client ? Promise.resolve(client.env[name] || undefined) : getenv($, name)
+ }
+ // GHOSTTY_SH and PROGRAM_FONTS_SH run the client's Ghostty under herdr ('': the PATH's).
+ const ghosttyInit = () => (S.herdrClient ? { env: { GHOSTTY_BIN_DIR: S.herdrClient.env.GHOSTTY_BIN_DIR ?? '' } } : {})
+
+ // The terminal values the font and mode readers use (S.itermProfile,
+ // S.colorFgBg, S.herdrHost, S.isKitty, S.isCmux): under herdr the client's
+ // when one is found, else this process's variables (under herdr: those of
+ // the terminal that started its server, the fallback).
+ export async function setOuter($: EngineInterface) {
+ S.itermProfile = (await outerEnv($, 'ITERM_PROFILE')) || undefined
+ S.colorFgBg = (await outerEnv($, 'COLORFGBG')) ?? ''
+ const client = S.herdrClient
+ if (client) {
+ S.herdrHost = client.kind
+ S.isKitty = client.kind === 'kitty'
+ S.isCmux = client.kind === 'cmux'
+ return
+ }
- S.isCmux = isCmuxIn({ surface: await envGet($, 'CMUX_SURFACE_ID'), workspace: await envGet($, 'CMUX_WORKSPACE_ID'), socket: await envGet($, 'CMUX_SOCKET_PATH') })
++ S.isCmux = isCmuxIn({ surface: await getenv($, 'CMUX_SURFACE_ID'), workspace: await getenv($, 'CMUX_WORKSPACE_ID'), socket: await getenv($, 'CMUX_SOCKET_PATH') })
+ S.herdrHost = S.isHerdr
+ ? herdrHostOf({
+ cmux: S.isCmux,
- ghosttyResources: await envGet($, 'GHOSTTY_RESOURCES_DIR'),
- ghosttyBin: await envGet($, 'GHOSTTY_BIN_DIR'),
- kittyPid: await envGet($, 'KITTY_PID'),
- kittyDir: await envGet($, 'KITTY_INSTALLATION_DIR'),
++ ghosttyResources: await getenv($, 'GHOSTTY_RESOURCES_DIR'),
++ ghosttyBin: await getenv($, 'GHOSTTY_BIN_DIR'),
++ kittyPid: await getenv($, 'KITTY_PID'),
++ kittyDir: await getenv($, 'KITTY_INSTALLATION_DIR'),
+ itermProfile: S.itermProfile,
+ })
+ : ''
- S.isKitty = isKittyIn({ term: S.termName, windowId: await envGet($, 'KITTY_WINDOW_ID'), pid: await envGet($, 'KITTY_PID') }) || S.herdrHost === 'kitty'
++ S.isKitty = isKittyIn({ term: S.termName, windowId: await getenv($, 'KITTY_WINDOW_ID'), pid: await getenv($, 'KITTY_PID') }) || S.herdrHost === 'kitty'
+ }
+
+ // herdr: reads the clients (HERDR_CLIENT_SH; the full scan) and follows the
+ // one that pickHerdrClient chooses (`was`: the client of before, kept while
+ // the app in front has none). True when its terminal changed
+ // (herdrClientChanged); a read that finds none keeps the last one. The
+ // clients and the app in front are kept for the light check.
+ export async function readHerdrClient($: EngineInterface, was: HerdrClient | null = S.herdrClient): Promise<boolean> {
- const got = await processRun($, ['sh', '-c', HERDR_CLIENT_SH], { timeoutMs: HOST_CHECK_MS }).catch(() => null)
++ const got = await exec($, ['sh', '-c', HERDR_CLIENT_SH], { timeoutMs: HOST_CHECK_MS }).catch(() => null)
+ const read = got?.exitCode === 0 ? herdrClientsOf(got.stdout) : null
+ // A failed scan counts too, so the next one waits HERDR_SCAN_MS.
- S.herdrScanAt = await clockNow($).catch(() => Date.now())
++ S.herdrScanAt = await nowMs($).catch(() => Date.now())
+ if (read) {
+ S.herdrClients = read.clients
+ S.herdrScanFront = read.front
+ }
+ const pick = read ? pickHerdrClient(read.clients, read.front === null ? null : frontKindOf(read.front), was) : null
+ if (!pick) return false
+ if (pick.by !== 'kept') S.herdrBy = pick.by
+ const changed = herdrClientChanged(S.herdrClient, pick.client)
+ S.herdrClient = pick.client
+ return changed
+ }
+
+ // herdr's check each HERDR_POLL_MS: the light check (HERDR_TICK_SH, then
+ // herdrTickPick on the clients of the last scan), else the full scan
+ // (readHerdrClient). True when the terminal changed.
+ export async function checkHerdrClient($: EngineInterface): Promise<boolean> {
- const now = await clockNow($).catch(() => Date.now())
++ const now = await nowMs($).catch(() => Date.now())
+ const ageMs = S.herdrScanAt === null ? null : now - S.herdrScanAt
+ let tick: HerdrTick | null = null
+ if (ageMs !== null && ageMs < HERDR_SCAN_MS) {
+ const ttys = S.herdrClients.map(c => `/dev/${ttyNameOf(c.tty)}`)
+ // Nothing to read (no client, no app in front off macOS, as a remote pane): no process.
- const got = ttys.length || S.hostOs === 'Darwin' ? await processRun($, ['sh', '-c', HERDR_TICK_SH, 'sh', S.hostOs, ...ttys], { timeoutMs: HOST_CHECK_MS }).catch(() => null) : { exitCode: 0, stdout: '' }
++ const got = ttys.length || S.hostOs === 'Darwin' ? await exec($, ['sh', '-c', HERDR_TICK_SH, 'sh', S.hostOs, ...ttys], { timeoutMs: HOST_CHECK_MS }).catch(() => null) : { exitCode: 0, stdout: '' }
+ tick = got?.exitCode === 0 ? herdrTickOf(got.stdout) : null
+ }
+ const light = herdrTickPick({ clients: S.herdrClients, tick, was: S.herdrClient, scanFront: S.herdrScanFront, ageMs })
+ if (!light) return readHerdrClient($)
+ S.herdrClients = light.clients
+ if (!light.pick) return false
+ if (light.pick.by !== 'kept') S.herdrBy = light.pick.by
+ const changed = herdrClientChanged(S.herdrClient, light.pick.client)
+ S.herdrClient = light.pick.client
+ return changed
+ }
+
// The font that the terminal's own config or profile names.
async function configFontOf($: EngineInterface, isMac: boolean): Promise<string> {
- if (S.isIterm && isMac) {
- const profile = await getenv($, 'ITERM_PROFILE')
+ if (isItermHere() && isMac) {
+ const profile = S.itermProfile
const [marks, guid] = await Promise.all([
- processRun($, ['sh', '-c', ITERM_BOOKMARKS_SH], { timeoutMs: 5000 }).catch(() => null),
- processRun($, ['sh', '-c', ITERM_DEFAULT_SH], { timeoutMs: 5000 }).catch(() => null),
+ exec($, ['sh', '-c', ITERM_BOOKMARKS_SH], { timeoutMs: 5000 }).catch(() => null),
+ exec($, ['sh', '-c', ITERM_DEFAULT_SH], { timeoutMs: 5000 }).catch(() => null),
])
// A read that failed or no profile: not known.
const font = marks?.exitCode === 0 ? itermFontOf(marks.stdout, profile, guid?.stdout ?? '') : null
@@@ -325,9 -486,9 +486,9 @@@
return named?.exitCode === 0 ? firstLine(named.stdout) : ''
}
if (isGhosttyHere()) {
- const shown = await exec($, ['sh', '-c', GHOSTTY_SH], { timeoutMs: 5000 }).catch(() => null)
- const shown = await processRun($, ['sh', '-c', GHOSTTY_SH], { timeoutMs: 5000, ...ghosttyInit() }).catch(() => null)
++ const shown = await exec($, ['sh', '-c', GHOSTTY_SH], { timeoutMs: 5000, ...ghosttyInit() }).catch(() => null)
// cmux loads its own config after Ghostty's; +show-config does not read it.
- const own = S.isCmux ? ((await readText($, cmuxGhosttyConfigPath((await envGet($, 'HOME')) ?? ''))) ?? '') : ''
+ const own = S.isCmux ? ((await readText($, cmuxGhosttyConfigPath((await getenv($, 'HOME')) ?? ''))) ?? '') : ''
return ghosttyFont($, isMac, ghosttyFontsOf(cmuxConfigOf(shown?.stdout ?? '', own)))
}
if (S.isKitty) {
@@@ -384,8 -553,8 +553,8 @@@ export async function readHostMode($: E
// 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
+ if (!isItermHere() || S.hostOs !== 'Darwin') return null
- const got = await processRun($, ['sh', '-c', ITERM_MODE_SH], { timeoutMs: HOST_CHECK_MS }).catch(() => null)
+ const got = await exec($, ['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
@@@ -401,12 -570,13 +570,13 @@@ export async function probeOsc11($: Eng
}
// The background of Ghostty's config. A `light:A,dark:B` theme follows the OS
- // (in cmux, cmux's appearance). In cmux, cmux's own config is read as well.
+ // (in cmux, cmux's appearance). In cmux, cmux's own config is read as well;
+ // herdr in Ghostty reads Ghostty's.
async function readGhosttyMode($: EngineInterface): Promise<HostMode | null> {
- if (!/ghostty/i.test(S.termProgram + S.termName)) return null
- const got = await exec($, ['sh', '-c', GHOSTTY_SH], { timeoutMs: HOST_CHECK_MS }).catch(() => null)
+ if (!isGhosttyIn(S.termProgram, S.termName) && S.herdrHost !== 'ghostty' && S.herdrHost !== 'cmux') return null
- const got = await processRun($, ['sh', '-c', GHOSTTY_SH], { timeoutMs: HOST_CHECK_MS, ...ghosttyInit() }).catch(() => null)
++ const got = await exec($, ['sh', '-c', GHOSTTY_SH], { timeoutMs: HOST_CHECK_MS, ...ghosttyInit() }).catch(() => null)
if (!got || got.exitCode !== 0) return null
- const home = (await envGet($, 'HOME')) ?? ''
+ const home = (await getenv($, 'HOME')) ?? ''
const own = S.isCmux ? ((await readText($, cmuxGhosttyConfigPath(home))) ?? '') : ''
const config = cmuxConfigOf(got.stdout, own)
if (S.isCmux && !ghosttyHasColors(config)) {
@@@ -419,9 -589,9 +589,9 @@@
if (pair) {
appearance = S.isCmux ? ((await readCmuxAppearance($).catch(() => null))?.mode ?? null) : ((await readOsMode($).catch(() => null))?.mode ?? null)
const where = {
- xdgConfig: (await envGet($, 'XDG_CONFIG_HOME')) || undefined,
+ xdgConfig: (await getenv($, 'XDG_CONFIG_HOME')) || undefined,
home,
- resources: (await getenv($, 'GHOSTTY_RESOURCES_DIR')) || undefined,
+ resources: (await outerEnv($, 'GHOSTTY_RESOURCES_DIR')) || undefined,
}
for (const mode of MODES) {
for (const path of ghosttyThemePaths(pair[mode], where)) {
@@@ -479,10 -649,10 +649,10 @@@ export async function readText($: Engin
// 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 envGet($, 'HOME')) ?? ''
+ const home = (await getenv($, 'HOME')) ?? ''
const dirs = kittyConfigDirsOf({
- kittyDir: (await getenv($, 'KITTY_CONFIG_DIRECTORY')) || undefined,
+ kittyDir: (await outerEnv($, 'KITTY_CONFIG_DIRECTORY')) || undefined,
- xdgConfig: (await envGet($, 'XDG_CONFIG_HOME')) || undefined,
+ xdgConfig: (await getenv($, 'XDG_CONFIG_HOME')) || undefined,
home,
isMac: S.hostOs === 'Darwin',
})
@@@ -519,9 -689,9 +689,9 @@@ async function readKittyMode($: EngineI
// 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 getenv($, 'RIO_CONFIG_HOME')) || undefined,
+ rioHome: (await outerEnv($, 'RIO_CONFIG_HOME')) || undefined,
- xdgConfig: (await envGet($, 'XDG_CONFIG_HOME')) || undefined,
- home: (await envGet($, 'HOME')) ?? '',
+ xdgConfig: (await getenv($, 'XDG_CONFIG_HOME')) || undefined,
+ home: (await getenv($, 'HOME')) ?? '',
isMac: S.hostOs === 'Darwin',
})
return { dir, config: tomlStringsOf((await readText($, `${dir}/config.toml`)) ?? '') }
@@@ -604,11 -788,20 +788,20 @@@ export function showMode($: EngineInter
beginEpoch($)
}
- // Polls the OS appearance while the setting is auto, and only then.
+ // Polls while the setting is auto or under herdr (its client can change), and
+ // only then: each HOST_POLL_MS, under herdr each HERDR_POLL_MS.
export function watchHost($: EngineInterface) {
- if (S.setting === 'auto' && !S.watch) {
+ const wanted = S.setting === 'auto' || S.isHerdr
+ const ms = S.isHerdr ? HERDR_POLL_MS : HOST_POLL_MS
+ // Started before setUp knew of herdr: started again with its period.
+ if (S.watch && (!wanted || S.watchMs !== ms)) {
+ S.watch.cancel()
+ S.watch = null
+ }
+ if (wanted && !S.watch) {
try {
- S.watch = every($, HOST_POLL_MS, () => void pollHost($).catch(() => undefined))
- S.watch = clockEvery($, ms, () => void pollHost($).catch(() => undefined))
++ S.watch = every($, ms, () => void pollHost($).catch(() => undefined))
+ S.watchMs = ms
} catch {
S.watch = null
}
diff --cc hooks/lib/mode.ts
index 393abd2,e1f3ba2..55ed6f9
--- a/hooks/lib/mode.ts
+++ b/hooks/lib/mode.ts
@@@ -90,6 -90,19 +90,19 @@@ export function parseOsc11(text: string
return { r: part(m[1]!), g: part(m[2]!), b: part(m[3]!) }
}
+ // Under herdr, the OSC 11 answer (the background of the terminal in front)
+ // does not always reach the mod (Claude Code reads it first). A poll with no
+ // answer keeps the last answer's mode until OSC11_MISSES polls in a row have
+ // none; then the other sources count. `last`: the answer kept and the misses
+ // in a row since it (null: none kept).
+ export const OSC11_MISSES = 3
+ export type Osc11Kept = { seen: HostMode; misses: number } | null
+ export function keptOsc11(last: Osc11Kept, answer: HostMode | null): { kept: Osc11Kept; use: HostMode | null } {
+ if (answer) return { kept: { seen: answer, misses: 0 }, use: answer }
+ if (last && last.misses + 1 < OSC11_MISSES) return { kept: { seen: last.seen, misses: last.misses + 1 }, use: last.seen }
+ return { kept: null, use: null }
+ }
+
// Control characters shown as text (\e, \a, \xNN), for /iui 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')}`))
+ text.replace(/[\x00-\x1f\x7f]/g, c => (c.charCodeAt(0) === 27 ? '\\e' : c.charCodeAt(0) === 7 ? '\\a' : `\\x${c.charCodeAt(0).toString(16).padStart(2, '0')}`))
diff --cc hooks/lib/pictures.tsx
index 2dd783b,3b5c2ed..d13e7ba
--- a/hooks/lib/pictures.tsx
+++ b/hooks/lib/pictures.tsx
@@@ -19,10 -19,11 +19,11 @@@ import
import { imagePathOf } from './markdown'
import { drawPages, hashOf, linkRowsOf, linksFor, type ShownLink } from './draw'
import { convertCall, logDebug, parseOd, pngSize } from './typst'
+ import { flipFile } from './flip'
import { pagesOf, type Drawing } from './answer'
- import { HEADERS_SH } from './host'
+ import { HEADERS_SH, perlFor } from './host'
import { frameFor, pictureColumns, shownFor, type Frame } from './frame'
-import { clockAfter, fsExists, fsList, fsRead, fsStat, fsWrite, processRun, sessionId, sessionRoot, uiClose, invalidate, uiOpen, uiResolve } from './api'
+import { delay, exists, ls, cat, stat, write, exec, sid, root, hide, redraw, show, uiResolve } from './api'
export type Picture = { file: string; stamp: string; bytes: number; width: number; height: number }
export type Shown = { source: ImageSource; columns: number; rows: number; alt: string }
@@@ -133,6 -143,28 +143,28 @@@ export async function shownOne($: Engin
return { source: { file, format: 'png', generation }, ...fit, alt }
}
+ // Flip mode: a PNG stored for herdr in iTerm2 drawn `rows` rows tall
+ // (flip.ts), in a key folder of the cache by the file, its stat stamp and
+ // the rows; made once (one run per key), kept from an earlier load. Null
+ // when it fails.
+ const flipped = new Map<string, Promise<string | null>>()
+ function flippedOf($: EngineInterface, ready: Env, p: Picture, rows: number): Promise<string | null> {
+ const key = `${p.file}@${p.stamp}@${rows}`
+ let got = flipped.get(key)
+ if (!got) {
+ const out = `${ready.cache}/${hashOf(['flip', p.file, p.stamp, rows])}/flip.png`
+ got = (async () => {
- const made = await fsStat($, out).catch(() => null)
++ const made = await stat($, out).catch(() => null)
+ if (made?.kind === 'file' && made.size) return out
+ const ok = await flipFile($, { src: p.file, out, rows, isPage: false, perl: perlFor(ready.isMac) })
+ if (!ok) await logDebug($, ready.cache, `could not store ${p.file} for herdr in iTerm2`)
+ return ok ? out : null
+ })()
+ keep(flipped, key, got, PICTURES_KEPT)
+ }
+ return got
+ }
+
const nameOf = (file: string) => file.split('/').pop() || 'image'
// A JPEG, WebP or SVG, or a PDF's page, as a PNG that Typst makes
diff --cc hooks/lib/setup.ts
index b82918b,f13ca43..884b8c0
--- a/hooks/lib/setup.ts
+++ b/hooks/lib/setup.ts
@@@ -4,13 -4,14 +4,14 @@@ import type { EngineInterface } from 'c
import { S } from './state'
import { readText } from './host'
-import { envGet, fsWrite, processRun, storeGet, storeSet, uiAsk, uiLog, uiToast } from './api'
+import { getenv, exists, write, exec, load, save, ask, log, toast } from './api'
// 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).
+ // and herdr need 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 and
+ // herdr alone, not in tmux or screen (Claude Code cannot draw there). The
+ // markers stay as they were (an old block set it in iTerm2 only).
export const SETUP_START = '# >>> cc-intelligent-ui: Claude Code pictures in iTerm2 >>>'
export const SETUP_END = '# <<< cc-intelligent-ui <<<'
export type ShellRc = { path: string; kind: 'sh' | 'fish' }
@@@ -67,61 -70,64 +70,75 @@@ async function shellRc($: EngineInterfa
})
}
+// The start file's text: '' when it is confirmed missing, null when it
+// exists (or may exist) but cannot be read. A write over null would lose it.
+async function readRc($: EngineInterface, path: string): Promise<string | null> {
+ const there = await exists($, path).catch(() => true)
+ if (!there) return ''
+ return readText($, path)
+}
+
- // What /iui setup says where iTerm2 does not run (not macOS): it changes no file.
- export const SETUP_NOT_MAC = '/iui setup is for iTerm2, which runs on macOS only, so Intelligent UI changed no file. ' +
- 'On Linux, kitty and Ghostty show pictures with no setup. ' +
+ // What /iui setup says where neither iTerm2 (macOS only) nor herdr runs: it changes no file.
+ export const SETUP_NOT_MAC = '/iui setup is for iTerm2 and herdr. iTerm2 runs on macOS only, and this terminal is not herdr, so Intelligent UI changed no file. ' +
+ 'On Linux, kitty and Ghostty show pictures with no setup. In herdr, run /iui setup in a herdr pane. ' +
'For Rio, set CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1 before you start Claude Code. Run /iui details to see if this terminal shows pictures.'
- // Adds (or removes) the setup block. Returns what to tell the person.
+ // The words for the terminal in use: herdr opens panes, iTerm2 tabs.
+ export const setupWordsOf = (isHerdr: boolean) => (isHerdr ? { app: 'herdr', tab: 'pane' } : { app: 'iTerm2', tab: 'tab' })
+
+ // Adds (or removes) the setup block. Returns what to tell the person. A
+ // block of an older version (no herdr) is replaced.
export async function runSetup($: EngineInterface, remove: boolean): Promise<string> {
- if (S.hostOs && S.hostOs !== 'Darwin') return SETUP_NOT_MAC
+ if (S.hostOs && S.hostOs !== 'Darwin' && !S.isHerdr) return SETUP_NOT_MAC
const rc = await shellRc($)
- const manual = `export CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1 (only in iTerm2, not in tmux or screen)`
+ const { app, tab } = setupWordsOf(S.isHerdr)
+ const manual = `export CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1 (only in iTerm2 and herdr, not in tmux or screen)`
if (!rc) return `Intelligent UI 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 text = await readRc($, rc.path)
+ if (text === null) return `Intelligent UI could not read ${rc.path}, so it changed no file. Add this to it yourself: ${manual}`
- const restart = 'Close this tab, open a new iTerm2 tab, and start Claude Code there to see pictures.'
+ const restart = `Close this ${tab}, open a new ${app} ${tab}, and start Claude Code there to see pictures.`
if (remove) {
if (!hasSetup(text)) return `${rc.path} has no Intelligent UI block.`
- await fsWrite($, rc.path, withoutSetup(text))
+ await write($, rc.path, withoutSetup(text))
- return `Removed the Intelligent UI block from ${rc.path}. New iTerm2 tabs show answers as text.`
+ return `Removed the Intelligent UI block from ${rc.path}. New ${app} ${tab}s show answers as text.`
}
- if (hasSetup(text)) return `${rc.path} already has the Intelligent UI block. ${restart}`
+ if (hasNewSetup(text, rc.kind)) return `${rc.path} already has the Intelligent UI block. ${restart}`
- if (rc.kind === 'fish') await processRun($, ['mkdir', '-p', rc.path.replace(/\/[^/]*$/, '')]).catch(() => null)
- await fsWrite($, rc.path, withSetup(text, rc.kind))
+ if (rc.kind === 'fish') await exec($, ['mkdir', '-p', rc.path.replace(/\/[^/]*$/, '')]).catch(() => null)
+ await write($, rc.path, withSetup(text, rc.kind))
- return `Added the Intelligent UI block to ${rc.path}. ${restart} Undo with /iui setup remove.`
+ const done = hasSetup(text) ? `Updated the Intelligent UI block in ${rc.path}` : `Added the Intelligent UI block to ${rc.path}`
+ return `${done}. ${restart} Undo with /iui 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 storeGet($, 'setup').catch(() => undefined)) === 'never') return
+ if ((await load($, 'setup').catch(() => undefined)) === 'never') return
const rc = await shellRc($)
- const text = rc ? ((await readText($, rc.path)) ?? '') : ''
+ const text = rc ? await readRc($, rc.path) : ''
- if (text === null || (rc && hasSetup(text))) return
++ if (text === null) return
+ // A block is enough for iTerm2; herdr needs this version's (an old one sets the variable in iTerm2 only).
+ const isOld = !!rc && hasSetup(text) && !hasNewSetup(text, rc.kind)
+ if (rc && hasSetup(text) && !(S.isHerdr && isOld)) return
- const file = rc ? rc.path.replace((await envGet($, 'HOME')) ?? '\u0000', '~') : "your shell's start file"
+ const home = (await getenv($, 'HOME')) ?? ''
+ const file = rc ? (home ? rc.path.replace(home, '~') : rc.path) : "your shell's start file"
- const answer = await ask($,
- `Intelligent UI 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: 'iui', options: ['Add the line', 'Not now', 'Never ask'] },
+ const { app, tab } = setupWordsOf(S.isHerdr)
+ const yes = isOld ? 'Update the line' : 'Add the line'
- const ask = isOld
++ const question = isOld
+ ? `Update the Intelligent UI line in ${file} so that it sets it in herdr too (not in tmux or screen)?`
+ : `Add one line to ${file} that sets it in iTerm2 and herdr only (not in tmux or screen)?`
- const answer = await uiAsk($,
- `Intelligent UI draws answers as pictures, but in ${app} Claude Code needs CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1 when it starts. ${ask}`,
++ const answer = await ask($,
++ `Intelligent UI draws answers as pictures, but in ${app} Claude Code needs CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1 when it starts. ${question}`,
+ { header: 'iui', options: [yes, 'Not now', 'Never ask'] },
)
- if (answer === 'Never ask') await storeSet($, 'setup', 'never')
+ if (answer === 'Never ask') await save($, 'setup', 'never')
- if (answer !== 'Add the line') return
+ if (answer !== yes) return
const said = await runSetup($, false)
// The toast box is small: a short line there, the whole text in the transcript.
try {
- uiLog($, said)
+ log($, said)
} catch {}
try {
- toast($, said.startsWith('Added') ? 'Close this tab and open a new iTerm2 tab to see pictures.' : 'See the transcript for the setup.', { timeoutMs: 10000 })
- uiToast($, /^(Added|Updated)/.test(said) ? `Close this ${tab} and open a new ${app} ${tab} to see pictures.` : 'See the transcript for the setup.', { timeoutMs: 10000 })
++ toast($, /^(Added|Updated)/.test(said) ? `Close this ${tab} and open a new ${app} ${tab} to see pictures.` : 'See the transcript for the setup.', { timeoutMs: 10000 })
} catch {}
}
diff --cc hooks/lib/state.ts
index 2c4cfce,2bcbc2b..b7cde2e
--- a/hooks/lib/state.ts
+++ b/hooks/lib/state.ts
@@@ -12,8 -12,9 +12,9 @@@ import type { GridMetrics } from './gri
import type { Checked } from './updates'
import type { ClipWay } from './clipboard'
import type { PdfFacts, PixelBox } from './images'
+ import type { HerdrClient, HerdrHost } from './terminal'
import { DEFAULT_HEIGHT, DEFAULT_SIZE, DEFAULT_WIDTH, type Height, type Width } from './settings'
-import { invalidate } from './api'
+import { redraw } from './api'
// 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
diff --cc hooks/lib/typst.ts
index 29f30c8,a8d7691..9daa044
--- a/hooks/lib/typst.ts
+++ b/hooks/lib/typst.ts
@@@ -12,7 -12,8 +12,8 @@@ import { HEADERS_SH, perlFor } from './
import { logDebug } from './log'
import { positionsOf, type Mark, type Positions } from './copy'
import { hasBoldFace, leanFontsFor } from './fonts'
+ import { flipFile } from './flip'
-import { clockAfter, envGet, fsExists, fsList, fsRead, fsWrite, processRun, spawn } from './api'
+import { delay, getenv, exists, ls, cat, write, exec, spawn } from './api'
// The typst command and its environment. Network off (see NO_NETWORK) and a
// package cache of our own, so only the vendored packages load, and the
@@@ -44,132 -43,6 +45,137 @@@ export function typstCall(o:
return { argv, env: noNetworkEnv(o.cache) }
}
+// ---- The root of a compile: only the files the mod puts there -------------
+// md.typ evals the answer's ```typst blocks (and math), and Typst lets code
+// read any file under its root. So a compile and a probe of answer text run
+// with a root of their own: a new private folder in the key folder, with
+// each file the template needs at its own path (so the inputs and doc.json
+// keep their paths). STAGE_SH makes it, from $1 the folder, $2 the plugin
+// root, $3 the doc JSON's path (its text on stdin), $4 the theme folder and
+// then the allowed images (all paths as rootPathOf gives them):
+// - render/: md.typ copied (Typst wants its main file inside the root) and
+// links to the rest of the plugin's render folder;
+// - the doc JSON, a file of its own (a compile of the same key at the same
+// time has its own folder);
+// - a link to the theme folder (a built-in one is in render/ already);
+// - a link to each image (and each image its SVG links to) that is a file
+// with an image name, also after its links (so a link named .png to
+// another file is not one). An image under a linked folder is there
+// already, and no folder is made through a link.
+// Typst follows the links; any other path is not found, and `..` can not
+// leave the root.
+export const STAGE_SH = [
+ 'umask 077',
+ 'r=$1 p=$2 d=$3 t=$4',
+ 'shift 4',
+ 'mkdir "$r" && mkdir -p "$r$p/render" "$r${d%/*}" || exit 1',
+ 'ln -s "$p"/render/* "$r$p/render/" && rm "$r$p/render/md.typ" && cp "$p/render/md.typ" "$r$p/render/md.typ" && cat > "$r$d" || exit 1',
+ 'case $t in',
+ ' "$p/render/"*) ;;',
+ ' /?*) if [ -d "$t" ] && [ ! -e "$r$t" ]; then mkdir -p "$r${t%/*}" && ln -s "$t" "$r$t" || exit 1; fi ;;',
+ 'esac',
+ 'for f; do',
+ ' case $f in',
+ ' *//*|*/./*|*/../*|*/.|*/..|"$p/render/"*|"$t/"*) continue ;;',
+ ' /?*) ;;',
+ ' *) continue ;;',
+ ' esac',
+ ' g=$f n=0',
+ ' while [ -L "$g" ] && [ $n -lt 40 ]; do',
+ ' l=$(readlink "$g") || break',
+ ' case $l in /*) g=$l ;; *) g=${g%/*}/$l ;; esac',
+ ' n=$((n + 1))',
+ ' done',
+ ' [ -L "$g" ] && continue',
+ ' case $(printf %s "${g##*/}" | tr A-Z a-z) in',
+ ' *.png|*.jpg|*.jpeg|*.gif|*.svg|*.webp) [ -f "$g" ] && [ ! -e "$r$f" ] && mkdir -p "$r${f%/*}" && ln -s "$g" "$r$f" ;;',
+ ' esac',
+ 'done',
+ 'exit 0',
+].join('\n')
+
+// A path as Typst reads it in its root: `.`, `..` and empty parts resolved
+// by name; null when `..` goes above the root.
+export function rootPathOf(path: string): string | null {
+ const parts: string[] = []
+ for (const part of path.split('/')) {
+ if (part === '' || part === '.') continue
+ if (part !== '..') parts.push(part)
+ else if (parts.pop() === undefined) return null
+ }
+ return `/${parts.join('/')}`
+}
+
+// The template's main file in a run folder.
+export const templateIn = (run: string, root: string) => `${run}${rootPathOf(root) ?? ''}/render/md.typ`
+
+// The doc JSON the template reads: the base folder, the segments and the
- // allow-list of images (path and full path of each, existingImages).
- export type Doc = { base: string; segments: readonly string[]; images: readonly string[] }
++// allow-list of images (path and full path of each, existingImages), and
++// the seams (the gaps at the breaks) when there is more than one segment.
++export type Doc = { base: string; segments: readonly string[]; images: readonly string[]; seams?: ([string, string] | null)[] }
++
++// The doc of a compile (and of its probe: the same seams).
++export const docOf = (base: string, segments: readonly string[], images: readonly string[]): Doc =>
++ ({ base, segments, images, ...(segments.length > 1 ? { seams: seamsOf(segments) } : {}) })
+
+// The full paths of a doc's allowed images (the odd entries), as in the root.
+export const imageFullsOf = (images: readonly string[]) =>
+ images.filter((_, i) => i % 2 === 1).map(rootPathOf).filter((p): p is string => !!p)
+
+// The arguments of STAGE_SH for a run folder: the images by their full
+// paths (and the images their SVGs link to), each once.
+export function stageArgs(run: string, root: string, docPath: string, themeDir: string, images: readonly string[], linked: readonly string[] = []): string[] {
+ return [run, rootPathOf(root) ?? '', rootPathOf(docPath) ?? '', rootPathOf(themeDir) ?? '', ...new Set([...imageFullsOf(images), ...linked])]
+}
+
+const IMAGE_NAME = /\.(png|jpe?g|gif|svg|webp)$/i
+
+// The images an SVG at `full` links to by a relative path (Typst loads them
+// from the SVG's folder in the root; it refuses absolute ones), as paths in
+// the root.
+export function svgLinksOf(svg: string, full: string): string[] {
+ const dir = full.replace(/\/[^/]*$/, '')
+ const found: string[] = []
+ for (const m of svg.matchAll(/\bhref\s*=\s*(["'])([^"']*)\1/g)) {
+ const href = m[2]!.trim()
+ if (!href || href.startsWith('#') || href.startsWith('/') || /^[a-z][a-z0-9+.-]*:/i.test(href)) continue
+ const path = rootPathOf(`${dir}/${href}`)
+ if (path && IMAGE_NAME.test(path)) found.push(path)
+ }
+ return found
+}
+
+// The images the allowed SVGs of `images` link to.
+async function svgLinks($: EngineInterface, images: readonly string[]): Promise<string[]> {
+ const found: string[] = []
+ for (const full of new Set(imageFullsOf(images).filter(p => /\.svg$/i.test(p)))) {
+ const svg = await cat($, full).catch(() => '')
+ if (typeof svg === 'string') found.push(...svgLinksOf(svg, full))
+ }
+ return found
+}
+
+let runs = 0
+// A new run folder's name in key folder `dir` (unique in this load, and
+// random across loads and sessions).
+const runFolderIn = (dir: string) => `${dir}/r-${(++runs).toString(36)}${Math.random().toString(36).slice(2, 10)}`
+
+// Runs `use` with a root of its own for `doc` (STAGE_SH), then removes it.
+// When the root can not be made, `use` still runs: Typst then finds no
+// template there and fails (never a wider root); the folder is left to the
+// 2-day sweep (it may be another run's, when its name was taken).
+export async function inRoot<T>($: EngineInterface, job: Job, dir: string, doc: Doc, use: (run: string) => Promise<T>): Promise<T> {
+ const run = runFolderIn(dir)
+ const args = stageArgs(run, job.env.root, `${dir}/doc.json`, job.themeDir, doc.images, await svgLinks($, doc.images))
+ const made = await exec($, ['sh', '-c', STAGE_SH, 'sh', ...args], { stdin: JSON.stringify(doc), timeoutMs: 10000 }).catch(() => null)
+ if (made?.exitCode !== 0) await logDebug($, job.env.cache, `the root ${run} could not be made: ${made?.stderr ?? 'sh did not run'}`)
+ try {
+ return await use(run)
+ } finally {
+ if (made?.exitCode === 0) void Promise.resolve(exec($, ['rm', '-rf', run], { timeoutMs: 10000 })).catch(() => undefined)
+ }
+}
+
// The arguments that load only the fonts of a lean folder (and Typst's own).
export const fontArgs = (fonts?: string) => (fonts ? ['--ignore-system-fonts', '--font-path', fonts] : [])
@@@ -542,17 -413,13 +548,17 @@@ export async function probePage
} catch {
return null
}
+ const segments = kept?.segments
if (!Array.isArray(segments) || segments.length !== o.pages || !job.env.typst) return null
const typst = job.env.typst
- const { inputs, ppi } = typstInputs(job, segments as string[], dir, o.isSafe)
- const ran = await runFonts($, job, await leanFor($, job, segments as string[]), fonts => {
- const { argv, env } = probeCall({ typst, root: job.env.root, cache: job.env.cache, inputs: { ...inputs, page: o.page + 1 }, ...(fonts ? { fonts } : {}) })
+ const images = Array.isArray(kept!.images) ? kept!.images.filter((p): p is string => typeof p === 'string') : []
- const doc: Doc = { base: typeof kept!.base === 'string' ? kept!.base : '', segments, images }
++ const doc = docOf(typeof kept!.base === 'string' ? kept!.base : '', segments, images)
+ const { inputs, ppi } = typstInputs(job, segments, dir, o.isSafe)
+ const fonts = await leanFor($, job, segments)
+ const ran = await inRoot($, job, dir, doc, run => runFonts($, job, fonts, fonts => {
+ const { argv, env } = probeCall({ typst, root: job.env.root, run, cache: job.env.cache, inputs: { ...inputs, page: o.page + 1 }, ...(fonts ? { fonts } : {}) })
return runKillable($, argv, { env, timeoutMs: COMPILE_TIMEOUT_MS })
- })
+ }))
if (ran.exitCode !== 0) {
await logDebug($, job.env.cache, `probe ${dir} page ${o.page + 1} failed:\n${ran.stderr}`)
return null
@@@ -601,14 -473,14 +607,15 @@@ export async function compile($: Engine
// The room height of a drawing in rows (less the pt rounding); unknown
// without a room (the default applies).
const roomRows = job.room ? Math.ceil(job.room.heightPt / rowPt - 0.01) : undefined
- let segments = splitSegments(job.text, job.columns, job.env.inline ? inlineBudget(job.cell) : SEGMENT_ROWS, job.size, roomRows)
+ let segments = splitSegments(job.text, job.columns, segmentBudget(job.env, job.columns, job.cell), job.size, roomRows)
const base = job.base ?? job.env.cwd
const images = await existingImages($, segments, base)
- await write($, `${dir}/doc.json`, JSON.stringify({ base, segments, images }))
- await fsWrite($, `${dir}/doc.json`, docOf(base, segments, images))
++ const doc = docOf(base, segments, images)
++ await write($, `${dir}/doc.json`, JSON.stringify(doc))
let tag = 'a'
let isSafe = false
- let ran = await runTypst($, job, { base, segments, images }, dir, tag, false, signal)
- let ran = await runTypst($, job, segments, dir, tag, false, signal)
++ let ran = await runTypst($, job, doc, dir, tag, false, signal)
let note: string | undefined
if (ran.isCancelled) return 'cancelled'
if (ran.exitCode !== 0) {
@@@ -618,7 -490,7 +625,7 @@@
note = firstLine(ran.stderr.split('\n').find(l => /error:/i.test(l)) ?? ran.stderr).replace(/^.*error:\s*/i, '')
tag = 'b'
isSafe = true
- ran = await runTypst($, job, { base, segments, images }, dir, tag, true, signal)
- ran = await runTypst($, job, segments, dir, tag, true, signal)
++ ran = await runTypst($, job, doc, dir, tag, true, signal)
if (ran.isCancelled) return 'cancelled'
if (ran.exitCode !== 0) {
await logDebug($, job.env.cache, `compile ${job.key} with safe=1 failed:\n${ran.stderr}`)
@@@ -635,8 -507,8 +642,9 @@@
const cut = segments.flatMap((seg, i) => (pages![i]!.rows > MAX_IMAGE_ROWS ? splitInTwo(seg, job.columns, job.size, roomRows) : [seg]))
if (cut.length > segments.length) {
if (signal?.aborted) return 'cancelled'
- await write($, `${dir}/doc.json`, JSON.stringify({ base, segments: cut, images }))
- const again = await runTypst($, job, { base, segments: cut, images }, dir, isSafe ? 'd' : 'c', isSafe, signal)
- await fsWrite($, `${dir}/doc.json`, docOf(base, cut, images))
- const again = await runTypst($, job, cut, dir, isSafe ? 'd' : 'c', isSafe, signal)
++ const cutDoc = docOf(base, cut, images)
++ await write($, `${dir}/doc.json`, JSON.stringify(cutDoc))
++ const again = await runTypst($, job, cutDoc, dir, isSafe ? 'd' : 'c', isSafe, signal)
if (again.isCancelled) return 'cancelled'
const split = again.exitCode === 0 ? await pagesOfRun($, job, dir, isSafe ? 'd' : 'c', cut) : null
if (split) {
@@@ -646,8 -518,30 +654,30 @@@
}
pages = pages.map(p => ({ ...p, rows: Math.min(MAX_IMAGE_ROWS, p.rows) }))
}
+ // Flip mode: each page stored for herdr in iTerm2, in place; a page that can not be stored fails the compile (the text shows).
+ if (job.flip) {
+ const flipped = await flipPages($, job, pages, signal)
+ if (typeof flipped === 'string') return flipped
+ pages = flipped
+ }
const { bulletRow } = firstLinePlace(job, segments)
const result: Result = { pages, bulletRow, ...(note ? { note } : {}) }
- await fsWrite($, `${dir}/pages.json`, JSON.stringify(result))
+ await write($, `${dir}/pages.json`, JSON.stringify(result))
return result
}
+
+ // The pages of a compile stored for flip mode (flip.ts: rows × B pixels
+ // tall, the bands reversed), each in place, with its new height.
+ async function flipPages($: EngineInterface, job: Job, pages: readonly Page[], signal?: AbortSignal): Promise<Page[] | 'failed' | 'cancelled'> {
+ const out: Page[] = []
+ for (const p of pages) {
+ const made = await flipFile($, { src: p.file, out: p.file, rows: p.rows, isPage: true, perl: perlFor(job.env.isMac), ...(signal ? { signal } : {}) })
+ if (signal?.aborted) return 'cancelled'
+ if (!made) {
+ await logDebug($, job.env.cache, `compile ${job.key}: could not store ${p.file} for herdr in iTerm2`)
+ return 'failed'
+ }
+ out.push({ ...p, height: made.height, flip: true })
+ }
+ return out
+ }
diff --cc hooks/register.tsx
index 14bb1b4,dbcd06f..95f2441
--- a/hooks/register.tsx
+++ b/hooks/register.tsx
@@@ -45,10 -45,10 +45,10 @@@ import { finalizeAll } from './lib/stre
import { knownTargets, knownWords, noteDrawn, noteDrawnAgain, noteOnScreen, wordsOf, type PageWords } from './lib/probe'
import { codePointsOf, decodeSelection, hasPlaceholders, joinSegments, pageTopsOf, pickPages, textOfRun, type Drawn, type Pick, type Segment } from './lib/copy'
import { pagesOf, type Drawing } from './lib/answer'
-import { clipboardNow, clipWatchArgs, clipWayReady, hintText } from './lib/clipboard'
+import { clipboardNow, clipboardRead, clipWatchArgs, clipWayReady, hintText } from './lib/clipboard'
import { setUp } from './lib/env'
import { frameFor, noteView, stopWatch, watchFrame, watchState } from './lib/frame'
- import { roomColumns } from './lib/terminal'
+ import { herdrText, isFlipHere, roomColumns } from './lib/terminal'
import { onScreenOf, pastedImagePath, pastedNumbers, sentFiles } from './lib/images'
import { drawPageField, pasteDir, pdfPagesOf, rowsAfter, sentOf, shownOf, underRow, type Shown, type Under } from './lib/pictures'
import { checkUpdates, loadUpdates, updateLine, updateNotice, type UpdateState } from './lib/updates'
diff --cc tests/root.test.ts
index 30191b2,0000000..ad2c381
mode 100644,000000..100644
--- a/tests/root.test.ts
+++ b/tests/root.test.ts
@@@ -1,172 -1,0 +1,186 @@@
+import { expect, test } from 'claude-code/testing'
+
+import { compile, forgetTouches, probePage, rootPathOf, STAGE_SH, stageArgs, svgLinksOf } from '../hooks/lib/typst'
+import { DEFAULT_METRICS, leanDirs, type Env, type Job } from '../hooks/lib/state'
+import { DEFAULT_CELL } from '../hooks/lib/settings'
+
+// Typst's root for answer text: a run folder of its own (STAGE_SH), never `/`.
+
+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 env: Env = {
+ typst: '/usr/bin/typst', canDraw: true, inline: false, cache: '/c', cwd: '/w', root: '/r', isMac: true, stamp: '1', home: '/h',
+ claudeTmp: '', termFont: '', designs: '/d', metrics: DEFAULT_METRICS,
+}
+let keys = 0
+const jobOf = (text: string): Job => ({
+ key: `k${++keys}`, requestId: 'r', text, columns: 100, cell: DEFAULT_CELL, theme: 'dark', size: 100, grid: true, themeDir: '/h/.claude/cc-intelligent-ui/themes/mine', env, epoch: 0,
+})
+
+// A host with typst: notes each process (argv, stdin) in order, and each
+// typst argv. `fails(argv)` says when typst fails; `stage` the exit code of
+// STAGE_SH; `exists` the files there are.
+function host(o: { fails?: (argv: string[]) => boolean; stage?: number; exists?: string[]; files?: Record<string, string> } = {}) {
+ const runs: { argv: string[]; stdin?: string }[] = []
+ const typst: string[][] = []
+ const files = new Map<string, string>(Object.entries(o.files ?? {}))
+ const run = (stdout: string, exitCode = 0) => ({ exitCode, stdout, stderr: '' })
+ const $ = {
+ fs: {
+ read: async (path: string) => {
+ if (!files.has(path)) throw new Error('ENOENT')
+ return files.get(path)!
+ },
+ write: async (path: string, text: string) => {
+ files.set(path, text)
+ },
+ exists: async (path: string) => (o.exists ?? []).includes(path),
+ list: async () => ['a-1.png', 'b-1.png'].map(name => ({ name, kind: 'file', size: 1, mtimeMs: 1, isLink: false })),
+ },
+ process: {
+ run: async (argv: string[], init?: { stdin?: string }) => {
+ runs.push({ argv, ...(init?.stdin !== undefined ? { stdin: init.stdin } : {}) })
+ if (argv[2] === STAGE_SH) return run('', o.stage ?? 0)
+ if (argv.join(' ').includes('od -An')) return run(argv.filter(a => a.endsWith('.png')).map(() => `${HEAD}\n@\n`).join(''))
+ return run('')
+ },
+ spawn: (request: { argv: string[] }) => {
+ const argv = request.argv.slice(4)
+ typst.push(argv)
+ runs.push({ argv })
+ const fail = o.fails?.(argv) ?? false
+ return (async function* () {
+ yield { stream: 'stdout' as const, text: argv[1] === 'query' ? '4242\n[]' : '4242\n' }
+ if (fail) yield { stream: 'stderr' as const, text: 'error: boom' }
+ return { code: fail ? 1 : 0, signal: null }
+ })()
+ },
+ },
+ clock: { after: () => ({ cancel() {} }) },
+ } as any
+ return { $, runs, typst, files }
+}
+
+const reset = () => {
+ leanDirs.clear()
+ forgetTouches()
+}
+const rootOf = (argv: string[]) => argv[argv.indexOf('--root') + 1]!
+const stages = (h: ReturnType<typeof host>) => h.runs.filter(r => r.argv[2] === STAGE_SH)
+// Lets the removal of a run folder (not waited for) start.
+const settle = async () => {
+ for (let i = 0; i < 20; i++) await Promise.resolve()
+}
+
+test('a compile runs typst in a new run folder of its key folder, never with the root at /', async () => {
+ reset()
+ const h = host({ exists: ['/w/pic.png'] })
+ const job = jobOf('A picture ![p](pic.png) and a block:\n\n```typst\n#read("/etc/hosts")\n```')
+ expect(await compile(h.$, job)).not.toBe('failed')
+ await settle()
+ expect(h.typst.length).toBe(1)
+ const argv = h.typst[0]!
+ const run = rootOf(argv)
+ expect(argv).toContain('--root')
+ expect(run).not.toBe('/')
+ expect(run.startsWith(`/c/${job.key}/r-`)).toBe(true)
+ // The template is the copy in the run folder (at its own path there).
+ expect(argv).toContain(`${run}/r/render/md.typ`)
+ expect(argv).not.toContain('/r/render/md.typ')
+ // The inputs keep their paths: the run folder has the files there.
+ expect(argv).toContain(`doc=/c/${job.key}/doc.json`)
+ expect(argv).toContain(`theme-dir=${job.themeDir}`)
+ // The folder is made first, with the doc JSON (as written) and the image.
+ const [stage] = stages(h)
+ expect(stage!.argv.slice(4)).toEqual([run, '/r', `/c/${job.key}/doc.json`, job.themeDir, '/w/pic.png'])
+ expect(stage!.stdin).toBe(h.files.get(`/c/${job.key}/doc.json`))
+ expect(h.runs.indexOf(stage!)).toBeLessThan(h.runs.findIndex(r => r.argv === argv))
+ // It goes after the run.
+ expect(h.runs.some(r => r.argv.join(' ') === `rm -rf ${run}`)).toBe(true)
+ reset()
+})
+
+test('the safe retry and the probe each run in a run folder of their own', async () => {
+ reset()
+ const h = host({ fails: argv => !argv.includes('safe=1') })
+ const job = jobOf('Some text.')
+ const result = await compile(h.$, job)
+ expect(result).not.toBe('failed')
+ expect(h.typst.length).toBe(2)
+ const [first, safe] = h.typst.map(rootOf)
+ expect(first).not.toBe(safe)
+ await probePage(h.$, job, `/c/${job.key}`, { page: 0, pages: 1, isSafe: true })
+ const probe = h.typst[2]!
+ expect(probe[1]).toBe('query')
+ expect(rootOf(probe).startsWith(`/c/${job.key}/r-`)).toBe(true)
+ expect(new Set(h.typst.map(rootOf)).size).toBe(3)
+ // No typst run anywhere has the root at /.
+ for (const argv of h.typst) expect(rootOf(argv)).not.toBe('/')
+ // The probe's folder has the doc JSON the compile wrote.
+ expect(stages(h)[2]!.stdin).toBe(h.files.get(`/c/${job.key}/doc.json`))
+ reset()
+})
+
++test('a doc of more than one segment keeps its seams in the run folder, for the compile and the probe', async () => {
++ reset()
++ const h = host()
++ const job = jobOf(Array.from({ length: 60 }, (_, i) => `Paragraph ${i} ${'word '.repeat(40)}`.trim()).join('\n\n'))
++ await compile(h.$, job)
++ const written = JSON.parse(h.files.get(`/c/${job.key}/doc.json`)!)
++ expect(written.segments.length).toBeGreaterThan(1)
++ expect(Array.isArray(written.seams)).toBe(true)
++ expect(JSON.parse(stages(h)[0]!.stdin!).seams).toEqual(written.seams)
++ await probePage(h.$, job, `/c/${job.key}`, { page: 0, pages: written.segments.length, isSafe: false })
++ expect(JSON.parse(stages(h).at(-1)!.stdin!).seams).toEqual(written.seams)
++ reset()
++})
++
+test('two compiles of the same key at once never share a run folder', async () => {
+ reset()
+ const h = host()
+ const job = jobOf('Same text.')
+ await Promise.all([compile(h.$, job), compile(h.$, { ...job })])
+ const roots = h.typst.map(rootOf)
+ expect(roots.length).toBe(2)
+ expect(roots[0]).not.toBe(roots[1])
+ reset()
+})
+
+test('when the run folder can not be made, typst still gets that folder as its root (it then fails), never /', async () => {
+ reset()
+ const h = host({ stage: 1, fails: () => true })
+ expect(await compile(h.$, jobOf('Text.'))).toBe('failed')
+ expect(h.typst.length).toBe(2)
+ for (const argv of h.typst) expect(rootOf(argv).startsWith('/c/k')).toBe(true)
+ reset()
+})
+
+test('paths in the root are resolved by name; a path above the root is none', () => {
+ expect(rootPathOf('/a/./b//c/../d.png')).toBe('/a/b/d.png')
+ expect(rootPathOf('/a/b/')).toBe('/a/b')
+ expect(rootPathOf('/../etc/hosts')).toBe(null)
+ expect(rootPathOf('/a/../../etc/hosts')).toBe(null)
+ expect(rootPathOf('/')).toBe('/')
+})
+
+test('the run folder gets each allowed image once, by its full path in the root', () => {
+ const images = ['pic.png', '/w/pic.png', './pic.png', '/w/./pic.png', 'x/../../up.png', '/w/x/../../up.png', '/../bad.png', '/../bad.png']
+ expect(stageArgs('/c/k/r-1', '/r/', '/c/k/doc.json', '/t//mine', images)).toEqual(['/c/k/r-1', '/r', '/c/k/doc.json', '/t/mine', '/w/pic.png', '/up.png'])
+ expect(stageArgs('/c/k/r-1', '/r', '/c/k/doc.json', '/t', [], ['/w/a.png', '/w/a.png'])).toEqual(['/c/k/r-1', '/r', '/c/k/doc.json', '/t', '/w/a.png'])
+})
+
+test("an SVG's linked images: relative image paths only, from the SVG's folder", () => {
+ const svg = [
+ '<image href="a.png"/>', '<image xlink:href=\'../up/b.JPG\'/>', '<image href="/etc/x.png"/>', '<image href="data:image/png;base64,AA"/>',
+ '<image href="https://x/y.png"/>', '<use href="#z"/>', '<image href="notes.txt"/>', '<image href="../../../../../x.png"/>',
+ ].join('')
+ expect(svgLinksOf(svg, '/w/pics/s.svg')).toEqual(['/w/pics/a.png', '/w/up/b.JPG'])
+})
+
+test('an allowed SVG gets the images it links to in the run folder', async () => {
+ reset()
+ const h = host({ exists: ['/w/s.svg'], files: { '/w/s.svg': '<svg><image href="pic.png"/></svg>' } })
+ await compile(h.$, jobOf('![s](s.svg)'))
+ expect(stages(h)[0]!.argv.slice(8)).toEqual(['/w/s.svg', '/w/pic.png'])
+ reset()
+})
diff --cc tests/setup.test.ts
index 16a4653,1c0400f..954533a
--- a/tests/setup.test.ts
+++ b/tests/setup.test.ts
@@@ -57,8 -85,9 +85,9 @@@ test('a block of the other kind is repl
expect(sh.startsWith('set -x A 1\n\n')).toBe(true)
})
- // 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, o: { env?: Record<string, string>; stored?: Record<string, unknown>; unreadable?: string } = {}) => {
+ // An iTerm2 session on a Mac with the engine's pictures off and a zsh user
+ // (`os`: another OS, `answer`: the option chosen, any question).
-const iterm = (on: any, files: Record<string, string>, answer: string | null, o: { env?: Record<string, string>; stored?: Record<string, unknown>; os?: string } = {}) => {
++const iterm = (on: any, files: Record<string, string>, answer: string | null, o: { env?: Record<string, string>; stored?: Record<string, unknown>; os?: string; unreadable?: string } = {}) => {
const store = new Map(Object.entries(o.stored ?? {}))
on('store.get', async ($: any, e: any) => ({ value: store.get(e.key) }))
on('store.set', async ($: any, e: any) => (store.set(e.key, e.value), { value: undefined }))
@@@ -80,10 -109,10 +109,10 @@@
on('process.run', async ($: any, e: any, next: any) => {
if (e.argv[0] === 'mkdir') return mkdirs.push(e.argv.slice(1).join(' ')), { value: { exitCode: 0, stdout: '', stderr: '', isStdoutTruncated: false, isStderrTruncated: false } }
return e.argv[0] === 'sh' && /cc-intelligent-ui-/.test(e.argv.join(' '))
- ? { value: { exitCode: 0, stdout: '/tmp/mdp\nDarwin\n', stderr: '', isStdoutTruncated: false, isStderrTruncated: false } }
+ ? { value: { exitCode: 0, stdout: `/tmp/mdp\n${o.os ?? 'Darwin'}\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.read', async ($: any, e: any, next: any) => (e.path === o.unreadable ? { deny: 'EACCES: permission denied' } : 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)
@@@ -225,34 -254,90 +254,122 @@@ test('a yes with a shell it does not kn
expect(toasts.filter(t => /transcript|tab/.test(t))).toEqual(['See the transcript for the setup.'])
})
+// A start file that exists but whose read fails (over 4 MiB, EACCES, an I/O error).
+const unreadable = (on: any, files: Record<string, string>, answer: string | null, o: Parameters<typeof iterm>[3] = {}) =>
+ iterm(on, files, answer, { ...o, unreadable: '/h/.zshrc' })
+
+test('/iui setup does not replace a start file whose read fails', async ($, on) => {
+ const files: Record<string, string> = { '/h/.zshrc': 'export PATH=/important:$PATH\n' }
+ unreadable(on, files, 'Not now', { stored: { setup: 'never' } })
+ const ran = await $.command.run({ command: 'iui', args: 'setup' } as any)
+ expect(ran.text).toContain('could not read /h/.zshrc')
+ expect(ran.text).toContain('changed no file')
+ expect(ran.text).toContain('export CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1')
+ expect(files['/h/.zshrc']).toBe('export PATH=/important:$PATH\n')
+})
+
+test('/iui setup remove does not write a start file whose read fails', async ($, on) => {
+ const files: Record<string, string> = { '/h/.zshrc': `${setupBlock('sh')}export A=1\n` }
+ unreadable(on, files, 'Not now', { stored: { setup: 'never' } })
+ const ran = await $.command.run({ command: 'iui', args: 'setup remove' } as any)
+ expect(ran.text).toContain('could not read /h/.zshrc')
+ expect(files['/h/.zshrc']).toBe(`${setupBlock('sh')}export A=1\n`)
+})
+
+test('a yes to the question does not write a start file whose read fails', async ($, on) => {
+ const files: Record<string, string> = { '/h/.zshrc': 'export A=1\n' }
+ const { asked, clock } = unreadable(on, files, 'Add the line')
+ await $.command.run({ command: 'iui', args: '' } as any)
+ await clock.settle()
+ // The file cannot be checked, so the question is not asked at all.
+ expect(asked.length).toBe(0)
+ expect(files['/h/.zshrc']).toBe('export A=1\n')
+})
++
+ // ---- herdr ------------------------------------------------------------------------
+
+ // A herdr pane (in no known terminal) with the engine's pictures off.
+ const HERDR = { TERM_PROGRAM: 'herdr', TERM_PROGRAM_VERSION: '0.9.5', HERDR_ENV: '1', TERM: 'xterm-256color', ITERM_PROFILE: '' }
+
+ test('in herdr with pictures off, the plugin asks once and adds the block on yes; the texts name herdr panes', async ($, on) => {
+ const files: Record<string, string> = { '/h/.zshrc': 'export A=1\n' }
+ const { asked, clock, toasts, logs } = iterm(on, files, 'Add the line', { env: HERDR })
+ const shown = await $.command.run({ command: 'iui', args: '' } as any)
+ expect(shown.text).toContain('In herdr, run /iui setup once to show pictures.')
+ await clock.settle()
+ expect(asked.length).toBe(1)
+ expect(asked[0]).toContain('in herdr Claude Code needs CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1')
+ expect(asked[0]).toContain('Add one line to ~/.zshrc that sets it in iTerm2 and herdr only')
+ expect(files['/h/.zshrc']).toBe(`export A=1\n\n${setupBlock('sh')}`)
+ expect(toasts.filter(t => /pane|tab/.test(t))).toEqual(['Close this pane and open a new herdr pane to see pictures.'])
+ expect(logs.some(l => l.includes('Added the Intelligent UI block to /h/.zshrc. Close this pane, open a new herdr pane, and start Claude Code there'))).toBe(true)
+ const again = await $.command.run({ command: 'iui', args: 'setup' } as any)
+ expect(again.text).toBe('/h/.zshrc already has the Intelligent UI block. Close this pane, open a new herdr pane, and start Claude Code there to see pictures.')
+ const removed = await $.command.run({ command: 'iui', args: 'setup remove' } as any)
+ expect(removed.text).toBe('Removed the Intelligent UI block from /h/.zshrc. New herdr panes show answers as text.')
+ expect(files['/h/.zshrc']).toBe('export A=1\n')
+ })
+
+ test('in herdr, an old block (iTerm2 only) is not enough: the question asks to update it, and a yes replaces it', async ($, on) => {
+ const files: Record<string, string> = { '/h/.zshrc': `export A=1\n\n${OLD_SH}` }
+ const { asked, clock, toasts, logs } = iterm(on, files, 'Update the line', { env: HERDR })
+ await $.command.run({ command: 'iui', args: '' } as any)
+ await clock.settle()
+ expect(asked.length).toBe(1)
+ expect(asked[0]).toContain('Update the Intelligent UI line in ~/.zshrc so that it sets it in herdr too')
+ expect(files['/h/.zshrc']).toBe(`export A=1\n\n${setupBlock('sh')}`)
+ expect(toasts.filter(t => /pane|tab/.test(t))).toEqual(['Close this pane and open a new herdr pane to see pictures.'])
+ expect(logs.some(l => l.startsWith('Updated the Intelligent UI block in /h/.zshrc. Close this pane'))).toBe(true)
+ })
+
+ test('in herdr with the new block already there, no question', async ($, on) => {
+ const files: Record<string, string> = { '/h/.zshrc': withSetup('export A=1\n', 'sh') }
+ const { asked, clock } = iterm(on, files, 'Add the line', { env: HERDR })
+ await $.command.run({ command: 'iui', args: '' } as any)
+ await clock.settle()
+ expect(asked).toEqual([])
+ })
+
+ test('in iTerm2, an old block is enough (no question); /iui setup updates it', async ($, on) => {
+ const files: Record<string, string> = { '/h/.zshrc': OLD_SH }
+ const { asked, clock } = iterm(on, files, 'Add the line')
+ await $.command.run({ command: 'iui', args: '' } as any)
+ await clock.settle()
+ expect(asked).toEqual([])
+ expect(files['/h/.zshrc']).toBe(OLD_SH)
+ const ran = await $.command.run({ command: 'iui', args: 'setup' } as any)
+ expect(ran.text).toBe('Updated the Intelligent UI block in /h/.zshrc. Close this tab, open a new iTerm2 tab, and start Claude Code there to see pictures. Undo with /iui setup remove.')
+ expect(files['/h/.zshrc']).toBe(setupBlock('sh'))
+ })
+
+ test('in herdr on Linux, /iui setup writes the block to .bashrc for bash (herdr starts no login shell there)', async ($, on) => {
+ const files: Record<string, string> = { '/h/.bashrc': 'export A=1\n' }
+ const { asked, clock } = iterm(on, files, 'Not now', { os: 'Linux', env: { ...HERDR, SHELL: '/bin/bash' } })
+ const shown = await $.command.run({ command: 'iui', args: '' } as any)
+ expect(shown.text).toContain('In herdr, run /iui setup once to show pictures.')
+ await clock.settle()
+ expect(asked.length).toBe(1)
+ const ran = await $.command.run({ command: 'iui', args: 'setup' } as any)
+ expect(ran.text).toBe('Added the Intelligent UI block to /h/.bashrc. Close this pane, open a new herdr pane, and start Claude Code there to see pictures. Undo with /iui setup remove.')
+ expect(files['/h/.bashrc']).toBe(`export A=1\n\n${setupBlock('sh')}`)
+ })
+
+ test('herdr with pictures on (the variable set): no question, no setup line', async ($, on) => {
+ const files: Record<string, string> = { '/h/.zshrc': '' }
+ const { asked, clock } = iterm(on, files, 'Add the line', { env: { ...HERDR, CLAUDE_CODE_FORCE_TERMINAL_IMAGES: '1' } })
+ const shown = await $.command.run({ command: 'iui', args: '' } as any)
+ expect(shown.text).not.toContain('/iui setup once')
+ await clock.settle()
+ expect(asked).toEqual([])
+ })
+
+ test('herdr in iTerm2 (ITERM_PROFILE kept) asks the herdr question, never the iTerm2 one', async ($, on) => {
+ const files: Record<string, string> = { '/h/.zshrc': '' }
+ const { asked, clock } = iterm(on, files, 'Not now', { env: { ...HERDR, ITERM_PROFILE: 'Default' } })
+ const shown = await $.command.run({ command: 'iui', args: '' } as any)
+ expect(shown.text).toContain('In herdr, run /iui setup once')
+ await clock.settle()
+ expect(asked.length).toBe(1)
+ expect(asked[0]).toContain('in herdr Claude Code needs')
+ expect(asked[0]).not.toContain('in iTerm2 Claude Code needs')
+ })