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: the font and theme of the terminal you use now
razorback16466c8ae9404a
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex d2616f7..5bcac43 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -8,7 +8,7 @@ All releases of Intelligent UI for Claude Code (`cc-intelligent-ui`). Claude Cod- **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).- `/iui setup` works in herdr on Linux too.-- `/iui details` names herdr, its version and the terminal that it runs in, for example `herdr 0.9.5 (in Ghostty)`.+- `/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)`.### Changed@@ -17,7 +17,9 @@ All releases of Intelligent UI for Claude Code (`cc-intelligent-ui`). Claude Cod### Fixed-- In herdr, the mod now uses the font and the background of the terminal that herdr runs in (Ghostty, kitty or iTerm2). Before, it used Menlo and the OS appearance, so the text could be dark on a dark background.+- 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.- 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).## 0.3.2 (2026-10-21)diff --git a/docs/development.md b/docs/development.mdindex 56048d5..9e532d6 100644--- a/docs/development.md+++ b/docs/development.md@@ -14,6 +14,7 @@ sh tests/cache-sh-test.sh # the cache folder sweep (CACHE_SH) in sh, dash ash tests/fonts-sh-test.sh # the copy of a font out of a terminal's program (PROGRAM_FONTS_SH and _PL) with perlsh 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/herdr-sh-test.sh # the herdr client finder (HERDR_CLIENT_SH) with fake ps, stat and lsof, in sh, dash and bashclaude plugin validate .```diff --git a/docs/how-it-works.md b/docs/how-it-works.mdindex a99a7d3..9ce2438 100644--- a/docs/how-it-works.md+++ b/docs/how-it-works.md@@ -88,6 +88,10 @@ Claude Code finds the light or dark mode for `auto` by asking the terminal for iThe 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 finds that terminal from the variables that herdr keeps of the terminal that started the herdr server: `GHOSTTY_RESOURCES_DIR` or `GHOSTTY_BIN_DIR` for Ghostty, `KITTY_PID` or `KITTY_INSTALLATION_DIR` for kitty, `ITERM_PROFILE` for iTerm2. It then uses that terminal's sources above (and its font for the text size). If it finds none, it uses `COLORFGBG`, then the OS appearance.+In **herdr**, `TERM_PROGRAM` is `herdr`, so it does not name the terminal that herdr runs in. Intelligent UI does these steps:-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 does not use OSC 11 yet.+- **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.+- **Fallback:** if it finds no client, it uses the variables that herdr keeps of the terminal that started the herdr server: `CMUX_*` for cmux, `GHOSTTY_RESOURCES_DIR` or `GHOSTTY_BIN_DIR` for Ghostty, `KITTY_PID` or `KITTY_INSTALLATION_DIR` for kitty, `ITERM_PROFILE` for iTerm2. If it finds none, it uses `COLORFGBG`, then the OS appearance.++Intelligent UI checks every 3 s. After a change, each mode's pictures compile once. `/iui probe` asks the terminal for its background with OSC 11 (5 times) and shows the raw answers. This is a test of whether the answer can reach the mod. The 3 s check uses OSC 11 only in herdr.diff --git a/docs/install.md b/docs/install.mdindex 98cdf67..213de1f 100644--- a/docs/install.md+++ b/docs/install.md@@ -14,7 +14,8 @@- **kitty (0.28 or later), Ghostty and cmux (Ghostty inside, macOS only):** pictures work with no setting. kitty and Ghostty work on macOS and on Linux.- **iTerm2 3.6 or later (3.7.5 tested, macOS only):** Claude Code needs `CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1` when it starts. A mod cannot set it early enough. The first time the mod runs in iTerm2, it asks to add one line to your shell's start file (`~/.zshrc`, `~/.bash_profile` or a fish `conf.d` file). The line sets the variable in iTerm2 and herdr only, not in tmux or screen. Then close the tab, open a new iTerm2 tab, and start Claude Code there. You can also run `/iui setup` (undo: `/iui setup remove`).- **herdr (0.9.5 tested, in Ghostty):** herdr is a terminal multiplexer. It draws the pictures of its panes in the terminal that it runs in, so that terminal must show kitty pictures (kitty or Ghostty). Claude Code needs `CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1` in herdr too. The first time the mod runs in a herdr pane, it asks to add the same line to your shell's start file. If the file has the line of an older version (iTerm2 only), the mod asks to update it. Then close the pane, open a new herdr pane, and start Claude Code there. You can also run `/iui setup` (undo: `/iui setup remove`). herdr works on macOS and on Linux.- - herdr hides the name of the terminal that it runs in. The mod finds that terminal from 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). The mod then reads the font and the background of that terminal. If you attach to the herdr server from a different terminal, the font and the `auto` mode can be wrong. `/iui details` shows the terminal that the mod found, for example `herdr 0.9.5 (in Ghostty)`.+ - herdr hides the name of the terminal that it runs in. With the `auto` theme, the mod gets the background from herdr: herdr gives the background of the terminal in front. This also works with `herdr --remote`.+ - For the font, the mod finds the herdr client where you typed last. You can attach to one herdr server from more than one terminal (for example Ghostty and kitty). The mod reads the variables and the terminal app of that client, then reads the font of that terminal. When you type in a different terminal, the mod finds it at the next check (every 3 s) and draws the pictures again with that font. If the mod cannot find a client, it uses the variables that herdr keeps of the terminal that started the herdr server (`GHOSTTY_RESOURCES_DIR` for Ghostty, `KITTY_PID` for kitty, `ITERM_PROFILE` for iTerm2). `/iui details` shows the terminal and how the mod found it, for example `herdr 0.9.5 (in kitty, the client you used last)` or `herdr 0.9.5 (in Ghostty, from the server's start)`.- Pages are shorter in herdr, so that herdr can send each one to the terminal. Refer to [Limitations](limitations.md).- **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.diff --git a/docs/limitations.md b/docs/limitations.mdindex fe822aa..6d14b59 100644--- a/docs/limitations.md+++ b/docs/limitations.md@@ -58,5 +58,5 @@- **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. The mod finds the terminal that herdr runs in from the variables of the terminal that started the herdr server. If you attach from a different terminal, the font and the `auto` mode can be wrong.+- **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.- **`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.tsindex a25b55c..c59ed16 100644--- a/hooks/lib/env.ts+++ b/hooks/lib/env.ts@@ -9,11 +9,11 @@ import {import { DEFAULT_METRICS, refresh, S, type Env } from './state'import { resolveMode, settingOf } from './mode'import { isItermIn } from './terminals'-import { canDrawIn, herdrHostOf, isHerdrIn, isSet, needsSetup } from './terminal'+import { canDrawIn, isHerdrIn, isSet, needsSetup } from './terminal'import { claudeTmpOf } from './images'import { applyTheme } from './themes'import { registerCommand } from './command'-import { readHostMode, termFontOf, watchHost } from './host'+import { readHerdrClient, readHostMode, setOuter, termFontOf, watchHost } from './host'import { readFrame, setFrame, watchFrame } from './frame'import { offerSetup } from './setup'import { findClipWay } from './clipboard'@@ -69,24 +69,18 @@ export function setUp($: EngineInterface): Promise<Env> {S.hostOs = os.trim()S.termProgram = programS.termName = term- S.itermProfile = (await envGet($, 'ITERM_PROFILE')) || undefinedS.isHerdr = isHerdrIn({ program, herdrEnv: await envGet($, 'HERDR_ENV') })S.herdrVersion = S.isHerdr ? ((await envGet($, 'TERM_PROGRAM_VERSION')) ?? '').trim() : ''- S.herdrHost = S.isHerdr- ? herdrHostOf({- ghosttyResources: await envGet($, 'GHOSTTY_RESOURCES_DIR'),- ghosttyBin: await envGet($, 'GHOSTTY_BIN_DIR'),- kittyPid: await envGet($, 'KITTY_PID'),- kittyDir: await envGet($, 'KITTY_INSTALLATION_DIR'),- itermProfile: S.itermProfile,- })- : ''- S.isKitty = /kitty/i.test(term) || !!(await envGet($, 'KITTY_WINDOW_ID')) || !!(await envGet($, 'KITTY_PID')) || S.herdrHost === 'kitty'+ // Under herdr the client the user typed in last gives the terminal; else (none found) the server's variables.+ S.herdrClient = null+ S.osc11Kept = null+ if (S.isHerdr) await readHerdrClient($).catch(() => false)+ await setOuter($)S.isRemote = sshS.debug = isSet(await envGet($, 'IUI_DEBUG'))S.isIterm = isItermIn({program,- profile: S.itermProfile,+ profile: (await envGet($, 'ITERM_PROFILE')) || undefined,session: (await envGet($, 'ITERM_SESSION_ID')) || undefined,lcTerminal: (await envGet($, 'LC_TERMINAL')) || undefined,})@@ -100,8 +94,6 @@ export function setUp($: EngineInterface): Promise<Env> {background: (await envGet($, 'CLAUDE_CODE_SESSION_KIND')) === 'bg',})if (S.setupNeeded) void offerSetup($).catch(() => undefined)- S.isCmux = !!(await envGet($, 'CMUX_SURFACE_ID')) || !!(await envGet($, 'CMUX_WORKSPACE_ID')) || !!(await envGet($, 'CMUX_SOCKET_PATH'))- S.colorFgBg = (await envGet($, 'COLORFGBG')) ?? ''S.userFontPaths = (await envGet($, 'TYPST_FONT_PATHS')) ?? ''if (S.setting === 'auto') S.host = (await readHostMode($).catch(() => null)) ?? S.hostS.theme = resolveMode(S.setting, S.host)diff --git a/hooks/lib/host.ts b/hooks/lib/host.tsindex b5ab1d9..0943416 100644--- a/hooks/lib/host.ts+++ b/hooks/lib/host.ts@@ -7,7 +7,7 @@ import type { IuiTheme } from '../../types'import { CLIP_WAKE_MS, HOST_CHECK_MS, HOST_POLL_MS, MODES } from './settings'import { S } from './state'import { beginEpoch } from './epoch'-import { luminanceOf, modeOfColorFgBg, modeOfLuminance, modeOfMacAppearance, parseOsc11, resolveMode, schemeOfPortal, type HostMode } from './mode'+import { keptOsc11, luminanceOf, modeOfColorFgBg, modeOfLuminance, modeOfMacAppearance, parseOsc11, resolveMode, schemeOfPortal, type HostMode } from './mode'import {cmuxAppearanceOf, cmuxConfigOf, cmuxGhosttyConfigPath, cmuxSettingsOf, familyOfFc, GHOSTTY_DEFAULT_FONT, ghosttyBackgroundOf, ghosttyFontsOf, ghosttyHasColors,ghosttyThemePaths, ghosttyThemesOf,@@ -16,7 +16,8 @@ import {rioConfigDirOf, RIO_DEFAULT_FONT, RIO_OLD_FONT, rioFontOf, rioForcedOf, rioThemeNamesOf, rioThemePath, tomlStringsOf, type CmuxAppearance, type KittyEntries,} from './terminals'import { firstLine } from './markdown'-import { isGhosttyHere } from './terminal'+import { herdrClientChanged, herdrClientOf, herdrHostOf, isCmuxIn, isGhosttyHere, isGhosttyIn, isKittyIn, isRioIn, type OuterName } from './terminal'+import { refont } from './frame'import { clockEvery, envGet, fsExists, fsRead, processRun } from './api'// One tty size read: `rows cols xpixel ypixel` (TIOCGWINSZ); exit 1 with no tty.@@ -193,6 +194,50 @@ export const OSC11_PL = [export const USE_OSC11 = falseexport const PROBE_RUNS = 5export 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.+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) ;;+ *) 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" '+ $1 == "@" { at[$2] = $3; nm[$2] = $4; sub(/^\\/dev\\//, "", nm[$2]); next }+ { p = $1; pp[p] = $2; ty[p] = $4; x = $0; sub(/^ *[0-9]+ +[0-9]+ +[0-9]+ +[^ ]+ +/, "", x); cm[p] = x; if ($3 != me) next+ n = split(x, w, " "); b = w[1]; sub(/.*\\//, "", b); if (b != "herdr") next+ if (n == 2 && w[2] == "server") { srv[p] = 1; ns++; next }+ r = x; sub(/^[^ ]+ ?/, "", r); if ((ty[p] in at) && r ~ /^(--session[= ][^ ]+|session attach [^ ]+|client)?$/) cl[p] = 1 }+ END {+ q = self; for (j = 0; j < 64 && q > 1; j++) { if (q in srv) break; q = pp[q] }+ printf "srv\\t%d\\t%s\\n", ns, (q in srv) ? q : ""+ for (p in cl) {+ a = pp[p]; for (j = 0; j < 64 && a > 1 && ty[a] !~ /^[?-]+$/; j++) a = pp[a]+ printf "cl\\t%s\\t%s\\t%s\\t%s\\t%s\\n", at[ty[p]], p, nm[ty[p]], cm[p], (a > 1 ? cm[a] : "") } }')+n=$(printf '%s\\n' "$c" | awk -F '\\t' '$1 == "srv" { print $2 }')+v=$(printf '%s\\n' "$c" | awk -F '\\t' '$1 == "srv" { print $3 }')+l=$(printf '%s\\n' "$c" | grep '^cl')+[ -n "$l" ] || exit 0+if [ "\${n:-0}" -gt 1 ]; then+ [ -n "$v" ] || exit 0+ if command -v lsof >/dev/null 2>&1; then+ k=$(lsof -a -U -p "$v,$(printf '%s\\n' "$l" | cut -f3 | paste -sd, -)" 2>/dev/null | awk -v v="$v" '$2 == v { a[$6] = 1 } $NF ~ /^->0x/ { e[NR] = substr($NF, 3); o[NR] = $2 } END { for (i in e) { f = 1; if (e[i] in a) print o[i] } if (f) print "peers" }')+ 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`// 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@@ -258,7 +303,7 @@ async function installedFamily($: EngineInterface, isMac: boolean, family: strin// such font) or 'failed' (no program, or the copy failed).async function programFont($: EngineInterface, isMac: boolean, o: { tag: string; family: string; name: string; paths: readonly string[] }): Promise<'copied' | 'none' | 'failed'> {const argv = ['sh', '-c', PROGRAM_FONTS_SH, 'sh', perlFor(isMac), PROGRAM_FONTS_PL, o.tag, o.family, o.name, ...o.paths]- const made = await processRun($, argv, { timeoutMs: 10000 }).catch(() => null)+ const made = await processRun($, argv, { timeoutMs: 10000, ...ghosttyInit() }).catch(() => null)const dir = made?.exitCode === 0 ? firstLine(made.stdout) : ''// No copy now: an older folder (maybe gone) is not given to Typst.if (!dir) S.fontPaths = ''@@ -313,10 +358,59 @@ async function rioFont($: EngineInterface, isMac: boolean): Promise<string> {// there, so the setup question for iTerm2 is not asked).const isItermHere = () => S.isIterm || S.herdrHost === 'iterm'+// A variable of the terminal the user sees: under herdr the client's+// (S.herdrClient; not set there is not set), else this process's.+export function outerEnv($: EngineInterface, name: OuterName): Promise<string | undefined> {+ const client = S.herdrClient+ return client ? Promise.resolve(client.env[name] || undefined) : envGet($, name)+}+// GHOSTTY_SH and PROGRAM_FONTS_SH run the client's Ghostty under herdr ('': the PATH's).+const ghosttyInit = () => (S.herdrClient ? { env: { GHOSTTY_BIN_DIR: S.herdrClient.env.GHOSTTY_BIN_DIR ?? '' } } : {})++// The terminal values the font and mode readers use (S.itermProfile,+// S.colorFgBg, S.herdrHost, S.isKitty, S.isCmux): under herdr the client's+// when one is found, else this process's variables (under herdr: those of+// the terminal that started its server, the fallback).+export async function setOuter($: EngineInterface) {+ S.itermProfile = (await outerEnv($, 'ITERM_PROFILE')) || undefined+ S.colorFgBg = (await outerEnv($, 'COLORFGBG')) ?? ''+ const client = S.herdrClient+ if (client) {+ S.herdrHost = client.kind+ S.isKitty = client.kind === 'kitty'+ S.isCmux = client.kind === 'cmux'+ return+ }+ S.isCmux = isCmuxIn({ surface: await envGet($, 'CMUX_SURFACE_ID'), workspace: await envGet($, 'CMUX_WORKSPACE_ID'), socket: await envGet($, 'CMUX_SOCKET_PATH') })+ S.herdrHost = S.isHerdr+ ? herdrHostOf({+ cmux: S.isCmux,+ ghosttyResources: await envGet($, 'GHOSTTY_RESOURCES_DIR'),+ ghosttyBin: await envGet($, 'GHOSTTY_BIN_DIR'),+ kittyPid: await envGet($, 'KITTY_PID'),+ kittyDir: await envGet($, 'KITTY_INSTALLATION_DIR'),+ itermProfile: S.itermProfile,+ })+ : ''+ 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> {+ 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+ return changed+}+// The font that the terminal's own config or profile names.async function configFontOf($: EngineInterface, isMac: boolean): Promise<string> {if (isItermHere() && isMac) {- const profile = await envGet($, 'ITERM_PROFILE')+ const profile = S.itermProfileconst [marks, guid] = await Promise.all([processRun($, ['sh', '-c', ITERM_BOOKMARKS_SH], { timeoutMs: 5000 }).catch(() => null),processRun($, ['sh', '-c', ITERM_DEFAULT_SH], { timeoutMs: 5000 }).catch(() => null),@@ -329,7 +423,7 @@ async function configFontOf($: EngineInterface, isMac: boolean): Promise<string>return named?.exitCode === 0 ? firstLine(named.stdout) : ''}if (isGhosttyHere()) {- const shown = await processRun($, ['sh', '-c', GHOSTTY_SH], { timeoutMs: 5000 }).catch(() => null)+ const shown = await processRun($, ['sh', '-c', GHOSTTY_SH], { timeoutMs: 5000, ...ghosttyInit() }).catch(() => null)// cmux loads its own config after Ghostty's; +show-config does not read it.const own = S.isCmux ? ((await readText($, cmuxGhosttyConfigPath((await envGet($, 'HOME')) ?? ''))) ?? '') : ''return ghosttyFont($, isMac, ghosttyFontsOf(cmuxConfigOf(shown?.stdout ?? '', own)))@@ -360,7 +454,9 @@ 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); 2. the+// 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@@ -370,6 +466,12 @@ export async function readHostMode($: EngineInterface): Promise<HostMode | null>if (USE_OSC11) {const bg = parseOsc11((await probeOsc11($))?.reply ?? '')if (bg) return { mode: modeOfLuminance(luminanceOf(bg)), source: 'terminal', detail: 'OSC 11 background' }+ } 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)@@ -408,8 +510,8 @@ export async function probeOsc11($: EngineInterface): Promise<{ reply: string }// (in cmux, cmux's appearance). In cmux, cmux's own config is read as well;// herdr in Ghostty reads Ghostty's.async function readGhosttyMode($: EngineInterface): Promise<HostMode | null> {- if (!/ghostty/i.test(S.termProgram + S.termName) && S.herdrHost !== 'ghostty') return null- const got = await processRun($, ['sh', '-c', GHOSTTY_SH], { timeoutMs: HOST_CHECK_MS }).catch(() => null)+ if (!isGhosttyIn(S.termProgram, S.termName) && S.herdrHost !== 'ghostty' && S.herdrHost !== 'cmux') return null+ const got = await processRun($, ['sh', '-c', GHOSTTY_SH], { timeoutMs: HOST_CHECK_MS, ...ghosttyInit() }).catch(() => null)if (!got || got.exitCode !== 0) return nullconst home = (await envGet($, 'HOME')) ?? ''const own = S.isCmux ? ((await readText($, cmuxGhosttyConfigPath(home))) ?? '') : ''@@ -426,7 +528,7 @@ async function readGhosttyMode($: EngineInterface): Promise<HostMode | null> {const where = {xdgConfig: (await envGet($, 'XDG_CONFIG_HOME')) || undefined,home,- resources: (await envGet($, 'GHOSTTY_RESOURCES_DIR')) || undefined,+ resources: (await outerEnv($, 'GHOSTTY_RESOURCES_DIR')) || undefined,}for (const mode of MODES) {for (const path of ghosttyThemePaths(pair[mode], where)) {@@ -472,8 +574,8 @@ async function readCmuxAppearance($: EngineInterface, file?: CmuxAppearance): Prreturn mode ? { mode, appearance } : null}-// Rio sets TERM_PROGRAM=rio, and TERM=rio when its terminfo is installed.-const isRioHere = () => /^rio$/i.test(S.termProgram) || /^rio$/i.test(S.termName)+// Rio sets TERM_PROGRAM=rio, and TERM=rio when its terminfo is installed; or herdr in Rio.+const isRioHere = () => isRioIn(S.termProgram, S.termName) || S.herdrHost === 'rio'// A file's text, or null when it can't be read.export async function readText($: EngineInterface, path: string): Promise<string | null> {@@ -486,7 +588,7 @@ export async function readText($: EngineInterface, path: string): Promise<stringasync function readKittyConfig($: EngineInterface): Promise<{ dir: string; entries: KittyEntries; home: string }> {const home = (await envGet($, 'HOME')) ?? ''const dirs = kittyConfigDirsOf({- kittyDir: (await envGet($, 'KITTY_CONFIG_DIRECTORY')) || undefined,+ kittyDir: (await outerEnv($, 'KITTY_CONFIG_DIRECTORY')) || undefined,xdgConfig: (await envGet($, 'XDG_CONFIG_HOME')) || undefined,home,isMac: S.hostOs === 'Darwin',@@ -524,7 +626,7 @@ async function readKittyMode($: EngineInterface): Promise<HostMode | null> {// Rio's config folder and its config.toml's string values.async function readRioConfig($: EngineInterface): Promise<{ dir: string; config: Record<string, string> }> {const dir = rioConfigDirOf({- rioHome: (await envGet($, 'RIO_CONFIG_HOME')) || undefined,+ rioHome: (await outerEnv($, 'RIO_CONFIG_HOME')) || undefined,xdgConfig: (await envGet($, 'XDG_CONFIG_HOME')) || undefined,home: (await envGet($, 'HOME')) ?? '',isMac: S.hostOs === 'Darwin',@@ -588,16 +690,24 @@ async function readLinuxScheme($: EngineInterface): Promise<LinuxScheme | null>return scheme ? { scheme, source: 'GNOME' } : null}-// One read of the OS appearance (never two at once); a changed mode redraws.+// One poll (never two at once): under herdr the client first (another+// terminal sets the terminal values again, then the font and its metrics+// are read again), then with auto the mode. A changed mode or font redraws.export async function pollHost($: EngineInterface) {- if (S.checking || S.setting !== 'auto') return+ if (S.checking || (S.setting !== 'auto' && !S.isHerdr)) returnS.checking = true+ let refonted = falsetry {- S.host = (await readHostMode($).catch(() => null)) ?? S.host+ const moved = S.isHerdr && (await readHerdrClient($).catch(() => false))+ if (moved) await setOuter($)+ if (S.setting === 'auto') S.host = (await readHostMode($).catch(() => null)) ?? S.host+ if (moved) refonted = await refont($).catch(() => false)} finally {S.checking = false}- showMode($)+ if (!refonted) return showMode($)+ S.theme = resolveMode(S.setting, S.host)+ beginEpoch($)}// Draws in the mode the setting and the OS give, when it changed: a new@@ -609,15 +719,16 @@ export function showMode($: EngineInterface) {beginEpoch($)}-// Polls the OS appearance while the setting is auto, and only then.+// Polls while the setting is auto or under herdr (its client can change), and only then.export function watchHost($: EngineInterface) {- if (S.setting === 'auto' && !S.watch) {+ const wanted = S.setting === 'auto' || S.isHerdr+ if (wanted && !S.watch) {try {S.watch = clockEvery($, HOST_POLL_MS, () => void pollHost($).catch(() => undefined))} catch {S.watch = null}- } else if (S.setting !== 'auto' && S.watch) {+ } else if (!wanted && S.watch) {S.watch.cancel()S.watch = null}diff --git a/hooks/lib/mode.ts b/hooks/lib/mode.tsindex 135ea10..e1f3ba2 100644--- a/hooks/lib/mode.ts+++ b/hooks/lib/mode.ts@@ -21,7 +21,7 @@ export function settingOf(value: unknown): ThemeSetting {// The OS appearance, and where it was read.export type HostMode = {mode: IuiTheme- source: 'terminal' | 'iTerm2' | 'Ghostty' | 'cmux' | 'kitty' | 'Rio' | 'macOS' | 'GNOME' | 'desktop portal' | 'COLORFGBG'+ source: 'terminal' | 'herdr' | 'iTerm2' | 'Ghostty' | 'cmux' | 'kitty' | 'Rio' | 'macOS' | 'GNOME' | 'desktop portal' | 'COLORFGBG'detail?: string}@@ -90,6 +90,19 @@ 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 }+}+// Control characters shown as text (\e, \a, \xNN), for /iui probe.export const escapeControls = (text: string) =>text.replace(/[\x00-\x1f\x7f]/g, c => (c === '\x1b' ? '\\e' : c === '\x07' ? '\\a' : `\\x${c.charCodeAt(0).toString(16).padStart(2, '0')}`))diff --git a/hooks/lib/state.ts b/hooks/lib/state.tsindex 0a6cf05..e10b73f 100644--- a/hooks/lib/state.ts+++ b/hooks/lib/state.ts@@ -5,14 +5,14 @@ import type { EngineInterface } from 'claude-code'import type { IuiTheme } from '../../types'import type { ThemeInfo } from './themes'-import type { HostMode, ThemeSetting } from './mode'+import type { HostMode, Osc11Kept, ThemeSetting } from './mode'import type { PlanVerdict } from './plan'import type { Drawn } from './copy'import type { GridMetrics } from './grid'import type { Checked } from './updates'import type { ClipWay } from './clipboard'import type { PdfFacts, PixelBox } from './images'-import type { HerdrHost } from './terminal'+import type { HerdrClient, HerdrHost } from './terminal'import { DEFAULT_HEIGHT, DEFAULT_SIZE, DEFAULT_WIDTH, type Height, type Width } from './settings'import { invalidate } from './api'@@ -174,16 +174,21 @@ export const S = {termProgram: '',termName: '',itermProfile: undefined as string | undefined,- // kitty: TERM=xterm-kitty, or its KITTY_WINDOW_ID / KITTY_PID (set in setUp).+ // kitty: TERM=xterm-kitty, or its KITTY_WINDOW_ID / KITTY_PID (set in setUp; setOuter).isKitty: false,- // iTerm2 (isItermIn) and cmux (Ghostty inside, with its CMUX_* variables), set in setUp.+ // 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) and the terminal it runs in- // (herdrHostOf; '' outside herdr or not known), set in setUp.+ // 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).isHerdr: false,herdrVersion: '',+ herdrClient: null as HerdrClient | null,herdrHost: '' as HerdrHost,+ 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.fontPaths: '',diff --git a/hooks/lib/terminal.ts b/hooks/lib/terminal.tsindex 8f52162..1c77595 100644--- a/hooks/lib/terminal.ts+++ b/hooks/lib/terminal.ts@@ -2,6 +2,8 @@// 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 { isItermIn } from './terminals'+import type { EnvName } from './api'// The columns a picture takes: the viewport less the bullet, at most `width`// (`/iui width`; full: no cap) and IMAGE_MAX_COLUMNS, at least 20.@@ -48,7 +50,15 @@ export function sizeOf(stdout: string, padded = false): { rows: number; columns:// padding (iTerm2, kitty and WezTerm do not), and it draws its own font when// its config names none. herdr in Ghostty uses Ghostty's font and config (its// tty pixels are whole cells, so the round down changes nothing).-export const isGhosttyHere = () => /ghostty/i.test(S.termProgram + S.termName) || S.isCmux || S.herdrHost === 'ghostty'+export const isGhosttyHere = () => isGhosttyIn(S.termProgram, S.termName) || S.isCmux || S.herdrHost === 'ghostty'++// The terminals by their variables: Ghostty by TERM_PROGRAM or TERM; kitty+// by TERM=xterm-kitty, KITTY_WINDOW_ID or KITTY_PID; cmux by one of its+// CMUX_* variables; Rio by TERM_PROGRAM=rio or TERM=rio.+export const isGhosttyIn = (program: string, term: string) => /ghostty/i.test(program + term)+export const isKittyIn = (env: { term: string; windowId?: string; pid?: string }) => /kitty/i.test(env.term) || !!env.windowId || !!env.pid+export const isCmuxIn = (env: { surface?: string; workspace?: string; socket?: string }) => !!env.surface || !!env.workspace || !!env.socket+export const isRioIn = (program: string, term: string) => /^rio$/i.test(program) || /^rio$/i.test(term)// A set flag: anything but empty, 0, false, no or off.export const isSet = (value: string | undefined) => !!value && !/^(0|false|no|off)$/i.test(value.trim())@@ -61,21 +71,107 @@ export function isHerdrIn(env: { program: string; herdrEnv?: string }): booleanreturn isSet(env.herdrEnv)}-// The terminal herdr runs in, from the variables it keeps of the terminal-// that started its server (most often the one attached now): Ghostty's-// GHOSTTY_*_DIR, kitty's KITTY_PID or KITTY_INSTALLATION_DIR, iTerm2's-// ITERM_PROFILE; '' when none.-export type HerdrHost = 'ghostty' | 'kitty' | 'iterm' | ''-export function herdrHostOf(env: { ghosttyResources?: string; ghosttyBin?: string; kittyPid?: string; kittyDir?: string; itermProfile?: string }): HerdrHost {+// The terminal herdr runs in. From the variables it keeps of the terminal+// that started its server (the fallback, when no client is found): cmux's+// CMUX_*, Ghostty's GHOSTTY_*_DIR, kitty's KITTY_PID or+// KITTY_INSTALLATION_DIR, iTerm2's ITERM_PROFILE; '' when none.+export type HerdrHost = 'ghostty' | 'cmux' | 'kitty' | 'iterm' | 'rio' | ''+export function herdrHostOf(env: { cmux?: boolean; ghosttyResources?: string; ghosttyBin?: string; kittyPid?: string; kittyDir?: string; itermProfile?: string }): HerdrHost {+ if (env.cmux) return 'cmux'if (env.ghosttyResources || env.ghosttyBin) return 'ghostty'if (env.kittyPid || env.kittyDir) return 'kitty'if (env.itermProfile) return 'iterm'return ''}-const HERDR_HOSTS = { ghostty: 'Ghostty', kitty: 'kitty', iterm: 'iTerm2' } as const-// herdr in /iui details: `herdr 0.9.5 (in Ghostty)`.-export const herdrText = (version: string, host: HerdrHost) =>- `herdr${version ? ` ${version}` : ''} (${host ? `in ${HERDR_HOSTS[host]}` : 'outer terminal not known'})`++// The variables of the terminal the user sees that the font and mode+// readers use (host.ts outerEnv): under herdr, the client's.+export const OUTER_NAMES = ['COLORFGBG', 'GHOSTTY_BIN_DIR', 'GHOSTTY_RESOURCES_DIR', 'ITERM_PROFILE', 'KITTY_CONFIG_DIRECTORY', 'RIO_CONFIG_HOME'] as const satisfies readonly EnvName[]+export type OuterName = (typeof OUTER_NAMES)[number]++// A herdr client (HERDR_CLIENT_SH): its pid, its tty and the tty's access+// time (the last key typed there), its command, the nearest ancestor with no+// tty (the terminal app), its variables and the terminal they give.+export type HerdrClient = { pid: number; atime: number; tty: string; cmd: string; app: string; env: Record<string, string>; kind: HerdrHost }++// The terminal of a client: by its terminal app's path first (a variable+// can come from another terminal that started this one), then by TERM,+// TERM_PROGRAM (another one, as WezTerm's: not known) and the variables of+// kitty, cmux, Ghostty and iTerm2.+export function outerKindOf(env: Readonly<Record<string, string>>, app: string): HerdrHost {+ // The program: an app bundle's path (its folders can hold spaces), else the first word.+ const path = /^\S*(?: [^ /-][^ ]*)*?\.app\/\S*/.exec(app)?.[0] ?? app.split(' ')[0] ?? ''+ if (/cmux/i.test(path)) return 'cmux'+ if (/ghostty/i.test(path)) return 'ghostty'+ if (/kitty/i.test(path)) return 'kitty'+ if (/iterm/i.test(path)) return 'iterm'+ if (/(^|\/)rio(\.app)?(\/|$)/i.test(path)) return 'rio'+ const program = env.TERM_PROGRAM ?? ''+ const term = env.TERM ?? ''+ const cmux = isCmuxIn({ surface: env.CMUX_SURFACE_ID, workspace: env.CMUX_WORKSPACE_ID, socket: env.CMUX_SOCKET_PATH })+ if (/kitty/i.test(term)) return 'kitty'+ if (isGhosttyIn(program, term)) return cmux ? 'cmux' : 'ghostty'+ if (isRioIn(program, term)) return 'rio'+ if (isItermIn({ program, profile: env.ITERM_PROFILE, session: env.ITERM_SESSION_ID, lcTerminal: env.LC_TERMINAL })) return 'iterm'+ if (program) return ''+ if (isKittyIn({ term, windowId: env.KITTY_WINDOW_ID, pid: env.KITTY_PID })) return 'kitty'+ return herdrHostOf({ cmux, ghosttyResources: env.GHOSTTY_RESOURCES_DIR, ghosttyBin: env.GHOSTTY_BIN_DIR, kittyDir: env.KITTY_INSTALLATION_DIR, itermProfile: env.ITERM_PROFILE })+}++// The variables of a process: NUL-separated (Linux /proc/<pid>/environ), or+// as macOS `ps eww` prints them: its command (`cmd`, as ps prints it with no+// variables), then `NAME=value` words. A value can hold spaces (an iTerm2+// profile name), so a word starts only where a `NAME=` follows a space.+export function envOfText(text: string, cmd: string): Record<string, string> {+ const env: Record<string, string> = {}+ let words: string[]+ if (text.includes('\0')) words = text.split('\0')+ else {+ const line = text.replace(/\n+$/, '')+ const bare = !!cmd && (line === cmd || line.startsWith(`${cmd} `))+ words = (bare ? line.slice(cmd.length) : line).split(/ (?=[A-Za-z_][A-Za-z0-9_]*=)/)+ // Not known where the command ends: its first word is not a variable.+ if (!bare) words.shift()+ }+ for (const word of words) {+ const m = /^([A-Za-z_][A-Za-z0-9_]*)=([\s\S]*)$/.exec(word)+ if (m) env[m[1]!] = m[2]!+ }+ return env+}++// HERDR_CLIENT_SH's output (`pid`, `atime`, `tty`, `cmd` and `app` lines,+// then `env` and the variables) as a client; null for none. Ghostty with no+// GHOSTTY_BIN_DIR gets its app's folder (GHOSTTY_SH runs that ghostty).+export function herdrClientOf(stdout: string): HerdrClient | null {+ const at = stdout.indexOf('\nenv\n')+ if (at < 0) return null+ const head = stdout.slice(0, at).split('\n')+ const field = (name: string) => head.find(line => line.startsWith(`${name} `))?.slice(name.length + 1).trim() ?? ''+ const pid = Number(field('pid'))+ if (!Number.isInteger(pid) || pid <= 0) return null+ const cmd = field('cmd')+ const app = field('app')+ const env = envOfText(stdout.slice(at + 5), cmd)+ const kind = outerKindOf(env, app)+ const bin = /^(.*)\/ghostty(?= |$)/.exec(app)?.[1]+ if (kind === 'ghostty' && !env.GHOSTTY_BIN_DIR && bin) env.GHOSTTY_BIN_DIR = bin+ return { pid, atime: Number(field('atime')) || 0, tty: field('tty'), cmd, app, env, kind }+}++// 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)++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).+export type HerdrFrom = 'client' | 'server'+export const herdrText = (version: string, host: HerdrHost, from: HerdrFrom = 'server') =>+ `herdr${version ? ` ${version}` : ''} (${+ host ? `in ${HERDR_HOSTS[host]}, ${from === 'client' ? 'the client you used last' : "from the server's start"}` : 'outer terminal not known'+ })`// Whether /iui setup can turn pictures on: they are off, and this is iTerm2// on a Mac or herdr (macOS or Linux), not over ssh, tmux, screen or adiff --git a/hooks/register.tsx b/hooks/register.tsxindex ac9431f..d46342b 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, OSC11_PL, perlFor, PROGRAM_FONTS_PL, PROGRAM_FONTS_SH, WATCH_PL } from './lib/host'+export { fcPatternOf, HERDR_CLIENT_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'@@ -827,8 +827,8 @@ export const register: Register = on => {: S.isHerdr && S.setupNeeded? 'Claude Code draws no pictures in herdr until CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1 is set when it starts (run /iui setup), so answers stay text': 'Claude Code draws no pictures here (it does in kitty and Ghostty, in iTerm2 3.6+, Rio 0.5.27+ and herdr with CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1, over ssh when TERM names kitty or Ghostty or with that variable; never in tmux, screen or a background session; not in WezTerm, Warp, Konsole or others), so answers stay text'- // In herdr: its version and the terminal it runs in.- const herdr = S.isHerdr ? `terminal ${herdrText(S.herdrVersion, S.herdrHost)}: ` : ''+ // In herdr: its version, the terminal it runs in and where that came from.+ const herdr = S.isHerdr ? `terminal ${herdrText(S.herdrVersion, S.herdrHost, S.herdrClient ? 'client' : 'server')}: ` : ''await clipWayReady()const auto = `Picture select: ${selectState()}\n/iui grab hint: ${hintOf(state === 'on')}`const updates = `Update checks: ${updateLine(await updateState($))}`diff --git a/tests/herdr-sh-test.sh b/tests/herdr-sh-test.shnew file mode 100644index 0000000..8af2c3e--- /dev/null+++ b/tests/herdr-sh-test.sh@@ -0,0 +1,138 @@+#!/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.+# Usage: sh tests/herdr-sh-test.sh (exit 0 when all pass)+set -u+here=$(cd "$(dirname "$0")/.." && pwd)+tmp=$(mktemp -d "${TMPDIR:-/tmp}/iui-herdr-test.XXXXXX")+trap 'rm -rf "$tmp"' EXIT+pass=0+fail=0+ok() { pass=$((pass + 1)); }+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"++uid=$(id -u)+realps=$(command -v ps)+bin=$tmp/bin+mkdir -p "$bin"+# Only these tools (so lsof is there only when a test puts it there).+for t in awk sed grep cut paste id cat tr; do ln -s "$(command -v "$t")" "$bin/$t"; done+# ps: `eww` prints $FAKE/env-<pid>; else the table, with this shell (the+# caller of ps, or the caller's caller) under the pane's claude (pid 4999900).+cat > "$bin/ps" <<EOF+#!/bin/sh+case "\$*" in *eww*) for p; do :; done; cat "\$FAKE/env-\$p" 2>/dev/null; exit 0 ;; esac+if [ -z "\${NOSELF:-}" ]; then+ up=\$($realps -o ppid= -p \$PPID | tr -d ' ')+ echo "\$PPID \$up $uid \$NOTTY sh"+ echo "\$up 4999900 $uid \$NOTTY sh"+fi+cat "\$FAKE/table"+EOF+printf '#!/bin/sh\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"; }++# 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+# user's), and two clients of a named session.+F=$tmp/mac+mkdir -p "$F"+cat > "$F/table" <<EOF+4999700 1 $uid ?? /Users/u/.local/bin/herdr server+4999800 4999700 $uid 16/14 -zsh+4999900 4999800 $uid 16/14 claude+4999100 1 $uid ?? /Applications/Ghostty.app/Contents/MacOS/ghostty -e /Users/u/.local/bin/herdr+4999101 4999100 0 16/12 /usr/bin/login -flp u /Users/u/.local/bin/herdr+4999102 4999101 $uid 16/12 herdr+4999200 1 $uid ?? /Applications/kitty.app/Contents/MacOS/kitty /Users/u/.local/bin/herdr+4999201 4999200 $uid 16/21 /Users/u/.local/bin/herdr+4999202 4999200 $uid 16/22 herdr pane list+4999203 4999200 $uid ?? herdr+4999204 4999200 1234567 16/23 herdr+4999205 4999200 $uid 16/24 herdr --session work+4999206 4999200 $uid 16/25 herdr session attach work+EOF+cat > "$F/stat" <<EOF+16/12 1000 /dev/ttys012+16/14 9999 /dev/ttys014+16/21 2000 /dev/ttys021+16/22 9999 /dev/ttys022+16/23 9999 /dev/ttys023+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"+# 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+herdr 4999102 u 4u unix 0xaaa1 0t0 ->0x5001+herdr 4999201 u 4u unix 0xbbb1 0t0 ->0x6001+herdr 4999700 u 4u unix 0x9001 0t0 /Users/u/.config/herdr/herdr.sock+herdr 4999700 u 30u unix 0x5001 0t0 /Users/u/.config/herdr/herdr-client.sock+EOF++shells=+for s in sh dash bash; do command -v "$s" >/dev/null 2>&1 && shells="$shells $s"; done+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"; }+ noself=+ 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"+ 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.+ 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)"+ # 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)"+ # 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)"+ mv "$F/lsof.keep" "$F/lsof"+ # Two servers and this pane's not found: nothing.+ noself=1; out=$(run); noself=+ [ -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" = "exit 0" ] && ok || bad "$s: no client, but output ($out)"+ # Linux: tty names (pts/N), stat -c, no tty is ?.+ 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)"+done++echo "herdr-sh-test: $pass passed, $fail failed (shells:$shells)"+[ "$fail" = 0 ]diff --git a/tests/mode.test.ts b/tests/mode.test.tsindex c6048a7..e1b2927 100644--- a/tests/mode.test.ts+++ b/tests/mode.test.ts@@ -166,7 +166,66 @@ test('with the theme on auto, herdr in iTerm2 draws as the iTerm2 profile is', a})const ran = await $.command.run({ command: 'iui', args: 'details' } as any)expect(ran.text).toContain('mode dark (auto, from iTerm2: profile Default background)')- expect(ran.text).toContain('terminal herdr (in iTerm2): ')+ 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)+ 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+ 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)+ 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)+ // Two polls with no answer: the last answer stays.+ await clock.advance(3000)+ 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)+})++// 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)+ })+ 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)')})// herdr with no hint of its terminal: as before, COLORFGBG, then the OS.diff --git a/tests/termfont.test.ts b/tests/termfont.test.tsindex 196d260..46cf166 100644--- a/tests/termfont.test.ts+++ b/tests/termfont.test.ts@@ -1,6 +1,6 @@import { expect, mock, test } from 'claude-code/testing'-import { fcPatternOf, KITTY_MAC_FONT, PROGRAM_FONTS_PL, PROGRAM_FONTS_SH, RIO_DEFAULT_FONT, RIO_OLD_FONT } from '../hooks/register'+import { fcPatternOf, HERDR_CLIENT_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'// The terminal font that the pictures use: the one the terminal draws. A@@ -16,7 +16,7 @@ const loose = (s: string) => s.replace(/\\(.)/g, '$1').replace(/\s/g, '').toLowe// The argument after the one that holds `marker` (a script's first argument).const argAfter = (argv: string[], marker: string) => argv[argv.findIndex(a => a.includes(marker)) + 1] ?? ''-type World = { ran: string[][]; fontPaths: string[]; copies: () => string[][] }+type World = { ran: string[][]; envs: (Record<string, string> | undefined)[]; fontPaths: string[]; copies: () => string[][]; clock: ReturnType<typeof mock.clock> }// A Mac or Linux with Typst. `run` answers a command first (undefined: the// world's answer); `families` are the installed ones (CoreText or// fontconfig), `proportional` those of them with no fixed-pitch style,@@ -38,9 +38,10 @@ function world(on: any, o: {}): World {S.fontPaths = ''mock.store(on)- mock.clock(on)+ const clock = mock.clock(on)mock.env(on, { HOME: '/h', ...o.env })const ran: string[][] = []+ const envs: (Record<string, string> | undefined)[] = []const fontPaths: string[] = []const families = o.families ?? []const nearest = o.nearest ?? 'DejaVu Sans Mono'@@ -48,6 +49,7 @@ function world(on: any, o: {const argv: string[] = e.argvconst cmd = argv.join(' ')ran.push(argv)+ envs.push(e.init?.env)const own = o.run?.(argv)if (own) return ownif (/cc-intelligent-ui-/.test(cmd)) return ok(`/c\n${o.isMac ? 'Darwin' : 'Linux'}\n/h/.cache/cc-intelligent-ui/designs\n`)@@ -83,7 +85,7 @@ function world(on: any, o: {const files = o.files ?? {}on('fs.read', async ($: any, e: any, next: any) => (e.path in files ? { value: files[e.path] } : e.path.startsWith('/h/') || e.path.startsWith('/c/') ? { deny: 'ENOENT' } : next(e)))on('fs.exists', async ($: any, e: any, next: any) => (e.path.startsWith('/h/') ? { value: e.path in files } : e.path === '/usr/bin/typst' ? { value: true } : next(e)))- return { ran, fontPaths, copies: () => ran.filter(argv => argv.includes(PROGRAM_FONTS_SH)) }+ return { ran, fontPaths, copies: () => ran.filter(argv => argv.includes(PROGRAM_FONTS_SH)), clock, envs }}const details = async ($: any) => (await $.command.run({ command: 'iui', args: 'details' } as any)).text as string// A test that leaves S.fontPaths empty after it (pure.test.ts expects it so).@@ -226,7 +228,7 @@ fontTest("herdr in Ghostty (GHOSTTY_RESOURCES_DIR kept): Ghostty's font-family;})const text = await details($)expect(text).toContain('terminal font Iosevka.')- expect(text).toContain('terminal herdr 0.9.5 (in Ghostty): this terminal draws pictures.')+ expect(text).toContain("terminal herdr 0.9.5 (in Ghostty, from the server's start): this terminal draws pictures.")})fontTest("herdr in kitty (KITTY_INSTALLATION_DIR kept): kitty's font_family", async ($, on) => {@@ -238,7 +240,7 @@ fontTest("herdr in kitty (KITTY_INSTALLATION_DIR kept): kitty's font_family", as})const text = await details($)expect(text).toContain('terminal font Iosevka.')- expect(text).toContain('terminal herdr (in kitty): ')+ expect(text).toContain("terminal herdr (in kitty, from the server's start): ")})fontTest('herdr in a terminal it does not know: no font, as before; the details say so', async ($, on) => {@@ -254,7 +256,73 @@ fontTest('herdr with pictures off: the details point to /iui setup', async ($, o// The setup question (pictures are off in herdr) is dismissed.on('tool.call', { tool: 'AskUserQuestion' }, async () => ({ deny: 'dismissed' }))const text = await details($)- expect(text).toContain('terminal herdr (in Ghostty): Claude Code draws no pictures in herdr until CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1 is set when it starts (run /iui setup)')+ expect(text).toContain("terminal herdr (in Ghostty, from the server's start): Claude Code draws no pictures in herdr until CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1 is set when it starts (run /iui setup)")+})++// The herdr client the user typed in last (HERDR_CLIENT_SH's output): the+// server was started from Ghostty (its variables are in the pane), the+// client is kitty or Ghostty.+const HERDR_SERVER_ENV = { TERM_PROGRAM: 'herdr', TERM_PROGRAM_VERSION: '0.9.5', HERDR_ENV: '1', TERM: 'xterm-256color', GHOSTTY_RESOURCES_DIR: '/R', GHOSTTY_BIN_DIR: '/B', CLAUDE_CODE_FORCE_TERMINAL_IMAGES: '1' }+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)++fontTest("herdr: the client you typed in last (kitty) wins over the server's variables (Ghostty)", async ($, on) => {+ 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(() => kittyClient)(argv) ?? shows('font-family = Iosevka\n')(argv),+ })+ const text = await details($)+ expect(text).toContain('terminal font Fira Code.')+ expect(text).toContain('terminal herdr 0.9.5 (in kitty, the client you used last): this terminal draws pictures.')+ expect(w.ran.some(argv => argv.join(' ').includes('+show-config'))).toBe(false)+})++fontTest("herdr: no client found (the check fails): the server's variables, as before", async ($, on) => {+ world(on, {+ isMac: true,+ env: HERDR_SERVER_ENV,+ families: ['Iosevka'],+ run: argv => (argv[2] === HERDR_CLIENT_SH ? ok('', 1) : shows('font-family = Iosevka\n')(argv)),+ })+ const text = await details($)+ expect(text).toContain('terminal font Iosevka.')+ expect(text).toContain("terminal herdr 0.9.5 (in Ghostty, from the server's start): ")+})++fontTest("herdr in Ghostty: Ghostty's +show-config runs with the client's GHOSTTY_BIN_DIR", async ($, on) => {+ const w = world(on, { isMac: true, env: HERDR_SERVER_ENV, families: ['Iosevka'], run: argv => clientIs(() => ghosttyClient)(argv) ?? shows('font-family = Iosevka\n')(argv) })+ expect(await details($)).toContain('terminal font Iosevka.')+ const seen = w.ran.flatMap((argv, i) => (argv.join(' ').includes('+show-config') ? [w.envs[i]?.GHOSTTY_BIN_DIR] : []))+ expect(seen.length).toBeGreaterThan(0)+ 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) => {+ 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),+ })+ 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.+ await w.clock.advance(3000)+ expect(w.fontPaths.length).toBe(measured)+ client = kittyClient+ await w.clock.advance(3000)+ 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)})// ---- kitty ----------------------------------------------------------------------diff --git a/tests/terminals.test.ts b/tests/terminals.test.tsindex cb35d89..c4ccaf0 100644--- a/tests/terminals.test.ts+++ b/tests/terminals.test.ts@@ -1,8 +1,8 @@import { expect, test } from 'claude-code/testing'import {- cmuxAppearanceOf, cmuxConfigOf, cmuxGhosttyConfigPath, cmuxSettingsOf, ghosttyBackgroundOf, ghosttyHasColors, ghosttyThemesOf, ghosttyValueOf, herdrHostOf, herdrText,- isHerdrIn, isItermIn, jsoncOf, needsSetup,+ cmuxAppearanceOf, cmuxConfigOf, cmuxGhosttyConfigPath, cmuxSettingsOf, envOfText, ghosttyBackgroundOf, ghosttyHasColors, ghosttyThemesOf, ghosttyValueOf,+ herdrClientChanged, herdrClientOf, herdrHostOf, herdrText, 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,@@ -235,13 +235,137 @@ test("herdr's terminal: Ghostty, then kitty, then iTerm2, by the variables of thexpect(herdrHostOf({ ghosttyResources: '', kittyPid: '', itermProfile: '' })).toBe('')})-test('herdr in /iui details: its version and its terminal', () => {- expect(herdrText('0.9.5', 'ghostty')).toBe('herdr 0.9.5 (in Ghostty)')- expect(herdrText('0.9.5', 'kitty')).toBe('herdr 0.9.5 (in kitty)')- expect(herdrText('', 'iterm')).toBe('herdr (in iTerm2)')+test('herdr in /iui details: its version, its terminal and where that came from', () => {+ expect(herdrText('0.9.5', 'kitty', 'client')).toBe('herdr 0.9.5 (in kitty, the client you used last)')+ expect(herdrText('0.9.5', 'ghostty')).toBe("herdr 0.9.5 (in Ghostty, from the server's start)")+ expect(herdrText('0.9.5', 'ghostty', 'server')).toBe("herdr 0.9.5 (in Ghostty, from the server's start)")+ 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('', '', 'client')).toBe('herdr (outer terminal not known)')expect(herdrText('', '')).toBe('herdr (outer terminal not known)')})+test("herdr's terminal from the server's variables: cmux first", () => {+ expect(herdrHostOf({ cmux: true, ghosttyResources: '/g' })).toBe('cmux')+ expect(herdrHostOf({ cmux: false, ghosttyResources: '/g' })).toBe('ghostty')+})++// The output of HERDR_CLIENT_SH, as measured on a Mac (kitty and Ghostty+// clients of one herdr server) and on Linux.+const KITTY_MAC = [+ 'pid 54346', 'atime 1792712692', 'tty ttys021', 'cmd /Users/u/.local/bin/herdr',+ 'app /Applications/kitty.app/Contents/MacOS/kitty /Users/u/.local/bin/herdr', 'env',+ '/Users/u/.local/bin/herdr USER=u __CFBundleIdentifier=net.kovidgoyal.kitty PATH=/Applications/kitty.app/Contents/MacOS:/usr/bin:/bin HOME=/Users/u ' ++ 'SHELL=/bin/zsh LANG=en_US.UTF-8 KITTY_WINDOW_ID=1 TERM=xterm-kitty COLORTERM=truecolor KITTY_PID=54120 ' ++ 'KITTY_INSTALLATION_DIR=/Applications/kitty.app/Contents/Resources/kitty',+ '',+].join('\n')+const GHOSTTY_MAC = [+ 'pid 50390', 'atime 1792712644', 'tty ttys012', 'cmd herdr', 'app /Applications/Ghostty.app/Contents/MacOS/ghostty -e /Users/u/.local/bin/herdr', 'env',+ 'herdr USER=u GHOSTTY_BIN_DIR=/Applications/Ghostty.app/Contents/MacOS TERM=xterm-ghostty TERM_PROGRAM=ghostty TERM_PROGRAM_VERSION=1.3.1 ' ++ 'GHOSTTY_RESOURCES_DIR=/Applications/Ghostty.app/Contents/Resources/ghostty COLORFGBG=15;0',+ '',+].join('\n')++test('a herdr client on macOS (ps eww): its command is not a variable, its variables are whole', () => {+ const kitty = herdrClientOf(KITTY_MAC)!+ expect(kitty).toMatchObject({ pid: 54346, atime: 1792712692, tty: 'ttys021', cmd: '/Users/u/.local/bin/herdr', kind: 'kitty' })+ expect(kitty.env.TERM).toBe('xterm-kitty')+ expect(kitty.env.KITTY_INSTALLATION_DIR).toBe('/Applications/kitty.app/Contents/Resources/kitty')+ expect(kitty.env.USER).toBe('u')+ expect(Object.keys(kitty.env).some(k => k.includes('herdr'))).toBe(false)+ const ghostty = herdrClientOf(GHOSTTY_MAC)!+ expect(ghostty).toMatchObject({ pid: 50390, kind: 'ghostty', cmd: 'herdr' })+ expect(ghostty.env.GHOSTTY_BIN_DIR).toBe('/Applications/Ghostty.app/Contents/MacOS')+ expect(ghostty.env.COLORFGBG).toBe('15;0')+})++test('ps eww text: a value with spaces stays whole; the arguments (--session x) are not variables', () => {+ const ps = 'herdr --session work ITERM_PROFILE=My Dark Profile TERM_PROGRAM=iTerm.app PATH=/a b/bin:/c X=a=b'+ const env = { ITERM_PROFILE: 'My Dark Profile', TERM_PROGRAM: 'iTerm.app', PATH: '/a b/bin:/c', X: 'a=b' }+ expect(envOfText(ps, 'herdr --session work')).toEqual(env)+ // The command not known: its first word goes.+ expect(envOfText(`${ps}\n`, '')).toEqual(env)+ expect(envOfText('herdr', 'herdr')).toEqual({})+ expect(envOfText('', '')).toEqual({})+ const iterm = herdrClientOf(['pid 7', 'atime 5', 'tty ttys003', 'cmd herdr --session work', 'app /Applications/iTerm.app/Contents/MacOS/iTermServer-3.5.10 x', 'env', ps].join('\n'))!+ expect(iterm.kind).toBe('iterm')+ expect(iterm.env.ITERM_PROFILE).toBe('My Dark Profile')+})++test('a herdr client on Linux (/proc/<pid>/environ): NUL-separated variables; a value can hold = and newlines', () => {+ const out = 'pid 4242\natime 1792700000\ntty pts/3\ncmd herdr session attach work\napp /usr/bin/kitty\nenv\n' ++ 'TERM=xterm-kitty\0KITTY_CONFIG_DIRECTORY=/home/u/kc\0A=b=c\0B=one\ntwo\0'+ const c = herdrClientOf(out)!+ expect(c).toMatchObject({ pid: 4242, tty: 'pts/3', kind: 'kitty', app: '/usr/bin/kitty' })+ expect(c.env).toEqual({ TERM: 'xterm-kitty', KITTY_CONFIG_DIRECTORY: '/home/u/kc', A: 'b=c', B: 'one\ntwo' })+})++test('no herdr client: no output, no pid or no env line is null; no variables read gives the app', () => {+ expect(herdrClientOf('')).toBeNull()+ expect(herdrClientOf('pid x\nenv\nTERM=xterm-kitty')).toBeNull()+ expect(herdrClientOf('pid 12\natime 3\ntty ttys001')).toBeNull()+ const bare = herdrClientOf('pid 12\natime 3\ntty ttys001\ncmd herdr\napp /Applications/Ghostty.app/Contents/MacOS/ghostty\nenv\n')!+ expect(bare.kind).toBe('ghostty')+ // Ghostty with no GHOSTTY_BIN_DIR: its app's folder (GHOSTTY_SH runs that ghostty).+ expect(bare.env).toEqual({ GHOSTTY_BIN_DIR: '/Applications/Ghostty.app/Contents/MacOS' })+})++test("a client's terminal: its app first, then TERM, TERM_PROGRAM and the terminals' variables", () => {+ // kitty started from a Ghostty shell keeps Ghostty's variables: the app (or TERM) says kitty.+ const fromGhostty = { TERM: 'xterm-kitty', TERM_PROGRAM: 'ghostty', GHOSTTY_RESOURCES_DIR: '/g', KITTY_WINDOW_ID: '1' }+ expect(outerKindOf(fromGhostty, '/Applications/kitty.app/Contents/MacOS/kitty')).toBe('kitty')+ expect(outerKindOf(fromGhostty, '')).toBe('kitty')+ expect(outerKindOf({ TERM: 'xterm-ghostty', TERM_PROGRAM: 'ghostty', KITTY_PID: '9' }, '')).toBe('ghostty')+ expect(outerKindOf({ TERM: 'xterm-ghostty', CMUX_SURFACE_ID: 's' }, '')).toBe('cmux')+ expect(outerKindOf({}, '/Applications/cmux.app/Contents/MacOS/cmux')).toBe('cmux')+ expect(outerKindOf({ TERM_PROGRAM: 'rio' }, '')).toBe('rio')+ expect(outerKindOf({}, '/Applications/rio.app/Contents/MacOS/rio')).toBe('rio')+ expect(outerKindOf({}, '/usr/bin/rio')).toBe('rio')+ expect(outerKindOf({ TERM_PROGRAM: 'iTerm.app' }, '')).toBe('iterm')+ expect(outerKindOf({ LC_TERMINAL: 'iTerm2' }, '')).toBe('iterm')+ expect(outerKindOf({ KITTY_WINDOW_ID: '2' }, '')).toBe('kitty')+ expect(outerKindOf({ GHOSTTY_BIN_DIR: '/b' }, '')).toBe('ghostty')+ // Another terminal (WezTerm) with kitty's variables of the shell that started it: not known.+ expect(outerKindOf({ TERM_PROGRAM: 'WezTerm', KITTY_PID: '9' }, '/Applications/WezTerm.app/Contents/MacOS/wezterm-gui')).toBe('')+ expect(outerKindOf({}, '')).toBe('')+ // An app bundle with spaces in its folder; arguments do not count.+ expect(outerKindOf({}, '/Applications/My Apps/Ghostty.app/Contents/MacOS/ghostty -e herdr')).toBe('ghostty')+ expect(outerKindOf({}, '/usr/bin/foot /Applications/kitty.app/x')).toBe('')+})++test('a change of herdr client: another terminal, profile or config counts; another window of the same does not', () => {+ const kitty = herdrClientOf(KITTY_MAC)!+ const ghostty = herdrClientOf(GHOSTTY_MAC)!+ expect(herdrClientChanged(null, null)).toBe(false)+ expect(herdrClientChanged(null, kitty)).toBe(true)+ expect(herdrClientChanged(kitty, ghostty)).toBe(true)+ expect(herdrClientChanged(kitty, { ...kitty, pid: 1, atime: 2, tty: 'ttys001', env: { ...kitty.env, KITTY_WINDOW_ID: '7', KITTY_PID: '1' } })).toBe(false)+ expect(herdrClientChanged(kitty, { ...kitty, env: { ...kitty.env, KITTY_CONFIG_DIRECTORY: '/other' } })).toBe(true)+ const iterm = { ...kitty, kind: 'iterm' as const, env: { ITERM_PROFILE: 'Dark' } }+ expect(herdrClientChanged(iterm, { ...iterm, env: { ITERM_PROFILE: 'Light' } })).toBe(true)+ 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)+ const light: HostMode = { mode: 'light', source: 'herdr' }+ const dark: HostMode = { mode: 'dark', source: 'herdr' }+ 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 })+})+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', () => {const off = { iterm: false, herdr: false, draws: false, ssh: false, os: 'Darwin', tmux: false, background: false }expect(needsSetup({ ...off, iterm: true })).toBe(true)