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

herdr in iTerm2: pages and pictures stored with their row bands reversed

razorback166f2935b0e2a7
diff --git a/docs/development.md b/docs/development.md
index 9e532d6..4222347 100644
--- a/docs/development.md
+++ b/docs/development.md
@@ -37,7 +37,7 @@ Picture select writes trace lines that start with `select:`:
## 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`. 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`. 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 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 --git a/docs/how-it-works.md b/docs/how-it-works.md
index 9ce2438..7c86b61 100644
--- a/docs/how-it-works.md
+++ b/docs/how-it-works.md
@@ -92,6 +92,7 @@ In **herdr**, `TERM_PROGRAM` is `herdr`, so it does not name the terminal that h
- **Background:** herdr answers OSC 11 with the background of the terminal in front. In herdr, this is source 0, before the sources above. It also works with `herdr --remote`, where the mod runs on the remote computer. Claude Code reads some answers first. If no answer comes, Intelligent UI keeps the last answer until 3 checks in a row get no answer. Then it uses the sources above.
- **Terminal and font:** herdr runs a server, and one or more clients (`herdr`, `herdr --session <name>`, `herdr session attach <name>`) attach to it from terminals. Intelligent UI finds the herdr server above its own process. Then it lists the herdr clients of this user that have a tty (one `ps`). With more than one herdr server, it keeps only the clients that connect to its own server (`lsof`). It uses the client whose tty was read last (the access time of the tty changes when you type in that terminal). It reads the variables of that client (Linux: `/proc/<pid>/environ`; macOS: `ps eww`) and the terminal app above it (the nearest process with no tty). The terminal app comes first, then `TERM`, `TERM_PROGRAM` and the variables of each terminal. Intelligent UI then uses that terminal's sources above (with that client's `ITERM_PROFILE`, `KITTY_CONFIG_DIRECTORY`, `GHOSTTY_BIN_DIR`, `GHOSTTY_RESOURCES_DIR`, `RIO_CONFIG_HOME` and `COLORFGBG`) and its font for the text size. It checks the client every 3 s. When the terminal changes, it reads the font and the background again and draws the pictures again.
+- **iTerm2:** herdr runs a terminal of its own for each pane. It draws a picture of Claude Code (kitty placeholder cells) in the outer terminal as one kitty placement for each row, with a source rectangle: row k of a picture that is H pixels tall and R rows tall shows the source rows from floor(k × H / R), floor(H / R) rows tall. iTerm2 3.6 and 3.7 count the top of a source rectangle from the bottom of the image. When the client is iTerm2 (not with `herdr --remote`), Intelligent UI stores each picture with the band of each row at the rows that iTerm2 reads for that row (`hooks/lib/flip.ts`). Before this, a page is made exactly R × B pixels tall (B is a whole number), so the change is the reverse order of the bands. Pictures under rows are first made by Typst at their size in cells. The render key includes this mode, so a change of client draws new files.
- **Fallback:** if it finds no client, it uses the variables that herdr keeps of the terminal that started the herdr server: `CMUX_*` for cmux, `GHOSTTY_RESOURCES_DIR` or `GHOSTTY_BIN_DIR` for Ghostty, `KITTY_PID` or `KITTY_INSTALLATION_DIR` for kitty, `ITERM_PROFILE` for iTerm2. If it finds none, it uses `COLORFGBG`, then the OS appearance.
Intelligent UI checks every 3 s. After a change, each mode's pictures compile once. `/iui 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 uses OSC 11 only in herdr.
diff --git a/docs/install.md b/docs/install.md
index 213de1f..517d34f 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -13,10 +13,11 @@
- **kitty (0.28 or later), Ghostty and cmux (Ghostty inside, macOS only):** pictures work with no setting. kitty and Ghostty work on macOS and on Linux.
- **iTerm2 3.6 or later (3.7.5 tested, macOS only):** 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 and herdr only, not in tmux or screen. Then close the tab, open a new iTerm2 tab, and start Claude Code there. You can also run `/iui setup` (undo: `/iui setup remove`).
-- **herdr (0.9.5 tested, in Ghostty):** herdr is a terminal multiplexer. It draws the pictures of its panes in the terminal that it runs in, so that terminal must show kitty pictures (kitty or Ghostty). Claude Code needs `CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1` in herdr too. The first time the mod runs in a herdr pane, it asks to add the same line to your shell's start file. If the file has the line of an older version (iTerm2 only), the mod asks to update it. Then close the pane, open a new herdr pane, and start Claude Code there. You can also run `/iui setup` (undo: `/iui setup remove`). herdr works on macOS and on Linux.
+- **herdr (0.9.5 tested, in Ghostty and iTerm2):** herdr is a terminal multiplexer. It draws the pictures of its panes in the terminal that it runs in, so that terminal must show kitty pictures (kitty, Ghostty or iTerm2 3.6 or later). Claude Code needs `CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1` in herdr too. The first time the mod runs in a herdr pane, it asks to add the same line to your shell's start file. If the file has the line of an older version (iTerm2 only), the mod asks to update it. Then close the pane, open a new herdr pane, and start Claude Code there. You can also run `/iui setup` (undo: `/iui setup remove`). herdr works on macOS and on Linux.
- herdr hides the name of the terminal that it runs in. With the `auto` theme, the mod gets the background from herdr: herdr gives the background of the terminal in front. This also works with `herdr --remote`.
- For the font, the mod finds the herdr client where you typed last. You can attach to one herdr server from more than one terminal (for example Ghostty and kitty). The mod reads the variables and the terminal app of that client, then reads the font of that terminal. When you type in a different terminal, the mod finds it at the next check (every 3 s) and draws the pictures again with that font. If the mod cannot find a client, it uses the variables that herdr keeps of the terminal that started the herdr server (`GHOSTTY_RESOURCES_DIR` for Ghostty, `KITTY_PID` for kitty, `ITERM_PROFILE` for iTerm2). `/iui details` shows the terminal and how the mod found it, for example `herdr 0.9.5 (in kitty, the client you used last)` or `herdr 0.9.5 (in Ghostty, from the server's start)`.
- Pages are shorter in herdr, so that herdr can send each one to the terminal. Refer to [Limitations](limitations.md).
+ - In iTerm2, herdr sends each row of a picture as one part of the image, and iTerm2 counts the top of that part from the bottom of the image. Thus the rows would show in the opposite order. When the herdr client where you typed last is iTerm2, the mod keeps the rows of each page and each picture in an order that iTerm2 shows correctly. Picture select also works. When you type in a different terminal (for example Ghostty), the mod draws the pictures again in the usual order. `/iui details` then shows `pages and pictures stored upside down by rows`. With `herdr --remote` in iTerm2, the mod cannot find the client, so the rows of the pictures show in the wrong order. Refer to [Limitations](limitations.md).
- **Rio 0.5.27 or later (not tested):** set `CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1` before you start Claude Code. Rio works on macOS and on Linux.
- Do not put the variable in the `env` of `~/.claude/settings.json`. It then applies in every terminal, also where pictures cannot show.
- **Warp (not yet):** Warp does not draw kitty pictures with Unicode placeholders yet. The pull request [warpdotdev/warp#16312](https://github.com/warpdotdev/warp/pull/16312) adds them. The mod will support Warp when that pull request is merged.
diff --git a/docs/limitations.md b/docs/limitations.md
index 6d14b59..ec4039b 100644
--- a/docs/limitations.md
+++ b/docs/limitations.md
@@ -59,4 +59,9 @@
- **A picture that the terminal dropped from its image memory** (after many large pictures) is not sent again when you scroll back to it.
- **Over ssh**, the mod cannot read the terminal's config on your computer. So it uses the metrics of the theme's code font (Menlo on macOS) 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.
- **In herdr**, herdr does not send an image to the terminal if the image is too large for its transfer limit (30 MiB as base64, approximately 22 MiB as pixels: width × height × 4 bytes). It shows no image and no message. Thus the mod makes pages shorter in herdr, so that each page is at most 16 MiB as pixels. A pasted image, an image that Claude sends, a PDF page or a live Typst drawing larger than approximately 22 MiB as pixels (for example, 2900 × 2000 pixels) does not show in herdr. With the `auto` theme, the background comes from herdr (the terminal in front). Claude Code sometimes reads herdr's answer first; then the mod keeps the last background for up to 2 more checks, after which it uses the terminal's config. The font comes from the herdr client where you typed last. With two terminals attached, the mod follows the terminal where you typed last, not the terminal that you look at. A change shows after the next check (up to 3 s; on Linux, the tty times change only about every 8 s, so it can take up to approximately 11 s). With `herdr --remote`, the client is on a different computer, so the mod does not find it and uses no terminal font, as over ssh. If the mod cannot read the processes (`ps`), it uses the variables of the terminal that started the herdr server. With more than one herdr server (named sessions), the mod uses `lsof` to find the clients of its own server; on Linux, `lsof` does not show this, so the mod can use a client of a different session.
+- **herdr in iTerm2:** iTerm2 3.6 and 3.7 count the top of a part of an image (a kitty placement with a source rectangle) from the bottom of the image. herdr sends each row of a picture as such a part, so in iTerm2 the rows of a picture show in the opposite order. When the herdr client where you typed last is iTerm2, the mod stores each page and each picture with its rows moved, so that iTerm2 shows them in the correct order. The mod decodes and encodes each page again for this, so a page takes more time to show, and its file is larger. Picture select works. These items stay incorrect:
+ - With `herdr --remote`, the client is on a different computer, so the mod does not know that the terminal is iTerm2. The rows of the pictures show in the wrong order. Use Ghostty or kitty for `herdr --remote` with pictures.
+ - If the mod cannot find the herdr client (for example, it cannot read the processes), it does not move the rows. It does not use the variables of the terminal that started the herdr server for this.
+ - With iTerm2 and a different terminal attached at the same time, the order is correct only in the terminal where you typed last. After you type in the other terminal, the next check (up to 3 s) draws the pictures again for it.
+ - While the mod makes the new pictures after a change of terminal, an old picture can show with its rows in the wrong order for a short time. An old page that is wider than the screen (after you make the window narrower) also shows in the wrong order until its new page is ready.
- **`auto` theme** reads the iTerm2 profile, the Ghostty, kitty and Rio configs, and the cmux settings directly (in herdr, those of the terminal that herdr runs in). 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 (on Linux, the desktop portal or GNOME's setting). If you change the theme of such a terminal and the OS appearance does not change, Intelligent UI does not see it. A change shows after up to 3 s.
diff --git a/hooks/lib/answer.ts b/hooks/lib/answer.ts
index 55f1c20..7db24f9 100644
--- a/hooks/lib/answer.ts
+++ b/hooks/lib/answer.ts
@@ -10,6 +10,7 @@ import { epochOpen, fauxBoldOf, finalized, keep, lastKey, lastText, live, pendin
import { fontFit, hashOf, inlineOf, renderKey, sizing } from './draw'
import { needsRoom } from './markdown'
import { pictureColumns } from './frame'
+import { isFlipHere } from './terminal'
import { pictureRowsFor } from './images'
import { designInMemory, designKey, loadDesign } from './designs'
import { resultOf, touchLater } from './typst'
@@ -105,16 +106,17 @@ export async function pagesOf($: EngineInterface, o: PagesInput): Promise<Drawin
return o.canStream && (live.has(id) || (seen !== text && !finalized.has(id) && (S.stepsLive > 0 || seen !== undefined)))
}
const room = await roomOf($, { hasRoom, textHash, base, env, rows, widthPt, rowPt, isLive: liveNow() })
+ const flip = isFlipHere(env)
const key = renderKey({
textHash, columns, cell, size: S.size, mode: S.theme, termFont: env.termFont,
- columnPt, templateStamp: env.stamp, look: active, inline: env.inline, herdr: env.herdr, base, room, grid: S.grid, fauxBold: fauxBoldOf(env.metrics),
+ columnPt, templateStamp: env.stamp, look: active, inline: env.inline, herdr: env.herdr, flip, base, room, grid: S.grid, fauxBold: fauxBoldOf(env.metrics),
})
const seen = lastText.get(id)
const changed = seen !== text
lastText.set(id, text)
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 --git a/hooks/lib/blit.ts b/hooks/lib/blit.ts
index b6520fb..5d61e79 100644
--- a/hooks/lib/blit.ts
+++ b/hooks/lib/blit.ts
@@ -22,6 +22,7 @@ import { forgetPages, holdPages, keyOf, needFrames } from './pagecache'
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'
@@ -70,9 +71,8 @@ export const FRAME_MS = 16
const FILES_KEPT = 4
const FILE_KEEP_MS = 2000
-// Writes stdin's base64 to the file (its folder made, a temporary name,
-// then renamed), and deletes the older frames named after it.
-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)'
+// The perl that writes a frame (flip.ts: it writes the PNGs of flip mode too).
+export { WRITE_PL } from './flip'
// Each drawing's site (the requestId its Images are drawn under) and its
// Images' key prefix, noted by drawPages; what each page shows now (sigOf,
diff --git a/hooks/lib/copy.ts b/hooks/lib/copy.ts
index 9d6b94e..481fd14 100644
--- a/hooks/lib/copy.ts
+++ b/hooks/lib/copy.ts
@@ -251,8 +251,9 @@ export function positionsOf(marks: readonly Mark[], ppi: number): Positions {
// A page drawn this session: its PNG size and the box its Image takes as
// drawn (fitBox: an old page in an open epoch draws smaller than it was
-// compiled for). The placeholders count the cells of that box.
-export type DrawnPage = { file: string; width: number; height: number; columns: number; rows: number }
+// compiled for). The placeholders count the cells of that box. `flip`: its
+// file is stored for flip mode (flip.ts).
+export type DrawnPage = { file: string; width: number; height: number; columns: number; rows: number; flip?: boolean }
// The rows of a drawing's transcript message on screen at its last draw
// (e.props.onScreen on the terminal): rows `first` to `last` of its `of`,
// from the first row of the tree the hook drew.
diff --git a/hooks/lib/draw.tsx b/hooks/lib/draw.tsx
index 135a7de..a9a83f8 100644
--- a/hooks/lib/draw.tsx
+++ b/hooks/lib/draw.tsx
@@ -71,6 +71,8 @@ export function renderKey(o: {
inline?: boolean
// Under herdr: pages are cut shorter too (herdrBudget).
herdr?: boolean
+ // Flip mode (herdr in iTerm2): pages stored with their bands moved (flip.ts).
+ flip?: boolean
// The folder relative images start from, when it is not the session's (a
// Markdown file's): the same text there shows other images.
base?: string
@@ -88,6 +90,7 @@ export function renderKey(o: {
return hashOf([
o.textHash, o.columns, o.cell.width, o.cell.height, o.size, o.mode, o.termFont, o.columnPt,
o.templateStamp, o.look.name, o.look.dir, o.look.stamp, TEMPLATE_VERSION, ...(o.inline ? ['inline'] : []), ...(o.herdr ? ['herdr'] : []),
+ ...(o.flip ? ['flip'] : []),
...(o.base ? ['base', o.base] : []),
...(room ? ['room', room.heightPt, room.design.widthPt, room.design.heightPt] : []),
...(o.grid ? ['grid', GRID_VERSION] : []),
diff --git a/hooks/lib/flip.ts b/hooks/lib/flip.ts
new file mode 100644
index 0000000..b3d2606
--- /dev/null
+++ b/hooks/lib/flip.ts
@@ -0,0 +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'
+
+// 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))
+ 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 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) })
+ return ran.exitCode === 0 ? { width: made.width, height: made.height } : null
+ } catch {
+ return null
+ }
+}
diff --git a/hooks/lib/frames.ts b/hooks/lib/frames.ts
index f1b2c9a..a86a15c 100644
--- a/hooks/lib/frames.ts
+++ b/hooks/lib/frames.ts
@@ -5,6 +5,7 @@
import type { IuiTheme } from '../../types'
import { chunk, concat, decodeSteps, deflatePiece, headOf, tailOf, type Piece, type Rgba } from './png'
import type { SelRow } from './select'
+import { reverseBands } from './flip'
export type Rgb = readonly [number, number, number]
@@ -51,8 +52,10 @@ const chunked = (raw: Uint8Array, line: number): Chunked => {
}
// A decoded page ready for frames: its pixels, the cells' pixel edges, the
-// plain row pieces, and the tinted ones made so far.
-export type Frames = { img: Rgba; xs: number[]; ys: number[]; color: Rgb; head: Uint8Array; plain: Chunked[]; tint: (Chunked | undefined)[] }
+// plain row pieces, and the tinted ones made so far. `flip`: a page stored
+// for flip mode (flip.ts): its pixels are in order, its frames' row pieces go
+// in reverse order.
+export type Frames = { img: Rgba; xs: number[]; ys: number[]; color: Rgb; head: Uint8Array; plain: Chunked[]; tint: (Chunked | undefined)[]; flip?: boolean }
export function framesOf(img: Rgba, box: { columns: number; rows: number }, color: Rgb): Frames {
const steps = framesFrom(img, box, color)
@@ -65,9 +68,12 @@ export function framesOf(img: Rgba, box: { columns: number; rows: number }, colo
// The same Frames from a PNG's bytes, in steps: the decode's (decodeSteps),
// then a yield after each plain row piece. The Frames are yielded once they
// can make frames; the steps after it make the tinted piece of each row.
-export function* framesSteps(png: Uint8Array, box: { columns: number; rows: number }, color: Rgb): Generator<Frames | undefined, Frames, void> {
+// `box.flip`: the PNG is stored for flip mode, so its bands are put back in
+// order first (a page drawn at another box keeps them: no frames fit it).
+export function* framesSteps(png: Uint8Array, box: { columns: number; rows: number; flip?: boolean }, color: Rgb): Generator<Frames | undefined, Frames, void> {
const img = yield* decodeSteps(png)
- const f = yield* framesFrom(img, box, color)
+ const flip = !!box.flip && reverseBands(img, box.rows)
+ const f = yield* framesFrom(img, box, color, flip)
yield f
const line = img.width * 4 + 1
for (let r = 0; r < box.rows; r++) {
@@ -77,7 +83,7 @@ export function* framesSteps(png: Uint8Array, box: { columns: number; rows: numb
return f
}
-function* framesFrom(img: Rgba, box: { columns: number; rows: number }, color: Rgb): Generator<undefined, Frames, void> {
+function* framesFrom(img: Rgba, box: { columns: number; rows: number }, color: Rgb, flip = false): Generator<undefined, Frames, void> {
const xs = edgesOf(img.width, box.columns)
const ys = edgesOf(img.height, box.rows)
const line = img.width * 4 + 1
@@ -86,7 +92,7 @@ function* framesFrom(img: Rgba, box: { columns: number; rows: number }, color: R
plain.push(chunked(bandOf(img, ys[r]!, ys[r + 1]!, 0, 0, color), line))
yield
}
- return { img, xs, ys, color, head: headOf(img.width, img.height), plain, tint: [] }
+ return { img, xs, ys, color, head: headOf(img.width, img.height), plain, tint: [], ...(flip ? { flip } : {}) }
}
// The bytes a page's Frames hold (the pixels and the pieces).
@@ -126,6 +132,7 @@ export function frameNow(f: Frames, rows: readonly SelRow[], budgetMs = TINT_MS,
}
return chunked(bandOf(f.img, y0, y1, f.xs[Math.max(0, sel.x0)]!, f.xs[Math.min(columns, sel.x1 + 1)]!, f.color), line)
})
+ if (f.flip) parts.reverse()
return { png: concat([f.head, ...parts.map(p => p.chunk), tailOf(parts.map(p => p.piece))]), isWhole }
}
diff --git a/hooks/lib/host.ts b/hooks/lib/host.ts
index 0943416..e83ee00 100644
--- a/hooks/lib/host.ts
+++ b/hooks/lib/host.ts
@@ -16,7 +16,7 @@ import {
rioConfigDirOf, RIO_DEFAULT_FONT, RIO_OLD_FONT, rioFontOf, rioForcedOf, rioThemeNamesOf, rioThemePath, tomlStringsOf, type CmuxAppearance, type KittyEntries,
} from './terminals'
import { firstLine } from './markdown'
-import { herdrClientChanged, herdrClientOf, herdrHostOf, isCmuxIn, isGhosttyHere, isGhosttyIn, isKittyIn, isRioIn, type OuterName } from './terminal'
+import { herdrClientChanged, herdrClientOf, herdrHostOf, isCmuxIn, isFlipHere, isGhosttyHere, isGhosttyIn, isKittyIn, isRioIn, type OuterName } from './terminal'
import { refont } from './frame'
import { clockEvery, envGet, fsExists, fsRead, processRun } from './api'
@@ -692,11 +692,13 @@ async function readLinuxScheme($: EngineInterface): Promise<LinuxScheme | null>
// One poll (never two at once): under herdr the client first (another
// terminal sets the terminal values again, then the font and its metrics
-// are read again), then with auto the mode. A changed mode or font redraws.
+// are read again), then with auto the mode. A changed mode, font or flip
+// mode (isFlipHere: iTerm2 in or out) redraws.
export async function pollHost($: EngineInterface) {
if (S.checking || (S.setting !== 'auto' && !S.isHerdr)) return
S.checking = true
let refonted = false
+ const flipWas = isFlipHere()
try {
const moved = S.isHerdr && (await readHerdrClient($).catch(() => false))
if (moved) await setOuter($)
@@ -705,7 +707,7 @@ export async function pollHost($: EngineInterface) {
} finally {
S.checking = false
}
- if (!refonted) return showMode($)
+ if (!refonted && isFlipHere() === flipWas) return showMode($)
S.theme = resolveMode(S.setting, S.host)
beginEpoch($)
}
diff --git a/hooks/lib/pictures.tsx b/hooks/lib/pictures.tsx
index 842bb6e..3b5c2ed 100644
--- a/hooks/lib/pictures.tsx
+++ b/hooks/lib/pictures.tsx
@@ -11,7 +11,7 @@ import {
type Env,
} from './state'
import { jobDone } from './epoch'
-import { fitBox, fitsInline, INLINE_MAX_BYTES, roomColumns } from './terminal'
+import { fitBox, fitsInline, INLINE_MAX_BYTES, isFlipHere, roomColumns } from './terminal'
import {
convertBox, convertedPath, factsAfter, folderOf, isNoPageError, lastKnownPage, NO_FACTS, onScreenOf, pageControls, pageOf, parsePage, pasteDirOf, pictureCells,
pictureRowsFor, type PdfFacts, type PixelBox, type SentFile,
@@ -19,8 +19,9 @@ 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'
@@ -105,11 +106,14 @@ export async function pictureBytes($: EngineInterface, p: Picture): Promise<stri
}
// The Images for the files that are PNGs, sized to the Frame on screen.
-// `at`: as statOf.
+// `at`: as statOf. In flip mode each is first a PNG Typst makes at its box
+// (8-bit RGBA, no larger than drawn), which shownOne stores flipped.
export async function shownOf($: EngineInterface, e: RowInput, ready: Env, files: readonly string[], at?: StatAt): Promise<Shown[]> {
const shown: Shown[] = []
+ const box = isFlipHere(ready) ? boxOf(shownFor(e.viewport), ready.inline, S.shownHeight) : null
for (const file of new Set(files)) {
- const s = await shownOne($, e, ready, file, nameOf(file), at)
+ const png = box ? ((await convertedOf($, ready, file, box, at)) ?? file) : file
+ const s = png ? await shownOne($, e, ready, png, nameOf(file), at) : null
if (s) shown.push(s)
}
return shown
@@ -119,7 +123,8 @@ export async function shownOf($: EngineInterface, e: RowInput, ready: Env, files
// (shownFor, S.shownHeight: a new size shows when its epoch commits, with
// every other picture), and at most as wide as the room now; null when it is not a PNG. `alt` is the file's name
// (the name of the file it was made of). Its generation follows the file's
-// stat alone: a new box is not a new file.
+// stat alone: a new box is not a new file. In flip mode it draws the PNG
+// stored for its rows (flippedOf); null when that fails.
export async function shownOne($: EngineInterface, e: RowInput, ready: Env, file: string, alt = nameOf(file), at?: StatAt): Promise<Shown | null> {
const p = await pictureOf($, file, at)
if (!p) return null
@@ -129,10 +134,37 @@ export async function shownOne($: EngineInterface, e: RowInput, ready: Env, file
const png = await pictureBytes($, p)
return png ? { source: { png }, ...fit, alt } : null
}
+ if (isFlipHere(ready)) {
+ const flipped = await flippedOf($, ready, p, fit.rows)
+ if (!flipped) return null
+ return { source: { file: flipped, format: 'png', generation: Number.parseInt(hashOf([p.stamp, fit.rows]).slice(0, 8), 16) }, ...fit, alt }
+ }
const generation = Number.parseInt(hashOf([p.stamp]).slice(0, 8), 16)
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)
+ 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
@@ -271,6 +303,8 @@ export async function sentOf(
const target = epochOpen() ? frameFor(e.viewport) : null
const box = boxOf(shown, o.ready.inline, S.shownHeight)
const next = target ? boxOf(target, o.ready.inline, S.height) : null
+ // Flip mode: a PNG too is made by Typst at its box first (as shownOf).
+ const flip = isFlipHere(o.ready)
const under: Under[] = []
for (const f of o.files) {
const full = imagePathOf(f.path, o.ready.cwd)
@@ -291,11 +325,11 @@ export async function sentOf(
if (u) under.push(u)
continue
}
- if (f.kind !== 'png' && next && (next.width !== box.width || next.height !== box.height)) {
+ if ((f.kind !== 'png' || flip) && next && (next.width !== box.width || next.height !== box.height)) {
void convertedOf($, o.ready, full, next, o.at).catch(() => null)
if (!(await hasPngOf($, full, o.at))) continue
}
- const png = f.kind === 'png' ? full : await convertedOf($, o.ready, full, box, o.at)
+ const png = f.kind === 'png' && !flip ? full : ((await convertedOf($, o.ready, full, box, o.at)) ?? (f.kind === 'png' ? full : null))
const picture = png ? await shownOne($, e, o.ready, png, nameOf(full), o.at) : null
if (picture) under.push(picture)
}
diff --git a/hooks/lib/probe.ts b/hooks/lib/probe.ts
index cda4824..451c0d4 100644
--- a/hooks/lib/probe.ts
+++ b/hooks/lib/probe.ts
@@ -21,7 +21,7 @@ import type { ShownLink } from './draw'
// rows above the pages in their message when the layout says (`top`), and
// the rows drawn under them besides a Typst error line (`after`); see Place.
export function noteDrawn(id: string, result: Result, room: number, at: { top?: number; after?: number } = {}) {
- const pages: DrawnPage[] = result.pages.map(p => ({ file: p.file, width: p.width, height: p.height, ...fitBox(p, room) }))
+ const pages: DrawnPage[] = result.pages.map(p => ({ file: p.file, width: p.width, height: p.height, ...fitBox(p, room), ...(p.flip ? { flip: true } : {}) }))
const dir = result.pages[0]?.file.replace(/\/[^/]*$/, '') ?? ''
const was = drawnAnswers.get(id)
const same = (p: DrawnPage, i: number) => {
diff --git a/hooks/lib/state.ts b/hooks/lib/state.ts
index e10b73f..67f8f95 100644
--- a/hooks/lib/state.ts
+++ b/hooks/lib/state.ts
@@ -75,8 +75,8 @@ export type Env = {
designs: string
}
// `columns` and `rows`: the cell box the page was compiled for (it is drawn
-// at that box, never stretched).
-export type Page = { file: string; width: number; height: number; alt: string; columns: number; rows: number }
+// at that box, never stretched). `flip`: stored for flip mode (flip.ts).
+export type Page = { file: string; width: number; height: number; alt: string; columns: number; rows: number; flip?: boolean }
export type Result = { pages: Page[]; bulletRow: number; note?: string }
export type Job = {
key: string
@@ -94,6 +94,8 @@ export type Job = {
base?: string
// The room for its drawings (a text with a live Typst block or a local image).
room?: Room
+ // Flip mode (herdr in iTerm2): its pages are stored flipped (flip.ts).
+ flip?: boolean
// The epoch (S.epoch) it was enqueued in: only the open epoch's jobs hold
// its commit (set by enqueue).
epoch: number
diff --git a/hooks/lib/terminal.ts b/hooks/lib/terminal.ts
index 1c77595..a86d2a4 100644
--- a/hooks/lib/terminal.ts
+++ b/hooks/lib/terminal.ts
@@ -164,13 +164,19 @@ export function herdrClientOf(stdout: string): HerdrClient | null {
export const herdrClientKey = (c: HerdrClient | null) => (c ? JSON.stringify([c.kind, ...OUTER_NAMES.map(name => c.env[name] ?? '')]) : '')
export const herdrClientChanged = (was: HerdrClient | null, now: HerdrClient | null) => herdrClientKey(was) !== herdrClientKey(now)
+// Flip mode (flip.ts): herdr, not over ssh, and the client the user typed in
+// last is iTerm2. A remote herdr pane (`herdr --remote`) finds no client.
+export const flipOf = (o: { herdr?: boolean; inline: boolean; client: HerdrClient | null }) => !!o.herdr && !o.inline && o.client?.kind === 'iterm'
+export const isFlipHere = (env: { herdr?: boolean; inline: boolean } | null = S.env) => !!env && flipOf({ herdr: env.herdr, inline: env.inline, client: S.herdrClient })
+
const HERDR_HOSTS = { ghostty: 'Ghostty', cmux: 'cmux', kitty: 'kitty', iterm: 'iTerm2', rio: 'Rio' } as const
// herdr in /iui details, and where its terminal came from: the client
-// typed in last, or the server's variables (the fallback).
+// typed in last, or the server's variables (the fallback); `flip`: flip mode is on.
export type HerdrFrom = 'client' | 'server'
-export const herdrText = (version: string, host: HerdrHost, from: HerdrFrom = 'server') =>
+export const FLIP_TEXT = "pages and pictures stored upside down by rows, for iTerm2's placement bug"
+export const herdrText = (version: string, host: HerdrHost, from: HerdrFrom = 'server', flip = false) =>
`herdr${version ? ` ${version}` : ''} (${
- host ? `in ${HERDR_HOSTS[host]}, ${from === 'client' ? 'the client you used last' : "from the server's start"}` : 'outer terminal not known'
+ host ? `in ${HERDR_HOSTS[host]}, ${from === 'client' ? 'the client you used last' : "from the server's start"}${flip ? `; ${FLIP_TEXT}` : ''}` : 'outer terminal not known'
})`
// Whether /iui setup can turn pictures on: they are off, and this is iTerm2
diff --git a/hooks/lib/typst.ts b/hooks/lib/typst.ts
index 968d4cd..8478bff 100644
--- a/hooks/lib/typst.ts
+++ b/hooks/lib/typst.ts
@@ -8,10 +8,11 @@ import { firstLine, imagePathOf, localImages, plainOf, splitInTwo, splitSegments
import { segmentBudget } from './terminal'
import { fontFit, placeFirstLine, sizing } from './draw'
import { DEFAULT_GRID, gridOf } from './grid'
-import { HEADERS_SH } from './host'
+import { HEADERS_SH, perlFor } from './host'
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'
// The typst command and its environment. Network off (see NO_NETWORK) and a
@@ -512,8 +513,30 @@ export async function compile($: EngineInterface, job: Job, signal?: AbortSignal
}
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))
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 --git a/hooks/register.tsx b/hooks/register.tsx
index d46342b..e298bf2 100644
--- a/hooks/register.tsx
+++ b/hooks/register.tsx
@@ -48,7 +48,7 @@ import { pagesOf, type Drawing } from './lib/answer'
import { clipboardNow, clipWatchArgs, clipWayReady, hintText } from './lib/clipboard'
import { setUp } from './lib/env'
import { frameFor, noteView, stopWatch, watchFrame, watchState } from './lib/frame'
-import { herdrText, 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'
@@ -827,8 +827,8 @@ export const register: Register = on => {
: S.isHerdr && S.setupNeeded
? 'Claude Code draws no pictures in herdr until CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1 is set when it starts (run /iui setup), so answers stay text'
: 'Claude Code draws no pictures here (it does in kitty and Ghostty, in iTerm2 3.6+, Rio 0.5.27+ and herdr 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'
- // In herdr: its version, the terminal it runs in and where that came from.
- const herdr = S.isHerdr ? `terminal ${herdrText(S.herdrVersion, S.herdrHost, S.herdrClient ? 'client' : 'server')}: ` : ''
+ // In herdr: its version, the terminal it runs in and where that came from (and flip mode).
+ const herdr = S.isHerdr ? `terminal ${herdrText(S.herdrVersion, S.herdrHost, S.herdrClient ? 'client' : 'server', isFlipHere(ready))}: ` : ''
await clipWayReady()
const auto = `Picture select: ${selectState()}\n/iui grab hint: ${hintOf(state === 'on')}`
const updates = `Update checks: ${updateLine(await updateState($))}`
diff --git a/render/convert.typ b/render/convert.typ
index bfe3ffe..18a46d2 100644
--- a/render/convert.typ
+++ b/render/convert.typ
@@ -1,5 +1,6 @@
// Intelligent UI: makes a PNG of a JPEG, WebP or SVG, or of one page of a
-// PDF (the engine's Image draws PNG only). Compiled at 72 ppi, where 1 pt
+// PDF (the engine's Image draws PNG only); in herdr in iTerm2 of a PNG too
+// (an 8-bit RGBA PNG at its box). Compiled at 72 ppi, where 1 pt
// is 1 pixel.
//
// Inputs: f = the image's absolute path (with --root /); maxw, maxh = the
@@ -19,6 +20,7 @@
#let be16(i) = at(i) * 256 + at(i + 1)
#let le16(i) = at(i) + at(i + 1) * 256
#let le24(i) = le16(i) + at(i + 2) * 65536
+#let be32(i) = be16(i) * 65536 + be16(i + 2)
#let has-tag(i, tag) = data.len() >= i + tag.len() and data.slice(i, i + tag.len()) == bytes(tag)
// A JPEG's (width, height): from the first SOF marker.
@@ -46,7 +48,7 @@
#let svg = lower(f).ends-with(".svg")
#let pdf = has-tag(0, "%PDF-") or lower(f).ends-with(".pdf")
-#let size = if has-tag(0, "RIFF") and has-tag(8, "WEBP") { webp-size() } else if at(0) == 0xff and at(1) == 0xd8 { jpeg-size() }
+#let size = if has-tag(0, "RIFF") and has-tag(8, "WEBP") { webp-size() } else if at(0) == 0xff and at(1) == 0xd8 { jpeg-size() } else if has-tag(1, "PNG") and has-tag(12, "IHDR") { (be32(16), be32(20)) }
// A PDF page is vector: its size in pt is its size in pixels, and it fits
// the box, the aspect kept (it can be made larger).
diff --git a/tests/flip.test.ts b/tests/flip.test.ts
new file mode 100644
index 0000000..7302f08
--- /dev/null
+++ b/tests/flip.test.ts
@@ -0,0 +1,206 @@
+import { expect, test } from 'claude-code/testing'
+
+import { encodeSteps, flipPng, flipRows, herdrBand, itermRowOf, padRows, reverseBands, WRITE_PL } from '../hooks/lib/flip'
+import { frameOf, framesOf, framesSteps, rgbOf } from '../hooks/lib/frames'
+import { decodePng, fromBase64, toBase64, type Rgba } from '../hooks/lib/png'
+import { compile, forgetTouches } from '../hooks/lib/typst'
+import { DEFAULT_METRICS, type Env, type Job } from '../hooks/lib/state'
+import { flipOf, herdrText, renderKey, type HerdrClient } from '../hooks/register'
+
+// A picture whose pixel at (x, y) tells its row: R = y, G = y >> 8, B = x, A = 255 - (y & 15).
+const imageOf = (width: number, height: number): Rgba => {
+ const data = new Uint8Array(width * height * 4)
+ for (let y = 0; y < height; y++) for (let x = 0; x < width; x++) data.set([y & 255, y >> 8, x & 255, 255 - (y & 15)], (y * width + x) * 4)
+ return { width, height, data }
+}
+const rowOf = (img: Rgba, y: number) => [...img.data.subarray(y * img.width * 4, (y + 1) * img.width * 4)]
+const encode = (img: Rgba) => {
+ const steps = encodeSteps(img)
+ for (;;) {
+ const got = steps.next()
+ if (got.done) return got.value
+ }
+}
+
+// What herdr in iTerm2 shows on row k: the source rect herdr sends, read from the bottom.
+const shownRows = (stored: Rgba, k: number, rows: number) => {
+ const { y, h } = herdrBand(k, stored.height, rows)
+ const at = itermRowOf(y, h, stored.height)
+ return Array.from({ length: h }, (_, i) => rowOf(stored, at + i))
+}
+// What a right terminal (Ghostty, kitty) shows on row k of the picture as it is.
+const rightRows = (img: Rgba, k: number, rows: number) => {
+ const { y, h } = herdrBand(k, img.height, rows)
+ return Array.from({ length: h }, (_, i) => rowOf(img, y + i))
+}
+
+test("herdr's band of each row: y = floor(k·H/R), h = floor(H/R), at least 1, at most to the bottom", () => {
+ expect([0, 1, 2, 3].map(k => herdrBand(k, 320, 4))).toEqual([{ y: 0, h: 80 }, { y: 80, h: 80 }, { y: 160, h: 80 }, { y: 240, h: 80 }])
+ expect([0, 1, 2, 3].map(k => herdrBand(k, 95, 4))).toEqual([{ y: 0, h: 23 }, { y: 23, h: 23 }, { y: 47, h: 23 }, { y: 71, h: 23 }])
+ expect([0, 1, 2, 3, 4].map(k => herdrBand(k, 3, 5))).toEqual([{ y: 0, h: 1 }, { y: 0, h: 1 }, { y: 1, h: 1 }, { y: 1, h: 1 }, { y: 2, h: 1 }])
+})
+
+test('iTerm2 reads a source rect from the bottom: the 800 x 320 test of 4 bands shows ROW 4 for y=0 and ROW 1 for y=240', () => {
+ expect(itermRowOf(0, 80, 320)).toBe(240)
+ expect(itermRowOf(240, 80, 320)).toBe(0)
+})
+
+test('a picture stored with flipRows shows each row right in herdr in iTerm2, for any height and rows', () => {
+ for (const [height, rows] of [[320, 4], [97, 7], [95, 4], [100, 1], [3, 5], [61, 60], [34 * 12 + 1, 12], [34 * 12 - 1, 12]] as const) {
+ const img = imageOf(3, height)
+ const stored = flipRows(img, rows)
+ for (let k = 0; k < rows; k++) expect(shownRows(stored, k, rows)).toEqual(rightRows(img, k, rows))
+ }
+})
+
+test('padRows makes a picture rows × B tall (B = round(H / R)): rows cut, or the last one repeated', () => {
+ const tall = padRows(imageOf(2, 37), 4)
+ expect(tall.height).toBe(36)
+ expect(rowOf(tall, 35)).toEqual(rowOf(imageOf(2, 37), 35))
+ const short = padRows(imageOf(2, 35), 4)
+ expect(short.height).toBe(36)
+ expect(rowOf(short, 35)).toEqual(rowOf(short, 34))
+ expect(rowOf(short, 34)).toEqual(rowOf(imageOf(2, 35), 34))
+ const same = imageOf(2, 36)
+ expect(padRows(same, 4)).toBe(same)
+ expect(padRows(imageOf(2, 1), 3).height).toBe(3)
+})
+
+test('for a page rows × B tall, flipRows reverses the bands, and reverseBands is that move and its own inverse', () => {
+ const img = imageOf(4, 5 * 7)
+ const flipped = flipRows(img, 5)
+ const reversed = { ...img, data: img.data.slice() }
+ expect(reverseBands(reversed, 5)).toBe(true)
+ expect([...reversed.data]).toEqual([...flipped.data])
+ for (let y = 0; y < 7; y++) expect(rowOf(flipped, y)).toEqual(rowOf(img, 4 * 7 + y))
+ expect(reverseBands(reversed, 5)).toBe(true)
+ expect([...reversed.data]).toEqual([...img.data])
+ expect(reverseBands({ ...img, data: img.data.slice() }, 4)).toBe(false)
+})
+
+test('flipPng: a page is padded then flipped; a picture keeps its height; both decode to the moved rows', () => {
+ const img = imageOf(5, 41)
+ const page = flipPng(encode(img), 4, true)
+ expect([page.width, page.height]).toEqual([5, 40])
+ expect([...decodePng(page.png).data]).toEqual([...flipRows(padRows(img, 4), 4).data])
+ const picture = flipPng(encode(img), 6, false)
+ expect(picture.height).toBe(41)
+ expect([...decodePng(picture.png).data]).toEqual([...flipRows(img, 6).data])
+})
+
+test('picture select on a flipped page: the frames read its rows in order, and a frame is stored flipped as the page is', () => {
+ const img = padRows(imageOf(6, 3 * 10), 3)
+ const box = { columns: 3, rows: 3 }
+ const color = rgbOf('#264f78')
+ const steps = framesSteps(flipPng(encode(img), 3, true).png, { ...box, flip: true }, color)
+ let got = steps.next()
+ while (!got.done) got = steps.next()
+ const f = got.value
+ expect(f.flip).toBe(true)
+ // The pixels as on the page, so the words' places and the tint stay in page coordinates.
+ expect([...f.img.data]).toEqual([...img.data])
+ const sel = [{ row: 0, x0: 1, x1: 2 }, { row: 2, x0: 0, x1: 2 }]
+ const plain = decodePng(frameOf(framesOf(img, box, color), sel))
+ expect([...decodePng(frameOf(f, sel)).data]).toEqual([...flipRows(plain, 3).data])
+ // A page not stored flipped draws its frames in order.
+ expect(framesOf(img, box, color).flip).toBeUndefined()
+})
+
+const client = (kind: HerdrClient['kind']): HerdrClient => ({ pid: 1, atime: 0, tty: '/dev/ttys001', cmd: 'herdr', app: '', env: {}, kind })
+
+test('flip mode: herdr, not over ssh, and the client typed in last is iTerm2', () => {
+ expect(flipOf({ herdr: true, inline: false, client: client('iterm') })).toBe(true)
+ expect(flipOf({ herdr: true, inline: false, client: client('ghostty') })).toBe(false)
+ expect(flipOf({ herdr: true, inline: false, client: client('kitty') })).toBe(false)
+ // herdr --remote: over ssh, and no client is found.
+ expect(flipOf({ herdr: true, inline: true, client: client('iterm') })).toBe(false)
+ expect(flipOf({ herdr: true, inline: false, client: null })).toBe(false)
+ expect(flipOf({ herdr: false, inline: false, client: client('iterm') })).toBe(false)
+ expect(flipOf({ inline: false, client: client('iterm') })).toBe(false)
+})
+
+test('/iui details names flip mode in the herdr part', () => {
+ expect(herdrText('0.9.5', 'iterm', 'client', true)).toBe("herdr 0.9.5 (in iTerm2, the client you used last; pages and pictures stored upside down by rows, for iTerm2's placement bug)")
+ expect(herdrText('0.9.5', 'iterm', 'client')).toBe('herdr 0.9.5 (in iTerm2, the client you used last)')
+})
+
+test('the render key has the flip mode: iTerm2 and Ghostty under herdr draw other files', () => {
+ const o = {
+ textHash: 'abc', columns: 80, cell: { width: 16, height: 34 }, size: 100, mode: 'dark' as const, termFont: 'Menlo', columnPt: 7,
+ templateStamp: 's', look: { name: 'vscode', dir: '/t', stamp: '1' }, herdr: true,
+ }
+ expect(renderKey({ ...o, flip: false })).toBe(renderKey(o))
+ expect(renderKey({ ...o, flip: true })).not.toBe(renderKey(o))
+})
+
+// A host whose typst makes one page (`png`): its bytes read back, the PNGs perl writes kept by path.
+function host(png: Uint8Array) {
+ const written = new Map<string, Uint8Array>()
+ const texts = new Map<string, string>()
+ const od = [...png.subarray(0, 24)].map(b => b.toString(16).padStart(2, '0')).join(' ')
+ const $ = {
+ fs: {
+ read: async (path: string, o?: { as?: string }) => {
+ if (o?.as === 'bytes' && path.endsWith('.png')) return { base64: toBase64(written.get(path) ?? png) }
+ if (!texts.has(path)) throw new Error('ENOENT')
+ return texts.get(path)!
+ },
+ write: async (path: string, text: string) => void texts.set(path, text),
+ exists: async () => false,
+ list: async () => [{ name: 'a-1.png', kind: 'file', size: 1, mtimeMs: 1, isLink: false }],
+ },
+ process: {
+ run: async (argv: string[], init?: { stdin?: string }) => {
+ if (argv[0] === '/usr/bin/perl' && argv[2] === WRITE_PL) written.set(argv[3]!, fromBase64(init!.stdin!))
+ if (argv.join(' ').includes('od -An')) return { exitCode: 0, stdout: `${od}\n@\n`, stderr: '' }
+ return { exitCode: 0, stdout: '', stderr: '' }
+ },
+ spawn: () =>
+ (async function* () {
+ yield { stream: 'stdout' as const, text: '4242\n' }
+ return { code: 0, signal: null }
+ })(),
+ },
+ // Only the slices' clock.after(0) runs (not the compile's timeout).
+ clock: { after: (ms: number, fn: () => void) => (ms === 0 && void Promise.resolve().then(fn), { cancel() {} }) },
+ } as any
+ return { $, written, texts }
+}
+
+const ENV: Env = {
+ typst: '/usr/bin/typst', canDraw: true, inline: false, herdr: true, cache: '/c', cwd: '/w', root: '/r', isMac: true, stamp: '1', home: '/h',
+ claudeTmp: '', termFont: 'Menlo', designs: '/d', metrics: DEFAULT_METRICS,
+}
+const jobOf = (key: string, flip: boolean): Job => ({
+ key, requestId: 'r', text: 'Some answer.', columns: 2, cell: { width: 8, height: 10 }, theme: 'dark', size: 100, grid: false, themeDir: '/r/render/themes/vscode',
+ env: ENV, epoch: 0, ...(flip ? { flip } : {}),
+})
+
+test('a compile in flip mode stores each page rows × B tall with its bands reversed, in place, and notes it in pages.json', async () => {
+ forgetTouches()
+ const img = imageOf(16, 41)
+ const h = host(encode(img))
+ const result = await compile(h.$, jobOf('kf', true))
+ if (typeof result !== 'object') throw new Error(`compile: ${result}`)
+ const page = result.pages[0]!
+ expect([page.file, page.width, page.height, page.rows, page.flip]).toEqual(['/c/kf/a-1.png', 16, 40, 4, true])
+ expect([...decodePng(h.written.get('/c/kf/a-1.png')!).data]).toEqual([...flipRows(padRows(img, 4), 4).data])
+ expect(JSON.parse(h.texts.get('/c/kf/pages.json')!).pages[0].flip).toBe(true)
+ // Not in flip mode: the page as Typst made it.
+ const plain = await compile(host(encode(img)).$, jobOf('kp', false))
+ if (typeof plain !== 'object') throw new Error(`compile: ${plain}`)
+ expect([plain.pages[0]!.height, plain.pages[0]!.flip]).toEqual([41, undefined])
+ forgetTouches()
+})
+
+test('a compile in flip mode whose page can not be stored fails, so the text shows', async () => {
+ forgetTouches()
+ // A PNG head that says 16 x 41, then no image data.
+ const head = encode(imageOf(16, 41)).subarray(0, 24)
+ const bad = new Uint8Array(40)
+ bad.set(head)
+ const g = host(bad)
+ expect(await compile(g.$, jobOf('kb', true))).toBe('failed')
+ expect(g.texts.has('/c/kb/pages.json')).toBe(false)
+ forgetTouches()
+})
diff --git a/tests/images.test.ts b/tests/images.test.ts
index ac7b35b..a744b0b 100644
--- a/tests/images.test.ts
+++ b/tests/images.test.ts
@@ -1,6 +1,9 @@
import { expect, mock, test } from 'claude-code/testing'
import { onScreenOf } from '../hooks/lib/images'
+import { encodeSteps, flipRows, WRITE_PL } from '../hooks/lib/flip'
+import { decodePng, fromBase64, toBase64, type Rgba } from '../hooks/lib/png'
+import { HERDR_CLIENT_SH } from '../hooks/lib/host'
import {
claudeTmpOf, convertBox, convertCall, convertedPath, DEFAULT_CELL, factsAfter, folderOf, imageKindOf, isMarkdownPath, isNoPageError, isPdfPath, lastKnownPage,
NO_FACTS, pageControls, pageCountOf, pageOf, parsePage, pasteDirOf, pastedImagePath, pastedNumbers, COMMIT_MIN_MS, DEFAULT_HEIGHT, RESIZE_QUIET_MS, PICTURE_MAX_ROWS, PICTURE_ROOM_ROWS, pictureCells,
@@ -364,6 +367,10 @@ function world(on: any, o: {
holdCompile?: Promise<void>
pdfs?: Record<string, number>
noHint?: boolean
+ // herdr (TERM_PROGRAM=herdr): the terminal app of the client found.
+ herdr?: string
+ // The bytes (base64) a read of a PNG in the cache gives (else PNG).
+ bytes?: string
} = {}) {
// Intelligent UI's store in memory (as mock.store), and its writes by key;
// `redrawsAt`: by key, the `done` writes (redraws) made when its write ended.
@@ -385,7 +392,7 @@ function world(on: any, o: {
return { value: undefined }
})
const clock = mock.clock(on)
- mock.env(on, { HOME: '/h', TERM: 'xterm-kitty', ...o.vars })
+ mock.env(on, { HOME: '/h', TERM: 'xterm-kitty', ...(o.herdr ? { TERM_PROGRAM: 'herdr' } : {}), ...o.vars })
const files = o.files ?? {}
const texts = o.texts ?? {}
const mtimes = o.mtimes ?? {}
@@ -395,6 +402,8 @@ function world(on: any, o: {
const reads: string[] = []
const converts: string[][] = []
const moves: string[][] = []
+ // The PNGs perl writes (flip mode), by path.
+ const pngs = new Map<string, Uint8Array>()
const docs: any[] = []
const logs: string[] = []
const stats = new Map<string, number>()
@@ -424,6 +433,8 @@ function world(on: any, o: {
const argv: string[] = e.argv
const cmd = argv.join(' ')
if (argv[0] === 'kill') return ok('')
+ if (o.herdr && argv[0] === 'sh' && argv[2] === HERDR_CLIENT_SH) return ok(`pid 77\natime 5\ntty /dev/ttys003\ncmd herdr\napp ${o.herdr}\nenv\nherdr TERM=xterm-256color\n`)
+ if (argv[0] === '/usr/bin/perl' && argv[2] === WRITE_PL) return (pngs.set(argv[3]!, fromBase64(e.init.stdin)), ok(''))
if (/cc-intelligent-ui-/.test(cmd)) return ok('/c\nDarwin\n')
if (argv[0] === 'id' && argv[1] === '-u') return ok('501\n')
if (cmd.includes('command -v typst')) return o.typst ? ok('/usr/bin/typst\n') : ok('', 1)
@@ -484,14 +495,14 @@ function world(on: any, o: {
return { value: undefined }
})
on('fs.read', async ($: any, e: any, next: any) => {
- if (e.as === 'bytes' && e.path in files) return (reads.push(e.path), { value: { base64: PNG } })
+ if (e.as === 'bytes' && e.path in files) return (reads.push(e.path), { value: { base64: o.bytes && e.path.startsWith('/c/') ? o.bytes : PNG } })
if (e.as !== 'bytes' && e.path in texts) return (reads.push(e.path), { value: texts[e.path] })
if (written.has(e.path)) return { value: written.get(e.path) }
return e.path.startsWith('/c/') || e.path.startsWith('/t/') ? { deny: 'ENOENT' } : next(e)
})
on('ui.toast', async () => ({ value: undefined }))
on('ui.render', () => ENGINE as any)
- return { clock, heads, reads, converts, moves, docs, logs, files, texts, mtimes, written, kept, redrawsAt, redraws: () => redraws }
+ return { clock, heads, reads, converts, moves, pngs, docs, logs, files, texts, mtimes, written, kept, redrawsAt, redraws: () => redraws }
}
const sent = (output: unknown, isErrored = false, id = 'tu-1') =>
@@ -527,6 +538,41 @@ test('a PNG Claude sends draws under its row, at its own size', async ($, on) =>
expect(heads).toEqual(['/t/icon.png'])
})
+// A small RGBA picture (each row its own colour) as a PNG, and its pixels.
+const ROWS_IMG: Rgba = (() => {
+ const data = new Uint8Array(8 * 20 * 4)
+ for (let y = 0; y < 20; y++) for (let x = 0; x < 8; x++) data.set([y * 12, x * 30, 255 - y, 255], (y * 8 + x) * 4)
+ return { width: 8, height: 20, data }
+})()
+const ROWS_PNG = (() => {
+ const steps = encodeSteps(ROWS_IMG)
+ for (;;) {
+ const got = steps.next()
+ if (got.done) return toBase64(got.value)
+ }
+})()
+
+test('in herdr in iTerm2, a PNG Claude sends is made by Typst at its box, then stored flipped by rows for that box, and drawn from that file', async ($, on) => {
+ const { converts, pngs } = world(on, { typst: true, herdr: '/Applications/iTerm.app/Contents/MacOS/iTerm2', files: { '/t/icon.png': HEAD }, bytes: ROWS_PNG })
+ await ready($)
+ const ui = await $.ui.mount(sent(attach('/t/icon.png')))
+ const [image] = images(await ui.drawn())
+ expect(converts.map(argv => argv.find(a => a.startsWith('f='))?.slice(2))).toEqual(['/t/icon.png'])
+ expect(image.props).toMatchObject({ columns: 40, rows: 10, alt: 'icon.png' })
+ expect(image.props.source.file).toMatch(/^\/c\/[0-9a-f]{16}\/flip\.png$/)
+ expect([...decodePng(pngs.get(image.props.source.file)!).data]).toEqual([...flipRows(ROWS_IMG, 10).data])
+ expect((await $.command.run({ command: 'iui', args: 'details' } as any)).text).toContain("pages and pictures stored upside down by rows, for iTerm2's placement bug")
+})
+
+test('in herdr in Ghostty, a PNG Claude sends draws as it is', async ($, on) => {
+ const { converts, pngs } = world(on, { typst: true, herdr: '/Applications/Ghostty.app/Contents/MacOS/ghostty', files: { '/t/icon.png': HEAD }, bytes: ROWS_PNG })
+ await ready($)
+ const ui = await $.ui.mount(sent(attach('/t/icon.png')))
+ expect(images(await ui.drawn())[0].props.source).toMatchObject({ file: '/t/icon.png', format: 'png' })
+ expect([converts.length, pngs.size]).toEqual([0, 0])
+ expect((await $.command.run({ command: 'iui', args: 'details' } as any)).text).not.toContain('upside down')
+})
+
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($)
diff --git a/tests/termfont.test.ts b/tests/termfont.test.ts
index 46cf166..e532f1d 100644
--- a/tests/termfont.test.ts
+++ b/tests/termfont.test.ts
@@ -325,6 +325,33 @@ fontTest('herdr: a change of client (Ghostty to kitty) is seen by the next poll:
expect(w.fontPaths.length).toBeGreaterThan(measured)
})
+const itermClient = 'pid 50400\natime 30\ntty ttys013\ncmd herdr\napp /Applications/iTerm.app/Contents/MacOS/iTerm2\nenv\nherdr TERM=xterm-256color TERM_PROGRAM=iTerm.app\n'
+
+fontTest('herdr: a change of client to iTerm2 and back turns flip mode on and off, and redraws even with the same font', async ($, on) => {
+ let client = ghosttyClient
+ let redraws = 0
+ on('state.set', async ($: any, e: any, next: any) => {
+ if (e.key === 'done') redraws++
+ return next(e)
+ })
+ const w = world(on, { isMac: true, env: HERDR_SERVER_ENV, families: ['Iosevka'], run: argv => clientIs(() => client)(argv) ?? shows('font-family = Iosevka\n')(argv) })
+ expect(await details($)).not.toContain('upside down')
+ await w.clock.advance(3000)
+ const before = redraws
+ // iTerm2's font is not read here (no profile), so the font stays: only flip mode changes.
+ client = itermClient
+ await w.clock.advance(3000)
+ const flipped = await details($)
+ expect(flipped).toContain("(in iTerm2, the client you used last; pages and pictures stored upside down by rows, for iTerm2's placement bug)")
+ expect(flipped).toContain('terminal font Iosevka.')
+ expect(redraws).toBeGreaterThan(before)
+ const during = redraws
+ client = ghosttyClient
+ await w.clock.advance(3000)
+ expect(await details($)).not.toContain('upside down')
+ expect(redraws).toBeGreaterThan(during)
+})
+
// ---- kitty ----------------------------------------------------------------------
const kittyConf = (line: string) => ({ '/h/.config/kitty/kitty.conf': `${line}\n` })