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
Copy: on the main screen, /iui grab copies; no session writes over another's copy
razorback16c4d666dfce12
diff --git a/README.md b/README.mdindex 02eb356..42270b4 100644--- a/README.md+++ b/README.md@@ -24,6 +24,8 @@ Then, in Claude Code:It works at once, with no restart.+Intelligent UI works best in fullscreen mode (recommended). To use it, run `/tui fullscreen` in Claude Code.+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 or Linux (X11 or Wayland). The pictures show only in some terminals:@@ -48,7 +50,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. On Linux, this needs a clipboard tool (refer to [Install](docs/install.md#linux)).+- **Copy text from pictures.** In fullscreen mode, 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.diff --git a/docs/how-it-works.md b/docs/how-it-works.mdindex 3f48d3e..341ec7c 100644--- a/docs/how-it-works.md+++ b/docs/how-it-works.md@@ -12,7 +12,7 @@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 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). In fullscreen mode, it reads the clipboard only when the selection of its session has picture cells, because a copy from this session is always a copy of that selection. 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 automatic copy works in fullscreen mode only: the mod reads the clipboard only when the selection of its session has picture cells, and it writes only when the clipboard is that selection. On the main screen, Claude Code gives no selection, so the mod cannot know which session a copy is from. There it does not change the clipboard. When the clipboard has picture cells that fit a page drawn in this session, it shows one toast that names `/iui grab`. `/iui grab` then reads the picture cells on the clipboard and writes their text. 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.## The lean font setdiff --git a/docs/install.md b/docs/install.mdindex d556849..91b3815 100644--- a/docs/install.md+++ b/docs/install.md@@ -57,12 +57,12 @@ The mod works on Linux with X11 and with Wayland. It uses these tools. Most Linu- **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:+- **The clipboard** (for the automatic copy in fullscreen mode and for `/iui grab` on the main screen, 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:`.+ If none of these work, the automatic copy is off. `/iui grab` (with a selection, in fullscreen mode), 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`.diff --git a/docs/limitations.md b/docs/limitations.mdindex 1e8653b..c5c367b 100644--- a/docs/limitations.md+++ b/docs/limitations.md@@ -11,7 +11,9 @@- The mod does not copy math, the text in an image, or the text in a Typst drawing.- The cells do not identify the answer. The mod uses the answer of the selected row if it knows it, else the newest answer whose pages fit the selection. A selection in one page of a long answer fits each page that is tall enough, and the mod uses the first one. Thus the text can come from a different page or an older answer of the same width. `/iui dump` shows the page that the mod used.- The mod knows only the last 64 answers, plans or files that it drew in this session.- - With two Claude Code sessions on one computer, a session on the main screen (not fullscreen mode) can change a copy from the other session, with the text of its own picture. A session in fullscreen mode changes only a copy of its own selection.+ - On the main screen (not fullscreen mode), there is no automatic copy. Claude Code gives the mod no selection on the main screen, so the mod cannot know which session a copy is from. Two sessions can have the same picture cells. Thus the mod does not change the clipboard, and a toast tells you to use `/iui grab`. Run `/iui grab` in the session that has the picture.+ - On the main screen, `/iui grab` does not know the row of the selection. Thus it can give the wrong text for a picture from before `/clear`, from a session that ended, or older than the last 64 pictures, and for a page after the first page of a long answer.+ - In fullscreen mode, a different fullscreen session can have an old selection of exactly the same cells. Then both sessions read the copy, and the first write stays.- In fullscreen mode, the mod does not change a copy of a selection that the terminal makes itself (for example, a drag with Option in iTerm2), because Claude Code does not see that selection. Select without the modifier key.- To stop the clipboard write on select, set `copyOnSelect` to `false` in `/config`. Then the mod does not copy a selection either, because it acts only when the clipboard changes. It changes only a clipboard that has picture cells (for example, after a copy with a key).- **Links in a picture:** a click on the picture does not open a link, because the mod cannot put a link on a picture. Use the link rows under the picture (refer to [Links, file paths and commands](usage.md#links-file-paths-and-commands)). A click on a command row copies the command only where Claude Code gets mouse clicks (fullscreen mode). A `file://` link opens in the app that the terminal chooses. A file row shows only when the file exists when the mod draws the answer.diff --git a/docs/usage.md b/docs/usage.mdindex af7be1e..c8dcc33 100644--- a/docs/usage.md+++ b/docs/usage.md@@ -58,7 +58,7 @@ Intelligent UI draws Claude's answers as rendered Markdown pictures. Only the dr| `/iui updates off` | Stops the check for a new version and its toast (kept for later sessions) || `/iui theme` | Lists the themes, shows which one is in use, and shows the folder for your own themes || `/iui theme <name>` | Changes to that theme (kept for later sessions) |-| `/iui grab` | Copies the text under your last mouse selection of pictures. Refer to [Copy text from a picture](#copy-text-from-a-picture). |+| `/iui grab` | Copies the text under your last mouse selection of pictures. On the main screen, it copies the text of the picture cells on the clipboard. Refer to [Copy text from a picture](#copy-text-from-a-picture). || `/iui dump` | Shows the last clipboard text with picture cells and how the mod read it (for a bug report). It also writes this to `copy-debug.json` in the cache folder. || `/iui probe` | Asks the terminal for its background colour with OSC 11 and shows the raw answers. Refer to [How `auto` is resolved](how-it-works.md#how-auto-is-resolved). |@@ -81,11 +81,13 @@ 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. 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, the mod changes the clipboard only when the clipboard holds the selection of its own session. Thus a copy from a different Claude Code session 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)). The automatic copy works in fullscreen mode only. We recommend fullscreen mode: run `/tui fullscreen` (`/tui default` goes back to the main screen). 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. The mod changes the clipboard only when the clipboard holds the selection of its own session. Thus a copy from a different Claude Code session stays as it is. The mod does not change a clipboard that has no picture cells.++On the main screen (not fullscreen mode), Claude Code gives the mod no selection. Thus the mod cannot know which session a copy is from, and it does not change the clipboard. When the clipboard has picture cells of a picture in this session, a toast tells you to use `/iui grab`. Select and copy, then run `/iui grab` in the same session. `/iui grab` puts the text of these picture cells on the clipboard. When the mod draws its first picture on the main screen, a toast recommends fullscreen mode (one time in each session).The mod finds the position of each word on a page when you copy from that page for the first time. This takes approximately 0.05 s for plain text (only ASCII characters, no math, no Typst block and no image), 0.15–0.5 s for other text, 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.-If the clipboard did not change, use `/iui grab`. It reads the last mouse selection of Claude Code (fullscreen mode only) and copies its text. If the copied text is not correct, `/iui dump` shows the cells that the mod found and the page that it used. It also writes all of this to `copy-debug.json` in the cache folder.+If the clipboard did not change, use `/iui grab`. In fullscreen mode, it reads the last mouse selection of Claude Code and copies its text. With no selection (the main screen), it reads the picture cells on the clipboard and copies their text. If the clipboard has the text already, it tells you. If the copied text is not correct, `/iui dump` shows the cells that the mod found and the page that it used. It also writes all of this to `copy-debug.json` in the cache folder.For the limits, refer to [Limitations](limitations.md).diff --git a/hooks/lib/clipboard.ts b/hooks/lib/clipboard.tsindex 3869c40..17bd5cf 100644--- a/hooks/lib/clipboard.ts+++ b/hooks/lib/clipboard.ts@@ -153,20 +153,25 @@ export function clipWatchArgs(isMac: boolean): string[] | null {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 {+// The automatic copy now, for /iui details and dump. `none`: the+// notifier stopped (the watcher printed `clip none`). `isFullscreen`: null+// before a render hook says; only fullscreen copies by itself.+export function autoCopyText(o: {+ isMac: boolean; hostOs: string; isRemote: boolean; isOn: boolean; isFullscreen: boolean | null; 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.isFullscreen === false) return 'off on the main screen (use /iui grab)'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.isFullscreen === null) return 'off (fullscreen or main screen is not known 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/command.ts b/hooks/lib/command.tsindex 438de90..396879d 100644--- a/hooks/lib/command.ts+++ b/hooks/lib/command.ts@@ -75,7 +75,7 @@ const SUBCOMMANDS = [{ name: 'theme', description: 'list the themes, or switch to one' },{ name: 'setup', description: 'iTerm2: add the shell line that turns pictures on' },{ name: 'details', description: 'the mode source, the terminal font, Typst and the terminal' },- { name: 'grab', description: 'copy the text of the pictures you last selected' },+ { name: 'grab', description: 'copy the text of the pictures you last selected (or copied, on the main screen)' },{ name: 'dump', description: 'show what the clipboard held and how it was read' },] as constconst SIZES = [80, 90, 100, 110, 120, 125, 150, 175, 200]@@ -164,7 +164,7 @@ export function commandSuggestions(export async function registerCommand($: EngineInterface) {await commandRegister($, {name: 'iui',- description: "Draw Claude's answers as rendered Markdown pictures: on, off, size <80-200> (text size in % of the terminal's), width [40-400|full] (the most columns a picture takes), height [6-200|half|full] (the most rows an image or a Typst drawing takes), grid [on|off] (each line of text on whole terminal rows), updates [on|off] (look for a new version once a day), theme [name] (list or switch themes), grab (copy the selected pictures' text), dump (copy diagnostics)",+ description: "Draw Claude's answers as rendered Markdown pictures: on, off, size <80-200> (text size in % of the terminal's), width [40-400|full] (the most columns a picture takes), height [6-200|half|full] (the most rows an image or a Typst drawing takes), grid [on|off] (each line of text on whole terminal rows), updates [on|off] (look for a new version once a day), theme [name] (list or switch themes), grab (copy the text of the selected pictures, or of the picture cells on the clipboard), dump (copy diagnostics)",argumentHint: '[on|off|size <percent>|width [columns|full]|height [rows|half|full]|grid [on|off]|updates [on|off]|theme [name]|grab|dump]',}).catch(() => undefined)}diff --git a/hooks/lib/state.ts b/hooks/lib/state.tsindex 781abe3..c161427 100644--- a/hooks/lib/state.ts+++ b/hooks/lib/state.ts@@ -130,6 +130,8 @@ export const S = {// The terminal's layout (a viewport's isFullscreen; fixed per session),// null before a render hook says.isFullscreen: null as boolean | null,+ // The fullscreen advice was shown (once, on the main screen).+ fullscreenTold: false,// The key folders in the cache at setUp: a key found there is read back// at once (a reopened session), with no queue and no blank.onDisk: new Set<string>(),diff --git a/hooks/register.tsx b/hooks/register.tsxindex d2791dd..c83d47a 100644--- a/hooks/register.tsx+++ b/hooks/register.tsx@@ -117,9 +117,18 @@ async function pictureEnv($: EngineInterface, e: { viewport?: RenderViewport }):void setUp($).catch(() => undefined)return null}+ if (S.env.canDraw && S.isFullscreen === false) tellFullscreen($)return S.env.canDraw ? { env: S.env, done: now } : null}+// Once a session, where pictures draw on the main screen: fullscreen gives+// the automatic copy (the main screen has no selection to own a copy).+function tellFullscreen($: EngineInterface) {+ if (S.fullscreenTold) return+ S.fullscreenTold = true+ uiToast($, 'Intelligent UI works best in fullscreen mode: run /tui fullscreen', { timeoutMs: 12000 })+}+// The env to draw Markdown pictures with (an answer, a plan): as// pictureEnv, and Typst found.async function answerEnv($: EngineInterface, e: { viewport?: RenderViewport }): Promise<{ env: Env; done: number } | null> {@@ -210,8 +219,9 @@ async function planEnv($: EngineInterface): Promise<Env | null> {// 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+// wl-paste, xclip, xsel or GTK) and, in fullscreen, when it holds placeholders,+// written again with the words under them; the main screen has /iui grab+// (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.@@ -295,14 +305,26 @@ function clipChanged($: EngineInterface, count: number | null, first: boolean) {if (!first) void readClipboard($).catch(() => undefined)}-// 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, the-// clipboard is rewritten only when it is that selection: another session's-// copy is that session's to read. In fullscreen a copy of this session's-// pictures is always of its selection, so with no selection that has-// placeholders the clipboard is not even read. A change while a read runs-// (a probe can take a second) reads once more after it.+// Not fullscreen (or not known yet): no selection says whose copy it is, and+// two sessions can have the same cells, so the clipboard is not changed.+// Cells that fit a page drawn here get one toast that names /iui grab.+async function hintGrab($: EngineInterface) {+ const text = await clipboardNow($)+ if (text === null || text === clip.seen) return+ clip.seen = text+ if (text === clip.wrote || !hasPlaceholders(text)) return+ if (!pickPages(decodeSelection(text), [...drawnAnswers.values()]).some(Boolean)) return+ clip.raw = text+ clip.rawRow = undefined+ uiToast($, 'Intelligent UI: picture cells copied; /iui grab puts their text on the clipboard')+}++// The clipboard changed: one read (clipboardNow). Only in fullscreen, and+// only when this session's selection has placeholders and is the+// clipboard's text, it is read and written back as text: a copy with no+// selection here is another session's. A clipboard with no placeholders,+// and our own write, are never touched. A change while a read runs (a+// probe can take a second) reads once more after it.async function readClipboard($: EngineInterface) {if (clip.busy) {clip.again = true@@ -312,14 +334,18 @@ async function readClipboard($: EngineInterface) {try {do {clip.again = false+ if (S.isFullscreen !== true) {+ await hintGrab($)+ continue+ }const selected = await uiSelection($).catch(() => undefined)- if (S.isFullscreen && !(selected && hasPlaceholders(selected.text))) continue+ if (!(selected && hasPlaceholders(selected.text))) continueconst text = await clipboardNow($)if (text === null || text === clip.seen) continueclip.seen = textif (text === clip.wrote || !hasPlaceholders(text)) continue- if (selected && !sameCopy(selected.text, text)) continue- await copyRead($, text, selected?.requestId)+ if (!sameCopy(selected.text, text)) continue+ await copyRead($, text, selected.requestId)} while (clip.again)} finally {clip.busy = false@@ -349,7 +375,7 @@ function stopClipboard($: EngineInterface) {function autoCopyOf(isOn: boolean): string {const now = watchState()return autoCopyText({- isMac: !!S.env?.isMac, hostOs: S.hostOs, isRemote: S.isRemote, isOn, none: clip.none, drawn: drawnAnswers.size > 0,+ isMac: !!S.env?.isMac, hostOs: S.hostOs, isRemote: S.isRemote, isOn, isFullscreen: S.isFullscreen, none: clip.none, drawn: drawnAnswers.size > 0,running: !!now?.clip && !now.ended, way: S.clipWay,})}@@ -361,20 +387,30 @@ async function updateState($: EngineInterface): Promise<UpdateState> {return { on: S.updates, off: S.updatesOff, own: S.ownVersion, checked: S.updateChecked, now }}-// /iui grab: the last mouse selection, read and copied.+// /iui grab: the last mouse selection, read and copied. With no selection+// (the main screen), the picture cells on the clipboard: the command says+// that the copy is this session's.async function grab($: EngineInterface): Promise<string> {const selected = await uiSelection($).catch(() => undefined)- if (!selected) return 'Intelligent UI: no mouse selection (it needs fullscreen mode; select over a picture first).'- if (!hasPlaceholders(selected.text)) return `Intelligent UI: the selection has no picture cells; it is ${selected.text.length} chars of text already.`- clip.raw = selected.text- clip.rawRow = selected.requestId- const read = await readCopy($, selected.text, selected.requestId)+ let raw = selected?.text+ if (raw === undefined) {+ const now = await clipboardNow($)+ if (now === null) return 'Intelligent UI: no mouse selection, and the clipboard can not be read (see /iui details).'+ if (clip.wrote && now === clip.wrote) return 'Intelligent UI: the clipboard has the text already.'+ if (!hasPlaceholders(now)) return 'Intelligent UI: no mouse selection and no picture cells on the clipboard; select over a picture and copy first.'+ raw = now+ }+ if (!hasPlaceholders(raw)) return `Intelligent UI: the selection has no picture cells; it is ${raw.length} chars of text already.`+ const row = selected?.requestId+ clip.raw = raw+ clip.rawRow = row+ const read = await readCopy($, raw, row)if (!read.resolved) return `Intelligent UI: found ${read.runs} picture run(s) but could not read them (see /iui dump).`clip.wrote = read.textclip.seen = read.textconst copied = await uiCopy($, { text: read.text })return copied.isCopied- ? `Intelligent UI: copied ${read.text.length} chars (${read.resolved} of ${read.runs} picture runs read${selected.requestId ? `, row ${selected.requestId}` : ''}).`+ ? `Intelligent UI: copied ${read.text.length} chars (${read.resolved} of ${read.runs} picture runs read${row ? `, row ${row}` : ''}).`: `Intelligent UI: the copy failed: ${copied.reason}.`}diff --git a/tests/copy.test.ts b/tests/copy.test.tsindex 8abb65a..2828b52 100644--- a/tests/copy.test.ts+++ b/tests/copy.test.ts@@ -371,7 +371,7 @@ test('/iui grab and dump are commands with typeahead rows; dump with nothing seeexpect(parseCommand('dump')).toEqual({ kind: 'dump' })expect(parseCommand('grab now')).toEqual({ kind: 'bad' })const rows = commandSuggestions('/iui gra', 'gra', 5, { themes: [], active: 'claude-code', size: 100 })- expect(rows).toEqual([{ text: 'grab', description: 'copy the text of the pictures you last selected' }])+ expect(rows).toEqual([{ text: 'grab', description: 'copy the text of the pictures you last selected (or copied, on the main screen)' }])expect(commandSuggestions('/iui du', 'du', 5, { themes: [], active: 'claude-code', size: 100 }).map(r => r.text)).toEqual(['dump'])const ran = await $.command.run({ command: 'iui', args: 'dump' } as any)expect(ran.text).toContain('Intelligent UI: no clipboard text with picture cells seen yet')@@ -392,11 +392,13 @@ const inputsOf = (argv: readonly string[]) => Object.fromEntries(argv.flatMap((a// its start and at each change of the clipboard; `clip none` with// `noBridge`), pbpaste reading `clipboard`, and the copies, toasts and// selection the test sees. `copy` is a copy in another app (or a mouse-// copy): the clipboard and its change count change.-function world(on: any, o: { failFirst?: boolean; noBridge?: boolean } = {}) {+// copy): the clipboard and its change count change; while `selects`, a copy+// of picture cells is this session's selection too (a mouse copy in+// fullscreen).+function world(on: any, o: { failFirst?: boolean; noBridge?: boolean; env?: Record<string, string> } = {}) {mock.store(on)const clock = mock.clock(on)- mock.env(on, { HOME: '/h', CLAUDE_CODE_FORCE_TERMINAL_IMAGES: '1' })+ mock.env(on, o.env ?? { HOME: '/h', CLAUDE_CODE_FORCE_TERMINAL_IMAGES: '1' })const files = new Map<string, string>()const compiles: Record<string, string>[] = []const queries: Record<string, string>[] = []@@ -407,12 +409,14 @@ function world(on: any, o: { failFirst?: boolean; noBridge?: boolean } = {}) {clock, files, compiles, queries, kills, watchers,clipboard: 'nothing yet', count: 40, pastes: 0, copies: [] as string[], toasts: [] as string[],selection: undefined as { text: string; requestId?: string } | undefined,+ selects: true,gate: null as Promise<void> | null, release: () => {},hold() {w.gate = new Promise<void>(r => (w.release = r))},copy(text: string) {w.clipboard = text+ if (w.selects && hasPlaceholders(text)) w.selection = { text }w.count++for (const c of watchers) if (!c.dead && c.argv[3] === 'clip' && !o.noBridge) c.say(`clip ${w.count}`)},@@ -498,18 +502,18 @@ function world(on: any, o: { failFirst?: boolean; noBridge?: boolean } = {}) {return w}-const message = (requestId: string, text: string) =>+const message = (requestId: string, text: string, isFullscreen: boolean | null = true) =>({plugin: 'cc-intelligent-ui', surface: 'terminal', component: 'AssistantMessage', requestId,- props: { text, isFirstOfReply: true }, viewport: { columns: 100, rows: 40 },+ props: { text, isFirstOfReply: true }, viewport: { columns: 100, rows: 40, ...(isFullscreen === null ? {} : { isFullscreen }) },}) as anyconst props = (text: string) => ({ text, isFirstOfReply: true }) as anyconst names = (files: Map<string, string>) => [...new Set([...files.keys()].filter(k => k.startsWith('/c/')).map(k => k.replace(/^.*\//, '')))].sort()// Draws `text` (SMALL_MD) as answer `id` (98 columns: the fixture's),// compiled; the watcher has its clipboard part (its first count noted).-async function drawAnswer($: any, w: ReturnType<typeof world>, id = 'ans-1', text = SMALL_MD) {- const ui = await $.ui.mount(message(id, text))+async function drawAnswer($: any, w: ReturnType<typeof world>, id = 'ans-1', text = SMALL_MD, isFullscreen: boolean | null = true) {+ const ui = await $.ui.mount(message(id, text, isFullscreen))await w.clock.settle()await ui.redraw(props(text))await w.clock.settle()@@ -661,10 +665,10 @@ test('a clipboard change runs pbpaste once and copies; no change, no read; our o// Its first count is only noted; no change, no read.await w.clock.advance(900)expect(w.pastes).toBe(0)- // A copy with no placeholders: one read, never written.+ // A copy with no placeholders (and no selection of picture cells): no read, never written.w.copy('copied in another app')await w.clock.settle()- expect(w.pastes).toBe(1)+ expect(w.pastes).toBe(0)expect(w.copies).toEqual([])w.copy(COPY)await w.clock.settle()@@ -672,9 +676,9 @@ test('a clipboard change runs pbpaste once and copies; no change, no read; our oexpect(w.toasts).toContain('Intelligent UI: copied 35 chars of text')// One read before the write; our own write changes the count: read// once, not copied again.- expect(w.pastes).toBe(4)+ expect(w.pastes).toBe(3)await w.clock.advance(900)- expect(w.pastes).toBe(4)+ expect(w.pastes).toBe(3)expect(w.copies.length).toBe(1)const dumped = await $.command.run({ command: 'iui', args: 'dump' } as any)expect(dumped.text).toContain('U+10EEEE[1,0]')@@ -688,7 +692,7 @@ test('a clipboard change runs pbpaste once and copies; no change, no read; our oexpect(w.kills).toEqual([w.watchers[0]!.pid, w.watchers[1]!.pid])w.copy(COPY)await w.clock.settle()- expect(w.pastes).toBe(4)+ expect(w.pastes).toBe(3)})test('/iui details says whether the automatic copy is on', async ($, on) => {@@ -756,9 +760,10 @@ test('a clipboard with picture cells that is not this session\'s selection is noconst w = world(on)await $.command.run({ command: 'iui', args: '' } as any)await drawAnswer($, w)- // This session has a selection of its own (no picture cells), and the- // clipboard has another session's picture cells.- w.selection = { text: 'my own text', requestId: 'u1' }+ w.selects = false+ // This session has a selection of its own picture cells, and the+ // clipboard has other picture cells (another session's).+ w.selection = { text: cells(2, 0, 97), requestId: 'ans-1' }w.copy([cells(1, 0, 97), cells(3, 0, 21)].join('\n'))await w.clock.settle()expect(w.pastes).toBe(1)@@ -773,12 +778,8 @@ test('a clipboard with picture cells that is not this session\'s selection is notest('in fullscreen the clipboard is read only with a selection of picture cells; with none it is another session\'s copy', async ($, on) => {const w = world(on)await $.command.run({ command: 'iui', args: '' } as any)- const ui = await $.ui.mount({ ...message('ans-1', SMALL_MD), viewport: { columns: 100, rows: 40, isFullscreen: true } })- await w.clock.settle()- await ui.redraw(props(SMALL_MD))- await w.clock.settle()- await w.clock.advance(300)- await w.clock.settle()+ await drawAnswer($, w)+ w.selects = false// No selection here: another fullscreen session's copy, not even read.w.selection = undefinedw.copy(COPY)@@ -878,6 +879,7 @@ test('a newer clipboard that the watcher has not said yet is not written over; iw.copy([cells(2, 0, 97), cells(3, 0, 21)].join('\n'))await w.clock.settle()w.clipboard = COPY+ w.selection = { text: COPY }w.release()await w.clock.settle()expect(w.copies).toEqual([COPIED])@@ -943,3 +945,109 @@ test('a clip child that ends on its own is started again; its old clipboard is nawait w.clock.settle()expect(w.copies).toEqual([COPIED])})++// ---- The main screen: no selection, so no automatic copy ---------------------++const GRAB_TOAST = 'Intelligent UI: picture cells copied; /iui grab puts their text on the clipboard'+const FULLSCREEN_TOAST = 'Intelligent UI works best in fullscreen mode: run /tui fullscreen'++test('main screen: picture cells on the clipboard are never rewritten (their session is not known); one toast names /iui grab', async ($, on) => {+ const w = world(on)+ w.selects = false+ await $.command.run({ command: 'iui', args: '' } as any)+ await drawAnswer($, w, 'ans-1', SMALL_MD, false)+ // Another session's cells: no write, no probe, one toast.+ w.copy(COPY)+ await w.clock.settle()+ await w.clock.advance(1000)+ expect(w.pastes).toBe(1)+ expect(w.copies).toEqual([])+ expect(w.queries).toEqual([])+ expect(w.toasts.filter(t => t.includes('/iui grab'))).toEqual([GRAB_TOAST])+ // dump shows them (its read probes the page).+ const dumped = await $.command.run({ command: 'iui', args: 'dump' } as any)+ expect(dumped.text).toContain('auto copy off on the main screen (use /iui grab)')+ expect(dumped.text).toContain('-> answer ans-1 page 0')+ // The same cells again: no second toast.+ w.copy(COPY)+ await w.clock.settle()+ expect(w.toasts.filter(t => t.includes('/iui grab')).length).toBe(1)+ // Cells that fit no page drawn here (column 150): no toast.+ w.copy([cells(1, 0, 150), cells(2, 0, 150)].join('\n'))+ await w.clock.settle()+ expect(w.toasts.filter(t => t.includes('/iui grab')).length).toBe(1)+ expect(w.copies).toEqual([])+ expect(w.queries.length).toBe(1)+})++test('main screen: /iui grab with no selection reads the clipboard and writes its text; a second grab says it is there', async ($, on) => {+ const w = world(on)+ w.selects = false+ await $.command.run({ command: 'iui', args: '' } as any)+ await drawAnswer($, w, 'ans-1', SMALL_MD, false)+ w.copy(COPY)+ await w.clock.settle()+ const grabbed = await $.command.run({ command: 'iui', args: 'grab' } as any)+ expect(grabbed.text).toBe('Intelligent UI: copied 35 chars (1 of 1 picture runs read).')+ expect(w.copies).toEqual([COPIED])+ // Our own write is not read back as new: no toast, no copy.+ await w.clock.settle()+ expect(w.copies).toEqual([COPIED])+ expect(w.toasts.filter(t => t.includes('/iui grab')).length).toBe(1)+ const again = await $.command.run({ command: 'iui', args: 'grab' } as any)+ expect(again.text).toBe('Intelligent UI: the clipboard has the text already.')+ expect(w.copies).toEqual([COPIED])+ w.copy('plain text')+ await w.clock.settle()+ const none = await $.command.run({ command: 'iui', args: 'grab' } as any)+ expect(none.text).toBe('Intelligent UI: no mouse selection and no picture cells on the clipboard; select over a picture and copy first.')+ expect(w.copies).toEqual([COPIED])+})++test('fullscreen or main screen not known yet: the clipboard is never written', async ($, on) => {+ const w = world(on)+ w.selects = false+ await $.command.run({ command: 'iui', args: '' } as any)+ await drawAnswer($, w, 'ans-1', SMALL_MD, null)+ // Even with a selection that is the copy.+ w.selection = { text: COPY, requestId: 'ans-1' }+ w.copy(COPY)+ await w.clock.settle()+ await w.clock.advance(1000)+ expect(w.copies).toEqual([])+ expect(w.queries).toEqual([])+ const details = await $.command.run({ command: 'iui', args: 'details' } as any)+ expect(details.text).toContain('\nAuto copy: off (fullscreen or main screen is not known yet)')+ // No advice either: the layout is not known.+ expect(w.toasts).not.toContain(FULLSCREEN_TOAST)+})++test('the fullscreen advice: once on the main screen, never in fullscreen', async ($, on) => {+ const w = world(on)+ await $.command.run({ command: 'iui', args: '' } as any)+ await drawAnswer($, w, 'ans-1', SMALL_MD, false)+ await drawAnswer($, w, 'ans-2', `${SMALL_MD}\n\nEnd.`, false)+ expect(w.toasts.filter(t => t === FULLSCREEN_TOAST).length).toBe(1)+})++test('the fullscreen advice is not shown in fullscreen', async ($, on) => {+ const w = world(on)+ await $.command.run({ command: 'iui', args: '' } as any)+ await drawAnswer($, w)+ expect(w.toasts).not.toContain(FULLSCREEN_TOAST)+})++test('the fullscreen advice is not shown where no picture draws (tmux)', async ($, on) => {+ const w = world(on, { env: { HOME: '/h', CLAUDE_CODE_FORCE_TERMINAL_IMAGES: '1', TMUX: '/tmp/tmux-501/default,1,0' } })+ await $.command.run({ command: 'iui', args: '' } as any)+ await drawAnswer($, w, 'ans-1', SMALL_MD, false)+ expect(w.compiles).toEqual([])+ expect(w.toasts).not.toContain(FULLSCREEN_TOAST)+})++test('the fullscreen advice is not shown with Intelligent UI off', async ($, on) => {+ const w = world(on)+ await $.command.run({ command: 'iui', args: 'off' } as any)+ await drawAnswer($, w, 'ans-1', SMALL_MD, false)+ expect(w.toasts).not.toContain(FULLSCREEN_TOAST)+})diff --git a/tests/linux.test.ts b/tests/linux.test.tsindex f4fa8e9..3fe9f80 100644--- a/tests/linux.test.ts+++ b/tests/linux.test.ts@@ -74,8 +74,13 @@ test('the GTK scripts: X11 events, a line at the start, a text read that fails w})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 }+ const base = { isMac: true, hostOs: 'Darwin', isRemote: false, isOn: true, isFullscreen: true as boolean | null, none: false, drawn: true, running: true, way: null }expect(autoCopyText(base)).toBe('on')+ // Only fullscreen copies by itself: the main screen has /iui grab.+ expect(autoCopyText({ ...base, isFullscreen: false })).toBe('off on the main screen (use /iui grab)')+ expect(autoCopyText({ ...base, isFullscreen: false, isOn: false })).toBe('off (Intelligent UI is off)')+ expect(autoCopyText({ ...base, isFullscreen: null })).toBe('off (fullscreen or main screen is not known yet)')+ expect(autoCopyText({ ...base, isFullscreen: null, drawn: false })).toBe('off (no picture yet)')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)')@@ -87,6 +92,7 @@ test('the automatic copy line: the macOS texts as they were, the Linux way or whexpect(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, isFullscreen: false })).toBe('off on the main screen (use /iui grab)')expect(autoCopyText({ ...linux, hostOs: 'FreeBSD' })).toBe('off (not macOS or Linux)')})@@ -151,8 +157,11 @@ function linuxWorld(on: any, o: { scheme?: number; noPortal?: boolean; env?: Recconst 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[],+ selection: undefined as { text: string } | undefined,copy(text: string) {w.clipboard = text+ // A mouse copy of picture cells in fullscreen is this session's selection.+ if (text.includes('\u{10EEEE}')) w.selection = { text }for (const c of watchers) if (!c.dead && c.argv[3] === 'clip') c.say(`clip ${c.n++}`)},}@@ -223,7 +232,7 @@ function linuxWorld(on: any, o: { scheme?: number; noPortal?: boolean; env?: Recw.copy(e.text)return { value: { isCopied: true } }})- on('ui.selection', async () => ({ value: undefined }))+ on('ui.selection', async () => ({ value: w.selection }))on('ui.toast', async ($: any, e: any) => {w.toasts.push(String(e.text))return { value: undefined }@@ -232,10 +241,10 @@ function linuxWorld(on: any, o: { scheme?: number; noPortal?: boolean; env?: Recreturn w}-const message = (requestId: string, text: string) =>+const message = (requestId: string, text: string, isFullscreen = true) =>({plugin: 'cc-intelligent-ui', surface: 'terminal', component: 'AssistantMessage', requestId,- props: { text, isFirstOfReply: true }, viewport: { columns: 100, rows: 40 },+ props: { text, isFirstOfReply: true }, viewport: { columns: 100, rows: 40, isFullscreen },}) as anyconst autoLine = async ($: any) => ((await $.command.run({ command: 'iui', args: 'details' } as any)).text ?? '').split('\n').find((l: string) => l.startsWith('Auto copy:'))@@ -267,6 +276,26 @@ test('Linux on Wayland: the watcher runs wl-paste --watch after clip, and a copyexpect(w.ran.some(argv => argv[0] === 'pbpaste')).toBe(false)})+test('Linux on Wayland, main screen: a copy of picture cells is not changed; /iui grab reads it with wl-paste and writes its text', async ($, on) => {+ const w = linuxWorld(on)+ await $.command.run({ command: 'iui', args: '' } as any)+ const ui = await $.ui.mount(message('ans-1', SMALL_MD, false))+ 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()+ expect(await autoLine($)).toBe('Auto copy: off on the main screen (use /iui grab)')+ w.copy([cells(1, 0, 97, '● '), cells(2, 0, 97), cells(3, 0, 21)].join('\n'))+ w.selection = undefined+ await w.clock.settle()+ expect(w.copies).toEqual([])+ expect(w.toasts).toContain('Intelligent UI: picture cells copied; /iui grab puts their text on the clipboard')+ const grabbed = await $.command.run({ command: 'iui', args: 'grab' } as any)+ expect(grabbed.text).toBe('Intelligent UI: copied 35 chars (1 of 1 picture runs read).')+ expect(w.copies).toEqual(['Copy test\nThe quick brown fox jumps'])+})+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 }))