Pasted images become chips you can click to open in the system viewer, in the transcript and above the prompt

把貼上的圖片變成可點擊的 chip. 點擊後用系統預設的圖片檢視器開啟原圖.
> [Image #1] 這張圖哪裡怪怪的?
⎿ [ Image #1 ]
| 位置 | 作用 |
|---|---|
| transcript | 帶圖片的 prompt 下方出現 [ Image #N ] chip |
| input 欄位 | 貼上後約 200ms, 正上方的 band 出現 Pasted [ Image #N ] chip; [Image #N] 文字在下一次按鍵後加上底線與顏色 |
| chip | 點擊後用系統預設程式開啟原圖. 開啟失敗時顯示 toast |
<temp>/<project>/<session>/images/<n>.<ext>. <temp> 是 temp 根目錄下的 claude (Windows) 或 claude-<uid> (macOS 和 Linux). temp 根目錄是 CLAUDE_CODE_TMPDIR, 沒有設定時是系統的 temp 資料夾. 這個檔案就是實際附加的圖片, 所以從檔案拖曳的圖片也正確.prompt.edit, 所以每 200ms 用 $.prompt.read() 讀一次輸入框. 只有互動模式的 terminal session 才會啟動這個 timer.session.append 的 image block. 編號取自 transcript 該列的 imagePasteIds, 所以手打的 [Image #N] 不會讓編號標錯. transcript 寫入之前, 先用文字中的標記暫時命名. 取得編號後, session state 改存快取檔案的路徑, 不再保存 base64. transcript 路徑取自 classic.UserPromptSubmit 和 classic.SessionStart.scripts/open_image.py 在 Windows 用檔案的預設程式開啟, 在 macOS 用 open, 在 Linux 用 xdg-open. 沒有快取檔案的圖片先寫到系統 temp 資料夾下的 claude-image-preview.scripts/paste_ids.py 從 transcript 檔尾往回讀取 imagePasteIds. 所有腳本都由 uv run --script 執行, 不需要額外套件.--resume 載入的舊訊息沒有 chip, 因為載入不會觸發 session.append.CLAUDE_CODE_ENABLE_FUNCTION_HOOKS=1claude --plugin-dir ./plugins/image-preview --debug # 存檔即 hot-reload
claude plugin validate ./plugins/image-preview
claude plugin test ./plugins/image-preview
uv run --script ./plugins/image-preview/scripts/paste_ids.py --path <transcript.jsonl> --uuid <row uuid>
uv run --script ./plugins/image-preview/scripts/open_image.py --path <image>
prompt.edit 在 2.1.291 的 test kit 中無法觸發, 所以 [Image #N] 的上色需要手動測試.
hooks/register.tsx 352 lines1/**
2 * image-preview: every pasted image becomes a chip that opens the picture.
3 *
4 * Chips sit under each prompt in the transcript that carried images, and in
5 * the band above the prompt for the `[Image #N]` placeholders in the draft.
6 * A click opens the whole picture in the system's own viewer.
7 *
8 * A draft's image is the file Claude Code cached for that paste,
9 * `<claude temp>/<project>/<session>/images/<n>.<ext>`. A sent prompt's images
10 * come whole from `session.append`, their paste numbers from the
11 * `imagePasteIds` its transcript line keeps; once those are known, the cached
12 * files stand in for the bytes.
13 *
14 * Everything that takes `$` is a top-level declaration: the loader inventories
15 * what a hooks module reaches for through `$`.
16 */
17import { atom, memberOf, read, update } from 'claude-code'
18import type { Args, EngineInterface, Register, RenderComponent, RenderElement, Timer } from 'claude-code'
19
20import type { ImageData, ImageRef, PictureSource } from '../types'
21import { imageNumbers, placeholders } from './placeholders'
22
23const ACCENT = 'suggestion'
24/** Pasting an image raises no `prompt.edit`, so the draft is read on a timer. */
25const POLL_MS = 200
26/** A sent prompt's transcript line is written a moment after its row: look again this often, this many times. */
27const RELABEL_MS = 500
28const RELABEL_TRIES = 10
29/** Claude Code's temp folder under a temp root: `claude` on Windows, `claude-<uid>` elsewhere. */
30const CLAUDE_TEMP = /^claude(-\d+)?$/
31/** A file of the paste cache: `<paste number>.<ext>`. */
32const PASTED_FILE = /^(\d+)\.[A-Za-z0-9]+$/
33/**
34 * The helpers declare their own dependencies, none of them; `--no-project`
35 * keeps them clear of the session's.
36 */
37const UV = ['uv', 'run', '--quiet', '--no-project', '--script']
38
39const MESSAGE_IMAGES = { plugin: 'image-preview', key: 'messageImages' } as const
40const IMAGE_SOURCE = { plugin: 'image-preview', key: 'imageSource' } as const
41const draftImages = atom({ plugin: 'image-preview', key: 'draftImages' } as const, [])
42
43/** The draft's image numbers as last written; unset after a reload, so the first read writes. */
44let draftNumbers: string | undefined
45let isReadingDraft = false
46/** The timer that reads the draft: one per module, whatever starts it again. */
47let draftPoll: Timer | undefined
48/** Where this session's paste cache and transcript are, found once per session id. */
49let pasteCache: { sessionId: string; dir: string } | undefined
50let transcript: { sessionId: string; path: string } | undefined
51
52/** A drawing that holds chips. */
53type Site = { surface: 'terminal'; component: RenderComponent }
54type ContentBlock = Args<'session.append'>['message']['content'][number]
55
56const draftId = (number: number) => `draft:${number}`
57const draftNumber = (imageId: string) => (imageId.startsWith('draft:') ? Number(imageId.slice(6)) : undefined)
58const helperPath = ($: EngineInterface, script: string) => `${$.plugin.root}/scripts/${script}`
59const firstLine = (text: string) => text.trim().split(/\r?\n/)[0] ?? ''
60
61/** An image block's bytes, when the block is one the engine holds inline. */
62function imageData(block: ContentBlock): ImageData[] {
63 const source = block.source as { type?: unknown; media_type?: unknown; data?: unknown } | undefined
64 if (block.type !== 'image' || source?.type !== 'base64' || typeof source.data !== 'string') return []
65 const mediaType = typeof source.media_type === 'string' ? source.media_type : 'image'
66 return [{ mediaType, base64: source.data }]
67}
68
69function textOf(block: ContentBlock): string {
70 return block.type === 'text' && typeof block.text === 'string' ? block.text : ''
71}
72
73// ── Claude Code's files ─────────────────────────────────────────────────────
74
75/**
76 * Where Claude Code's temp folder may be: `claude` on Windows, `claude-<uid>`
77 * on macOS and Linux, under `CLAUDE_CODE_TMPDIR` when it is set, else under
78 * the system's temp folder. Each is found by its name, since the session
79 * folder under it tells which one is this person's.
80 */
81async function claudeTemps($: EngineInterface): Promise<string[]> {
82 const custom = await $.env.get('CLAUDE_CODE_TMPDIR')
83 const system = [await $.env.get('TEMP'), await $.env.get('TMP'), await $.env.get('TMPDIR'), '/tmp']
84 const bases = (custom ? [custom] : system).flatMap((base) => (base ? [base.replace(/[\\/]+$/, '')] : []))
85
86 const temps: string[] = []
87 for (const base of new Set(bases)) {
88 for (const entry of await $.fs.list(base).catch(() => [])) {
89 if (entry.kind === 'dir' && CLAUDE_TEMP.test(entry.name)) temps.push(`${base}/${entry.name}`)
90 }
91 }
92 return temps
93}
94
95/**
96 * `tail` under the one project folder of `root` that holds it. A project
97 * folder is named after a working directory that may have moved since, so
98 * this session's is found by what it holds instead of rebuilt.
99 */
100async function underProject($: EngineInterface, root: string, tail: string): Promise<string | undefined> {
101 for (const entry of await $.fs.list(root).catch(() => [])) {
102 const path = `${root}/${entry.name}/${tail}`
103 if (entry.kind === 'dir' && (await $.fs.exists(path))) return path
104 }
105 return undefined
106}
107
108async function pasteCacheDir($: EngineInterface): Promise<string | undefined> {
109 const sessionId = await $.session.id()
110 if (pasteCache?.sessionId === sessionId) return pasteCache.dir
111 for (const root of await claudeTemps($)) {
112 const dir = await underProject($, root, `${sessionId}/images`)
113 if (dir !== undefined) {
114 pasteCache = { sessionId, dir }
115 return dir
116 }
117 }
118 return undefined
119}
120
121/** The files Claude Code cached for this session's pastes, by paste number, whatever their extension. */
122async function pastedFiles($: EngineInterface): Promise<Map<number, string>> {
123 const files = new Map<number, string>()
124 const dir = await pasteCacheDir($)
125 if (dir === undefined) return files
126 for (const entry of await $.fs.list(dir).catch(() => [])) {
127 const paste = entry.kind === 'file' ? PASTED_FILE.exec(entry.name) : null
128 if (paste) files.set(Number(paste[1]), `${dir}/${entry.name}`)
129 }
130 return files
131}
132
133/** The transcript a classic event names: each prompt, and each session that starts. */
134function noteTranscript(e: { session_id: string; transcript_path: string }): void {
135 if (e.transcript_path) transcript = { sessionId: e.session_id, path: e.transcript_path }
136}
137
138/**
139 * The session's transcript, as a classic event named it; after a reload,
140 * until the next prompt names it, found by its name under the config folder.
141 */
142async function transcriptPath($: EngineInterface): Promise<string | undefined> {
143 const sessionId = await $.session.id()
144 if (transcript?.sessionId === sessionId) return transcript.path
145 const home = (await $.env.get('USERPROFILE')) ?? (await $.env.get('HOME'))
146 const config = (await $.env.get('CLAUDE_CONFIG_DIR')) ?? (home ? `${home}/.claude` : undefined)
147 const path = config === undefined ? undefined : await underProject($, `${config}/projects`, `${sessionId}.jsonl`)
148 if (path !== undefined) transcript = { sessionId, path }
149 return path
150}
151
152/** Where an image's bytes are: the paste cache for a draft's, state for a sent one's. */
153async function sourceOf($: EngineInterface, imageId: string): Promise<PictureSource> {
154 const number = draftNumber(imageId)
155 if (number !== undefined) {
156 const path = (await pastedFiles($)).get(number)
157 if (path === undefined) throw new Error(`Claude Code holds no pasted image #${number} in this session.`)
158 return { path }
159 }
160 const { value: source } = await $.state.get({ ...IMAGE_SOURCE, id: imageId })
161 if (!source) throw new Error('This image is no longer held.')
162 return source
163}
164
165// ── Sent prompts ────────────────────────────────────────────────────────────
166
167async function rememberImages($: EngineInterface, uuid: string, content: readonly ContentBlock[]): Promise<void> {
168 const pictures = content.flatMap(imageData)
169 if (pictures.length === 0) return
170
171 // Until the transcript line says which pastes these are, the tags in the
172 // text name them when they match the images one to one.
173 const numbers = imageNumbers(content.map(textOf).join('\n'))
174 const images = pictures.map((_, index) => ({
175 id: `${uuid}:${index}`,
176 label: numbers.length === pictures.length ? `Image #${numbers[index]}` : `Image ${index + 1}`,
177 }))
178
179 // Held until the transcript line names the pastes; `keepPastes` lets them go.
180 for (const [index, image] of images.entries()) {
181 const picture = pictures[index]
182 if (picture) await $.state.set({ ...IMAGE_SOURCE, id: image.id }, picture)
183 }
184 await $.state.set({ ...MESSAGE_IMAGES, id: uuid }, images)
185 $.clock.after(RELABEL_MS, () => void relabel($, uuid, RELABEL_TRIES))
186}
187
188/** The paste numbers row `uuid`'s transcript line keeps; null until the line is written. */
189async function pasteIds($: EngineInterface, uuid: string): Promise<number[] | null> {
190 const path = await transcriptPath($)
191 if (path === undefined) return null
192 const argv = [...UV, helperPath($, 'paste_ids.py'), '--path', path, '--uuid', uuid]
193 const result = await $.process.run(argv, { timeoutMs: 30_000 })
194 if (result.exitCode === 4) return []
195 if (result.exitCode !== 0) return null
196 return result.stdout.trim().split(',').filter(Boolean).map(Number)
197}
198
199/**
200 * Names each image by the paste it came from: `imagePasteIds` keeps one
201 * number per image block, in order. A typed `[Image #1]` reads the same as a
202 * pasted one, so the tags in the text alone can misname them.
203 */
204async function relabel($: EngineInterface, uuid: string, tries: number): Promise<void> {
205 try {
206 const ids = await pasteIds($, uuid)
207 if (ids === null) {
208 if (tries > 1) $.clock.after(RELABEL_MS, () => void relabel($, uuid, tries - 1))
209 return
210 }
211 const { value: images } = await $.state.get({ ...MESSAGE_IMAGES, id: uuid })
212 if (!images || ids.length !== images.length) return
213 const labeled = images.map((image, index) => ({ ...image, label: `Image #${ids[index]}` }))
214 await $.state.set({ ...MESSAGE_IMAGES, id: uuid }, labeled)
215 await keepPastes($, images, ids)
216 } catch (error) {
217 $.ui.log(`image-preview: reading paste numbers failed: ${String(error)}`, { to: 'debug' })
218 }
219}
220
221/**
222 * Swaps each image's bytes for the file Claude Code cached for its paste: the
223 * session then holds a path, not megabytes. Bytes with no file stay.
224 */
225async function keepPastes($: EngineInterface, images: ImageRef[], ids: number[]): Promise<void> {
226 const files = await pastedFiles($)
227 for (const [index, image] of images.entries()) {
228 const path = files.get(ids[index] ?? -1)
229 if (path !== undefined) await $.state.set({ ...IMAGE_SOURCE, id: image.id }, { path })
230 }
231}
232
233// ── The draft ───────────────────────────────────────────────────────────────
234
235async function syncDraft($: EngineInterface, text: string): Promise<void> {
236 const numbers = imageNumbers(text)
237 const key = numbers.join(',')
238 if (key === draftNumbers) return
239
240 await update($, draftImages, () => numbers.map((number) => ({ id: draftId(number), label: `Image #${number}` })))
241 // Kept once the write landed: after a failed one the next tick writes again.
242 draftNumbers = key
243}
244
245async function readDraft($: EngineInterface): Promise<void> {
246 if (isReadingDraft) return
247 isReadingDraft = true
248 try {
249 await syncDraft($, (await $.prompt.read()).text)
250 } catch {
251 // The next tick reads it again.
252 } finally {
253 isReadingDraft = false
254 }
255}
256
257// ── Presses ─────────────────────────────────────────────────────────────────
258
259/** Opens the whole picture in the system's own viewer. */
260async function openImage($: EngineInterface, image: ImageRef): Promise<void> {
261 try {
262 const source = await sourceOf($, image.id)
263 const argv = [...UV, helperPath($, 'open_image.py')]
264 const result =
265 'path' in source
266 ? await $.process.run([...argv, '--path', source.path], { timeoutMs: 30_000 })
267 : await $.process.run([...argv, '--media-type', source.mediaType], { stdin: source.base64, timeoutMs: 30_000 })
268 if (result.exitCode !== 0) $.ui.toast(`Cannot open ${image.label}: ${firstLine(result.stderr)}`)
269 } catch (error) {
270 $.ui.toast(`Cannot open ${image.label}: ${error instanceof Error ? error.message : String(error)}`)
271 }
272}
273
274// ── Drawing ─────────────────────────────────────────────────────────────────
275
276function chipStrip($: EngineInterface, site: Site, images: ImageRef[], lead: string): RenderElement {
277 const { Box, Text, Button } = $.ui.resolve(site)
278 return (
279 <Box flexDirection="row" gap={1}>
280 <Text dimColor>{lead}</Text>
281 {images.map((image) => (
282 <Button key={`chip:${image.id}`} label={image.label} onPress={() => openImage($, image)} />
283 ))}
284 </Box>
285 )
286}
287
288export const register: Register = (on) => {
289 on('session.start', async ($, e, next) => {
290 // A draft is a person's at the terminal prompt, and the band is drawn there alone.
291 if (e.isInteractive && e.surface === 'terminal') draftPoll ??= $.clock.every(POLL_MS, () => void readDraft($))
292 return next(e)
293 })
294
295 // `/clear`, `/resume` and a fork switch sessions without another `session.start`.
296 on('classic.SessionStart', async ($, e, next) => {
297 // Unset, so the next tick writes the chips for the new session.
298 draftNumbers = undefined
299 noteTranscript(e)
300 return next(e)
301 }).catch(($, e, next) => next(e))
302
303 // Raised before the prompt's row is appended, so its relabel knows the transcript.
304 on('classic.UserPromptSubmit', async ($, e, next) => {
305 noteTranscript(e)
306 return next(e)
307 }).catch(($, e, next) => next(e))
308
309 // Kept by the row's uuid before the row is stored, as the event allows; a
310 // failure here never keeps the row from being stored.
311 on('session.append', { door: 'prompt' }, async ($, e, next) => {
312 if (e.agentId === undefined) await rememberImages($, e.uuid, e.message.content)
313 return next(e)
314 }).catch(($, e, next) => next(e))
315
316 // Paint only: the draft's chips come from the timer, since a paste raises no edit.
317 on('prompt.edit', async ($, e, next) => {
318 const box = await next(e)
319 const marks = placeholders(box.text).map(({ start, end }) => ({ start, end, color: ACCENT, underline: true }))
320 if (marks.length === 0) return box
321 return { ...box, decorations: [...(box.decorations ?? []), ...marks] }
322 }).catch(($, e, next) => next(e))
323
324 on('ui.render', { component: 'UserMessage', surface: 'terminal' }, async ($, e, next) => {
325 const images = await read($, memberOf(MESSAGE_IMAGES, e))
326 if (!images?.length) return next(e)
327
328 const { Box } = $.ui.resolve(e)
329 const drawn = await next(e)
330 return (
331 <Box flexDirection="column">
332 {drawn}
333 <Box marginLeft={2}>{chipStrip($, e, images, '⎿')}</Box>
334 </Box>
335 )
336 })
337
338 on('ui.render', { component: 'AbovePrompt', surface: 'terminal' }, async ($, e, next) => {
339 const images = await read($, draftImages)
340 if (e.props.hasSurvey || images.length === 0) return next(e)
341
342 const { Box } = $.ui.resolve(e)
343 const below = await next(e)
344 return (
345 <Box flexDirection="column">
346 {below}
347 {chipStrip($, e, images, 'Pasted')}
348 </Box>
349 )
350 })
351}
352hooks/placeholders.ts 19 lines1/** Where Claude Code wrote `[Image #N]` for a pasted image. */
2export type Placeholder = { number: number; start: number; end: number }
3
4const PLACEHOLDER = /\[Image #(\d+)\]/g
5
6/** Every `[Image #N]` in the text, in order, repeats included. */
7export function placeholders(text: string): Placeholder[] {
8 return [...text.matchAll(PLACEHOLDER)].map((match) => ({
9 number: Number(match[1]),
10 start: match.index,
11 end: match.index + match[0].length,
12 }))
13}
14
15/** The image numbers the text names, each once, in order. */
16export function imageNumbers(text: string): number[] {
17 return [...new Set(placeholders(text).map((found) => found.number))]
18}
19types/index.d.ts 33 lines1/** One image a chip stands for. */
2export type ImageRef = {
3 /** `<message uuid>:<index>` for a sent image, `draft:<n>` for paste `n` in the draft. */
4 id: string
5 /** What the chip reads: `Image #1`. */
6 label: string
7}
8
9/** A sent image's bytes, as the transcript row carried them. */
10export type ImageData = {
11 mediaType: string
12 base64: string
13}
14
15/**
16 * Where the viewer reads an image: a file Claude Code cached for a paste,
17 * or bytes the transcript row carried, kept only while no file is known.
18 */
19export type PictureSource = { path: string } | ImageData
20
21declare module 'claude-code' {
22 interface PluginState {
23 'image-preview': {
24 /** The images a transcript message carried, by the message's uuid. */
25 messageImages: StateFamily<ImageRef[]>
26 /** The `[Image #N]` placeholders in the prompt draft, in order. */
27 draftImages: ImageRef[]
28 /** Where each sent image is read from, by its id. */
29 imageSource: StateFamily<PictureSource>
30 }
31 }
32}
33