📸 Shows you the pictures: a thumbnail the moment you paste one, and /gallery of every image you and Claude passed around this session.

Shows a thumbnail as soon as you paste a screenshot, and keeps a gallery of every image in the session.

/plugin install show-and-tell@claude-desk-neighbours
Hit ctrl+v with an image on your clipboard and a thumbnail appears above the prompt within about a quarter of a second, before you've sent anything. Show & Tell watches your draft for Claude Code's [Image #1] and copies the image Claude Code saved for it. If that file isn't where it expects, it reads the clipboard itself (osascript on macOS, wl-paste or xclip on Linux, PowerShell on Windows). If that doesn't work either, it grabs the image when you send the prompt.
Claude's pictures get picked up the same way. That covers images Claude opens with Read, screenshots returned by browser or MCP tools, pictures Claude writes or edits, and images a shell command creates in the working directory or one level down (playwright screenshot, a chart script).
The band above the prompt shows the newest thumbnails, with Gallery and Dismiss buttons. A pasted thumbnail stays for as long as it's in your draft. If you delete it or clear the draft, it goes straight away. Once you send it, it goes 20 seconds later, the same as everything else. You can change that time in /config.
Run /gallery, or click the band's Gallery button, to see every image from this session, newest first, with a big preview of whichever one you select. a, y and c filter to all images, yours, or Claude's. o opens the image in your viewer, i puts @path in your prompt so Claude can look at it again, p copies the path, and f shows it in its folder. Tab moves through the list. This is after Claude fixed the checkout and took a snapshot:

The gallery asks for enough room to show a picture. If it doesn't get it (say, an inline pane in a small terminal), the picture shrinks to fit and the footer is hidden so the header, actions and list stay visible.
Pictures only render in terminals that support the kitty graphics protocol, which means Ghostty and kitty. In other terminals, in tmux and in the desktop app, the band and gallery show the same thing as text (📎 Pasted image #1 · 200×120), and all the buttons still work.
Thumbnails have to be PNGs, so other formats get converted once: with sips on macOS and ImageMagick (magick or convert) elsewhere. On macOS, qlmanage handles SVG and PDF. If there's no converter, the image is still listed, just without a picture.
There are no model calls. Pasted images, and images that only exist inside a tool's result, are copied to ~/.claude/show-and-tell/<session>/ next to a manifest.json that restores the gallery after /resume. Files Claude read or created stay where they are. Copies older than seven days are deleted when a session starts. The cleanup uses find, so on Windows they stick around until you delete them yourself.
While a session is open, the draft is checked four times a second. That's just a read of the prompt box, and nothing runs unless a new [Image #N] shows up. Where Claude Code saves pastes (/tmp/claude-<uid>/…/images/) isn't part of the plugin API, so a future version of Claude Code might move it. If that happens, Show & Tell falls back to reading the clipboard.
hooks/register.tsx 722 lines1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import type { Shot, ShotSource } from '../types'
5
6const SHOTS = { plugin: 'show-and-tell', key: 'shots' } as const
7const FRESH = { plugin: 'show-and-tell', key: 'fresh' } as const
8const PICKED = { plugin: 'show-and-tell', key: 'picked' } as const
9const FILTER = { plugin: 'show-and-tell', key: 'filter' } as const
10
11const shots = atom(SHOTS, [])
12const fresh = atom(FRESH, [])
13const picked = atom(PICKED, null)
14const filter = atom(FILTER, 'all')
15
16const PANE = 'show-and-tell'
17const TITLE = '📸 Show & Tell'
18
19const POLL_MS = 250
20const KEEP_DAYS = 7
21const MAX_SHOTS = 200
22const MAX_READ = 4 * 1024 * 1024
23const THUMB_COLUMNS = 16
24const PREVIEW_COLUMNS = 72
25const GALLERY_ROWS = 24
26const GALLERY_COLUMNS = 90
27// From this width the preview sits beside the details and the list, not above them.
28const SIDE_BY_SIDE = 70
29const SCAN_DIRS = 40
30
31const PICTURE = /\.(png|jpe?g|gif|webp|bmp|tiff?|heic|svg|pdf)$/i
32const VECTOR = /\.(svg|pdf)$/i
33const IMAGE_TOKEN = /\[Image #(\d+)\]/g
34const ICON: Record<ShotSource, string> = { you: '📎', 'claude-read': '👀', 'claude-made': '🎨' }
35
36type Block = { type: string; [field: string]: unknown }
37type Platform = 'mac' | 'linux' | 'windows'
38type Look = { thumb: string | null; width: number | null; height: number | null }
39
40/** The image numbers a draft holds, as Claude Code writes a paste into it: `[Image #2]`. */
41export function imageNumbers(text: string): number[] {
42 return [...text.matchAll(IMAGE_TOKEN)].map(match => Number(match[1]))
43}
44
45/** What kind of picture base64 bytes are, by their first bytes. */
46export function kindOf(base64: string): 'png' | 'jpeg' | 'gif' | 'webp' | null {
47 if (base64.startsWith('iVBORw0KGgo')) return 'png'
48 if (base64.startsWith('/9j/')) return 'jpeg'
49 if (base64.startsWith('R0lGOD')) return 'gif'
50 if (base64.startsWith('UklGR')) return 'webp'
51 return null
52}
53
54const BASE64 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
55
56/** A PNG's width and height, read from its header. */
57export function pngSize(base64: string): { width: number; height: number } | null {
58 if (kindOf(base64) !== 'png' || base64.length < 32) return null
59 const bytes: number[] = []
60 for (let at = 0; at < 32; at += 4) {
61 const n = [0, 1, 2, 3].reduce((acc, i) => (acc << 6) | BASE64.indexOf(base64[at + i] ?? 'A'), 0)
62 bytes.push((n >> 16) & 255, (n >> 8) & 255, n & 255)
63 }
64 const word = (at: number) => (((bytes[at] ?? 0) << 24) | ((bytes[at + 1] ?? 0) << 16) | ((bytes[at + 2] ?? 0) << 8) | (bytes[at + 3] ?? 0)) >>> 0
65 const width = word(16)
66 const height = word(20)
67 return width > 0 && height > 0 ? { width, height } : null
68}
69
70/** How many rows a picture `columns` wide needs; a terminal cell is about twice as tall as wide. */
71export function rowsFor(width: number | null, height: number | null, columns: number, maxRows: number): number {
72 const rows = width !== null && height !== null ? Math.round((columns * height) / width / 2) : Math.round(columns / 3)
73 return Math.max(1, Math.min(maxRows, rows))
74}
75
76/** The base64 of every image block in a row's content, those inside a tool result included. */
77export function imagesIn(content: readonly Block[]): string[] {
78 const found: string[] = []
79 for (const block of content) {
80 if (block.type === 'image') {
81 const source = block.source as { type?: unknown; data?: unknown } | undefined
82 if (source?.type === 'base64' && typeof source.data === 'string') found.push(source.data)
83 } else if (block.type === 'tool_result' && Array.isArray(block.content)) {
84 found.push(...imagesIn(block.content as Block[]))
85 }
86 }
87 return found
88}
89
90/** `mcp__claude-in-chrome__computer` reads as `claude-in-chrome computer`. */
91export function toolLabel(tool: string): string {
92 return tool.startsWith('mcp__') ? tool.slice(5).split('__').join(' ') : tool
93}
94
95function baseName(path: string): string {
96 return path.split(/[\\/]/).pop() ?? path
97}
98
99function dirName(path: string): string {
100 const at = Math.max(path.lastIndexOf('/'), path.lastIndexOf('\\'))
101 return at <= 0 ? path : path.slice(0, at)
102}
103
104/** "10:42" in local time. */
105function clockTime(ms: number): string {
106 const d = new Date(ms)
107 return `${String(d.getHours()).padStart(2, '0')}:${String(d.getMinutes()).padStart(2, '0')}`
108}
109
110async function ran($: EngineInterface, argv: readonly string[], init?: { stdin?: string; env?: Record<string, string> }): Promise<boolean> {
111 const done = await $.process.run(argv, init).catch(() => null)
112 return done?.exitCode === 0
113}
114
115let platformOf: Promise<Platform> | null = null
116let userOf: Promise<string | null> | null = null
117
118function platform($: EngineInterface): Promise<Platform> {
119 platformOf ??= (async (): Promise<Platform> => {
120 if ((await $.env.get('WINDIR')) !== undefined) return 'windows'
121 const uname = await $.process.run(['uname', '-s']).catch(() => null)
122 return uname?.stdout.trim() === 'Darwin' ? 'mac' : 'linux'
123 })()
124 return platformOf
125}
126
127function userId($: EngineInterface): Promise<string | null> {
128 userOf ??= $.process
129 .run(['id', '-u'])
130 .then(r => (r.exitCode === 0 ? r.stdout.trim() : null))
131 .catch(() => null)
132 return userOf
133}
134
135async function storeRoot($: EngineInterface): Promise<string | null> {
136 const home = (await $.env.get('HOME')) ?? (await $.env.get('USERPROFILE'))
137 return home === undefined ? null : `${home}/.claude/show-and-tell`
138}
139
140async function sessionDir($: EngineInterface): Promise<string | null> {
141 const root = await storeRoot($)
142 if (root === null) return null
143 const dir = `${root}/${await $.session.id()}`
144 // `$.fs.write` makes the folders it needs; the shell copies below do not.
145 if (!(await $.fs.exists(dir))) await $.fs.write(`${dir}/.keep`, '')
146 return dir
147}
148
149let seq = 0
150
151async function newId($: EngineInterface, prefix: string): Promise<{ id: string; at: number }> {
152 const at = await $.clock.now()
153 seq += 1
154 return { id: `${prefix}-${at}-${seq}`, at }
155}
156
157async function writeBytes($: EngineInterface, path: string, base64: string): Promise<boolean> {
158 if ((await platform($)) === 'windows') {
159 const script = '[IO.File]::WriteAllBytes($env:SHOW_AND_TELL_OUT, [Convert]::FromBase64String([Console]::In.ReadToEnd()))'
160 return ran($, ['powershell', '-NoProfile', '-Command', script], { stdin: base64, env: { SHOW_AND_TELL_OUT: path } })
161 }
162 return ran($, ['sh', '-c', 'base64 --decode > "$1"', 'sh', path], { stdin: base64 })
163}
164
165async function copyFile($: EngineInterface, from: string, to: string): Promise<boolean> {
166 if ((await platform($)) === 'windows') {
167 const script = 'Copy-Item -LiteralPath $env:SHOW_AND_TELL_FROM -Destination $env:SHOW_AND_TELL_OUT'
168 return ran($, ['powershell', '-NoProfile', '-Command', script], { env: { SHOW_AND_TELL_FROM: from, SHOW_AND_TELL_OUT: to } })
169 }
170 return ran($, ['cp', from, to])
171}
172
173/** Writes the clipboard's picture to `path` as a PNG, with the tool each platform has. */
174async function clipboardTo($: EngineInterface, path: string): Promise<boolean> {
175 const os = await platform($)
176 if (os === 'mac') {
177 await ran($, [
178 'osascript',
179 '-e', 'on run argv',
180 '-e', 'set f to open for access (POSIX file (item 1 of argv)) with write permission',
181 '-e', 'set eof f to 0',
182 '-e', 'write (the clipboard as «class PNGf») to f',
183 '-e', 'close access f',
184 '-e', 'end run',
185 path,
186 ])
187 } else if (os === 'linux') {
188 const read = 'wl-paste --no-newline --type image/png > "$1" 2>/dev/null || xclip -selection clipboard -t image/png -o > "$1"'
189 await ran($, ['sh', '-c', read, 'sh', path])
190 } else {
191 const script =
192 'Add-Type -AssemblyName System.Windows.Forms; $i = [System.Windows.Forms.Clipboard]::GetImage(); if ($i) { $i.Save($env:SHOW_AND_TELL_OUT) } else { exit 1 }'
193 await ran($, ['powershell', '-NoProfile', '-STA', '-Command', script], { env: { SHOW_AND_TELL_OUT: path } })
194 }
195 const stat = await $.fs.stat(path).catch(() => null)
196 return stat !== null && stat.size > 0
197}
198
199/** Where Claude Code keeps a pasted image the moment it lands in the draft. Not an API: when it
200 * moves, the clipboard is read instead, and failing that the image is taken as the prompt is sent. */
201async function pasteCache($: EngineInterface, n: number): Promise<string | null> {
202 const uid = await userId($)
203 if (uid === null) return null
204 const base = (await $.env.get('CLAUDE_CODE_TMPDIR')) ?? '/tmp'
205 const project = (await $.session.cwd()).replace(/[^A-Za-z0-9]/g, '-')
206 const path = `${base}/claude-${uid}/${project}/${await $.session.id()}/images/${n}.png`
207 return (await $.fs.exists(path)) ? path : null
208}
209
210async function sizeOf($: EngineInterface, png: string): Promise<{ width: number; height: number } | null> {
211 const stat = await $.fs.stat(png).catch(() => null)
212 if (stat === null || stat.size > MAX_READ) return null
213 const { base64 } = await $.fs.read(png, { as: 'bytes' })
214 return pngSize(base64)
215}
216
217/** A PNG of `file` the terminal can draw: the file itself when it is one, else one converted
218 * into `dir`. Null where this machine has no converter for it. */
219async function lookOf($: EngineInterface, file: string, dir: string, id: string): Promise<Look> {
220 const size = await sizeOf($, file).catch(() => null)
221 if (size !== null) return { thumb: file, ...size }
222 const os = await platform($)
223 let thumb: string | null = null
224 if (os === 'mac' && VECTOR.test(file)) {
225 const out = `${dir}/${id}`
226 if ((await ran($, ['mkdir', '-p', out])) && (await ran($, ['qlmanage', '-t', '-s', '800', '-o', out, file]))) {
227 thumb = `${out}/${baseName(file)}.png`
228 }
229 } else if (os === 'mac') {
230 const out = `${dir}/${id}.thumb.png`
231 if (await ran($, ['sips', '-s', 'format', 'png', file, '--out', out])) thumb = out
232 } else {
233 const out = `${dir}/${id}.thumb.png`
234 const first = VECTOR.test(file) ? `${file}[0]` : file
235 if ((await ran($, ['magick', first, out])) || (os === 'linux' && (await ran($, ['convert', first, out])))) thumb = out
236 }
237 if (thumb === null || !(await $.fs.exists(thumb))) return { thumb: null, width: null, height: null }
238 const converted = await sizeOf($, thumb).catch(() => null)
239 return { thumb, width: converted?.width ?? null, height: converted?.height ?? null }
240}
241
242let bandMs = 20_000
243
244async function saveManifest($: EngineInterface): Promise<void> {
245 const dir = await sessionDir($)
246 if (dir !== null) await $.fs.write(`${dir}/manifest.json`, JSON.stringify(await read($, shots)))
247}
248
249async function loadManifest($: EngineInterface): Promise<void> {
250 const root = await storeRoot($)
251 const path = root === null ? null : `${root}/${await $.session.id()}/manifest.json`
252 const saved = path !== null && (await $.fs.exists(path)) ? (JSON.parse(await $.fs.read(path)) as Shot[]) : []
253 const kept: Shot[] = []
254 for (const shot of saved) {
255 if (!(await $.fs.exists(shot.path))) continue
256 const hasThumb = shot.thumb !== null && (await $.fs.exists(shot.thumb))
257 kept.push(hasThumb ? shot : { ...shot, thumb: null })
258 }
259 await $.state.set(SHOTS, kept)
260}
261
262async function addShot($: EngineInterface, shot: Shot, isFresh: boolean): Promise<void> {
263 await update($, shots, list => {
264 const same = (s: Shot) => s.id === shot.id || (shot.source !== 'you' && s.source !== 'you' && s.path === shot.path)
265 // Claude often reads back a picture it just made; it stays one Claude made.
266 const wasMade = shot.source === 'claude-read' && list.some(s => same(s) && s.source === 'claude-made')
267 return [{ ...shot, source: wasMade ? 'claude-made' : shot.source }, ...list.filter(s => !same(s))].slice(0, MAX_SHOTS)
268 })
269 await saveManifest($)
270 if (!isFresh) return
271 await update($, fresh, ids => [shot.id, ...ids.filter(id => id !== shot.id)].slice(0, 8))
272 // A paste still in the draft stays up; its time starts when the prompt is sent.
273 if (shot.source !== 'you' || shot.isSent === true) expire($, shot.id)
274}
275
276/** Takes a thumbnail off the band once its time is up. */
277function expire($: EngineInterface, id: string): void {
278 $.clock.after(bandMs, () => void update($, fresh, ids => ids.filter(f => f !== id)).catch(() => undefined))
279}
280
281/** Takes a paste the moment its `[Image #N]` shows in the draft. */
282async function capturePaste($: EngineInterface, n: number): Promise<void> {
283 const known = (await read($, shots)).some(s => s.source === 'you' && s.imageNo === n && s.isSent !== true)
284 if (known) return
285 const dir = await sessionDir($)
286 if (dir === null) return
287 const { id, at } = await newId($, 'paste')
288 const path = `${dir}/${id}.png`
289 const cached = await pasteCache($, n).catch(() => null)
290 const isTaken = cached !== null ? await copyFile($, cached, path) : await clipboardTo($, path)
291 if (!isTaken) return
292 const look = await lookOf($, path, dir, id)
293 await addShot($, { id, source: 'you', label: `Pasted image #${n}`, path, ...look, at, imageNo: n }, true)
294}
295
296async function saveBytes($: EngineInterface, base64: string, source: ShotSource, label: string, isFresh: boolean, imageNo?: number): Promise<void> {
297 const kind = kindOf(base64)
298 if (kind === null) return
299 const dir = await sessionDir($)
300 if (dir === null) return
301 const { id, at } = await newId($, source)
302 const path = `${dir}/${id}.${kind === 'jpeg' ? 'jpg' : kind}`
303 if (!(await writeBytes($, path, base64))) return
304 const size = pngSize(base64)
305 const look = size !== null ? { thumb: path, ...size } : await lookOf($, path, dir, id)
306 await addShot($, { id, source, label, path, ...look, at, ...(imageNo !== undefined ? { imageNo, isSent: true } : {}) }, isFresh)
307}
308
309/** A prompt's images as it is stored: a paste already taken is marked sent, any other is kept now. */
310async function takePrompt($: EngineInterface, images: readonly string[], numbers: readonly number[]): Promise<void> {
311 for (const [index, base64] of images.entries()) {
312 const n = numbers[index]
313 const list = await read($, shots)
314 const taken = list.find(s => s.source === 'you' && s.imageNo === n && s.isSent !== true)
315 if (taken !== undefined) {
316 await update($, shots, all => all.map(s => (s.id === taken.id ? { ...s, isSent: true } : s)))
317 continue
318 }
319 await saveBytes($, base64, 'you', n === undefined ? 'Sent image' : `Image #${n}`, false, n)
320 }
321 await saveManifest($)
322}
323
324/** A file Claude read or made, shown where it lies; only a converted thumbnail is the plugin's. */
325async function keepFile($: EngineInterface, file: string, source: ShotSource): Promise<void> {
326 const dir = await sessionDir($)
327 if (dir === null) return
328 const { id, at } = await newId($, source)
329 const look = await lookOf($, file, dir, id)
330 await addShot($, { id, source, label: baseName(file), path: file, ...look, at }, true)
331}
332
333/** Pictures a shell command wrote: the working directory and the folders just inside it. */
334async function scanMade($: EngineInterface, since: number): Promise<void> {
335 const cwd = await $.session.cwd()
336 const root = await storeRoot($)
337 const top = await $.fs.list(cwd).catch(() => [])
338 const dirs = [cwd, ...top.filter(e => e.kind === 'dir' && !e.name.startsWith('.') && e.name !== 'node_modules').map(e => `${cwd}/${e.name}`)]
339 const made: string[] = []
340 for (const dir of dirs.slice(0, SCAN_DIRS)) {
341 const entries = dir === cwd ? top : await $.fs.list(dir).catch(() => [])
342 for (const entry of entries) {
343 const path = `${dir}/${entry.name}`
344 if (entry.kind === 'file' && PICTURE.test(entry.name) && entry.mtimeMs >= since && (root === null || !path.startsWith(root))) made.push(path)
345 }
346 }
347 for (const path of made.slice(0, 12)) await keepFile($, path, 'claude-made')
348}
349
350/** Removes kept images older than a week. `$.fs` cannot delete, so this asks `find`; where there is
351 * no `find` (Windows) the call fails and the images stay. */
352async function prune($: EngineInterface): Promise<void> {
353 const root = await storeRoot($)
354 if (root === null || !(await $.fs.exists(root))) return
355 await $.process.run(['find', root, '-type', 'f', '-mtime', `+${KEEP_DAYS}`, '-delete'])
356 await $.process.run(['find', root, '-mindepth', '1', '-type', 'd', '-empty', '-delete'])
357}
358
359let seen: number[] = []
360let isPolling = false
361// Image numbers sent with a prompt that the draft has not yet been seen to drop; their leaving is
362// the send, not the draft being abandoned.
363let submitted: number[] = []
364// The image numbers of the prompt being sent, matched in order to the image blocks it is stored with.
365let sending: number[] = []
366
367async function poll($: EngineInterface): Promise<void> {
368 if (isPolling) return
369 isPolling = true
370 try {
371 const now = imageNumbers((await $.prompt.read()).text)
372 const added = now.filter(n => !seen.includes(n))
373 const gone = seen.filter(n => !now.includes(n))
374 const abandoned = gone.filter(n => !submitted.includes(n))
375 submitted = submitted.filter(n => !gone.includes(n))
376 seen = now
377 if (abandoned.length > 0) await dropPastes($, abandoned)
378 for (const n of added) await capturePaste($, n)
379 } finally {
380 isPolling = false
381 }
382}
383
384async function openFile($: EngineInterface, path: string): Promise<void> {
385 const os = await platform($)
386 const argv = os === 'mac' ? ['open', path] : os === 'linux' ? ['xdg-open', path] : ['cmd', '/c', 'start', '', path]
387 if (!(await ran($, argv))) $.ui.toast(`📸 Could not open ${path}`)
388}
389
390async function showInFolder($: EngineInterface, path: string): Promise<void> {
391 const os = await platform($)
392 const argv = os === 'mac' ? ['open', '-R', path] : os === 'linux' ? ['xdg-open', dirName(path)] : ['explorer', `/select,${path}`]
393 // Explorer exits 1 even when it opens the folder.
394 if (!(await ran($, argv)) && os !== 'windows') $.ui.toast(`📸 Could not open ${dirName(path)}`)
395}
396
397async function copyPath($: EngineInterface, path: string, surface: 'terminal' | 'desktop' | 'mobile' | 'vscode'): Promise<void> {
398 const copied = await $.ui.copy({ text: path, surface })
399 $.ui.toast(copied.isCopied ? '📸 Path copied' : `📸 ${path}`)
400}
401
402async function insertPath($: EngineInterface, path: string): Promise<void> {
403 await $.ui.close({ id: PANE })
404 await $.prompt.fill({ text: `@${path} `, mode: 'insert' })
405}
406
407/** The unsent pastes on the band with these image numbers. */
408async function pastesOf($: EngineInterface, numbers: readonly number[]): Promise<string[]> {
409 const list = await read($, shots)
410 const ids = await read($, fresh)
411 return list
412 .filter(s => ids.includes(s.id) && s.source === 'you' && s.isSent !== true && s.imageNo !== undefined && numbers.includes(s.imageNo))
413 .map(s => s.id)
414}
415
416/** A paste taken out of the draft, or the draft cleared, takes its thumbnail down at once. */
417async function dropPastes($: EngineInterface, numbers: readonly number[]): Promise<void> {
418 const gone = await pastesOf($, numbers)
419 await update($, fresh, ids => ids.filter(id => !gone.includes(id)))
420}
421
422/** A sent paste's thumbnail stays its usual time from now. */
423async function expirePastes($: EngineInterface, numbers: readonly number[]): Promise<void> {
424 for (const id of await pastesOf($, numbers)) expire($, id)
425}
426
427async function reset($: EngineInterface): Promise<void> {
428 seen = []
429 submitted = []
430 await $.state.set(SHOTS, [])
431 await $.state.set(FRESH, [])
432 await $.state.set(PICKED, null)
433}
434
435// The engine draws the band's collapse mark `[-]` over the right end of its first row without
436// narrowing `bodyColumns`, so band rows stop this many cells short of the edge.
437const MARKER = 4
438
439/** Opens the gallery. Inline it would get a third of the height; a picture needs more. */
440async function openGallery($: EngineInterface): Promise<void> {
441 await $.ui.open({ id: PANE, title: TITLE, focus: true, closeOnEscape: true, rows: GALLERY_ROWS, columns: GALLERY_COLUMNS })
442}
443
444/** The box a picture fills: `columns` wide unless that would make it taller than `maxRows`,
445 * then as wide as `maxRows` allows, keeping its shape. */
446export function fitPicture(width: number | null, height: number | null, columns: number, maxRows: number): { columns: number; rows: number } {
447 const rows = rowsFor(width, height, columns, maxRows)
448 if (width === null || height === null || Math.round((columns * height) / width / 2) <= maxRows) return { columns, rows }
449 return { columns: Math.max(1, Math.min(columns, Math.round((maxRows * 2 * width) / height))), rows: maxRows }
450}
451
452function sizeText(shot: Shot): string {
453 return shot.width !== null && shot.height !== null ? ` · ${shot.width}×${shot.height}` : ''
454}
455
456const SOURCE_WORD: Record<ShotSource, string> = { you: 'you pasted', 'claude-read': 'Claude looked at', 'claude-made': 'Claude made' }
457
458export const register: Register = (on, options) => {
459 bandMs = Number(options.bandSeconds ?? 20) * 1000
460
461 on('session.start', async ($, e, next) => {
462 await $.command.register({ name: 'gallery', description: '📸 Every image you and Claude passed around this session' })
463 void loadManifest($).catch(() => undefined)
464 void prune($).catch(() => undefined)
465 if (e.isInteractive) $.clock.every(POLL_MS, () => void poll($).catch(() => undefined))
466 return next(e)
467 })
468
469 on('command.run', { command: 'gallery' }, async $ => {
470 await openGallery($)
471 return { text: '📸 Gallery open. Esc closes.' }
472 })
473
474 on('prompt.submit', ($, e, next) => {
475 sending = imageNumbers(e.text)
476 submitted = [...submitted, ...sending]
477 void expirePastes($, sending).catch(() => undefined)
478 return next(e)
479 })
480
481 // The image bytes first reach a plugin here, as the prompt or a tool's result is stored. The row
482 // passes on untouched; what it carries is copied out beside it.
483 on('session.append', { door: 'prompt' }, ($, e, next) => {
484 const images = imagesIn(e.message.content)
485 if (images.length > 0) {
486 const numbers = sending
487 sending = []
488 void takePrompt($, images, numbers).catch(() => undefined)
489 }
490 return next(e)
491 })
492
493 on('session.append', { door: 'tool-result' }, ($, e, next) => {
494 // A Read keeps the file it read (below); every other tool's picture exists only here.
495 const tool = e.origin.kind === 'tool' && 'tool' in e.origin ? e.origin.tool : null
496 if (tool !== null && tool !== 'Read') {
497 for (const base64 of imagesIn(e.message.content)) {
498 void saveBytes($, base64, 'claude-read', toolLabel(tool), true).catch(() => undefined)
499 }
500 }
501 return next(e)
502 })
503
504 on('tool.call', { tool: 'Read' }, async ($, e, next) => {
505 const done = await next(e)
506 if (done.deny === undefined && done.isError !== true && PICTURE.test(e.file_path)) {
507 void keepFile($, e.file_path, 'claude-read').catch(() => undefined)
508 }
509 return done
510 })
511
512 on('tool.call', { tool: 'Write' }, async ($, e, next) => {
513 const done = await next(e)
514 if (done.deny === undefined && done.isError !== true && PICTURE.test(e.file_path)) {
515 void keepFile($, e.file_path, 'claude-made').catch(() => undefined)
516 }
517 return done
518 })
519
520 on('tool.call', { tool: 'Edit' }, async ($, e, next) => {
521 const done = await next(e)
522 if (done.deny === undefined && done.isError !== true && PICTURE.test(e.file_path)) {
523 void keepFile($, e.file_path, 'claude-made').catch(() => undefined)
524 }
525 return done
526 })
527
528 on('tool.call', { tool: 'Bash' }, async ($, e, next) => {
529 const since = await $.clock.now()
530 const done = await next(e)
531 if (done.deny === undefined) void scanMade($, since).catch(() => undefined)
532 return done
533 })
534
535 // `/clear` and `/resume` go on under a new session with empty state and fire no `session.start`;
536 // their classic SessionStart (source `clear` or `resume`) is the one place to load the gallery again.
537 on('classic.SessionStart', ($, e, next) => {
538 if (e.source === 'clear' || e.source === 'resume') void loadManifest($).catch(() => undefined)
539 return next(e)
540 })
541
542 on('session.end', async ($, e, next) => {
543 if (e.reason === 'clear' || e.reason === 'resume') await reset($).catch(() => undefined)
544 return next(e)
545 })
546
547 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
548 if (e.props.hasSurvey) return next(e)
549 const ids = await read($, fresh)
550 const list = await read($, shots)
551 const showing = ids.map(id => list.find(s => s.id === id)).filter((s): s is Shot => s !== undefined)
552 if (showing.length === 0) return next(e)
553 const below = await next(e)
554 const width = e.props.bodyColumns - MARKER
555 const fits = Math.max(1, Math.floor((width - 22) / (THUMB_COLUMNS + 2)))
556 const thumbRows = e.props.maxRows - 2
557 if (e.surface === 'terminal' && thumbRows >= 3) {
558 const { Box, Text, Button, Image } = $.ui.resolve(e)
559 return (
560 <Box flexDirection="column">
561 {below}
562 <Box flexDirection="row" columnGap={2} width={width}>
563 {showing.slice(0, fits).map(shot => (
564 <Box flexDirection="column" width={THUMB_COLUMNS} flexShrink={0}>
565 {/* The label is under it, so where the terminal draws no pixels the alt says the size. */}
566 {shot.thumb !== null && (
567 <Image
568 key={`band-${shot.id}`}
569 source={{ file: shot.thumb, format: 'png', generation: shot.at }}
570 columns={THUMB_COLUMNS}
571 rows={rowsFor(shot.width, shot.height, THUMB_COLUMNS, thumbRows)}
572 alt={shot.width !== null && shot.height !== null ? `${shot.width}×${shot.height}` : 'picture'}
573 />
574 )}
575 <Text dimColor wrap="truncate-end">
576 {ICON[shot.source]} {shot.label}
577 </Text>
578 </Box>
579 ))}
580 <Box flexDirection="column" flexShrink={0}>
581 {showing.length > fits && <Text dimColor>+{showing.length - fits} more</Text>}
582 <Button key="band-gallery" plain label="Gallery" onPress={() => void openGallery($)} />
583 <Button key="band-dismiss" plain dimColor label="Dismiss" onPress={() => void $.state.set(FRESH, [])} />
584 </Box>
585 </Box>
586 </Box>
587 )
588 }
589 const { Box, Text, Button } = $.ui.resolve(e)
590 const [first] = showing
591 return (
592 <Box flexDirection="column">
593 {below}
594 <Box flexDirection="row" flexWrap="wrap" columnGap={2} width={width}>
595 <Box flexShrink={1}>
596 <Text>
597 📸 {first === undefined ? '' : `${ICON[first.source]} ${first.label}${sizeText(first)}`}
598 {showing.length > 1 ? ` and ${showing.length - 1} more` : ''}
599 </Text>
600 </Box>
601 <Box flexShrink={0}>
602 <Button key="band-gallery" plain label="Gallery" onPress={() => void openGallery($)} />
603 </Box>
604 </Box>
605 </Box>
606 )
607 })
608
609 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
610 const all = await read($, shots)
611 const which = await read($, filter)
612 const pickedId = await read($, picked)
613 const list = all.filter(s => which === 'all' || (which === 'you' ? s.source === 'you' : s.source !== 'you'))
614 const current = list.find(s => s.id === pickedId) ?? list[0]
615 const { bodyColumns } = e.props
616 const bodyRows = e.props.scroll.bodyRows
617 const isBeside = bodyColumns >= SIDE_BY_SIDE
618 // Every row is counted: an inline pane may get far fewer than it asked for, and what does not
619 // fit is cut off. The header (with the filters) takes 2, the footer 2 where there is room.
620 const hasFooter = bodyRows >= 14
621 const room = Math.max(3, bodyRows - 2 - (hasFooter ? 2 : 0))
622 // Beside the picture: the details (3 rows and a gap), the list, and a "+N more" line if needed.
623 const listFits = (rows: number) => (list.length <= rows ? list.length : Math.max(1, rows - 1))
624 const listRows = isBeside ? listFits(room - 4) : listFits(Math.min(3, Math.max(1, room - 7)))
625 const box = fitPicture(
626 current?.width ?? null,
627 current?.height ?? null,
628 isBeside ? Math.min(PREVIEW_COLUMNS, Math.floor(bodyColumns * 0.45)) : Math.min(bodyColumns - 2, PREVIEW_COLUMNS),
629 isBeside ? room : room - 4 - listRows - (list.length > listRows ? 1 : 0),
630 )
631 const hasPicture = current?.thumb != null && e.surface === 'terminal' && box.rows >= 3
632 const tabs = (['all', 'you', 'claude'] as const).map(f => ({ f, label: f === 'all' ? 'All' : f === 'you' ? 'You' : 'Claude', hotkey: f[0] }))
633 const { Box, Text, Button } = $.ui.resolve(e)
634 const preview =
635 hasPicture && current?.thumb != null && e.surface === 'terminal'
636 ? (() => {
637 const { Image } = $.ui.resolve(e)
638 return (
639 <Box flexShrink={0} marginRight={isBeside ? 2 : 0}>
640 <Image
641 key="preview"
642 source={{ file: current.thumb, format: 'png', generation: current.at }}
643 columns={box.columns}
644 rows={box.rows}
645 alt="This terminal shows no pictures; o opens it"
646 />
647 </Box>
648 )
649 })()
650 : null
651 const details = current !== undefined && (
652 <Box flexDirection="column" marginBottom={1}>
653 <Text bold wrap="truncate-end">
654 {ICON[current.source]} {current.label}
655 {sizeText(current)}
656 </Text>
657 <Text dimColor wrap="truncate-end">
658 {SOURCE_WORD[current.source]} at {clockTime(current.at)} · {current.path}
659 </Text>
660 <Box flexDirection="row" flexWrap="wrap" columnGap={2}>
661 <Button key="act-open" hotkey="o" plain label="Open" autoFocus onPress={() => void openFile($, current.path)} />
662 <Button key="act-insert" hotkey="i" plain label="Insert @path" onPress={() => void insertPath($, current.path)} />
663 <Button key="act-copy" hotkey="p" plain label="Copy path" onPress={press => void copyPath($, current.path, press.surface)} />
664 <Button key="act-folder" hotkey="f" plain label="Show in folder" onPress={() => void showInFolder($, current.path)} />
665 </Box>
666 </Box>
667 )
668 const picks = list.slice(0, listRows).map(shot => (
669 <Button
670 key={`pick-${shot.id}`}
671 plain
672 dimColor={shot.id !== current?.id}
673 label={`${shot.id === current?.id ? '›' : ' '} ${clockTime(shot.at)} ${ICON[shot.source]} ${shot.label}${sizeText(shot)}`}
674 onPress={() => void $.state.set(PICKED, shot.id)}
675 />
676 ))
677 const more = list.length > picks.length ? <Text dimColor> +{list.length - picks.length} more</Text> : null
678 return (
679 <Box flexDirection="column">
680 <Box flexDirection="row" flexWrap="wrap" columnGap={3} marginBottom={1}>
681 <Box flexDirection="row">
682 <Text bold>📸 Show & Tell</Text>
683 <Text dimColor>
684 {' '}
685 · {all.length} image{all.length === 1 ? '' : 's'} this session
686 </Text>
687 </Box>
688 <Box flexDirection="row" columnGap={2}>
689 {tabs.map(t => (
690 <Button key={`tab-${t.f}`} hotkey={t.hotkey} plain dimColor={t.f !== which} label={t.label} onPress={() => void $.state.set(FILTER, t.f)} />
691 ))}
692 </Box>
693 </Box>
694 {current === undefined && <Text dimColor>Nothing yet. Paste an image with ctrl+v, or let Claude read or make one.</Text>}
695 {current !== undefined && isBeside && (
696 <Box flexDirection="row">
697 {preview}
698 <Box flexDirection="column" flexGrow={1} flexShrink={1}>
699 {details}
700 {picks}
701 {more}
702 </Box>
703 </Box>
704 )}
705 {current !== undefined && !isBeside && (
706 <Box flexDirection="column">
707 {preview}
708 {details}
709 {picks}
710 {more}
711 </Box>
712 )}
713 {hasFooter && (
714 <Box marginTop={1}>
715 <Text dimColor>Kept {KEEP_DAYS} days · tab walks the list · esc closes</Text>
716 </Box>
717 )}
718 </Box>
719 )
720 })
721}
722types/index.d.ts 35 lines1/** Who brought an image into the session: you pasted it, Claude looked at it, or Claude made it. */
2export type ShotSource = 'you' | 'claude-read' | 'claude-made'
3
4/** One image of the session, for the band and the gallery. */
5export type Shot = {
6 id: string
7 source: ShotSource
8 label: string
9 /** The file Open, Copy path and Insert use: the plugin's own copy, or the file Claude read or made. */
10 path: string
11 /** A PNG the terminal can draw, or null where none could be made (the gallery lists it as text). */
12 thumb: string | null
13 width: number | null
14 height: number | null
15 at: number
16 /** The `[Image #N]` a paste came in as. */
17 imageNo?: number
18 /** A paste that has gone out with a prompt. */
19 isSent?: boolean
20}
21
22declare module 'claude-code' {
23 interface PluginState {
24 'show-and-tell': {
25 /** Newest first. */
26 shots: Shot[]
27 /** Ids the band above the prompt shows. */
28 fresh: string[]
29 /** The gallery's selected shot. */
30 picked: string | null
31 filter: 'all' | 'you' | 'claude'
32 }
33 }
34}
35