Browse the images you paste into the prompt: chips above the prompt and a master/detail browser window that previews them and opens them in your OS viewer

A Claude Code mod for previewing images you paste or drop into the prompt.
You paste or drop an image into the prompt, don't submit, and step away. When you come back, the prompt only shows [Image #1], and you can't tell which image that was. Claude Code has no way to preview it from the prompt. This was raised in anthropics/claude-code#68986, which was closed.
This mod fills the gap: the 🖼 Image #N chips above the prompt open the pending image in a browser window, where you can also open it in your OS viewer. It works for images pasted from the clipboard as well as dropped files, before you submit. Type a space after the [Image #N] tag that Claude Code inserts, so the chip appears.

🖼 Image #N chip for each [Image #N] in your draft. Clicking a chip opens the image browser on that image (and, if the window can't start, the image in the OS viewer). If the browser window is already open, it switches to that image instead of opening a second window./image-preview): a window with a master/detail layout. The left table lists this session's images (number, name, size, source) with a filter box. The right side previews the selected image in the browser itself, with Fit and 100% zoom, and shows its path, dimensions, size and date. Buttons open the image in the OS viewer (Preview on macOS), show it in the file manager (Finder on macOS), and copy its path. Arrow keys move through the table, Enter opens the OS viewer, and double-clicking a row does too. The theme follows your system (Light and Dark are selectable) and the list refreshes as you add images./image-preview opens the browser. /image-preview 2 opens image 2 in the OS viewer directly. /image-preview pane opens the older terminal pane (a plain list with buttons), which also works where the window can't run.The mod watches your draft for [Image #N] tags. For a dropped file it remembers the original path. Otherwise it finds the copy Claude Code saved at <tmp>/claude-<uid>/<project>/<session>/images/N.<ext>. The chips and the browser use whichever is available, and show a notice if neither is.
/image-preview starts a small local web server (server/server.mjs, no dependencies) and opens its page in a Chrome app window with its own profile, the same approach as gui-editors:
Claude Code session
└─ mod (hooks/register.tsx, hooks/gui.ts)
├─ $.process.spawn ──► node server/server.mjs (lives and dies with the mod)
├─ $.http.fetch ──► POST /open-window, /sync, /ping
└─ /image-preview command
├─ serves the page on 127.0.0.1:<random port>
├─ lists the session's images and streams them to the page
└─ opens or reveals files with the OS (`open`, `xdg-open`, `explorer`)
The server exits about a minute after the mod stops sending its heartbeat. If it can't start, /image-preview falls back to the terminal pane.
Safety. Everything binds to 127.0.0.1. A request whose Host isn't 127.0.0.1:<port> is refused (DNS rebinding), and every API call needs a per-run token that only the served page and the mod know. The server only serves files that are on its own list (this session's saved images and the dropped files the mod reported), never a path from the page, and runs commands as argv arrays, never through a shell.
Try it from a checkout:
claude --plugin-dir /path/to/image-preview
Or install it from GitHub, inside Claude Code:
/plugin marketplace add sandipchitale/claude-code-image-preview
/plugin install image-preview@image-preview
Then run /reload-plugins (or restart). Choose user scope to use it in every project.
$.process isn't available in the desktop app or IDE extensions), Node 18+, and Chrome. Without Chrome it opens your default browser instead. Elsewhere, use /image-preview pane.[Image #N] tag.| OS | Open | Reveal |
|---|---|---|
| macOS | open | open -R (selects the file) |
| Linux | xdg-open | xdg-open on the folder (the file is not selected) |
| Windows | cmd /c start | explorer /select, |
/private/tmp and /tmp (and the pane uses find over them), so the saved-image lookup is untested outside macOS.[Image #N] widget, so the chips above the prompt stand in for it.Button's colors on hover or focus, and the mod can't turn that off.MIT
hooks/register.tsx 280 lines1import { atom, read, update } from 'claude-code'
2import type { Register } from 'claude-code'
3
4import type { PreviewFile } from '../types'
5import { openFile, revealFile } from './os'
6import { isUp, openGui, sync } from './gui'
7import { droppedImagePath, tokens } from './paths'
8
9const draft = atom({ plugin: 'image-preview', key: 'draft' } as const, '')
10const files = atom({ plugin: 'image-preview', key: 'files' } as const, {} as Record<string, PreviewFile>)
11const origins = atom({ plugin: 'image-preview', key: 'origins' } as const, {} as Record<string, string>)
12// Images the user cleared from the pane, so a rescan doesn't bring them back.
13const cleared = atom({ plugin: 'image-preview', key: 'cleared' } as const, {} as Record<string, boolean>)
14
15// Dropped or pasted file paths not yet matched to an [Image #N] chip.
16let pending: string[] = []
17
18// Icon labels of one width, so the buttons match.
19const PAD = (icon: string) => ` ${icon} `
20
21async function scan($: any) {
22 const sid = await $.session.id()
23 const r = await $.process.run(['find', '/private/tmp', '/tmp', '-maxdepth', '5', '-path', `*/${sid}/images/*`])
24 const gone = await read($, cleared)
25 const found: Record<string, PreviewFile> = {}
26 for (const line of r.stdout.split('\n')) {
27 const m = /\/images\/(\d+)\.[A-Za-z]+$/.exec(line.trim())
28 if (m && !gone[m[1]]) found[m[1]] = { path: line.trim() }
29 }
30 await update($, files, cur => ({ ...cur, ...found }))
31}
32
33async function locate($: any, n: number) {
34 const sid = await $.session.id()
35 const r = await $.process.run(['find', '/private/tmp', '/tmp', '-maxdepth', '5', '-path', `*/${sid}/images/${n}.*`])
36 const path = r.stdout.split('\n').find((l: string) => l.trim())
37 if (path) {
38 await update($, files, m => ({ ...m, [n]: { path } }))
39 }
40}
41
42const PANE = 'image-preview'
43
44async function clearAll($: any) {
45 const ids = Object.keys(await read($, files))
46 await update($, cleared, m => ({ ...m, ...Object.fromEntries(ids.map(id => [id, true])) }))
47 await update($, files, () => ({}))
48}
49
50// A chip opens the browser window on that image, or the OS viewer if the window can't start.
51async function showInWindow($: any, n: number) {
52 const payload = { session: await $.session.id(), origins: await read($, origins), select: n }
53 const state = await openGui($, payload, () => {
54 void $.ui.toast(`The image window can't start. Opening Image #${n} in your OS viewer.`)
55 void show($, n)
56 })
57 const where = 'the "Images in this session" window'
58 if (state === 'starting') await $.ui.toast(`Starting ${where}. Image #${n} will show there.`)
59 else if (state === 'opened') await $.ui.toast(`Image #${n} is shown in ${where}.`)
60 else if (state === 'reused') await $.ui.toast(`Image #${n} is shown in the open ${where}. It may be behind other windows.`)
61 else {
62 await $.ui.toast(`The image window didn't answer. Opening Image #${n} in your OS viewer.`)
63 await show($, n)
64 }
65}
66
67async function show($: any, n: number) {
68 const run = (argv: string[]) => $.process.run(argv)
69 const origin = (await read($, origins))[n]
70 // The dropped file may have been moved since, so the saved copy is the fallback.
71 if (origin && (await openFile(run, origin))) return true
72 let have = (await read($, files))[n]
73 if (!have) {
74 await locate($, n)
75 have = (await read($, files))[n]
76 }
77 if (have && (await openFile(run, have.path))) return true
78 await $.ui.toast(`Image #${n} isn't saved yet or can't be found`)
79 return false
80}
81
82export const register: Register = on => {
83 on('session.start', async ($, e, next) => {
84 await $.command.register({
85 name: 'image-preview',
86 description: 'Browse this session\'s images in a window: /image-preview [n | pane]',
87 })
88 return next(e)
89 })
90
91 on('command.run', { command: 'image-preview' }, async ($, e: any) => {
92 const arg = String(e.args ?? '').trim()
93 const openPane = async () => {
94 await scan($)
95 await $.ui.open({ id: PANE, title: 'Images', focus: true })
96 }
97 if (arg === 'pane') {
98 await openPane()
99 return { text: 'Images pane opened.' }
100 }
101 const n = Number(arg)
102 if (n) {
103 const ok = await show($, n)
104 return { text: ok ? `Opened Image #${n}.` : `Image #${n} not found.` }
105 }
106 // The window needs the session's own folder, and the paths of dropped files the mod has seen.
107 const payload = { session: await $.session.id(), origins: await read($, origins) }
108 const state = await openGui($, payload, () => void openPane())
109 return {
110 text:
111 state === 'starting'
112 ? 'image-preview: starting the window… (if it cannot start, the Images pane opens instead)'
113 : state === 'opened'
114 ? 'image-preview: window opened.'
115 : 'image-preview: the window server did not answer. Try /image-preview pane.',
116 }
117 })
118
119 on('prompt.edit', async ($, e, next) => {
120 const result: any = await next(e)
121 const after: string =
122 result?.text ?? e.text.slice(0, e.start) + e.inputText + e.text.slice(e.end)
123 await update($, draft, () => after)
124 if (after.trim() === '') pending = []
125 const dropped = droppedImagePath(e.inputText)
126 if (dropped) pending.push(dropped)
127 const before = new Set(tokens(e.text))
128 for (const n of tokens(after)) {
129 if (before.has(n)) continue
130 const origin = pending.shift()
131 if (origin) {
132 await update($, origins, m => ({ ...m, [n]: origin }))
133 if (isUp()) sync($, { session: await $.session.id(), origins: await read($, origins) })
134 }
135 }
136 return result
137 })
138
139 on('prompt.submit', async ($, e, next) => {
140 await update($, draft, () => '')
141 pending = []
142 const sent = await next(e)
143 await scan($).catch(() => {})
144 return sent
145 })
146
147 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
148 const { Box, Button } = $.ui.resolve(e)
149 // Other plugins' rows (and the engine's) stay, below this one.
150 const [text, beneath] = await Promise.all([read($, draft), next(e)])
151 const ns = [...new Set(tokens(text))]
152 if (ns.length === 0) return beneath
153 return (
154 <Box flexDirection="column">
155 <Box flexDirection="row" gap={1}>
156 {ns.map(n => (
157 <Button
158 key={`img-${n}`}
159 plain
160 onPress={() => showInWindow($, n)}
161 >
162 {`🖼 Image #${n}`}
163 </Button>
164 ))}
165 </Box>
166 {beneath}
167 </Box>
168 )
169 })
170
171 on('ui.render', { component: 'Pane', requestId: PANE }, async ($, e) => {
172 const { Box, Text, Button } = $.ui.resolve(e)
173 const known = await read($, files)
174 const origin = await read($, origins)
175 const shown = (n: number) => origin[n] ?? known[n].path
176 const ids = Object.keys(known).map(Number).sort((a, b) => a - b)
177 // Tooltips are the last children of the root, so nothing paints over them:
178 // an absolute Box paints over siblings before it only. Each joins its
179 // button's hover scope, and sits at a position the fixed layout gives.
180 const ROW0 = 4
181 const ROWH = 3
182 const COLS = [2, 14, 26]
183 const tip = (key: string, top: number, left: number, text: string) => (
184 <Box
185 key={`card-${key}`}
186 position="absolute"
187 top={top}
188 left={left}
189 display="none"
190 hover={{ display: 'flex', scope: key }}
191 borderStyle="round"
192 backgroundColor="inverseText"
193 paddingX={1}
194 >
195 <Text color="text">{text}</Text>
196 </Box>
197 )
198 return (
199 <Box flexDirection="column" paddingX={1} paddingBottom={4}>
200 <Box
201 key="clear-box"
202 hover={{ scope: 'tip-clear' }}
203 alignSelf="flex-start"
204 >
205 <Button key="clear" onPress={() => clearAll($)}>
206 {PAD('🧹')}
207 </Button>
208 </Box>
209 <Text> </Text>
210 <Text bold>Images in this session</Text>
211 <Text> </Text>
212 {ids.length === 0 && <Text dimColor>No images yet.</Text>}
213 {ids.map(n => (
214 <Box
215 key={`row-${n}`}
216 flexDirection="row"
217 alignItems="center"
218 gap={2}
219 paddingX={1}
220 paddingY={1}
221 hover={{ backgroundColor: 'subtle' }}
222 >
223 <Box
224 key={`reveal-box-${n}`}
225 hover={{ scope: `tip-reveal-${n}` }}
226 >
227 <Button
228 key={`reveal-${n}`}
229 onPress={() => revealFile((argv: string[]) => $.process.run(argv), shown(n))}
230 >
231 {PAD('📂')}
232 </Button>
233 </Box>
234 <Box
235 key={`copy-box-${n}`}
236 hover={{ scope: `tip-copy-${n}` }}
237 >
238 <Button
239 key={`copy-${n}`}
240 onPress={(press: any) =>
241 $.ui.copy({ text: shown(n), surface: press.surface })
242 }
243 >
244 {PAD('📋')}
245 </Button>
246 </Box>
247 <Box
248 key={`view-box-${n}`}
249 hover={{ scope: `tip-view-${n}` }}
250 >
251 <Button key={`view-${n}`} onPress={() => show($, n)}>
252 {PAD('👀')}
253 </Button>
254 </Box>
255 <Button key={`open-${n}`} plain onPress={() => show($, n)}>
256 {`[Image #${n}]`}
257 </Button>
258 </Box>
259 ))}
260 {tip('tip-clear', 1, 1, 'Clear list')}
261 {ids.map((n, i) => {
262 const rowTop = ROW0 + i * ROWH
263 // Below the row, unless the card would run past the bottom edge of the
264 // window as scrolled: then above the button (the card is 3 rows tall,
265 // the button on the row's middle line).
266 const offset = e.props?.scroll?.offset ?? 0
267 const room = e.props?.scroll?.bodyRows ?? e.viewport?.rows ?? 24
268 const below =
269 rowTop + ROWH + 3 - offset > room ? rowTop - 2 : rowTop + ROWH
270 return [
271 tip(`tip-reveal-${n}`, below, COLS[0], 'Show in Finder'),
272 tip(`tip-copy-${n}`, below, COLS[1], 'Copy path'),
273 tip(`tip-view-${n}`, below, COLS[2], 'View in OS preview'),
274 ]
275 })}
276 </Box>
277 )
278 })
279}
280hooks/os.ts 34 lines1// Opening and revealing a file differs per OS and the mod can't read the OS,
2// so each command is tried in turn and the first that works is used.
3type Run = (argv: string[]) => Promise<{ exitCode: number }>
4
5const dirname = (p: string) => p.replace(/[\\/][^\\/]*$/, '') || '/'
6
7async function firstOk(run: Run, attempts: { argv: string[]; trustExit?: boolean }[]) {
8 for (const a of attempts) {
9 try {
10 const r = await run(a.argv)
11 if (r.exitCode === 0 || a.trustExit) return true
12 } catch {
13 // command not installed: try the next one
14 }
15 }
16 return false
17}
18
19export const openArgv = (p: string) => [
20 { argv: ['open', p] },
21 { argv: ['xdg-open', p] },
22 { argv: ['cmd', '/c', 'start', '', p] },
23]
24
25// explorer.exe exits 1 even when it worked, so its attempt is trusted.
26export const revealArgv = (p: string) => [
27 { argv: ['open', '-R', p] },
28 { argv: ['explorer', `/select,${p}`], trustExit: true },
29 { argv: ['xdg-open', dirname(p)] },
30]
31
32export const openFile = (run: Run, p: string) => firstOk(run, openArgv(p))
33export const revealFile = (run: Run, p: string) => firstOk(run, revealArgv(p))
34hooks/gui.ts 80 lines1// The browser window: a small local server (server/server.mjs) lives as long as this module, a Chrome
2// app window shows its page, and a heartbeat keeps it up. Without the server the mod uses its pane.
3const HEARTBEAT_MS = 15_000
4
5let port: number | undefined
6let token = ''
7let isStarting = false
8let hasHeartbeat = false
9
10export type Payload = { session: string; origins: Record<string, string>; select?: number }
11
12export const isUp = () => port !== undefined
13
14async function post($: any, path: string, body: unknown = {}) {
15 if (port === undefined) return undefined
16 try {
17 return await $.http.fetch(`http://127.0.0.1:${port}${path}`, {
18 method: 'POST',
19 headers: { 'x-preview-token': token, 'content-type': 'application/json' },
20 body: JSON.stringify(body),
21 })
22 } catch {
23 return undefined
24 }
25}
26
27// The child lives as long as this loop: it ends with the module or the server.
28function startServer($: any, onReady: () => void, onFail: () => void) {
29 if (isStarting || port !== undefined) return
30 isStarting = true
31 void (async () => {
32 let buffer = ''
33 try {
34 const child = $.process.spawn({ argv: ['node', `${$.plugin.root}/server/server.mjs`] })
35 for await (const piece of child) {
36 if (!('stream' in piece) || piece.stream !== 'stdout' || port !== undefined) continue
37 buffer += piece.text
38 const newline = buffer.indexOf('\n')
39 if (newline < 0) continue
40 const hello = JSON.parse(buffer.slice(0, newline))
41 token = hello.token
42 port = hello.port
43 if (!hasHeartbeat) {
44 hasHeartbeat = true
45 $.clock.every(HEARTBEAT_MS, () => void post($, '/ping'))
46 }
47 onReady()
48 }
49 } catch (error) {
50 $.ui.log(`image-preview: server failed: ${String(error)}`, { to: 'debug' })
51 } finally {
52 const failed = port === undefined
53 port = undefined
54 token = ''
55 isStarting = false
56 if (failed) onFail()
57 }
58 })()
59}
60
61// Opens the window, starting the server first if it is not running. `onFail` runs when it cannot start.
62export async function openGui($: any, payload: Payload, onFail: () => void) {
63 if (port === undefined) {
64 startServer($, () => void post($, '/open-window', payload), onFail)
65 return 'starting'
66 }
67 const res = await post($, '/open-window', payload)
68 if (!res?.ok) return 'unanswered'
69 let reused = false
70 try {
71 reused = JSON.parse(res.text).reused === true
72 } catch {}
73 return reused ? 'reused' : 'opened'
74}
75
76// Tell a running server about a newly learned dropped-file path. Fire and forget.
77export function sync($: any, payload: Payload) {
78 if (port !== undefined) void post($, '/sync', payload)
79}
80hooks/paths.ts 21 lines1export const tokens = (text: string) =>
2 [...text.matchAll(/\[Image #?(\d+)\]/g)].map(m => Number(m[1]))
3
4const IMAGE_EXT = /\.(png|jpe?g|gif|webp|heic|tiff?|bmp)$/i
5
6// The absolute path of a dropped or pasted image file (plain, quoted, escaped
7// or file://), or null for anything else, including a URL that won't decode.
8export function droppedImagePath(input: string): string | null {
9 let raw = input.trim().replace(/^(['"])(.*)\1$/, '$2')
10 if (raw.startsWith('file://')) {
11 try {
12 raw = decodeURIComponent(raw.slice('file://'.length))
13 } catch {
14 return null
15 }
16 } else {
17 raw = raw.replace(/\\(.)/g, '$1')
18 }
19 return raw.startsWith('/') && raw.length > 1 && IMAGE_EXT.test(raw) ? raw : null
20}
21types/index.d.ts 13 lines1export type PreviewFile = { path: string }
2
3declare module 'claude-code' {
4 interface PluginState {
5 'image-preview': {
6 draft: string
7 files: Record<string, PreviewFile>
8 origins: Record<string, string>
9 cleared: Record<string, boolean>
10 }
11 }
12}
13