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: choose the client in the terminal app in front, checked every 1 s

razorback1639684e2682af
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 5bcac43..71ad131 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,9 +6,10 @@ All releases of Intelligent UI for Claude Code (`cc-intelligent-ui`). Claude Cod
### 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 or Ghostty). Refer to [Terminals](docs/install.md#terminals).
+- **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 client you used last)`. If the mod uses the variables of the herdr server, it shows `(in Ghostty, from the server's start)`.
+- `/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
@@ -19,8 +20,9 @@ All releases of Intelligent UI for Claude Code (`cc-intelligent-ui`). Claude Cod
- 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 where you typed last. You can attach to one herdr server from more than one terminal, for example from Ghostty and from kitty. When you type in a different terminal, the mod finds it at the next check (every 3 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.
+ - 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.
## 0.3.2 (2026-10-21)
diff --git a/docs/development.md b/docs/development.md
index 639cbd2..c7102e7 100644
--- a/docs/development.md
+++ b/docs/development.md
@@ -15,7 +15,7 @@ sh tests/fonts-sh-test.sh # the copy of a font out of a terminal's program
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/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 and lsof, in sh, dash and bash
+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 .
```
diff --git a/docs/how-it-works.md b/docs/how-it-works.md
index df05095..38c3675 100644
--- a/docs/how-it-works.md
+++ b/docs/how-it-works.md
@@ -91,8 +91,8 @@ The terminal comes before the OS: a dark terminal on a light Mac is dark.
In **herdr**, `TERM_PROGRAM` is `herdr`, so it does not name the terminal that herdr runs in. Intelligent UI does these steps:
- **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.
+- **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`). On macOS, it uses a client in the terminal app in front (`lsappinfo`, by the app's bundle id). If there are two or more such clients, it uses the one whose tty was read last (the access time of the tty changes when you type in that terminal). If the app in front has no client (for example, a browser), it keeps the client that it used before. On Linux, and when it cannot read the app in front, it uses the client whose tty was read last. The tty time alone is not sufficient: iTerm2 answers each picture that herdr sends (herdr puts `q=2`, no answer, only in the first part of the upload), so the tty of the iTerm2 client is read each time that the mod draws pictures, also when you do not type there. An answer of this type from a terminal on Linux is not known. 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 1 s. This check reads only the app in front and the tty times of the known clients (one small `sh` with `lsappinfo` and `stat`, approximately 0.01 s of CPU time). The full check with the process list (approximately 0.1 s of CPU time) runs only when the 1 s check finds a change (a different client, a terminal in front with no known client, or a tty that is gone), and every 10 s to find new and gone clients. 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.
+Intelligent UI checks the theme every 3 s (in herdr, also at once when the terminal changes). 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 517d34f..bf615e7 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -15,9 +15,9 @@
- **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 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)`.
+ - For the font, the mod finds the herdr client that you use. You can attach to one herdr server from more than one terminal (for example Ghostty and kitty). On macOS, the mod uses the client in the terminal app in front. If that app has two or more clients, it uses the one where you typed last. If the app in front has no client (for example, a browser), the mod keeps the client that it used before. On Linux, the mod uses the client where you typed last. The mod does not use only the place where you typed last on macOS, because iTerm2 answers each picture that herdr sends, and that looks like typing in iTerm2. The mod reads the variables and the terminal app of that client, then reads the font of that terminal. When you go to a different terminal, the mod finds it at the next check (every 1 s) and draws the pictures again with that font. If you attach a new client in the app that is in front, or on Linux, the mod can find it only at the full check (every 10 s). 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 Ghostty, the terminal in front)`, `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).
+ - 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 that the mod uses 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 go to 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 18c846e..2e7c61a 100644
--- a/docs/limitations.md
+++ b/docs/limitations.md
@@ -59,10 +59,10 @@
- **The look is close to VS Code, not exact:** Typst does not use CSS. Raw HTML in Markdown is shown in a simple form or dropped. Loose lists have tight spacing (with `/iui grid on`, the items of a loose list have a gap of one row).
- **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:
+- **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 that the mod uses: on macOS, the client in the terminal app in front (with two or more clients in that app, the one where you typed last); on Linux, the client where you typed last. On Linux, with two terminals attached, the mod follows the terminal where you typed last, not the terminal that you look at. On macOS, when the app in front is not a terminal with a client (for example, a browser or an editor), the mod keeps the client that it used before. A change shows after the next check (up to 1 s; on Linux, the tty times change only about every 8 s, so it can take up to approximately 9 s). A new client that you attach in the app in front shows after the full check (up to 10 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 that the mod uses 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.
+ - With iTerm2 and a different terminal attached at the same time, the order is correct only in the terminal that the mod uses (on macOS, the terminal app in front). After you go to the other terminal, the next check (up to 1 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/env.ts b/hooks/lib/env.ts
index c59ed16..1199115 100644
--- a/hooks/lib/env.ts
+++ b/hooks/lib/env.ts
@@ -71,10 +71,11 @@ export function setUp($: EngineInterface): Promise<Env> {
S.termName = term
S.isHerdr = isHerdrIn({ program, herdrEnv: await envGet($, 'HERDR_ENV') })
S.herdrVersion = S.isHerdr ? ((await envGet($, 'TERM_PROGRAM_VERSION')) ?? '').trim() : ''
- // Under herdr the client the user typed in last gives the terminal; else (none found) the server's variables.
+ // 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($).catch(() => false)
+ if (S.isHerdr) await readHerdrClient($, was).catch(() => false)
await setOuter($)
S.isRemote = ssh
S.debug = isSet(await envGet($, 'IUI_DEBUG'))
diff --git a/hooks/lib/host.ts b/hooks/lib/host.ts
index e83ee00..a399132 100644
--- a/hooks/lib/host.ts
+++ b/hooks/lib/host.ts
@@ -4,7 +4,7 @@
import type { EngineInterface } from 'claude-code'
import type { IuiTheme } from '../../types'
-import { CLIP_WAKE_MS, HOST_CHECK_MS, HOST_POLL_MS, MODES } from './settings'
+import { CLIP_WAKE_MS, HERDR_POLL_MS, HERDR_SCAN_MS, HOST_CHECK_MS, HOST_POLL_MS, MODES } from './settings'
import { S } from './state'
import { beginEpoch } from './epoch'
import { keptOsc11, luminanceOf, modeOfColorFgBg, modeOfLuminance, modeOfMacAppearance, parseOsc11, resolveMode, schemeOfPortal, type HostMode } from './mode'
@@ -16,9 +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 { herdrClientChanged, herdrClientOf, herdrHostOf, isCmuxIn, isFlipHere, isGhosttyHere, isGhosttyIn, isKittyIn, isRioIn, type OuterName } from './terminal'
+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, envGet, fsExists, fsRead, processRun } from './api'
+import { clockEvery, clockNow, envGet, fsExists, fsRead, processRun } 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))'`
@@ -194,20 +197,25 @@ export const OSC11_PL = [
export const USE_OSC11 = false
export const PROBE_RUNS = 5
export const HEADERS_SH = `for f in "$@"; do head -c 24 "$f" | od -An -v -tx1; echo @; done`
-// herdr: the client the user typed in last, of this pane's server. One ps
-// lists the processes; this pane's server is the `herdr server` above this
-// shell. A client is a `herdr` of this user with a tty (no arguments,
-// `--session <name>`, `session attach <name>` or `client`). With more than
-// one server, lsof keeps the clients whose socket peer is one of this
-// server's sockets (no lsof, or no peer column as on Linux: all stay). The
-// client whose tty has the newest access time (a key read there) wins. It
-// prints `pid`, `atime`, `tty`, `cmd` (its command) and `app` (its nearest
-// ancestor with no tty: the terminal app) lines, then `env` and the
-// client's variables (Linux: /proc/<pid>/environ, NUL-separated; macOS: `ps
-// eww`, its command then the variables). Nothing (exit 0) when none is found.
+// herdr: the clients of this pane's server. One ps lists the processes;
+// this pane's server is the `herdr server` above this shell. A client is a
+// `herdr` of this user with a tty (no arguments, `--session <name>`,
+// `session attach <name>` or `client`). With more than one server, lsof
+// keeps the clients whose socket peer is one of this server's sockets (no
+// lsof, or no peer column as on Linux: all stay). On macOS it prints first
+// `front` and the bundle id of the app in front (lsappinfo; no line when
+// that can't be read). Then for each client: `pid`, `atime` (its tty's
+// access time, a key read there; macOS: with a fraction), `tty`, `cmd` (its
+// command) and `app` (its nearest ancestor with no tty: the terminal app)
+// lines, then `env` and the client's variables (Linux:
+// /proc/<pid>/environ, NUL-separated; macOS: `ps eww`, its command then the
+// variables). pickHerdrClient chooses one. Nothing (exit 0) when none is found.
export const HERDR_CLIENT_SH = `s=$$
-case $(uname -s) in
- Darwin|*BSD) t=$(ps -A -o pid= -o ppid= -o uid= -o tdev= -o command= 2>/dev/null) || exit 0; a=$(stat -f '%Hr/%Lr %a %N' /dev/ttys* 2>/dev/null) ;;
+u=$(uname -s)
+case $u in
+ Darwin|*BSD) t=$(ps -A -o pid= -o ppid= -o uid= -o tdev= -o command= 2>/dev/null) || exit 0
+ f='%Fa'; case $(stat -f %Fa /dev/null 2>/dev/null) in [0-9]*.[0-9]*) ;; *) f='%a' ;; esac
+ a=$(stat -f "%Hr/%Lr $f %N" /dev/ttys* 2>/dev/null) ;;
*) t=$(ps -A -o pid= -o ppid= -o uid= -o tty= -o command= 2>/dev/null) || exit 0; a=$(stat -c '%n %X %n' /dev/pts/[0-9]* /dev/tty[0-9]* 2>/dev/null | sed 's|^/dev/||') ;;
esac
c=$({ printf '%s\\n' "$a" | sed 's/^/@ /'; printf '%s\\n' "$t"; } | awk -v me="$(id -u)" -v self="$s" '
@@ -233,11 +241,33 @@ if [ "\${n:-0}" -gt 1 ]; then
case $k in *peers*) l=$({ printf '%s\\n@\\n' "$k"; printf '%s\\n' "$l"; } | awk -F '\\t' 'f == 0 { if ($0 == "@") f = 1; else m[$0] = 1; next } $3 in m') ;; esac
fi
fi
-b=$(printf '%s\\n' "$l" | awk -F '\\t' '$1 == "cl" && (z == "" || $2 + 0 > za) { z = $0; za = $2 + 0 } END { print z }')
-[ -n "$b" ] || exit 0
-p=$(printf '%s\\n' "$b" | cut -f3)
-printf '%s\\n' "$b" | awk -F '\\t' '{ printf "pid %s\\natime %s\\ntty %s\\ncmd %s\\napp %s\\nenv\\n", $3, $2, $4, $5, $6 }'
-if [ -r "/proc/$p/environ" ]; then cat "/proc/$p/environ"; else ps eww -o command= -p "$p"; fi`
+if [ "$u" = Darwin ] && command -v lsappinfo >/dev/null 2>&1; then
+ f=$(lsappinfo info -only bundleid "$(lsappinfo front 2>/dev/null)" 2>/dev/null | sed -n 's/^"CFBundleIdentifier"="\\(.*\\)"$/\\1/p')
+ [ -n "$f" ] && printf 'front %s\\n' "$f"
+fi
+printf '%s\\n' "$l" | cut -f3 | while read -r p; do
+ printf '%s\\n' "$l" | awk -F '\\t' -v p="$p" '$3 == p { printf "pid %s\\natime %s\\ntty %s\\ncmd %s\\napp %s\\nenv\\n", $3, $2, $4, $5, $6 }'
+ if [ -r "/proc/$p/environ" ]; then cat "/proc/$p/environ"; echo; else ps eww -o command= -p "$p"; fi
+done
+exit 0`
+// herdr's light check, each HERDR_POLL_MS: argument 1 is the OS (uname -s),
+// the others the known clients' ttys (/dev/...). On macOS it prints `front`
+// and the bundle id of the app in front (as HERDR_CLIENT_SH), then an
+// `atime <tty> <time>` line per tty (with a fraction on macOS; none for a
+// tty that is gone). No ps: it costs a tenth of the full scan.
+export const HERDR_TICK_SH = `o=$1; shift
+if [ "$o" = Darwin ] && command -v lsappinfo >/dev/null 2>&1; then
+ f=$(lsappinfo info -only bundleid "$(lsappinfo front 2>/dev/null)" 2>/dev/null)
+ case $f in '"CFBundleIdentifier"="'*'"') f=\${f#*=\\"}; printf 'front %s\\n' "\${f%\\"}" ;; esac
+fi
+[ $# -gt 0 ] || exit 0
+case $o in
+ Darwin|*BSD) a=$(stat -f 'atime %N %Fa' "$@" 2>/dev/null)
+ case $a in *[0-9].[0-9]*) ;; *) a=$(stat -f 'atime %N %a' "$@" 2>/dev/null) ;; esac ;;
+ *) a=$(stat -c 'atime %n %X' "$@" 2>/dev/null) ;;
+esac
+[ -n "$a" ] && printf '%s\\n' "$a"
+exit 0`
// The terminal's font family: iTerm2's profile font, Ghostty's font-family,
// kitty's font_family, Rio's [fonts] family; '' elsewhere or when it can't
@@ -395,15 +425,48 @@ export async function setOuter($: EngineInterface) {
S.isKitty = isKittyIn({ term: S.termName, windowId: await envGet($, 'KITTY_WINDOW_ID'), pid: await envGet($, 'KITTY_PID') }) || S.herdrHost === 'kitty'
}
-// herdr: reads the client the user typed in last (HERDR_CLIENT_SH). True
-// when its terminal changed (herdrClientChanged); a read that finds none
-// keeps the last one.
-export async function readHerdrClient($: EngineInterface): Promise<boolean> {
+// 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 client = got?.exitCode === 0 ? herdrClientOf(got.stdout) : null
- if (!client) return false
- const changed = herdrClientChanged(S.herdrClient, client)
- S.herdrClient = client
+ 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())
+ 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 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: '' }
+ 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
}
@@ -693,16 +756,20 @@ 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, font or flip
-// mode (isFlipHere: iTerm2 in or out) redraws.
-export async function pollHost($: EngineInterface) {
+// mode (isFlipHere: iTerm2 in or out) redraws. Under herdr the mode is read
+// each HOST_POLL_MS (every third poll), at once for another terminal, and
+// with `modeNow`.
+export async function pollHost($: EngineInterface, modeNow = false) {
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))
+ const moved = S.isHerdr && (await checkHerdrClient($).catch(() => false))
if (moved) await setOuter($)
- if (S.setting === 'auto') S.host = (await readHostMode($).catch(() => null)) ?? S.host
+ const due = !S.isHerdr || modeNow || moved || ++S.hostTicks >= HOST_POLL_MS / HERDR_POLL_MS
+ if (due) S.hostTicks = 0
+ if (S.setting === 'auto' && due) S.host = (await readHostMode($).catch(() => null)) ?? S.host
if (moved) refonted = await refont($).catch(() => false)
} finally {
S.checking = false
@@ -721,17 +788,22 @@ export function showMode($: EngineInterface) {
beginEpoch($)
}
-// Polls while the setting is auto or under herdr (its client can change), 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) {
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 = clockEvery($, HOST_POLL_MS, () => void pollHost($).catch(() => undefined))
+ S.watch = clockEvery($, ms, () => void pollHost($).catch(() => undefined))
+ S.watchMs = ms
} catch {
S.watch = null
}
- } else if (!wanted && S.watch) {
- S.watch.cancel()
- S.watch = null
}
}
diff --git a/hooks/lib/settings.ts b/hooks/lib/settings.ts
index 221ac9b..5f241a6 100644
--- a/hooks/lib/settings.ts
+++ b/hooks/lib/settings.ts
@@ -78,6 +78,11 @@ export const NO_NETWORK = 'http://127.0.0.1:9'
// how long one read may take.
export const HOST_POLL_MS = 3000
export const HOST_CHECK_MS = 2000
+// Under herdr: how often the light client check runs (the app in front and
+// the known clients' tty times), and the most time between two full scans
+// (the process list: new or gone clients).
+export const HERDR_POLL_MS = 1000
+export const HERDR_SCAN_MS = 10000
// Copy: how often the watcher reads the clipboard's change count (macOS;
// one call in the watcher, no process), and the word positions of how
// many pages are kept in memory (a copy probes only the pages it reads).
diff --git a/hooks/lib/state.ts b/hooks/lib/state.ts
index 67f8f95..2bcbc2b 100644
--- a/hooks/lib/state.ts
+++ b/hooks/lib/state.ts
@@ -181,15 +181,23 @@ export const S = {
// iTerm2 (isItermIn) and cmux (Ghostty inside, with its CMUX_* variables), set in setUp (cmux: setOuter).
isIterm: false,
isCmux: false,
- // herdr (isHerdrIn), its version ('' not known), the client the user
- // typed in last (HERDR_CLIENT_SH; null: none found, so the server's
- // variables count), the terminal it runs in ('' outside herdr or not
- // known; setOuter), all set in setUp and kept by the poll; and the last
- // OSC 11 answer of its pane (keptOsc11).
+ // herdr (isHerdrIn), its version ('' not known), the client in use
+ // (pickHerdrClient: in the terminal app in front, or typed in last; null:
+ // none found, so the server's variables count) and how it was chosen, the
+ // terminal it runs in ('' outside herdr or not known; setOuter), all set
+ // in setUp and kept by the poll; and the last OSC 11 answer of its pane
+ // (keptOsc11).
isHerdr: false,
herdrVersion: '',
herdrClient: null as HerdrClient | null,
+ herdrBy: 'typed' as 'front' | 'typed',
herdrHost: '' as HerdrHost,
+ // The clients, the app in front and the time of the last full scan (null: none yet), for the light check.
+ herdrClients: [] as HerdrClient[],
+ herdrScanFront: null as string | null,
+ herdrScanAt: null as number | null,
+ // Polls under herdr since the last mode read (it runs every HOST_POLL_MS).
+ hostTicks: 0,
osc11Kept: null as Osc11Kept,
// A font folder for Typst (TYPST_FONT_PATHS): the font a terminal carries
// in its program (Ghostty's, Rio's), when it draws it. '' for none.
@@ -206,6 +214,8 @@ export const S = {
setupNeeded: false,
setupAsked: false,
watch: null as { cancel: () => void } | null,
+ // The poll timer's period (watchHost).
+ watchMs: 0,
checking: false,
// Linux: the tool that reads the desktop portal's colour scheme (host.ts;
// null: not tried yet, '': none works, so GNOME's gsettings is read).
diff --git a/hooks/lib/terminal.ts b/hooks/lib/terminal.ts
index a86d2a4..310875c 100644
--- a/hooks/lib/terminal.ts
+++ b/hooks/lib/terminal.ts
@@ -1,7 +1,7 @@
// What the terminal can draw: its columns and cell size, whether the engine
// draws pictures there, and how large a picture sent as bytes (over ssh) can be.
import { S, type Cell } from './state'
-import { GUTTER, IMAGE_MAX_COLUMNS, SEGMENT_ROWS, type Width } from './settings'
+import { GUTTER, HERDR_SCAN_MS, IMAGE_MAX_COLUMNS, SEGMENT_ROWS, type Width } from './settings'
import { isItermIn } from './terminals'
import type { EnvName } from './api'
@@ -159,24 +159,107 @@ export function herdrClientOf(stdout: string): HerdrClient | null {
return { pid, atime: Number(field('atime')) || 0, tty: field('tty'), cmd, app, env, kind }
}
+// HERDR_CLIENT_SH's output: the bundle id of the app in front (`front`;
+// null when not read, as on Linux) and each client (a block from its `pid`
+// line). An old output of one client with no `front` line also parses.
+export function herdrClientsOf(stdout: string): { front: string | null; clients: HerdrClient[] } {
+ const [head = '', ...blocks] = `\n${stdout}`.split(/\n(?=pid [^\n]*\n)/)
+ const front = /^front (.+)$/m.exec(head)?.[1]?.trim() || null
+ return { front, clients: blocks.map(block => herdrClientOf(block)).filter((c): c is HerdrClient => !!c) }
+}
+
+// The terminal kinds of the app in front (macOS bundle ids): the herdr
+// hosts, and WezTerm and Terminal (no herdr host of their own). '' for
+// another app (a browser, an editor).
+export type FrontKind = HerdrHost | 'wezterm' | 'terminal'
+const FRONT_APPS: Readonly<Record<string, FrontKind>> = {
+ 'com.mitchellh.ghostty': 'ghostty',
+ 'net.kovidgoyal.kitty': 'kitty',
+ 'com.googlecode.iterm2': 'iterm',
+ 'com.cmuxterm.app': 'cmux',
+ 'com.github.wez.wezterm': 'wezterm',
+ 'com.raphaelamorim.rio': 'rio',
+ 'com.apple.Terminal': 'terminal',
+}
+export const frontKindOf = (bundleId: string): FrontKind => FRONT_APPS[bundleId] ?? ''
+// A client's kind to compare with the app in front: its terminal, else
+// WezTerm or Terminal by its terminal app's path.
+export const clientFrontKindOf = (c: HerdrClient): FrontKind =>
+ c.kind || (/wezterm/i.test(c.app) ? 'wezterm' : /\/Terminal\.app\//.test(c.app) ? 'terminal' : '')
+
+// The herdr client to follow, and why: `front` (macOS: a client in the
+// terminal app in front; with more than one, the tty read last), `typed`
+// (the tty read last: no front app known, as on Linux, or no client kept),
+// `kept` (the app in front has no client, as a browser: the client of
+// before stays). The tty time alone is not enough: iTerm2 answers each
+// picture upload of herdr, so its client's tty is read with no key typed.
+// null when there is no client.
+export type HerdrPick = { client: HerdrClient; by: 'front' | 'typed' | 'kept' }
+export function pickHerdrClient(clients: readonly HerdrClient[], front: FrontKind | null, was: HerdrClient | null): HerdrPick | null {
+ const newest = (list: readonly HerdrClient[]) => list.reduce((a, b) => (b.atime > a.atime ? b : a))
+ if (!clients.length) return null
+ if (front === null) return { client: newest(clients), by: 'typed' }
+ const same = front ? clients.filter(c => clientFrontKindOf(c) === front) : []
+ if (same.length) return { client: newest(same), by: 'front' }
+ const kept = was ? clients.find(c => c.pid === was.pid) : undefined
+ return kept ? { client: kept, by: 'kept' } : { client: newest(clients), by: 'typed' }
+}
+
+// A tty as the scan names it (`ttys012`, `pts/3`), with no `/dev/`.
+export const ttyNameOf = (tty: string) => tty.replace(/^\/dev\//, '')
+
+// HERDR_TICK_SH's output: the bundle id of the app in front (`front`; null
+// when not read, as on Linux) and each tty's access time (`atime /dev/<tty>
+// <time>`; a tty that is gone has no line), by ttyNameOf.
+export type HerdrTick = { front: string | null; atimes: Map<string, number> }
+export function herdrTickOf(stdout: string): HerdrTick {
+ const front = /^front (.+)$/m.exec(stdout)?.[1]?.trim() || null
+ const atimes = new Map<string, number>()
+ for (const m of stdout.matchAll(/^atime \/dev\/(\S+) ([0-9]+(?:\.[0-9]+)?)$/gm)) atimes.set(m[1]!, Number(m[2]))
+ return { front, atimes }
+}
+
+// The light check under herdr: the clients of the last full scan with the
+// tick's tty times, and the pick among them (null: no client). Null when a
+// full scan must run: none yet (`ageMs` null) or HERDR_SCAN_MS since the
+// last, the tick failed, a client's tty is gone, the app in front is a
+// terminal with no client (and not the one in front at the scan), or the
+// pick is another client than `was`.
+export function herdrTickPick(o: { clients: readonly HerdrClient[]; tick: HerdrTick | null; was: HerdrClient | null; scanFront: string | null; ageMs: number | null }): { clients: HerdrClient[]; pick: HerdrPick | null } | null {
+ const { tick } = o
+ if (!tick || o.ageMs === null || o.ageMs >= HERDR_SCAN_MS) return null
+ const clients: HerdrClient[] = []
+ for (const c of o.clients) {
+ const atime = tick.atimes.get(ttyNameOf(c.tty))
+ if (atime === undefined) return null
+ clients.push({ ...c, atime })
+ }
+ const front = tick.front === null ? null : frontKindOf(tick.front)
+ if (front && tick.front !== o.scanFront && !clients.some(c => clientFrontKindOf(c) === front)) return null
+ if (!clients.length) return { clients, pick: null }
+ const pick = pickHerdrClient(clients, front, o.was)
+ return pick && pick.client.pid === o.was?.pid ? { clients, pick } : null
+}
+
// What the font and the mode depend on: the kind and OUTER_NAMES (not the
// pid or the time: another window of the same terminal changes nothing).
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.
+// Flip mode (flip.ts): herdr, not over ssh, and the client in use
+// (pickHerdrClient) 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); `flip`: flip mode is on.
-export type HerdrFrom = 'client' | 'server'
+// herdr in /iui details, and where its terminal came from: the client in
+// the terminal app in front (`front`), the client typed in last
+// (`client`), or the server's variables (the fallback); `flip`: flip mode is on.
+export type HerdrFrom = 'front' | 'client' | '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"}${flip ? `; ${FLIP_TEXT}` : ''}` : 'outer terminal not known'
+ host ? `in ${HERDR_HOSTS[host]}, ${from === 'front' ? 'the terminal in front' : 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/register.tsx b/hooks/register.tsx
index e298bf2..dbcd06f 100644
--- a/hooks/register.tsx
+++ b/hooks/register.tsx
@@ -82,7 +82,7 @@ export {
} from './lib/themes'
export { commandSuggestions, parseCommand, type Command, type Suggestion } from './lib/command'
export { hasNewSetup, hasSetup, SETUP_END, SETUP_NOT_MAC, SETUP_START, setupBlock, setupWordsOf, shellRcOf, withoutSetup, withSetup, type ShellRc } from './lib/setup'
-export { fcPatternOf, HERDR_CLIENT_SH, OSC11_PL, perlFor, PROGRAM_FONTS_PL, PROGRAM_FONTS_SH, WATCH_PL } from './lib/host'
+export { fcPatternOf, HERDR_CLIENT_SH, HERDR_TICK_SH, OSC11_PL, perlFor, PROGRAM_FONTS_PL, PROGRAM_FONTS_SH, WATCH_PL } from './lib/host'
export {
convertCall, isSafePage, measureCall, noNetworkEnv, pageRowsOf, parseOd, pngSize, probeCall, resultOf, roomInputs, shouldRetrySafe, typstCall, typstInputs,
} from './lib/typst'
@@ -828,7 +828,7 @@ export const register: Register = on => {
? '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 (and flip mode).
- const herdr = S.isHerdr ? `terminal ${herdrText(S.herdrVersion, S.herdrHost, S.herdrClient ? 'client' : 'server', isFlipHere(ready))}: ` : ''
+ const herdr = S.isHerdr ? `terminal ${herdrText(S.herdrVersion, S.herdrHost, S.herdrClient ? (S.herdrBy === 'front' ? 'front' : '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($))}`
@@ -858,7 +858,7 @@ export const register: Register = on => {
S.settingRaw = typeof set.value === 'string' ? set.value : ''
S.setting = settingOf(set.value)
// Not awaited: the setting is saved at once; the OS read redraws later.
- if (S.setting === 'auto') void pollHost($).catch(() => undefined)
+ if (S.setting === 'auto') void pollHost($, true).catch(() => undefined)
else showMode($)
watchHost($)
return set
diff --git a/tests/herdr-sh-test.sh b/tests/herdr-sh-test.sh
index 8af2c3e..3d52292 100644
--- a/tests/herdr-sh-test.sh
+++ b/tests/herdr-sh-test.sh
@@ -1,10 +1,13 @@
#!/bin/sh
# Runs the herdr client check (HERDR_CLIENT_SH in hooks/lib/host.ts) in sh,
-# dash and bash with a fake ps, stat, uname and lsof: it finds this pane's
-# server above the shell, keeps the clients of this user with a tty, keeps
-# with two servers only the clients of this one (by lsof), picks the tty
-# read last, and prints that client's lines, its terminal app and its
-# variables; nothing when no client is found.
+# dash and bash with a fake ps, stat, uname, lsof and lsappinfo: it finds
+# this pane's server above the shell, keeps the clients of this user with a
+# tty, keeps with two servers only the clients of this one (by lsof),
+# prints on macOS the app in front (`front`, by lsappinfo), then each
+# client's lines (its tty's access time, with a fraction on macOS), its
+# terminal app and its variables; nothing when no client is found. Then
+# the light check (HERDR_TICK_SH) with a fake stat and lsappinfo: the app
+# in front on macOS, and the access time of each tty asked that is there.
# Usage: sh tests/herdr-sh-test.sh (exit 0 when all pass)
set -u
here=$(cd "$(dirname "$0")/.." && pwd)
@@ -18,6 +21,8 @@ bad() { fail=$((fail + 1)); echo "FAIL: $*"; }
# The TypeScript text as sh: the escapes undone.
perl -0ne 'if (/^export const HERDR_CLIENT_SH = `(.*?)`$/ms) { $_ = $1; s/\\\\/\x00/g; s/\\\$/\$/g; s/\x00/\\/g; print }' "$here/hooks/lib/host.ts" > "$tmp/client.sh"
[ -s "$tmp/client.sh" ] && ok || bad "HERDR_CLIENT_SH: not found in host.ts"
+perl -0ne 'if (/^export const HERDR_TICK_SH = `(.*?)`$/ms) { $_ = $1; s/\\\\/\x00/g; s/\\\$/\$/g; s/\x00/\\/g; print }' "$here/hooks/lib/host.ts" > "$tmp/tick.sh"
+[ -s "$tmp/tick.sh" ] && ok || bad "HERDR_TICK_SH: not found in host.ts"
uid=$(id -u)
realps=$(command -v ps)
@@ -37,10 +42,20 @@ if [ -z "\${NOSELF:-}" ]; then
fi
cat "\$FAKE/table"
EOF
-printf '#!/bin/sh\ncat "$FAKE/stat"\n' > "$bin/stat"
+# stat: `/dev/null` (the check for fractional times) gives one; else $FAKE/stat.
+printf '#!/bin/sh\ncase "$*" in *" /dev/null") echo 1792718368.016685000; exit 0 ;; esac\ncat "$FAKE/stat"\n' > "$bin/stat"
printf '#!/bin/sh\necho "$FAKE_OS"\n' > "$bin/uname"
chmod +x "$bin/ps" "$bin/stat" "$bin/uname"
lsof_bin() { printf '#!/bin/sh\ncat "$FAKE/lsof"\n' > "$bin/lsof"; chmod +x "$bin/lsof"; }
+# lsappinfo: `front` gives an ASN; `info -only bundleid <asn>` that app's id ($FRONT).
+cat > "$bin/lsappinfo" <<'EOF2'
+#!/bin/sh
+case "$1" in
+ front) echo 'ASN:0x0-0x1a01a:' ;;
+ info) [ "$4" = 'ASN:0x0-0x1a01a:' ] && [ -n "${FRONT:-}" ] && printf '"CFBundleIdentifier"="%s"\n' "$FRONT" ;;
+esac
+EOF2
+chmod +x "$bin/lsappinfo"
# A Mac: a server (and its pane's shell and claude), Ghostty's and kitty's
# clients, and processes that are not clients (a CLI call, no tty, another
@@ -63,7 +78,7 @@ cat > "$F/table" <<EOF
4999206 4999200 $uid 16/25 herdr session attach work
EOF
cat > "$F/stat" <<EOF
-16/12 1000 /dev/ttys012
+16/12 1000.25 /dev/ttys012
16/14 9999 /dev/ttys014
16/21 2000 /dev/ttys021
16/22 9999 /dev/ttys022
@@ -87,51 +102,114 @@ for s in sh dash bash; do command -v "$s" >/dev/null 2>&1 && shells="$shells $s"
for s in $shells; do
# By its path: PATH holds only the fake tools.
[ "$s" = bash ] && s="$(command -v bash) --posix" || s=$(command -v "$s")
- run() { PATH=$bin FAKE=$F FAKE_OS=Darwin NOTTY=?? NOSELF=$noself $s "$tmp/client.sh"; }
+ run() { PATH=$bin FAKE=$F FAKE_OS=Darwin NOTTY=?? NOSELF=$noself FRONT=$front $s "$tmp/client.sh"; }
+ # The pids of the clients printed, in order of pid; one client's lines.
+ pids() { echo "$1" | grep '^pid ' | cut -d' ' -f2 | sort | tr '\n' ' '; }
+ block() { echo "$1" | awk -v p="$2" '/^pid / { q = $2 } q == p'; }
noself=
+ front=
rm -f "$bin/lsof"
- # One server: the tty read last (kitty's) wins.
- out=$(run)
- [ "$(echo "$out" | sed -n 1p)" = "pid 4999201" ] && ok || bad "$s: not kitty's client ($out)"
- [ "$(echo "$out" | sed -n 2,5p | tr '\n' '|')" = "atime 2000|tty ttys021|cmd /Users/u/.local/bin/herdr|app /Applications/kitty.app/Contents/MacOS/kitty /Users/u/.local/bin/herdr|" ] && ok || bad "$s: kitty's lines ($out)"
- [ "$(echo "$out" | sed -n 6,7p | tr '\n' '|')" = "env|/Users/u/.local/bin/herdr TERM=xterm-kitty KITTY_WINDOW_ID=1|" ] && ok || bad "$s: kitty's variables ($out)"
- # Ghostty read last: its app is above login (which has a tty).
- sed 's/^16\/12 1000/16\/12 3000/' "$F/stat" > "$F/stat2" && mv "$F/stat2" "$F/stat"
+ # One server: all its clients (Ghostty's, kitty's and the named session's), not the others.
out=$(run)
- [ "$(echo "$out" | sed -n 1p)" = "pid 4999102" ] && ok || bad "$s: not Ghostty's client ($out)"
- [ "$(echo "$out" | grep '^app ')" = "app /Applications/Ghostty.app/Contents/MacOS/ghostty -e /Users/u/.local/bin/herdr" ] && ok || bad "$s: Ghostty's app ($out)"
- sed 's/^16\/12 3000/16\/12 1000/' "$F/stat" > "$F/stat2" && mv "$F/stat2" "$F/stat"
- # Two servers: lsof keeps this server's client (Ghostty), though kitty's was read last.
+ [ "$(pids "$out")" = "4999102 4999201 4999205 4999206 " ] && ok || bad "$s: not the four clients ($out)"
+ [ "$(block "$out" 4999201 | sed -n 2,5p | tr '\n' '|')" = "atime 2000|tty ttys021|cmd /Users/u/.local/bin/herdr|app /Applications/kitty.app/Contents/MacOS/kitty /Users/u/.local/bin/herdr|" ] && ok || bad "$s: kitty's lines ($out)"
+ [ "$(block "$out" 4999201 | sed -n 6,7p | tr '\n' '|')" = "env|/Users/u/.local/bin/herdr TERM=xterm-kitty KITTY_WINDOW_ID=1|" ] && ok || bad "$s: kitty's variables ($out)"
+ # Ghostty: its app is above login (which has a tty); its time keeps the fraction.
+ [ "$(block "$out" 4999102 | grep '^app ')" = "app /Applications/Ghostty.app/Contents/MacOS/ghostty -e /Users/u/.local/bin/herdr" ] && ok || bad "$s: Ghostty's app ($out)"
+ [ "$(block "$out" 4999102 | grep '^atime ')" = "atime 1000.25" ] && ok || bad "$s: Ghostty's time ($out)"
+ [ "$(block "$out" 4999102 | sed -n 7p)" = "herdr TERM=xterm-ghostty TERM_PROGRAM=ghostty" ] && ok || bad "$s: Ghostty's variables ($out)"
+ # No app in front known: no front line.
+ [ -z "$(echo "$out" | grep '^front')" ] && ok || bad "$s: a front line with no app in front ($out)"
+ # The app in front: its bundle id first.
+ front=com.mitchellh.ghostty; out=$(run); front=
+ [ "$(echo "$out" | sed -n 1p)" = "front com.mitchellh.ghostty" ] && ok || bad "$s: not the app in front ($out)"
+ [ "$(pids "$out")" = "4999102 4999201 4999205 4999206 " ] && ok || bad "$s: with the app in front, not the four clients ($out)"
+ # Two servers: lsof keeps this server's client (Ghostty) only.
echo "4999701 1 $uid ?? /opt/herdr server" >> "$F/table"
lsof_bin
out=$(run)
- [ "$(echo "$out" | sed -n 1p)" = "pid 4999102" ] && ok || bad "$s: two servers, not this server's client ($out)"
+ [ "$(pids "$out")" = "4999102 " ] && ok || bad "$s: two servers, not this server's client ($out)"
# No lsof: all clients stay.
rm -f "$bin/lsof"
out=$(run)
- [ "$(echo "$out" | sed -n 1p)" = "pid 4999201" ] && ok || bad "$s: two servers, no lsof, not the last read ($out)"
+ [ "$(pids "$out")" = "4999102 4999201 4999205 4999206 " ] && ok || bad "$s: two servers, no lsof, not all clients ($out)"
# lsof with no peer column (Linux): all clients stay.
lsof_bin
cp "$F/lsof" "$F/lsof.keep"
sed 's/->0x[0-9a-f]*/type=STREAM/' "$F/lsof.keep" > "$F/lsof"
out=$(run)
- [ "$(echo "$out" | sed -n 1p)" = "pid 4999201" ] && ok || bad "$s: two servers, no peers, not the last read ($out)"
+ [ "$(pids "$out")" = "4999102 4999201 4999205 4999206 " ] && ok || bad "$s: two servers, no peers, not all clients ($out)"
mv "$F/lsof.keep" "$F/lsof"
# Two servers and this pane's not found: nothing.
- noself=1; out=$(run); noself=
+ noself=1; front=com.mitchellh.ghostty; out=$(run); noself=; front=
[ -z "$out" ] && ok || bad "$s: two servers, none above the shell, but output ($out)"
sed '$d' "$F/table" > "$F/table2" && mv "$F/table2" "$F/table"
rm -f "$bin/lsof"
# No client (the only one left has no tty): nothing, exit 0.
grep -v -e ' 16/2[1-5] ' -e ' 16/12 herdr' "$F/table" > "$F/table.none"
- out=$(cp "$F/table" "$F/table.keep" && cp "$F/table.none" "$F/table" && run; echo "exit $?"; cp "$F/table.keep" "$F/table")
+ out=$(cp "$F/table" "$F/table.keep" && cp "$F/table.none" "$F/table" && front=com.mitchellh.ghostty run; echo "exit $?"; cp "$F/table.keep" "$F/table")
[ "$out" = "exit 0" ] && ok || bad "$s: no client, but output ($out)"
- # Linux: tty names (pts/N), stat -c, no tty is ?.
+ # Linux: tty names (pts/N), stat -c, no tty is ?, no front line (lsappinfo is not asked).
sed -e 's/ 16\/\([0-9]*\) / pts\/\1 /' -e 's/ ?? / ? /' "$F/table" > "$tmp/linux-table"
L=$tmp/linux; mkdir -p "$L"; cp "$tmp/linux-table" "$L/table"; cp "$F"/env-* "$L/"
- sed 's|^16/\([0-9]*\) \([0-9]*\) .*|/dev/pts/\1 \2 /dev/pts/\1|' "$F/stat" > "$L/stat"
- out=$(PATH=$bin FAKE=$L FAKE_OS=Linux NOTTY=? NOSELF= $s "$tmp/client.sh")
- [ "$(echo "$out" | sed -n 1,3p | tr '\n' '|')" = "pid 4999201|atime 2000|tty pts/21|" ] && ok || bad "$s: Linux, not kitty's client ($out)"
+ sed 's|^16/\([0-9]*\) \([0-9.]*\) .*|/dev/pts/\1 \2 /dev/pts/\1|' "$F/stat" > "$L/stat"
+ out=$(PATH=$bin FAKE=$L FAKE_OS=Linux NOTTY=? NOSELF= FRONT=com.mitchellh.ghostty $s "$tmp/client.sh")
+ [ "$(pids "$out")" = "4999102 4999201 4999205 4999206 " ] && ok || bad "$s: Linux, not the four clients ($out)"
+ [ "$(block "$out" 4999201 | sed -n 1,3p | tr '\n' '|')" = "pid 4999201|atime 2000|tty pts/21|" ] && ok || bad "$s: Linux, kitty's lines ($out)"
+ [ -z "$(echo "$out" | grep '^front')" ] && ok || bad "$s: Linux, a front line ($out)"
+done
+
+# The light check: its own stat, which prints the format for each path in
+# $FAKE/times (`path time`) and fails for the others; %a and %X give whole
+# seconds; %Fa gives no number with NOFRAC (a stat with no %F).
+tbin=$tmp/tbin
+mkdir -p "$tbin"
+for t in awk sed; do ln -s "$(command -v "$t")" "$tbin/$t"; done
+ln -s "$bin/lsappinfo" "$tbin/lsappinfo"
+cat > "$tbin/stat" <<'EOF2'
+#!/bin/sh
+fmt=$2; shift 2
+rc=0
+for p; do
+ t=$(awk -v p="$p" '$1 == p { print $2 }' "$FAKE/times")
+ if [ -z "$t" ]; then echo "stat: $p: No such file or directory" >&2; rc=1; continue; fi
+ case $fmt in *%Fa) [ -n "${NOFRAC:-}" ] && t=Fa ;; *) t=${t%%.*} ;; esac
+ printf '%s\n' "$fmt" | sed "s|%[Nn]|$p|; s|%Fa|$t|; s|%[aX]|$t|"
+done
+exit $rc
+EOF2
+chmod +x "$tbin/stat"
+T=$tmp/tick; mkdir -p "$T"
+printf '/dev/ttys012 1000.250000000\n/dev/ttys021 2000.000000000\n/dev/pts/21 2000.000000000\n' > "$T/times"
+for s in $shells; do
+ [ "$s" = bash ] && s="$(command -v bash) --posix" || s=$(command -v "$s")
+ tick() { PATH=$tbin FAKE=$T FRONT=$front NOFRAC=$nofrac $s "$tmp/tick.sh" "$@"; echo "exit $?"; }
+ front=; nofrac=
+ nl='
+'
+ # macOS: the app in front, then each tty's time with its fraction.
+ front=com.mitchellh.ghostty; out=$(tick Darwin /dev/ttys012 /dev/ttys021); front=
+ [ "$out" = "front com.mitchellh.ghostty${nl}atime /dev/ttys012 1000.250000000${nl}atime /dev/ttys021 2000.000000000${nl}exit 0" ] && ok || bad "$s: tick, macOS ($out)"
+ # No app in front known: no front line.
+ out=$(tick Darwin /dev/ttys012)
+ [ "$out" = "atime /dev/ttys012 1000.250000000${nl}exit 0" ] && ok || bad "$s: tick, no front ($out)"
+ # A tty that is gone: no line for it; the others stay.
+ out=$(tick Darwin /dev/ttys099 /dev/ttys021)
+ [ "$out" = "atime /dev/ttys021 2000.000000000${nl}exit 0" ] && ok || bad "$s: tick, a tty gone ($out)"
+ # All gone: nothing, exit 0.
+ out=$(tick Darwin /dev/ttys099)
+ [ "$out" = "exit 0" ] && ok || bad "$s: tick, all gone ($out)"
+ # A stat with no %Fa: whole seconds.
+ nofrac=1; out=$(tick Darwin /dev/ttys012 /dev/ttys021); nofrac=
+ [ "$out" = "atime /dev/ttys012 1000${nl}atime /dev/ttys021 2000${nl}exit 0" ] && ok || bad "$s: tick, no %Fa ($out)"
+ # No tty asked: the app in front only.
+ front=com.googlecode.iterm2; out=$(tick Darwin); front=
+ [ "$out" = "front com.googlecode.iterm2${nl}exit 0" ] && ok || bad "$s: tick, no tty ($out)"
+ # Linux: stat -c, whole seconds, and no front line (lsappinfo is not asked).
+ front=com.mitchellh.ghostty; out=$(tick Linux /dev/pts/21 /dev/pts/9); front=
+ [ "$out" = "atime /dev/pts/21 2000${nl}exit 0" ] && ok || bad "$s: tick, Linux ($out)"
+ out=$(tick Linux)
+ [ "$out" = "exit 0" ] && ok || bad "$s: tick, Linux, no tty ($out)"
done
echo "herdr-sh-test: $pass passed, $fail failed (shells:$shells)"
diff --git a/tests/mode.test.ts b/tests/mode.test.ts
index e1b2927..7ca4689 100644
--- a/tests/mode.test.ts
+++ b/tests/mode.test.ts
@@ -192,8 +192,11 @@ test('with the theme on auto, herdr takes the OSC 11 background first, and keeps
const mode = async () => (await $.command.run({ command: 'iui', args: 'details' } as any)).text as string
const herdrLight = 'mode light (auto, from herdr: OSC 11 background of the terminal in front)'
expect(await mode()).toContain(herdrLight)
+ // Under herdr the poll runs each second, but the mode is read each 3 s.
+ await clock.advance(2000)
+ expect(probes).toBe(1)
// Two polls with no answer: the last answer stays.
- await clock.advance(3000)
+ await clock.advance(1000)
expect(await mode()).toContain(herdrLight)
await clock.advance(3000)
expect(await mode()).toContain(herdrLight)
diff --git a/tests/termfont.test.ts b/tests/termfont.test.ts
index e532f1d..fa1d8c4 100644
--- a/tests/termfont.test.ts
+++ b/tests/termfont.test.ts
@@ -1,7 +1,8 @@
import { expect, mock, test } from 'claude-code/testing'
-import { fcPatternOf, HERDR_CLIENT_SH, KITTY_MAC_FONT, PROGRAM_FONTS_PL, PROGRAM_FONTS_SH, RIO_DEFAULT_FONT, RIO_OLD_FONT } from '../hooks/register'
+import { fcPatternOf, HERDR_CLIENT_SH, HERDR_TICK_SH, KITTY_MAC_FONT, PROGRAM_FONTS_PL, PROGRAM_FONTS_SH, RIO_DEFAULT_FONT, RIO_OLD_FONT } from '../hooks/register'
import { S } from '../hooks/lib/state'
+import { HERDR_SCAN_MS } from '../hooks/lib/settings'
// The terminal font that the pictures use: the one the terminal draws. A
// font that a terminal carries in its program is copied out for Typst; a
@@ -266,6 +267,10 @@ const HERDR_SERVER_ENV = { TERM_PROGRAM: 'herdr', TERM_PROGRAM_VERSION: '0.9.5',
const kittyClient = 'pid 54346\natime 20\ntty ttys021\ncmd herdr\napp /Applications/kitty.app/Contents/MacOS/kitty herdr\nenv\nherdr TERM=xterm-kitty KITTY_WINDOW_ID=1 KITTY_CONFIG_DIRECTORY=/h/kc\n'
const ghosttyClient = 'pid 50390\natime 10\ntty ttys012\ncmd herdr\napp /Applications/Ghostty.app/Contents/MacOS/ghostty -e herdr\nenv\nherdr TERM=xterm-ghostty TERM_PROGRAM=ghostty GHOSTTY_BIN_DIR=/G\n'
const clientIs = (out: () => string) => (argv: string[]) => (argv[2] === HERDR_CLIENT_SH ? ok(out()) : undefined)
+// The light check (HERDR_TICK_SH): the app in front (null: none read) and a time for each tty asked.
+const tickIs = (front: () => string | null) => (argv: string[]) =>
+ argv[2] === HERDR_TICK_SH ? ok(`${front() ? `front ${front()}\n` : ''}${argv.slice(5).map(tty => `atime ${tty} 10\n`).join('')}`) : undefined
+const scansOf = (w: World) => w.ran.filter(argv => argv[2] === HERDR_CLIENT_SH).length
fontTest("herdr: the client you typed in last (kitty) wins over the server's variables (Ghostty)", async ($, on) => {
const w = world(on, {
@@ -301,53 +306,94 @@ fontTest("herdr in Ghostty: Ghostty's +show-config runs with the client's GHOSTT
expect(seen.every(dir => dir === '/G')).toBe(true)
})
-fontTest('herdr: a change of client (Ghostty to kitty) is seen by the next poll: the font is read and measured again', async ($, on) => {
+fontTest('herdr: the check each second runs no full scan; a new client (Ghostty to kitty) is seen by the full scan each 10 s: the font is read and measured again', async ($, on) => {
let client = ghosttyClient
const w = world(on, {
isMac: true,
env: HERDR_SERVER_ENV,
families: ['Iosevka', 'Fira Code'],
files: { '/h/kc/kitty.conf': 'font_family Fira Code\n' },
- run: argv => clientIs(() => client)(argv) ?? shows('font-family = Iosevka\n')(argv),
+ run: argv => clientIs(() => client)(argv) ?? tickIs(() => null)(argv) ?? shows('font-family = Iosevka\n')(argv),
})
const first = await details($)
expect(first).toContain('terminal font Iosevka.')
expect(first).toContain('(in Ghostty, the client you used last)')
const measured = w.fontPaths.length
- // The same terminal in the next poll: nothing is read again.
+ const scanned = scansOf(w)
+ // Each second the light check (the known client's tty), no full scan; nothing is read again.
await w.clock.advance(3000)
+ const ticks = w.ran.filter(argv => argv[2] === HERDR_TICK_SH)
+ expect(ticks.length).toBe(3)
+ expect(ticks[0]!.slice(4)).toEqual(['Darwin', '/dev/ttys012'])
+ expect(scansOf(w)).toBe(scanned)
expect(w.fontPaths.length).toBe(measured)
+ // kitty's client is new: the light check does not see it, the full scan at 10 s does.
client = kittyClient
- await w.clock.advance(3000)
+ await w.clock.advance(HERDR_SCAN_MS - 4000)
+ expect(scansOf(w)).toBe(scanned)
+ await w.clock.advance(1000)
+ expect(scansOf(w)).toBe(scanned + 1)
const later = await details($)
expect(later).toContain('terminal font Fira Code.')
expect(later).toContain('(in kitty, the client you used last)')
expect(w.fontPaths.length).toBeGreaterThan(measured)
})
+fontTest('herdr: a terminal in front with no known client makes a full scan at the next second, and only once while it stays in front', async ($, on) => {
+ let client = ghosttyClient
+ let front: string | null = 'com.mitchellh.ghostty'
+ const w = world(on, {
+ isMac: true,
+ env: HERDR_SERVER_ENV,
+ families: ['Iosevka', 'Fira Code'],
+ files: { '/h/kc/kitty.conf': 'font_family Fira Code\n' },
+ run: argv => clientIs(() => `front ${front}\n${client}`)(argv) ?? tickIs(() => front)(argv) ?? shows('font-family = Iosevka\n')(argv),
+ })
+ expect(await details($)).toContain('(in Ghostty, the terminal in front)')
+ const scanned = scansOf(w)
+ // kitty comes in front with a new client: the next check scans and follows it.
+ client = kittyClient
+ front = 'net.kovidgoyal.kitty'
+ await w.clock.advance(1000)
+ expect(scansOf(w)).toBe(scanned + 1)
+ const later = await details($)
+ expect(later).toContain('terminal font Fira Code.')
+ expect(later).toContain('(in kitty, the terminal in front)')
+ // WezTerm in front, with no client: one scan; then the client of before stays, with no scan each second.
+ front = 'com.github.wez.wezterm'
+ await w.clock.advance(1000)
+ expect(scansOf(w)).toBe(scanned + 2)
+ await w.clock.advance(3000)
+ expect(scansOf(w)).toBe(scanned + 2)
+ expect(await details($)).toContain('(in kitty, the terminal in front)')
+})
+
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 front = 'com.mitchellh.ghostty'
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) })
+ const w = world(on, { isMac: true, env: HERDR_SERVER_ENV, families: ['Iosevka'], run: argv => clientIs(() => `front ${front}\n${client}`)(argv) ?? tickIs(() => front)(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)
+ front = 'com.googlecode.iterm2'
+ await w.clock.advance(1000)
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("(in iTerm2, the terminal in front; 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)
+ front = 'com.mitchellh.ghostty'
+ await w.clock.advance(1000)
expect(await details($)).not.toContain('upside down')
expect(redraws).toBeGreaterThan(during)
})
diff --git a/tests/terminals.test.ts b/tests/terminals.test.ts
index c4ccaf0..189f277 100644
--- a/tests/terminals.test.ts
+++ b/tests/terminals.test.ts
@@ -2,11 +2,12 @@ import { expect, test } from 'claude-code/testing'
import {
cmuxAppearanceOf, cmuxConfigOf, cmuxGhosttyConfigPath, cmuxSettingsOf, envOfText, ghosttyBackgroundOf, ghosttyHasColors, ghosttyThemesOf, ghosttyValueOf,
- herdrClientChanged, herdrClientOf, herdrHostOf, herdrText, isHerdrIn, isItermIn, jsoncOf, keptOsc11, needsSetup, OSC11_MISSES, outerKindOf, type HostMode,
+ clientFrontKindOf, frontKindOf, herdrClientChanged, herdrClientOf, herdrClientsOf, herdrHostOf, herdrText, herdrTickOf, herdrTickPick, pickHerdrClient, ttyNameOf, type HerdrClient, isHerdrIn, isItermIn, jsoncOf, keptOsc11, needsSetup, OSC11_MISSES, outerKindOf, type HostMode,
KITTY_DEFAULT_BG, kittyAutoFileOf, kittyBackgroundOf, kittyConfigDirsOf, kittyEntriesOf, kittyFontOf, kittyIncludePath, kittyLinesOf,
kittySchemeOfGnome, kittyValueOf,
RIO_DEFAULT_BG, RIO_DEFAULT_FONT, rioBackgroundOf, rioConfigDirOf, rioFontOf, rioForcedOf, rioThemeNamesOf, rioThemePath, tomlStringsOf,
} from '../hooks/register'
+import { HERDR_SCAN_MS } from '../hooks/lib/settings'
// ---- kitty ------------------------------------------------------------------
@@ -242,6 +243,7 @@ test('herdr in /iui details: its version, its terminal and where that came from'
expect(herdrText('', 'iterm', 'client')).toBe('herdr (in iTerm2, the client you used last)')
expect(herdrText('', 'cmux', 'client')).toBe('herdr (in cmux, the client you used last)')
expect(herdrText('', 'rio', 'client')).toBe('herdr (in Rio, the client you used last)')
+ expect(herdrText('0.9.5', 'ghostty', 'front')).toBe('herdr 0.9.5 (in Ghostty, the terminal in front)')
expect(herdrText('', '', 'client')).toBe('herdr (outer terminal not known)')
expect(herdrText('', '')).toBe('herdr (outer terminal not known)')
})
@@ -441,3 +443,115 @@ test("cmux's own Ghostty config: its theme wins; one theme name becomes a light:
// No theme there: the Ghostty config as shown, with its other values.
expect(ghosttyHasColors(cmuxConfigOf(shown, 'font-size = 13\n'))).toBe(false)
})
+
+// HERDR_CLIENT_SH on a Mac with an iTerm2 and a Ghostty client (measured):
+// iTerm2's tty read last (its answers to herdr's picture uploads), Ghostty in front.
+const ITERM_MAC = [
+ 'pid 57693', 'atime 1792718368.016685000', 'tty ttys012', 'cmd /Users/u/.local/bin/herdr',
+ 'app /Users/u/Library/Application Support/iTerm2/iTermServer-3.7.6 /Users/u/Library/Application Support/iTerm2/iterm2-daemon-2.socket', 'env',
+ '/Users/u/.local/bin/herdr TERM_PROGRAM=iTerm.app TERM=xterm-256color TERM_PROGRAM_VERSION=3.7.6 ITERM_PROFILE=Default COLORFGBG=7;0',
+ '',
+].join('\n')
+const GHOSTTY_MAC2 = GHOSTTY_MAC.replace('atime 1792712644', 'atime 1792718338.716905000')
+
+test('the output of all herdr clients: the app in front, then each client from its pid line', () => {
+ const both = herdrClientsOf(`front com.mitchellh.ghostty\n${ITERM_MAC}${GHOSTTY_MAC2}`)
+ expect(both.front).toBe('com.mitchellh.ghostty')
+ expect(both.clients.map(c => [c.pid, c.kind, c.atime])).toEqual([[57693, 'iterm', 1792718368.016685], [50390, 'ghostty', 1792718338.716905]])
+ expect(both.clients[0]!.env.ITERM_PROFILE).toBe('Default')
+ expect(both.clients[1]!.env.COLORFGBG).toBe('15;0')
+ // No front line (Linux, or lsappinfo failed): null. One client of the old output parses.
+ expect(herdrClientsOf(KITTY_MAC)).toMatchObject({ front: null, clients: [{ pid: 54346, kind: 'kitty' }] })
+ expect(herdrClientsOf('')).toEqual({ front: null, clients: [] })
+ expect(herdrClientsOf('front com.apple.Safari\n')).toEqual({ front: 'com.apple.Safari', clients: [] })
+ // Linux: NUL-separated variables, then a new line before the next client.
+ const linux = herdrClientsOf('pid 1\natime 5\ntty pts/1\ncmd herdr\napp /usr/bin/kitty\nenv\nTERM=xterm-kitty\0\npid 2\natime 9\ntty pts/2\ncmd herdr\napp /usr/bin/ghostty\nenv\nTERM=xterm-ghostty\0\n')
+ expect(linux.clients.map(c => [c.pid, c.kind, c.env.TERM])).toEqual([[1, 'kitty', 'xterm-kitty'], [2, 'ghostty', 'xterm-ghostty']])
+})
+
+test('the app in front: its bundle id as a terminal kind; another app is none', () => {
+ expect(frontKindOf('com.mitchellh.ghostty')).toBe('ghostty')
+ expect(frontKindOf('net.kovidgoyal.kitty')).toBe('kitty')
+ expect(frontKindOf('com.googlecode.iterm2')).toBe('iterm')
+ expect(frontKindOf('com.cmuxterm.app')).toBe('cmux')
+ expect(frontKindOf('com.github.wez.wezterm')).toBe('wezterm')
+ expect(frontKindOf('com.raphaelamorim.rio')).toBe('rio')
+ expect(frontKindOf('com.apple.Terminal')).toBe('terminal')
+ expect(frontKindOf('com.apple.Safari')).toBe('')
+ expect(frontKindOf('')).toBe('')
+ const base = herdrClientOf(GHOSTTY_MAC)!
+ expect(clientFrontKindOf(base)).toBe('ghostty')
+ expect(clientFrontKindOf({ ...base, kind: '', app: '/Applications/WezTerm.app/Contents/MacOS/wezterm-gui start' })).toBe('wezterm')
+ expect(clientFrontKindOf({ ...base, kind: '', app: '/System/Applications/Utilities/Terminal.app/Contents/MacOS/Terminal' })).toBe('terminal')
+ expect(clientFrontKindOf({ ...base, kind: '', app: '/usr/sbin/sshd' })).toBe('')
+})
+
+test('the herdr client to follow: the terminal in front first, then the tty read last', () => {
+ const iterm = herdrClientOf(ITERM_MAC)!
+ const ghostty = herdrClientOf(GHOSTTY_MAC2)!
+ const ghostty2: HerdrClient = { ...ghostty, pid: 50391, atime: ghostty.atime + 1 }
+ const kitty = herdrClientOf(KITTY_MAC)!
+ // iTerm2's tty read last (picture uploads), but Ghostty in front: Ghostty.
+ expect(pickHerdrClient([iterm, ghostty], 'ghostty', null)).toEqual({ client: ghostty, by: 'front' })
+ expect(pickHerdrClient([iterm, ghostty], 'iterm', ghostty)).toEqual({ client: iterm, by: 'front' })
+ // Two clients of the app in front: the tty read last of them.
+ expect(pickHerdrClient([iterm, ghostty, ghostty2], 'ghostty', null)).toEqual({ client: ghostty2, by: 'front' })
+ // No client in the app in front (a browser, or a terminal with no client): the client of before stays, as read now.
+ expect(pickHerdrClient([iterm, ghostty], '', ghostty)).toEqual({ client: ghostty, by: 'kept' })
+ expect(pickHerdrClient([iterm, ghostty], 'wezterm', { ...ghostty, atime: 1 })).toEqual({ client: ghostty, by: 'kept' })
+ // First read, or the client of before is gone: the tty read last.
+ expect(pickHerdrClient([iterm, ghostty], '', null)).toEqual({ client: iterm, by: 'typed' })
+ expect(pickHerdrClient([iterm, ghostty], '', kitty)).toEqual({ client: iterm, by: 'typed' })
+ // No app in front known (Linux): the tty read last.
+ expect(pickHerdrClient([ghostty, iterm, kitty], null, ghostty)).toEqual({ client: iterm, by: 'typed' })
+ expect(pickHerdrClient([], 'ghostty', ghostty)).toBeNull()
+})
+
+test("herdr's light check output: the app in front and each tty's access time", () => {
+ const tick = herdrTickOf('front com.mitchellh.ghostty\natime /dev/ttys012 1792718368.016685000\natime /dev/ttys021 1792718338\n')
+ expect(tick.front).toBe('com.mitchellh.ghostty')
+ expect([...tick.atimes]).toEqual([['ttys012', 1792718368.016685], ['ttys021', 1792718338]])
+ // Linux: no front line; a tty under /dev/pts keeps its folder.
+ expect(herdrTickOf('atime /dev/pts/3 1792718338\n')).toEqual({ front: null, atimes: new Map([['pts/3', 1792718338]]) })
+ expect(herdrTickOf('')).toEqual({ front: null, atimes: new Map() })
+ // A line with no time is not one.
+ expect(herdrTickOf('atime /dev/ttys012 \natime /dev/ttys013 x\n').atimes.size).toBe(0)
+ expect(ttyNameOf('/dev/ttys003')).toBe('ttys003')
+ expect(ttyNameOf('pts/3')).toBe('pts/3')
+})
+
+test("herdr's light check: the pick on the clients of the last scan, else a full scan", () => {
+ const iterm = herdrClientOf(ITERM_MAC)!
+ // iTerm2 on ttys012, Ghostty on ttys013.
+ const ghostty: HerdrClient = { ...herdrClientOf(GHOSTTY_MAC2)!, tty: 'ttys013' }
+ const kitty = herdrClientOf(KITTY_MAC)!
+ const tickOf = (front: string | null, times: Record<string, number>) => ({ front, atimes: new Map(Object.entries(times)) })
+ const base = { clients: [iterm, ghostty], was: ghostty, scanFront: 'com.mitchellh.ghostty', ageMs: 1000 }
+ // Ghostty in front, as at the scan: the times are new, the pick stays Ghostty, no scan.
+ const same = herdrTickPick({ ...base, tick: tickOf('com.mitchellh.ghostty', { ttys012: 50, ttys013: 40 }) })
+ expect(same?.pick).toEqual({ client: { ...ghostty, atime: 40 }, by: 'front' })
+ expect(same?.clients.map(c => c.atime)).toEqual([50, 40])
+ // A browser in front: the client of before stays.
+ expect(herdrTickPick({ ...base, tick: tickOf('com.apple.Safari', { ttys012: 50, ttys013: 40 }) })?.pick?.by).toBe('kept')
+ // The app in front has another client (iTerm2): a full scan.
+ expect(herdrTickPick({ ...base, tick: tickOf('com.googlecode.iterm2', { ttys012: 50, ttys013: 40 }) })).toBeNull()
+ // A terminal in front with no client (kitty): a full scan, but not again when the scan saw it in front.
+ expect(herdrTickPick({ ...base, tick: tickOf('net.kovidgoyal.kitty', { ttys012: 50, ttys013: 40 }) })).toBeNull()
+ expect(herdrTickPick({ ...base, scanFront: 'net.kovidgoyal.kitty', tick: tickOf('net.kovidgoyal.kitty', { ttys012: 50, ttys013: 40 }) })?.pick?.by).toBe('kept')
+ // A tty gone, or the tick failed: a full scan.
+ expect(herdrTickPick({ ...base, tick: tickOf('com.mitchellh.ghostty', { ttys013: 40 }) })).toBeNull()
+ expect(herdrTickPick({ ...base, tick: null })).toBeNull()
+ // No scan yet, or the last one HERDR_SCAN_MS ago: a full scan.
+ const tick = tickOf('com.mitchellh.ghostty', { ttys012: 50, ttys013: 40 })
+ expect(herdrTickPick({ ...base, tick, ageMs: null })).toBeNull()
+ expect(herdrTickPick({ ...base, tick, ageMs: HERDR_SCAN_MS })).toBeNull()
+ expect(herdrTickPick({ ...base, tick, ageMs: HERDR_SCAN_MS - 1 })).not.toBeNull()
+ // Linux (no app in front): the tty read last; another client than before: a full scan.
+ expect(herdrTickPick({ ...base, scanFront: null, tick: tickOf(null, { ttys012: 30, ttys013: 40 }) })?.pick?.by).toBe('typed')
+ expect(herdrTickPick({ ...base, scanFront: null, tick: tickOf(null, { ttys012: 50, ttys013: 40 }) })).toBeNull()
+ // A tty named with /dev/ (an older scan) is found too.
+ expect(herdrTickPick({ ...base, clients: [{ ...kitty, tty: '/dev/ttys021' }], was: kitty, scanFront: null, tick: tickOf(null, { ttys021: 9 }) })?.pick?.client.atime).toBe(9)
+ // No client at the scan: nothing to follow, and no scan before HERDR_SCAN_MS (unless a new terminal is in front).
+ expect(herdrTickPick({ clients: [], was: null, scanFront: null, ageMs: 1000, tick: tickOf(null, {}) })).toEqual({ clients: [], pick: null })
+ expect(herdrTickPick({ clients: [], was: null, scanFront: null, ageMs: 1000, tick: tickOf('com.mitchellh.ghostty', {}) })).toBeNull()
+})