SLOPSHOPPER

media-view

Show images and GIFs inline in Claude Code — in the prompt, the transcript and a gallery — and let Claude see them too.

panebandrowsguardcommandprompt
v0.0.0MITupdated 2026-10-20retogo/claude-media-view
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · media-view
│ ┃ Media ✕ › fix the failing auth test and add an audit log call │ ┃ │ ┃ No images in this session yet. ⏺ Read(src/auth.ts) │ ⎿ Read 6 lines │ ⏺ Update(src/auth.ts) │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /media-view │ ⎿ media-view: Opened the media gallery. │ │ ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Pane · Media
No images in this session yet.
Pane · Media settings
What media-view draws, kept for every session: Show media [ [x] Above the prompt ] [ [x] Under prompts you sent ] [ [x] Under Claude’s tool calls ] [ [x] Under Claude’s replies ] GIFs [ [x] Animate GIFs ] Formats [ [x] Convert WebP, HEIC, TIFF and SVG through the OS ] [ [x] Convert with ffmpeg instead, where installed ]
README

claude-media-view

A Claude Code mod that shows images and GIFs inline in the terminal — and lets Claude see them too.

What it does

  • Composer preview: pictures of pasted images above the prompt while you write, labelled #n like their [Image #n] tags.
  • Transcript inline: pictures under the rows that carry them — images Claude reads, images MCP tools answer with (such as a browser's screenshots), image files Claude names in its replies, and images you send. GIFs play, and pause while scrolled out of view.
  • Gallery: /media-view opens a pane with every image the chat shows, newest first, and when it showed, with buttons to copy its path or open it. Turning a place off in the settings takes its images out of the chat and the gallery alike, also for the images already shown.
  • PNG, GIF and JPEG on macOS, Linux and Windows with built-in decoders: nothing to install, no ffmpeg.
  • WebP, HEIC and TIFF on macOS and Windows under tool calls and replies, converted by the OS's own codecs; animated WebPs play on macOS. Where ffmpeg is installed it converts instead, on Linux too, and animated WebPs play everywhere. SVG files named in replies are drawn on macOS. The decoders are native code, so a setting turns conversion off.

No network access, no telemetry, no self-update.

Install

At the prompt of a Claude Code session:

/plugin install media-view --marketplace retogo/claude-media-view

Answer y to add the marketplace, then pick a scope. From a shell:

claude plugin install media-view --marketplace retogo/claude-media-view

Use

CommandDoes
/media-viewOpens the gallery, with the settings as a tab beside it
/media-view settingsShows the settings tab: each place images show, on or off, GIF animation, and conversion by the OS or ffmpeg
/media-view stillShows transcript GIFs as still pictures
/media-view animatePlays transcript GIFs again (the default)

Every setting is on by default; the settings are kept for later sessions. An image file named in a reply is drawn only where the Read tool may read it without asking.

Requirements

  • Claude Code 2.1.301 or later
  • A terminal with the kitty graphics protocol and Unicode placeholders: Ghostty or kitty. Elsewhere, media-view logs once why no picture is shown and how to fix it.
  • In background sessions, tmux or agent view: add "CLAUDE_CODE_FORCE_TERMINAL_IMAGES": "1" to the env block of ~/.claude/settings.json.

Development

claude --plugin-dir .          # run a session with the mod loaded
claude plugin validate .       # check the manifests and the hooks module
claude plugin test .           # run the tests

The decisions behind the design, and what is not built yet, are in docs/adr.

License

MIT. Vendored code keeps its own license: jpeg-js (BSD-3-Clause and Apache-2.0) and fflate (MIT), see the headers in hooks/domain/media/vendor/.

Source 39 files
hooks/register.tsx 293 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface, Register } from 'claude-code'
3
4import { stopAnimations } from './adapters/animator'
5import { drawnUnlessSuperseded } from './adapters/superseded'
6import { enginePorts } from './adapters/engine'
7import { drawAbovePrompt, drawMediaViewPane, drawPictureRows, drawSettingsPane } from './adapters/views'
8import { openCommand } from './domain/platform'
9import { DEFAULT_SETTINGS, settingsFrom, toggled, type Settings } from './domain/settings'
10import { mediaViewClosed } from './usecases/closes/mediaView'
11import { mediaView } from './usecases/commandRuns/mediaView'
12import { rememberReadPath } from './usecases/images'
13import { abovePrompt, watchDraft } from './usecases/renders/abovePrompt'
14import { assistantMessage } from './usecases/renders/assistantMessage'
15import { MEDIA_VIEW_PANE, mediaViewPane } from './usecases/renders/pane/mediaView'
16import { SETTINGS_PANE, settingsPane } from './usecases/renders/pane/settings'
17import { toolGroup } from './usecases/renders/toolGroup'
18import { toolResult } from './usecases/renders/toolResult'
19import { userMessage } from './usecases/renders/userMessage'
20import { promptSubmits } from './usecases/promptSubmits'
21import { sessionStarts } from './usecases/sessionStarts'
22import { anyTool } from './usecases/toolCalls/anyTool'
23import type { Ports } from './usecases/ports'
24
25const TRANSCRIPT_SITES = ['ToolGroup', 'ToolResult', 'UserMessage', 'AssistantMessage'] as const
26// The key the plugin's store keeps the settings under, for every session.
27const SETTINGS_STORE_KEY = 'settings'
28
29// State refs live where they are read and written (ADR 0014); types/index.d.ts lists them.
30const settings = atom({ plugin: 'media-view', key: 'settings' } as const, DEFAULT_SETTINGS)
31const draftImageNumbers = atom({ plugin: 'media-view', key: 'draftImageNumbers' } as const, [])
32const mediaViewScrollOffset = atom({ plugin: 'media-view', key: 'mediaViewScrollOffset' } as const, 0)
33const shownAt = atom({ plugin: 'media-view', key: 'shownAt' } as const, {})
34const seenImages = atom({ plugin: 'media-view', key: 'seenImages' } as const, [])
35const imageTagRows = atom({ plugin: 'media-view', key: 'imageTagRows' } as const, {})
36
37// Ports over the session's $, made at session.start: work they start outlives the render that asked for it,
38// which a newer draw of the same row would otherwise cut short (ADR 0007). Without a session (tests that only
39// draw), a hook's own $ serves.
40let sessionPorts: Ports | undefined
41
42// What a superseded draw answers: nothing, as the engine no longer uses it.
43function superseded($: EngineInterface, e: Parameters<EngineInterface['ui']['resolve']>[0]) {
44  const { Box } = $.ui.resolve(e)
45  return <Box />
46}
47
48// The settings, for this session and kept in the store for the next ones (ADR 0023); GIFs stop at once when turned off.
49async function saveSettings($: EngineInterface, next: Settings) {
50  await update($, settings, () => next)
51  await $.store.set(SETTINGS_STORE_KEY, next)
52  if (!next.animateGifs) {
53    TRANSCRIPT_SITES.forEach(site => stopAnimations(site))
54  }
55}
56
57// Keeps when an image first showed in the chat; a later sight of it changes nothing.
58async function recordShown($: EngineInterface, key: string) {
59  const at = await $.clock.now()
60  await update($, shownAt, times => (key in times ? times : { ...times, [key]: at }))
61}
62const portsFor = ($: EngineInterface) => sessionPorts ?? enginePorts($)
63
64// The composition root: every hook, each answered by a usecase over the engine's ports (ADRs 0014, 0015).
65export const register: Register = on => {
66  on('session.start', async ($, e, next) => {
67    const started = await next(e)
68    sessionPorts = enginePorts($)
69    const stored = settingsFrom(await $.store.get(SETTINGS_STORE_KEY))
70    if (JSON.stringify(stored) !== JSON.stringify(await read($, settings))) {
71      await update($, settings, () => stored)
72    }
73    await sessionStarts({
74      watchDraft: () =>
75        watchDraft({
76          every: (ms, tick) => $.clock.every(ms, () => void tick()),
77          readDraft: async () => (await $.prompt.read()).text,
78          // `change` hands back `current` itself when nothing changed: then nothing is written.
79          updateDraftNumbers: async change => {
80            const current = await read($, draftImageNumbers)
81            const changed = change(current)
82            if (changed !== current) {
83              await update($, draftImageNumbers, () => [...changed])
84            }
85          },
86        }),
87      registerCommand: async command => {
88        await $.command.register(command)
89      },
90    })
91    return started
92  })
93
94  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) =>
95    drawnUnlessSuperseded(
96      next.signal,
97      async () => {
98        if (e.surface !== 'terminal') {
99          return next(e)
100        }
101        const numbers = await read($, draftImageNumbers)
102        const view = e.props.hasSurvey || !(await read($, settings)).abovePrompt
103          ? null
104          : await abovePrompt(portsFor($), { numbers, bodyColumns: e.props.bodyColumns, maxRows: e.props.maxRows })
105        if (view === null) {
106          stopAnimations('AbovePrompt', e.requestId)
107          return next(e)
108        }
109        return drawAbovePrompt($, e, view)
110      },
111      () => superseded($, e),
112    ),
113  )
114
115  on('ui.render', { component: 'ToolGroup' }, async ($, e, next) =>
116    drawnUnlessSuperseded(
117      next.signal,
118      async () => {
119        if (e.surface !== 'terminal') {
120          return next(e)
121        }
122        const shows = await read($, settings)
123        const rows = shows.toolCalls
124          ? await toolGroup(portsFor($), { requestId: e.requestId, calls: e.props.calls, viewportColumns: e.viewport?.columns })
125          : null
126        const own = await next(e)
127        return rows === null ? own : drawPictureRows($, e, { site: 'ToolGroup', own, rows, isAnimated: shows.animateGifs })
128      },
129      () => superseded($, e),
130    ),
131  )
132
133  on('ui.render', { component: 'ToolResult' }, async ($, e, next) =>
134    drawnUnlessSuperseded(
135      next.signal,
136      async () => {
137        if (e.surface !== 'terminal') {
138          return next(e)
139        }
140        const shows = await read($, settings)
141        const rows = shows.toolCalls
142          ? await toolResult(portsFor($), {
143              toolUseId: e.props.tool_use_id,
144              tool: e.props.tool,
145              output: e.props.output,
146              viewportColumns: e.viewport?.columns,
147            })
148          : null
149        const own = await next(e)
150        return rows === null ? own : drawPictureRows($, e, { site: 'ToolResult', own, rows, isAnimated: shows.animateGifs })
151      },
152      () => superseded($, e),
153    ),
154  )
155
156  on('ui.render', { component: 'UserMessage' }, async ($, e, next) =>
157    drawnUnlessSuperseded(
158      next.signal,
159      async () => {
160        if (e.surface !== 'terminal') {
161          return next(e)
162        }
163        const shows = await read($, settings)
164        const rows = shows.userMessages
165          ? await userMessage(portsFor($), {
166              requestId: e.requestId,
167              text: e.props.text,
168              isFromSomeoneElse: e.props.from !== undefined,
169              viewportColumns: e.viewport?.columns,
170            })
171          : null
172        const own = await next(e)
173        return rows === null ? own : drawPictureRows($, e, { site: 'UserMessage', own, rows, isAnimated: shows.animateGifs })
174      },
175      () => superseded($, e),
176    ),
177  )
178
179  on('ui.render', { component: 'AssistantMessage' }, async ($, e, next) =>
180    drawnUnlessSuperseded(
181      next.signal,
182      async () => {
183        if (e.surface !== 'terminal') {
184          return next(e)
185        }
186        const shows = await read($, settings)
187        const rows = shows.assistantMessages
188          ? await assistantMessage(portsFor($), { requestId: e.requestId, text: e.props.text, viewportColumns: e.viewport?.columns })
189          : null
190        const own = await next(e)
191        return rows === null ? own : drawPictureRows($, e, { site: 'AssistantMessage', own, rows, isAnimated: shows.animateGifs })
192      },
193      () => superseded($, e),
194    ),
195  )
196
197  on('ui.render', { component: 'Pane', requestId: MEDIA_VIEW_PANE }, async ($, e, next) =>
198    drawnUnlessSuperseded(
199      next.signal,
200      async () => {
201        if (e.surface !== 'terminal') {
202          const { Text } = $.ui.resolve(e)
203          return <Text>media-view draws pictures in the terminal.</Text>
204        }
205        // Read so that a scroll of this pane (written below), or an image the transcript just drew, redraws this pane.
206        await Promise.all([read($, mediaViewScrollOffset), read($, seenImages), read($, imageTagRows)])
207        const ports = portsFor($)
208        const entries = await mediaViewPane(ports, {
209          bodyColumns: e.props.bodyColumns,
210          scroll: e.props.scroll,
211          shownAt: await read($, shownAt),
212          draftNumbers: await read($, draftImageNumbers),
213          settings: await read($, settings),
214        })
215        return drawMediaViewPane($, e, entries, {
216          copyPath: path => $.ui.copy({ text: path }),
217          open: async path => ports.run(openCommand((await ports.host()).os, path)),
218          showInChat: rowId => $.ui.scroll({ to: { requestId: rowId }, block: 'center' }),
219        })
220      },
221      () => superseded($, e),
222    ),
223  )
224
225  on('ui.render', { component: 'Pane', requestId: SETTINGS_PANE }, async ($, e, next) =>
226    drawnUnlessSuperseded(
227      next.signal,
228      async () => {
229        const current = await read($, settings)
230        if (e.surface !== 'terminal') {
231          const { Text } = $.ui.resolve(e)
232          return <Text>media-view draws pictures in the terminal.</Text>
233        }
234        return drawSettingsPane($, e, settingsPane(current), key => saveSettings($, toggled(current, key)))
235      },
236      () => superseded($, e),
237    ),
238  )
239
240  on('ui.scroll', { requestId: MEDIA_VIEW_PANE }, async ($, e, next) => {
241    const scrolled = await next(e)
242    await update($, mediaViewScrollOffset, () => e.offset)
243    return scrolled
244  })
245
246  on('ui.close', async ($, e, next) => {
247    const closed = await next(e)
248    await mediaViewClosed(
249      { paneId: e.id, closedBy: e.origin.kind },
250      { stopPaneAnimations: () => stopAnimations('Pane'), closePane: id => $.ui.close({ id }) },
251    )
252    return closed
253  })
254
255  on('command.run', { command: 'media-view' }, async ($, e) => ({
256    text: await mediaView(
257      {
258        openPane: async () => {
259          await $.ui.open({ id: MEDIA_VIEW_PANE, title: 'Media' })
260        },
261        openSettings: async () => {
262          await $.ui.open({ id: SETTINGS_PANE, title: 'Media settings' })
263        },
264        // Opening an open pane only retitles it; giving it the keys brings it to the front.
265        showPane: async () => {
266          await $.ui.open({ id: MEDIA_VIEW_PANE, title: 'Media', focus: true })
267        },
268        setTranscriptAnimated: async isAnimated => saveSettings($, { ...(await read($, settings)), animateGifs: isAnimated }),
269      },
270      e.args,
271    ),
272  }))
273
274  // Any call: a Read's path, which a ToolResult row's props do not carry, and when a result's images showed.
275  on('tool.call', async ($, e, next) => {
276    if (e.tool === 'Read') {
277      rememberReadPath(e.tool_use_id, e.file_path)
278    }
279    const called = await next(e)
280    await anyTool(key => recordShown($, key), { tool: e.tool, toolUseId: e.tool_use_id, result: 'result' in called ? called.result : undefined })
281    return called
282  })
283
284  // Only a prompt from this session's own composer carries its pastes; another agent's or session's numbers its own.
285  on('prompt.submit', async ($, e, next) => {
286    const submitted = await next(e)
287    if (submitted.drop === undefined && e.origin.kind === 'composer') {
288      await promptSubmits(key => recordShown($, key), submitted.text)
289    }
290    return submitted
291  })
292}
293
hooks/adapters/animator.ts 117 lines
1import type { EngineInterface, Timer } from 'claude-code'
2
3import { isTerminalDeny, noticeFor } from '../domain/blitDeny'
4import type { Frame } from '../domain/media/frameCache'
5
6// A blit sent in the same pass as the render that mounts its Image lands before the mount.
7const RETRIES_BEFORE_MOUNT = 20
8const RETRY_MS = 100
9
10export type Site = 'AbovePrompt' | 'ToolGroup' | 'ToolResult' | 'UserMessage' | 'AssistantMessage' | 'Pane'
11
12// One blit loop; a stopped loop's tick that was waiting on a blit sees `isStopped` and ends.
13type Loop = { timer: Timer | undefined; isStopped: boolean }
14
15const loops = new Map<string, Loop>()
16const checkedStills = new Set<string>()
17let isTerminalRefusing = false
18
19const loopId = (site: Site, requestId: string, key: string) => `${site}/${requestId}/${key}`
20
21const stop = (id: string, loop: Loop) => {
22  loop.isStopped = true
23  loop.timer?.cancel()
24  loops.delete(id)
25}
26
27export const stopAnimation = (site: Site, requestId: string, key: string) => {
28  const id = loopId(site, requestId, key)
29  const loop = loops.get(id)
30  if (loop !== undefined) {
31    stop(id, loop)
32  }
33}
34
35export const stopAnimations = (site: Site, requestId?: string) => {
36  const prefix = requestId === undefined ? `${site}/` : `${site}/${requestId}/`
37  for (const [id, loop] of loops) {
38    if (id.startsWith(prefix)) {
39      stop(id, loop)
40    }
41  }
42}
43
44// Stops the loops of a site's request whose Images are no longer drawn.
45export const stopAnimationsExcept = (site: Site, requestId: string, keys: readonly string[]) => {
46  const drawn = new Set(keys.map(key => loopId(site, requestId, key)))
47  for (const [id, loop] of loops) {
48    if (id.startsWith(`${site}/${requestId}/`) && !drawn.has(id)) {
49      stop(id, loop)
50    }
51  }
52}
53
54// Swaps a keyed Image through its frames until it is unmounted or stopped. A still gets one
55// blit of its own frame, which sends nothing new but tells whether this terminal draws it.
56// Once the terminal refuses pictures no loop starts again: every blit would be refused too.
57export function animate(
58  $: EngineInterface,
59  { site, requestId, key, frames }: { site: Site; requestId: string; key: string; frames: Frame[] },
60  onDeny: (deny: string) => void,
61) {
62  const id = loopId(site, requestId, key)
63  const isStill = frames.length < 2
64  if (isTerminalRefusing || loops.has(id) || (isStill && checkedStills.has(id))) {
65    return
66  }
67  checkedStills.add(id)
68  const loop: Loop = { timer: undefined, isStopped: false }
69  loops.set(id, loop)
70  let index = 0
71  let hasLanded = false
72  let retries = 0
73  const schedule = (ms: number) => {
74    if (!loop.isStopped) {
75      loop.timer = $.clock.after(ms, tick)
76    }
77  }
78  const tick = async () => {
79    const next = (index + 1) % frames.length
80    const result = await $.ui.blit({ requestId, key, source: frames[next]!.source })
81    if (loop.isStopped) {
82      return
83    }
84    if (result.deny !== undefined) {
85      if (isTerminalDeny(result.deny)) {
86        isTerminalRefusing = true
87      } else if (!hasLanded && retries++ < RETRIES_BEFORE_MOUNT) {
88        schedule(RETRY_MS)
89        return
90      }
91      stop(id, loop)
92      onDeny(result.deny)
93      return
94    }
95    hasLanded = true
96    if (isStill) {
97      stop(id, loop)
98      return
99    }
100    index = next
101    schedule(frames[index]!.delayMs)
102  }
103  schedule(isStill ? 0 : frames[0]!.delayMs)
104}
105
106const reported = new Set<string>()
107
108// Logs the fix for a terminal deny once per session (ADR 0001).
109export function reportDeny($: EngineInterface, deny: string) {
110  const notice = noticeFor(deny)
111  if (notice === undefined || reported.has(notice)) {
112    return
113  }
114  reported.add(notice)
115  $.ui.log(notice)
116}
117
hooks/adapters/superseded.ts 14 lines
1// A draw that a newer draw of the same row superseded is aborted, and its `$` calls then reject: the engine has gone
2// on without its tree, so the failure means nothing and `superseded` answers in its place (ADR 0024). A failure of
3// a draw still under way is thrown on.
4export async function drawnUnlessSuperseded<T>(signal: AbortSignal, draw: () => Promise<T>, superseded: () => T): Promise<T> {
5  try {
6    return await draw()
7  } catch (error) {
8    if (signal.aborted) {
9      return superseded()
10    }
11    throw error
12  }
13}
14
hooks/adapters/engine.ts 129 lines
1import { atom, read, update } from 'claude-code'
2import type { EngineInterface } from 'claude-code'
3
4import { isWindows, joinPath, osFrom, READ_BLOCK_BYTES, readChunkCommand, tmpRootFor } from '../domain/platform'
5import { DEFAULT_SETTINGS } from '../domain/settings'
6import type { Host, Ports, SeenImage } from '../usecases/ports'
7
8const CACHE_DIRECTORY = 'media-view'
9const MIB = 1024 * 1024
10// $.fs.read rejects files over 4 MiB.
11const FS_READ_LIMIT_BYTES = 4 * MIB
12const MAX_FILE_BYTES = 64 * MIB
13// Base64 of a chunk, line breaks included, stays under a process's 4 MiB of output.
14const CHUNK_BYTES = 32 * READ_BLOCK_BYTES
15
16// The gallery's records live in the session's state, which a hot reload of the module leaves (ADR 0021).
17const seenImages = atom({ plugin: 'media-view', key: 'seenImages' } as const, [])
18const imageTagRows = atom({ plugin: 'media-view', key: 'imageTagRows' } as const, {})
19const shownAt = atom({ plugin: 'media-view', key: 'shownAt' } as const, {})
20const settings = atom({ plugin: 'media-view', key: 'settings' } as const, DEFAULT_SETTINGS)
21
22let host: Promise<Host> | undefined
23
24async function resolveHost($: EngineInterface): Promise<Host> {
25  const osVariable = await $.env.get('OS')
26  const os = isWindows(osVariable) ? 'windows' : osFrom({ osVariable, uname: (await $.process.run(['uname', '-s'])).stdout })
27  const tmpRoot = tmpRootFor(os, {
28    claudeTmpDir: await $.env.get('CLAUDE_CODE_TMPDIR'),
29    temp: os === 'windows' ? await $.env.get('TEMP') : undefined,
30    uid: os === 'windows' ? undefined : (await $.process.run(['id', '-u'])).stdout.trim(),
31  })
32  return { os, tmpRoot, cacheRoot: joinPath(os, tmpRoot, CACHE_DIRECTORY) }
33}
34
35// Resolved once per session; an attempt a render cut short is forgotten (ADR 0007).
36function sessionHost($: EngineInterface) {
37  host ??= resolveHost($).catch(error => {
38    host = undefined
39    throw error
40  })
41  return host
42}
43
44let ffmpeg: Promise<boolean> | undefined
45
46// Whether `ffmpeg -version` runs, asked once per session: an ffmpeg missing from PATH fails to start.
47function sessionFfmpeg($: EngineInterface) {
48  ffmpeg ??= $.process.run(['ffmpeg', '-version']).then(
49    ran => ran.exitCode === 0,
50    () => false,
51  )
52  return ffmpeg
53}
54
55// Reads a file of any size up to MAX_FILE_BYTES: small ones whole, larger ones in base64 chunks (ADR 0005).
56async function readWhole($: EngineInterface, path: string) {
57  const { size } = await $.fs.stat(path)
58  if (size < FS_READ_LIMIT_BYTES) {
59    return Uint8Array.fromBase64((await $.fs.read(path, { as: 'bytes' })).base64)
60  }
61  if (size > MAX_FILE_BYTES) {
62    throw new Error(`${path} is ${Math.ceil(size / MIB)} MiB, over the ${MAX_FILE_BYTES / MIB} MiB media-view reads`)
63  }
64  const { os } = await sessionHost($)
65  const bytes = new Uint8Array(size)
66  for (let offset = 0; offset < size; offset += CHUNK_BYTES) {
67    const { argv, init } = readChunkCommand(os, path, offset, CHUNK_BYTES)
68    const read = await $.process.run(argv, init)
69    if (read.exitCode !== 0) {
70      throw new Error(`reading ${path} failed: ${read.stderr.trim()}`)
71    }
72    bytes.set(Uint8Array.fromBase64(read.stdout.replace(/\s+/g, '')).subarray(0, size - offset), offset)
73  }
74  return bytes
75}
76
77// Runs a state write once the current dispatch is over: a render hook may only read state.
78function afterDrawing($: EngineInterface, write: () => Promise<unknown>) {
79  $.clock.after(0, () => void write())
80}
81
82// The usecases' ports over this hook's `$` (ADR 0015).
83export function enginePorts($: EngineInterface): Ports {
84  return {
85    host: () => sessionHost($),
86    sessionId: () => $.session.id(),
87    readFile: path => readWhole($, path),
88    checkRead: path => $.tool.check({ tool: 'Read', input: { file_path: path } }),
89    // A render may not write state, and only a render knows the row: the write waits for the render to end.
90    rememberSeen: async image => {
91      const isKept = (images: readonly SeenImage[]) => images.some(({ key }) => key === image.key)
92      if (!isKept(await read($, seenImages))) {
93        afterDrawing($, () => update($, seenImages, images => (isKept(images) ? images : [...images, image])))
94      }
95    },
96    seenImages: async () => [...(await read($, seenImages))],
97    rememberImageTagRow: async (n, rowId) => {
98      if ((await read($, imageTagRows))[n] === undefined) {
99        afterDrawing($, () => update($, imageTagRows, rows => (rows[n] === undefined ? { ...rows, [n]: rowId } : rows)))
100      }
101    },
102    imageTagRowOf: async n => (await read($, imageTagRows))[n],
103    rememberShownAt: async key => {
104      if ((await read($, shownAt))[key] === undefined) {
105        const at = await $.clock.now()
106        afterDrawing($, () => update($, shownAt, times => (times[key] === undefined ? { ...times, [key]: at } : times)))
107      }
108    },
109    listDirectory: async path => (await $.fs.list(path)).map(({ name, kind }) => ({ name, kind })),
110    exists: path => $.fs.exists(path),
111    run: async ({ argv, init }) => {
112      const ran = await $.process.run(argv, init)
113      if (ran.exitCode !== 0) {
114        throw new Error(`${argv[0]} exited ${ran.exitCode}: ${ran.stderr.trim()}`)
115      }
116    },
117    convertsFormats: async () => (await read($, settings)).convertFormats,
118    prefersFfmpeg: async () => (await read($, settings)).preferFfmpeg,
119    isFfmpegInstalled: () => sessionFfmpeg($),
120    requestRedraw: afterMs => {
121      if (afterMs === undefined) {
122        $.ui.invalidate('ui.render')
123      } else {
124        $.clock.after(afterMs, () => $.ui.invalidate('ui.render'))
125      }
126    },
127  }
128}
129
hooks/adapters/views.tsx 130 lines
1import type { EngineInterface, RenderElement, RenderInputOf } from 'claude-code'
2
3import type { CellBox } from '../domain/layout'
4import type { SettingKey } from '../domain/settings'
5import { TILE_GAP, type AbovePromptTiles } from '../usecases/renders/abovePrompt'
6import { ENTRY_GAP, PANE_PADDING, type MediaViewEntry } from '../usecases/renders/pane/mediaView'
7import type { SettingSection } from '../usecases/renders/pane/settings'
8import { PICTURE_GAP, type PictureRows } from '../usecases/renders/pictureRows'
9import { animate, reportDeny, stopAnimation, stopAnimations, stopAnimationsExcept, type Site } from './animator'
10
11const BUTTON_GAP = 1
12// Rows between the settings pane's sections.
13const SECTION_GAP = 1
14
15// An Image of another size is another Image: the terminal keeps an unchanged source at the size it was first sent (ADR 0017).
16const sizedKey = (key: string, { columns, rows }: CellBox) => `${key}@${columns}x${rows}`
17
18type TranscriptRow = RenderInputOf<'ToolGroup' | 'ToolResult' | 'UserMessage' | 'AssistantMessage', 'terminal'>
19
20// The engine's own row, then the pictures under it; GIFs move only while the row is on screen (ADR 0008).
21export function drawPictureRows(
22  $: EngineInterface,
23  e: TranscriptRow,
24  { site, own, rows, isAnimated }: { site: Site; own: RenderElement; rows: PictureRows; isAnimated: boolean },
25) {
26  const { Box, Image } = $.ui.resolve(e)
27  const pictures = rows.flat().map(shown => ({ ...shown, key: sizedKey(shown.key, shown.box) }))
28  if (e.props.onScreen === null || !isAnimated) {
29    stopAnimations(site, e.requestId)
30  } else {
31    stopAnimationsExcept(site, e.requestId, pictures.map(({ key }) => key))
32    pictures.forEach(({ key, picture }) => animate($, { site, requestId: e.requestId, key, frames: picture.frames }, deny => reportDeny($, deny)))
33  }
34
35  return (
36    <Box flexDirection="column">
37      {own}
38      {rows.map(row => (
39        <Box flexDirection="row" gap={PICTURE_GAP}>
40          {row.map(({ key, picture, box }) => (
41            <Image key={sizedKey(key, box)} source={picture.frames[0]!.source} columns={box.columns} rows={box.rows} alt="image" />
42          ))}
43        </Box>
44      ))}
45    </Box>
46  )
47}
48
49// The draft's pictures above the prompt, each labelled `#n`, with `+N` for those left out.
50export function drawAbovePrompt($: EngineInterface, e: RenderInputOf<'AbovePrompt', 'terminal'>, { tiles, hidden }: AbovePromptTiles) {
51  const { Box, Image, Text } = $.ui.resolve(e)
52  const keys = tiles.map(({ n, box }) => sizedKey(`paste-${n}`, box))
53  stopAnimationsExcept('AbovePrompt', e.requestId, keys)
54  tiles.forEach(({ picture }, i) =>
55    animate($, { site: 'AbovePrompt', requestId: e.requestId, key: keys[i]!, frames: picture.frames }, deny => reportDeny($, deny)),
56  )
57
58  return (
59    <Box flexDirection="row" gap={TILE_GAP}>
60      {tiles.map(({ n, picture, box }) => (
61        <Box flexDirection="column">
62          <Image key={sizedKey(`paste-${n}`, box)} source={picture.frames[0]!.source} columns={box.columns} rows={box.rows} alt={`[Image #${n}]`} />
63          <Text dimColor>{`#${n}`}</Text>
64        </Box>
65      ))}
66      {hidden > 0 && <Text dimColor>{`+${hidden}`}</Text>}
67    </Box>
68  )
69}
70
71export type MediaViewButtons = {
72  copyPath: (path: string) => unknown
73  open: (path: string) => unknown
74  showInChat: (rowId: string) => unknown
75}
76
77// Each image of the session: its path and buttons above its picture, so text lines up whatever the width.
78export function drawMediaViewPane($: EngineInterface, e: RenderInputOf<'Pane', 'terminal'>, entries: MediaViewEntry[], buttons: MediaViewButtons) {
79  const { Box, Button, Image, Text } = $.ui.resolve(e)
80  if (entries.length === 0) {
81    return (
82      <Box paddingTop={PANE_PADDING.top} paddingX={PANE_PADDING.x}>
83        <Text dimColor>No images in this session yet.</Text>
84      </Box>
85    )
86  }
87  // Only entries inside the pane's scroll window move (ADR 0008).
88  const keys = entries.map(({ id, box }) => sizedKey(id, box))
89  stopAnimationsExcept('Pane', e.requestId, keys)
90  entries.forEach(({ picture, isVisible }, i) =>
91    isVisible
92      ? animate($, { site: 'Pane', requestId: e.requestId, key: keys[i]!, frames: picture.frames }, deny => reportDeny($, deny))
93      : stopAnimation('Pane', e.requestId, keys[i]!),
94  )
95
96  return (
97    <Box flexDirection="column" gap={ENTRY_GAP} paddingTop={PANE_PADDING.top} paddingX={PANE_PADDING.x}>
98      {entries.map(({ id, label, heading, path, picture, box, rowId }) => (
99        <Box flexDirection="column">
100          <Text>{heading}</Text>
101          <Box flexDirection="row" gap={BUTTON_GAP}>
102            <Button key={`copy-${id}`} label="Copy path" onPress={() => buttons.copyPath(path)} />
103            <Button key={`open-${id}`} label="Open" onPress={() => buttons.open(path)} />
104            {rowId !== undefined && <Button key={`show-${id}`} label="Show in chat" onPress={() => buttons.showInChat(rowId)} />}
105          </Box>
106          <Image key={sizedKey(id, box)} source={picture.frames[0]!.source} columns={box.columns} rows={box.rows} alt={label} />
107        </Box>
108      ))}
109    </Box>
110  )
111}
112
113// What media-view draws, each a button that turns it on or off, under its section's title.
114export function drawSettingsPane($: EngineInterface, e: RenderInputOf<'Pane', 'terminal'>, sections: SettingSection[], toggle: (key: SettingKey) => unknown) {
115  const { Box, Button, Text } = $.ui.resolve(e)
116  return (
117    <Box flexDirection="column" gap={SECTION_GAP} paddingTop={PANE_PADDING.top} paddingX={PANE_PADDING.x}>
118      <Text dimColor>What media-view draws, kept for every session:</Text>
119      {sections.map(({ title, entries }) => (
120        <Box flexDirection="column">
121          <Text bold>{title}</Text>
122          {entries.map(({ key, label, isOn }) => (
123            <Button key={`setting-${key}`} label={`[${isOn ? 'x' : ' '}] ${label}`} onPress={() => toggle(key)} />
124          ))}
125        </Box>
126      ))}
127    </Box>
128  )
129}
130
hooks/domain/platform.ts 185 lines
1import { MAX_CONVERTED_PIXELS, type ConvertedFormat } from './media/decode'
2
3export type Os = 'mac' | 'linux' | 'windows'
4
5// A process to run: its argument vector, and its stdin, extra environment and time limit.
6export type Command = { argv: string[]; init: { stdin?: string; env?: Record<string, string>; timeoutMs?: number } }
7
8const WINDOWS_OS_VARIABLE = 'Windows_NT'
9const MAC_UNAME = 'Darwin'
10const POSIX_TMP_BASE = '/tmp'
11// Paths reach child processes through the environment, never through a shell string.
12const PATH_VARIABLE = 'MEDIA_VIEW_PATH'
13const POWERSHELL = ['powershell.exe', '-NoProfile', '-NonInteractive', '-Command']
14
15export const osFrom = ({ osVariable, uname }: { osVariable: string | undefined; uname: string | undefined }): Os => {
16  if (osVariable === WINDOWS_OS_VARIABLE) {
17    return 'windows'
18  }
19  return uname?.trim() === MAC_UNAME ? 'mac' : 'linux'
20}
21
22export const isWindows = (osVariable: string | undefined) => osVariable === WINDOWS_OS_VARIABLE
23
24export const joinPath = (os: Os, ...parts: string[]) => parts.join(os === 'windows' ? '\\' : '/')
25
26// Where Claude Code keeps per-session files, the paste cache among them.
27export const tmpRootFor = (
28  os: Os,
29  { claudeTmpDir, temp, uid }: { claudeTmpDir: string | undefined; temp: string | undefined; uid: string | undefined },
30) => {
31  if (os === 'windows') {
32    return `${temp}\\claude`
33  }
34  const base = (claudeTmpDir ?? POSIX_TMP_BASE).replace(/\/+$/, '')
35  return `${base}/claude-${uid}`
36}
37
38// `$.fs.write` writes text only; binary goes through a process reading base64 on stdin.
39export const writeBytesCommand = (os: Os, path: string, bytes: Uint8Array): Command => {
40  const init = { stdin: bytes.toBase64(), env: { [PATH_VARIABLE]: path } }
41  if (os === 'windows') {
42    return {
43      argv: [...POWERSHELL, `[IO.File]::WriteAllBytes($env:${PATH_VARIABLE}, [Convert]::FromBase64String([Console]::In.ReadToEnd()))`],
44      init,
45    }
46  }
47  return { argv: ['/bin/sh', '-c', `base64 -d > "$${PATH_VARIABLE}"`], init }
48}
49
50export const makeDirectoryCommand = (os: Os, path: string): Command =>
51  os === 'windows'
52    ? { argv: [...POWERSHELL, `New-Item -ItemType Directory -Force -Path $env:${PATH_VARIABLE} | Out-Null`], init: { env: { [PATH_VARIABLE]: path } } }
53    : { argv: ['mkdir', '-p', path], init: {} }
54
55export const openCommand = (os: Os, path: string): Command =>
56  os === 'windows'
57    ? { argv: [...POWERSHELL, `Start-Process -FilePath $env:${PATH_VARIABLE}`], init: { env: { [PATH_VARIABLE]: path } } }
58    : os === 'mac'
59      ? { argv: ['open', path], init: {} }
60      : // xdg-open waits for some viewers to exit; in the background it returns at once.
61        { argv: ['/bin/sh', '-c', `xdg-open "$${PATH_VARIABLE}" >/dev/null 2>&1 &`], init: { env: { [PATH_VARIABLE]: path } } }
62
63const OUT_PATH_VARIABLE = 'MEDIA_VIEW_OUT_PATH'
64
65// What turns a converted format into a PNG or a GIF: the OS's own codecs, or an ffmpeg the person installed (ADR 0030).
66export type Converter = 'os' | 'ffmpeg'
67
68// `width` and `height` are the sniffed size, at which an SVG is drawn.
69export type Conversion = { from: string; to: string; format: ConvertedFormat; isAnimated: boolean; width: number; height: number }
70
71// A conversion still running past this is given up on: a small SVG can still take long to draw (ADR 0031).
72const CONVERSION_TIMEOUT_MS = 10_000
73
74// AppKit draws an SVG into a bitmap of the size given, which it then writes as a PNG. An SVG's references to other
75// files or URLs are not followed: AppKit draws a placeholder for each (ADR 0031).
76const APPKIT_SVG_SCRIPT = `ObjC.import('AppKit')
77function run([from, to, width, height]) {
78  const image = $.NSImage.alloc.initWithContentsOfFile(from)
79  if (image.isNil()) {
80    throw new Error('AppKit read no SVG')
81  }
82  const bitmap = $.NSBitmapImageRep.alloc.initWithBitmapDataPlanesPixelsWidePixelsHighBitsPerSampleSamplesPerPixelHasAlphaIsPlanarColorSpaceNameBytesPerRowBitsPerPixel($(), Number(width), Number(height), 8, 4, true, false, $.NSDeviceRGBColorSpace, 0, 0)
83  $.NSGraphicsContext.saveGraphicsState
84  $.NSGraphicsContext.setCurrentContext($.NSGraphicsContext.graphicsContextWithBitmapImageRep(bitmap))
85  image.drawInRectFromRectOperationFraction($.NSMakeRect(0, 0, Number(width), Number(height)), $.NSZeroRect, $.NSCompositingOperationCopy, 1)
86  $.NSGraphicsContext.restoreGraphicsState
87  if (!bitmap.representationUsingTypeProperties($.NSBitmapImageFileTypePNG, $()).writeToFileAtomically(to, true)) {
88    throw new Error('AppKit wrote no PNG')
89  }
90}`
91
92// ImageIO writes an animated WebP's frames as a looping GIF, each held as long as the WebP holds it. JXA knows no
93// type for ImageIO's key constants, so the keys are written as the strings they stand for (ADR 0029).
94const IMAGE_IO_GIF_SCRIPT = `ObjC.import('Foundation')
95ObjC.import('ImageIO')
96const gif = (key, value) => $.NSDictionary.dictionaryWithObjectForKey($.NSDictionary.dictionaryWithObjectForKey(value, key), '{GIF}')
97function run([from, to]) {
98  const source = $.CGImageSourceCreateWithURL($.NSURL.fileURLWithPath(from), $())
99  const count = $.CGImageSourceGetCount(source)
100  const destination = $.CGImageDestinationCreateWithURL($.NSURL.fileURLWithPath(to), $('com.compuserve.gif'), count, $())
101  $.CGImageDestinationSetProperties(destination, gif('LoopCount', $(0)))
102  for (let i = 0; i < count; i++) {
103    const webp = ObjC.castRefToObject($.CGImageSourceCopyPropertiesAtIndex(source, i, $())).objectForKey('{WebP}')
104    $.CGImageDestinationAddImageFromSource(destination, source, i, gif('DelayTime', webp.objectForKey('UnclampedDelayTime')))
105  }
106  if (!$.CGImageDestinationFinalize(destination)) {
107    throw new Error('ImageIO wrote no GIF')
108  }
109}`
110// One palette made for the whole animation keeps its colours closer than GIF's default palette.
111const FFMPEG_GIF_FILTER = 'split[a][b];[a]palettegen[p];[b][p]paletteuse'
112// ffmpeg reads only the local file, as the demuxer of the format the module sniffed rather than whatever its own
113// probe finds, and decodes no frame past the module's pixel cap (ADR 0030).
114const FFMPEG = ['ffmpeg', '-nostdin', '-v', 'error', '-y', '-protocol_whitelist', 'file', '-max_pixels', String(MAX_CONVERTED_PIXELS), '-f']
115// ffmpeg is commonly built without an SVG decoder, so it is left to the OS (ADR 0031).
116const FFMPEG_DEMUXERS: Partial<Record<ConvertedFormat, string>> = { webp: 'webp_pipe', heic: 'mov', tiff: 'tiff_pipe' }
117// ffmpeg reads an animated WebP's frames through a demuxer of its own, which refuses a still.
118const FFMPEG_ANIMATED_WEBP_DEMUXER = 'webp_anim'
119
120// Whether a converter keeps an animation, as a GIF: ffmpeg anywhere, the OS on macOS only.
121export const convertsAnimation = (os: Os, converter: Converter) => converter === 'ffmpeg' || os === 'mac'
122
123// Whether ffmpeg converts the format, where the person prefers it (ADR 0030).
124export const ffmpegConverts = (format: ConvertedFormat) => FFMPEG_DEMUXERS[format] !== undefined
125
126const commandFor = (os: Os, converter: Converter, { from, to, format, isAnimated, width, height }: Conversion): Command | null => {
127  if (converter === 'ffmpeg') {
128    const demuxer = isAnimated ? FFMPEG_ANIMATED_WEBP_DEMUXER : FFMPEG_DEMUXERS[format]
129    const output = isAnimated ? ['-filter_complex', FFMPEG_GIF_FILTER, '-loop', '0'] : ['-frames:v', '1', '-update', '1']
130    return demuxer === undefined ? null : { argv: [...FFMPEG, demuxer, '-i', from, ...output, to], init: {} }
131  }
132  if (os === 'mac') {
133    if (format === 'svg') {
134      return { argv: ['osascript', '-l', 'JavaScript', '-e', APPKIT_SVG_SCRIPT, from, to, String(width), String(height)], init: {} }
135    }
136    return isAnimated
137      ? { argv: ['osascript', '-l', 'JavaScript', '-e', IMAGE_IO_GIF_SCRIPT, from, to], init: {} }
138      : { argv: ['sips', '-s', 'format', 'png', from, '--out', to], init: {} }
139  }
140  if (os === 'windows' && format !== 'svg') {
141    return {
142      argv: [
143        ...POWERSHELL,
144        `$ErrorActionPreference = 'Stop'; Add-Type -AssemblyName PresentationCore; $i = [IO.File]::OpenRead($env:${PATH_VARIABLE}); $d = [Windows.Media.Imaging.BitmapDecoder]::Create($i, 'None', 'OnLoad'); $i.Close(); $e = New-Object Windows.Media.Imaging.PngBitmapEncoder; $e.Frames.Add($d.Frames[0]); $o = [IO.File]::Create($env:${OUT_PATH_VARIABLE}); $e.Save($o); $o.Close()`,
145      ],
146      init: { env: { [PATH_VARIABLE]: from, [OUT_PATH_VARIABLE]: to } },
147    }
148  }
149  return null
150}
151
152// Converts an image the module does not decode to a PNG of its first frame, or an animation to a GIF, within a time
153// limit; null where the converter has no codec for it: the OS on Linux, an SVG anywhere but macOS (ADR 0029).
154export const convertCommand = (os: Os, converter: Converter, conversion: Conversion): Command | null => {
155  const command = commandFor(os, converter, conversion)
156  return command && { ...command, init: { ...command.init, timeoutMs: CONVERSION_TIMEOUT_MS } }
157}
158
159const OFFSET_VARIABLE = 'MEDIA_VIEW_OFFSET'
160const LENGTH_VARIABLE = 'MEDIA_VIEW_LENGTH'
161// dd reads whole blocks; chunks are aligned to them.
162export const READ_BLOCK_BYTES = 65536
163
164// `$.fs.read` stops at 4 MiB and a process's output at 4 MiB too; a larger file is read as base64 slices.
165export const readChunkCommand = (os: Os, path: string, offset: number, length: number): Command => {
166  const env = { [PATH_VARIABLE]: path, [OFFSET_VARIABLE]: String(offset), [LENGTH_VARIABLE]: String(length) }
167  if (os === 'windows') {
168    return {
169      argv: [
170        ...POWERSHELL,
171        `$f = [IO.File]::OpenRead($env:${PATH_VARIABLE}); [void]$f.Seek([long]$env:${OFFSET_VARIABLE}, 0); $b = New-Object byte[] ([int]$env:${LENGTH_VARIABLE}); $n = $f.Read($b, 0, $b.Length); $f.Close(); [Convert]::ToBase64String($b, 0, $n)`,
172      ],
173      init: { env },
174    }
175  }
176  return {
177    argv: [
178      '/bin/sh',
179      '-c',
180      `dd if="$${PATH_VARIABLE}" bs=${READ_BLOCK_BYTES} skip=$((${OFFSET_VARIABLE} / ${READ_BLOCK_BYTES})) count=$((${LENGTH_VARIABLE} / ${READ_BLOCK_BYTES})) 2>/dev/null | base64`,
181    ],
182    init: { env },
183  }
184}
185
hooks/domain/settings.ts 53 lines
1// Where media-view shows images, each named after the Claude Code component it draws in, and how it plays GIFs
2// (ADR 0027), and whether the formats media-view does not decode are converted (ADR 0029), and by ffmpeg where it is
3// installed (ADR 0030), each the person's to turn off in the settings pane.
4export const SHOW_SETTING_KEYS = ['abovePrompt', 'userMessages', 'toolCalls', 'assistantMessages'] as const
5export const PLAY_SETTING_KEYS = ['animateGifs'] as const
6export const FORMAT_SETTING_KEYS = ['convertFormats', 'preferFfmpeg'] as const
7export const SETTING_KEYS = [...SHOW_SETTING_KEYS, ...PLAY_SETTING_KEYS, ...FORMAT_SETTING_KEYS] as const
8
9export type SettingKey = (typeof SETTING_KEYS)[number]
10
11export type Settings = Record<SettingKey, boolean>
12
13// The settings that each let images be shown in one place, in the chat and in the gallery alike.
14export type ShowSetting = (typeof SHOW_SETTING_KEYS)[number]
15
16// The settings pane's sections, in the order the person reads them.
17export const SETTING_SECTIONS: readonly { title: string; keys: readonly SettingKey[] }[] = [
18  { title: 'Show media', keys: SHOW_SETTING_KEYS },
19  { title: 'GIFs', keys: PLAY_SETTING_KEYS },
20  { title: 'Formats', keys: FORMAT_SETTING_KEYS },
21]
22
23export const SETTING_LABELS: Record<SettingKey, string> = {
24  abovePrompt: 'Above the prompt',
25  userMessages: 'Under prompts you sent',
26  toolCalls: 'Under Claude’s tool calls',
27  assistantMessages: 'Under Claude’s replies',
28  animateGifs: 'Animate GIFs',
29  convertFormats: 'Convert WebP, HEIC, TIFF and SVG through the OS',
30  preferFfmpeg: 'Convert with ffmpeg instead, where installed',
31}
32
33export const DEFAULT_SETTINGS: Settings = {
34  abovePrompt: true,
35  userMessages: true,
36  toolCalls: true,
37  assistantMessages: true,
38  animateGifs: true,
39  convertFormats: true,
40  preferFfmpeg: true,
41}
42
43// Settings from what the plugin's store holds, a file the person or an older version may have written: a setting
44// missing or not a yes or no stays at its default.
45export const settingsFrom = (stored: unknown): Settings => {
46  const values = (stored ?? {}) as Partial<Record<SettingKey, unknown>>
47  return Object.fromEntries(
48    SETTING_KEYS.map(key => [key, typeof values[key] === 'boolean' ? values[key] : DEFAULT_SETTINGS[key]]),
49  ) as Settings
50}
51
52export const toggled = (settings: Settings, key: SettingKey): Settings => ({ ...settings, [key]: !settings[key] })
53
hooks/usecases/closes/mediaView.ts 22 lines
1import { MEDIA_VIEW_PANE } from '../renders/pane/mediaView'
2import { SETTINGS_PANE } from '../renders/pane/settings'
3
4// The gallery and its settings open as a pair of tabs; each closes the other.
5const PAIRED: Record<string, string> = { [MEDIA_VIEW_PANE]: SETTINGS_PANE, [SETTINGS_PANE]: MEDIA_VIEW_PANE }
6
7// Closing the gallery stops its GIFs. When the person closes either of the pair, the other closes too; a close
8// media-view made itself, or an unload, closes nothing more, so the pair never closes each other in turn. Other
9// panes are someone else's.
10export const mediaViewClosed = async (
11  { paneId, closedBy }: { paneId: string; closedBy: 'plugin' | 'person' | 'unload' },
12  actions: { stopPaneAnimations: () => void; closePane: (id: string) => Promise<void> },
13) => {
14  if (paneId === MEDIA_VIEW_PANE) {
15    actions.stopPaneAnimations()
16  }
17  const other = PAIRED[paneId]
18  if (closedBy === 'person' && other !== undefined) {
19    await actions.closePane(other)
20  }
21}
22
hooks/usecases/commandRuns/mediaView.ts 40 lines
1// What `$.command.register` declares for `/media-view`.
2export const MEDIA_VIEW_COMMAND = {
3  name: 'media-view',
4  description: 'Open the gallery of this session’s images; `settings` chooses what is drawn; `still` or `animate` sets GIFs',
5  argumentHint: '[settings|still|animate]',
6}
7
8export type MediaViewActions = {
9  openPane: () => Promise<void>
10  openSettings: () => Promise<void>
11  // Brings the open gallery to the front of the engine's tabs.
12  showPane: () => Promise<void>
13  setTranscriptAnimated: (isAnimated: boolean) => Promise<void>
14}
15
16// `/media-view` opens the gallery and `settings` the settings, each with the other as the engine's tab beside it,
17// so the settings are always one tab away. Tabs stand in the order first opened, the gallery first, and a pane
18// first opened is shown, so the gallery is shown again after the settings open. `still` and `animate` set GIFs.
19// Answers the command's text.
20export const mediaView = async (actions: MediaViewActions, args: string) => {
21  const argument = args.trim()
22  if (argument === 'still' || argument === 'animate') {
23    const isAnimated = argument === 'animate'
24    await actions.setTranscriptAnimated(isAnimated)
25    return `Transcript GIFs: ${isAnimated ? 'animated' : 'still'}.`
26  }
27  if (argument === 'settings') {
28    await actions.openPane()
29    await actions.openSettings()
30    return 'Opened the media-view settings.'
31  }
32  if (argument !== '') {
33    return `Usage: /${MEDIA_VIEW_COMMAND.name} ${MEDIA_VIEW_COMMAND.argumentHint}`
34  }
35  await actions.openPane()
36  await actions.openSettings()
37  await actions.showPane()
38  return 'Opened the media gallery.'
39}
40
hooks/usecases/images.ts 207 lines
1import { imageFileName } from '../domain/imageTags'
2import {
3  decodeMedia,
4  isCompleteImage,
5  isDecodedName,
6  MAX_CONVERTED_PIXELS,
7  MAX_CONVERTED_TOTAL_PIXELS,
8  sniffConverted,
9  type ConvertedFormat,
10} from '../domain/media/decode'
11import { cacheDirectoryName, framePlan, type Picture, type Plan } from '../domain/media/frameCache'
12import { convertCommand, convertsAnimation, ffmpegConverts, joinPath, makeDirectoryCommand, writeBytesCommand, type Converter } from '../domain/platform'
13import type { SourceImage } from '../domain/readOutput'
14import type { Host, Ports } from './ports'
15
16const IMAGES_DIRECTORY = 'images'
17const MAX_RETRIES = 3
18// Long enough for Claude Code to finish writing a paste the draft already shows.
19const RETRY_DELAY_MS = 250
20// Pictures are drawn at most 40 columns wide, some 800 device pixels on a high-density screen: a still is kept up
21// to that, while a GIF's many frames past a smaller edge, or past this count, only cost memory and disk (ADR 0006).
22const DRAWN_LIMITS = { maxEdge: 512, maxStillEdge: 1024, maxFrames: 200 }
23// Write processes running at once, across every picture (ADR 0007).
24const CONCURRENT_WRITES = 4
25// A converted format's source and what its converter makes of it, beside the picture's numbered frames.
26const CONVERTED_SOURCE_FILE = 'source'
27const CONVERTED_PNG_FILE = 'source.png'
28const CONVERTED_GIF_FILE = 'source.gif'
29
30// A source not there yet (a paste Claude Code is still writing): a failure to retry, not "no picture".
31class NotWrittenYet extends Error {}
32
33// A converted format while the settings leave it no converter (conversion off, or no ffmpeg where the OS has none):
34// no picture for now, kept for no later draw, so one after the settings change converts (ADR 0029).
35class NotConvertedNow extends Error {}
36
37const pictures = new Map<string, Promise<Picture | null>>()
38const plans = new Map<string, Plan>()
39const failures = new Map<string, number>()
40const readPaths = new Map<string, string>()
41const pasteCaches = new Map<string, string>()
42
43let writesRunning = 0
44const writesWaiting: (() => void)[] = []
45
46const withWriteSlot = async (write: () => Promise<void>) => {
47  if (writesRunning >= CONCURRENT_WRITES) {
48    await new Promise<void>(resolve => writesWaiting.push(resolve))
49  }
50  writesRunning++
51  try {
52    await write()
53  } finally {
54    writesRunning--
55    writesWaiting.shift()?.()
56  }
57}
58
59const decodeOrNull = (source: SourceImage | null) => {
60  try {
61    return source && decodeMedia(source.bytes, DRAWN_LIMITS)
62  } catch {
63    return null
64  }
65}
66
67// ffmpeg where it converts the format, the person prefers it and it is installed, else the OS (ADRs 0030, 0031).
68const converterFor = async (ports: Ports, format: ConvertedFormat): Promise<Converter> =>
69  ffmpegConverts(format) && (await ports.prefersFfmpeg()) && (await ports.isFfmpegInstalled()) ? 'ffmpeg' : 'os'
70
71// A source in a converted format, as the PNG, or the GIF of an animation, its converter makes of it in the
72// picture's directory; null where the conversion or reading its output back fails, which no retry changes, and for
73// a source declaring more pixels than the decoders take, which is not handed to a converter at all (ADR 0029).
74// Any other source is decoded as it is.
75const convertedOrAsIs = async (ports: Ports, host: Host, directory: string, source: SourceImage | null) => {
76  const converted = source && sniffConverted(source.bytes)
77  if (!converted) {
78    return source
79  }
80  const framePixels = converted.width * converted.height
81  if (framePixels > MAX_CONVERTED_PIXELS || framePixels * converted.frames > MAX_CONVERTED_TOTAL_PIXELS) {
82    return null
83  }
84  const converter = await converterFor(ports, converted.format)
85  const isAnimated = converted.frames > 1 && convertsAnimation(host.os, converter)
86  const from = joinPath(host.os, directory, CONVERTED_SOURCE_FILE)
87  const to = joinPath(host.os, directory, isAnimated ? CONVERTED_GIF_FILE : CONVERTED_PNG_FILE)
88  const { format, width, height } = converted
89  const convert = convertCommand(host.os, converter, { from, to, format, isAnimated, width, height })
90  if (convert === null || !(await ports.convertsFormats())) {
91    throw new NotConvertedNow()
92  }
93  await ports.run(makeDirectoryCommand(host.os, directory))
94  await ports.run(writeBytesCommand(host.os, from, source.bytes))
95  try {
96    await ports.run(convert)
97    return { bytes: await ports.readFile(to) }
98  } catch {
99    return null
100  }
101}
102
103// The picture's files, decoded once and kept until written. Undefined when the source is no picture or cannot be
104// decoded, which no retry changes; a load that throws (I/O, a paste not written yet) is the caller's to retry.
105const planFor = async (ports: Ports, host: Host, key: string, load: () => Promise<SourceImage | null>) => {
106  const planned = plans.get(key)
107  if (planned !== undefined) {
108    return planned
109  }
110  const directory = joinPath(host.os, host.cacheRoot, await cacheDirectoryName(key))
111  const decoded = decodeOrNull(await convertedOrAsIs(ports, host, directory, await load()))
112  if (!decoded) {
113    return undefined
114  }
115  const plan = framePlan(host.os, directory, decoded)
116  plans.set(key, plan)
117  return plan
118}
119
120const writePlan = async (ports: Ports, host: Host, { directory, writes, ...picture }: Plan): Promise<Picture> => {
121  await ports.run(makeDirectoryCommand(host.os, directory))
122  await Promise.all(writes.map(({ path, bytes }) => withWriteSlot(() => ports.run(writeBytesCommand(host.os, path, bytes)))))
123  return picture
124}
125
126// A failed load or write is forgotten and retried on a later draw, at most MAX_RETRIES times; a decoded plan is
127// kept, so a retry only writes. After that the picture stays absent (ADR 0007).
128const loadOrRetry = async (ports: Ports, key: string, load: () => Promise<SourceImage | null>): Promise<Picture | null> => {
129  try {
130    const host = await ports.host()
131    const plan = await planFor(ports, host, key, load)
132    if (plan === undefined) {
133      return null
134    }
135    const picture = await writePlan(ports, host, plan)
136    plans.delete(key)
137    return picture
138  } catch (error) {
139    if (error instanceof NotConvertedNow) {
140      pictures.delete(key)
141      return null
142    }
143    const failed = (failures.get(key) ?? 0) + 1
144    failures.set(key, failed)
145    if (failed <= MAX_RETRIES) {
146      pictures.delete(key)
147      ports.requestRedraw(RETRY_DELAY_MS)
148    } else {
149      plans.delete(key)
150    }
151    return null
152  }
153}
154
155// Decodes and writes a source to the frame cache once per key; later calls share the result.
156// Resolves null, never rejects, when the source is no picture or every attempt failed.
157export const loadPicture = (ports: Ports, key: string, load: () => Promise<SourceImage | null>) => {
158  if (!pictures.has(key)) {
159    pictures.set(key, loadOrRetry(ports, key, load))
160  }
161  return pictures.get(key)!
162}
163
164// The paste cache folder of a session, `<tmp root>/<project>/<session>/images`, remembered once found.
165export const pasteCacheOf = async (ports: Ports, host: Host, sessionId: string) => {
166  const known = pasteCaches.get(sessionId)
167  if (known !== undefined) {
168    return known
169  }
170  for (const project of await ports.listDirectory(host.tmpRoot)) {
171    const images = joinPath(host.os, host.tmpRoot, project.name, sessionId, IMAGES_DIRECTORY)
172    if (project.kind === 'dir' && (await ports.exists(images))) {
173      pasteCaches.set(sessionId, images)
174      return images
175    }
176  }
177  return undefined
178}
179
180const readImageTag = async (ports: Ports, sessionId: string, n: number): Promise<SourceImage | null> => {
181  const host = await ports.host()
182  const images = await pasteCacheOf(ports, host, sessionId)
183  const name = images === undefined ? undefined : imageFileName((await ports.listDirectory(images)).map(entry => entry.name), n)
184  if (images === undefined || name === undefined) {
185    throw new NotWrittenYet(`[Image #${n}] is not in the paste cache yet`)
186  }
187  if (!isDecodedName(name)) {
188    return null
189  }
190  const bytes = await ports.readFile(joinPath(host.os, images, name))
191  if (!isCompleteImage(bytes)) {
192    throw new NotWrittenYet(`[Image #${n}] is still being written`)
193  }
194  return { bytes }
195}
196
197// The picture of `[Image #n]`, from the session's paste cache (ADR 0004).
198export const loadImageTag = (ports: Ports, sessionId: string, n: number) =>
199  loadPicture(ports, `paste/${sessionId}/${n}`, () => readImageTag(ports, sessionId, n))
200
201// The file a Read call read, kept from its `tool.call` for rows whose props do not carry it.
202export const rememberReadPath = (toolUseId: string, path: string) => {
203  readPaths.set(toolUseId, path)
204}
205
206export const readPathOf = (toolUseId: string) => readPaths.get(toolUseId)
207
hooks/usecases/renders/abovePrompt.ts 89 lines
1import { imageTagNumbers } from '../../domain/imageTags'
2import { cellBox, type CellBox } from '../../domain/layout'
3import type { Picture } from '../../domain/media/frameCache'
4import { loadImageTag } from '../images'
5import type { Ports } from '../ports'
6
7// Pasting raises no edit event, so the draft is read on a timer.
8const DRAFT_POLL_MS = 200
9const MAX_TILE_COLUMNS = 24
10const MAX_TILE_ROWS = 6
11const LABEL_ROWS = 1
12const MORE_LABEL_COLUMNS = 4
13export const TILE_GAP = 1
14
15export type Tile = { n: number; picture: Picture; box: CellBox }
16
17// What the `AbovePrompt` band draws: the tiles that fit, and how many are left out.
18export type AbovePromptTiles = { tiles: Tile[]; hidden: number }
19
20export type DraftPorts = {
21  every: (ms: number, tick: () => Promise<void>) => { cancel: () => void }
22  readDraft: () => Promise<string>
23  updateDraftNumbers: (change: (current: readonly number[]) => readonly number[]) => Promise<void>
24}
25
26const isSameList = (a: readonly number[], b: readonly number[]) => a.length === b.length && a.every((n, i) => n === b[i])
27
28let watch: { cancel: () => void } | undefined
29
30// Keeps the draft's image tag numbers up to date, written only when they change.
31export const watchDraft = (draft: DraftPorts) => {
32  let lastDraft: string | undefined
33  let isReading = false
34  watch?.cancel()
35  watch = draft.every(DRAFT_POLL_MS, async () => {
36    if (isReading) {
37      return
38    }
39    isReading = true
40    try {
41      const text = await draft.readDraft()
42      if (text !== lastDraft) {
43        lastDraft = text
44        const numbers = imageTagNumbers(text)
45        await draft.updateDraftNumbers(current => (isSameList(current, numbers) ? current : numbers))
46      }
47    } finally {
48      isReading = false
49    }
50  })
51}
52
53// The tiles that fit in `columns`, keeping room for a `+N` label when some are left out.
54const fitTiles = (tiles: Tile[], columns: number) => {
55  const fitted: Tile[] = []
56  let used = 0
57  for (const tile of tiles) {
58    const needed = tile.box.columns + (fitted.length > 0 ? TILE_GAP : 0)
59    const reserve = fitted.length + 1 < tiles.length ? MORE_LABEL_COLUMNS : 0
60    if (used + needed + reserve > columns) {
61      break
62    }
63    fitted.push(tile)
64    used += needed
65  }
66  return fitted
67}
68
69// The pictures of the draft's image tags, one row above the prompt; null when there are none.
70export const abovePrompt = async (
71  ports: Ports,
72  { numbers, bodyColumns, maxRows }: { numbers: readonly number[]; bodyColumns: number; maxRows: number },
73): Promise<AbovePromptTiles | null> => {
74  if (numbers.length === 0) {
75    return null
76  }
77  const sessionId = await ports.sessionId()
78  const tileRows = Math.max(1, Math.min(MAX_TILE_ROWS, maxRows - LABEL_ROWS))
79  const loaded = await Promise.all(numbers.map(n => loadImageTag(ports, sessionId, n).then(picture => picture && { n, picture })))
80  const tiles = loaded
81    .filter((item): item is { n: number; picture: Picture } => item !== null)
82    .map(item => ({ ...item, box: cellBox(item.picture, { maxColumns: MAX_TILE_COLUMNS, maxRows: tileRows }) }))
83  if (tiles.length === 0) {
84    return null
85  }
86  const shown = fitTiles(tiles, bodyColumns)
87  return { tiles: shown, hidden: tiles.length - shown.length }
88}
89
hooks/usecases/renders/assistantMessage.ts 34 lines
1import { imagePathsIn } from '../../domain/imagePaths'
2import { loadPicture } from '../images'
3import type { Ports } from '../ports'
4import { isShown, placeInRows, type PictureRows, type Shown } from './pictureRows'
5
6// The picture of an image file a reply names, when Read may read it without asking and the file is there: a reply
7// is drawn again and again, so it never puts a question to the person nor retries a path to nothing (ADR 0022).
8const replyImage = async (ports: Ports, requestId: string, path: string, i: number): Promise<Shown | null> => {
9  if ((await ports.checkRead(path)).decision !== 'allow' || !(await ports.exists(path))) {
10    return null
11  }
12  const key = `file/${path}`
13  const picture = await loadPicture(ports, key, async () => ({ bytes: await ports.readFile(path) }))
14  if (picture === null) {
15    return null
16  }
17  await ports.rememberSeen({ key, path, label: path, shownAtKey: requestId, rowId: requestId, setting: 'assistantMessages', picture })
18  await ports.rememberShownAt(requestId)
19  return { key: `image-${i}`, picture }
20}
21
22// The pictures of the image files an `AssistantMessage` row names; null when it names none that can be drawn.
23export const assistantMessage = async (
24  ports: Ports,
25  { requestId, text, viewportColumns }: { requestId: string; text: string; viewportColumns: number | undefined },
26): Promise<PictureRows | null> => {
27  const paths = imagePathsIn(text)
28  if (paths.length === 0) {
29    return null
30  }
31  const shown = (await Promise.all(paths.map((path, i) => replyImage(ports, requestId, path, i)))).filter(isShown)
32  return shown.length === 0 ? null : placeInRows(shown, viewportColumns)
33}
34