Shows pasted images as framed thumbnails under the prompt; click to expand, open in a pane, or /image

Personal customizations for Claude Code: function-hook plugins ("mods") and the status line.
Get them with git clone https://github.com/ohade/claude-mods.git; each section says how to load its mod.
Use scripts/land.sh <commit-ish> as the only route for putting a change on main. It resolves one commit, tests every top-level mod with a tests/ directory in a temporary detached worktree, and requires successful exit codes and nonzero passing test counts. It then fast-forwards main, updates the detached live worktree, atomically writes a local deployment receipt, and pushes the tested SHA to origin/main last. A concurrent local main change can never substitute an untested commit in the push. No rebase, reset, rollback, force push or automatic retry.
The default layout is ~/git/claude-mods, ~/git/worktrees/claude-mods/live and ~/.claude/state/claude-mods-live.json. Keep the mod-loading symlinks pointed at the live worktree; the script does not install or change them. CLAUDE_MODS_HOME replaces the home prefix for an alternate layout or isolated tests; unset means the current user's home.
The gate also runs each mod's Python tests/helpers/test_*.py suite, Bun tests/helpers/check_*.ts checks, and any declared npm typecheck script. It runs the landing script's shell and Python self-tests once from the tested tree. Python suites need a nonzero test count and an OK footer. Packages need a committed lockfile: npm ci --ignore-scripts --include=dev --no-audit --no-fund installs their development dependencies only in the temporary worktree. Registry access or a populated local cache is required; an offline dependency failure refuses landing before publication. Have Python 3, Bun, Node/npm and ~/.Trash available; keep the real HOME, since OS helpers use it to find the installed checkout. CLAUDE_MODS_HOME changes only the deployment layout.
TypeScript mods also need the engine-written SDK input. Test/validate do not generate it. The input is a mod-layout root containing <mod>/.claude-plugin/types/. By default the gate reads the promoted root for the pinned version, <layout root>/.local/share/claude-mods/sdk/<version>, where the layout root is CLAUDE_MODS_HOME or your home directory and <version> is version in scripts/sdk-types.json. A non-empty CLAUDE_MODS_SDK_ROOT is the only input instead, with no fallback. The live checkout is never read unless you name it there. The engine version must match the manifest, every SDK file must match its reviewed digest, and the API declaration header must name that version. Only then are the checked bytes copied into the temporary test tree. Missing, stale or changed inputs refuse landing.
On an engine update, load the reviewed mod once in the matching Claude Code version, keep the engine-written folder outside the landing tree, and review the API changes and new manifest hashes together. Then promote that capture. Promotion checks every file against the manifest, holds the land lock, and never replaces an existing root. Do not edit the generated declarations or replace them with stubs.
python3 scripts/land-state.py sdk-promote /absolute/path/to/engine-written-mod-layout scripts/sdk-types.json "$HOME"
CLAUDE_MODS_SDK_ROOT=/absolute/path/to/engine-written-mod-layout scripts/land.sh <reviewed-commit>
scripts/land.sh <reviewed-commit>
scripts/land.sh --status
Both worktrees must be clean, the canonical checkout on main, and live detached in the same repository. A directory lock serializes landings. Only a lock older than 30 minutes whose same-host owner PID is provably dead can be reclaimed. An alive, reused or unknown PID stays locked; inspect the printed lock and owner before manually clearing it.
Test/preflight failures leave main, live and the receipt untouched. Publication cannot be atomic across Git worktrees and a remote: a checkout failure can leave main advanced, and a receipt failure can leave both checkouts advanced. Errors print the exact phase and all three SHAs. Rerun the same commit after resolving the cause: it is tested again, already-completed merge and checkout steps are skipped, and the receipt and push are retried. A push failure retains the local deployment and its receipt; the remote may be behind (or have accepted a push before the connection failed). Repeating a non-forced push is safe. Existing successful receipts keep their original previous_commit when that same deployment is retried.
Each mod has a private log under ~/.claude/state/claude-mods-land-logs.*. Tests time out after 10 minutes per native suite or helper command; push after 2 minutes. Interrupted children are stopped before the temporary worktree is removed. Receipts record commit, previous_commit, UTC deployed_at, per-mod native pass/fail counts and log_dir. Additional checks have separate logs in that directory. For TypeScript mods, sdk records the engine version and SHA-256 of the reviewed SDK manifest. An unfamiliar test footer fails closed. Keep failure logs for diagnosis; they are not committed. No arguments/invalid usage exit 2, help/status exit 0 on success, runtime failures exit 1, and Ctrl-C exits 130.
Track checks main, live, receipt agreement and ancestry after startup. A verified main-ahead state shows one status line with the landing command. Missing/invalid state, unrelated histories and Git errors stay silent. It makes no model call and does not await Git during session start. This is a startup snapshot; it does not poll or claim that running sessions loaded the new code.
Run bash scripts/tests/land.test.sh for local Git fixtures with fake Claude, and claude plugin test track for the drift integration fixture and the whole Track suite. Real landing and hot-reload acceptance are separate checks. land.sh is an explicit landing command, not a watcher: running a test command alone does not deploy anything.
Shows each image you paste into a prompt as a small framed thumbnail under your message.
open in pane under the frame opens the image in a pane. The pane docks beside the transcript in the fullscreen layout when the terminal is at least 110 columns wide; otherwise it opens above the prompt./image [n] opens image #n, or the latest one, in the same pane./recall … [Image #1]) show once, above the first row of Claude's reply (a tool call or text), and stay. Claude Code draws the command's own row with no render hook, so they cannot sit under it.Requirements: macOS (the mod uses sips and base64), Claude Code 2.1.289 or later with function-hook plugins, and a terminal that draws images with the kitty graphics protocol (Ghostty, kitty). Elsewhere the thumbnail shows its [Image #n] label instead.
Limits: thumbnails appear after you submit the prompt, not while you type. Images in a resumed session get no thumbnail. The decoded originals live in a private folder under $TMPDIR and are deleted when the session ends.
Load it in every session with one of:
ln -s ../../git/claude-mods/image-thumbs ~/.claude/skills/image-thumbs # skills folder
claude --plugin-dir ~/git/claude-mods/image-thumbs # one session
or list the folder in CLAUDE_CODE_PLUGIN_DIRS in the env block of ~/.claude/settings.json.
Check it with claude plugin validate image-thumbs, and type-check it with tsc -p image-thumbs once Claude Code has loaded it (loading writes the API types into .claude-plugin/types/).
A pane beside the transcript, titled Session Tracker, that keeps substantive questions, their answers, and meaningful work. Claude decides what to register from any sender, including later content in a running turn. Doorbells and informational notifications alone need no row. Track has no transport-specific workflow.
track_question and closes it with a completed answer block or mark_answered (answered or deferred); a standing rule in the system prompt asks it to. A question with a verified user source links to that source. Otherwise its tracking call is the visible source. For a normal answer, Claude writes its formatted Markdown once between standalone <!-- A15:start --> and <!-- A15:end --> lines, replacing 15 with the stable numeric id returned by track_question. Track captures the completed main-model response, hides the markers and shows the answer once. Its dim acknowledgement sits outside the answer. Each [ A ] highlights only its own block, leaving other answers and status footers unlit. Incomplete, empty, nested, duplicate or mismatched markers never complete a question; code examples, block quotes, peer hand-backs and subagent responses cannot supply an answer. Unknown and withdrawn ids remain unchanged. For tool/file-only answers, Claude supplies the completed answer_text, or explicitly identifies the latest verified native response with answer_request_id. A bare answered status is refused without changing the ledger; latest progress text cannot supply an answer. The update draws one dim ✓ Q<n>. answered line. If the explicit text has no verified native source, a separate answer row displays the saved words at that call. This can add answer tokens; the call's displayed answer may be the answer's first visible delivery. An answered question turns green. The instruction explicitly includes short follow-up questions before answering; a row still requires Claude to register it.[ Q ] and [ A ] columns scroll to the verified source and answer. The row you land on lights up and fades out over about two seconds: your prompt or the actual answer text alone. The acknowledgement is a separate row. [ A ] stays faded until captured answer text exists; an acknowledgement or an older answer with no saved text does not make it ready. Question and step labels use Q1. and S1.. The digits 1–9 press the jumps while the pane has focus (ctrl+x tab). Groups containing an uncleared question's tracking source or displayed restore stay unfolded; unrelated groups retain their native collapsed state. This exposes the ToolUse child that owns the target and changes how those groups appear in the transcript. Composer rows always have an owned wrapper. Transcript jumps use requestId; { key } resolves only plugin panes and AbovePrompt, so it cannot reveal a transcript answer Box. Call-sourced answers use their stable ToolUse call ID. Assistant answers use the exact host render instance observed on this load. The bounded presentation cache is lost on reload; an unseen assistant or restore host refuses visibly, without falling back to an acknowledgement or a guessed key. Shading still selects only the answer text. Native jumps after reload remain an acceptance gate, including oldest and middle rows away from the viewport.↑2 ↓5). Empty sections say only "None yet." Below 40 body columns, counts use 12/39, questions place their Q/A controls below the text, and step clocks use a separate line. Short controls and hints fit a 17-column body. The banner keeps the state on one line and omits background counts when space is tight. Claude Code owns the draggable transcript/dock divider. Its 2.1.293 plugin API exposes no hover mouse-cursor control for that divider; Track cannot set a horizontal resize cursor there. For plugin authors: native JSX Fragment is a column Box. Horizontal row children must stay flat; wrapping them in a fragment stacks their labels and clips the measured region.waiting only when the user must act; peer waits use paused or pending with an optional note. mark_step({ delegated: true }) identifies work owned by agents, including agents launched through other tools. It shows the brown hourglass and agents banner. Use delegated: false when the main session resumes that step. This is explicit ownership, not a peer-liveness probe. Completed steps clear it. Concurrent main work stays grey on its own row. Explicit ownership leaves agent counts unknown; only native-only activity supplies a count. User waiting does not hide concurrent work: unsaved, agents, main work, and waiting on you are separate rows, top to bottom, and only the amber glyph pulses. A short pane collapses to the highest-priority row and a count. Paused, pending and user-waiting rows retain ownership metadata but do not count as active delegated work or show a running hourglass. An open question dialog alone does not imply that the main session is working. Actual native background activity still shows and pulses.TaskCreate, TaskUpdate, TodoWrite and explicit track_steps calls. Successful plan approval adds one reminder to reuse open steps and register missing work. It leaves the entire register unchanged. A Task named like a plan step links to it. The step in progress shows who is on it: a spinner breathing in grey while the main session works, an amber hourglass while it waits on agents, a still blue ◆ while it waits on you. A duration runs only for an in-progress step with a known start and no end. Pending, paused and waiting rows hide their clocks and reserve no clock space, even if an earlier start is retained. Completed rows show a fixed duration only when both times are known. These are wall-clock durations from the first start; resuming does not subtract parked intervals. Below a minute they show <1m; below an hour they show whole minutes such as 4m or 11m, without seconds or padding. At an hour or above they retain 1h 05m. An interrupted main turn pauses only its own in-progress, non-delegated steps with an interrupted note. It preserves other turns, cleared rows and delegated work. Turn ownership survives reload in the same session; restoration into another session drops it while retaining the status and note. A late completion cannot stop a newer main turn's working banner.◑ 4 of 8 · 50% per section, counted over visible rows. Clear completed hides finished rows in its own section and removes them from that section's count. Questions has a: clear completed for answered questions; it keeps open and deferred questions and every step. Steps' c: clear completed, in both the header and bottom bar, keeps every question. Narrow panes shorten the labels to a: done and c: done. Each explicit action saves the ledger; rendering does not save it.q and s empty the Questions or the Steps section; cleared open questions are withdrawn, so the model is told not to answer them. The Steps controls (s: clear all, c: clear completed) appear twice, in the Steps header and in the bottom bar, and neither moves when the steps scroll./retro, a plan in chat, a multi-step task), it registers the steps with track_steps and ticks them with mark_step. Work that joins a running plan, such as review comments from Plannotator, is inserted with track_steps({ steps, after }) after the step it follows. While a managed plugin bypasses the system-prompt rule, each typed prompt, skill command and plugin prompt carries the instruction beside it; built-in commands do not. After reload, only the exact current composed instruction suppresses this fallback. A legacy boolean delivery flag is insufficient. Requests found in read content count as work even when they need one command. Claude reuses an open step for that same work. This is a generic instruction, not transport parsing.restore_tracker({ from_session }) copies the previous session's steps back, in order, with their ids and statuses, and its questions not cleared, with new ids after this session's own. Task ids start again in each session, so a restored Task step's id gains restored: and keeps no link to the old Task. When the model marks a question answered, the mod keeps the answer's text (up to 1,000 characters), and the restore call's row in the transcript shows each restored question with its answer, its deferral note, or "(answer text was not saved)" for one answered before answers were kept. [ Q ] and [ A ] reveal the observed restore row and shade their own question or answer inside it. A requestId reveals the whole row; a later question or answer may remain below the viewport in a large snapshot. Exact placement within that row is unresolved. The call refuses to overwrite unrelated steps unless replace: true is passed. Repeated restoration reuses stable source identities and keeps local progress. A model call supplies its displayed restore row; a programmatic call first appends and validates a plugin-owned user note. This note is model-visible and can repeat saved answer tokens, but does not submit a turn. It labels the saved words as passive tracking data, not a new request or authority. A refused or altered note leaves the ledger unchanged. Only the exact acknowledged body, stamped Track sender and matching native UUID family can acquire its UserMessage targets. Separate question and answer keys use an observed host instance when available, with no ledger or store writes during rendering. Repeat calls reuse the native message UUID. A repeat repairs an older system-notice target once, preserves local progress, and omits user-cleared questions. The supported note marker survives resume. The old InfoNotice fixture remains for legacy compatibility; it is not a native system-transcript route. Native note visibility and jumps still need acceptance. After plugin reload, the user also observed failures for older native question and answer targets; only the newest pair jumped. Restored data and passing render fixtures do not prove native jump behavior. Active target records stay while their questions are uncleared; only inactive snapshot history is capped at three. Store capacity failures remain visible.✕ removes a question; your next prompt tells the model not to answer it./rewind drops the questions asked in the rewound turns. Each finished turn saves the register, and native session startup loads it for /resume. Rewind observations are coalesced and fenced to their session; compaction and capped transcript reads do not imply that older calls were rewound. A refused rewind save holds the prompt until the save can succeed. Marker answers remain answered while their stable block id and full completed words remain in the main transcript; removing that block reopens its question. The transcript API has no response UUID, so rewind checks use the full answer fingerprint rather than the jump target. Answer jumps use event order within the question's actual tracking turn. Text before the tracking call cannot become its answer, even when wall-clock timestamps are equal. A later turn may answer an older question. For the tool/file-only fallback, a mark before a response must provide completed answer_text. A later response can reanchor it only when the full completed words match exactly and only one eligible question matches. Unidentified future text never supplies missing answer words. An explicit answer_request_id must match the latest host-observed response; unknown sources are refused. If both text and a native source id are provided, their full words must match. A bounded SHA-256 fingerprint compares full answers before the saved-text limit is applied; different endings cannot match just because their saved prefixes are equal. Event order is reserved before fingerprint calculation. During that calculation, a concurrent source-id call with long text can be refused; it leaves the ledger unchanged. Explicit text alone can still save its words at the tracking call. This concurrent publication window is not live-proven. Saved text is bounded to 1,000 Unicode code points. Legacy progress saved as an answer is not silently rewritten. An already captured answer stays unchanged. Step updates name the affected step. An acknowledged mark_step change also returns a Saved row: JSON record with the exact saved id, subject, status and optional note. A failed save reports Unsaved and returns no saved-row claim. Step blocker notes stay complete through save, interruption and restore; display limits never shorten their stored values.It opens by itself by the built-in diff panel's rule, less the git condition: in the fullscreen layout, at least 144 columns wide, and never after you closed it by hand (ctrl+x x). A reload of the mod leaves an open pane open. /track shows or hides it at any width, and like /btw it acts at once while a turn runs and adds nothing to the session; /track status prints the open questions. To keep the diff panel out of the slot, type /diff once.
/track classifier reports the optional question classifier's setting. /track classifier on and /track classifier off change it. Changes share the ledger write queue, session lease and store lock. If ownership, locking or the verified write fails, the command reports that the setting was not saved; later attempts can retry. Reading the setting does not acquire a writer lock.
Requirements: Claude Code with function-hook plugins, macOS/POSIX file locks, and Python 3. The first compatibility target is the generated 2.1.292 API. Engine and fresh-process checks use 2.1.293. A 2.1.292 runtime run and a seated managed-policy Stop run are not available on this Mac.
Load it from the clone folder (cd claude-mods), wherever it sits, with one of:
mkdir -p ~/.claude/skills && ln -s "$PWD/track" ~/.claude/skills/track # every session
claude --plugin-dir "$PWD/track" # one session
or list the clone's track folder in CLAUDE_CODE_PLUGIN_DIRS in the env block of ~/.claude/settings.json.
Check it with claude plugin validate track and test it with claude plugin test track. Once Claude Code has loaded it
hooks/register.tsx 719 lines1import type { EngineInterface, Register } from 'claude-code'
2
3import type { Pasted, Shown, Thumb } from '../types'
4import { freshNumbers, imageNumbers } from './numbers.ts'
5
6const BY_IMAGE = { plugin: 'image-thumbs', key: 'byImage' } as const
7const SHOWN = { plugin: 'image-thumbs', key: 'shown' } as const
8const PASTED = { plugin: 'image-thumbs', key: 'pasted' } as const
9const EXPANDED = { plugin: 'image-thumbs', key: 'expanded' } as const
10const REPAINTS = { plugin: 'image-thumbs', key: 'repaints' } as const
11const CLAIMED = { plugin: 'image-thumbs', key: 'claimed' } as const
12const PASTED_AT = { plugin: 'image-thumbs', key: 'pastedAt' } as const
13const USED = { plugin: 'image-thumbs', key: 'used' } as const
14const SUBMITTED = { plugin: 'image-thumbs', key: 'submittedAt' } as const
15const SLASH_PENDING = { plugin: 'image-thumbs', key: 'slashPending' } as const
16const REPLY_PICTURES = { plugin: 'image-thumbs', key: 'replyPictures' } as const
17const TURN_ROWS = { plugin: 'image-thumbs', key: 'turnRows' } as const
18
19// A transcript row is drawn under its uuid with the last group zeroed.
20const requestIdOf = (uuid: string): string => `${uuid.slice(0, 24)}000000000000`
21
22const PANE = 'image-view'
23
24// A slash command's row as the prompt shows it: `/name` or `/plugin:name`,
25// then a space or the end. A path (`/Users/me/shot.png`) is not one.
26const SLASH_ROW = /^\/[\w.:-]+(?:\s|$)/
27
28// The rows that carry a pasted picture among their blocks: a typed prompt and
29// a slash command's expansion. A skill's expansion (/recall ...) is a meta row
30// of its own by the note door; the command's row before it has the text alone.
31// A message sent mid-turn comes in by the delivery door with its text alone.
32// Most thumbnails are built at submit from the saved files; these rows build
33// the rest from their own bytes.
34const PICTURE_DOORS = ['prompt', 'command', 'attachment', 'note'] as const
35
36// Thumbnail height in terminal rows; the width follows the picture's aspect.
37const ROWS = 5
38// A terminal cell is about twice as tall as it is wide.
39const CELL_ASPECT = 2.1
40// An expanded picture's height cap in rows, so one never fills the screen.
41const EXPANDED_ROWS = 24
42// Docked beside a fullscreen transcript the pane asks for this many columns;
43// seated inline above the prompt (main screen, narrow terminal), this many rows.
44const PANE_COLUMNS = 100
45const PANE_ROWS = 40
46
47type ImageBlock = {
48 type: 'image'
49 source: { type: 'base64'; media_type?: string; data: string }
50}
51
52type Block = { type: string; [field: string]: unknown }
53
54const isImageBlock = (block: Block): block is ImageBlock => {
55 const source = block.source as { type?: string; data?: unknown } | undefined
56
57 return block.type === 'image' && source?.type === 'base64' && typeof source.data === 'string'
58}
59
60const textOf = (blocks: Block[]): string => blocks.map(block => (block.type === 'text' ? String(block.text) : '')).join('\n')
61
62// Pictures: decoding pasted bytes to disk, resizing with macOS sips, and
63// deleting what is no longer needed. They stay in this file because the
64// engine follows $ only into functions declared in the hooks module itself.
65
66// Thumbnail pixels: 240 tall covers 5 rows of a Retina cell (about 40 px)
67// with room to spare; the width cap only bites on very wide pictures.
68const THUMB_HEIGHT = 240
69const THUMB_MAX_WIDTH = 1600
70// The large view's longest side, tried in order while the PNG is over the
71// 2 MiB an Image takes as bytes.
72const VIEW_SIDES = [2048, 1600, 1200, 900]
73const MAX_PNG_BYTES = 2 * 1024 * 1024
74
75type Size = { width: number; height: number }
76
77const runOrThrow = async ($: EngineInterface, argv: string[], stdin?: string): Promise<string> => {
78 const result = await $.process.run(argv, stdin === undefined ? undefined : { stdin })
79 if (result.exitCode !== 0) {
80 throw new Error(`${argv[0]} exited ${result.exitCode}: ${result.stderr.trim()}`)
81 }
82
83 return result.stdout
84}
85
86const pixelSize = async ($: EngineInterface, path: string): Promise<Size> => {
87 const out = await runOrThrow($, ['/usr/bin/sips', '-g', 'pixelWidth', '-g', 'pixelHeight', path])
88 const width = Number(/pixelWidth: (\d+)/.exec(out)?.[1])
89 const height = Number(/pixelHeight: (\d+)/.exec(out)?.[1])
90 if (!(width > 0 && height > 0)) {
91 throw new Error(`sips gave no size for ${path}`)
92 }
93
94 return { width, height }
95}
96
97// Writes `from` as a PNG at `to`, scaled down (never up) to fit the box, with
98// macOS sips, which also reads JPEG, GIF and WebP; an Image draws PNG only.
99const writePng = async ($: EngineInterface, from: string, to: string, box: Size): Promise<Size> => {
100 const size = await pixelSize($, from)
101 const scale = Math.min(1, box.width / size.width, box.height / size.height)
102 const out = {
103 width: Math.max(1, Math.round(size.width * scale)),
104 height: Math.max(1, Math.round(size.height * scale)),
105 }
106 const resample = scale < 1 ? ['-z', String(out.height), String(out.width)] : []
107 await runOrThrow($, ['/usr/bin/sips', '-s', 'format', 'png', ...resample, from, '--out', to])
108
109 return out
110}
111
112// Reads a PNG as base64 and deletes the file. The delete is best effort: a
113// leftover stays in the private $TMPDIR folder, which macOS clears itself.
114const takePng = async ($: EngineInterface, path: string): Promise<string> => {
115 const { base64 } = await $.fs.read(path, { as: 'bytes' })
116 await $.process.run(['/bin/rm', '-f', path])
117
118 return base64
119}
120
121const folderOf = (path: string): string => path.slice(0, path.lastIndexOf('/'))
122
123// Best effort, as in takePng: the folder stays when something is left in it.
124const deleteOriginal = async ($: EngineInterface, originalPath: string): Promise<void> => {
125 await $.process.run(['/bin/rm', '-f', originalPath])
126 await $.process.run(['/bin/rmdir', folderOf(originalPath)])
127}
128
129// Where a picture's bytes are: base64 from a row, or the file Claude Code
130// saved when it was pasted.
131type Source = { data: string } | { file: string }
132
133// Copies one pasted image into a private folder of its own under $TMPDIR,
134// kept for the session so the large view can be drawn from the original,
135// and returns its thumbnail; undefined, with the reason in the debug log.
136const makeThumb = async ($: EngineInterface, source: Source, n: number): Promise<Thumb | undefined> => {
137 const created = await $.process.run(['/usr/bin/mktemp', '-d', '-t', 'claude-image-thumbs'])
138 const dir = created.stdout.trim()
139 if (created.exitCode !== 0 || dir === '') {
140 $.ui.log(`image-thumbs: no folder for image #${n}: mktemp exited ${created.exitCode}`, { to: 'debug' })
141
142 return undefined
143 }
144 const originalPath = `${dir}/original`
145
146 try {
147 if ('file' in source) {
148 await runOrThrow($, ['/bin/cp', source.file, originalPath])
149 } else {
150 await runOrThrow($, ['/usr/bin/base64', '-D', '-o', originalPath], source.data)
151 }
152 const thumbPath = `${dir}/thumb.png`
153 const size = await writePng($, originalPath, thumbPath, { width: THUMB_MAX_WIDTH, height: THUMB_HEIGHT })
154
155 return { png: await takePng($, thumbPath), ...size, n, originalPath }
156 } catch (error) {
157 $.ui.log(`image-thumbs: no thumbnail for image #${n}: ${String(error)}`, { to: 'debug' })
158 await deleteOriginal($, originalPath)
159
160 return undefined
161 }
162}
163
164// The original as the largest PNG under 2 MiB that VIEW_SIDES allows.
165const largeView = async ($: EngineInterface, originalPath: string, n: number): Promise<Shown> => {
166 const viewPath = `${folderOf(originalPath)}/view.png`
167 for (const side of VIEW_SIDES) {
168 const size = await writePng($, originalPath, viewPath, { width: side, height: side })
169 const { size: bytes } = await $.fs.stat(viewPath)
170 if (bytes <= MAX_PNG_BYTES) {
171 return { png: await takePng($, viewPath), ...size, n }
172 }
173 }
174 await $.process.run(['/bin/rm', '-f', viewPath])
175 throw new Error(`image #${n} is over ${MAX_PNG_BYTES} bytes even at ${VIEW_SIDES.at(-1)} px`)
176}
177
178const openImage = async ($: EngineInterface, n: number, originalPath: string): Promise<void> => {
179 try {
180 await $.state.set(SHOWN, await largeView($, originalPath, n))
181 } catch (error) {
182 $.ui.toast(`image-thumbs: cannot open image #${n}: ${String(error)}`)
183
184 return
185 }
186 const opened = await $.ui.open({
187 id: PANE,
188 title: `Image #${n}`,
189 focus: true,
190 closeOnEscape: true,
191 columns: PANE_COLUMNS,
192 rows: PANE_ROWS,
193 })
194 if (!opened.isPlaced) {
195 $.ui.toast(`image-thumbs: the image pane did not open: ${opened.reason}`)
196 }
197}
198
199const isThumb = (thumb: Thumb | undefined): thumb is Thumb => thumb !== undefined
200
201const isStored = async ($: EngineInterface, n: number): Promise<boolean> =>
202 (await $.state.get({ ...BY_IMAGE, id: String(n) })).value !== undefined
203
204const keepThumbs = async ($: EngineInterface, thumbs: Thumb[]): Promise<void> => {
205 if (thumbs.length === 0) {
206 return
207 }
208 await Promise.all(thumbs.map(thumb => $.state.set({ ...BY_IMAGE, id: String(thumb.n) }, thumb)))
209 const { value: pasted = [] } = await $.state.get(PASTED)
210 const added: Pasted[] = thumbs.map(({ n, originalPath }) => ({ n, originalPath }))
211 await $.state.set(PASTED, [...pasted, ...added])
212}
213
214// A text's own pictures: the numbers it names past the newest one claimed.
215const freshOf = async ($: EngineInterface, text: string): Promise<number[]> => {
216 const { value: claimed = 0 } = await $.state.get(CLAIMED)
217
218 return freshNumbers(text, claimed)
219}
220
221const claim = async ($: EngineInterface, numbers: number[]): Promise<void> => {
222 const { value: claimed = 0 } = await $.state.get(CLAIMED)
223 await $.state.set(CLAIMED, Math.max(claimed, ...numbers))
224}
225
226// Builds and stores the thumbnails of a row's own pictures not built yet,
227// matched to `images` in order.
228const storeThumbs = async ($: EngineInterface, text: string, images: ImageBlock[]): Promise<void> => {
229 const numbers = (await freshOf($, text)).slice(0, images.length)
230 const made = await Promise.all(
231 numbers.map(async (n, index) =>
232 (await isStored($, n)) ? undefined : makeThumb($, { data: images[index]?.source.data ?? '' }, n),
233 ),
234 )
235 await keepThumbs($, made.filter(isThumb))
236 await claim($, numbers)
237}
238
239// Claude Code saves each pasted picture when it is pasted, as
240// $TMPDIR/clipboard-YYYY-MM-DD-HHMMSS-<id>.png (local time). A slash
241// command's row, and a message sent mid-turn, are printed before any row
242// carrying the picture's bytes, and a printed row is not drawn again; so when
243// a prompt is submitted its thumbnails are built from these files.
244const SAVED_NAME = /\/clipboard-(\d{4})-(\d{2})-(\d{2})-(\d{2})(\d{2})(\d{2})-[0-9A-Za-z]+\.\w+$/
245// How far a file's name time may be from its paste: the name keeps whole
246// seconds, and the file is written as the paste lands.
247const PASTE_SLACK_MS = 3000
248
249type Saved = { path: string; at: number }
250
251const savedAt = (path: string): number | undefined => {
252 const parts = SAVED_NAME.exec(path)?.slice(1).map(Number)
253 if (parts === undefined) {
254 return undefined
255 }
256 const [year = 0, month = 1, day = 1, hours = 0, minutes = 0, seconds = 0] = parts
257
258 return new Date(year, month - 1, day, hours, minutes, seconds).getTime()
259}
260
261// The pictures Claude Code saved in the last two hours, oldest first.
262const savedPictures = async ($: EngineInterface): Promise<Saved[]> => {
263 const dir = (await runOrThrow($, ['/usr/bin/getconf', 'DARWIN_USER_TEMP_DIR'])).trim().replace(/\/$/, '')
264 const found = await runOrThrow($, ['/usr/bin/find', dir, '-maxdepth', '1', '-name', 'clipboard-*', '-mmin', '-120'])
265
266 return found
267 .split('\n')
268 .flatMap(path => {
269 const at = savedAt(path)
270
271 return at === undefined ? [] : [{ path, at }]
272 })
273 .sort((one, other) => one.at - other.at)
274}
275
276// The saved file of each wanted picture: the one saved nearest its paste,
277// when the paste was seen. Pictures left over take the files saved since the
278// last prompt only when there are exactly as many: one more may be another
279// session's paste, and drawing it here would show the wrong picture.
280const pickFiles = (pastedAt: (number | undefined)[], saved: Saved[], since: number): (string | undefined)[] => {
281 const taken = new Set<string>()
282 const picked = pastedAt.map(at => {
283 if (at === undefined) {
284 return undefined
285 }
286 const [nearest] = saved
287 .filter(file => !taken.has(file.path) && Math.abs(file.at - at) <= PASTE_SLACK_MS)
288 .sort((one, other) => Math.abs(one.at - at) - Math.abs(other.at - at))
289 if (nearest !== undefined) {
290 taken.add(nearest.path)
291 }
292
293 return nearest?.path
294 })
295 const missing = picked.flatMap((path, index) => (path === undefined ? [index] : []))
296 const sinceLast = saved.filter(file => !taken.has(file.path) && file.at >= since - PASTE_SLACK_MS)
297 if (missing.length > 0 && sinceLast.length === missing.length) {
298 missing.forEach((index, order) => {
299 picked[index] = sinceLast[order]?.path
300 })
301 }
302
303 return picked
304}
305
306// A picture pasted from the clipboard is saved under the session's own folder
307// as /private/tmp/claude-<uid>/<project>/<session id>/images/<n>.png, by its
308// number; a picture pasted as a file (a screenshot tool's) is not, and is
309// matched to a clipboard-* file instead. Undefined when there is no folder.
310const sessionImages = async ($: EngineInterface): Promise<string | undefined> => {
311 const uid = (await runOrThrow($, ['/usr/bin/id', '-u'])).trim()
312 const id = await $.session.id()
313 const found = await runOrThrow($, ['/usr/bin/find', `/private/tmp/claude-${uid}`, '-maxdepth', '2', '-type', 'd', '-name', id])
314 const [folder] = found.split('\n').filter(line => line !== '')
315
316 return folder === undefined ? undefined : `${folder}/images`
317}
318
319const isFile = async ($: EngineInterface, path: string): Promise<boolean> => {
320 try {
321 return (await $.fs.stat(path)).kind === 'file'
322 } catch {
323 return false
324 }
325}
326
327// At submit, before any row of the prompt exists: builds the thumbnails of
328// the pictures `text` names that are not built yet, from their saved files.
329const storeSavedThumbs = async ($: EngineInterface, text: string): Promise<void> => {
330 const submittedAt = Date.now()
331 const { value: since = 0 } = await $.state.get(SUBMITTED)
332 await $.state.set(SUBMITTED, submittedAt)
333 const numbers = await freshOf($, text)
334 const wanted = (await Promise.all(numbers.map(async n => ((await isStored($, n)) ? [] : [n])))).flat()
335 if (wanted.length === 0) {
336 return
337 }
338 const images = await sessionImages($).catch((error: unknown) => {
339 $.ui.log(`image-thumbs: no session folder found: ${String(error)}`, { to: 'debug' })
340
341 return undefined
342 })
343 const inFolder = await Promise.all(
344 wanted.map(async n => {
345 const path = images === undefined ? undefined : `${images}/${n}.png`
346
347 return path !== undefined && (await isFile($, path)) ? path : undefined
348 }),
349 )
350 let saved: Saved[] = []
351 if (inFolder.includes(undefined)) {
352 try {
353 saved = await savedPictures($)
354 } catch (error) {
355 $.ui.log(`image-thumbs: no saved pictures listed: ${String(error)}`, { to: 'debug' })
356 }
357 }
358 const { value: used = [] } = await $.state.get(USED)
359 // The numbers without a file in the folder, matched to clipboard-* files.
360 const needing = wanted.flatMap((_, index) => (inFolder[index] === undefined ? [index] : []))
361 const pastedAt = await Promise.all(
362 needing.map(async index => (await $.state.get({ ...PASTED_AT, id: String(wanted[index]) })).value),
363 )
364 const matched = pickFiles(
365 pastedAt,
366 saved.filter(file => !used.includes(file.path)),
367 since,
368 )
369 const files = [...inFolder]
370 needing.forEach((index, order) => {
371 files[index] = matched[order]
372 })
373 const made = await Promise.all(
374 wanted.map((n, index) => {
375 const file = files[index]
376
377 return file === undefined ? undefined : makeThumb($, { file }, n)
378 }),
379 )
380 const thumbs = made.filter(isThumb)
381 await keepThumbs($, thumbs)
382 await $.state.set(USED, [...used, ...files.filter((file): file is string => file !== undefined)])
383 // Claimed only when every picture was built: a row then builds the rest
384 // from its own bytes, where it carries them.
385 if (thumbs.length === wanted.length) {
386 await claim($, numbers)
387 }
388}
389
390// The largest box of cells inside `room` that keeps the picture's aspect.
391const fitCells = (size: Size, room: { columns: number; rows: number }): { columns: number; rows: number } => {
392 const columns = Math.min(room.columns, Math.round((room.rows * CELL_ASPECT * size.width) / size.height), 255)
393 const rows = Math.min(room.rows, Math.round((columns * size.height) / size.width / CELL_ASPECT), 255)
394
395 return { columns: Math.max(2, columns), rows: Math.max(1, rows) }
396}
397
398// The slash command pictures a reply row took when it first drew.
399const replyPictures = async ($: EngineInterface, ids: string[]): Promise<number[]> =>
400 (await Promise.all(ids.map(async id => (await $.state.get({ ...REPLY_PICTURES, id })).value ?? []))).flat()
401
402// The id of a reply row that may still take the waiting pictures: one of the
403// turn's rows stored since the slash command ran, while they wait.
404const claimableId = async ($: EngineInterface, ids: string[]): Promise<string | undefined> => {
405 const { value: pending = [] } = await $.state.get(SLASH_PENDING)
406 if (pending.length === 0) {
407 return undefined
408 }
409 const { value: rows = [] } = await $.state.get(TURN_ROWS)
410
411 return ids.find(id => rows.includes(id))
412}
413
414export const register: Register = on => {
415 on('session.start', async ($, e, next) => {
416 // A pane asked for by code below 144 columns waits unseen; drop any such
417 // leftover so it does not appear later when the terminal widens.
418 await $.ui.close({ id: PANE })
419 await $.command.register({
420 name: 'image',
421 description: 'Open a pasted image large in a pane',
422 argumentHint: '[image number]',
423 })
424
425 return next(e)
426 })
427
428 // Build the thumbnails before the row is stored, so the row's first drawing
429 // already has them: a row printed to the terminal's scrollback is not redrawn.
430 on('session.append', { door: PICTURE_DOORS }, async ($, e, next) => {
431 const images = e.message.content.filter(isImageBlock)
432 if (images.length === 0) {
433 return next(e)
434 }
435 // Claude Code's own numbers, in order, from the row's [Image #n] tags.
436 await storeThumbs($, textOf(e.message.content), images)
437
438 return next(e)
439 })
440
441 // A paste puts [Image #n] in the prompt box: when it landed tells which
442 // saved file is that picture's.
443 on('prompt.edit', async ($, e, next) => {
444 const numbers = imageNumbers(e.inputText)
445 if (numbers.length > 0) {
446 const at = Date.now()
447 await Promise.all(numbers.map(n => $.state.set({ ...PASTED_AT, id: String(n) }, at)))
448 }
449
450 return next(e)
451 })
452
453 // A prompt typed at the prompt or sent while Claude works, before its rows
454 // exist.
455 on('prompt.submit', async ($, e, next) => {
456 if (e.attachments?.some(attachment => attachment.type === 'image') === true) {
457 await storeSavedThumbs($, e.text)
458 }
459
460 return next(e)
461 })
462
463 // A slash command's pictures are in its arguments. The engine draws the
464 // command's row through UserMessage only as a placeholder while the command
465 // starts, and the row that stays with no render hook; so they wait for the
466 // reply's first row, a tool call or text, and are drawn above it, once.
467 on('command.run', async ($, e, next) => {
468 const named = imageNumbers(e.args)
469 if (named.length > 0) {
470 await storeSavedThumbs($, e.args)
471 const stored = (await Promise.all(named.map(async n => ((await isStored($, n)) ? [n] : [])))).flat()
472 await $.state.set(SLASH_PENDING, stored)
473 await $.state.set(TURN_ROWS, [])
474 }
475
476 return next(e)
477 })
478
479 // The reply's rows, as each is stored: a text block's under the row's id, a
480 // tool call's under its tool_use id. Thinking draws no row of its own.
481 on('session.append', { door: 'response' }, async ($, e, next) => {
482 const { value: pending = [] } = await $.state.get(SLASH_PENDING)
483 if (pending.length > 0) {
484 const ids = e.message.content.flatMap(block =>
485 block.type === 'tool_use' ? [String(block.id)] : block.type === 'text' ? [requestIdOf(e.uuid)] : [],
486 )
487 if (ids.length > 0) {
488 const { value: rows = [] } = await $.state.get(TURN_ROWS)
489 await $.state.set(TURN_ROWS, [...rows, ...ids])
490 }
491 }
492
493 return next(e)
494 })
495
496 // A reply with no text leaves nothing to draw them on; the next turn's
497 // reply is not theirs.
498 on('turn.complete', async ($, e, next) => {
499 if (e.agentId === undefined) {
500 await $.state.set(SLASH_PENDING, [])
501 await $.state.set(TURN_ROWS, [])
502 }
503
504 return next(e)
505 })
506
507 // A /clear ends the session too, and the next one may number its pictures
508 // from #1 again.
509 on('session.end', async ($, e, next) => {
510 const { value: pasted = [] } = await $.state.get(PASTED)
511 await Promise.all(pasted.map(image => deleteOriginal($, image.originalPath)))
512 await $.state.set(PASTED, [])
513
514 return next(e)
515 })
516
517 on('command.run', { command: 'image' }, async ($, e) => {
518 const { value: pasted = [] } = await $.state.get(PASTED)
519 const asked = e.args.trim().replace(/^#/, '')
520 const image = asked === '' ? pasted.at(-1) : pasted.find(one => String(one.n) === asked)
521 if (image === undefined) {
522 const known = pasted.map(one => `#${one.n}`).join(', ')
523
524 return { text: known === '' ? 'No pasted images yet.' : `No image #${asked}. Pasted so far: ${known}.` }
525 }
526 await openImage($, image.n, image.originalPath)
527
528 return { text: `Opened image #${image.n}.` }
529 })
530
531 // A click on a picture, posted by its click area (click-area.ts), expands
532 // the thumbnail in place or shrinks it back. In place rather than in a
533 // pane: a click a Client posts counts as code, and the engine seats a pane
534 // code opens only from 144 columns.
535 on('ui.message', async ($, e, next) => {
536 const data = e.data as { toggle?: unknown; repaint?: unknown; claim?: unknown } | null
537 // A reply row's claim area, on the row's first drawing here
538 // (claim-area.ts): the first to claim takes the waiting pictures.
539 if (typeof data?.claim === 'string') {
540 const id = data.claim
541 const { value: pending = [] } = await $.state.get(SLASH_PENDING)
542 const { value: rows = [] } = await $.state.get(TURN_ROWS)
543 if (pending.length > 0 && rows.includes(id)) {
544 await $.state.set({ ...REPLY_PICTURES, id }, pending)
545 await $.state.set(SLASH_PENDING, [])
546 await $.state.set(TURN_ROWS, [])
547 }
548
549 return {}
550 }
551 // A click area asking, after its first drawing, for its picture to be
552 // drawn again under a new key (click-area.ts).
553 if (typeof data?.repaint === 'number') {
554 const id = String(data.repaint)
555 const { value: repaints = 0 } = await $.state.get({ ...REPAINTS, id })
556 await $.state.set({ ...REPAINTS, id }, repaints + 1)
557
558 return {}
559 }
560 if (typeof data?.toggle !== 'number') {
561 return next(e)
562 }
563 const n = data.toggle
564 const id = String(n)
565 const { value: expandedPicture } = await $.state.get({ ...EXPANDED, id })
566 if (expandedPicture !== undefined && expandedPicture !== null) {
567 await $.state.set({ ...EXPANDED, id }, null)
568
569 return {}
570 }
571 const { value: thumb } = await $.state.get({ ...BY_IMAGE, id })
572 if (thumb === undefined) {
573 return {}
574 }
575 try {
576 await $.state.set({ ...EXPANDED, id }, await largeView($, thumb.originalPath, n))
577 } catch (error) {
578 $.ui.toast(`image-thumbs: cannot expand image #${n}: ${String(error)}`)
579 }
580
581 return {}
582 })
583
584 on('ui.render', { component: ['UserMessage', 'AssistantMessage', 'ToolUse', 'ToolGroup'] }, async ($, e, next) => {
585 if (e.surface !== 'terminal') {
586 return next(e)
587 }
588 // A prompt's row by the numbers it names, not by the row: a message sent
589 // mid-turn is drawn under an id other than the row its pictures came in
590 // on; a slash command's placeholder row draws none. A reply's row (text,
591 // a tool call, a folded group of calls) by the slash command pictures
592 // tied to it; an unfolded group leaves them to its own ToolUse rows.
593 const isReply = e.component !== 'UserMessage'
594 const rowIds =
595 e.component === 'AssistantMessage'
596 ? [e.requestId]
597 : e.component === 'ToolUse'
598 ? [e.props.tool_use_id]
599 : e.component === 'ToolGroup' && !e.props.isExpanded
600 ? e.props.calls.flatMap(call => (call.tool_use_id === undefined ? [] : [call.tool_use_id]))
601 : []
602 const numbers =
603 e.component === 'UserMessage'
604 ? SLASH_ROW.test(e.props.text)
605 ? []
606 : imageNumbers(e.props.text)
607 : await replyPictures($, rowIds)
608 if (numbers.length === 0) {
609 const id = isReply ? await claimableId($, rowIds) : undefined
610 if (id === undefined) {
611 return next(e)
612 }
613 const row = await next(e)
614 const { Box, Client } = $.ui.resolve(e)
615
616 return (
617 <Box flexDirection="column">
618 {row}
619 <Box position="absolute" top={0} left={0}>
620 <Client key={`claim-${id}`} module="./claim-area.ts" props={{ id }} width={1} height={1} />
621 </Box>
622 </Box>
623 )
624 }
625 const stored = await Promise.all(numbers.map(async n => (await $.state.get({ ...BY_IMAGE, id: String(n) })).value))
626 const thumbs = stored.filter((thumb): thumb is Thumb => thumb !== undefined)
627 if (thumbs.length === 0) {
628 return next(e)
629 }
630 const expanded = await Promise.all(
631 thumbs.map(async thumb => (await $.state.get({ ...EXPANDED, id: String(thumb.n) })).value ?? null),
632 )
633 const repaints = await Promise.all(
634 thumbs.map(async thumb => (await $.state.get({ ...REPAINTS, id: String(thumb.n) })).value ?? 0),
635 )
636 const row = await next(e)
637 const { Box, Button, Client, Image, Text } = $.ui.resolve(e)
638 // Less the row's indent and the frame's two border columns.
639 const columns = (e.viewport?.columns ?? 80) - 6
640 const room = { columns, rows: ROWS }
641 const roomExpanded = { columns, rows: Math.max(ROWS, Math.min(EXPANDED_ROWS, (e.viewport?.rows ?? 40) - 10)) }
642
643 const pictures = (
644 <Box flexDirection="row" flexWrap="wrap" columnGap={2} marginLeft={2}>
645 {thumbs.map((thumb, index) => {
646 const { n, originalPath } = thumb
647 const expandedPicture = expanded[index] ?? null
648 const cells = expandedPicture === null ? fitCells(thumb, room) : fitCells(expandedPicture, roomExpanded)
649 const png = expandedPicture === null ? thumb.png : expandedPicture.png
650 // Drawn again under a new key shortly after the first drawing: a new
651 // image id, sent again with its cells written again, as a window
652 // resize does for every picture. The first drawing can stay blank.
653 const drawing = repaints[index] ?? 0
654
655 return (
656 <Box flexDirection="column" alignItems="flex-start">
657 <Box borderStyle="round" borderDimColor>
658 <Box>
659 <Image key={`thumb-${n}-${drawing}`} source={{ png }} {...cells} alt={`[Image #${n}]`} />
660 <Box position="absolute" top={0} left={0}>
661 <Client
662 key={`click-${n}`}
663 module="./click-area.ts"
664 props={{ n }}
665 width={cells.columns}
666 height={cells.rows}
667 />
668 </Box>
669 </Box>
670 </Box>
671 <Box flexDirection="row">
672 <Text dimColor>
673 #{n} · click the picture to {expandedPicture === null ? 'expand' : 'shrink'} ·{' '}
674 </Text>
675 <Button
676 key={`open-${n}`}
677 label="open in pane"
678 plain
679 dimColor
680 onPress={() => openImage($, n, originalPath)}
681 />
682 </Box>
683 </Box>
684 )
685 })}
686 </Box>
687 )
688
689 // Under a prompt; above a reply, whose text follows from the pictures.
690 return (
691 <Box flexDirection="column">
692 {isReply && pictures}
693 {row}
694 {!isReply && pictures}
695 </Box>
696 )
697 })
698
699 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
700 const { value: shown } = await $.state.get(SHOWN)
701 if (e.surface !== 'terminal' || shown === undefined || shown === null) {
702 const { Text } = $.ui.resolve(e)
703
704 return <Text dimColor>No image open. Type /image to open the latest one.</Text>
705 }
706 const { Box, Image, Text } = $.ui.resolve(e)
707 const room = { columns: e.props.bodyColumns, rows: Math.max(2, e.props.scroll.bodyRows - 1) }
708
709 return (
710 <Box flexDirection="column">
711 <Image key="view" source={{ png: shown.png }} {...fitCells(shown, room)} alt={`[Image #${shown.n}]`} />
712 <Text dimColor>
713 {shown.width}×{shown.height} px · Esc closes
714 </Text>
715 </Box>
716 )
717 })
718}
719hooks/numbers.ts 19 lines1// Claude Code numbers the pictures pasted in a session (#1, #2, ...) and writes
2// [Image #n] where each one sits in the prompt's text. The tag is what ties a
3// picture to the rows that show it: the typed prompt, a slash command's row
4// (its pictures arrive on the command's expansion, a row of their own), and a
5// message sent while Claude works (they arrive on the attachment that folds it
6// into the turn).
7const TAG = /\[Image #(\d+)\]/g
8
9// The picture numbers a text names, each once, in the order first written.
10export const imageNumbers = (text: string): number[] => [
11 ...new Set([...text.matchAll(TAG)].map(match => Number(match[1]))),
12]
13
14// The numbers of a row's own pictures, in order: those its text names past
15// `last`, the newest number seen before. A number at or below it refers to an
16// earlier picture again. A picture the text names nowhere (a file the prompt
17// attached) has none.
18export const freshNumbers = (text: string, last: number): number[] => imageNumbers(text).filter(n => n > last)
19hooks/claim-area.ts 18 lines1import type { ClientModule } from 'claude-code'
2
3// Lies over a reply row while a slash command's pictures wait for a row to
4// draw them, and draws nothing. On its first drawing it tells the hooks module
5// that this row drew here, so the row takes the pictures and draws them.
6// A row another mod draws on its own never draws this, and never takes them;
7// a render hook may not write state, so the claim comes this way.
8const ClaimArea: ClientModule<{ id: string }, { isClaimed: true }> = (props, surface) => {
9 if (surface.state === undefined) {
10 surface.setState({ isClaimed: true })
11 surface.post({ claim: props.id })
12 }
13
14 return surface.elements.Box({})
15}
16
17export default ClaimArea
18hooks/click-area.ts 34 lines1import type { ClientModule } from 'claude-code'
2
3// How long after a thumbnail first draws its click area asks for it to be
4// drawn again.
5const REPAINT_MS = 300
6
7// Lies over a picture in a prompt row and draws nothing, so the picture
8// beneath shows, and tells the hooks module the number of the picture a left
9// click landed on.
10//
11// On a new thumbnail's first drawing cmux's terminal (Ghostty 1.3.2) can leave
12// the box empty until a window resize, which sends every picture again and
13// writes its cells again. Changing cells beside it, or sending it again under
14// the same id, does not; so shortly after, the click area asks for it to be
15// drawn again under a new key, which does both for this picture alone.
16const ClickArea: ClientModule<{ n: number }, { isRepaintAsked: true }> = (props, surface) => {
17 if (surface.state === undefined) {
18 surface.setState({ isRepaintAsked: true })
19 const stop = surface.every(REPAINT_MS, () => {
20 stop()
21 surface.post({ repaint: props.n })
22 })
23 }
24 surface.onPointer(event => {
25 if (event.type === 'up' && event.button === 'left') {
26 surface.post({ toggle: props.n })
27 }
28 })
29
30 return surface.elements.Box({})
31}
32
33export default ClickArea
34types/index.d.ts 47 lines1// One pasted picture's thumbnail, under Claude Code's number for it.
2export type Thumb = {
3 png: string
4 width: number
5 height: number
6 n: number
7 // The decoded original on disk, for the large view.
8 originalPath: string
9}
10
11// The picture the image pane draws.
12export type Shown = { png: string; width: number; height: number; n: number }
13
14// Every image pasted this session, for `/image <n>`: Claude Code's number
15// and the decoded original on disk.
16export type Pasted = { n: number; originalPath: string }
17
18declare module 'claude-code' {
19 interface PluginState {
20 'image-thumbs': {
21 // Thumbnails by image number: every row whose text names it draws it.
22 byImage: StateFamily<Thumb>
23 // How many times each thumbnail asked to be drawn again; part of its key.
24 repaints: StateFamily<number>
25 shown: Shown | null
26 // The large picture a thumbnail expanded into, by image number.
27 expanded: StateFamily<Shown | null>
28 pasted: Pasted[]
29 // The newest picture number a row or a submitted prompt took as its own.
30 claimed: number
31 // When each picture's [Image #n] landed in the prompt box, in ms.
32 pastedAt: StateFamily<number>
33 // The saved clipboard files thumbnails were built from.
34 used: string[]
35 // When the last prompt or slash command was submitted, in ms.
36 submittedAt: number
37 // A slash command's pictures, waiting for the first reply row with text.
38 slashPending: number[]
39 // The reply rows stored since the slash command ran: the first of them
40 // that draws through this mod takes its pictures.
41 turnRows: string[]
42 // The slash command pictures drawn above a reply row, by its request id.
43 replyPictures: StateFamily<number[]>
44 }
45 }
46}
47