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
Linux: clipboard watch (wl-paste, clipnotify, GTK), desktop portal mode, fontconfig font, plan editors, install docs
razorback160c8df692a6fe
diff --git a/README.md b/README.mdindex 1c217c0..02eb356 100644--- a/README.md+++ b/README.md@@ -14,6 +14,8 @@ Intelligent UI draws each answer from Claude as a typeset picture, with [Typst](brew install typst```+On Linux, you can also use `cargo install --locked typst-cli`, a package of your distribution, or the release file from GitHub. Refer to [Install](docs/install.md#install-typst-on-linux).+Then, in Claude Code:```@@ -24,12 +26,12 @@ It works at once, with no restart.To get new versions, turn on auto-update for the `razorback16` marketplace in `/plugin`, or update manually. Refer to [Update](docs/install.md#update). The mod also shows a notice when a new version is available (`/iui updates off` stops it).-You need Claude Code 2.1.298 or later, [Typst](https://typst.app) 0.15 and macOS. The pictures show only in some terminals:+You need Claude Code 2.1.298 or later, [Typst](https://typst.app) 0.15, and macOS or Linux (X11 or Wayland). The pictures show only in some terminals:| Terminal | Pictures | What to do ||---|---|---|-| kitty 0.28+, Ghostty, cmux | Yes | Nothing |-| iTerm2 3.6+ | Yes | Run `/iui setup` one time |+| kitty 0.28+, Ghostty, cmux (macOS) | Yes | Nothing |+| iTerm2 3.6+ (macOS) | Yes | Run `/iui setup` one time || Rio 0.5.27+ | Yes (not tested) | Set `CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1` || ssh | Yes, from kitty or Ghostty | Refer to [Install](docs/install.md#terminals) || tmux, screen | No | — |@@ -46,7 +48,7 @@ In other terminals, the mod shows the normal text. Refer to [Install](docs/insta- **LaTeX math.** Inline `$…$` and display `$$…$$` math, typeset.- **Live diagrams, charts and plots.** Claude writes Typst with CeTZ, cetz-plot and fletcher. The drawings use your theme's colours and work offline.- **Images and files.** Images in an answer, images that Claude sends, Markdown files that Claude sends, and images that you paste show in the transcript.-- **Copy text from pictures.** Select and copy text with the mouse, as you do with normal text.+- **Copy text from pictures.** Select and copy text with the mouse, as you do with normal text. On Linux, this needs a clipboard tool (refer to [Install](docs/install.md#linux)).- **Links you can click.** The links, file paths and commands of an answer show in rows under its picture. A cmd+click on a link opens it. A click on a command copies it.- **Plans you can read.** In plan mode, the plan shows rendered, with an approve, edit or reject question under it.- **Themes that follow light and dark.** Claude Code's own colours by default, or VS Code's Markdown preview. You can make your own.@@ -85,7 +87,7 @@ More in the [gallery](docs/gallery.md): plots, fractals and a tour of all the Ma| `/iui grid on` / `off` | Puts each line of text on the terminal rows, so that a mouse selection covers the text (on by default) || `/iui updates on` / `off` | Turns the daily check for a new version on or off (on by default) || `/iui details` | Shows the terminal, font, mode and Typst that the mod found |-| `/iui setup` | iTerm2: adds the shell line that turns pictures on |+| `/iui setup` | iTerm2 (macOS): adds the shell line that turns pictures on || `/iui grab` | Copies the text under your last mouse selection of pictures || `/iui dump` | Shows how the mod read the last clipboard with picture cells (for a bug report) |diff --git a/docs/development.md b/docs/development.mdindex 11906eb..eef5adb 100644--- a/docs/development.md+++ b/docs/development.md@@ -17,11 +17,11 @@ claude plugin validate .## Debug log-Set `IUI_DEBUG=1` before you start Claude Code. The mod then writes trace lines to `debug.log` in the cache folder (`${TMPDIR}/cc-intelligent-ui-<uid>/`).+Set `IUI_DEBUG=1` before you start Claude Code. The mod then writes trace lines to `debug.log` in the cache folder (`${TMPDIR}/cc-intelligent-ui-<uid>/`, `/tmp` when `TMPDIR` is not set).## Module layout-The hooks module is `hooks/register.tsx`. It connects the hooks to the modules in `hooks/lib/`. Each module has one topic, for example `markdown.ts` (blocks and segments), `mode.ts` (light or dark), `typst.ts` (compile), `draw.tsx` (the pages of an answer and the link rows under them), `links.ts` (the links, file paths and commands of a text), `answer.ts` (one text through the compile and cache steps), `plan.tsx` (the plan approval question and the plan rows), `frame.ts` (the terminal size and the watcher process, which also reports the clipboard changes), `copy.ts` (the text under a mouse selection of pictures), `probe.ts` (the drawn pages, and the words of a page that a copy reads, kept in memory) and `updates.ts` (the daily check for a new version). The values that change are in one object, `S`, in `state.ts`. Each `$` method has one call site, a wrapper in `api.ts`; the other modules call the wrappers. This keeps the `calls:` note of `claude plugin validate` short (the validator cuts a note at about 1,000 characters, and the catalogue scan then cannot read the footprint). The tests import from `hooks/register.tsx`, which exports the names that they use.+The hooks module is `hooks/register.tsx`. It connects the hooks to the modules in `hooks/lib/`. Each module has one topic, for example `markdown.ts` (blocks and segments), `mode.ts` (light or dark), `typst.ts` (compile), `draw.tsx` (the pages of an answer and the link rows under them), `links.ts` (the links, file paths and commands of a text), `answer.ts` (one text through the compile and cache steps), `plan.tsx` (the plan approval question and the plan rows), `frame.ts` (the terminal size and the watcher process, which also reports the clipboard changes), `clipboard.ts` (how the clipboard is read and watched: macOS, or the Linux tools), `copy.ts` (the text under a mouse selection of pictures), `probe.ts` (the drawn pages, and the words of a page that a copy reads, kept in memory) and `updates.ts` (the daily check for a new version). The values that change are in one object, `S`, in `state.ts`. Each `$` method has one call site, a wrapper in `api.ts`; the other modules call the wrappers. This keeps the `calls:` note of `claude plugin validate` short (the validator cuts a note at about 1,000 characters, and the catalogue scan then cannot read the footprint). The tests import from `hooks/register.tsx`, which exports the names that they use.The Typst template is `render/md.typ`. The themes are in `render/themes/` (refer to [`render/themes/README.md`](../render/themes/README.md)). The vendored Typst packages are in `render/packages/preview/`.diff --git a/docs/how-it-works.md b/docs/how-it-works.mdindex df324a6..15b6467 100644--- a/docs/how-it-works.md+++ b/docs/how-it-works.md@@ -7,12 +7,12 @@1. A `ui.render` hook on `AssistantMessage` gets each block of the answer as Markdown.2. While Claude writes a block, the block is hidden. The block is final when the model request starts its next block (a tool call, more text) or ends. If the mod did not see the request, the block is final after its text stops changing for 400 ms. Then the mod writes the block to a JSON file and runs `typst compile` with `render/md.typ`. Long answers are cut at block boundaries into pages. One page is one PNG.3. The hook draws one `Image` per PNG, in place of the text.-4. Text size: the mod finds the terminal font (iTerm2 profile, Ghostty, kitty or Rio config, else Menlo metrics) and the cell size in pixels. Typst then measures both fonts so that 100% looks as large as the terminal text.+4. Text size: the mod finds the terminal font (iTerm2 profile, Ghostty, kitty or Rio config; on Linux, else fontconfig's `monospace` font; else the metrics of the theme's code font, Menlo on macOS) and the cell size in pixels. Typst then measures both fonts so that 100% looks as large as the terminal text.5. If a compile fails (a bad Typst block or an unknown LaTeX command), the mod compiles once more in safe mode: Typst blocks and math show as code. A dim line under the picture names the error. If that also fails, the normal text shows.-6. Pictures are kept in `${TMPDIR}/cc-intelligent-ui-<uid>/`. Folders older than 2 days are deleted at start. The drawing space of each answer at its first compile is kept in `~/.cache/cc-intelligent-ui/designs`, so that its Typst drawings keep the same share of the screen in later sessions.+6. Pictures are kept in `${TMPDIR}/cc-intelligent-ui-<uid>/` (`/tmp` when `TMPDIR` is not set). Folders older than 2 days are deleted at start. The drawing space of each answer at its first compile is kept in `~/.cache/cc-intelligent-ui/designs`, so that its Typst drawings keep the same share of the screen in later sessions.7. Links: the mod finds the web links, file paths and commands in the Markdown (not in code blocks or math). It draws one dim row for each under the pages, with a `Link` (an OSC 8 link) for a web link or a file, and a `Button` that copies a command (`$.ui.copy`). It keeps a file row only when the file exists (`$.fs.exists`, kept in memory for 512 paths). Each row is one terminal row, cut at its end. The copy (step 9) counts these rows under the pages, so it still finds the page that you select.8. The plan: a `ui.render` hook on the ExitPlanMode `ToolUse` row draws the plan through the same steps. Claude Code shows that row above the approval question. The approved result row then shows only its header, so the plan does not show two times. A `tool.call` hook on ExitPlanMode asks the mod's question (`$.ui.ask`) before Claude Code asks for permission. Then a `classic.PermissionRequest` hook gives the answer to Claude Code at once, so the Claude Code dialog does not show. For an approval, the hook sends the plan (`updatedInput`) and the new permission mode (`setMode`). For the person's text, the `tool.call` hook refuses the call with that text.-9. Copy: one long-lived `perl` process watches the terminal size (at each SIGWINCH) and, on macOS, the clipboard. For the clipboard, it uses `/usr/bin/perl` with Apple's PerlObjCBridge and reads the change counter of the clipboard (`NSPasteboard changeCount`) every 0.3 s. This read is in the process and starts no other process (approximately 0.05% of one CPU core). The clipboard part starts only while the mod is on and after the mod drew its first picture in this session; then the mod starts the process again with the clipboard part (and again without it after `/iui off`). When the counter changes, the mod reads the clipboard one time (`pbpaste`). The first counter after a start is not a change, so an old clipboard is not copied. A picture cell holds its row and its column (kitty placeholder U+10EEEE plus two combining marks). The mod finds the drawn page that has these rows, at the size that it is drawn. Then it finds the position of each word on that page: it runs the probe (`typst query` on the same template, with the same inputs as the PNG compile, plus `probe=1` and `page=<n>`) for the selected pages only. The mod keeps the positions of the last 64 pages in memory. It writes nothing to disk for this, and the PNGs do not change. The mod takes the words in the selected cells. Immediately before it writes the text with `$.ui.copy`, it reads the clipboard again. If the clipboard has a newer copy, the mod does not write over it, and it reads that copy next. If the process stops, the mod starts it again after 1 s (3 times at most). At `/clear` or a resume, the process continues without the clipboard part. At other session ends (for example `/exit`), the mod stops the process and does not start a new one. A `ui.copy` hook also changes a copy with picture cells to the text.+9. Copy: one long-lived `perl` process watches the terminal size (at each SIGWINCH) and the clipboard. On macOS, it uses `/usr/bin/perl` with Apple's PerlObjCBridge and reads the change counter of the clipboard (`NSPasteboard changeCount`) every 0.3 s. This read is in the process and starts no other process (approximately 0.05% of one CPU core). On Linux, the process starts a child in a process group of its own. The child runs a tool that prints a line at each clipboard change (`wl-paste --watch`, `clipnotify` or GTK 3 from Python, refer to [Linux](install.md#linux)) and gives the mod a counter for each line. Nothing runs between two changes. When the `perl` process stops, it stops that process group. The clipboard part starts only while the mod is on and after the mod drew its first picture in this session; then the mod starts the process again with the clipboard part (and again without it after `/iui off`). When the counter changes, the mod reads the clipboard one time (`pbpaste` on macOS; `wl-paste`, `xclip`, `xsel` or GTK on Linux). The first counter after a start is not a change, so an old clipboard is not copied. A picture cell holds its row and its column (kitty placeholder U+10EEEE plus two combining marks). The mod finds the drawn page that has these rows, at the size that it is drawn. Then it finds the position of each word on that page: it runs the probe (`typst query` on the same template, with the same inputs as the PNG compile, plus `probe=1` and `page=<n>`) for the selected pages only. The mod keeps the positions of the last 64 pages in memory. It writes nothing to disk for this, and the PNGs do not change. The mod takes the words in the selected cells. Immediately before it writes the text with `$.ui.copy`, it reads the clipboard again. If the clipboard has a newer copy, the mod does not write over it, and it reads that copy next. If the process stops, the mod starts it again after 1 s (3 times at most). At `/clear` or a resume, the process continues without the clipboard part. At other session ends (for example `/exit`), the mod stops the process and does not start a new one. A `ui.copy` hook also changes a copy with picture cells to the text.## How `auto` is resolved@@ -21,10 +21,10 @@ Claude Code finds the light or dark mode for `auto` by asking the terminal for i1. **The iTerm2 profile:** the background colour of the profile in use (`ITERM_PROFILE`, else the default profile). Intelligent UI finds iTerm2 by `TERM_PROGRAM`. If `TERM_PROGRAM` is not set, `ITERM_PROFILE`, `ITERM_SESSION_ID` or `LC_TERMINAL=iTerm2` also show iTerm2. If the profile has separate colours for light and dark mode, Intelligent UI uses the set for iTerm2's theme (Settings > Appearance). If that theme is Automatic, Minimal or Compact, it uses the set for the OS appearance.2. **The Ghostty config:** the `background` that `ghostty +show-config` gives. With a `theme = light:A,dark:B`, Intelligent UI reads the background from the theme file for the OS appearance. With no theme and no `background`, it uses Ghostty's default (`#282c34`, dark).- **cmux** (Ghostty inside, found by its `CMUX_*` variables) reads the same Ghostty config, then its own config, `~/Library/Application Support/com.cmuxterm.app/config.ghostty`. The cmux themes picker (Settings > Themes, `cmux themes`) writes the theme there, and that theme wins over the Ghostty config's. A `light:A,dark:B` theme follows cmux's appearance (see below). If these configs set no `theme`, `background`, `foreground` or `palette`, cmux uses its adaptive default theme. Intelligent UI then uses cmux's appearance: `app.appearance` in `~/.config/cmux/cmux.json`, else the value in cmux's Settings. If that appearance is System, Intelligent UI uses the OS appearance. If `terminal.adaptiveDefaultTheme` is `false` in `cmux.json`, Intelligent UI uses the Ghostty rules above.-3. **The kitty config:** the `background` in `kitty.conf` and in the files that it includes (`include` lines only). The themes kitten writes such an include. If the config folder has `dark-theme.auto.conf`, `light-theme.auto.conf` or `no-preference-theme.auto.conf` (kitty 0.38 and later), Intelligent UI uses the file for the OS appearance, as kitty does. With no `background`, it uses kitty's default (`#000000`, dark). The config folder is `KITTY_CONFIG_DIRECTORY`. If that is not set, it is the first of `$XDG_CONFIG_HOME/kitty`, `~/.config/kitty` and (on macOS) `~/Library/Preferences/kitty` that has a `kitty.conf`.+3. **The kitty config:** the `background` in `kitty.conf` and in the files that it includes (`include` lines only). The themes kitten writes such an include. If the config folder has `dark-theme.auto.conf`, `light-theme.auto.conf` or `no-preference-theme.auto.conf` (kitty 0.38 and later), Intelligent UI uses the file for the OS appearance, as kitty does (on Linux, the portal's or GNOME's colour scheme). With no `background`, it uses kitty's default (`#000000`, dark). The config folder is `KITTY_CONFIG_DIRECTORY`. If that is not set, it is the first of `$XDG_CONFIG_HOME/kitty`, `~/.config/kitty` and (on macOS) `~/Library/Preferences/kitty` that has a `kitty.conf`.4. **The Rio config:** `config.toml` in `RIO_CONFIG_HOME`, else in `~/.config/rio` (on Linux, `$XDG_CONFIG_HOME/rio` if that is set). With an `[adaptive-theme]`, Intelligent UI reads the theme file for `force-theme`, else for the OS appearance. Else it reads the file for `theme`, else the `[colors] background`. Theme files are in the `themes` folder. With no background, it uses Rio's default (`#0F0D0E`, dark).5. **`COLORFGBG`**, as it was when Claude Code started. Ghostty does not set it.-6. **The OS appearance:** macOS Dark or Light, or GNOME's `color-scheme` on Linux.+6. **The OS appearance:** macOS Dark or Light. On Linux, the `color-scheme` of the freedesktop portal (through `gdbus`, else `busctl`; "no preference" is light), else GNOME's `color-scheme` (`gsettings`). The mod keeps the tool that works, so each check starts one process.7. **Dark.**The terminal comes before the OS: a dark terminal on a light Mac is dark.diff --git a/docs/install.md b/docs/install.mdindex 2bf9353..d556849 100644--- a/docs/install.md+++ b/docs/install.md@@ -6,14 +6,14 @@- Claude Code 2.1.298 or later (tested on 2.1.301)- [Typst](https://typst.app) 0.15 (tested on 0.15.1)-- macOS (tested). Linux can work, but it is not tested.+- macOS (tested) or Linux with X11 or Wayland. The Linux parts are tested in a container, not yet on a Linux desktop. Refer to [Linux](#linux).- A terminal where Claude Code draws pictures. Refer to [Terminals](#terminals).## Terminals-- **kitty (0.28 or later), Ghostty and cmux (Ghostty inside):** pictures work with no setting.-- **iTerm2 3.6 or later (3.7.5 tested):** 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 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`).-- **Rio 0.5.27 or later (not tested):** set `CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1` before you start Claude Code.+- **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 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`).+- **Rio 0.5.27 or later (not tested):** set `CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1` before you start Claude Code. Rio works on macOS and on Linux.- Do not put the variable in the `env` of `~/.claude/settings.json`. It then applies in every terminal, also where pictures cannot show.- **Warp (not yet):** Warp does not draw kitty pictures with Unicode placeholders yet. The pull request [warpdotdev/warp#16312](https://github.com/warpdotdev/warp/pull/16312) adds them. The mod will support Warp when that pull request is merged.- **Not supported:** WezTerm and Konsole do not draw kitty pictures with Unicode placeholders, so they show no pictures, also with the variable set. Alacritty, Terminal.app, Windows Terminal, GNOME Terminal (and other VTE terminals), foot, VS Code, Tabby, Hyper and JetBrains terminals have no kitty pictures.@@ -25,7 +25,7 @@ Where pictures cannot draw, the mod shows the normal text. To see why a terminal## Install steps-1. Install Typst: `brew install typst` (or see [Typst's install page](https://github.com/typst/typst#installation)).+1. Install Typst: `brew install typst` on macOS. On Linux, refer to [Install Typst on Linux](#install-typst-on-linux). For all the ways, refer to [Typst's install page](https://github.com/typst/typst#installation).2. At the prompt of a Claude Code session in the terminal, type:```@@ -40,6 +40,40 @@ From a shell:claude plugin install cc-intelligent-ui --marketplace razorback16/cc-intelligent-ui```+## Install Typst on Linux++You need Typst 0.15 or later. Use one of these ways:++- **Cargo** (Rust): `cargo install --locked typst-cli`. Typst goes into `~/.cargo/bin`.+- **The release file:** download `typst-x86_64-unknown-linux-musl.tar.xz` (or `typst-aarch64-unknown-linux-musl.tar.xz` for ARM) from [the Typst releases](https://github.com/typst/typst/releases). Extract it and put `typst` in a folder on your `PATH`, for example `~/.local/bin`.+- **A package of your distribution, Snap (`sudo snap install typst`) or Homebrew on Linux (`brew install typst`).** Make sure that the version is 0.15 or later (`typst --version`). Some distributions have an older version.++The mod finds Typst on the `PATH` of your login shell. It also looks in `/usr/local/bin`, `/usr/bin`, `/snap/bin`, `~/.cargo/bin`, `~/.local/bin` and the Homebrew folders.++## Linux++The mod works on Linux with X11 and with Wayland. It uses these tools. Most Linux systems have the first three.++- **perl** (perl 5): reads the terminal size and its cell size, and watches for a change of the size.+- **fontconfig** (`fc-match`, `fc-list`): finds the terminal font when the terminal's config does not name one. kitty and most terminals use fontconfig's `monospace` font. Ghostty uses its own JetBrains Mono when its config names no font. The mod uses JetBrains Mono only when fontconfig has it, because Typst must find the font too.+- **The light or dark mode of the desktop** (for the `auto` theme): the freedesktop portal (`org.freedesktop.appearance color-scheme`, through `gdbus` or `busctl`). GNOME, KDE Plasma and most desktops have the portal. If the portal does not answer, the mod reads GNOME's `color-scheme` (`gsettings`).+- **The clipboard** (for the automatic copy, refer to [Copy text from a picture](usage.md#copy-text-from-a-picture)). The mod uses the first of these that it finds:+ 1. **Wayland, not GNOME:** `wl-paste` from `wl-clipboard`. `wl-paste --watch` tells the mod about each clipboard change. It needs the data-control protocol of the compositor (KDE Plasma, Sway, Hyprland and other wlroots compositors have it).+ 2. **X11, and GNOME on Wayland (through Xwayland):** `clipnotify` tells the mod about each clipboard change, and `xclip` or `xsel` reads the clipboard. If `clipnotify` is not installed, the mod uses GTK 3 from Python (`python3-gi`, which most GNOME desktops have) for both.+ 3. **GNOME on Wayland with no X11 tool:** `wl-paste`. GNOME does not have the data-control protocol, so `wl-paste --watch` stops, and the automatic copy is off.++ If none of these work, the automatic copy is off. `/iui grab`, Claude Code's `/copy` and the `ui.copy` hook still work. `/iui details` shows the tool in use, or why the automatic copy is off, on the line `Auto copy:`.+- **"Edit the plan"** (refer to [Plan approval](usage.md#plan-approval)): VS Code (`code --wait`), else the first of VSCodium, Zed, Sublime Text, Kate, gedit and gvim that is on the `PATH`. These editors can wait until you close the file. If none is installed, the option does not show.+- **The cache folder** is in `$TMPDIR`, else in `/tmp`.++`/iui setup` is for iTerm2 only. On Linux it changes no file.++To install the clipboard tools, for example:++- Debian and Ubuntu: `sudo apt install wl-clipboard xclip` (`clipnotify` is not in their packages: build it from [cdown/clipnotify](https://github.com/cdown/clipnotify), or use GTK 3 from Python: `sudo apt install python3-gi gir1.2-gtk-3.0`).+- Fedora: `sudo dnf install wl-clipboard xclip`.+- Arch Linux: `sudo pacman -S wl-clipboard xclip clipnotify`.+## UpdateClaude Code finds a new version of the mod from the version number in its `plugin.json`. For a marketplace that is not from Anthropic, such as `razorback16`, auto-update is off by default.diff --git a/docs/limitations.md b/docs/limitations.mdindex acd02bf..fa2772b 100644--- a/docs/limitations.md+++ b/docs/limitations.md@@ -3,7 +3,9 @@← Back to the [README](../README.md)- **Copying text from a picture** (refer to [Copy text from a picture](usage.md#copy-text-from-a-picture)) has these limits:- - The automatic copy works only on macOS, and not over ssh (`pbpaste` reads the clipboard of the computer that runs Claude Code). It also needs `/usr/bin/perl` with Apple's PerlObjCBridge (macOS has it), which reads the change counter of the clipboard. If the bridge does not load, the automatic copy is off: the mod does not read the clipboard at intervals in its place. `/iui details` shows the state on the line `Auto copy:`. When the automatic copy is off, the clipboard keeps the picture cells (U+10EEEE plus combining marks), and a paste gives strange characters. Use `/iui grab`, Claude Code's `/copy` (the last answer as Markdown, `/copy 2` for the one before it), or turn the mod off (`/iui off`) to select text.+ - The automatic copy works on macOS and on Linux, but not over ssh (the mod reads the clipboard of the computer that runs Claude Code). On macOS, it needs `/usr/bin/perl` with Apple's PerlObjCBridge (macOS has it), which reads the change counter of the clipboard. On Linux, it needs a tool that tells the mod about each clipboard change: `wl-paste --watch` on Wayland, else `clipnotify` or GTK 3 from Python on X11 and Xwayland (refer to [Linux](install.md#linux)). If no such tool works, the automatic copy is off: the mod does not read the clipboard at intervals in its place. `/iui details` shows the state on the line `Auto copy:`.+ - On GNOME with Wayland, `wl-paste --watch` does not work (GNOME does not have the data-control protocol). The mod then uses the X11 tools through Xwayland. This is not tested on a GNOME desktop yet.+ - On Linux with the old `clipnotify` (1.0.2 or earlier), a mouse selection (the PRIMARY selection) also makes the mod read the clipboard once. The mod changes nothing in that case. When the automatic copy is off, the clipboard keeps the picture cells (U+10EEEE plus combining marks), and a paste gives strange characters. Use `/iui grab`, Claude Code's `/copy` (the last answer as Markdown, `/copy 2` for the one before it), or turn the mod off (`/iui off`) to select text.- The first copy from a page takes 0.15–0.5 s (2–3 s for a page with a large Typst drawing), and no toast shows during this time. If you paste before the toast "copied N chars of text" shows, the paste gives the picture cells.- The mod copies whole words. It copies a word when the selection covers the middle of the word. In a code block, in a long word (30 characters or more, for example a path or a URL) and in CJK text, it copies each character whose middle is in the selection.- The mod does not copy math, the text in an image, or the text in a Typst drawing.@@ -22,10 +24,10 @@- **Search does not find text in a picture.**- **While Claude writes**, the block is hidden, and Claude Code's spinner shows the progress. When the block is final, its picture shows after the compile (0.15–0.6 s). A long answer shows only when it is done. If the picture is not ready 2 s after the block is final, the normal text shows until the picture is ready. If the compile fails, the normal text stays. An earlier answer that is not in the cache (for example, after a resume) is blank for up to 1 s, then shows as text until its picture is ready.- **Short summaries** between tool calls stay as text.-- **Plan approval:** a mod cannot draw the Claude Code approval dialog, so the mod shows its own question. That question can have 4 options at most. Thus it has no option to keep planning (use Type something or Esc). The edit option cannot use a terminal editor (vim, nano), because a mod has no terminal. Where an organization manages Claude Code, `classic.PermissionRequest` hooks of a plugin that you install do not run. Then the Claude Code dialog shows after the mod's question.+- **Plan approval:** a mod cannot draw the Claude Code approval dialog, so the mod shows its own question. That question can have 4 options at most. Thus it has no option to keep planning (use Type something or Esc). The edit option cannot use a terminal editor (vim, nano), because a mod has no terminal. On Linux, it uses only the GUI editors that can wait until you close the file (refer to [Linux](install.md#linux)), not `xdg-open`. Where an organization manages Claude Code, `classic.PermissionRequest` hooks of a plugin that you install do not run. Then the Claude Code dialog shows after the mod's question.- **Typst blocks:** `#page`, `#pagebreak` and `#set page` are errors. A package that is not in the mod cannot be downloaded (the network is blocked for Typst), so its block shows as code.- **Security:** Typst runs with `--root /`, so a Typst block can read any file that you can read and draw it in the picture. Nothing leaves the computer.- **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 Menlo metrics 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.-- **`auto` theme** reads the iTerm2 profile, the Ghostty, kitty and Rio configs, and the cmux settings directly. 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. 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.+- **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.+- **`auto` theme** reads the iTerm2 profile, the Ghostty, kitty and Rio configs, and the cmux settings directly. 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/docs/usage.md b/docs/usage.mdindex 1ab2394..08d5bc8 100644--- a/docs/usage.md+++ b/docs/usage.md@@ -7,7 +7,7 @@ Intelligent UI draws Claude's answers as rendered Markdown pictures. Only the dr## What it draws- Headings, lists, task lists, tables, block quotes, links, footnotes and horizontal rules-- Code blocks with syntax colours, in your terminal's font (found for iTerm2, Ghostty, kitty and Rio; else Menlo, SF Mono or DejaVu Sans Mono)+- Code blocks with syntax colours, in your terminal's font (found for iTerm2, Ghostty, kitty and Rio; on Linux, else fontconfig's `monospace` font; else Menlo, SF Mono or DejaVu Sans Mono)- Math (`$…$` and `$$…$$`, LaTeX syntax, through mitex)- Images from ``. A relative path starts from the session's folder. Remote images show as an alt-text box.- Live Typst: a fenced block with the language `typst` (or `typ`) is rendered, not shown as code. These packages are in the mod and work offline:@@ -36,7 +36,7 @@ Intelligent UI draws Claude's answers as rendered Markdown pictures. Only the dr| `/iui` | Shows the state, the theme, the text size, the width, the image height and the row grid, a problem that keeps pictures away, and a new version when there is one || `/iui details` | Shows all that the mod found: where the mode comes from, the terminal font, the Typst path, why the terminal can or cannot show pictures, if the automatic copy is on (`Auto copy:`), and the state of the update check (`Update checks:`) || `/iui on` / `off` | Turns the pictures on or off (kept for later sessions) |-| `/iui setup` / `setup remove` | iTerm2: adds or removes the shell line that turns pictures on (then close the tab and open a new one) |+| `/iui setup` / `setup remove` | iTerm2 (macOS only): adds or removes the shell line that turns pictures on (then close the tab and open a new one). On Linux, it changes no file. || `/iui size <80–200>` | Text size in percent. 100 is the same visual size as your terminal text. || `/iui width` | Shows the width: the most columns that a picture can use || `/iui width <40–400>` | Sets the most columns that a picture can use (kept for later sessions) |@@ -76,7 +76,7 @@ The mod does not take web links from code blocks, inline code or math. It takes## Copy text from a picture-Select the text in a picture (an answer, a plan or a Markdown file that Claude sent) with the mouse, as you do with normal text. The selection puts picture cells on the clipboard. On macOS, while the mod is on and has drawn a picture in this session, the mod sees each change of the clipboard (in 0.3 s or less). When the clipboard has picture cells, the mod puts the text under your selection on the clipboard, and a toast shows the number of characters. Wait for this toast, then paste. In fullscreen mode, if this session has a selection, the mod changes the clipboard only when the clipboard holds that selection. Thus a copy from a different Claude Code session usually stays as it is. The mod does not change a clipboard that has no picture cells.+Select the text in a picture (an answer, a plan or a Markdown file that Claude sent) with the mouse, as you do with normal text. The selection puts picture cells on the clipboard. While the mod is on and has drawn a picture in this session, the mod sees each change of the clipboard (on macOS in 0.3 s or less; on Linux at once, with the tools in [Linux](install.md#linux)). When the clipboard has picture cells, the mod puts the text under your selection on the clipboard, and a toast shows the number of characters. Wait for this toast, then paste. In fullscreen mode, if this session has a selection, the mod changes the clipboard only when the clipboard holds that selection. Thus a copy from a different Claude Code session usually stays as it is. The mod does not change a clipboard that has no picture cells.The mod finds the position of each word on a page when you copy from that page for the first time. This takes 0.15–0.5 s, and more (2–3 s) for a page with a large Typst drawing. No toast shows while it does this. Only the toast of the copy shows. The mod keeps the positions in memory, so the next copy from the same page is fast.@@ -113,7 +113,7 @@ When Claude exits plan mode, the mod draws the plan as a picture in the transcri| Type something | Sends your text to Claude as changes to the plan. Claude stays in plan mode and writes a new plan. || Esc | Rejects the plan and stops the turn. |-The editor is VS Code (`code --wait`) when the `code` command is on your PATH. If `code` is not on the PATH, macOS uses TextEdit (`open -W -t`). In that case, quit TextEdit when you complete the edit. Over ssh and on Linux with no `code` command, the "Edit the plan" option does not show.+The editor is VS Code (`code --wait`) when the `code` command is on your PATH. If `code` is not on the PATH, macOS uses TextEdit (`open -W -t`). In that case, quit TextEdit when you complete the edit. On Linux with a display, the mod uses the first of VSCodium (`codium --wait`), Zed (`zed --wait`), Sublime Text (`subl --wait`), Kate (`kate --block`), gedit (`gedit --wait`) and gvim (`gvim -f`) that is on the PATH. Close the file (or the window) when you complete the edit. Over ssh with no `code` command, and on Linux with none of these editors, the "Edit the plan" option does not show.The mod shows the plan file as it is when the question opens. Claude can write the plan file and exit plan mode in the same message. Then Claude Code sends the plan from before that write. In this case, the mod waits for the write to complete (5 seconds at most) and reads the file again. You approve the plan that you see, and Claude gets that plan.diff --git a/hooks/lib/api.ts b/hooks/lib/api.tsindex c9d398e..b028cbb 100644--- a/hooks/lib/api.ts+++ b/hooks/lib/api.ts@@ -12,11 +12,11 @@ import type {// (the validator lists them), so envGet has one call per name.export type EnvName =| 'CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC' | 'CLAUDE_CODE_FORCE_TERMINAL_IMAGES' | 'CLAUDE_CODE_SESSION_KIND' | 'CLAUDE_CODE_TMPDIR'- | 'CMUX_SOCKET_PATH' | 'CMUX_SURFACE_ID' | 'CMUX_WORKSPACE_ID' | 'COLORFGBG' | 'DISABLE_AUTOUPDATER' | 'DISABLE_UPDATES'+ | 'CMUX_SOCKET_PATH' | 'CMUX_SURFACE_ID' | 'CMUX_WORKSPACE_ID' | 'COLORFGBG' | 'DISABLE_AUTOUPDATER' | 'DISABLE_UPDATES' | 'DISPLAY'| 'GHOSTTY_RESOURCES_DIR' | 'HOME'| 'ITERM_PROFILE' | 'ITERM_SESSION_ID' | 'IUI_DEBUG' | 'IUI_FORCE' | 'KITTY_CONFIG_DIRECTORY' | 'KITTY_PID'| 'KITTY_WINDOW_ID' | 'LC_TERMINAL' | 'RIO_CONFIG_HOME' | 'SHELL' | 'SSH_CONNECTION' | 'SSH_TTY' | 'STY'- | 'TERM' | 'TERM_PROGRAM' | 'TMUX' | 'XDG_CONFIG_HOME' | 'ZDOTDIR'+ | 'TERM' | 'TERM_PROGRAM' | 'TMUX' | 'WAYLAND_DISPLAY' | 'XDG_CONFIG_HOME' | 'XDG_CURRENT_DESKTOP' | 'ZDOTDIR'export function clockAfter($: EngineInterface, ms: number, fn: () => void) {return $.clock.after(ms, fn)@@ -54,6 +54,7 @@ export function envGet($: EngineInterface, name: EnvName): Promise<string | undecase 'COLORFGBG': return $.env.get('COLORFGBG')case 'DISABLE_AUTOUPDATER': return $.env.get('DISABLE_AUTOUPDATER')case 'DISABLE_UPDATES': return $.env.get('DISABLE_UPDATES')+ case 'DISPLAY': return $.env.get('DISPLAY')case 'GHOSTTY_RESOURCES_DIR': return $.env.get('GHOSTTY_RESOURCES_DIR')case 'HOME': return $.env.get('HOME')case 'ITERM_PROFILE': return $.env.get('ITERM_PROFILE')@@ -72,7 +73,9 @@ export function envGet($: EngineInterface, name: EnvName): Promise<string | undecase 'TERM': return $.env.get('TERM')case 'TERM_PROGRAM': return $.env.get('TERM_PROGRAM')case 'TMUX': return $.env.get('TMUX')+ case 'WAYLAND_DISPLAY': return $.env.get('WAYLAND_DISPLAY')case 'XDG_CONFIG_HOME': return $.env.get('XDG_CONFIG_HOME')+ case 'XDG_CURRENT_DESKTOP': return $.env.get('XDG_CURRENT_DESKTOP')case 'ZDOTDIR': return $.env.get('ZDOTDIR')}}diff --git a/hooks/lib/clipboard.ts b/hooks/lib/clipboard.tsnew file mode 100644index 0000000..3869c40--- /dev/null+++ b/hooks/lib/clipboard.ts@@ -0,0 +1,172 @@+// The clipboard of this computer: how a copy reads it and how its changes+// are seen. macOS: pbpaste, and the change count of the watcher's+// PerlObjCBridge (host.ts). Linux: Wayland's wl-paste (its --watch sees each+// change), else X11 (also Xwayland): xclip or xsel to read, clipnotify for+// an event at each change, else GTK 3 from Python (python3-gi, on most GNOME+// desktops) for both. Where no tool sees the changes, the automatic copy is+// off: the clipboard is never read at intervals in its place.+import type { EngineInterface } from 'claude-code'++import { S } from './state'+import { envGet, processRun } from './api'++// The tools the choice looks for, in the order it prefers them. `gtk` is+// python3 when it can load GTK 3 (gi).+export const CLIP_TOOLS = ['wl-paste', 'xclip', 'xsel', 'clipnotify', 'gtk'] as const+export type ClipTool = (typeof CLIP_TOOLS)[number]++// How the clipboard is read and watched: `read` the argv that prints its+// text; `watch` the notifier's argv (the watcher runs it and gives one+// `clip <n>` line for each line it prints, the first at its start: its+// clipboard then is no new copy); `name` for /iui details. `off`: why the+// automatic copy is off (`read`, when set, still serves the ui.copy hook).+export type ClipWay = { name: string; read: string[]; watch: string[]; wayland: boolean } | { off: string }++// The Wayland notifier's command: wl-paste runs it at each change (and once+// at its start) with the new data on stdin, which it reads to the end so the+// app that copied does not get a broken pipe. A copy that a password manager+// marks as sensitive gives no line, so it is never read.+export const WL_WATCH_SH = 'cat >/dev/null; [ "$CLIPBOARD_STATE" = sensitive ] || echo'+// The X11 notifier: a line at its start, then one at each change of the+// CLIPBOARD selection. clipnotify 1.0.3+ prints them itself (-l); an older+// one does not know the flags, watches PRIMARY too, and exits at the first+// change, so the loop runs it again. It ends when clipnotify fails (no X+// display). `$0` is clipnotify's path.+export const X11_WATCH_SH = 'echo; while "$0" -s clipboard -l; do echo; done'+// GTK 3 on X11 (GDK_BACKEND=x11: through Xwayland on a Wayland desktop, where+// an app sees the clipboard events with no focus): the watch prints a line+// at its start and at each owner change of CLIPBOARD; the read prints the+// text (exit 1 for none). Both exit 1 with no display.+export const GTK_WATCH_PY = [+ 'import sys, gi',+ 'gi.require_version("Gtk", "3.0")',+ 'from gi.repository import Gtk, Gdk',+ 'if Gdk.Display.get_default() is None: sys.exit(1)',+ 'def say(*_):',+ ' try:',+ ' sys.stdout.write("\\n"); sys.stdout.flush()',+ ' except BrokenPipeError:',+ ' sys.exit(0)',+ 'Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD).connect("owner-change", say)',+ 'say()',+ 'Gtk.main()',+].join('\n')+export const GTK_READ_PY = [+ 'import sys, gi',+ 'gi.require_version("Gtk", "3.0")',+ 'from gi.repository import Gtk, Gdk',+ 'if Gdk.Display.get_default() is None: sys.exit(1)',+ 't = Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD).wait_for_text()',+ 'if t is None: sys.exit(1)',+ 'sys.stdout.write(t)',+].join('\n')+const GTK_ENV = ['/usr/bin/env', 'GDK_BACKEND=x11', 'PYTHONIOENCODING=utf-8']++// The way to read and watch the clipboard on Linux, from the session+// (WAYLAND_DISPLAY, DISPLAY, the desktop) and the tools found (their paths).+// Wayland: wl-paste, whose --watch needs the data-control protocol. GNOME+// does not have it (and its wl-paste read shows a window), so on GNOME the+// X11 ways through Xwayland come first. X11: xclip, xsel or GTK to read, and+// clipnotify or GTK to see the changes (X11 has no other event for them).+export function clipWayOf(o: { wayland: boolean; x11: boolean; desktop: string; found: Partial<Record<ClipTool, string>> }): ClipWay {+ const { found } = o+ const wl = o.wayland && found['wl-paste'] ? found['wl-paste'] : ''+ const gtk = found.gtk ? { read: [...GTK_ENV, found.gtk, '-c', GTK_READ_PY], watch: [...GTK_ENV, found.gtk, '-c', GTK_WATCH_PY] } : null+ const reader = found.xclip ? { tool: 'xclip', read: [found.xclip, '-o', '-selection', 'clipboard', '-t', 'UTF8_STRING'] }+ : found.xsel ? { tool: 'xsel', read: [found.xsel, '-o', '-b'] }+ : gtk ? { tool: 'GTK', read: gtk.read } : null+ const watcher = found.clipnotify ? { tool: 'clipnotify', watch: ['sh', '-c', X11_WATCH_SH, found.clipnotify] } : gtk ? { tool: 'GTK', watch: gtk.watch } : null+ const isGnome = /gnome/i.test(o.desktop)+ const waylandWay = () =>+ ({ name: 'wl-paste --watch (Wayland)', read: [wl, '-n', '-t', 'text'], watch: [wl, '--watch', 'sh', '-c', WL_WATCH_SH], wayland: true })+ const x11Way = () => {+ if (!o.x11 || !reader || !watcher) return null+ const name = watcher.tool === reader.tool ? watcher.tool : `${watcher.tool} and ${reader.tool}`+ return { name: `${name} (X11${o.wayland ? ', Xwayland' : ''})`, read: reader.read, watch: watcher.watch, wayland: false }+ }+ if (wl && !isGnome) return waylandWay()+ const viaX = x11Way()+ if (viaX) return viaX+ if (wl) return waylandWay()+ if (!o.wayland && !o.x11) return { off: 'no Wayland or X11 display' }+ if (o.x11 && reader) return { off: `no clipnotify and no GTK 3 for Python: X11 has no clipboard event for ${reader.tool}` }+ return { off: o.wayland ? 'no wl-paste (install wl-clipboard)' : 'no xclip, xsel or GTK 3 for Python, and no clipnotify' }+}++// Prints `tool path` for each clipboard tool on the PATH, and `gtk <python3>`+// when there is no clipnotify and python3 loads GTK 3.+const GTK_CHECK_PY = 'import gi; gi.require_version("Gtk", "3.0"); from gi.repository import Gtk'+export const FIND_SH = [+ `for c in ${CLIP_TOOLS.filter(c => c !== 'gtk').join(' ')}; do p=$(command -v "$c" 2>/dev/null) && echo "$c $p"; done`,+ `command -v clipnotify >/dev/null 2>&1 || { p=$(command -v python3 2>/dev/null) && "$p" -c '${GTK_CHECK_PY}' >/dev/null 2>&1 && echo "gtk $p"; }`,+].join('; ')++// The tools of `FIND_SH`'s output, by name; only absolute paths.+export function clipToolsOf(stdout: string): Partial<Record<ClipTool, string>> {+ const found: Partial<Record<ClipTool, string>> = {}+ for (const line of stdout.split('\n')) {+ const m = /^(\S+) (\/.*)$/.exec(line.trim())+ if (m && (CLIP_TOOLS as readonly string[]).includes(m[1]!)) found[m[1] as ClipTool] = m[2]!+ }+ return found+}++// Linux, on this computer (setUp, not awaited: GTK loads in 0.1-0.3 s):+// finds the tools once and sets S.clipWay. A copy needs it only after the+// first picture; /iui details and dump wait for it (clipWayReady).+let finding: Promise<unknown> | null = null+export const clipWayReady = (): Promise<unknown> => finding ?? Promise.resolve()+export function findClipWay($: EngineInterface): Promise<ClipWay> {+ const p = lookUp($)+ finding = p.catch(() => undefined)+ return p+}+async function lookUp($: EngineInterface): Promise<ClipWay> {+ const got = await processRun($, ['sh', '-c', FIND_SH], { timeoutMs: 5000 }).catch(() => null)+ S.clipWay = clipWayOf({+ wayland: !!(await envGet($, 'WAYLAND_DISPLAY')),+ x11: !!(await envGet($, 'DISPLAY')),+ desktop: (await envGet($, 'XDG_CURRENT_DESKTOP')) ?? '',+ found: clipToolsOf(got?.stdout ?? ''),+ })+ return S.clipWay+}++// The clipboard now as text: pbpaste (UTF-8) on macOS, else the way found+// on Linux; null when it can not be read (no tool, or no text in it).+export async function clipboardNow($: EngineInterface): Promise<string | null> {+ if (S.env?.isMac) {+ const got = await processRun($, ['pbpaste'], { timeoutMs: 2000, env: { LANG: 'en_US.UTF-8', LC_ALL: 'en_US.UTF-8' } }).catch(() => null)+ return got && got.exitCode === 0 ? got.stdout : null+ }+ const way = S.clipWay+ if (!way || !('read' in way)) return null+ const got = await processRun($, way.read, { timeoutMs: 2000 }).catch(() => null)+ return got && got.exitCode === 0 ? got.stdout : null+}++// The watcher's arguments after `clip`: none on macOS (its PerlObjCBridge),+// the notifier on Linux; null where the changes can not be seen.+export function clipWatchArgs(isMac: boolean): string[] | null {+ if (isMac) return []+ const way = S.clipWay+ return way && 'watch' in way ? way.watch : null+}++// The automatic copy now, for /iui details and dump. `ended`: the+// notifier stopped (the watcher printed `clip none`).+export function autoCopyText(o: { isMac: boolean; hostOs: string; isRemote: boolean; isOn: boolean; none: boolean; drawn: boolean; running: boolean; way: ClipWay | null }): string {+ if (!o.isMac && o.hostOs !== 'Linux') return 'off (not macOS or Linux)'+ if (o.isRemote) return 'off (ssh)'+ if (!o.isMac && o.way && 'off' in o.way) return `off (${o.way.off})`+ if (!o.isMac && !o.way) return 'off (the clipboard tools are not looked up yet)'+ if (!o.isOn) return 'off (Intelligent UI is off)'+ if (o.none) {+ if (o.isMac) return 'off (no PerlObjCBridge in /usr/bin/perl)'+ const way = o.way as Extract<ClipWay, { watch: string[] }>+ return `off (${way.name} stopped${way.wayland ? ': the compositor may not have the data-control protocol' : ''})`+ }+ if (!o.drawn) return 'off (no picture yet)'+ if (!o.running) return 'off (the watcher does not run)'+ return o.isMac ? 'on' : `on, with ${(o.way as Extract<ClipWay, { name: string }>).name}`+}diff --git a/hooks/lib/env.ts b/hooks/lib/env.tsindex ffe5080..3b0e9d2 100644--- a/hooks/lib/env.ts+++ b/hooks/lib/env.ts@@ -4,7 +4,7 @@ import { atom, update } from 'claude-code'import type { EngineInterface } from 'claude-code'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, NO_TYPST,+ BASE_THEME, DEFAULT_HEIGHT, DEFAULT_SIZE, DESIGNS_KEPT_DAYS, DEFAULT_THEME, DEFAULT_WIDTH, MAX_HEIGHT, MAX_SIZE, MAX_WIDTH, MIN_HEIGHT, MIN_SIZE, MIN_WIDTH, noTypstOf,} from './settings'import { DEFAULT_METRICS, refresh, S, type Env } from './state'import { resolveMode, settingOf } from './mode'@@ -16,6 +16,7 @@ import { registerCommand } from './command'import { readHostMode, termFontOf, watchHost } from './host'import { readFrame, setFrame, watchFrame } from './frame'import { offerSetup } from './setup'+import { findClipWay } from './clipboard'import { findTypst, measureFonts } from './typst'import { checkUpdates } from './updates'import { configList, envGet, fsList, fsStat, pluginRoot, processRun, sessionCwd, storeGet, uiToast } from './api'@@ -28,7 +29,7 @@ const isOn = atom({ plugin: 'cc-intelligent-ui', key: 'isOn' } as const, true)// the designs folder (outside the tmp cache) and drops design files not// touched for DESIGNS_KEPT_DAYS; prints the cache folder, the OS name and// the designs folder.-const CACHE_SH = `d="\${TMPDIR:-/tmp}"; d="\${d%/}/cc-intelligent-ui-$(id -u)"; g="\${XDG_CACHE_HOME:-$HOME/.cache}/cc-intelligent-ui/designs"; mkdir -p "$d" && chmod 700 "$d" && { find "$d" -mindepth 1 -maxdepth 1 -type d -mtime +2 ! -name pkg-cache -exec rm -rf {} + 2>/dev/null; mkdir -p "$g" 2>/dev/null && find "$g" -type f -mtime +${DESIGNS_KEPT_DAYS} -delete 2>/dev/null; printf '%s\\n%s\\n%s\\n' "$d" "$(uname -s)" "$g"; }`+export const CACHE_SH = `d="\${TMPDIR:-/tmp}"; d="\${d%/}/cc-intelligent-ui-$(id -u)"; g="\${XDG_CACHE_HOME:-$HOME/.cache}/cc-intelligent-ui/designs"; mkdir -p "$d" && chmod 700 "$d" && { find "$d" -mindepth 1 -maxdepth 1 -type d -mtime +2 ! -name pkg-cache -exec rm -rf {} + 2>/dev/null; mkdir -p "$g" 2>/dev/null && find "$g" -type f -mtime +${DESIGNS_KEPT_DAYS} -delete 2>/dev/null; printf '%s\\n%s\\n%s\\n' "$d" "$(uname -s)" "$g"; }`// Once per load: the cache folder, Typst, the terminal and its font, the// theme, the cell. A failed setup is tried again on the next call.@@ -91,12 +92,14 @@ export function setUp($: EngineInterface): Promise<Env> {S.grid = (await storeGet($, 'grid').catch(() => undefined)) !== falseif ((await storeGet($, 'enabled').catch(() => undefined)) === false) await update($, isOn, () => false).catch(() => undefined)const isMac = os.trim() === 'Darwin'+ // Linux, on this computer: the clipboard tools, for the copy.+ if (S.hostOs === 'Linux' && !ssh) void findClipWay($).catch(() => undefined)setFrame(await readFrame($))if (canDraw) watchFrame($)const typst = await findTypst($)if (!typst) {try {- uiToast($, NO_TYPST, { timeoutMs: 8000 })+ uiToast($, noTypstOf(isMac), { timeoutMs: 8000 })} catch {}}const termFont = await termFontOf($, program, isMac).catch(() => '')diff --git a/hooks/lib/frame.ts b/hooks/lib/frame.tsindex dfd325d..0d141ad 100644--- a/hooks/lib/frame.ts+++ b/hooks/lib/frame.ts@@ -1,7 +1,7 @@// The Frame: the terminal's columns, rows and cell, the one source of truth// for every size. A small watcher prints the tty size (TIOCGWINSZ) at each-// SIGWINCH that changed it (and, on macOS once a picture is drawn, the-// clipboard's change count: register.tsx); the render hooks note the viewport (the+// SIGWINCH that changed it (and, once a picture is drawn, the clipboard's+// changes: clipboard.ts, register.tsx); the render hooks note the viewport (the// transcript can be narrower than the tty). Both restart one quiet timer:// during a burst no job starts, and once it is quiet one tty read settles// it. A changed Frame begins an epoch (epoch.ts), so a drag or a font size@@ -14,6 +14,7 @@ import { beginEpoch, holdJobs, releaseJobs } from './epoch'import { pump } from './stream'import { columnsFor, sizeOf } from './terminal'import { CELL_SH, perlFor, termFontOf, WATCH_PL } from './host'+import { clipWatchArgs } from './clipboard'import { measureFonts } from './typst'import { clockAfter, processRun, processSpawn } from './api'@@ -251,7 +252,8 @@ export function watchFrame($: EngineInterface, clip?: ((count: number | null, ficonst me: NonNullable<typeof watcher> = { clip: isClip, ended: false, stop }watcher = metry {- const child = processSpawn($, { argv: [perlFor(S.hostOs === 'Darwin'), '-e', WATCH_PL, ...(isClip ? ['clip'] : [])] })+ const isMac = S.hostOs === 'Darwin'+ const child = processSpawn($, { argv: [perlFor(isMac), '-e', WATCH_PL, ...(isClip ? ['clip', ...(clipWatchArgs(isMac) ?? [])] : [])] })void followWatcher(child, line => {if ('pid' in line) {pid = line.piddiff --git a/hooks/lib/host.ts b/hooks/lib/host.tsindex 98f56e8..e20f21f 100644--- a/hooks/lib/host.ts+++ b/hooks/lib/host.ts@@ -7,9 +7,10 @@ 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, modeOfGnome, modeOfLuminance, modeOfMacAppearance, parseOsc11, resolveMode, type HostMode } from './mode'+import { luminanceOf, modeOfColorFgBg, modeOfLuminance, modeOfMacAppearance, parseOsc11, resolveMode, schemeOfPortal, type HostMode } from './mode'import {- cmuxAppearanceOf, cmuxConfigOf, cmuxGhosttyConfigPath, cmuxSettingsOf, ghosttyBackgroundOf, ghosttyFontOf, ghosttyHasColors, ghosttyThemePaths, ghosttyThemesOf,+ cmuxAppearanceOf, cmuxConfigOf, cmuxGhosttyConfigPath, cmuxSettingsOf, familyOfFc, GHOSTTY_DEFAULT_FONT, ghosttyBackgroundOf, ghosttyFontOf, ghosttyHasColors,+ ghosttyThemePaths, ghosttyThemesOf,ghosttyValueOf, hexColorOf, itermAppearanceOf, itermFontOf, itermModeOf, jsoncOf, kittyAutoFileOf, kittyBackgroundOf,kittyConfigDirsOf, kittyEntriesOf, kittyFontOf, kittySchemeOfGnome, kittyValueOf, parseFontSpec, rioBackgroundOf,rioConfigDirOf, rioFontOf, rioForcedOf, rioThemeNamesOf, rioThemePath, tomlStringsOf, type CmuxAppearance, type KittyEntries,@@ -21,16 +22,20 @@ import { clockEvery, envGet, fsExists, fsRead, processRun } from './api'export const CELL_SH = `perl -e 'open(T, "</dev/tty") or exit 1; my $w = " " x 8; ioctl(T, ($^O eq "darwin" ? 0x40087468 : 0x5413), $w) or exit 1; print join(" ", unpack("S4", $w))'`// The watcher (frame.ts): one long-lived perl for the tty size and the// clipboard. It prints `pid <n>` first, then a line `size rows cols xpixel-// ypixel` at start and at each change. With the argument `clip` (macOS-// only: /usr/bin/perl, which has PerlObjCBridge) it also prints `clip <n>`,-// the clipboard's change count, at start and at each change, read every-// CLIP_WAKE_MS; `clip none` once when the bridge does not load (then only-// the size). It sleeps in sigsuspend with SIGWINCH and SIGALRM blocked-// outside it, so a SIGWINCH that comes while it reads is kept for the next-// sleep (never lost), and it does no work between signals. With no clip,-// an alarm each 10 s wakes it only to see that its parent still runs. Exit-// 1 when /dev/tty does not open (and no clip); exit 0 when the parent dies-// (its parent id changes) or stdout breaks.+// ypixel` at start and at each change. With the argument `clip` alone+// (macOS: /usr/bin/perl, which has PerlObjCBridge) it also prints `clip+// <n>`, the clipboard's change count, at start and at each change, read+// every CLIP_WAKE_MS; `clip none` once when the bridge does not load (then+// only the size). With `clip` and a command (Linux: the notifier of+// clipboard.ts), a child of its own process group runs that command and+// prints `clip <n>` (0, 1, ...) for each line the command prints, and `clip+// none` when it ends; the watcher stops that group when it exits. It sleeps+// in sigsuspend with SIGWINCH and SIGALRM blocked outside it, so a SIGWINCH+// that comes while it reads is kept for the next sleep (never lost), and it+// does no work between signals. With no bridge, an alarm each 10 s wakes it+// only to see that its parent still runs. Exit 1 when /dev/tty does not+// open (and no clip); exit 0 when the parent dies (its parent id changes),+// stdout breaks, or (with a notifier) at SIGTERM.export const WATCH_PL = ['use POSIX (); use Config; use Time::HiRes ();','my %n; @n{split " ", $Config{sig_name}} = split " ", $Config{sig_num};',@@ -39,14 +44,23 @@ export const WATCH_PL = ['my $parent = getppid(); my $last = ""; my $seen = ""; $| = 1;','$SIG{PIPE} = sub { exit 0 }; $SIG{WINCH} = sub {}; $SIG{ALRM} = sub {};','print "pid $$\\n" or exit 0;',- 'my $pb;',- 'if (($ARGV[0] // "") eq "clip") {',+ 'my $pb; my $relay;',+ 'if (($ARGV[0] // "") eq "clip" && @ARGV > 1) {',+ ' $relay = fork();',+ ' if (defined $relay && !$relay) {',+ ' $SIG{PIPE} = "IGNORE"; $SIG{WINCH} = "DEFAULT"; $SIG{ALRM} = "DEFAULT"; setpgrp(0, 0); my $c; my $k = 0;',+ ' if (open($c, "-|", @ARGV[1 .. $#ARGV])) { while (<$c>) { print "clip $k\\n" or last; $k++; } }',+ ' print "clip none\\n"; kill "TERM", -$$; POSIX::_exit(0);',+ ' }',+ ' if ($relay) { setpgrp($relay, $relay); $SIG{TERM} = sub { exit 0 }; } else { print "clip none\\n" or exit 0; }',+ '} elsif (($ARGV[0] // "") eq "clip") {',' $pb = eval { require Foundation; Foundation->import;',' NSBundle->bundleWithPath_("/System/Library/Frameworks/AppKit.framework")->load;',' @NSPasteboard::ISA = ("PerlObjCBridge"); my $p = NSPasteboard->generalPasteboard; defined $p->changeCount ? $p : undef };',' print "clip none\\n" or exit 0 unless $pb;','}',- 'exit 1 unless $tty || $pb;',+ 'END { kill "TERM", -$relay if $relay; }',+ 'exit 1 unless $tty || $pb || $relay;','POSIX::sigprocmask(POSIX::SIG_BLOCK(), POSIX::SigSet->new($n{WINCH}, $n{ALRM}));','my $none = POSIX::SigSet->new();','while (1) {',@@ -98,10 +112,32 @@ export const HEADERS_SH = `for f in "$@"; do head -c 24 "$f" | od -An -v -tx1; e// 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-// be read.+// be read. On Linux, when the terminal's config names none: fontconfig's+// monospace font (fc-match), which kitty and most terminals use.export async function termFontOf($: EngineInterface, program: string, isMac: boolean): Promise<string> {// Over ssh, a config here is not the one of the user's terminal.if (S.isRemote) return ''+ const font = await configFontOf($, program, isMac)+ if (font || isMac) return font+ return fcFamily($, 'monospace')+}++// A family fontconfig gives for a pattern (the first of its names), '' when+// fc-match fails. `fc-match` always gives a font, the nearest one.+async function fcFamily($: EngineInterface, pattern: string): Promise<string> {+ const got = await processRun($, ['fc-match', pattern, '-f', '%{family}'], { timeoutMs: 5000 }).catch(() => null)+ return got?.exitCode === 0 ? familyOfFc(got.stdout) : ''+}++// Ghostty draws its own JetBrains Mono when no font-family is set. On Linux+// it is used when fontconfig has it too (Typst can then draw it).+async function ghosttyDefaultFont($: EngineInterface): Promise<string> {+ const got = await processRun($, ['fc-list', '-q', GHOSTTY_DEFAULT_FONT], { timeoutMs: 5000 }).catch(() => null)+ return got?.exitCode === 0 ? GHOSTTY_DEFAULT_FONT : ''+}++// The font that the terminal's own config or profile names.+async function configFontOf($: EngineInterface, program: string, isMac: boolean): Promise<string> {if (S.isIterm && isMac) {const profile = await envGet($, 'ITERM_PROFILE')const [marks, guid] = await Promise.all([@@ -115,21 +151,20 @@ export async function termFontOf($: EngineInterface, program: string, isMac: boo}if (/ghostty/i.test(program)) {const shown = await processRun($, ['sh', '-c', GHOSTTY_SH], { timeoutMs: 5000 }).catch(() => null)- return ghosttyFontOf(shown?.stdout ?? '') ?? ''+ const family = ghosttyFontOf(shown?.stdout ?? '')+ return family ?? (isMac ? '' : await ghosttyDefaultFont($))}if (S.isKitty) {- // A family name as is; a PostScript name to its family (macOS); the- // system's monospace from fontconfig (Linux; on macOS it is Menlo).+ // A family name as is; a PostScript name to its family (macOS: AppKit;+ // Linux: fontconfig); the system's monospace from fontconfig (Linux,+ // termFontOf; on macOS it is Menlo).const font = kittyFontOf(kittyValueOf((await readKittyConfig($)).entries, 'font_family'))if (font && 'family' in font) return font.familyif (font && isMac) {const named = await processRun($, ['osascript', '-l', 'JavaScript', '-e', FAMILY_JXA, font.postscript], { timeoutMs: 5000 }).catch(() => null)return named?.exitCode === 0 ? firstLine(named.stdout) : ''}- if (!font && !isMac) {- const got = await processRun($, ['fc-match', 'monospace', '-f', '%{family}'], { timeoutMs: 5000 }).catch(() => null)- return got?.exitCode === 0 ? (got.stdout.split(',')[0] ?? '').trim() : ''- }+ if (font) return fcFamily($, `:postscriptname=${font.postscript}`)return ''}if (isRioHere()) return rioFontOf((await readRioConfig($)).config)@@ -285,10 +320,8 @@ async function readKittyMode($: EngineInterface): Promise<HostMode | null> {let auto: { file: string; entries: KittyEntries } | null = nullif (found.some(Boolean)) {let scheme: (typeof schemes)[number] | null = null- if (S.hostOs === 'Linux') {- const got = await processRun($, ['gsettings', 'get', 'org.gnome.desktop.interface', 'color-scheme'], { timeoutMs: HOST_CHECK_MS }).catch(() => null)- scheme = got && got.exitCode === 0 ? kittySchemeOfGnome(got.stdout) : null- } else scheme = (await readOsMode($).catch(() => null))?.mode ?? null+ if (S.hostOs === 'Linux') scheme = (await readLinuxScheme($).catch(() => null))?.scheme ?? null+ else scheme = (await readOsMode($).catch(() => null))?.mode ?? nullif (scheme && found[schemes.indexOf(scheme)]) {const file = kittyAutoFileOf(scheme)auto = { file, entries: await kittyEntriesOf(`${dir}/${file}`, path => readText($, path), { home }) }@@ -324,20 +357,48 @@ async function readRioMode($: EngineInterface): Promise<HostMode | null> {return bg ? { mode: modeOfLuminance(luminanceOf(bg)), source: 'Rio', detail: got.detail } : null}-// The OS appearance: macOS, or GNOME's colour scheme on Linux.+// The OS appearance: macOS, or on Linux the desktop's colour scheme+// (readLinuxScheme; no preference is light, as GNOME's default is).async function readOsMode($: EngineInterface): Promise<HostMode | null> {if (S.hostOs === 'Darwin') {const got = await processRun($, ['defaults', 'read', '-g', 'AppleInterfaceStyle'], { timeoutMs: HOST_CHECK_MS }).catch(() => null)return got ? { mode: modeOfMacAppearance(got.exitCode, got.stdout), source: 'macOS' } : null}if (S.hostOs === 'Linux') {- const got = await processRun($, ['gsettings', 'get', 'org.gnome.desktop.interface', 'color-scheme'], { timeoutMs: HOST_CHECK_MS }).catch(() => null)- const mode = got && got.exitCode === 0 ? modeOfGnome(got.stdout) : null- if (mode) return { mode, source: 'GNOME' }+ const seen = await readLinuxScheme($).catch(() => null)+ if (seen) return { mode: seen.scheme === 'dark' ? 'dark' : 'light', source: seen.source }}return null}+// The freedesktop portal's colour scheme (GNOME, KDE and others: the value+// kitty reads too), by gdbus, else busctl. The first tool that works is+// kept, so each check runs one process; when neither works, GNOME's+// gsettings is read in its place.+const PORTAL_ARGS = {+ gdbus: ['gdbus', 'call', '--session', '--dest', 'org.freedesktop.portal.Desktop', '--object-path', '/org/freedesktop/portal/desktop',+ '--method', 'org.freedesktop.portal.Settings.Read', 'org.freedesktop.appearance', 'color-scheme'],+ busctl: ['busctl', '--user', 'call', 'org.freedesktop.portal.Desktop', '/org/freedesktop/portal/desktop', 'org.freedesktop.portal.Settings',+ 'Read', 'ss', 'org.freedesktop.appearance', 'color-scheme'],+} as const+type LinuxScheme = { scheme: 'dark' | 'light' | 'no-preference'; source: 'desktop portal' | 'GNOME' }+async function readLinuxScheme($: EngineInterface): Promise<LinuxScheme | null> {+ const tools = S.portalTool === null ? (['gdbus', 'busctl'] as const) : S.portalTool ? [S.portalTool] : []+ for (const tool of tools) {+ const got = await processRun($, PORTAL_ARGS[tool], { timeoutMs: HOST_CHECK_MS }).catch(() => null)+ const scheme = got && got.exitCode === 0 ? schemeOfPortal(got.stdout) : null+ if (scheme) {+ S.portalTool = tool+ return { scheme, source: 'desktop portal' }+ }+ }+ if (S.portalTool === null) S.portalTool = ''+ if (S.portalTool) return null+ const got = await processRun($, ['gsettings', 'get', 'org.gnome.desktop.interface', 'color-scheme'], { timeoutMs: HOST_CHECK_MS }).catch(() => null)+ const scheme = got && got.exitCode === 0 ? kittySchemeOfGnome(got.stdout) : null+ return scheme ? { scheme, source: 'GNOME' } : null+}+// One read of the OS appearance (never two at once); a changed mode redraws.export async function pollHost($: EngineInterface) {if (S.checking || S.setting !== 'auto') returndiff --git a/hooks/lib/mode.ts b/hooks/lib/mode.tsindex e540ca6..135ea10 100644--- a/hooks/lib/mode.ts+++ b/hooks/lib/mode.ts@@ -19,7 +19,11 @@ 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' | 'COLORFGBG'; detail?: string }+export type HostMode = {+ mode: IuiTheme+ source: 'terminal' | 'iTerm2' | 'Ghostty' | 'cmux' | 'kitty' | 'Rio' | 'macOS' | 'GNOME' | 'desktop portal' | 'COLORFGBG'+ detail?: string+}// `defaults read -g AppleInterfaceStyle`: "Dark" in dark mode; in light mode// the key does not exist and the command fails.@@ -36,6 +40,15 @@ export function modeOfGnome(stdout: string): IuiTheme | null {return null}+// The freedesktop portal's `org.freedesktop.appearance color-scheme`+// (Settings.Read), as gdbus prints it (`(<<uint32 1>>,)`) or busctl (`v v u+// 1`): 1 dark, 2 light, 0 no preference; null for anything else.+export function schemeOfPortal(stdout: string): 'dark' | 'light' | 'no-preference' | null {+ const m = /(?:\buint32|\bu)\s+(\d+)\b/.exec(stdout)+ const v = m ? Number(m[1]) : -1+ return v === 1 ? 'dark' : v === 2 ? 'light' : v === 0 ? 'no-preference' : null+}+// COLORFGBG, "fg;bg" or "fg;x;bg": the last field is the background colour// index. 0-6 and 8 are dark, 7 and 15 light; anything else is not known.export function modeOfColorFgBg(value: string | undefined): IuiTheme | null {diff --git a/hooks/lib/plan.tsx b/hooks/lib/plan.tsxindex 91a3ee6..8d5eabf 100644--- a/hooks/lib/plan.tsx+++ b/hooks/lib/plan.tsx@@ -15,7 +15,7 @@ import { S, writesLive } from './state'import { firstLine } from './markdown'import type { Drawing } from './answer'import { drawPages, type ShownLink } from './draw'-import { clockAfter, commandRun, fsRead, processRun, promptSubmit, turnAbort, uiAsk, uiResolve } from './api'+import { clockAfter, commandRun, envGet, fsRead, processRun, promptSubmit, turnAbort, uiAsk, uiResolve } from './api'// The question's chip and its two wordings.export const PLAN_HEADER = 'Plan'@@ -146,14 +146,32 @@ export function decisionOf(verdict: PlanVerdict, toolInput: unknown): Permission// The editor that opens the plan file and waits until it is closed: VS Code// (`code --wait`) when it is on the PATH, else TextEdit on a Mac (`open -W`-// waits until TextEdit quits). Not over ssh, where TextEdit is the remote-// computer's. A mod has no terminal, so no terminal editor.-export function editorArgv(o: { code: string; isMac: boolean; isRemote: boolean }, file: string): string[] | null {+// waits until TextEdit quits), else on Linux a GUI editor that waits+// (`gui`: its path and flag, LINUX_EDITORS). Not over ssh, where TextEdit+// or the GUI editor is the remote computer's. A mod has no terminal, so no+// terminal editor; xdg-open does not wait, so it is not used.+export function editorArgv(o: { code: string; isMac: boolean; isRemote: boolean; gui?: readonly string[] }, file: string): string[] | null {if (o.code) return [o.code, '--wait', file]if (o.isMac && !o.isRemote) return ['open', '-W', '-t', file]+ if (!o.isMac && !o.isRemote && o.gui?.length) return [...o.gui, file]return null}+// The GUI editors on Linux that can wait until the file is closed, in the+// order they are looked for, with the flag that makes them wait.+export const LINUX_EDITORS: readonly (readonly [string, string])[] = [+ ['codium', '--wait'], ['zed', '--wait'], ['zeditor', '--wait'], ['subl', '--wait'], ['kate', '--block'], ['gedit', '--wait'], ['gvim', '-f'],+]+// Prints `name path` for the first editor of LINUX_EDITORS on the PATH.+const GUI_EDITOR_SH = `for c in ${LINUX_EDITORS.map(([name]) => name).join(' ')}; do p=$(command -v "$c" 2>/dev/null) && { echo "$c $p"; break; }; done`++// The editor of GUI_EDITOR_SH's output: its path and its flag; [] for none.+export function guiEditorOf(stdout: string): string[] {+ const m = /^(\S+) (\/.*)$/.exec(firstLine(stdout))+ const flag = m ? LINUX_EDITORS.find(([name]) => name === m[1])?.[1] : undefined+ return m && flag ? [m[2]!, flag] : []+}+// ---- The flow -----------------------------------------------------------------// The `code` command's path ('' when none), looked up once per load.@@ -172,6 +190,22 @@ async function findCode($: EngineInterface): Promise<string> {return found}+// On Linux with a display (X11 or Wayland), a GUI editor that waits+// ([] when none), looked up once per load.+async function findGuiEditor($: EngineInterface): Promise<string[]> {+ if (S.planGui !== null) return S.planGui+ let found: string[] = []+ if ((await envGet($, 'WAYLAND_DISPLAY')) || (await envGet($, 'DISPLAY'))) {+ for (const flag of ['-lc', '-c']) {+ const got = await processRun($, ['sh', flag, GUI_EDITOR_SH], { timeoutMs: 5000 }).catch(() => null)+ found = got?.exitCode === 0 ? guiEditorOf(got.stdout) : []+ if (found.length) break+ }+ }+ S.planGui = found+ return found+}+// What the mod's question decided: a verdict for the PermissionRequest, or// the person's words (a deny of the call: Claude revises the plan).export type PlanOutcome = { kind: 'verdict'; verdict: PlanVerdict } | { kind: 'feedback'; message: string }@@ -185,7 +219,9 @@ export async function decidePlan($: EngineInterface,o: { plan: string; callPlan: string; file: string; isMac: boolean; isRemote: boolean; onEdited: (plan: string) => void },): Promise<PlanOutcome> {- const argv = o.file ? editorArgv({ code: await findCode($), isMac: o.isMac, isRemote: o.isRemote }, o.file) : null+ const code = o.file ? await findCode($) : ''+ const gui = o.file && !code && !o.isMac && !o.isRemote ? await findGuiEditor($) : []+ const argv = o.file ? editorArgv({ code, isMac: o.isMac, isRemote: o.isRemote, gui }, o.file) : nullconst canEdit = !!argvlet plan = o.planlet isEdited = falsediff --git a/hooks/lib/settings.ts b/hooks/lib/settings.tsindex 12a3950..c5c9f1d 100644--- a/hooks/lib/settings.ts+++ b/hooks/lib/settings.ts@@ -61,8 +61,16 @@ export const GRID_VERSION = '2'export const COMPILE_TIMEOUT_MS = 20000export const ALT_CHARS = 200// Where Typst is when the login shell's PATH does not find it. `~` is $HOME.-export const TYPST_FALLBACKS = ['/opt/homebrew/bin/typst', '/usr/local/bin/typst', '/usr/bin/typst', '/snap/bin/typst', '~/.cargo/bin/typst', '~/.local/bin/typst']+export const TYPST_FALLBACKS = [+ '/opt/homebrew/bin/typst', '/usr/local/bin/typst', '/usr/bin/typst', '/snap/bin/typst', '~/.cargo/bin/typst', '~/.local/bin/typst',+ '/home/linuxbrew/.linuxbrew/bin/typst', '~/.linuxbrew/bin/typst',+]export const NO_TYPST = 'Intelligent UI: install Typst (brew install typst) to see rendered answers'+// How to install Typst: brew on macOS; on Linux, cargo or a release file+// (docs/install.md has more ways).+export const typstHintOf = (isMac: boolean) =>+ isMac ? 'brew install typst' : 'cargo install --locked typst-cli, or a release from github.com/typst/typst/releases'+export const noTypstOf = (isMac: boolean) => (isMac ? NO_TYPST : `Intelligent UI: install Typst (${typstHintOf(false)}) to see rendered answers`)// Typst downloads a package it doesn't find under --package-path; a proxy// nobody listens on makes that fail at once, so a live block never fetches.export const NO_NETWORK = 'http://127.0.0.1:9'diff --git a/hooks/lib/setup.ts b/hooks/lib/setup.tsindex 32b375e..b15e1d1 100644--- a/hooks/lib/setup.ts+++ b/hooks/lib/setup.ts@@ -67,8 +67,14 @@ async function shellRc($: EngineInterface): Promise<ShellRc | null> {})}+// What /iui setup says where iTerm2 does not run (not macOS): it changes no file.+export const SETUP_NOT_MAC = '/iui setup is for iTerm2, which runs on macOS only, so Intelligent UI changed no file. ' ++ 'On Linux, kitty and Ghostty show pictures with no setup. ' ++ 'For Rio, set CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1 before you start Claude Code. Run /iui details to see if this terminal shows pictures.'+// Adds (or removes) the setup block. Returns what to tell the person.export async function runSetup($: EngineInterface, remove: boolean): Promise<string> {+ if (S.hostOs && S.hostOs !== 'Darwin') return SETUP_NOT_MACconst rc = await shellRc($)const manual = `export CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1 (only in iTerm2, not in tmux or screen)`if (!rc) return `Intelligent UI does not know your shell, so it changed no file. Add this to your shell's start file: ${manual}`diff --git a/hooks/lib/state.ts b/hooks/lib/state.tsindex 06c1903..45f0113 100644--- a/hooks/lib/state.ts+++ b/hooks/lib/state.ts@@ -10,6 +10,7 @@ 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 { DEFAULT_HEIGHT, DEFAULT_SIZE, DEFAULT_WIDTH, type Height, type Width } from './settings'import { uiInvalidate } from './api'@@ -167,16 +168,24 @@ export const S = {setupAsked: false,watch: null as { cancel: () => void } | null,checking: false,+ // Linux: the tool that reads the desktop portal's colour scheme (host.ts;+ // null: not tried yet, '': none works, so GNOME's gsettings is read).+ portalTool: null as 'gdbus' | 'busctl' | '' | null,+ // Linux: how the clipboard is read and watched (clipboard.ts; null: not+ // looked up, as on macOS and over ssh).+ clipWay: null as ClipWay | null,// Streaming: model requests of the main loop in flight.stepsLive: 0,// The plan (plan.tsx): the main loop's running turn (`turn.start`), the// verdict the mod's question gave for the PermissionRequest that follows// (null: none, the engine's dialog asks), the question asked now ('': none),- // and the `code` command's path (null: not looked up yet; '': none).+ // and the `code` command's path (null: not looked up yet; '': none), and+ // on Linux a GUI editor that waits (its path and flag; [] none).mainTurnId: '',planVerdict: null as PlanVerdict | null,planAsking: '',planCode: null as string | null,+ planGui: null as string[] | null,// The update check (updates.ts), read once per load (`updatesLoading`):// `/iui updates` (on by default), the variable that turns the check off// ('' none), this mod's version ('' not known) and the last check (null:diff --git a/hooks/lib/terminals.ts b/hooks/lib/terminals.tsindex 30cdd86..61df508 100644--- a/hooks/lib/terminals.ts+++ b/hooks/lib/terminals.ts@@ -114,6 +114,7 @@ export function ghosttyThemePaths(name: string, o: { xdgConfig?: string; home: s...(o.resources ? [`${o.resources}/themes/${name}`] : []),`/Applications/Ghostty.app/Contents/Resources/ghostty/themes/${name}`,`/usr/share/ghostty/themes/${name}`,+ `/usr/local/share/ghostty/themes/${name}`,]}@@ -134,6 +135,13 @@ export function ghosttyBackgroundOf(config: string, appearance: IuiTheme | null,return themeBg[appearance] || null}+// The font Ghostty carries and draws when no font-family is set.+export const GHOSTTY_DEFAULT_FONT = 'JetBrains Mono'++// fontconfig's `%{family}` (fc-match -f): the first of its names, which+// can be a list (`Noto Sans Mono,Noto Sans Mono Regular`).+export const familyOfFc = (stdout: string) => (stdout.split(',')[0] ?? '').trim()+// The first `font-family = X` of `ghostty +show-config`.export function ghosttyFontOf(config: string): string | null {for (const line of config.split('\n')) {diff --git a/hooks/register.tsx b/hooks/register.tsxindex 46300ff..7b3f882 100644--- a/hooks/register.tsx+++ b/hooks/register.tsx@@ -22,7 +22,7 @@ import type { EngineInterface, Register, RenderElement, RenderViewport } from 'cimport {DEFAULT_THEME, gridText, heightText, IMAGE_MAX_COLUMNS, MARGIN_TOP, MAX_HEIGHT, MAX_SIZE, MAX_WIDTH, MIN_HEIGHT, MIN_SIZE, MIN_WIDTH, RESULTS_KEPT, TYPST_PROMPT,- widthText,+ typstHintOf, widthText,} from './lib/settings'import { clip, drawnAnswers, editedPlans, keep, queue, refresh, running, S, subagentPlans, writesLive, type Env } from './lib/state'import { beginEpoch } from './lib/epoch'@@ -37,13 +37,14 @@ import { finalizeAll } from './lib/stream'import { noteDrawn, noteDrawnAgain, noteOnScreen, wordsOf } from './lib/probe'import { codePointsOf, decodeSelection, hasPlaceholders, joinSegments, pageTopsOf, pickPages, textOfRun, type Pick, type Segment } from './lib/copy'import { pagesOf, type Drawing } from './lib/answer'+import { autoCopyText, clipboardNow, clipWatchArgs, clipWayReady } from './lib/clipboard'import { setUp } from './lib/env'import { frameFor, noteView, stopWatch, watchFrame, watchState } from './lib/frame'import { roomColumns } from './lib/terminal'import { onScreenOf, pastedImagePath, pastedNumbers, sentFiles } from './lib/images'import { pasteDir, rowsAfter, sentOf, shownOf, underRow, type Shown, type Under } from './lib/pictures'import { checkUpdates, loadUpdates, updateLine, updateNotice, type UpdateState } from './lib/updates'-import { clockNow, fsWrite, processRun, sessionSurfaces, storeSet, uiCopy, uiResolve, uiSelection, uiToast } from './lib/api'+import { clockNow, fsWrite, sessionSurfaces, storeSet, uiCopy, uiResolve, uiSelection, uiToast } from './lib/api'import {currentPlan, decidePlan, decisionOf, drawAskLine, drawPlanResult, drawPlanUse, isPlanQuestion, planFileOf, planInputOf, planOf,planShownOf, scheduleClear, type PlanVerdict,@@ -72,7 +73,7 @@ export {type ThemeInfo, type ThemeProblem, type ThemeSyntax,} from './lib/themes'export { commandSuggestions, parseCommand, type Command, type Suggestion } from './lib/command'-export { hasSetup, SETUP_END, SETUP_START, setupBlock, shellRcOf, withoutSetup, withSetup, type ShellRc } from './lib/setup'+export { hasSetup, SETUP_END, SETUP_NOT_MAC, SETUP_START, setupBlock, shellRcOf, withoutSetup, withSetup, type ShellRc } from './lib/setup'export { OSC11_PL, perlFor, WATCH_PL } from './lib/host'export {convertCall, isSafePage, measureCall, noNetworkEnv, pageRowsOf, parseOd, pngSize, probeCall, resultOf, roomInputs, shouldRetrySafe, typstCall, typstInputs,@@ -83,12 +84,13 @@ export {export { nextJob } from './lib/stream'export * from './lib/images'export * from './lib/copy'+export { autoCopyText, CLIP_TOOLS, clipToolsOf, clipWayOf, FIND_SH, GTK_READ_PY, GTK_WATCH_PY, WL_WATCH_SH, X11_WATCH_SH, type ClipTool, type ClipWay } from './lib/clipboard'export {agoText, checkedOf, compareVersions, isDue, isNewer, parseVersion, shouldTell, toldOf, UPDATE_EVERY_MS, UPDATE_FETCH_MS, UPDATE_STEPS, UPDATE_TOAST_MS,UPDATE_URL, updateLine, updateNotice, updateToast, versionOf,} from './lib/updates'export {- choiceOf, decisionOf, editorArgv, feedbackOf, isPlanQuestion, normalPath, PLAN_ASK_LINE, PLAN_AUTO, PLAN_CLEAR, PLAN_DRAWING, PLAN_EDIT,+ choiceOf, decisionOf, editorArgv, feedbackOf, guiEditorOf, LINUX_EDITORS, isPlanQuestion, normalPath, PLAN_ASK_LINE, PLAN_AUTO, PLAN_CLEAR, PLAN_DRAWING, PLAN_EDIT,PLAN_FEEDBACK, PLAN_HEADER, PLAN_IMPLEMENT, PLAN_MANUAL, PLAN_QUESTION, PLAN_QUESTION_EDITED, PLAN_REJECTED, planFileOf, planInputOf,planOf, planOptions, planShownOf, shortPath, verdictOf, type PlanChoice, type PlanVerdict,} from './lib/plan'@@ -203,9 +205,10 @@ async function planEnv($: EngineInterface): Promise<Env | null> {// ---- Copy -----------------------------------------------------------------// A mouse copy over a picture puts kitty placeholder cells on the clipboard,-// and no hook sees that copy. On macOS the watcher (lib/frame.ts) prints the-// clipboard's change count when it changes; at a change the clipboard is-// read once (pbpaste) and, when it holds placeholders, written again with+// and no hook sees that copy. The watcher (lib/frame.ts) prints a line when+// the clipboard changes (macOS: its change count; Linux: a notifier's+// line, lib/clipboard.ts); at a change the clipboard is read once (pbpaste,+// wl-paste, xclip, xsel or GTK) and, when it holds placeholders, written again with// the words under them (see lib/copy.ts; the drawn pages and the words of// a page are in lib/probe.ts). No timer reads the clipboard or the// selection.@@ -247,12 +250,6 @@ async function readCopy($: EngineInterface, raw: string, requestId?: string): Prreturn read}-// The clipboard now (pbpaste, UTF-8); null when it can not be read.-async function clipboardNow($: EngineInterface): Promise<string | null> {- const got = await processRun($, ['pbpaste'], { timeoutMs: 2000, env: { LANG: 'en_US.UTF-8', LC_ALL: 'en_US.UTF-8' } }).catch(() => null)- return got && got.exitCode === 0 ? got.stdout : null-}-// Writes the text read for `raw` (placeholders) to the clipboard, once:// our own write is never read back as new. Just before the write the// clipboard is read again: a newer copy (made while the picture was read,@@ -283,9 +280,9 @@ async function copyRead($: EngineInterface, raw: string, requestId?: string) {// line breaks that the selection does not have, or the other way).const sameCopy = (a: string, b: string) => a.replace(/\r\n/g, '\n').replace(/\s+$/, '') === b.replace(/\r\n/g, '\n').replace(/\s+$/, '')-// A watcher line `clip <count>` (null: `clip none`, no PerlObjCBridge: the-// automatic copy stays off). The first count of a child (at its start) is-// only noted: the clipboard then is no new copy (after a hot reload, it can+// A watcher line `clip <count>` (null: `clip none`, no PerlObjCBridge or+// the Linux notifier ended: the automatic copy stays off). The first count+// of a child (at its start) is only noted: the clipboard then is no new copy (after a hot reload, it can// be an old copy of picture cells).function clipChanged($: EngineInterface, count: number | null, first: boolean) {if (count === null) {@@ -296,7 +293,7 @@ function clipChanged($: EngineInterface, count: number | null, first: boolean) {if (!first) void readClipboard($).catch(() => undefined)}-// The clipboard changed: one read (pbpaste). Placeholders that are not our+// The clipboard changed: one read (clipboardNow). Placeholders that are not our// own write are read and written back as text. A clipboard with no// placeholders is never touched. When this session has a selection// (fullscreen), the clipboard is rewritten only when it is that selection:@@ -324,15 +321,16 @@ async function readClipboard($: EngineInterface) {}}-// The watcher's clipboard part: on macOS, on this computer (over ssh-// pbpaste reads the remote one's clipboard), only while Intelligent UI is-// on (its callers draw, or read the atom) and a picture is drawn. It is a-// new child (the flag is an argument): its first count is only noted. A-// child that runs is kept; one that ended is started again (watchFrame-// caps it). With no-// PerlObjCBridge the child goes on as it is (size only).+// The watcher's clipboard part: on macOS, or on Linux with a tool that sees+// the changes (lib/clipboard.ts), on this computer (over ssh the clipboard+// read is the remote one's), only while Intelligent UI is on (its callers+// draw, or read the atom) and a picture is drawn. It is a new child (the+// flag is an argument): its first count is only noted. A child that runs+// is kept; one that ended is started again (watchFrame caps it). With no+// PerlObjCBridge (or a notifier that ended) the child goes on as it is+// (size only).function watchClipboard($: EngineInterface) {- if (!S.env?.isMac || S.isRemote || !drawnAnswers.size || clip.none) return+ if (!S.env || S.isRemote || !drawnAnswers.size || clip.none || clipWatchArgs(S.env.isMac) === null) returnwatchFrame($, (count, first) => clipChanged($, count, first))}@@ -344,13 +342,11 @@ function stopClipboard($: EngineInterface) {// The automatic copy now, for /iui details and dump.function autoCopyOf(isOn: boolean): string {- if (!S.env?.isMac) return 'off (not macOS)'- if (S.isRemote) return 'off (ssh)'- if (!isOn) return 'off (Intelligent UI is off)'- if (clip.none) return 'off (no PerlObjCBridge in /usr/bin/perl)'- if (!drawnAnswers.size) return 'off (no picture yet)'const now = watchState()- return now?.clip && !now.ended ? 'on' : 'off (the watcher does not run)'+ return autoCopyText({+ isMac: !!S.env?.isMac, hostOs: S.hostOs, isRemote: S.isRemote, isOn, none: clip.none, drawn: drawnAnswers.size > 0,+ running: !!now?.clip && !now.ended, way: S.clipWay,+ })}// The update check's state now, for /iui, /iui details and /iui updates.@@ -392,6 +388,7 @@ function screenText(pick: { id: string; page: number }): string {// read, and the same in full in <cache>/copy-debug.json. `on`: Intelligent// UI is on.async function dump($: EngineInterface, on: boolean): Promise<string> {+ await clipWayReady()const auto = autoCopyOf(on)if (!clip.raw) return `Intelligent UI: no clipboard text with picture cells seen yet (auto copy ${auto}; ${drawnAnswers.size} pictures drawn).`const read = await readCopy($, clip.raw, clip.rawRow)@@ -564,11 +561,12 @@ export const register: Register = on => {const bad = asked.kind === 'bad' ? `Not understood: "${e.args.trim()}".\n` : ''const theme = S.look?.name ?? DEFAULT_THEMEif (asked.kind === 'details') {- const font = ready.termFont ? `terminal font ${ready.termFont}` : 'terminal font not known (Menlo assumed)'- const typst = ready.typst ? `Typst: ${ready.typst}` : 'Typst: not found (brew install typst)'+ const font = ready.termFont ? `terminal font ${ready.termFont}` : `terminal font not known (${ready.isMac ? 'Menlo' : "the theme's code font"} assumed)`+ const typst = ready.typst ? `Typst: ${ready.typst}` : `Typst: not found (${typstHintOf(ready.isMac)})`const terminal = ready.canDraw? `this terminal draws pictures${ready.inline ? ' (over ssh, sent as bytes)' : ''}`: 'Claude Code draws no pictures here (it does in kitty and Ghostty, in iTerm2 3.6+ and Rio 0.5.27+ 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'+ await clipWayReady()const auto = `Auto copy: ${autoCopyOf(state === 'on')}`const updates = `Update checks: ${updateLine(await updateState($))}`return { text: `Intelligent UI is ${state}, theme ${theme}, ${modeLine(S.theme, S.setting, S.settingRaw, S.host)}, text size ${S.size}%, width ${widthText(S.width)}, image and drawing height ${heightText(S.height)}, row grid ${S.grid ? 'on' : 'off'}, ${font}. ${typst}; ${terminal}.\n${auto}\n${updates}` }@@ -577,8 +575,11 @@ export const register: Register = on => {const sized = (v: number | 'full' | 'half', unit: string) => (typeof v === 'number' ? `${v} ${unit}` : v)const lines = [`Intelligent UI is ${state}: theme ${theme}, ${S.theme}, text ${S.size}%, width ${sized(S.width, 'columns')}, height ${sized(S.height, 'rows')}, grid ${S.grid ? 'on' : 'off'}.`]if (S.setupNeeded) lines.push('In iTerm2, run /iui setup once to show pictures.')- else if (!ready.canDraw) lines.push('This terminal shows no pictures, so answers stay text. Pictures show in kitty, Ghostty and iTerm2 3.6+.')- if (!ready.typst) lines.push('Typst is not installed, so answers stay text. Install it: brew install typst')+ else if (!ready.canDraw) {+ const where = ready.isMac ? 'kitty, Ghostty and iTerm2 3.6+' : 'kitty and Ghostty, and in Rio with CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1'+ lines.push(`This terminal shows no pictures, so answers stay text. Pictures show in ${where}.`)+ }+ if (!ready.typst) lines.push(`Typst is not installed, so answers stay text. Install it: ${typstHintOf(ready.isMac)}`)const notice = updateNotice(await updateState($))if (notice) lines.push(notice)lines.push('Change: /iui on | off | size | width | height | grid | updates | theme. More: /iui details')diff --git a/tests/frame.test.ts b/tests/frame.test.tsindex d2aca12..6d91422 100644--- a/tests/frame.test.ts+++ b/tests/frame.test.ts@@ -117,8 +117,8 @@ test('WATCH_PL sleeps in sigsuspend with SIGWINCH and SIGALRM blocked outside itexpect(WATCH_PL).not.toContain('sleep')})-test('WATCH_PL loads the bridge in an eval only with the clip argument, and says clip none when it fails', () => {- expect(WATCH_PL).toContain('if (($ARGV[0] // "") eq "clip")')+test('WATCH_PL loads the bridge in an eval only with the clip argument alone, and says clip none when it fails', () => {+ expect(WATCH_PL).toContain('} elsif (($ARGV[0] // "") eq "clip") {')expect(WATCH_PL).toContain('$pb = eval { require Foundation; Foundation->import;')expect(WATCH_PL).toContain('@NSPasteboard::ISA = ("PerlObjCBridge")')expect(WATCH_PL).toContain('print "clip none\\n" or exit 0 unless $pb;')@@ -126,11 +126,21 @@ test('WATCH_PL loads the bridge in an eval only with the clip argument, and saysexpect(WATCH_PL).toContain('print "size $line\\n"')expect(WATCH_PL).toContain('print "pid $$\\n"')// No tty and no clipboard part: exit 1.- expect(WATCH_PL).toContain('exit 1 unless $tty || $pb;')+ expect(WATCH_PL).toContain('exit 1 unless $tty || $pb || $relay;')expect(perlFor(true)).toBe('/usr/bin/perl')expect(perlFor(false)).toBe('perl')})+test('WATCH_PL with clip and a command (Linux): a child in its own group relays the lines, and the group stops with the watcher', () => {+ expect(WATCH_PL).toContain('if (($ARGV[0] // "") eq "clip" && @ARGV > 1) {')+ expect(WATCH_PL).toContain('setpgrp(0, 0)')+ expect(WATCH_PL).toContain('open($c, "-|", @ARGV[1 .. $#ARGV])')+ expect(WATCH_PL).toContain('print "clip $k\\n" or last; $k++;')+ expect(WATCH_PL).toContain('print "clip none\\n"; kill "TERM", -$$; POSIX::_exit(0);')+ expect(WATCH_PL).toContain('setpgrp($relay, $relay); $SIG{TERM} = sub { exit 0 };')+ expect(WATCH_PL).toContain('END { kill "TERM", -$relay if $relay; }')+})+// ---- The quiet timer ----------------------------------------------------------------// A timer in memory: `advance` runs each wait that comes due, in order.diff --git a/tests/linux.test.ts b/tests/linux.test.tsnew file mode 100644index 0000000..f4fa8e9--- /dev/null+++ b/tests/linux.test.ts@@ -0,0 +1,330 @@+import { expect, mock, test } from 'claude-code/testing'++import {+ autoCopyText, clipToolsOf, clipWayOf, editorArgv, familyOfFc, FIND_SH, GHOSTTY_DEFAULT_FONT, GTK_READ_PY, GTK_WATCH_PY, guiEditorOf, LINUX_EDITORS,+ placeholderCell, schemeOfPortal, SETUP_NOT_MAC, WATCH_PL, WL_WATCH_SH, X11_WATCH_SH, type ClipWay,+} from '../hooks/register'+import { CACHE_SH } from '../hooks/lib/env'+import { SMALL_MARKS, SMALL_MD } from './copy-fixture'++const ok = (stdout: string, exitCode = 0) => ({ value: { exitCode, stdout, stderr: exitCode ? 'error: boom' : '', isStdoutTruncated: false, isStderrTruncated: false } })++// ---- The clipboard: which way on Linux -----------------------------------------++const ALL = { 'wl-paste': '/usr/bin/wl-paste', xclip: '/usr/bin/xclip', xsel: '/usr/bin/xsel', clipnotify: '/usr/local/bin/clipnotify', gtk: '/usr/bin/python3' }++test('the tools found: `name path` lines, absolute paths only', () => {+ expect(clipToolsOf('wl-paste /usr/bin/wl-paste\nxclip /usr/bin/xclip\ngtk /usr/bin/python3\nxsel xsel\nother /bin/x\n')).toEqual({+ 'wl-paste': '/usr/bin/wl-paste', xclip: '/usr/bin/xclip', gtk: '/usr/bin/python3',+ })+ expect(clipToolsOf('')).toEqual({})+ // GTK is checked only when there is no clipnotify.+ expect(FIND_SH).toContain('command -v clipnotify >/dev/null 2>&1 || {')+ expect(FIND_SH).toContain('echo "gtk $p"')+})++test('Wayland (not GNOME): wl-paste reads, and its --watch sees each change', () => {+ const way = clipWayOf({ wayland: true, x11: true, desktop: 'KDE', found: ALL })+ expect(way).toEqual({+ name: 'wl-paste --watch (Wayland)', read: ['/usr/bin/wl-paste', '-n', '-t', 'text'],+ watch: ['/usr/bin/wl-paste', '--watch', 'sh', '-c', WL_WATCH_SH], wayland: true,+ })+ // The data goes to the end, and a sensitive copy gives no line.+ expect(WL_WATCH_SH).toBe('cat >/dev/null; [ "$CLIPBOARD_STATE" = sensitive ] || echo')+})++test('GNOME on Wayland (no data-control): the X11 tools through Xwayland come first, wl-paste last', () => {+ expect(clipWayOf({ wayland: true, x11: true, desktop: 'ubuntu:GNOME', found: ALL })).toEqual({+ name: 'clipnotify and xclip (X11, Xwayland)', read: ['/usr/bin/xclip', '-o', '-selection', 'clipboard', '-t', 'UTF8_STRING'],+ watch: ['sh', '-c', X11_WATCH_SH, '/usr/local/bin/clipnotify'], wayland: false,+ })+ // Only GTK (a GNOME desktop with no other tool): GTK reads and watches.+ const gtk = clipWayOf({ wayland: true, x11: true, desktop: 'GNOME', found: { gtk: '/usr/bin/python3' } }) as Extract<ClipWay, { name: string }>+ expect(gtk.name).toBe('GTK (X11, Xwayland)')+ expect(gtk.read).toEqual(['/usr/bin/env', 'GDK_BACKEND=x11', 'PYTHONIOENCODING=utf-8', '/usr/bin/python3', '-c', GTK_READ_PY])+ expect(gtk.watch).toEqual(['/usr/bin/env', 'GDK_BACKEND=x11', 'PYTHONIOENCODING=utf-8', '/usr/bin/python3', '-c', GTK_WATCH_PY])+ // No X tool: wl-paste (its --watch can fail; then the copy is off).+ expect(clipWayOf({ wayland: true, x11: true, desktop: 'GNOME', found: { 'wl-paste': '/w' } })).toMatchObject({ name: 'wl-paste --watch (Wayland)', wayland: true })+})++test('X11: clipnotify or GTK sees the changes; xclip, xsel or GTK reads', () => {+ expect(clipWayOf({ wayland: false, x11: true, desktop: 'XFCE', found: { xsel: '/x/xsel', clipnotify: '/x/cn' } })).toMatchObject({+ name: 'clipnotify and xsel (X11)', read: ['/x/xsel', '-o', '-b'],+ })+ expect(clipWayOf({ wayland: false, x11: true, desktop: '', found: { xclip: '/x/xclip', gtk: '/p' } })).toMatchObject({+ name: 'GTK and xclip (X11)', read: ['/x/xclip', '-o', '-selection', 'clipboard', '-t', 'UTF8_STRING'],+ })+ // wl-paste is not used with no Wayland display.+ expect(clipWayOf({ wayland: false, x11: true, desktop: '', found: { 'wl-paste': '/w', xclip: '/x/xclip' } })).toEqual({+ off: 'no clipnotify and no GTK 3 for Python: X11 has no clipboard event for xclip',+ })+ expect(clipWayOf({ wayland: false, x11: true, desktop: '', found: {} })).toEqual({ off: 'no xclip, xsel or GTK 3 for Python, and no clipnotify' })+ expect(clipWayOf({ wayland: true, x11: false, desktop: 'sway', found: { xclip: '/x' } })).toEqual({ off: 'no wl-paste (install wl-clipboard)' })+ expect(clipWayOf({ wayland: false, x11: false, desktop: '', found: ALL })).toEqual({ off: 'no Wayland or X11 display' })+ // clipnotify 1.0.3+ loops by itself (-l); an older one exits at each change.+ expect(X11_WATCH_SH).toBe('echo; while "$0" -s clipboard -l; do echo; done')+})++test('the GTK scripts: X11 events, a line at the start, a text read that fails with no text', () => {+ expect(GTK_WATCH_PY).toContain('Gtk.Clipboard.get(Gdk.SELECTION_CLIPBOARD).connect("owner-change", say)')+ expect(GTK_WATCH_PY).toContain('sys.stdout.write("\\n"); sys.stdout.flush()')+ expect(GTK_WATCH_PY).toContain('if Gdk.Display.get_default() is None: sys.exit(1)')+ expect(GTK_READ_PY).toContain('.wait_for_text()')+ expect(GTK_READ_PY).toContain('if t is None: sys.exit(1)')+})++test('the automatic copy line: the macOS texts as they were, the Linux way or why it is off', () => {+ const base = { isMac: true, hostOs: 'Darwin', isRemote: false, isOn: true, none: false, drawn: true, running: true, way: null }+ expect(autoCopyText(base)).toBe('on')+ expect(autoCopyText({ ...base, none: true })).toBe('off (no PerlObjCBridge in /usr/bin/perl)')+ expect(autoCopyText({ ...base, isRemote: true })).toBe('off (ssh)')+ expect(autoCopyText({ ...base, running: false })).toBe('off (the watcher does not run)')+ const wl = clipWayOf({ wayland: true, x11: false, desktop: 'sway', found: ALL })+ const linux = { ...base, isMac: false, hostOs: 'Linux', way: wl }+ expect(autoCopyText(linux)).toBe('on, with wl-paste --watch (Wayland)')+ expect(autoCopyText({ ...linux, none: true })).toBe('off (wl-paste --watch (Wayland) stopped: the compositor may not have the data-control protocol)')+ expect(autoCopyText({ ...linux, way: clipWayOf({ wayland: false, x11: true, desktop: '', found: ALL }), none: true })).toBe('off (clipnotify and xclip (X11) stopped)')+ expect(autoCopyText({ ...linux, way: { off: 'no Wayland or X11 display' } })).toBe('off (no Wayland or X11 display)')+ expect(autoCopyText({ ...linux, way: null })).toBe('off (the clipboard tools are not looked up yet)')+ expect(autoCopyText({ ...linux, drawn: false })).toBe('off (no picture yet)')+ expect(autoCopyText({ ...linux, hostOs: 'FreeBSD' })).toBe('off (not macOS or Linux)')+})++// ---- Light or dark: the desktop portal ---------------------------------------------++test("the portal's color-scheme, as gdbus and busctl print it (Read and ReadOne)", () => {+ expect(schemeOfPortal('(<<uint32 1>>,)\n')).toBe('dark')+ expect(schemeOfPortal('(<<uint32 2>>,)\n')).toBe('light')+ expect(schemeOfPortal('(<<uint32 0>>,)\n')).toBe('no-preference')+ expect(schemeOfPortal('(<uint32 1>,)\n')).toBe('dark')+ expect(schemeOfPortal('v v u 1\n')).toBe('dark')+ expect(schemeOfPortal('v u 2\n')).toBe('light')+ expect(schemeOfPortal('v v u 0\n')).toBe('no-preference')+ expect(schemeOfPortal('(<<uint32 7>>,)')).toBe(null)+ expect(schemeOfPortal('Error: GDBus.Error:org.freedesktop.portal.Error.NotFound')).toBe(null)+ expect(schemeOfPortal('')).toBe(null)+})++// ---- Fonts and the plan editor ----------------------------------------------------++test("fontconfig's family: the first of its names", () => {+ expect(familyOfFc('DejaVu Sans Mono')).toBe('DejaVu Sans Mono')+ expect(familyOfFc('Noto Sans Mono,Noto Sans Mono Regular')).toBe('Noto Sans Mono')+ expect(familyOfFc('')).toBe('')+ expect(GHOSTTY_DEFAULT_FONT).toBe('JetBrains Mono')+})++test('the plan editor on Linux: code, else a GUI editor that waits, never over ssh', () => {+ expect(guiEditorOf('kate /usr/bin/kate\n')).toEqual(['/usr/bin/kate', '--block'])+ expect(guiEditorOf('gedit /usr/bin/gedit')).toEqual(['/usr/bin/gedit', '--wait'])+ expect(guiEditorOf('gvim /usr/bin/gvim')).toEqual(['/usr/bin/gvim', '-f'])+ expect(guiEditorOf('xdg-open /usr/bin/xdg-open')).toEqual([])+ expect(guiEditorOf('')).toEqual([])+ expect(LINUX_EDITORS.map(([name]) => name)).not.toContain('xdg-open')+ const gui = ['/usr/bin/kate', '--block']+ expect(editorArgv({ code: '/usr/bin/code', isMac: false, isRemote: false, gui }, '/h/p.md')).toEqual(['/usr/bin/code', '--wait', '/h/p.md'])+ expect(editorArgv({ code: '', isMac: false, isRemote: false, gui }, '/h/p.md')).toEqual(['/usr/bin/kate', '--block', '/h/p.md'])+ expect(editorArgv({ code: '', isMac: false, isRemote: true, gui }, '/h/p.md')).toBe(null)+ expect(editorArgv({ code: '', isMac: false, isRemote: false, gui: [] }, '/h/p.md')).toBe(null)+ // macOS does not change: TextEdit, never a GUI editor of the list.+ expect(editorArgv({ code: '', isMac: true, isRemote: false, gui }, '/h/p.md')).toEqual(['open', '-W', '-t', '/h/p.md'])+})++// ---- A Linux session ---------------------------------------------------------------++const HEAD = '89 50 4e 47 0d 0a 1a 0a 00 00 00 0d 49 48 44 52 00 00 06 20 00 00 02 00'+const WRAP = 'echo $$; exec "$@"'+const inputsOf = (argv: readonly string[]) => Object.fromEntries(argv.flatMap((a, i) => (argv[i - 1] === '--input' ? [a.split(/=(.*)/s).slice(0, 2)] : [])))+const cells = (row: number, from: number, to: number, lead = ' ') =>+ lead + Array.from({ length: to - from + 1 }, (_, i) => placeholderCell(row, from + i)).join('')++// A Linux computer in kitty on Wayland (sway): uname says Linux, the tools+// are wl-paste only, the portal says `scheme`, kitty's config names no font+// (fontconfig gives one), and the watcher is `perl` with the notifier after+// `clip`. `copy` changes the clipboard: each clip child prints a line.+function linuxWorld(on: any, o: { scheme?: number; noPortal?: boolean; env?: Record<string, string>; noTypst?: boolean; jetbrains?: boolean } = {}) {+ mock.store(on)+ const clock = mock.clock(on)+ mock.env(on, o.env ?? { HOME: '/h', TERM: 'xterm-kitty', KITTY_WINDOW_ID: '1', WAYLAND_DISPLAY: 'wayland-1', XDG_CURRENT_DESKTOP: 'sway' })+ const files = new Map<string, string>()+ const ran: string[][] = []+ const watchers: { argv: string[]; say: (line: string) => void; dead: boolean; n: number }[] = []+ const w = {+ clock, files, ran, watchers, clipboard: 'old', reads: 0, copies: [] as string[], toasts: [] as string[],+ copy(text: string) {+ w.clipboard = text+ for (const c of watchers) if (!c.dead && c.argv[3] === 'clip') c.say(`clip ${c.n++}`)+ },+ }+ let pids = 7000+ const killers = new Map<string, () => void>()+ on('process.spawn', async function* ($: any, e: any) {+ const argv: string[] = e.argv+ if (argv[0] === 'perl' && argv[1] === '-e' && argv[2] === WATCH_PL) {+ const pid = String(pids++)+ const lines = [`pid ${pid}`]+ let wake = () => {}+ const me = { argv, dead: false, n: 0, say: (line: string) => (lines.push(line), wake()) }+ // The notifier's first line, at its start.+ if (argv[3] === 'clip') me.say(`clip ${me.n++}`)+ watchers.push(me)+ killers.set(pid, () => ((me.dead = true), wake()))+ for (;;) {+ while (lines.length && !me.dead) yield { stream: 'stdout', text: `${lines.shift()}\n` }+ if (me.dead) return { value: { code: null, signal: 'SIGTERM' } }+ await new Promise<void>(r => (wake = r))+ }+ }+ if (argv[0] !== 'sh' || argv[2] !== WRAP || argv[4] !== '/usr/bin/typst') return { value: { code: 2, signal: null } }+ yield { stream: 'stdout', text: `${pids++}\n` }+ const typst = argv.slice(4)+ if (typst[1] === 'compile') return { value: { code: 0, signal: null } }+ const inputs = inputsOf(typst)+ yield { stream: 'stdout', text: JSON.stringify(SMALL_MARKS.map(m => ({ ...m, p: Number(inputs.page) }))) }+ return { value: { code: 0, signal: null } }+ })+ on('process.run', async ($: any, e: any) => {+ const argv: string[] = e.argv+ const cmd = argv.join(' ')+ ran.push(argv)+ if (argv[0] === 'kill') {+ killers.get(argv[1]!)?.()+ return ok('')+ }+ if (/cc-intelligent-ui-/.test(cmd)) return ok('/c\nLinux\n/h/.cache/cc-intelligent-ui/designs\n')+ if (cmd.includes('command -v typst')) return o.noTypst ? ok('', 1) : ok('/usr/bin/typst\n')+ if (argv[0] === 'sh' && argv[2] === FIND_SH) return ok('wl-paste /usr/bin/wl-paste\n')+ if (argv[0] === '/usr/bin/typst' && argv[1] === 'eval') return ok('{}')+ if (cmd.includes('od -An')) return ok(argv.filter(a => a.endsWith('.png')).map(() => `${HEAD}\n@\n`).join(''))+ if (argv[0] === 'gdbus') return o.noPortal ? ok('', 1) : ok(`(<<uint32 ${o.scheme ?? 1}>>,)\n`)+ if (argv[0] === 'busctl') return ok('', 1)+ if (argv[0] === 'gsettings') return ok("'prefer-light'\n")+ if (argv[0] === 'fc-match' && argv[1] === 'monospace') return ok('DejaVu Sans Mono')+ if (argv[0] === 'fc-list' && argv[2] === 'JetBrains Mono') return ok('', o.jetbrains ? 0 : 1)+ if (cmd === '/usr/bin/wl-paste -n -t text') {+ w.reads+++ return ok(w.clipboard)+ }+ return ok('', 1)+ })+ on('fs.write', async ($: any, e: any) => {+ files.set(e.path, e.text)+ return { value: undefined }+ })+ on('fs.read', async ($: any, e: any, next: any) => (files.has(e.path) ? { value: files.get(e.path) } : e.path.startsWith('/c/') || e.path.startsWith('/h/') ? { deny: 'ENOENT' } : next(e)))+ on('fs.exists', async ($: any, e: any, next: any) => (o.noTypst || e.path.startsWith('/h/') ? { value: false } : next(e)))+ on('fs.list', async ($: any, e: any, next: any) => {+ if (!e.path.startsWith('/c/')) return next(e)+ const segments = (JSON.parse(files.get(`${e.path}/doc.json`) ?? '{"segments":[""]}') as { segments: string[] }).segments+ return { value: segments.map((_, i) => ({ name: `a-${i + 1}.png`, kind: 'file', size: 1, mtimeMs: 1, isLink: false })) }+ })+ on('ui.copy', async ($: any, e: any) => {+ w.copies.push(e.text)+ w.copy(e.text)+ return { value: { isCopied: true } }+ })+ on('ui.selection', async () => ({ value: undefined }))+ on('ui.toast', async ($: any, e: any) => {+ w.toasts.push(String(e.text))+ return { value: undefined }+ })+ on('ui.render', () => ({ type: 'Text', props: {}, children: ['engine drawing'] }) as any)+ return w+}++const message = (requestId: string, text: string) =>+ ({+ plugin: 'cc-intelligent-ui', surface: 'terminal', component: 'AssistantMessage', requestId,+ props: { text, isFirstOfReply: true }, viewport: { columns: 100, rows: 40 },+ }) as any++const autoLine = async ($: any) => ((await $.command.run({ command: 'iui', args: 'details' } as any)).text ?? '').split('\n').find((l: string) => l.startsWith('Auto copy:'))++test('Linux on Wayland: the watcher runs wl-paste --watch after clip, and a copy of picture cells is read with wl-paste and written as text', async ($, on) => {+ const w = linuxWorld(on)+ await $.command.run({ command: 'iui', args: '' } as any)+ expect(await autoLine($)).toBe('Auto copy: off (no picture yet)')+ const ui = await $.ui.mount(message('ans-1', SMALL_MD))+ await w.clock.settle()+ await ui.redraw({ text: SMALL_MD, isFirstOfReply: true } as any)+ await w.clock.settle()+ await w.clock.advance(300)+ await w.clock.settle()+ // The size watcher (perl from the PATH), then the one with the notifier.+ expect(w.watchers.map(c => c.argv.slice(3))).toEqual([[], ['clip', '/usr/bin/wl-paste', '--watch', 'sh', '-c', WL_WATCH_SH]])+ expect(await autoLine($)).toBe('Auto copy: on, with wl-paste --watch (Wayland)')+ // The first line (the notifier's start) is not a change: no read.+ expect(w.reads).toBe(0)+ w.copy([cells(1, 0, 97, '● '), cells(2, 0, 97), cells(3, 0, 21)].join('\n'))+ await w.clock.settle()+ expect(w.copies).toEqual(['Copy test\nThe quick brown fox jumps'])+ expect(w.toasts.some(t => t.startsWith('Intelligent UI: copied'))).toBe(true)+ // A copy with no picture cells is read and left as it is.+ w.copy('plain text')+ await w.clock.settle()+ expect(w.copies.length).toBe(1)+ // pbpaste is never run on Linux.+ expect(w.ran.some(argv => argv[0] === 'pbpaste')).toBe(false)+})++test('Linux, auto, in kitty: kitty\'s config comes first; the font is fontconfig\'s monospace', async ($, on) => {+ const w = linuxWorld(on, { scheme: 1 })+ on('config.list', async () => ({ value: [{ key: 'theme', value: 'auto' }] as any }))+ const ran = await $.command.run({ command: 'iui', args: 'details' } as any)+ // kitty's config has no background: kitty's default (dark) comes first.+ expect(ran.text).toContain('(auto, from kitty')+ expect(ran.text).toContain('terminal font DejaVu Sans Mono')+ expect(w.ran.some(argv => argv[0] === 'osascript' || argv[0] === 'defaults')).toBe(false)+})++test('Linux with no terminal config: the portal, else gsettings, gives the OS mode', async ($, on) => {+ linuxWorld(on, { scheme: 2, env: { HOME: '/h', TERM: 'xterm-256color', WAYLAND_DISPLAY: 'wayland-1', CLAUDE_CODE_FORCE_TERMINAL_IMAGES: '1' } })+ on('config.list', async () => ({ value: [{ key: 'theme', value: 'auto' }] as any }))+ const ran = await $.command.run({ command: 'iui', args: 'details' } as any)+ expect(ran.text).toContain('mode light (auto, from desktop portal)')+ expect(ran.text).toContain('terminal font DejaVu Sans Mono')+})++test('Linux with no portal: GNOME gsettings gives the OS mode', async ($, on) => {+ const w = linuxWorld(on, { noPortal: true, env: { HOME: '/h', TERM: 'xterm-256color', CLAUDE_CODE_FORCE_TERMINAL_IMAGES: '1' } })+ on('config.list', async () => ({ value: [{ key: 'theme', value: 'auto' }] as any }))+ const ran = await $.command.run({ command: 'iui', args: 'details' } as any)+ expect(ran.text).toContain('mode light (auto, from GNOME)')+ // gdbus and busctl failed once each; the next check reads gsettings only.+ const before = w.ran.filter(a => a[0] === 'gdbus' || a[0] === 'busctl').length+ expect(before).toBe(2)+ await w.clock.advance(3000)+ await w.clock.settle()+ expect(w.ran.filter(a => a[0] === 'gdbus' || a[0] === 'busctl').length).toBe(2)+ expect(w.ran.filter(a => a[0] === 'gsettings').length).toBeGreaterThan(1)+})++test("Ghostty on Linux with no font-family: its JetBrains Mono when fontconfig has it, else fontconfig's monospace", async ($, on) => {+ linuxWorld(on, { jetbrains: true, env: { HOME: '/h', TERM: 'xterm-ghostty', TERM_PROGRAM: 'ghostty' } })+ expect((await $.command.run({ command: 'iui', args: 'details' } as any)).text).toContain('terminal font JetBrains Mono')+})++test("Ghostty on Linux with no font-family and no JetBrains Mono: fontconfig's monospace", async ($, on) => {+ linuxWorld(on, { env: { HOME: '/h', TERM: 'xterm-ghostty', TERM_PROGRAM: 'ghostty' } })+ expect((await $.command.run({ command: 'iui', args: 'details' } as any)).text).toContain('terminal font DejaVu Sans Mono')+})++test('/iui setup on Linux changes no file and says why', async ($, on) => {+ const w = linuxWorld(on)+ const ran = await $.command.run({ command: 'iui', args: 'setup' } as any)+ expect(ran.text).toBe(SETUP_NOT_MAC)+ expect([...w.files.keys()].some(k => /zshrc|bashrc|fish/.test(k))).toBe(false)+})++test('/iui on Linux with no Typst names a Linux way to install it', async ($, on) => {+ linuxWorld(on, { noTypst: true })+ const ran = await $.command.run({ command: 'iui', args: '' } as any)+ expect(ran.text).toContain('Install it: cargo install --locked typst-cli')+ expect(ran.text).not.toContain('brew install typst')+})++test('the cache folder: TMPDIR, else /tmp (Linux often has no TMPDIR); the designs in XDG_CACHE_HOME, else ~/.cache', () => {+ expect(CACHE_SH).toContain('d="${TMPDIR:-/tmp}"; d="${d%/}/cc-intelligent-ui-$(id -u)"')+ expect(CACHE_SH).toContain('g="${XDG_CACHE_HOME:-$HOME/.cache}/cc-intelligent-ui/designs"')+ expect(CACHE_SH).toContain('"$(uname -s)"')+})diff --git a/tests/pure.test.ts b/tests/pure.test.tsindex d3ea5f3..993b0f4 100644--- a/tests/pure.test.ts+++ b/tests/pure.test.ts@@ -717,7 +717,7 @@ test("Ghostty's background comes from its config, its theme, or its default", ()const where = { home: '/h', resources: '/R' }expect(ghosttyThemePaths('Nord', where)).toEqual(['/h/.config/ghostty/themes/Nord', '/h/Library/Application Support/com.mitchellh.ghostty/themes/Nord', '/R/themes/Nord',- '/Applications/Ghostty.app/Contents/Resources/ghostty/themes/Nord', '/usr/share/ghostty/themes/Nord',+ '/Applications/Ghostty.app/Contents/Resources/ghostty/themes/Nord', '/usr/share/ghostty/themes/Nord', '/usr/local/share/ghostty/themes/Nord',])expect(ghosttyThemePaths('Nord', { ...where, xdgConfig: '/x' })[0]).toBe('/x/ghostty/themes/Nord')expect(ghosttyThemePaths('/t/Mine', where)).toEqual(['/t/Mine'])