Skip to content

Claude's answers, rendered: Markdown, math, charts and diagrams drawn in the Claude Code terminal. Independent project, not affiliated with Anthropic.

TypeScript claude-code-mod

Read: an image Claude reads shows as a small preview under its expanded row; IUI_FORCE in a background session, IUI_INLINE (#2)

razorback16835159866de0
diff --git a/CHANGELOG.md b/CHANGELOG.md
index edb1221..c6c26f5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,17 @@
All releases of Intelligent UI for Claude Code (`cc-intelligent-ui`). Claude Code finds a new version by the `version` in `.claude-plugin/plugin.json`. To get it, refer to [Update](docs/install.md#update).
+## Unreleased
+
+### New
+
+- **Images that Claude reads.** When Claude opens a PNG, JPEG or WebP image with the Read tool, the image draws under the expanded Read row (ctrl+o, `--verbose`, or an unfolded group) as a small preview, as a pasted image does. The folded line (`Read 2 files`) stays as it is. Refer to [Images that Claude reads](docs/usage.md#images-that-claude-reads). ([#2](https://github.com/razorback16/cc-intelligent-ui/issues/2))
+- **`IUI_INLINE`.** `IUI_INLINE=1` sends pictures as data, as over ssh. `IUI_INLINE=0` makes the terminal read the files, also over ssh. Use it where the mod cannot see ssh, such as in a background session.
+
+### Fixed
+
+- **Background sessions with `IUI_FORCE=1`.** A background session (`claude --bg`, `claude attach`) now tries to show pictures when `IUI_FORCE=1` is set, also when the daemon started in tmux. Before, it never showed pictures. ([#2](https://github.com/razorback16/cc-intelligent-ui/issues/2))
+
## 0.3.4 (2026-10-25)
### New
diff --git a/README.md b/README.md
index 9f85a86..d5c8af3 100644
--- a/README.md
+++ b/README.md
@@ -46,7 +46,7 @@ Needs Claude Code 2.1.298 or later. Works best in fullscreen mode (`/tui fullscr
- **Rendered Markdown:** headings, tables, task lists, quotes and highlighted code, in your terminal's font.
- **LaTeX math:** inline and display, typeset.
- **Diagrams, charts and plots:** Claude draws them live with Typst, in your theme's colours, offline.
-- **Images and files:** images in answers, images and Markdown files that Claude sends, and a preview of images you paste, above the prompt box.
+- **Images and files:** images in answers, images and Markdown files that Claude sends, images that Claude reads (in the expanded row), and a preview of images you paste, above the prompt box.
- **Copy answers as usual:** in fullscreen, drag over an answer to select and copy its text, as you do with normal text. Click a link or a file to open it (alt+click copies it); click a command to copy it. [How copy works](docs/usage.md#copy-text-from-a-picture).
- **Readable plans:** plan mode shows the plan rendered, with approve, edit and reject.
- **Light and dark themes:** Claude Code's colours or VS Code's, or your own.
diff --git a/docs/install.md b/docs/install.md
index af2142c..c0c1620 100644
--- a/docs/install.md
+++ b/docs/install.md
@@ -17,9 +17,10 @@
- **Rio 0.5.27+ (not tested):** set `CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1` before you start Claude Code. Runs on macOS and Linux.
- **ssh:** works when your local terminal is kitty or Ghostty (`TERM` must come through ssh), or when you set `CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1` on the remote computer. Pictures go as data, so a page over 4096 pixels on a side or over 2 MiB shows as text, and an image that large does not show.
- **tmux and screen:** no pictures. Claude Code does not send pictures through them, even with the variable set. Set `IUI_FORCE=1` to try anyway.
+- **`IUI_INLINE`:** `IUI_INLINE=1` sends pictures as data, as over ssh; `IUI_INLINE=0` makes the terminal read the files, also over ssh. With no value, the mod sends data only over ssh (`SSH_CONNECTION` or `SSH_TTY`).
- **Warp and WezTerm (not yet):** they do not draw kitty pictures with Unicode placeholders. Support comes when [warpdotdev/warp#16312](https://github.com/warpdotdev/warp/pull/16312) and [wezterm/wezterm#7924](https://github.com/wezterm/wezterm/pull/7924) are merged.
- **Not supported:** Konsole (no Unicode placeholders), Alacritty, Terminal.app, Windows Terminal, GNOME Terminal and other VTE terminals, foot, VS Code, Tabby, Hyper and JetBrains terminals (no kitty pictures).
-- **Background sessions** (agent view, forks, `claude attach`) cannot show pictures.
+- **Background sessions** (agent view, forks, `claude attach`): no pictures by default. A background session has the variables of the daemon, not of your terminal. Set `IUI_FORCE=1` in the session's environment to try. When the terminal is on another computer, also set `IUI_INLINE=1` (the daemon has no `SSH_CONNECTION`).
Where pictures cannot show, you see the normal text. `/iui details` tells you why.
diff --git a/docs/usage.md b/docs/usage.md
index 46b2c12..68928eb 100644
--- a/docs/usage.md
+++ b/docs/usage.md
@@ -20,6 +20,7 @@ Intelligent UI draws Claude's answers as rendered Markdown. Only the drawing cha
A `theme` dictionary (`theme.fg`, `theme.muted`, `theme.blue`, `theme.palette`, `theme.width`, `theme.height`, …) lets a drawing use the terminal's colours and fit its space. A short part of the system prompt tells Claude about it. A drawing keeps the layout of its first draw, and scales when the terminal size changes.
- **Files that Claude sends** (the SendUserFile tool): images, PDF pages and Markdown files. See [Files that Claude sends](#files-that-claude-sends).
+- **Images that Claude reads** (the Read tool): the image under its Read row when the row is expanded (ctrl+o, `--verbose`). See [Images that Claude reads](#images-that-claude-reads).
- **Images you paste** (`[Image #N]`): a small preview above the prompt box, and the same small images under your prompt after you send it. See [Preview of pasted images](#preview-of-pasted-images).
- **Plans** in plan mode, with the mod's own approval question. See [Plan approval](#plan-approval).
@@ -35,6 +36,10 @@ JPEG, WebP, SVG, PDF and Markdown need Typst.
**Size.** An image is never larger than its file or wider than the transcript. `/iui height` sets the most rows it can use (by default half the screen, 24 rows at most). The same limit applies to Typst drawings in answers.
+### Images that Claude reads
+
+When Claude opens an image with the Read tool, the image draws under the expanded Read row: in the ctrl+o transcript, with `--verbose`, or in a group that you unfold. The folded line (`Read 2 files`) shows no file, so it stays as it is. PNG, JPEG and WebP draw from the file on disk as a small preview, the size of a pasted image's preview (5 rows), with the file name as its alt text. GIF stays as the normal row. JPEG and WebP need Typst.
+
### PDF pages
- **Change page:** a line such as `‹ 3 ›` shows under the page. Click `‹` or `›`. `‹` is gray on page 1, and `›` on the last page. The mod does not show the number of pages.
diff --git a/hooks/lib/api.ts b/hooks/lib/api.ts
index 9b81cc1..6ffb5ef 100644
--- a/hooks/lib/api.ts
+++ b/hooks/lib/api.ts
@@ -19,7 +19,7 @@ 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' | 'DISPLAY'
| 'GHOSTTY_BIN_DIR' | 'GHOSTTY_RESOURCES_DIR' | 'HERDR_ENV' | 'HOME'
- | 'ITERM_PROFILE' | 'ITERM_SESSION_ID' | 'IUI_DEBUG' | 'IUI_FORCE' | 'KITTY_CONFIG_DIRECTORY' | 'KITTY_INSTALLATION_DIR' | 'KITTY_PID'
+ | 'ITERM_PROFILE' | 'ITERM_SESSION_ID' | 'IUI_DEBUG' | 'IUI_FORCE' | 'IUI_INLINE' | 'KITTY_CONFIG_DIRECTORY' | 'KITTY_INSTALLATION_DIR' | 'KITTY_PID'
| 'KITTY_WINDOW_ID' | 'LC_TERMINAL' | 'RIO_CONFIG_HOME' | 'SHELL' | 'SSH_CONNECTION' | 'SSH_TTY' | 'STY'
| 'TERM' | 'TERM_PROGRAM' | 'TERM_PROGRAM_VERSION' | 'TMUX' | 'TYPST_FONT_PATHS' | 'WAYLAND_DISPLAY' | 'XDG_CONFIG_HOME' | 'XDG_CURRENT_DESKTOP' | 'ZDOTDIR'
@@ -68,6 +68,7 @@ export function getenv($: EngineInterface, name: EnvName): Promise<string | unde
case 'ITERM_SESSION_ID': return $.env.get('ITERM_SESSION_ID')
case 'IUI_DEBUG': return $.env.get('IUI_DEBUG')
case 'IUI_FORCE': return $.env.get('IUI_FORCE')
+ case 'IUI_INLINE': return $.env.get('IUI_INLINE')
case 'KITTY_CONFIG_DIRECTORY': return $.env.get('KITTY_CONFIG_DIRECTORY')
case 'KITTY_INSTALLATION_DIR': return $.env.get('KITTY_INSTALLATION_DIR')
case 'KITTY_PID': return $.env.get('KITTY_PID')
diff --git a/hooks/lib/composer.tsx b/hooks/lib/composer.tsx
index 000692f..a7a77eb 100644
--- a/hooks/lib/composer.tsx
+++ b/hooks/lib/composer.tsx
@@ -23,10 +23,10 @@ import { isFlipHere } from './terminal'
import { delay, stat, write, exec, sid, uiResolve } from './api'
export type BandInput = RenderInput<'AbovePrompt', 'terminal'>
-export type RowInput = RenderInput<'UserMessage', 'terminal'>
-// One preview: the image's number, its source (the filled copy once made)
-// and its picture's cells.
-export type Preview = { n: number; source: ImageSource; columns: number; rows: number }
+export type RowInput = RenderInput<'UserMessage' | 'ToolUse', 'terminal'>
+// One preview: the image's number, its source (the filled copy once made),
+// its picture's cells and its alt (by default the number's).
+export type Preview = { n: number; source: ImageSource; columns: number; rows: number; alt?: string }
type Slot = { columns: number; rows: number }
type Size = { width: number; height: number }
@@ -118,23 +118,47 @@ export async function previewsOf(
): Promise<{ lines: Preview[][]; isWhole: boolean; isFinal: boolean }> {
const dir = await pasteDir($, ready)
if (!dir && !o.paths?.size) return { lines: [], isWhole: false, isFinal: true }
- const flip = isFlipHere(ready)
const cell = shownFor(view).cell
- const found: { n: number; plain: ImageSource | null; p: Picture }[] = []
+ const pictures: { n: number; p: Picture | null }[] = []
for (const n of numbers) {
const path = o.paths?.get(n)
const p = (dir ? await pictureOf($, pastedImagePath(dir, n)) : null) ?? (path ? await pathPicture($, ready, path, convertBox(o.columns, PREVIEW_ROWS, cell)) : null)
+ pictures.push({ n, p })
+ }
+ return layPreviews($, view, ready, pictures, o)
+}
+
+// The images Claude reads (`files`, absolute paths), as previews under its
+// row (after the gutter), each with its file's name as its alt.
+export async function filePreviews(
+ $: EngineInterface, view: RenderViewport | undefined, ready: Env, files: readonly string[], o: { columns: number; redraw: () => void },
+): Promise<{ lines: Preview[][]; isWhole: boolean; isFinal: boolean }> {
+ const box = convertBox(o.columns, PREVIEW_ROWS, shownFor(view).cell)
+ const pictures: { n: number; p: Picture | null; alt: string }[] = []
+ for (const [i, file] of files.entries()) pictures.push({ n: i + 1, p: await pathPicture($, ready, file, box), alt: file.split('/').pop() || 'image' })
+ return layPreviews($, view, ready, pictures, { ...o, maxRows: Number.POSITIVE_INFINITY, labelled: false })
+}
+
+// The previews of `pictures` (null: not found), as previewsOf says.
+async function layPreviews(
+ $: EngineInterface, view: RenderViewport | undefined, ready: Env, pictures: readonly { n: number; p: Picture | null; alt?: string }[],
+ o: { columns: number; maxRows: number; labelled: boolean; redraw: () => void },
+): Promise<{ lines: Preview[][]; isWhole: boolean; isFinal: boolean }> {
+ const flip = isFlipHere(ready)
+ const cell = shownFor(view).cell
+ const found: { n: number; plain: ImageSource | null; p: Picture; alt?: string }[] = []
+ for (const { n, p, alt } of pictures) {
const plain = p && !flip ? await sourceOf($, ready, p) : null
- if (p && (flip || plain)) found.push({ n, plain, p })
+ if (p && (flip || plain)) found.push({ n, plain, p, alt })
}
- const isWhole = found.length === numbers.length
+ const isWhole = found.length === pictures.length
const laid = o.labelled
? previewLayout(found.map(f => f.p), cell, o.columns, o.maxRows, found.map(f => labelColumns(f.n)))
: previewLayout(found.map(f => f.p), cell, o.columns - GUTTER, o.maxRows)
if (!laid) return { lines: [], isWhole, isFinal: true }
let isFinal = true
const previews = new Map<number, Preview>()
- for (const [i, { n, plain, p }] of found.entries()) {
+ for (const [i, { n, plain, p, alt }] of found.entries()) {
const box = laid.boxes[i]!
const made = filledOf($, ready, p, cellPixels(box, cell), cell, o.redraw)
if (made === undefined) isFinal = false
@@ -142,7 +166,7 @@ export async function previewsOf(
// Flip mode with no copy (no Typst, or it failed): the image stored for its rows.
const bare = flip && made === null ? await sourceOf($, ready, p, box.rows) : plain
const source = (q ? await sourceOf($, ready, q, box.rows) : null) ?? bare
- if (source) previews.set(i, { n, source, ...box })
+ if (source) previews.set(i, { n, source, ...box, ...(alt ? { alt } : {}) })
}
const lines = laid.lines.map(line => line.flatMap(i => previews.get(i) ?? [])).filter(line => line.length)
return { lines, isWhole, isFinal }
@@ -310,7 +334,7 @@ export function previewRetry($: EngineInterface, key: string, redraw: () => void
// (the first one's in the gutter), else after the gutter (as underRow).
function previewLines($: EngineInterface, e: BandInput | RowInput, lines: readonly Preview[][], labelled: boolean) {
const { Box, Text, Image } = uiResolve($, e)
- const image = (p: Preview) => <Image key={`preview-${p.n}`} source={p.source} columns={p.columns} rows={p.rows} alt={altOf(p.n)} />
+ const image = (p: Preview) => <Image key={`preview-${p.n}`} source={p.source} columns={p.columns} rows={p.rows} alt={p.alt ?? altOf(p.n)} />
return (
<Box flexDirection="column" marginLeft={labelled ? 0 : GUTTER}>
{lines.map((line, i) => (
diff --git a/hooks/lib/env.ts b/hooks/lib/env.ts
index b09af12..aad99f5 100644
--- a/hooks/lib/env.ts
+++ b/hooks/lib/env.ts
@@ -9,7 +9,7 @@ import {
import { DEFAULT_METRICS, refresh, S, settingsSet, type Env } from './state'
import { OSC11_TRIES, resolveMode, settingOf } from './mode'
import { isItermIn } from './terminals'
-import { canDrawIn, isHerdrIn, isSet, needsSetup } from './terminal'
+import { canDrawIn, inlineOf, isHerdrIn, isSet, needsSetup } from './terminal'
import { claudeTmpOf } from './images'
import { applyTheme } from './themes'
import { parseEditor } from './open'
@@ -165,7 +165,7 @@ export function setUp($: EngineInterface): Promise<Env> {
S.env = {
typst,
canDraw,
- inline: ssh && canDraw,
+ inline: inlineOf(ssh, await getenv($, 'IUI_INLINE')) && canDraw,
herdr: S.isHerdr,
cache,
cwd: await cwd($).catch(() => '/'),
diff --git a/hooks/lib/images.ts b/hooks/lib/images.ts
index dfa7d24..9c71fbc 100644
--- a/hooks/lib/images.ts
+++ b/hooks/lib/images.ts
@@ -85,6 +85,16 @@ export function sentFiles(output: unknown): SentFile[] {
return found
}
+// The image a Read call opened: its file, the kind by its name (the
+// result's bytes can be a smaller JPEG of it); none for a GIF or no image.
+export function readFiles(input: unknown, output: unknown): SentFile[] {
+ const type = output && typeof output === 'object' ? (output as { type?: unknown }).type : undefined
+ const path = input && typeof input === 'object' ? (input as { file_path?: unknown }).file_path : undefined
+ if (type !== 'image' || typeof path !== 'string' || !path || /\.gif$/i.test(path)) return []
+ const kind = imageKindOf({ path })
+ return kind ? [{ path, kind }] : []
+}
+
// The paths of a SendUserFile result that draw as a picture (PNG, JPEG,
// WebP, SVG, and a page of a PDF).
export const sentImages = (output: unknown) => sentFiles(output).filter(f => f.kind !== 'markdown').map(f => f.path)
diff --git a/hooks/lib/terminal.ts b/hooks/lib/terminal.ts
index e767b22..4b9e49f 100644
--- a/hooks/lib/terminal.ts
+++ b/hooks/lib/terminal.ts
@@ -282,19 +282,21 @@ export function needsSetup(o: { iterm: boolean; herdr: boolean; draws: boolean;
// Whether the engine draws pictures here; elsewhere an Image shows only its
// alt, so the text is better. Claude Code turns kitty graphics on by itself
// only for kitty and Ghostty; any other terminal draws only when
-// CLAUDE_CODE_FORCE_TERMINAL_IMAGES is set. A background session never
-// draws. In tmux or screen the engine draws none even when forced (it does
-// not wrap them for passthrough), so only IUI_FORCE tries. Over ssh
+// CLAUDE_CODE_FORCE_TERMINAL_IMAGES is set. In a background session (its
+// variables are the daemon's), tmux or screen (the engine does not wrap them
+// for passthrough) only IUI_FORCE tries. Over ssh
// TERM_PROGRAM and KITTY_WINDOW_ID do not come through, so TERM tells; the
// pictures then go as bytes (Env.inline), as the terminal can't read our files.
export function canDrawIn(env: { program: string; term: string; kitty: boolean; tmux: boolean; ssh: boolean; background: boolean; engineForced: boolean; modForced: boolean }): boolean {
- if (env.background) return false
- if (env.tmux) return env.modForced
+ if (env.background || env.tmux) return env.modForced
if (env.engineForced || env.modForced) return true
if (env.ssh) return /ghostty|kitty/i.test(env.term)
return /ghostty/i.test(env.program + env.term) || /kitty/i.test(env.term) || env.kitty
}
+// Whether pictures go as bytes: IUI_INLINE when set (1 or 0, as isSet), else over ssh.
+export const inlineOf = (ssh: boolean, inline: string | undefined) => (inline?.trim() ? isSet(inline) : ssh)
+
// The most an Image's `{ png }` source holds: 2 MiB decoded, 1 to 4096
// pixels a side (the engine refuses the tree past that).
export const INLINE_MAX_BYTES = 2 * 1024 * 1024
diff --git a/hooks/register.tsx b/hooks/register.tsx
index 145fa71..6113a19 100644
--- a/hooks/register.tsx
+++ b/hooks/register.tsx
@@ -50,9 +50,9 @@ import { clipboardNow, clipboardRead, clipWatchArgs, clipWayReady, hintText } fr
import { setUp } from './lib/env'
import { frameFor, noteView, stopWatch, watchFrame, watchState } from './lib/frame'
import { herdrText, isFlipHere, roomColumns } from './lib/terminal'
-import { onScreenOf, pastedNumbers, sentFiles } from './lib/images'
+import { onScreenOf, pastedNumbers, readFiles, sentFiles } from './lib/images'
import { drawPageField, pasteDir, pdfPagesOf, rowsAfter, sentOf, underRow, type Under } from './lib/pictures'
-import { drawPreviews, forgetPaths, keepPaths, pathPaste, pathsOf, previewRetry, previewsOf, previewsUnder, sameNumbers, type Preview } from './lib/composer'
+import { drawPreviews, filePreviews, forgetPaths, keepPaths, pathPaste, pathsOf, previewRetry, previewsOf, previewsUnder, sameNumbers, type Preview } from './lib/composer'
import { checkUpdates, loadUpdates, updateLine, updateNotice, type UpdateState } from './lib/updates'
import { nowMs, write, surf, save, copy, uiSelection, toast, sid, exec, delay } from './lib/api'
import { detachedArgv, editorNow, OPEN_TIMEOUT_MS, openArgv, openedText, useName, type Use } from './lib/open'
@@ -216,6 +216,7 @@ const answers = new Map<string, Memo<AnswerMemo>>()
const plans = new Map<string, Memo<{ drawing: Drawing; links: ShownLink[] }>>()
const unders = new Map<string, Memo<Under[]>>()
const pasted = new Map<string, Memo<Preview[][]>>()
+const readPreviews = new Map<string, Memo<Preview[][]>>()
const drafts = new Map<string, Memo<Preview[][]>>()
// The kept value when the inputs and the stamp are the same. A new onScreen
@@ -1158,10 +1159,10 @@ export const register: Register = on => {
const terminal = S.cacheProblem
? `Intelligent UI draws no pictures: ${S.cacheProblem} (it never uses a shared folder instead)`
: ready.canDraw
- ? `this terminal draws pictures${ready.inline ? ' (over ssh, sent as bytes)' : ''}`
+ ? `this terminal draws pictures${ready.inline ? (S.isRemote ? ' (over ssh, sent as bytes)' : ' (sent as bytes: IUI_INLINE)') : ''}`
: S.isHerdr && S.setupNeeded
? 'Claude Code draws no pictures in herdr until CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1 is set when it starts (run /iui setup), so answers stay text'
- : 'Claude Code draws no pictures here (it does in kitty and Ghostty, in iTerm2 3.6+, Rio 0.5.27+ and herdr with CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1, over ssh when TERM names kitty or Ghostty or with that variable; never in tmux, screen or a background session; not in WezTerm, Warp, Konsole or others), so answers stay text'
+ : 'Claude Code draws no pictures here (it does in kitty and Ghostty, in iTerm2 3.6+, Rio 0.5.27+ and herdr with CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1, over ssh when TERM names kitty or Ghostty or with that variable; in tmux, screen or a background session only with IUI_FORCE=1; not in WezTerm, Warp, Konsole or others), so answers stay text'
// In herdr: its version, the terminal it runs in and where that came from (and flip mode).
const herdr = S.isHerdr ? `terminal ${herdrText(S.herdrVersion, S.herdrHost, S.herdrClient ? (S.herdrBy === 'front' ? 'front' : 'client') : 'server', isFlipHere(ready))}: ` : ''
await clipWayReady()
@@ -1357,6 +1358,40 @@ export const register: Register = on => {
}
})
+ // The image Claude opens with Read, as a small preview (as a pasted
+ // image's) under its expanded row (ctrl+o, --verbose, an unfolded group);
+ // the folded line shows no file, so none there.
+ on('ui.render', { component: 'ToolUse', props: { tool: 'Read' } }, async ($, e, next) => {
+ if (e.surface !== 'terminal' || e.props.isErrored) return next(e)
+ const files = readFiles(e.props.input, e.props.output).map(f => f.path)
+ if (!files.length) return next(e)
+ let lines: Preview[][] = []
+ try {
+ const ready = await pictureEnv($, e)
+ const mine = memberOf(filled, e)
+ if (ready) await read($, mine)
+ const k = { text: files.join('\n'), extra: '', stamp: ready ? stampOf(ready, e.viewport) : '', onScreen: undefined }
+ const kept = ready ? memoOf(readPreviews, e.requestId, k, () => false) : undefined
+ if (kept) lines = kept
+ else if (ready) {
+ const redraw = () => void update($, mine, n => n + 1).catch(() => undefined)
+ const made = await filePreviews($, e.viewport, ready.env, files, { columns: roomColumns(e.viewport), redraw })
+ lines = made.lines
+ if (lines.length && made.isFinal) memoSet(readPreviews, e.requestId, k, lines)
+ else readPreviews.delete(e.requestId)
+ }
+ } catch {
+ lines = []
+ }
+ const row = await next(e)
+ if (!lines.length) return row
+ try {
+ return previewsUnder($, e, row, lines)
+ } catch {
+ return row
+ }
+ })
+
// The page field of a PDF under a SendUserFile row (pictures.tsx askPage):
// the pane PAGE_PANE, named as a literal so the validator reads it.
on('ui.render', { component: 'Pane', requestId: 'iui-page' }, async ($, e, next) => {
diff --git a/tests/draw.test.ts b/tests/draw.test.ts
index 50a8721..b60f34e 100644
--- a/tests/draw.test.ts
+++ b/tests/draw.test.ts
@@ -2,7 +2,7 @@ import { expect, mock, test } from 'claude-code/testing'
import {
alignFirstLine, scaledBulletRow, base64Bytes, canDrawIn, COMMIT_MIN_MS, DEFAULT_CELL, fileHref, fitsInline, herdrBudget, HERDR_MAX_PAGE_BYTES, INLINE_MAX_BYTES,
- INLINE_MAX_SIDE, inlineBudget, renderKey, RESIZE_QUIET_MS, resolveLinks, SEGMENT_ROWS, segmentBudget, sizing, WATCH_PL,
+ INLINE_MAX_SIDE, inlineBudget, inlineOf, renderKey, RESIZE_QUIET_MS, resolveLinks, SEGMENT_ROWS, segmentBudget, sizing, WATCH_PL,
} from '../hooks/register'
import { TABLE_GRID } from './table-fixture'
// This file's own copy of the drawing code, called with a fake `$`.
@@ -19,9 +19,20 @@ test('tmux and screen draw no pictures, even with the engine forced; only IUI_FO
expect(canDrawIn({ ...base, tmux: true, modForced: true })).toBe(true)
})
-test('a background session never draws pictures, not even with IUI_FORCE', () => {
+test('a background session draws pictures only with IUI_FORCE, also with tmux in its TERM', () => {
expect(canDrawIn({ ...base, program: 'ghostty', background: true })).toBe(false)
- expect(canDrawIn({ ...base, term: 'xterm-kitty', background: true, engineForced: true, modForced: true })).toBe(false)
+ expect(canDrawIn({ ...base, term: 'xterm-kitty', background: true, engineForced: true })).toBe(false)
+ expect(canDrawIn({ ...base, term: 'xterm-kitty', background: true, modForced: true })).toBe(true)
+ expect(canDrawIn({ ...base, term: 'tmux-256color', tmux: true, background: true, modForced: true })).toBe(true)
+})
+
+test('pictures go as bytes over ssh, or as IUI_INLINE says when it is set', () => {
+ expect(inlineOf(false, undefined)).toBe(false)
+ expect(inlineOf(true, undefined)).toBe(true)
+ expect(inlineOf(true, '')).toBe(true)
+ expect(inlineOf(false, '1')).toBe(true)
+ expect(inlineOf(true, '0')).toBe(false)
+ expect(inlineOf(true, 'off')).toBe(false)
})
test('over ssh, TERM tells: kitty or Ghostty draws, an unknown terminal only when forced', () => {
@@ -287,6 +298,16 @@ const props = (text: string) => ({ text, isFirstOfReply: true }) as any
const images = (tree: any): any[] =>
tree && typeof tree === 'object' ? [...(tree.type === 'Image' ? [tree] : []), ...(tree.children ?? []).flatMap(images)] : []
+test('in a background session with IUI_FORCE and IUI_INLINE, a page goes as PNG bytes', async ($, on) => {
+ const { clock } = world(on, { CLAUDE_CODE_SESSION_KIND: 'bg', TERM: 'tmux-256color', IUI_FORCE: '1', IUI_INLINE: '1' })
+ const ran = await $.command.run({ command: 'iui', args: 'details' } as any)
+ expect(ran.text).toContain('sent as bytes: IUI_INLINE')
+ const ui = await $.ui.mount(message('bg-1', 'Some **bold** text.'))
+ await clock.settle()
+ await ui.redraw(props('Some **bold** text.'))
+ expect(images(await ui.drawn())[0].props.source).toEqual({ png: PNG })
+})
+
test('over ssh in kitty, a page goes as PNG bytes, read once', async ($, on) => {
const { clock, reads } = world(on, { SSH_CONNECTION: '10.0.0.2 50000 10.0.0.1 22', TERM: 'xterm-kitty' })
const ran = await $.command.run({ command: 'iui', args: 'details' } as any)
diff --git a/tests/images.test.ts b/tests/images.test.ts
index 8d326c4..74f57e8 100644
--- a/tests/images.test.ts
+++ b/tests/images.test.ts
@@ -8,7 +8,7 @@ import { FILL_SH } from '../hooks/lib/typst'
import {
claudeTmpOf, convertBox, convertCall, convertedPath, DEFAULT_CELL, factsAfter, folderOf, imageKindOf, isMarkdownPath, isNoPageError, isPdfPath, lastKnownPage,
NO_FACTS, pageControls, pageCountOf, pageOf, parsePage, pasteDirOf, pastedImagePath, pastedNumbers, COMMIT_MIN_MS, DEFAULT_HEIGHT, RESIZE_QUIET_MS, PICTURE_MAX_ROWS, PICTURE_ROOM_ROWS, pictureCells,
- pictureRowsFor, projectSlug, renderKey, rowsAfter, sentFiles, sentImages, shortError, type Under, altOf, cellPixels, fillCall, filledPath, labelColumns, labelOf, linesOf, previewLayout, PREVIEW_RETRY_MS, sameNumbers,
+ pictureRowsFor, projectSlug, readFiles, renderKey, rowsAfter, sentFiles, sentImages, shortError, type Under, altOf, cellPixels, fillCall, filledPath, labelColumns, labelOf, linesOf, previewLayout, PREVIEW_RETRY_MS, sameNumbers,
clipImagePaths, PATH_RECHECK_MS, READ_PL,
} from '../hooks/register'
@@ -1335,6 +1335,65 @@ test('an errored SendUserFile call leaves the row as it is', async ($, on) => {
expect(await ui.drawn()).toMatchObject(ENGINE)
})
+// A Read call's row: its input and output (an image's bytes, as Claude Code keeps them).
+const READ_IMAGE = { type: 'image', file: { base64: PNG, type: 'image/png', originalSize: 1000 } }
+const readRow = (file_path: string, output: unknown = READ_IMAGE, isErrored = false, id = 'tr-1') =>
+ ({
+ plugin: 'cc-intelligent-ui', surface: 'terminal', component: 'ToolUse', requestId: id,
+ props: { tool_use_id: id, tool: 'Read', input: { file_path }, output, isRunning: false, isErrored, isInterrupted: false, isExpanded: true }, viewport: { columns: 100, rows: 40 },
+ }) as any
+
+test('a Read of an image gives its file, by its name; not a GIF, text or another result', () => {
+ const image = { type: 'image', file: { base64: '', type: 'image/jpeg', originalSize: 1 } }
+ expect(readFiles({ file_path: '/t/a.png' }, image)).toEqual([{ path: '/t/a.png', kind: 'png' }])
+ expect(readFiles({ file_path: '/t/a.JPG' }, image)).toEqual([{ path: '/t/a.JPG', kind: 'jpeg' }])
+ expect(readFiles({ file_path: '/t/a.webp' }, image)).toEqual([{ path: '/t/a.webp', kind: 'webp' }])
+ expect(readFiles({ file_path: '/t/a.gif' }, image)).toEqual([])
+ expect(readFiles({ file_path: '/t/a.md' }, { type: 'text', file: { filePath: '/t/a.md', content: '' } })).toEqual([])
+ expect(readFiles({ file_path: '/t/a.pdf' }, { type: 'pdf', file: { filePath: '/t/a.pdf', base64: '', originalSize: 1 } })).toEqual([])
+ expect(readFiles({}, image)).toEqual([])
+ expect(readFiles({ file_path: '/t/a.png' }, undefined)).toEqual([])
+})
+
+test('an image Claude reads draws under its expanded Read row as a small preview, as a pasted image', async ($, on) => {
+ world(on, { files: { '/t/shot.png': HEAD } })
+ await ready($)
+ const ui = await $.ui.mount(readRow('/t/shot.png'))
+ const tree: any = await ui.drawn()
+ expect(tree.children[0]).toMatchObject(ENGINE)
+ expect(tree.children[1]).toMatchObject(PREVIEWS)
+ const [image] = images(tree)
+ // 640 x 320 px in PREVIEW_ROWS (5) rows of 32 px: 20 x 5 cells.
+ expect(image.props).toMatchObject({ columns: 20, rows: 5, alt: 'shot.png' })
+ expect(image.props.source).toMatchObject({ file: '/t/shot.png', format: 'png' })
+})
+
+test('with Typst, a read PNG draws as the copy that fills its cells; a JPEG as the PNG Typst makes of it first', async ($, on) => {
+ const { converts, fills } = world(on, { typst: true, files: { '/t/shot.png': HEAD, '/t/photo.jpg': HEAD } })
+ await ready($)
+ const ui = await $.ui.mount(readRow('/t/shot.png'))
+ await ui.drawn()
+ await ui.redraw(readRow('/t/shot.png').props)
+ const [image] = images(await ui.drawn())
+ expect(fills.length).toBe(1)
+ expect(image.props.source.file).toMatch(/^\/c\/[0-9a-f]{16}\/image\.png$/)
+ expect(image.props).toMatchObject({ columns: 20, rows: 5, alt: 'shot.png' })
+ const jpeg = await $.ui.mount(readRow('/t/photo.jpg', READ_IMAGE, false, 'tr-2'))
+ const [photo] = images(await jpeg.drawn())
+ expect(converts.map(argv => argv.find(a => a.startsWith('f='))?.slice(2))).toEqual(['/t/photo.jpg'])
+ expect(photo.props).toMatchObject({ rows: 5, alt: 'photo.jpg' })
+})
+
+test('a Read row of text, still running, or errored stays as it is', async ($, on) => {
+ world(on, { files: { '/t/shot.png': HEAD } })
+ await ready($)
+ expect(await (await $.ui.mount(readRow('/t/a.md', { type: 'text', file: { filePath: '/t/a.md', content: 'x', numLines: 1, startLine: 1, totalLines: 1 } }))).drawn()).toMatchObject(ENGINE)
+ const running = readRow('/t/shot.png', READ_IMAGE, false, 'tr-2')
+ delete running.props.output
+ expect(await (await $.ui.mount(running)).drawn()).toMatchObject(ENGINE)
+ expect(await (await $.ui.mount(readRow('/t/shot.png', 'File does not exist.', true, 'tr-3'))).drawn()).toMatchObject(ENGINE)
+})
+
// The previews as the row draws them: after the gutter, a line of pictures
// PREVIEW_GAP apart. The band's have no gutter: each is after its number.
const PREVIEWS = { type: 'Box', props: { flexDirection: 'column', marginLeft: 2 } }