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: no timed OSC 11 probe, no scan each second when detached, only the terminal's variables read

razorback1690fc1ada92f6
diff --git a/CHANGELOG.md b/CHANGELOG.md
index eb79b03..fc3c53b 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -28,7 +28,7 @@ All releases of Intelligent UI for Claude Code (`cc-intelligent-ui`). Claude Cod
- When `$.ui.selection()` fails, a `ui.copy` of picture cells and `/iui grab` copy again (before, they said that a newer copy came first).
- A clipboard read that fails (an error or the 2 s timeout), or a late read of one of the mod's last 4 copies, no longer cancels a newer copy.
- In herdr, the mod now uses the font and the background of the terminal that herdr runs in (Ghostty, kitty, iTerm2, cmux or Rio). Before, it used Menlo and the OS appearance, so the text could be dark on a dark background.
- - With the `auto` theme, the background comes from herdr: herdr gives the background of the terminal in front (OSC 11). This also works with `herdr --remote`. If an answer does not come, the mod keeps the last background for up to 2 more checks.
+ - 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`. The mod asks only at the start and when you change to a different terminal, never on a timer, because the question reads the tty that Claude Code reads. Refer to [Limitations](docs/limitations.md).
- 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.
diff --git a/README.md b/README.md
index dedc60e..a248732 100644
--- a/README.md
+++ b/README.md
@@ -134,7 +134,7 @@ The mod sends nothing about you or your sessions anywhere.
- **Clipboard, read:** a small `perl` process watches the clipboard while the mod is on and has drawn a picture (not over ssh). On macOS it reads only the change counter; when the counter changes, the mod reads the text once with a short `perl` script (PerlObjCBridge). On Linux a notifier (`wl-paste --watch`, `clipnotify` or GTK 3 from `python3`) tells it of each change, and it then reads the text with `wl-paste`, `xclip` or GTK. `/iui grab` with no mouse selection also reads the clipboard once. The text is only checked for picture cells (then a toast names `/iui grab`); it is kept in memory only and sent nowhere (`/iui dump` writes the last clipboard with picture cells to `copy-debug.json` in the cache folder). A password manager's copy is never read: on macOS a copy with a concealed or transient type, on Linux a copy that offers the `x-kde-passwordManagerHint` target, and on Wayland also a copy marked sensitive. (On Wayland, `wl-paste --watch` hands each new copy to `cat`, which drops it.)
- **Clipboard, written:** only at these times: when you release a picture selection, when you click a link, a file path, a command or a copy button in a picture, on `/iui grab`, when you press the command button in a link row (in fullscreen with `/iui select off`, where Claude Code gets the click), and when the mod changes a `$.ui.copy` that has picture cells to its text.
- **Files:** a private cache folder in `$TMPDIR` (`cc-intelligent-ui-<uid>`, `/tmp` when `TMPDIR` is not set; mode 700, its folders deleted after 2 days). Each compile makes a folder of its own in it (the Typst root, see below) and deletes it after the compile. Also `~/.cache/cc-intelligent-ui/designs` (files deleted after 180 days) and `~/.cache/cc-intelligent-ui/fonts` (fonts copied out of a terminal app, such as Ghostty's JetBrains Mono; `$XDG_CACHE_HOME` in place of `~/.cache` when it is set). The previews of pasted images are made in the cache folder too, from the image files that Claude Code writes when you paste. `/iui setup` (iTerm2 on macOS, and herdr) changes your shell start file, only when you run it or agree to its question. The install script adds the same block when iTerm2 or herdr is there (`IUI_NO_SHELL_SETUP=1` stops it).
-- **Processes:** `typst`, the `perl` watcher, and short helper commands such as `perl`, `sh`, `osascript`, `defaults`, `plutil`, `fc-list` and `fc-match`. In herdr, while the mod is on and pictures show, a check each second finds the herdr client that you use: `stat` of the terminals' devices (the time of the last key), and on macOS `lsappinfo` (the app in front); each 10 s also `ps` (the processes and, of your own herdr clients, their variables) and `lsof`. Of a client's variables, the mod keeps only those of the terminal (for example `TERM`, `ITERM_PROFILE`, `GHOSTTY_RESOURCES_DIR`); it writes none of this anywhere. On Linux also `wl-paste`, `xclip`, `clipnotify` or `python3 -I` (GTK 3; isolated, so it loads no code from the project folder) for the clipboard.
+- **Processes:** `typst`, the `perl` watcher, and short helper commands such as `perl`, `sh`, `osascript`, `defaults`, `plutil`, `fc-list` and `fc-match`. In herdr, only while the mod is on and pictures show (from the start), a check each second finds the herdr client that you use: `stat` of the clients' terminal devices (the time of the last key), and on macOS `lsappinfo` (the app in front); with no client attached, no check each second. Each 10 s, and when the check each second finds a change, a full check: `ps` (the list of processes), `lsof` (with more than one herdr server), and the variables of your own herdr clients (Linux: `/proc/<pid>/environ`; macOS: `ps eww`). The shell of this check keeps only `TERM`, `TERM_PROGRAM`, `COLORFGBG`, `LC_TERMINAL`, `ITERM_PROFILE`, `ITERM_SESSION_ID`, `GHOSTTY_BIN_DIR`, `GHOSTTY_RESOURCES_DIR`, `KITTY_CONFIG_DIRECTORY`, `KITTY_INSTALLATION_DIR`, `KITTY_PID`, `KITTY_WINDOW_ID`, `CMUX_SOCKET_PATH`, `CMUX_SURFACE_ID`, `CMUX_WORKSPACE_ID` and `RIO_CONFIG_HOME`; the mod (and other mods' hooks) get no other variable. It writes none of this anywhere. With the `auto` theme, a `perl` asks herdr's pane for its background (OSC 11) at the start and when you change to a different herdr client, not on a timer. On Linux also `wl-paste`, `xclip`, `clipnotify` or `python3 -I` (GTK 3; isolated, so it loads no code from the project folder) for the clipboard.
- **Typst:** each compile of an answer or a plan runs with a narrow root: a new folder with the mod's template, the theme and the images that the text names. So the code in an answer cannot read other files on your computer. The skill's `check.sh` compiles the same way, and so does the preview of a pasted image (a folder with only its template and the pasted image).
## Docs
diff --git a/docs/how-it-works.md b/docs/how-it-works.md
index 21667c0..b464265 100644
--- a/docs/how-it-works.md
+++ b/docs/how-it-works.md
@@ -92,9 +92,9 @@ 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`). 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.
+- **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. The question reads the tty that Claude Code reads (refer to [Limitations](limitations.md)), so Intelligent UI asks only at the start and when it changes to a different herdr client, never on a timer. It asks only when no key came in the prompt box for 2 s, when the mod is on and draws pictures in herdr, and when the theme was `auto` at the start or at the change of client. Claude Code reads some answers first. If no answer comes, it asks again at the next checks, 3 times at most. Then it uses the sources above. It keeps an answer while the sources above give the same mode as when the answer came. When they change (for example, the OS appearance changes and the terminal's theme follows it), it uses them.
+- **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`; the shell that reads them keeps only the terminal's variables, `CLIENT_NAMES` in `hooks/lib/terminal.ts`) 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 no client is attached (a detached pane), there is no 1 s check, only the full check every 10 s. The checks run only while the mod is on and Claude Code draws pictures in herdr. 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 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.
+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 never uses OSC 11. Only in herdr, the mod uses OSC 11 at the start and for a new client (see above).
diff --git a/docs/limitations.md b/docs/limitations.md
index c608aa4..b72d2b5 100644
--- a/docs/limitations.md
+++ b/docs/limitations.md
@@ -59,7 +59,8 @@
- **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 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.
+- **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). The mod asks herdr at the start and when you change to a different herdr client (with `herdr --remote`, only at the start). Then a change of the terminal's background shows only if the terminal's config or the OS appearance changes too, or at the next change of client. Claude Code sometimes reads herdr's answer first; then the mod asks again, 3 times at most, 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.
+- **In herdr, the background question can take a key.** The mod asks herdr's pane for its background (OSC 11) with a short `perl` that reads the tty for up to 0.3 s. Claude Code reads the same tty. A key, an answer in a dialog, Esc or a mouse report that comes in these 0.3 s can go to the mod, and Claude Code then does not get it. The mod asks only with the `auto` theme, at the start and when you change to a different herdr client (3 times at most each time), and not within 2 s of a key in the prompt box. It does not see keys in a dialog or mouse reports, so the risk stays there. A theme that is not `auto` stops the question.
- **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.
diff --git a/hooks/lib/env.ts b/hooks/lib/env.ts
index 5ea1abd..d8da700 100644
--- a/hooks/lib/env.ts
+++ b/hooks/lib/env.ts
@@ -7,13 +7,13 @@ import {
BASE_THEME, DEFAULT_HEIGHT, DEFAULT_SIZE, DESIGNS_KEPT_DAYS, DEFAULT_THEME, DEFAULT_WIDTH, MAX_HEIGHT, MAX_SIZE, MAX_WIDTH, MIN_HEIGHT, MIN_SIZE, MIN_WIDTH, noTypstOf,
} from './settings'
import { DEFAULT_METRICS, refresh, S, settingsSet, type Env } from './state'
-import { resolveMode, settingOf } from './mode'
+import { OSC11_TRIES, resolveMode, settingOf } from './mode'
import { isItermIn } from './terminals'
import { canDrawIn, isHerdrIn, isSet, needsSetup } from './terminal'
import { claudeTmpOf } from './images'
import { applyTheme } from './themes'
import { registerCommand } from './command'
-import { readHerdrClient, readHostMode, setOuter, termFontOf, watchHost } from './host'
+import { osc11Due, readHerdrClient, readHostMode, setOuter, termFontOf, watchHost } from './host'
import { readFrame, refontAfterStart, setFrame, watchFrame } from './frame'
import { offerSetup } from './setup'
import { findClipWay } from './clipboard'
@@ -71,11 +71,19 @@ export function setUp($: EngineInterface): Promise<Env> {
S.termName = term
S.isHerdr = isHerdrIn({ program, herdrEnv: await getenv($, 'HERDR_ENV') })
S.herdrVersion = S.isHerdr ? ((await getenv($, 'TERM_PROGRAM_VERSION')) ?? '').trim() : ''
+ S.herdrDraws = S.isHerdr && canDraw
+ // Off when it starts (the stored setting), unless an /iui command set it meanwhile.
+ const enabled = await load($, 'enabled').catch(() => undefined)
+ const off = settingsSet.has('enabled') ? S.isOff : enabled === false
// 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.
+ // The clients' processes are read only while the mod is on and draws pictures.
const was = S.herdrClient
S.herdrClient = null
S.osc11Kept = null
- if (S.isHerdr) await readHerdrClient($, was).catch(() => false)
+ S.herdrClients = []
+ S.herdrScanFront = null
+ S.herdrScanAt = null
+ if (S.herdrDraws && !off) await readHerdrClient($, was).catch(() => false)
await setOuter($)
S.isRemote = ssh
S.debug = isSet(await getenv($, 'IUI_DEBUG'))
@@ -96,9 +104,10 @@ export function setUp($: EngineInterface): Promise<Env> {
})
if (S.setupNeeded) void offerSetup($).catch(() => undefined)
S.userFontPaths = (await getenv($, 'TYPST_FONT_PATHS')) ?? ''
- if (S.setting === 'auto') S.host = (await readHostMode($).catch(() => null)) ?? S.host
+ // Under herdr with auto, its OSC 11 answer is asked at the start (osc11Due).
+ S.osc11Tries = S.setting === 'auto' ? OSC11_TRIES : 0
+ if (S.setting === 'auto') S.host = (await readHostMode($, await osc11Due($, off)).catch(() => null)) ?? S.host
S.theme = resolveMode(S.setting, S.host)
- S.herdrDraws = S.isHerdr && canDraw
watchHost($)
// The stored settings, but not one an /iui command set meanwhile (settingsSet).
const kept = Number(await load($, 'size').catch(() => undefined))
@@ -118,7 +127,6 @@ export function setUp($: EngineInterface): Promise<Env> {
if (!settingsSet.has('select')) S.select = select
// An engine with no version call is older than picture select.
S.engine = await Promise.resolve().then(() => ver($)).then(v => v.base ?? v.version, () => '')
- const enabled = await load($, 'enabled').catch(() => undefined)
if (enabled === false && !settingsSet.has('enabled')) {
S.isOff = true
watchHost($)
diff --git a/hooks/lib/host.ts b/hooks/lib/host.ts
index ad4c95b..9f46497 100644
--- a/hooks/lib/host.ts
+++ b/hooks/lib/host.ts
@@ -7,7 +7,7 @@ import type { IuiTheme } from '../../types'
import { CLIP_WAKE_MS, HERDR_POLL_MS, HERDR_SCAN_MS, HOST_CHECK_MS, HOST_POLL_MS, MODES, OSC11_QUIET_MS } from './settings'
import { S } from './state'
import { beginEpoch } from './epoch'
-import { keptOsc11, luminanceOf, modeOfColorFgBg, modeOfLuminance, modeOfMacAppearance, parseOsc11, resolveMode, schemeOfPortal, type HostMode } from './mode'
+import { keptOsc11, luminanceOf, OSC11_TRIES, modeOfColorFgBg, modeOfLuminance, modeOfMacAppearance, parseOsc11, resolveMode, schemeOfPortal, type HostMode } from './mode'
import {
cmuxAppearanceOf, cmuxConfigOf, cmuxGhosttyConfigPath, cmuxSettingsOf, familyOfFc, GHOSTTY_DEFAULT_FONT, ghosttyBackgroundOf, ghosttyFontsOf, ghosttyHasColors,
ghosttyThemePaths, ghosttyThemesOf,
@@ -204,14 +204,20 @@ export const HEADERS_SH = `for f in "$@"; do head -c 24 "$f" | od -An -v -tx1; e
// 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.
+// that can't be read), also when no client is found. 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 of the client's
+// variables only CLIENT_NAMES (Linux: from /proc/<pid>/environ,
+// NUL-separated; macOS: from `ps eww`, its command then the variables, cut
+// as envOfText does). pickHerdrClient chooses one.
export const HERDR_CLIENT_SH = `s=$$
u=$(uname -s)
+e='COLORFGBG|GHOSTTY_BIN_DIR|GHOSTTY_RESOURCES_DIR|ITERM_PROFILE|KITTY_CONFIG_DIRECTORY|RIO_CONFIG_HOME|CMUX_SOCKET_PATH|CMUX_SURFACE_ID|CMUX_WORKSPACE_ID|ITERM_SESSION_ID|KITTY_INSTALLATION_DIR|KITTY_PID|KITTY_WINDOW_ID|LC_TERMINAL|TERM|TERM_PROGRAM'
+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
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
@@ -241,13 +247,14 @@ 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
-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
+ if [ -r "/proc/$p/environ" ]; then tr '\\0' '\\n' < "/proc/$p/environ" | grep -E "^($e)=" | tr '\\n' '\\0'; echo
+ else ps eww -o command= -p "$p" | awk -v c="$(printf '%s\\n' "$l" | awk -F '\\t' -v p="$p" '$3 == p { print $5 }')" -v k="^($e)=" '
+ { x = $0; if (x == c || index(x, c " ") == 1) x = substr(x, length(c) + 1); else if (match(x, / [A-Za-z_][A-Za-z0-9_]*=/)) x = substr(x, RSTART); else x = ""
+ o = c; while (x != "") { x = substr(x, 2); w = x; x = ""; if (match(w, / [A-Za-z_][A-Za-z0-9_]*=/)) { x = substr(w, RSTART); w = substr(w, 1, RSTART - 1) }
+ if (w ~ k) o = o " " w }
+ print o }'; fi
done
exit 0`
// herdr's light check, each HERDR_POLL_MS: argument 1 is the OS (uname -s),
@@ -456,8 +463,8 @@ export async function checkHerdrClient($: EngineInterface): Promise<boolean> {
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 exec($, ['sh', '-c', HERDR_TICK_SH, 'sh', S.hostOs, ...ttys], { timeoutMs: HOST_CHECK_MS }).catch(() => null) : { exitCode: 0, stdout: '' }
+ // No client (a detached or remote pane): nothing to read, no process.
+ const got = ttys.length ? await exec($, ['sh', '-c', HERDR_TICK_SH, 'sh', S.hostOs, ...ttys], { timeoutMs: HOST_CHECK_MS }).catch(() => null) : { exitCode: 0, stdout: '' }
tick = got?.exitCode === 0 ? herdrTickOf(got.stdout) : null
}
const light = herdrTickPick({ clients: S.herdrClients, tick, was: S.herdrClient, scanFront: S.herdrScanFront, ageMs })
@@ -517,24 +524,42 @@ async function configFontOf($: EngineInterface, isMac: boolean): Promise<string>
}
// The mode for auto now, or null when nothing can be read (keep the last
-// one): 1. the terminal's OSC 11 answer (off, see USE_OSC11; on under herdr,
-// local or remote: its pane answers with the background of the terminal in
-// front, and a missed answer keeps the last one a while, keptOsc11); 2. the
-// terminal's own settings (iTerm2's profile, Ghostty's, kitty's or Rio's
-// config); 3. COLORFGBG at start; 4. the
-// OS appearance; 5. dark (resolveMode). The terminal comes before the OS: a
-// dark terminal on a light Mac is dark. Over ssh, only COLORFGBG (when ssh
-// sends it): the configs and the OS here are the remote computer's.
-export async function readHostMode($: EngineInterface): Promise<HostMode | null> {
+// one): 0. under herdr, local or remote, its pane's OSC 11 answer (the
+// background of the terminal in front), asked only with `ask` (osc11Due)
+// and kept while the sources below do not change (keptOsc11); 1. the
+// terminal's OSC 11 answer (off, see USE_OSC11); 2. the terminal's own
+// settings (iTerm2's profile, Ghostty's, kitty's or Rio's config); 3.
+// COLORFGBG at start; 4. the OS appearance; 5. dark (resolveMode). The
+// terminal comes before the OS: a dark terminal on a light Mac is dark.
+// Over ssh, only COLORFGBG (when ssh sends it): the configs and the OS
+// here are the remote computer's.
+export async function readHostMode($: EngineInterface, ask = false): Promise<HostMode | null> {
+ if (!S.isHerdr) return readOwnMode($)
+ let answer: HostMode | null | undefined
+ if (ask) {
+ S.osc11Tries = Math.max(0, S.osc11Tries - 1)
+ const bg = parseOsc11((await probeOsc11($).catch(() => null))?.reply ?? '')
+ answer = bg ? { mode: modeOfLuminance(luminanceOf(bg)), source: 'herdr', detail: 'OSC 11 background of the terminal in front' } : null
+ if (answer) S.osc11Tries = 0
+ }
+ const { kept, use } = keptOsc11(S.osc11Kept, await readOwnMode($).catch(() => null), answer)
+ S.osc11Kept = kept
+ return use
+}
+
+// Under herdr, an OSC 11 probe is due: tries are left (the start or a new
+// client, with auto), the mod draws herdr pictures and is on, and no key
+// came in the prompt box for OSC11_QUIET_MS.
+export async function osc11Due($: EngineInterface, off = S.isOff): Promise<boolean> {
+ if (S.osc11Tries <= 0 || !S.isHerdr || !S.herdrDraws || off || S.setting !== 'auto') return false
+ return (await nowMs($).catch(() => Date.now())) - S.keyAt >= OSC11_QUIET_MS
+}
+
+// Sources 1 to 5 of readHostMode.
+async function readOwnMode($: EngineInterface): Promise<HostMode | null> {
if (USE_OSC11) {
const bg = parseOsc11((await probeOsc11($))?.reply ?? '')
if (bg) return { mode: modeOfLuminance(luminanceOf(bg)), source: 'terminal', detail: 'OSC 11 background' }
- } else if (S.isHerdr) {
- const bg = parseOsc11((await probeOsc11($).catch(() => null))?.reply ?? '')
- const answer: HostMode | null = bg ? { mode: modeOfLuminance(luminanceOf(bg)), source: 'herdr', detail: 'OSC 11 background of the terminal in front' } : null
- const { kept, use } = keptOsc11(S.osc11Kept, answer)
- S.osc11Kept = kept
- if (use) return use
}
if (S.isRemote) {
const mode = modeOfColorFgBg(S.colorFgBg)
@@ -758,7 +783,8 @@ async function readLinuxScheme($: EngineInterface): Promise<LinuxScheme | null>
// are read again), then with auto the mode. A changed mode, font or flip
// 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`.
+// with `modeNow`. No timed OSC 11 probe: only one that osc11Due allows
+// (the start or a new client), never for `modeNow` (a dialog can be open).
export async function pollHost($: EngineInterface, modeNow = false) {
const herdr = herdrPolled()
if (S.checking || (S.setting !== 'auto' && !herdr)) return
@@ -767,13 +793,16 @@ export async function pollHost($: EngineInterface, modeNow = false) {
const flipWas = isFlipHere()
try {
const moved = herdr && (await checkHerdrClient($).catch(() => false))
- if (moved) await setOuter($)
- const due = !herdr || modeNow || moved || ++S.hostTicks >= HOST_POLL_MS / HERDR_POLL_MS
- // Under herdr a timed read asks the tty (OSC 11): not while the mod is off,
- // nor just after a key in the prompt (it stays due: a later poll reads).
- const asks = !S.isHerdr || modeNow || moved || (!S.isOff && (await nowMs($).catch(() => Date.now())) - S.keyAt >= OSC11_QUIET_MS)
- if (due && asks) S.hostTicks = 0
- if (S.setting === 'auto' && due && asks) S.host = (await readHostMode($).catch(() => null)) ?? S.host
+ if (moved) {
+ await setOuter($)
+ // The answer was the terminal of before: a new client is asked again.
+ S.osc11Kept = null
+ S.osc11Tries = S.setting === 'auto' ? OSC11_TRIES : 0
+ }
+ const ask = herdr && !modeNow && (await osc11Due($))
+ const due = !herdr || modeNow || moved || ask || ++S.hostTicks >= HOST_POLL_MS / HERDR_POLL_MS
+ if (due) S.hostTicks = 0
+ if (S.setting === 'auto' && due) S.host = (await readHostMode($, ask).catch(() => null)) ?? S.host
if (moved) refonted = await refont($).catch(() => false)
} finally {
S.checking = false
diff --git a/hooks/lib/mode.ts b/hooks/lib/mode.ts
index 55ed6f9..145bb78 100644
--- a/hooks/lib/mode.ts
+++ b/hooks/lib/mode.ts
@@ -90,17 +90,21 @@ export function parseOsc11(text: string): Rgb | null {
return { r: part(m[1]!), g: part(m[2]!), b: part(m[3]!) }
}
-// Under herdr, the OSC 11 answer (the background of the terminal in front)
-// does not always reach the mod (Claude Code reads it first). A poll with no
-// answer keeps the last answer's mode until OSC11_MISSES polls in a row have
-// none; then the other sources count. `last`: the answer kept and the misses
-// in a row since it (null: none kept).
-export const OSC11_MISSES = 3
-export type Osc11Kept = { seen: HostMode; misses: number } | null
-export function keptOsc11(last: Osc11Kept, answer: HostMode | null): { kept: Osc11Kept; use: HostMode | null } {
- if (answer) return { kept: { seen: answer, misses: 0 }, use: answer }
- if (last && last.misses + 1 < OSC11_MISSES) return { kept: { seen: last.seen, misses: last.misses + 1 }, use: last.seen }
- return { kept: null, use: null }
+// Under herdr, the OSC 11 answer (the background of the terminal in front).
+// The probe reads the tty that Claude Code reads, so it runs only at the
+// start and for a new herdr client, at most OSC11_TRIES times (an answer
+// can go to Claude Code). `answer`: a probe's mode (undefined: no probe this
+// time); `base`: the mode of the other sources now. The answer stays while
+// those give the mode they gave when it came (null: not known, no change);
+// a change there (the OS, the terminal's config) wins.
+export const OSC11_TRIES = 3
+export type Osc11Kept = { seen: HostMode; base: IuiTheme | null } | null
+export function keptOsc11(last: Osc11Kept, base: HostMode | null, answer?: HostMode | null): { kept: Osc11Kept; use: HostMode | null } {
+ if (answer) return { kept: { seen: answer, base: base?.mode ?? null }, use: answer }
+ if (!last) return { kept: null, use: base }
+ if (!base) return { kept: last, use: last.seen }
+ if (last.base === null) return { kept: { seen: last.seen, base: base.mode }, use: last.seen }
+ return last.base === base.mode ? { kept: last, use: last.seen } : { kept: null, use: base }
}
// Control characters shown as text (\e, \a, \xNN), for /iui probe.
diff --git a/hooks/lib/settings.ts b/hooks/lib/settings.ts
index bcdd799..ba9979a 100644
--- a/hooks/lib/settings.ts
+++ b/hooks/lib/settings.ts
@@ -83,9 +83,9 @@ export const HOST_CHECK_MS = 2000
// (the process list: new or gone clients).
export const HERDR_POLL_MS = 1000
export const HERDR_SCAN_MS = 10000
-// Under herdr the mode read asks the pane's tty (OSC 11), which Claude Code
-// reads too: a key typed then can go to the probe. So a poll does not ask
-// within this time of a key in the prompt box.
+// Under herdr the OSC 11 probe (at the start and for a new client) reads the
+// pane's tty, which Claude Code reads too: a key typed then can go to the
+// probe. So it does not run within this time of a key in the prompt box.
export const OSC11_QUIET_MS = 2000
// 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
diff --git a/hooks/lib/state.ts b/hooks/lib/state.ts
index e665081..55b80cd 100644
--- a/hooks/lib/state.ts
+++ b/hooks/lib/state.ts
@@ -186,7 +186,7 @@ export const S = {
// 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).
+ // (keptOsc11) and the probes still allowed (OSC11_TRIES: the start or a new client).
isHerdr: false,
herdrVersion: '',
herdrClient: null as HerdrClient | null,
@@ -199,6 +199,7 @@ export const S = {
// Polls under herdr since the last mode read (it runs every HOST_POLL_MS).
hostTicks: 0,
osc11Kept: null as Osc11Kept,
+ osc11Tries: 0,
// 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.
fontPaths: '',
diff --git a/hooks/lib/terminal.ts b/hooks/lib/terminal.ts
index d95dc11..e767b22 100644
--- a/hooks/lib/terminal.ts
+++ b/hooks/lib/terminal.ts
@@ -231,8 +231,9 @@ export function herdrTickOf(stdout: string): HerdrTick {
// 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`.
+// terminal with no client (and not the one in front at the scan; with no
+// client at all, only the scan each HERDR_SCAN_MS), 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
@@ -243,8 +244,8 @@ export function herdrTickPick(o: { clients: readonly HerdrClient[]; tick: HerdrT
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 }
+ if (front && tick.front !== o.scanFront && !clients.some(c => clientFrontKindOf(c) === front)) return null
const pick = pickHerdrClient(clients, front, o.was)
return pick && pick.client.pid === o.was?.pid ? { clients, pick } : null
}
@@ -312,9 +313,12 @@ export const inlineBudget = (px: Cell) => Math.max(20, Math.min(SEGMENT_ROWS, Ma
export const HERDR_MAX_PAGE_BYTES = 16 * 1024 * 1024
// Under herdr, a segment's budget in rows so that its page (the columns'
// width in device pixels, as sizing makes it) stays under HERDR_MAX_PAGE_BYTES
-// (with room for the rough row count).
-export const herdrBudget = (columns: number, px: Cell) =>
- Math.max(20, Math.min(SEGMENT_ROWS, Math.floor((HERDR_MAX_PAGE_BYTES / (4 * Math.round(columns * px.width) * px.height)) * 0.75)))
+// (with room for the rough row count): at least 20 rows, but never more
+// rows than fit (1 at least).
+export const herdrBudget = (columns: number, px: Cell) => {
+ const fit = HERDR_MAX_PAGE_BYTES / (4 * Math.round(columns * px.width) * px.height)
+ return Math.max(1, Math.min(Math.floor(fit), Math.max(20, Math.min(SEGMENT_ROWS, Math.floor(fit * 0.75)))))
+}
// A segment's budget in rows: the smaller of the ssh and herdr ones that apply.
export const segmentBudget = (env: { inline: boolean; herdr?: boolean }, columns: number, px: Cell) =>
Math.min(env.inline ? inlineBudget(px) : SEGMENT_ROWS, env.herdr ? herdrBudget(columns, px) : SEGMENT_ROWS)
diff --git a/tests/draw.test.ts b/tests/draw.test.ts
index da6746a..943b344 100644
--- a/tests/draw.test.ts
+++ b/tests/draw.test.ts
@@ -63,9 +63,20 @@ test('under herdr a segment is cut so its page stays under 16 MiB of RGBA', () =
// A wide page on a Retina screen: 41 rows fit, 30 with the room for the rough count.
expect(herdrBudget(187, { width: 16, height: 34 })).toBe(30)
expect(herdrBudget(187, { width: 16, height: 34 }) * 34 * 2992 * 4 / 0.75).toBeLessThanOrEqual(HERDR_MAX_PAGE_BYTES)
- // A small page keeps the normal budget; a huge one at least 20 rows.
+ // A small page keeps the normal budget; a large one at least 20 rows, when 20 rows fit.
expect(herdrBudget(80, { width: 8, height: 16 })).toBe(SEGMENT_ROWS)
- expect(herdrBudget(255, { width: 40, height: 80 })).toBe(20)
+ expect(herdrBudget(255, { width: 20, height: 40 })).toBe(20)
+ // A huge cell: 20 rows would be 65 MiB (herdr sends none of it), so only the rows that fit.
+ expect(herdrBudget(255, { width: 40, height: 80 })).toBe(5)
+ expect(herdrBudget(255, { width: 400, height: 800 })).toBe(1)
+ // The budget never passes HERDR_MAX_PAGE_BYTES (a row of 16 MiB or more: 1 row).
+ for (const columns of [20, 80, 187, 255]) {
+ for (const width of [7, 16, 24, 32, 40, 60]) {
+ const px = { width, height: width * 2 }
+ const row = 4 * Math.round(columns * px.width) * px.height
+ if (row <= HERDR_MAX_PAGE_BYTES) expect(herdrBudget(columns, px) * row).toBeLessThanOrEqual(HERDR_MAX_PAGE_BYTES)
+ }
+ }
// The cell width counts as sizing rounds it.
expect(herdrBudget(100, { width: 15.5, height: 30 })).toBe(Math.floor((HERDR_MAX_PAGE_BYTES / (4 * 1550 * 30)) * 0.75))
})
diff --git a/tests/herdr-sh-test.sh b/tests/herdr-sh-test.sh
index 3d52292..da7aee3 100644
--- a/tests/herdr-sh-test.sh
+++ b/tests/herdr-sh-test.sh
@@ -3,9 +3,10 @@
# 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
+# prints on macOS the app in front (`front`, by lsappinfo; also with no
+# client), then each client's lines (its tty's access time, with a fraction
+# on macOS), its terminal app and of its variables only the terminal's
+# (CLIENT_NAMES: no other variable leaves the shell). 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)
@@ -86,8 +87,11 @@ cat > "$F/stat" <<EOF
16/24 500 /dev/ttys024
16/25 400 /dev/ttys025
EOF
-echo '/Users/u/.local/bin/herdr TERM=xterm-kitty KITTY_WINDOW_ID=1' > "$F/env-4999201"
-echo 'herdr TERM=xterm-ghostty TERM_PROGRAM=ghostty' > "$F/env-4999102"
+# Other variables (a token, a value with spaces) are cut out in the shell.
+echo '/Users/u/.local/bin/herdr TERM=xterm-kitty API_TOKEN=s3cret KITTY_WINDOW_ID=1 HOME=/Users/u' > "$F/env-4999201"
+echo 'herdr SECRET=a b TERM=xterm-ghostty ITERM_PROFILE=My Profile TERM_PROGRAM=ghostty PATH=/bin:/usr/bin' > "$F/env-4999102"
+# A line that does not start with the command (as envOfText: the first word is cut).
+echo 'herdr-x --y TERM=xterm-256color TOKEN=z' > "$F/env-4999205"
# The second server's socket peer is kitty's; this server's is Ghostty's.
cat > "$F/lsof" <<EOF
COMMAND PID USER FD TYPE DEVICE SIZE/OFF NODE NAME
@@ -117,7 +121,9 @@ for s in $shells; do
# 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)"
+ [ "$(block "$out" 4999102 | sed -n 7p)" = "herdr TERM=xterm-ghostty ITERM_PROFILE=My Profile TERM_PROGRAM=ghostty" ] && ok || bad "$s: Ghostty's variables ($out)"
+ [ "$(block "$out" 4999205 | sed -n 7p)" = "herdr --session work TERM=xterm-256color" ] && ok || bad "$s: the named session's variables ($out)"
+ case $out in *s3cret*|*SECRET*|*TOKEN*|*PATH=*|*HOME=*) bad "$s: other variables printed ($out)" ;; *) ok ;; esac
# 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.
@@ -140,15 +146,18 @@ for s in $shells; do
out=$(run)
[ "$(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.
+ # Two servers and this pane's not found: no client, only the app in front.
noself=1; front=com.mitchellh.ghostty; out=$(run); noself=; front=
- [ -z "$out" ] && ok || bad "$s: two servers, none above the shell, but output ($out)"
+ [ "$out" = "front com.mitchellh.ghostty" ] && ok || bad "$s: two servers, none above the shell, but clients ($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.
+ # No client (the only one left has no tty, a detached pane): the app in front only, 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" && front=com.mitchellh.ghostty run; echo "exit $?"; cp "$F/table.keep" "$F/table")
- [ "$out" = "exit 0" ] && ok || bad "$s: no client, but output ($out)"
+ [ "$out" = "front com.mitchellh.ghostty
+exit 0" ] && ok || bad "$s: no client, not the app in front only ($out)"
+ out=$(cp "$F/table" "$F/table.keep" && cp "$F/table.none" "$F/table" && run; echo "exit $?"; cp "$F/table.keep" "$F/table")
+ [ "$out" = "exit 0" ] && ok || bad "$s: no client and no app in front, but output ($out)"
# 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/"
@@ -157,6 +166,13 @@ for s in $shells; do
[ "$(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)"
+ # Linux with /proc/<pid>/environ (here under $L): only the terminal's variables, NUL-separated.
+ mkdir -p "$L/proc/4999201"
+ printf 'TERM=xterm-kitty\0API_TOKEN=s3cret\0KITTY_WINDOW_ID=1\0TERM_X=1\0HOME=/home/u\0' > "$L/proc/4999201/environ"
+ sed "s|/proc/|$L/proc/|g" "$tmp/client.sh" > "$tmp/client-proc.sh"
+ out=$(PATH=$bin FAKE=$L FAKE_OS=Linux NOTTY=? NOSELF= $s "$tmp/client-proc.sh" | tr '\0' '|')
+ [ "$(block "$out" 4999201 | sed -n 7p)" = "TERM=xterm-kitty|KITTY_WINDOW_ID=1|" ] && ok || bad "$s: Linux, kitty's /proc variables ($out)"
+ case $out in *s3cret*|*HOME=*|*TERM_X*) bad "$s: Linux, other variables printed ($out)" ;; *) ok ;; esac
done
# The light check: its own stat, which prints the format for each path in
diff --git a/tests/mode.test.ts b/tests/mode.test.ts
index 47f5570..b9fd8f1 100644
--- a/tests/mode.test.ts
+++ b/tests/mode.test.ts
@@ -1,5 +1,8 @@
import { expect, mock, test } from 'claude-code/testing'
+import { HERDR_CLIENT_SH, HERDR_TICK_SH } from '../hooks/register'
+import { S } from '../hooks/lib/state'
+
// Claude Code's theme on auto, on a Mac in light mode: the OS read gives light.
test('with the theme on auto, the mode comes from the OS appearance, read every 3 s', async ($, on) => {
mock.store(on)
@@ -169,104 +172,170 @@ test('with the theme on auto, herdr in iTerm2 draws as the iTerm2 profile is', a
expect(ran.text).toContain("terminal herdr (in iTerm2, from the server's start): ")
})
-// herdr answers OSC 11 with the background of the terminal in front: it is
-// the first source of auto. A missed answer (Claude Code read it) keeps the
-// last one until 3 polls in a row miss; then the terminal's config counts.
-test('with the theme on auto, herdr takes the OSC 11 background first, and keeps it over 2 missed answers', async ($, on) => {
- mock.store(on)
+// herdr in Ghostty (the server's variables), with pictures, the theme on
+// auto: `answers` are herdr's OSC 11 replies in turn ('' or none left: no
+// answer), `config` Ghostty's +show-config, `run` answers a command first.
+const herdrOk = (stdout: string, exitCode = 0) => ({ value: { exitCode, stdout, stderr: '', isStdoutTruncated: false, isStderrTruncated: false } })
+function herdrWorld(on: any, o: {
+ answers?: string[]
+ config?: () => string
+ env?: Record<string, string>
+ stored?: Record<string, unknown>
+ setting?: string
+ run?: (argv: string[]) => ReturnType<typeof herdrOk> | undefined
+}) {
+ S.keyAt = Number.NEGATIVE_INFINITY
+ mock.store(on, o.stored)
const clock = mock.clock(on)
- mock.env(on, { HOME: '/h', TERM_PROGRAM: 'herdr', HERDR_ENV: '1', TERM: 'xterm-256color', GHOSTTY_RESOURCES_DIR: '/R', CLAUDE_CODE_FORCE_TERMINAL_IMAGES: '1' })
- on('config.list', async () => ({ value: [{ key: 'theme', value: 'auto' }] as any }))
- const ok = (stdout: string, exitCode = 0) => ({ value: { exitCode, stdout, stderr: '', isStdoutTruncated: false, isStderrTruncated: false } })
- const answers = ['\x1b]11;rgb:ffff/ffff/ffff\x1b\\', '', '', '', '\x1b]11;rgb:ffff/ffff/ffff\x07', '']
- let probes = 0
+ mock.env(on, { HOME: '/h', TERM_PROGRAM: 'herdr', HERDR_ENV: '1', TERM: 'xterm-256color', GHOSTTY_RESOURCES_DIR: '/R', CLAUDE_CODE_FORCE_TERMINAL_IMAGES: '1', ...o.env })
+ on('config.list', async () => ({ value: [{ key: 'theme', value: o.setting ?? 'auto' }] as any }))
+ on('config.set', async ($: any, e: any) => ({ value: e.value }))
+ on('tool.call', { tool: 'AskUserQuestion' }, async () => ({ deny: 'dismissed' }))
+ on('prompt.edit', async ($: any, e: any) => ({ text: e.text + e.inputText, cursor: e.text.length + e.inputText.length }))
+ const w = { probes: 0, clock }
on('process.run', async ($: any, e: any, next: any) => {
const argv: string[] = e.argv
const cmd = argv.join(' ')
- if (argv[0] === 'sh' && /cc-intelligent-ui-/.test(cmd)) return ok('/tmp/mdp\nDarwin\n')
- if (argv[0] === 'perl' && cmd.includes('11;?')) return ok(answers[probes++] ?? '')
- if (argv[0] === 'sh' && cmd.includes('+show-config')) return ok('background = #1d1f21\n')
- if (argv[0] === 'defaults' && argv.includes('AppleInterfaceStyle')) return ok('', 1)
+ const own = o.run?.(argv)
+ if (own) return own
+ if (argv[0] === 'sh' && /cc-intelligent-ui-/.test(cmd)) return herdrOk('/tmp/mdp\nDarwin\n')
+ if (argv[0] === 'perl' && cmd.includes('11;?')) return herdrOk(o.answers?.[w.probes++] ?? '')
+ if (argv[0] === 'sh' && cmd.includes('+show-config')) return herdrOk(o.config?.() ?? 'background = #1d1f21\n')
+ if (argv[0] === 'defaults' && argv.includes('AppleInterfaceStyle')) return herdrOk('', 1)
return next(e)
})
- 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(1000)
- expect(await mode()).toContain(herdrLight)
- await clock.advance(3000)
- expect(await mode()).toContain(herdrLight)
- // The third in a row: Ghostty's config (dark).
- await clock.advance(3000)
- expect(await mode()).toContain('mode dark (auto, from Ghostty: config background)')
- await clock.advance(3000)
- expect(await mode()).toContain(herdrLight)
- expect(probes).toBe(5)
+ return w
+}
+const modeOf = async ($: any) => (await $.command.run({ command: 'iui', args: 'details' } as any)).text as string
+const typeKey = async ($: any) => ($ as any).prompt.edit({ origin: { kind: 'composer' }, text: '', cursor: 0, start: 0, end: 0, inputText: 'a' })
+const WHITE = '\x1b]11;rgb:ffff/ffff/ffff\x1b\\'
+const BLACK = '\x1b]11;rgb:0000/0000/0000\x07'
+const HERDR_LIGHT = 'mode light (auto, from herdr: OSC 11 background of the terminal in front)'
+
+// herdr answers OSC 11 with the background of the terminal in front: it is
+// the first source of auto. The probe reads the tty that Claude Code reads
+// (a key or a mouse report can go to it), so it runs at the start, not on
+// a timer: the answer stays while the terminal's config (or the OS) gives
+// the mode it gave then, and a change there wins.
+test('with the theme on auto, herdr asks OSC 11 at the start only, keeps the answer while the config stays, and follows a change of the config', async ($, on) => {
+ let config = 'background = #1d1f21\n'
+ const w = herdrWorld(on, { answers: [WHITE], config: () => config })
+ expect(await modeOf($)).toContain(HERDR_LIGHT)
+ expect(w.probes).toBe(1)
+ // No timed probe: 30 s of polls (each 1 s, the mode each 3 s) ask nothing.
+ await w.clock.advance(30000)
+ expect(w.probes).toBe(1)
+ expect(await modeOf($)).toContain(HERDR_LIGHT)
+ // Ghostty's config changes (a theme that follows the OS): it wins at the next mode read.
+ config = 'background = #fafafa\n'
+ await w.clock.advance(3000)
+ expect(await modeOf($)).toContain('mode light (auto, from Ghostty: config background)')
+ config = 'background = #1d1f21\n'
+ await w.clock.advance(3000)
+ expect(await modeOf($)).toContain('mode dark (auto, from Ghostty: config background)')
+ expect(w.probes).toBe(1)
})
-// The OSC 11 probe reads the pane's tty, as Claude Code does: a key typed
-// then can go to the probe. A timed probe waits for 2 s with no key in the
-// prompt, and none runs while the mod is off.
-test('under herdr, no timed OSC 11 probe just after a key in the prompt, nor with the mod off', async ($, on) => {
- mock.store(on)
- const clock = mock.clock(on)
- mock.env(on, { HOME: '/h', TERM_PROGRAM: 'herdr', HERDR_ENV: '1', TERM: 'xterm-256color', GHOSTTY_RESOURCES_DIR: '/R', CLAUDE_CODE_FORCE_TERMINAL_IMAGES: '1' })
- on('config.list', async () => ({ value: [{ key: 'theme', value: 'auto' }] as any }))
- const ok = (stdout: string, exitCode = 0) => ({ value: { exitCode, stdout, stderr: '', isStdoutTruncated: false, isStderrTruncated: false } })
- let probes = 0
- on('process.run', async ($: any, e: any, next: any) => {
- const argv: string[] = e.argv
- const cmd = argv.join(' ')
- if (argv[0] === 'sh' && /cc-intelligent-ui-/.test(cmd)) return ok('/tmp/mdp\nDarwin\n')
- if (argv[0] === 'perl' && cmd.includes('11;?')) return (probes++, ok('\x1b]11;rgb:ffff/ffff/ffff\x1b\\'))
- if (argv[0] === 'defaults' && argv.includes('AppleInterfaceStyle')) return ok('', 1)
- return next(e)
- })
- on('prompt.edit', async ($: any, e: any) => ({ text: e.text + e.inputText, cursor: e.text.length + e.inputText.length }))
- await $.command.run({ command: 'iui', args: '' } as any)
- expect(probes).toBe(1)
- // A key each 500 ms for 6 s: no timed probe.
- let text = ''
- for (let i = 0; i < 12; i++) {
- await ($ as any).prompt.edit({ origin: { kind: 'composer' }, text, cursor: text.length, start: text.length, end: text.length, inputText: 'a' })
- text += 'a'
- await clock.advance(500)
+// A missed answer (Claude Code read it): tried again at the next polls, 3 times at most.
+test('under herdr, a missed OSC 11 answer is asked at most 3 times, then the config counts', async ($, on) => {
+ const w = herdrWorld(on, { answers: [] })
+ expect(await modeOf($)).toContain('mode dark (auto, from Ghostty: config background)')
+ await w.clock.advance(10000)
+ expect(w.probes).toBe(3)
+ await w.clock.advance(20000)
+ expect(w.probes).toBe(3)
+ expect(await modeOf($)).toContain('mode dark (auto, from Ghostty: config background)')
+})
+
+// The start probe waits until 2 s pass with no key in the prompt box.
+test('under herdr, the start OSC 11 probe waits for 2 s with no key in the prompt', async ($, on) => {
+ try {
+ const w = herdrWorld(on, { answers: [WHITE] })
+ await typeKey($)
+ await w.clock.settle()
+ expect(await modeOf($)).toContain('mode dark (auto, from Ghostty: config background)')
+ expect(w.probes).toBe(0)
+ // A key each 500 ms for 6 s: no probe.
+ for (let i = 0; i < 12; i++) {
+ await typeKey($)
+ await w.clock.advance(500)
+ }
+ expect(w.probes).toBe(0)
+ // 2 s with no key: the next poll asks, once.
+ await w.clock.advance(3000)
+ expect(w.probes).toBe(1)
+ expect(await modeOf($)).toContain(HERDR_LIGHT)
+ await w.clock.advance(9000)
+ expect(w.probes).toBe(1)
+ } finally {
+ S.keyAt = Number.NEGATIVE_INFINITY
}
- expect(probes).toBe(1)
- // 2 s with no key: the next poll asks.
- await clock.advance(3000)
- expect(probes).toBe(2)
- // The mod off: none.
- await $.command.run({ command: 'iui', args: 'off' } as any)
- await clock.advance(9000)
- expect(probes).toBe(2)
+})
+
+// Where the mod draws no herdr pictures, or is off, or the theme was not
+// auto at the start (/config is a dialog: a key there is not seen), no probe.
+for (const [why, o] of [
+ ['Claude Code draws no pictures (setup not done)', { env: { CLAUDE_CODE_FORCE_TERMINAL_IMAGES: '' } }],
+ ['the mod is stored off', { stored: { enabled: false } }],
+] as const) {
+ test(`under herdr with the theme on auto, no OSC 11 probe when ${why}`, async ($, on) => {
+ try {
+ const w = herdrWorld(on, { answers: [WHITE], ...o })
+ await modeOf($)
+ await w.clock.advance(9000)
+ expect(w.probes).toBe(0)
+ expect(await modeOf($)).toContain('mode dark (auto, from Ghostty: config background)')
+ } finally {
+ S.isOff = false
+ }
+ })
+}
+
+test('under herdr, the theme set to auto later asks no OSC 11 (a dialog can be open), not even at the next polls', async ($, on) => {
+ const w = herdrWorld(on, { answers: [WHITE], setting: 'dark' })
+ await modeOf($)
+ await $.config.set({ key: 'theme', value: 'auto' } as any)
+ await w.clock.advance(9000)
+ expect(w.probes).toBe(0)
+ expect(await modeOf($)).toContain('mode dark (auto, from Ghostty: config background)')
+})
+
+// A new herdr client (another terminal in front) is asked again, once.
+test('under herdr, a new client in front is asked OSC 11 again, once', async ($, on) => {
+ const ghostty = '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 kitty = '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\n'
+ let front = 'com.mitchellh.ghostty'
+ const w = herdrWorld(on, {
+ answers: [BLACK, WHITE],
+ run: argv =>
+ argv[2] === HERDR_CLIENT_SH ? herdrOk(`front ${front}\n${ghostty}${kitty}`)
+ : argv[2] === HERDR_TICK_SH ? herdrOk(`front ${front}\n${argv.slice(5).map(tty => `atime ${tty} 10\n`).join('')}`)
+ : undefined,
+ })
+ expect(await modeOf($)).toContain('mode dark (auto, from herdr: OSC 11 background of the terminal in front)')
+ await w.clock.advance(5000)
+ expect(w.probes).toBe(1)
+ front = 'net.kovidgoyal.kitty'
+ await w.clock.advance(1000)
+ expect(w.probes).toBe(2)
+ expect(await modeOf($)).toContain(HERDR_LIGHT)
+ await w.clock.advance(9000)
+ expect(w.probes).toBe(2)
})
// herdr --remote: the pane is over ssh (the mod runs on the remote
-// computer), but herdr's OSC 11 answer is still the user's terminal.
-test('with the theme on auto, a remote herdr pane takes the OSC 11 background first, then COLORFGBG', async ($, on) => {
- mock.store(on)
- const clock = mock.clock(on)
- mock.env(on, { HOME: '/h', TERM_PROGRAM: 'herdr', HERDR_ENV: '1', TERM: 'xterm-256color', SSH_CONNECTION: '1 2 3 4', COLORFGBG: '0;15', CLAUDE_CODE_FORCE_TERMINAL_IMAGES: '1' })
- on('config.list', async () => ({ value: [{ key: 'theme', value: 'auto' }] as any }))
- const ok = (stdout: string, exitCode = 0) => ({ value: { exitCode, stdout, stderr: '', isStdoutTruncated: false, isStderrTruncated: false } })
- const answers = ['\x1b]11;rgb:0000/0000/0000\x1b\\']
- let probes = 0
- on('process.run', async ($: any, e: any, next: any) => {
- const argv: string[] = e.argv
- const cmd = argv.join(' ')
- if (argv[0] === 'sh' && /cc-intelligent-ui-/.test(cmd)) return ok('/tmp/mdp\nLinux\n')
- if (argv[0] === 'perl' && cmd.includes('11;?')) return ok(answers[probes++] ?? '')
- return next(e)
+// computer), but herdr's OSC 11 answer is still the user's terminal; it
+// stays while COLORFGBG (the only other source there) does not change.
+test('with the theme on auto, a remote herdr pane takes the OSC 11 background at the start, before COLORFGBG', async ($, on) => {
+ const w = herdrWorld(on, {
+ answers: [BLACK],
+ env: { GHOSTTY_RESOURCES_DIR: '', SSH_CONNECTION: '1 2 3 4', COLORFGBG: '0;15' },
+ run: argv => (argv[0] === 'sh' && /cc-intelligent-ui-/.test(argv.join(' ')) ? herdrOk('/tmp/mdp\nLinux\n') : undefined),
})
- const mode = async () => (await $.command.run({ command: 'iui', args: 'details' } as any)).text as string
- expect(await mode()).toContain('mode dark (auto, from herdr: OSC 11 background of the terminal in front)')
- await clock.advance(9000)
- expect(await mode()).toContain('mode light (auto, from COLORFGBG)')
+ expect(await modeOf($)).toContain('mode dark (auto, from herdr: OSC 11 background of the terminal in front)')
+ await w.clock.advance(9000)
+ expect(await modeOf($)).toContain('mode dark (auto, from herdr: OSC 11 background of the terminal in front)')
+ expect(w.probes).toBe(1)
})
// herdr with no hint of its terminal: as before, COLORFGBG, then the OS.
diff --git a/tests/termfont.test.ts b/tests/termfont.test.ts
index 75e7cda..c249b21 100644
--- a/tests/termfont.test.ts
+++ b/tests/termfont.test.ts
@@ -551,6 +551,54 @@ fontTest('herdr: a terminal in front with no known client makes a full scan at t
expect(await details($)).toContain('(in kitty, the terminal in front)')
})
+// A detached pane (no client attached): no light check (nothing to read)
+// and no full scan each second, whatever app is in front; the full scan
+// runs each HERDR_SCAN_MS. An old scan with no `front` line is the same.
+for (const scan of ['front com.mitchellh.ghostty\n', '']) {
+ fontTest(`herdr detached (no client${scan ? '' : ', no front line'}): one full scan each 10 s, no check each second`, async ($, on) => {
+ let front = 'com.mitchellh.ghostty'
+ const w = world(on, {
+ isMac: true,
+ env: HERDR_SERVER_ENV,
+ families: ['Iosevka'],
+ run: argv => clientIs(() => scan)(argv) ?? tickIs(() => front)(argv) ?? shows('font-family = Iosevka\n')(argv),
+ })
+ await details($)
+ const scanned = scansOf(w)
+ const ticks = () => w.ran.filter(argv => argv[2] === HERDR_TICK_SH).length
+ await w.clock.advance(3000)
+ // Another terminal comes in front: still no scan before the 10 s one.
+ front = 'net.kovidgoyal.kitty'
+ await w.clock.advance(HERDR_SCAN_MS - 4000)
+ expect(scansOf(w)).toBe(scanned)
+ await w.clock.advance(1000)
+ expect(scansOf(w)).toBe(scanned + 1)
+ expect(ticks()).toBe(0)
+ expect(await details($)).toContain("(in Ghostty, from the server's start)")
+ })
+}
+
+// The client scan reads other processes' variables: only while the mod is on and pictures show.
+pollTest('herdr, the mod stored off: no client scan at the start; /iui on scans', async ($, on) => {
+ const w = world(on, { isMac: true, env: HERDR_SERVER_ENV, families: ['Iosevka'], stored: { enabled: false }, run: argv => clientIs(() => ghosttyClient)(argv) ?? tickIs(() => null)(argv) ?? shows('font-family = Iosevka\n')(argv) })
+ expect(await details($)).toContain("(in Ghostty, from the server's start)")
+ await w.clock.advance(5000)
+ expect(scansOf(w)).toBe(0)
+ await $.command.run({ command: 'iui', args: 'on' } as any)
+ await w.clock.advance(1000)
+ expect(scansOf(w)).toBe(1)
+ expect(await details($)).toContain('(in Ghostty, the client you used last)')
+})
+
+pollTest('herdr with pictures off (setup not done): no client scan', async ($, on) => {
+ const { CLAUDE_CODE_FORCE_TERMINAL_IMAGES: _, ...env } = HERDR_SERVER_ENV
+ on('tool.call', { tool: 'AskUserQuestion' }, async () => ({ deny: 'dismissed' }))
+ const w = world(on, { isMac: true, env, families: ['Iosevka'], run: argv => clientIs(() => ghosttyClient)(argv) ?? tickIs(() => null)(argv) ?? shows('font-family = Iosevka\n')(argv) })
+ await details($)
+ await w.clock.advance(5000)
+ expect(scansOf(w)).toBe(0)
+})
+
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) => {
diff --git a/tests/terminals.test.ts b/tests/terminals.test.ts
index e939b8a..eebd5b5 100644
--- a/tests/terminals.test.ts
+++ b/tests/terminals.test.ts
@@ -2,7 +2,7 @@ import { expect, test } from 'claude-code/testing'
import {
cmuxAppearanceOf, cmuxConfigOf, cmuxGhosttyConfigPath, cmuxSettingsOf, envOfText, ghosttyBackgroundOf, ghosttyHasColors, ghosttyThemesOf, ghosttyValueOf,
- clientFrontKindOf, frontKindOf, herdrClientChanged, herdrClientOf, herdrClientsOf, herdrHostOf, herdrText, herdrTickOf, herdrTickPick, pickHerdrClient, ttyNameOf, type HerdrClient, 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_TRIES, outerKindOf, CLIENT_NAMES, HERDR_CLIENT_SH, 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,
@@ -362,22 +362,37 @@ test('a change of herdr client: another terminal, profile or config counts; anot
expect(herdrClientChanged(ghostty, { ...ghostty, env: { ...ghostty.env, COLORFGBG: '0;15' } })).toBe(true)
})
-test("herdr's OSC 11: a missed answer keeps the last one until OSC11_MISSES polls in a row miss", () => {
- expect(OSC11_MISSES).toBe(3)
+test("herdr's OSC 11: the answer stays while the other sources give the mode they gave when it came; a change there wins", () => {
+ expect(OSC11_TRIES).toBe(3)
const light: HostMode = { mode: 'light', source: 'herdr' }
const dark: HostMode = { mode: 'dark', source: 'herdr' }
+ const ghosttyDark: HostMode = { mode: 'dark', source: 'Ghostty' }
+ const ghosttyLight: HostMode = { mode: 'light', source: 'Ghostty' }
+ // No answer kept: the other sources (or none).
expect(keptOsc11(null, null)).toEqual({ kept: null, use: null })
- let step = keptOsc11(null, light)
- expect(step).toEqual({ kept: { seen: light, misses: 0 }, use: light })
- step = keptOsc11(step.kept, null)
- expect(step).toEqual({ kept: { seen: light, misses: 1 }, use: light })
- step = keptOsc11(step.kept, null)
- expect(step).toEqual({ kept: { seen: light, misses: 2 }, use: light })
- // The third miss in a row: the other sources count.
- expect(keptOsc11(step.kept, null)).toEqual({ kept: null, use: null })
- // An answer starts again from 0.
- step = keptOsc11(keptOsc11(step.kept, dark).kept, null)
- expect(step).toEqual({ kept: { seen: dark, misses: 1 }, use: dark })
+ expect(keptOsc11(null, ghosttyDark)).toEqual({ kept: null, use: ghosttyDark })
+ expect(keptOsc11(null, ghosttyDark, null)).toEqual({ kept: null, use: ghosttyDark })
+ // An answer wins over the config, and is kept with the config's mode then.
+ let step = keptOsc11(null, ghosttyDark, light)
+ expect(step).toEqual({ kept: { seen: light, base: 'dark' }, use: light })
+ // Reads with no probe: the config gives the same mode, so the answer stays.
+ step = keptOsc11(step.kept, ghosttyDark)
+ expect(step).toEqual({ kept: { seen: light, base: 'dark' }, use: light })
+ // A missed probe or a failed read changes nothing.
+ expect(keptOsc11(step.kept, ghosttyDark, null).use).toBe(light)
+ expect(keptOsc11(step.kept, null).use).toBe(light)
+ // The config (or the OS) changes: it wins, and the answer is dropped.
+ expect(keptOsc11(step.kept, ghosttyLight)).toEqual({ kept: null, use: ghosttyLight })
+ // An answer with no other source: the first mode read later is its reference.
+ step = keptOsc11(null, null, dark)
+ expect(step).toEqual({ kept: { seen: dark, base: null }, use: dark })
+ step = keptOsc11(step.kept, ghosttyLight)
+ expect(step).toEqual({ kept: { seen: dark, base: 'light' }, use: dark })
+ expect(keptOsc11(step.kept, ghosttyDark).use).toBe(ghosttyDark)
+})
+
+test("herdr's client scan prints of each client's variables only CLIENT_NAMES (the filter is in the shell)", () => {
+ expect(HERDR_CLIENT_SH).toContain(`e='${CLIENT_NAMES.join('|')}'`)
})
test('/iui setup is offered in iTerm2 on a Mac and in herdr (macOS or Linux), with pictures off, not in ssh, tmux, screen or a background session', () => {
@@ -563,7 +578,9 @@ test("herdr's light check: the pick on the clients of the last scan, else a full
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).
+ // No client at the scan (a detached pane): nothing to follow, and no scan before HERDR_SCAN_MS, whatever app 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()
+ expect(herdrTickPick({ clients: [], was: null, scanFront: null, ageMs: 1000, tick: tickOf('com.mitchellh.ghostty', {}) })).toEqual({ clients: [], pick: null })
+ expect(herdrTickPick({ clients: [], was: null, scanFront: 'com.apple.Safari', ageMs: 1000, tick: tickOf('net.kovidgoyal.kitty', {}) })).toEqual({ clients: [], pick: null })
+ expect(herdrTickPick({ clients: [], was: null, scanFront: null, ageMs: HERDR_SCAN_MS, tick: tickOf(null, {}) })).toBeNull()
})