Claude shows its finished work right in your terminal: screenshots, videos of it clicking through your app, and synced before/after QA

<img src="docs/homepage.jpg" alt="A recording of the Tern homepage plays inside Claude Code, with the list of what changed beside it" width="100%">
<h1 align="center">claude-show-your-work</h1>
<a href="https://github.com/iamumeransari/claude-show-your-work/stargazers"><img src="https://img.shields.io/github/stars/iamumeransari/claude-show-your-work?style=flat&logo=github&label=Stars&color=E3B341" alt="GitHub stars"></a> <a href="#install"><img src="https://img.shields.io/badge/Claude_Code-plugin-D97757?logo=claude&logoColor=white" alt="Claude Code plugin"></a> <a href="#install"><img src="https://img.shields.io/badge/macOS_%7C_Linux-555555" alt="macOS and Linux"></a> <a href="LICENSE"><img src="https://img.shields.io/github/license/iamumeransari/claude-show-your-work?color=22C55E" alt="MIT license"></a>
Run these two commands in Claude Code:
/plugin marketplace add https://github.com/iamumeransari/claude-show-your-work.git#releases
/plugin install show-your-work@iamumeransari
It supports Ghostty and kitty, on macOS and Linux, with Claude Code 2.1.286 or later. Videos also need ffmpeg: install it with your package manager (brew install ffmpeg on macOS), or ask Claude to install it.
When the install finishes, a short onboarding shows you around. Run /show-your-work at any time to change your settings.
Claude shows you its work in the chat whenever it builds or changes something visual. You can also ask for it directly:
When Claude builds a feature or fixes a bug, it tests the change with Playwright, records the run and plays the recording in the chat, with everything you need to review the work in one place:
<img src="docs/concepts.jpg" alt="Four landing page concepts for Tern shown in the chat" width="49%"> <img src="docs/breakpoints.jpg" alt="The Tern homepage at desktop, tablet and phone sizes shown in the chat" width="49%">
Whatever Claude designs, you see it right in the chat: landing pages, app screens, components, design concepts, slides, charts and generated images. Ask for a few directions and they appear side by side, then keep iterating on the one you like.
<img src="docs/persona.jpg" alt="An ad persona in the chat" width="49%"> <img src="docs/reel.jpg" alt="The ad made from it, playing in the chat" width="49%">
Beyond product QA, Claude can show you a video of almost anything it works on. Building a website and want to see how it feels as you scroll from top to bottom? Just ask, and the recording plays in the chat, animations and all.
Making an ad, an animation or a launch video? Each cut plays right in the chat, in a full-featured video player:
show-your-work supports Ghostty and kitty, on macOS and Linux. Pictures work there straight away.
CLAUDE_CODE_FORCE_TERMINAL_IMAGES=1, so the first time, the plugin turns that on for new tmux panes and the notice copies a command that reopens the chat with it. The plugin also turns on allow-passthrough for its own pane and passes the pictures through. Nothing in your tmux config is changed.Versions 0.6.7 to 0.6.9 offered a Turn on pictures button in Warp, WezTerm and Konsole, which added a line to your shell profile. It made pictures draw as a grid of boxes, so the plugin now removes that line by itself.
Yes, Claude Code can show images in the terminal with the show-your-work plugin. Once it's installed, Claude shows screenshots, designs, charts and other images right in the chat. It works in Ghostty and kitty.
Yes, Claude Code can play videos in the terminal with the show-your-work plugin. It plays screen recordings, animations, ads and launch videos inside the Claude Code chat. It comes with a feature-rich video player, with scrubbing, skip controls, clickable timestamps and side-by-side comparisons.
You can see what Claude Code built by installing the show-your-work plugin. Whenever Claude builds or changes something visual, it takes a screenshot or records it and shows you the result in the chat. You don't have to switch to a browser and find the page yourself.
Yes, Claude Code can test your app and show you a recording with the show-your-work plugin. Claude tests the features it builds with Playwright, records each run and plays the recording in the chat. The steps are listed beside the video with timestamps. Each check turns green or red as the video reaches it.
Yes, Claude Code can show you a before and after of a change or bug fix with the show-your-work plugin. Claude records the same Playwright steps on the old version and the new one. Compare plays both recordings side by side, in sync. Each test check turns green or red as the video reaches it.
Yes, show-your-work is a Claude Code plugin for visual QA. It records Claude's Playwright test runs and plays them in the chat. Each recording comes with clickable change markers and checks that turn green or red as the video plays. For a change or bug fix, it plays the before and after side by side, in sync.
The easiest way to check that Claude Code actually fixed a bug is to have it record the fix with show-your-work. Ask Claude to fix the bug and show you the before and after. The old and new versions play side by side, in sync, with the checks that now pass marked in green.
show-your-work goes beyond viewing images in the terminal. Its main strength is visual QA. It plays synced before-and-after Playwright recordings, lists the changes you can click to jump to, and turns each check green or red as the video plays. You can review a feature or a fix without leaving Claude Code.
No, show-your-work barely uses any extra tokens, because it's built from the ground up to be both token and memory efficient. Images and videos are drawn straight into your terminal with the kitty graphics protocol, without using any tokens. Videos are also decoded and streamed efficiently, so very little memory is used.
The show-your-work plugin supports Ghostty and kitty, on macOS and Linux.
Yes, show-your-work is free and open source under the MIT license.
No, you don't need to update it yourself. The plugin updates itself, so you're never left behind. You can choose between Stable and Latest releases during the onboarding, or any time with /show-your-work.
You can see the onboarding again by running /show-your-work tour. It covers recordings, before and after, version history and the settings.
No, it doesn't take up much space. It keeps recent pictures and videos so you can flip back through them, and clears out the oldest once they add up to about 1 GB.
You choose whether to share anonymous usage data. You can make that choice during the onboarding, or change it any time with /show-your-work. It never collects any sensitive data whatsoever. The details are in the Privacy policy.
Here's everything the plugin does on your computer, so you know exactly what you're installing. Your pictures and videos never leave your machine.
To get pictures and videos ready, it uses ffmpeg and ffprobe (turning a video into frames and reading its length) and, on macOS, sips (converting a picture to PNG). When you press View, Show in Finder or Save to Downloads, it opens the file with open on macOS or xdg-open on Linux. On macOS, mdfind helps /img find an image you pasted.
A few short scripts run with sh and perl. They find ffmpeg and your home folder, read the terminal's cell size so pictures fit, tidy the plugin's temp folder, open a viewer on Linux, and switch between the Stable and Latest channels. It also uses cp, mkdir, rm, cat and touch for its own temp files, and claude plugin to install its own updates from this repository, at most once a day. You can turn updates off. The updater will be turned off after the plugin moves to the Claude Code plugin directory, which keeps it up to date instead.
It keeps these files:
$TMPDIR/claude-show-your-work-<your user id>), and anything older than a week is cleaned up..show-your-work/ in your project, so you can look back through versions.~/Downloads.SHOW_YOUR_WORK_DEBUG=1, it writes a debug.log in the temp folder.Once a day it reads the plugin's latest version number from raw.githubusercontent.com.
If Usage data is set to share in /show-your-work, it sends anonymous usage counts to us.i.posthog.com. These are event names and counts, plus the plugin and Claude Code versions, your terminal, your OS and whether ffmpeg is installed, under a random install id. They never include file names, paths, prompts, anything you type or your IP address. The key in the code is PostHog's public key, which can only send events.
Inside Claude Code, it uses these hooks:
prompt.submit sends one short line with your message, telling Claude this terminal can show pictures (or why it can't). It sends it once a session, again after a compaction, and when that changes.prompt.submit closes the settings when you send a message and remembers the names of images you paste, so /img can find them. Your message isn't changed.tool.call handles the plugin's own show_image and show_video tools. It never touches other tools.command.run runs /img and /show-your-work. Right after you install, it runs /show-your-work tour once to show you around.ui.render draws the plugin's player, notices, settings and tour.session.start and session.end set up the temp folder and terminal at the start, and send any waiting usage counts at the end. Inside tmux they also start and stop the picture pass-through for the plugin's pane (see Terminals).To report a bug or suggest a change, open an issue.
The plugin gives Claude two tools, show_image and show_video. A basic call needs only a path. For a before and after, Claude also passes the old file and the test results:
{
"path": "qa/after.webm", // the run on the fixed version
"compare": "qa/before.webm", // the same steps on the old version
"title": "Pricing page",
"url": "http://localhost:3000/pricing",
"changes": [ // what changed, and the second it shows up
{ "title": "Annual toggle sets prices", "at": 3.2 },
{ "title": "Plan buttons line up", "at": 5.4 }
],
"summary": [ // the test results, at most three lines
{ "label": "Billing: toggle works", "ok": true, "passed": 1, "total": 1 },
{ "label": "Layout: plans, buttons", "ok": true, "passed": 3, "total": 3 }
]
}
Videos are cut into frames at up to 12 per second, at the width the window shows them (at most 2400 px), with a cap of 3,600 frames (five minutes at full rate). To open a file yourself, run /img path/to/file.png.
To work on the plugin, edit the modules in hooks/ (register.tsx is the entry) and run /reload-plugins to load your changes. Before sending a change, run claude plugin validate . and claude plugin test ..
show-your-work is actively maintained. It is the first plugin to bring pictures, videos and automated visual QA with Playwright recordings into the Claude Code terminal. Its launch video has been viewed more than 275,000 times. It has since become the popular choice among developers who want to see what Claude builds without leaving the terminal. It's listed in some of the biggest Claude Code plugin catalogs and currently ranks among the top trending plugins for Claude Code.
If you want Claude Code to show you screenshots, screen recordings or before-and-after comparisons of its work without leaving the terminal, this plugin is built for exactly that.
MIT. Photography in the examples is from Unsplash, used under the Unsplash License. Privacy.
hooks/bundle.tsx 4315 lines1// Generated by tools/bundle.mjs from the modules in hooks/. Edit those, then
2// run `node tools/bundle.mjs`; this file is what hooks.json loads.
3
4import type { EngineInterface, Register, Timer } from 'claude-code'
5import type { Check, Frames, KeyChange, Overlay, Shown, Summary } from '../types'
6import { atom, read, update } from 'claude-code'
7
8// ── layout.ts ─────────────────────────────────────────────────────────────
9// Sizing, from the room a player has to the box it draws and the pixels its
10// picture needs, and the helpers that fit text to a width.
11
12
13// The window's fill: a step lighter than a dark terminal, so it reads as one panel.
14const PANEL = '#2c2e35'
15// The QA report beside the picture, and the width the window needs for it.
16export const SIDE = 40
17// The sidebar's fill: darker than the window, so the report stands apart.
18export const SIDEBAR = '#1d1e23'
19const WIDE_ENOUGH = 110
20
21// One path from the room a player has to the box it draws and the pixels its
22// picture needs:
23// layoutOf(room) the space: columns and rows for the picture, report beside or below
24// targetBox(w, h, ...) the box a picture of that shape fills in it
25// pixelsFor(box, cell) the screen pixels that box needs (PX_MIN to PX_MAX)
26// drawBox(w, h, ...) the box drawn: the target, cut down to the picture's own pixels
27// The terminal draws a picture at its own pixel size at most, so pictures and
28// frames are made as wide as their box (frameWidth when prepared, sharpen
29// when a player needs more), and drawBox keeps a picture that's still short
30// of pixels whole instead of small in a big box.
31const PX_MIN = 320
32export const PX_MAX = 2400
33export type Room = { columns: number; rows: number; isPane: boolean; hasReport: boolean }
34export type Layout = { isWide: boolean; inner: number; maxCols: number; maxRows: number }
35export function layoutOf(room: Room): Layout {
36 const isWide = room.hasReport && room.columns - 8 >= WIDE_ENOUGH
37 // The window's border and padding; a pane has no row border of its own.
38 const inner = room.columns - (room.isPane ? 6 : 10)
39 const space = inner - (isWide ? SIDE + 3 : 0)
40 // Picture size (settings): Large is Standard times SIZE_STEP, every limit
41 // scaled by the same fixed factor, so a picture's size stays predictable.
42 const step = sizeStep()
43 const maxCols = Math.max(1, Math.max(Math.min(space, 24), Math.min(space, Math.round((room.isPane ? 220 : 120) * step))))
44 // Inline, a picture takes at most 55% of the screen's height (82% in Large);
45 // a pane keeps 12 rows for its controls.
46 const fullRows = room.isPane ? Math.max(6, room.rows - 12) : Math.max(8, Math.min(Math.round(40 * step), Math.floor(room.rows * 0.55 * step)))
47 // iTerm2 draws a picture only while all of it is on screen: the player
48 // (title, picture, controls) fits in the window there.
49 const maxRows = state.terminalName === 'iterm2' && !room.isPane ? Math.max(6, Math.min(fullRows, room.rows - 16)) : fullRows
50 return { isWide, inner, maxCols, maxRows }
51}
52export const targetBox = (width: number, height: number, layout: Layout, px: Cell | null) =>
53 fit(width, height, layout.maxCols, layout.maxRows, px, false)
54export const drawBox = (width: number, height: number, layout: Layout, px: Cell | null) =>
55 fit(width, height, layout.maxCols, layout.maxRows, px, true)
56// Enough for the box's width and, given the picture's shape, its height:
57// boxes are whole rows, so a wide picture sized by width alone falls short.
58// Large (Picture size) scales every size limit by this one factor.
59export const SIZE_STEP = 1.5
60export const sizeStep = () => (settings.standard_size ? 1 : SIZE_STEP)
61export const pixelsFor = (box: { columns: number; rows?: number }, px: Cell | null, aspect = 0) =>
62 px ? Math.max(PX_MIN, Math.min(Math.round(PX_MAX * sizeStep()), Math.ceil(Math.max(box.columns * px.width, (box.rows ?? 0) * px.height * aspect) / 2) * 2)) : 1600
63
64// Fits a picture in a box of cells, its own shape. With the cell's size in
65// pixels known and `isCapped`, never past the picture's own pixels; unknown,
66// a cell is about twice as tall as wide.
67export function fit(width: number, height: number, maxCols: number, maxRows: number, px?: Cell | null, isCapped = true) {
68 if (px) {
69 const scale = Math.min(isCapped ? 1 : Number.POSITIVE_INFINITY, (maxCols * px.width) / width, (maxRows * px.height) / height)
70 // A hair over, so a box that fits exactly (38 rows, computed as 37.999…) keeps its last row.
71 const rows = Math.max(1, Math.min(255, Math.floor((height * scale) / px.height + 1e-9)))
72 const shown = isCapped ? Math.min(height, rows * px.height) : rows * px.height
73 const columns = Math.max(1, Math.min(255, maxCols, Math.ceil((shown * width) / height / px.width)))
74 return { columns, rows }
75 }
76 let columns = Math.max(1, Math.min(255, maxCols))
77 let rows = Math.ceil((columns * height) / width / 2)
78 if (rows > maxRows) {
79 rows = maxRows
80 columns = Math.max(1, Math.ceil((rows * 2 * width) / height))
81 }
82
83 return { columns: Math.min(255, columns), rows: Math.max(1, Math.min(255, rows)) }
84}
85
86// The width a picture or clip is made at when it's prepared: what an inline
87// player in this terminal needs (see layoutOf). 1600 px at most while unmeasured.
88export function frameWidth(width: number, height: number, term: { columns: number; rows: number } | null, px: Cell | null) {
89 if (!term || !px || !width || !height) return Math.min(1600, width)
90 const layout = layoutOf({ columns: term.columns, rows: term.rows, isPane: false, hasReport: false })
91 return pixelsFor(targetBox(width, height, layout, px), px, width / height)
92}
93
94// The drawn box for `room` columns already free of chrome (the pair view).
95export function sizeFor(width: number, height: number, room: number, rows: number, isPane: boolean, px: Cell | null = state.cell) {
96 return drawBox(width, height, layoutOf({ columns: room + (isPane ? 6 : 10), rows, isPane, hasReport: false }), px)
97}
98
99// The terminal's cell in pixels, from the size its tty reports; null where it
100// reports none (tmux, a relay), and measured again when the window changes.
101export type Cell = { width: number; height: number }
102export const CELL_SH = `perl -e 'open(T, "</dev/tty") or exit 1; my $w = " " x 8; ioctl(T, ($^O eq "darwin" ? 0x40087468 : 0x5413), $w) or exit 1; print join(" ", unpack("S4", $w))'`
103// The tty's size is in screen pixels in Ghostty, kitty and WezTerm (measured:
104// a 157-column Ghostty window on a 1280-point Retina screen reports 2520 px).
105// Multiplying it by the screen's scale, as 0.6.0 did, made every cell twice
106// its size, so pictures were made twice as wide as needed and, in Large, drawn
107// in boxes half as wide as they should be. A cell under POINT_CELL wide on a
108// Retina screen can only be points (no readable font is that narrow in
109// pixels), so only then is it scaled.
110const POINT_CELL = 10
111export function cellOf(stdout: string, scale = 1): Cell | null {
112 const [rows, columns, x, y] = stdout.trim().split(/\s+/).map(Number)
113 if (!(rows && columns && x && y)) return null
114 const unit = scale > 1 && x / columns < POINT_CELL ? scale : 1
115 return { width: (x / columns) * unit, height: (y / rows) * unit }
116}
117const SCALE_SH = `osascript -l JavaScript -e 'ObjC.import("AppKit"); $.NSScreen.mainScreen.backingScaleFactor'`
118export async function measureCells($: EngineInterface) {
119 const [r, s] = await Promise.all([
120 $.process.run(['sh', '-c', CELL_SH]).catch(() => null),
121 state.isMac ? $.process.run(['sh', '-c', SCALE_SH]).catch(() => null) : null,
122 ])
123 // A measure Claude Code cancelled (a newer draw replaced the one that asked,
124 // as happens many times while a window edge is dragged) says nothing about
125 // the terminal: the last size stands. Dropping it fell back to guessed 2:1
126 // cells, a picture of the wrong shape until the next resize.
127 if (!r) return void event('measure', { state: 'cancelled', kept: state.cell && `${state.cell.width.toFixed(2)}x${state.cell.height.toFixed(2)}` })
128 const scale = Number(s?.stdout.trim()) || 1
129 state.cell = r.exitCode === 0 ? cellOf(r.stdout, scale) : null
130 const [rows, columns] = (r.exitCode === 0 ? r.stdout : '').trim().split(/\s+/).map(Number)
131 state.termSize = rows && columns ? { columns, rows } : null
132 event('measure', { state: 'measured', tty: r.stdout.trim(), scale, cell: state.cell && `${state.cell.width.toFixed(2)}x${state.cell.height.toFixed(2)}` })
133}
134// Players of different widths each ask: one measure a second at most, the
135// last ask still measured.
136let measuredAt = 0
137export async function remeasure($: EngineInterface): Promise<boolean> {
138 const wait = measuredAt + 1000 - (await $.clock.now())
139 if (wait > 0) await $.clock.sleep(wait)
140 measuredAt = await $.clock.now()
141 const was = state.cell
142 await measureCells($)
143 return was?.width !== state.cell?.width || was?.height !== state.cell?.height
144}
145
146// The viewport is the whole screen; a docked pane is narrower and shorter, so
147// it sizes to its own body.
148export type PaneProps = { bodyColumns?: number; bodyRows?: number; scroll?: { bodyRows?: number } }
149export const paneSize = (viewport: { columns: number; rows: number } | undefined, props: PaneProps) => {
150 if (!viewport) return viewport
151 const rows = props.bodyRows ?? props.scroll?.bodyRows
152 return { columns: props.bodyColumns || viewport.columns, rows: rows || viewport.rows }
153}
154
155export const clock = (s: number) => `${Math.floor(Math.max(0, s) / 60)}:${String(Math.floor(Math.max(0, s) % 60)).padStart(2, '0')}`
156
157// One line, whatever the length: cut at a word, with … where it was cut.
158export function oneLine(text: string, width: number): string {
159 const flat = text.replace(/\s+/g, ' ').trim()
160 width = Math.max(4, Math.floor(width))
161 if (flat.length <= width) return flat
162 const cut = flat.slice(0, width - 1)
163 const space = cut.lastIndexOf(' ')
164 return `${(space > width / 2 ? cut.slice(0, space) : cut).replace(/[\s,.;:]+$/, '')}…`
165}
166
167// A tab name short enough that every tab fits on one line and stays clickable.
168export const tabLabel = (text: string, max = 12) => (text.length > max ? `${text.slice(0, max - 1).trimEnd()}…` : text)
169
170// Words wrapped to lines of at most width, so the whole text is always shown.
171export function wrapWords(text: string, width: number): string[] {
172 width = Math.max(1, Math.floor(width))
173 const lines: string[] = []
174 let line = ''
175 for (const word of text.split(/\s+/).filter(Boolean)) {
176 for (let w = word; w; ) {
177 const piece = w.length > width ? w.slice(0, width) : w
178 w = w.slice(piece.length)
179 if (!line) line = piece
180 else if (line.length + 1 + piece.length <= width) line += ` ${piece}`
181 else {
182 lines.push(line)
183 line = piece
184 }
185 }
186 }
187 return lines.length || line ? [...lines, line].filter(Boolean) : ['']
188}
189
190// Splits wrapped items into pages that each fit rows; an item never splits.
191export function pagesOf<T>(items: { item: T; rows: number }[], rows: number): T[][] {
192 const pages: T[][] = [[]]
193 let used = 0
194 for (const { item, rows: need } of items) {
195 if (used + need > rows && pages.at(-1)!.length) {
196 pages.push([])
197 used = 0
198 }
199 pages.at(-1)!.push(item)
200 used += need
201 }
202 return pages
203}
204
205// ── telemetry.ts ──────────────────────────────────────────────────────────
206// Anonymous usage stats and the button presses they count. The local debug
207// log is diagnostics.ts, kept apart so nothing in it is ever sent.
208
209
210// A button press, by name only. False, so it chains: act('save') || keep().
211export const act = (action: string): false => {
212 track('action', { action })
213 return false
214}
215
216// Anonymous usage stats, sent to PostHog: what kind of thing happened and how
217// often, under a random id made once per install. Never a file name, path,
218// URL, title, prompt or anything typed. Off with SHOW_YOUR_WORK_TELEMETRY=0 or
219// DO_NOT_TRACK=1, and nothing is sent while POSTHOG_PROJECT is empty.
220// PostHog's public project id for this plugin: it can only add events, never
221// read them, so it ships. The address is written out at the call, so the
222// directory review can read where the events go.
223const POSTHOG_PROJECT = 'phc_mLGFguVcH3Tei4txwqXFPU4xBgFDKThEZncahTv3LS3W'
224// Events wait here and go out together, at most once a minute and at exit.
225const FLUSH_MS = 60_000
226const MAX_QUEUED = 500
227
228export type Props = Record<string, string | number | boolean | null | undefined | Record<string, string | number | boolean | undefined>>
229export type Event = { event: string; properties: Props; timestamp: string }
230let installId = ''
231let base: Props = {}
232let isFlushing = false
233
234// A made-up name for an install, the same every time for one id, so profiles
235// read as "Swift Otter" rather than a UUID. Nothing in it comes from the person.
236const ADJECTIVES = ['Swift', 'Quiet', 'Brave', 'Clever', 'Sunny', 'Lucky', 'Bold', 'Calm', 'Eager', 'Gentle', 'Happy', 'Jolly', 'Keen', 'Lively', 'Mellow', 'Nimble', 'Plucky', 'Rapid', 'Snappy', 'Tidy', 'Witty', 'Zesty', 'Cosmic', 'Fuzzy']
237const ANIMALS = ['Otter', 'Falcon', 'Panda', 'Fox', 'Koala', 'Lynx', 'Heron', 'Badger', 'Gecko', 'Owl', 'Puffin', 'Raccoon', 'Seal', 'Tiger', 'Wombat', 'Yak', 'Bison', 'Crane', 'Dolphin', 'Ferret', 'Hedgehog', 'Lemur', 'Moose', 'Quokka']
238export function nicknameOf(id: string): string {
239 let hash = 0
240 for (const ch of id) hash = (hash * 31 + ch.charCodeAt(0)) >>> 0
241 const n = Math.floor(hash / ADJECTIVES.length) % 1000
242
243 return `${ADJECTIVES[hash % ADJECTIVES.length]} ${ANIMALS[Math.floor(hash / 1000) % ANIMALS.length]} ${n}`
244}
245
246// An installed copy runs from Claude Code's plugin cache. One loaded from a
247// folder (--plugin-dir) is someone working on the plugin: it sends nothing.
248export const isInstalledCopy = (root: string) => /\/plugins\/cache\//.test(root)
249
250// SHOW_YOUR_WORK_TELEMETRY=0, DO_NOT_TRACK=1 or CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC: nothing is sent.
251export const isStatsBlocked = (optOut?: string, dnt?: string, quiet?: string) =>
252 /^(0|false|off|no)$/i.test(optOut ?? '') || /^(1|true)$/i.test(dnt ?? '') || !!quiet
253
254export async function startTelemetry($: EngineInterface, context: Props) {
255 if (!POSTHOG_PROJECT || !isInstalledCopy($.plugin.root)) return
256 const optOut = await $.env.get('SHOW_YOUR_WORK_TELEMETRY')
257 const dnt = await $.env.get('DO_NOT_TRACK')
258 const quiet = await $.env.get('CLAUDE_CODE_DISABLE_NONESSENTIAL_TRAFFIC')
259 if (isStatsBlocked(optOut, dnt, quiet)) return
260 // Turned back on in the same session: the timer is already running.
261 if (installId) return void (state.isOn = true)
262 installId = String((await $.store.get('installId')) ?? '')
263 const isNew = !installId
264 if (isNew) {
265 installId = crypto.randomUUID()
266 await $.store.set('installId', installId)
267 }
268 state.isOn = true
269 // Each install is one anonymous person, keyed by its random id: the profile
270 // holds the setup it runs on, never anything about who uses it.
271 // No location, ever: no IP is sent, and PostHog is told not to look one up.
272 base = { ...context, $ip: null, $geoip_disable: true }
273 const profile = { $set: { ...context, name: nicknameOf(installId), update_channel: settings.stable_updates ? 'stable' : 'latest', usage_data: 'on' }, $set_once: { first_plugin_version: String(context.plugin_version ?? "") } }
274 if (isNew) track('installed', profile)
275 track('session_started', profile)
276 $.clock.every(FLUSH_MS, () => void flush($))
277}
278
279// Counts and kinds only: callers pass no names, paths or text.
280export function track(event: string, properties: Props = {}) {
281 if (!state.isOn) return
282 if (state.queue.length >= MAX_QUEUED) state.queue.shift()
283 state.queue.push({ event, properties: { ...base, ...properties }, timestamp: new Date().toISOString() })
284}
285
286export async function flush($: EngineInterface) {
287 if (!state.isOn || isFlushing || !state.queue.length) return
288 isFlushing = true
289 const batch = state.queue
290 state.queue = []
291 try {
292 const r = await $.http.fetch('https://us.i.posthog.com/batch/', {
293 method: 'POST',
294 headers: { 'content-type': 'application/json' },
295 body: JSON.stringify({ api_key: POSTHOG_PROJECT, batch: batch.map(e => ({ ...e, distinct_id: installId })) }),
296 })
297 // A refused batch is dropped, not retried: stats are never worth a backlog.
298 if (!r.ok && r.status >= 500) state.queue = [...batch, ...state.queue].slice(-MAX_QUEUED)
299 } catch {
300 state.queue = [...batch, ...state.queue].slice(-MAX_QUEUED)
301 } finally {
302 isFlushing = false
303 }
304}
305
306// ── media.ts ──────────────────────────────────────────────────────────────
307// Getting pictures and videos ready to draw: conversion, frames cut a chunk
308// at a time, the side-by-side clip of two runs, and the frame cache.
309
310
311
312// Deletes the oldest frame folders until the cache is under $1 KB, keeping the
313// newest two and the ones named in $2; only inside a folder this user owns.
314export const TRIM_SH = [
315 '[ -d "$0" ] && [ ! -L "$0" ] && [ -O "$0" ] && cd -P "$0" 2>/dev/null || exit 0',
316 // Only the folders the plugin names (v-<key>, v<n>-<time>, p-<key>,
317 // p2-<key>), one per line: a picture named by the user never matches.
318 'all=$(ls -dtr -- v* p* 2>/dev/null | grep -E "^(v-[0-9a-f]+|v[0-9]+-[0-9]+|p2?-[0-9a-f]+)$"); n=$(printf "%s\\n" "$all" | grep -c .)',
319 // Only these folders count against the cap: the stills beside them used to
320 // count too, so with enough of those every trim emptied the frame cache.
321 'size() { printf "%s\\n" "$all" | while IFS= read -r f; do [ -d "$f" ] && du -sk -- "$f"; done | awk \'{s += $1} END {print s + 0}\'; }',
322 'printf "%s\\n" "$all" | head -n $((n > 2 ? n - 2 : 0)) | while IFS= read -r d; do',
323 ' [ -n "$d" ] && [ -d "$d" ] || continue',
324 ' [ "$(size)" -le "$1" ] && break',
325 ' case " $2 " in *" $d "*) continue ;; esac',
326 // A folder changed in the last two minutes may be being cut into right
327 // now (a copy at another width of a playing video): never pulled away.
328 ' [ -n "$(find "./$d" -maxdepth 0 -mmin -2 2>/dev/null)" ] && continue',
329 ' [ -L "$d" ] || rm -rf "./$d"',
330 'done; true',
331].join('\n')
332// Deletes anything in the cache older than a week, without following links.
333export const CLEAN_SH = [
334 '[ -d "$0" ] && [ ! -L "$0" ] && [ -O "$0" ] || exit 0',
335 'find -P "$0" -mindepth 1 -maxdepth 1 -mtime +7 -exec rm -rf {} + 2>/dev/null; true',
336].join('\n')
337export const VIDEO = /\.(mp4|mov|m4v|webm|mkv|avi|gif)$/i
338// Frames a clip is cut into at most, and the rate it plays at below that.
339// A clip cut whole (no known length) keeps every frame on disk at once, so it
340// stays at MAX_FRAMES. One of known length is cut as it plays and only a few
341// chunks are ever on disk, so it can run to MAX_STREAMED at the full rate.
342const MAX_FRAMES = 900
343const MAX_STREAMED = 3600
344const MAX_FPS = 12
345
346// A typed or dragged-in path: quotes, backslash-escaped spaces and ~ allowed.
347export function expand(path: string, base: string, homeDir: string): string {
348 let p = path.trim().replace(/^(['"])(.*)\1$/, '$2').replace(/\\(.)/g, '$1')
349 if (p === '~' || p.startsWith('~/')) p = homeDir + p.slice(1)
350 if (p.startsWith('/')) return p
351
352 return `${base.replace(/\/$/, '')}/${p}`
353}
354
355// A name with its look-alike spaces made plain: macOS writes a narrow
356// no-break space before AM/PM in screenshot names, which a typed path lacks.
357export const looseName = (name: string) =>
358 name.normalize('NFC').replace(/[ - ]/g, ' ')
359
360// The file a path means: as given when it exists, else the one entry in its
361// folder whose name matches once spaces are made plain.
362export async function locate($: EngineInterface, raw: string): Promise<string> {
363 const path = expand(raw, state.cwd, state.home)
364 if (await $.fs.stat(path).then(() => true, () => false)) return path
365 const cut = path.lastIndexOf('/')
366 const dir = path.slice(0, cut) || '/'
367 const want = looseName(path.slice(cut + 1))
368 const hit = (await $.fs.list(dir).catch(() => [])).find(f => looseName(f.name) === want)
369
370 return hit ? `${dir.replace(/\/$/, '')}/${hit.name}` : path
371}
372
373export const frameFile = (frames: Frames, i: number) => `${frames.dir}/f${String(i + 1).padStart(5, '0')}.png`
374
375// How fast to sample a clip of known length so it stays under MAX_STREAMED.
376export const sampleRate = (duration: number) =>
377 Math.max(1, Math.min(MAX_FPS, Math.floor(MAX_STREAMED / Math.max(duration, 0.1))))
378
379// A PNG's size from its header (bytes 16 to 24), without any tool.
380export function pngDims(base64: string): { width: number; height: number } | null {
381 const b = Uint8Array.from(atob(base64.slice(0, 44)), c => c.charCodeAt(0))
382 if (b.length < 24 || b[0] !== 0x89 || b[1] !== 0x50 || b[2] !== 0x4e || b[3] !== 0x47) return null
383 const at = (i: number) => (((b[i] ?? 0) << 24) | ((b[i + 1] ?? 0) << 16) | ((b[i + 2] ?? 0) << 8) | (b[i + 3] ?? 0)) >>> 0
384
385 return { width: at(16), height: at(20) }
386}
387
388// Finds a pasted image's original file by name with Spotlight (macOS).
389export async function findPasted($: EngineInterface, name: string): Promise<string | null> {
390 if (name.startsWith('/')) return name
391 if (!state.isMac) return null
392 const found = await $.process.run(['mdfind', '-name', name])
393
394 return found.stdout.split('\n').find(line => line.endsWith(`/${name}`)) ?? null
395}
396
397export async function pngSize($: EngineInterface, png: string) {
398 if (!state.isMac) {
399 const d = pngDims(String((await $.fs.read(png, { as: 'bytes' }) as unknown as { base64: string }).base64 ?? ''))
400 if (!d || !d.width || !d.height) throw new Error(`not an image: ${png}`)
401 return d
402 }
403 const dims = await $.process.run(['sips', '-g', 'pixelWidth', '-g', 'pixelHeight', png])
404 const width = Number(/pixelWidth:\s*(\d+)/.exec(dims.stdout)?.[1] ?? 0)
405 const height = Number(/pixelHeight:\s*(\d+)/.exec(dims.stdout)?.[1] ?? 0)
406 if (!width || !height) throw new Error(`not an image: ${png}`)
407
408 return { width, height }
409}
410
411// Frames on disk are a cache: past 500 MB the oldest folders go, and a window
412// that plays one again decodes it again (ensureChunk). The newest two stay.
413const FRAMES_CAP_KB = 500_000
414// Folders this session is playing are never trimmed.
415export function trimFrames($: EngineInterface) {
416 const inUse = [...watching.keys()].map(d => d.split('/').pop()!).join(' ')
417 return $.process.run(['sh', '-c', TRIM_SH, state.TMP, String(FRAMES_CAP_KB), inUse]).catch(() => undefined)
418}
419
420// A recording often opens on a blank page while the browser loads: white,
421// off-white, grey or dark, maybe with a small spinner or logo. Any frame that
422// is nearly one flat tone counts as blank; the clip starts at the first real one.
423async function whiteLead($: EngineInterface, real: string, duration: number): Promise<number> {
424 const r = await $.process.run([state.ffmpeg, '-v', 'info', '-t', '8', '-i', real,
425 '-vf', 'fps=10,scale=160:-2,signalstats,metadata=print:key=lavfi.signalstats.YLOW:key=lavfi.signalstats.YHIGH',
426 '-an', '-f', 'null', '-']).catch(() => null)
427 return r ? leadFrom(r.stderr, duration) : 0
428}
429
430// The blank opening in that log: the time of the first frame whose 10th to
431// 90th percentile brightness spreads wider than a flat page does, if that
432// leaves something after it.
433export function leadFrom(log: string, duration: number): number {
434 let t = 0, low = -1
435 for (const line of log.split('\n')) {
436 const pts = line.match(/pts_time:([\d.]+)/)
437 if (pts) { t = Number(pts[1]); low = -1; continue }
438 const lo = line.match(/YLOW=([\d.]+)/)
439 if (lo) { low = Number(lo[1]); continue }
440 const hi = line.match(/YHIGH=([\d.]+)/)
441 if (hi && low >= 0) {
442 if (Number(hi[1]) - low > 24) {
443 const lead = Math.round(t * 100) / 100
444 return lead > 0 && (!(duration > 0) || lead < duration - 0.5) ? lead : 0
445 }
446 low = -1
447 }
448 }
449 return 0
450}
451
452// Times given on the clip as it was, moved to the frames that start after
453// its white opening.
454export function shiftTimes<T extends { at?: number }>(list: T[] | undefined, lead: number): T[] | undefined {
455 if (!list || !lead) return list
456 return list.map(c => (c.at === undefined ? c : { ...c, at: Math.max(0, +(c.at - lead).toFixed(2)) }))
457}
458
459// What to tell Claude and the person when a video can't be cut into frames.
460export const NO_FFMPEG =
461 "videos need ffmpeg, and it isn't installed. Pictures still work. Install it with `brew install ffmpeg` " +
462 '(Claude can run that for you), then restart Claude Code. No Homebrew? Install it first from https://brew.sh.'
463
464// On Linux ffmpeg also turns pictures other than PNG into PNG.
465export const NO_FFMPEG_LINUX =
466 "videos and pictures other than PNG need ffmpeg, and it isn't installed. Install it with your package manager, " +
467 'for example `sudo apt install ffmpeg` or `sudo dnf install ffmpeg` (Claude can run that for you), then restart Claude Code.'
468export const noFfmpeg = (mac: boolean) => (mac ? NO_FFMPEG : NO_FFMPEG_LINUX)
469export const FFMPEG_PROMPT_LINUX =
470 "Install ffmpeg for me with this machine's package manager (for example `sudo apt install ffmpeg`). Then show it again."
471
472// What the person pastes back so Claude installs ffmpeg and tries again.
473export const FFMPEG_PROMPT =
474 'Install ffmpeg for me with `brew install ffmpeg`. If Homebrew isn\'t installed, tell me how to install it first. Then show the video again.'
475
476// A failure as the person and Claude see it: a box in place of the picture,
477// one plain message for Claude, and a prompt to paste back. Never raw tool
478// output, never the plugin's internal copy of a file.
479export type NoticeKind = 'missing' | 'not_image' | 'broken_video' | 'no_picture' | 'no_ffmpeg' | 'other'
480export type Notice = { kind: NoticeKind; title: string; text: string; message: string; prompt: string }
481
482// How a failure reads, from whatever the tools said; `path` is the person's own.
483export function noticeOf(err: unknown, path: string, homeDir = ''): Notice {
484 const raw = String((err as Error)?.message ?? err)
485 const shown = homeDir && path.startsWith(`${homeDir}/`) ? `~${path.slice(homeDir.length)}` : path
486 const name = path.split('/').pop() || path
487 if (raw.includes(NO_FFMPEG_LINUX)) return {
488 kind: 'no_ffmpeg', title: 'This needs ffmpeg', message: NO_FFMPEG_LINUX, prompt: FFMPEG_PROMPT_LINUX,
489 text: "ffmpeg isn't installed, so videos and pictures other than PNG can't show here. Copy the prompt and paste it to Claude to install it, or install it yourself, for example `sudo apt install ffmpeg`.",
490 }
491 if (raw.includes(NO_FFMPEG)) return {
492 kind: 'no_ffmpeg', title: 'Videos need ffmpeg', message: NO_FFMPEG, prompt: FFMPEG_PROMPT,
493 text: "ffmpeg isn't installed, so this video can't play here. Pictures still work. Copy the prompt and paste it to Claude to install it, or run `brew install ffmpeg` yourself. No Homebrew? Get it from brew.sh first.",
494 }
495 if (/does not contain any stream|matches no streams|no frames in|Output file is empty/i.test(raw)) return {
496 kind: 'no_picture', title: 'This video has no picture',
497 text: `${name} has sound but no picture, so there's nothing to play.`,
498 message: `${shown} has no video track (sound only), so there's nothing to play. Don't retry it; show a file with a picture instead.`,
499 prompt: `${shown} has no picture, only sound. Find the right video and show it to me again.`,
500 }
501 if (/ffmpeg could not read|Invalid data|moov atom|could not find codec|Error opening input/i.test(raw)) return {
502 kind: 'broken_video', title: "This video can't be read",
503 text: `${name} couldn't be opened as a video. It may be cut off, still being written, or not really a video.`,
504 message: `${shown} couldn't be read as a video: it's damaged, unfinished (still recording or cut off), or not a video. Re-export or re-record it, then show it again.`,
505 prompt: `${shown} couldn't be read as a video. Check it, re-export or re-record it if it's broken, then show it to me again.`,
506 }
507 if (/could not convert|not an image|Cannot extract image|sips/i.test(raw)) return {
508 kind: 'not_image', title: "This isn't a picture",
509 text: `${name} isn't a picture, so it can't be shown. Pictures can be PNG, JPEG, WebP, GIF or TIFF.`,
510 message: `${shown} isn't a picture (show_image opens PNG, JPEG, WebP, GIF and TIFF). Show an image file, or use show_video for a video.`,
511 prompt: `${shown} isn't a picture. Show me the right file instead.`,
512 }
513 if (/ENOENT|no such file|not found/i.test(raw)) return {
514 kind: 'missing', title: 'File not found',
515 text: `There's no file at ${shown}.`,
516 message: `There's no file at ${shown}. Check the path (it may have moved or not been saved yet), then show it again.`,
517 prompt: `There's no file at ${shown}. Find the right file and show it to me again.`,
518 }
519 const detail = (raw.split('\n')[0] ?? '').replace(/\/(?:private\/)?tmp\/\S+|\S*\/\.show-your-work\/\S+/g, name).slice(0, 160)
520 return {
521 kind: 'other', title: "Couldn't show it",
522 text: `${name} couldn't be shown: ${detail}`,
523 message: `${shown} couldn't be shown: ${detail}`,
524 prompt: `${shown} couldn't be shown (${detail}). Look into it and show it to me again.`,
525 }
526}
527
528// The usage-stats reason for a failure, as a kind.
529export const REASONS: Record<NoticeKind, string> = {
530 missing: 'missing_file', no_ffmpeg: 'video_tools', not_image: 'unreadable', broken_video: 'unreadable', no_picture: 'unreadable', other: 'other',
531}
532
533// Cuts a clip into PNG frames the terminal can swap through.
534// A file as it is now: its path, size and modified time. The same unchanged
535// file shown again maps to the same frames folder and skips the decode; a
536// re-rendered one gets a new key and decodes fresh.
537export function keyOf(text: string): string {
538 let hash = 5381
539 for (let i = 0; i < text.length; i++) hash = ((hash << 5) + hash + text.charCodeAt(i)) >>> 0
540 return hash.toString(16).padStart(8, '0') + text.length.toString(16)
541}
542export async function identityOf($: EngineInterface, raw: string): Promise<string | undefined> {
543 const st = await $.fs.stat(expand(raw, state.cwd, state.home), { resolve: true }).catch(() => null)
544 return st ? keyOf(`${st.realPath ?? raw}|${st.size}|${st.mtimeMs}`) : undefined
545}
546// What a folder's meta.json holds, unchecked: the caller says what it expects.
547// (No type argument at the call: the directory review reads only fn($, ...).)
548async function readMeta($: EngineInterface, dir: string): Promise<unknown> {
549 const r = await $.process.run(['cat', `${dir}/meta.json`]).catch(() => null)
550 if (!r || r.exitCode !== 0) return null
551 try { return JSON.parse(r.stdout) as unknown } catch { return null }
552}
553function writeMeta($: EngineInterface, dir: string, meta: unknown) {
554 return $.process.run(['sh', '-c', 'printf "%s" "$1" > "$0/meta.json"', dir, JSON.stringify(meta)]).catch(() => undefined)
555}
556
557export async function prepareVideo($: EngineInterface, real: string, title: string, key?: string, cutAt?: number): Promise<Shown> {
558 if (!state.hasVideoTools) {
559 state.hasVideoTools = (await Promise.all([exists($, state.ffmpeg), exists($, state.ffprobe)])).every(Boolean)
560 if (!state.hasVideoTools) throw new Error(noFfmpeg(state.isMac))
561 }
562 const facts = await $.process.run([state.ffprobe, '-v', 'error', '-select_streams', 'v:0', '-show_entries', 'stream=width,height:format=duration', '-of', 'default=nw=1', real])
563 const field = (name: string) => Number(new RegExp(`^${name}=([0-9.]+)`, 'm').exec(facts.stdout)?.[1] ?? Number.NaN)
564 // Frames stay within PX_MAX in every Picture size (see sharpen).
565 const cut = Math.min(PX_MAX, cutAt ?? frameWidth(field('width'), field('height'), state.termSize, state.cell))
566 const own = field('width') > 0 && field('height') > 0 ? { sourceWidth: field('width'), sourceHeight: field('height') } : {}
567 // A clip is cut once per width: a bigger window cuts it again, bigger.
568 const folder = key && `v-${keyOf(`${key}|${cut}${state.sendBytes ? '|bytes' : ''}`)}`
569 // The same file shown before: its folder, frames and size are already there.
570 if (folder) {
571 const dir = `${state.TMP}/${folder}`
572 const meta = (await readMeta($, dir)) as { frames: Omit<Frames, 'dir'>; width: number; height: number } | null
573 if (meta) {
574 const frames = { ...meta.frames, dir }
575 await $.process.run(['touch', dir]).catch(() => undefined)
576 await ensureChunk($, frames, real, 0)
577 await prefill($, frames, real)
578 return { kind: 'video', path: frameFile(frames, 0), source: real, width: meta.width, height: meta.height, ...own, title, generation: ++state.generation, frames }
579 }
580 }
581 // Some recordings (MediaRecorder webm) carry no duration: sample those at the
582 // top rate. The clip's length is then what the frames cover.
583 const probed = field('duration')
584 const fps = sampleRate(Number.isFinite(probed) && probed > 0 ? probed : 1)
585 state.generation += 1
586 const dir = folder ? `${state.TMP}/${folder}` : `${state.TMP}/v${state.generation}-${Math.floor(await $.clock.now())}`
587 await $.process.run(['mkdir', '-p', dir])
588 const lead = await whiteLead($, real, probed)
589 const known = Number.isFinite(probed) && probed > 0
590 // A clip of known length is decoded as it plays, a chunk at a time (see
591 // ensureChunk); one without (MediaRecorder webm) is cut whole, as before.
592 const total = known ? Math.max(1, Math.min(MAX_STREAMED, Math.floor((probed - lead) * fps))) : 0
593 const pngsIn = async () => (await $.fs.list(dir)).filter(f => f.name.endsWith('.png')).map(f => `${dir}/${f.name}`)
594 const made = await cutFrames($, isFew => [
595 // The palette waits for the end of its input: only the first chunk is read.
596 state.ffmpeg, '-v', 'error', ...(lead ? ['-ss', String(lead)] : []), ...(known ? ['-t', chunkSeconds(Math.min(CHUNK, total), fps)] : []), '-i', real,
597 '-vf', `fps=${fps},${scaleFor(cut, isFew)}`,
598 '-frames:v', String(known ? Math.min(CHUNK, total) : MAX_FRAMES), '-compression_level', '1', '-y', `${dir}/f%05d.png`,
599 ], pngsIn)
600 if (made.exitCode !== 0) throw new Error(`ffmpeg could not read ${real}: ${made.stderr.trim().slice(0, 200)}`)
601 const pngs = (await $.fs.list(dir)).filter(f => f.name.endsWith('.png')).length
602 if (!pngs) throw new Error(`no frames in ${real}`)
603 const count = known ? Math.max(pngs, total) : pngs
604 const frames = { dir, count, fps, duration: count / fps, cut, ...(lead ? { lead } : {}) }
605 const poster = frameFile(frames, 0)
606
607 const size = await pngSize($, poster)
608 if (folder) await writeMeta($, dir, { frames: { count, fps, duration: frames.duration, cut, ...(lead ? { lead } : {}) }, ...size })
609 void trimFrames($)
610 if (known) await prefill($, frames, real)
611 return { kind: 'video', path: poster, source: real, ...size, ...own, title, generation: state.generation, frames }
612}
613
614// The same clip at another width, for a resized window. Its facts (rate,
615// length, lead-in) are already known, so only the chunk on screen is cut
616// (about 0.3 s) instead of preparing the clip again from its start, which
617// took seconds and cut the wrong part first. The folder is the one
618// prepareVideo would use for that width, so either finds the other's frames.
619export async function rescaleVideo($: EngineInterface, m: Shown, width: number, at: number): Promise<Shown | null> {
620 const f = m.frames
621 const source = m.source
622 if (!f || !source) return null
623 const key = await identityOf($, source)
624 const dir = `${state.TMP}/v-${keyOf(`${key}|${width}${state.sendBytes ? '|bytes' : ''}`)}`
625 const frames: Frames = { ...f, dir, cut: width }
626 const i = Math.max(0, Math.min(at, f.count - 1))
627 await $.process.run(['mkdir', '-p', dir])
628 await ensureChunk($, frames, source, i)
629 const shown = frameFile(frames, i)
630 if (await isGone($, shown)) return null
631 const size = await pngSize($, shown)
632 await writeMeta($, dir, { frames: { count: f.count, fps: f.fps, duration: f.duration, cut: width, ...(f.lead ? { lead: f.lead } : {}) }, ...size })
633 void trimFrames($)
634 return { ...m, path: shown, ...size, generation: ++state.generation, frames }
635}
636
637// Frames are decoded from the clip as it plays, 24 at a time: the chunk on
638// screen and the ones a 5 s skip either way reaches stay on disk, the rest
639// go. A frame asked for again further away (a long seek, a window scrolled
640// back to) is decoded again. The poster, frame 1, always stays.
641const CHUNK = 24
642// Every chunk is cut at normal priority. Chunks two or more ahead used to be
643// cut at macOS's utility class (nice 10 on Linux) to give way to other work,
644// but with every core busy macOS starves that class outright: a chunk never
645// finished, and when playback reached it, it waited on that cut and froze
646// for good (#14). Cutting only runs while a video plays, 5 s ahead at most.
647// Chunks are cut with ffmpeg's default threads, one cut at a time (see
648// cutAhead). One thread each looked enough on a plain test clip (1 s at
649// 2400 px in 0.85 s), but real footage is far heavier: a 72 Mbit/s 1080p
650// H.264 export with keyframes up to 3 s apart took 4.9 s per 2 s chunk on
651// one thread (7.7 s with every core busy), so playback waited on every chunk
652// and ran in slow motion (#14). Default threads: 1.4 s (2.4 s busy), at about
653// 310 MB peak instead of 133 MB. The side-by-side clip still uses one thread.
654const ONE_THREAD = ['-threads', '1', '-filter_threads', '1']
655const decoding = new Map<string, Promise<void>>()
656export function exists($: EngineInterface, file: string) {
657 return $.fs.stat(file).then(() => true, () => false)
658}
659// Gone only when the disk says so; no answer at all (no fs here) is not gone.
660export function isGone($: EngineInterface, file: string) {
661 return $.fs.stat(file).then(() => false, (e: unknown) => /ENOENT|not found|no such file/i.test(String((e as Error)?.message ?? e)))
662}
663
664// Chunks whose frames were cut: playback waits on any other. Only a hint:
665// cutting still checks the files, so a chunk the cache cleaner took comes back.
666const cutChunks = new Set<string>()
667const chunkKey = (f: Frames, i: number) => `${f.dir}#${Math.floor(Math.max(0, Math.min(i, f.count - 1)) / CHUNK)}`
668export const isFrameCut = (media: Shown, i: number) => !media.frames || cutChunks.has(chunkKey(media.frames, i))
669
670// A frame that should be on disk isn't (the temp folder was cleaned, or the
671// cache trimmed): forget its chunk was cut and cut it again from the source.
672// False when the source itself is gone too.
673export async function recutFrame($: EngineInterface, media: Shown, i: number): Promise<boolean> {
674 const f = media.frames
675 if (!f || !media.source || (await isGone($, media.source))) return false
676 await $.process.run(['mkdir', '-p', f.dir]).catch(() => undefined)
677 cutChunks.delete(chunkKey(f, i))
678 await ensureChunk($, f, media.source, i)
679 return !(await isGone($, frameFile(f, Math.min(i, f.count - 1))))
680}
681
682// A terminal that refuses a picture file draws an empty box, and nothing comes
683// back to say so. Ghostty and kitty read any file up to 400 MB (checked in
684// their source), inside tmux too. Others may not: Orca reads one only from a
685// temp folder or the terminal's own worktree, and only up to 2 MiB (#16).
686// Elsewhere a still is drawn from a temp-folder copy under 2 MB (pngSource),
687// and a chunk with a frame over it is cut again in 256 colours (cutFrames).
688const READS_ANY_FILE = new Set(['ghostty', 'kitty'])
689export const readsAnyFile = () => READS_ANY_FILE.has(state.terminalName) || READS_ANY_FILE.has(state.outerTerminal)
690export const BYTES_MAX = 2_000_000
691// Over ssh every frame crosses as bytes: 256 colours, one palette per chunk,
692// no dithering, halve them. Frames on this machine go by path in full colour.
693const PALETTE = ',split[a][b];[a]palettegen[p];[b][p]paletteuse=dither=none'
694// How much of the clip a chunk reads, a frame's slack included.
695export const chunkSeconds = (frames: number, fps: number) => String(+((frames + 1) / fps).toFixed(3))
696const scaleFor = (cut: number | undefined, isFew: boolean) => (cut ? `scale=${cut}:-2` : "scale='min(1600,iw)':-2") + (isFew ? PALETTE : '')
697// Runs a cut. Outside Ghostty and kitty, a frame over BYTES_MAX may not draw,
698// so the rare chunk with one (a very wide window, grainy footage) is cut again
699// in 256 colours. Every other chunk keeps full colour; the check is a stat per
700// frame and no process.
701async function cutFrames($: EngineInterface, cut: (isFew: boolean) => string[], files: () => Promise<string[]>) {
702 const made = await $.process.run(cut(state.sendBytes))
703 if (made.exitCode !== 0 || state.sendBytes || readsAnyFile()) return made
704 const sizes = await Promise.all((await files()).map(f => Promise.resolve().then(() => $.fs.stat(f)).then(st => st.size, () => 0)))
705 if (!sizes.some(size => size > BYTES_MAX)) return made
706 debug('cut again in 256 colours: a frame is over 2 MB')
707 return $.process.run(cut(true))
708}
709
710function ensureChunk($: EngineInterface, f: Frames, source: string | undefined, i: number): Promise<void> {
711 const c = Math.floor(Math.max(0, Math.min(i, f.count - 1)) / CHUNK)
712 const key = `${f.dir}#${c}`
713 const running = decoding.get(key)
714 if (running) return running
715 const job = (async () => {
716 const first = c * CHUNK
717 // The frame asked for, not the chunk's first: the poster outlives its chunk.
718 if (await exists($, frameFile(f, Math.max(0, Math.min(i, f.count - 1))))) return
719 if (!source) return
720 const cutAt = Date.now()
721 await $.process.run(['mkdir', '-p', f.dir])
722 const n = Math.min(CHUNK, f.count - first)
723 const cutChunk = (isFew: boolean) => [
724 state.ffmpeg, '-v', 'error', '-ss', String(+((f.lead ?? 0) + first / f.fps).toFixed(3)), '-t', chunkSeconds(n, f.fps), '-i', source,
725 '-vf', `fps=${f.fps},${scaleFor(f.cut, isFew)}`, '-frames:v', String(n),
726 '-start_number', String(first + 1), '-compression_level', '1', '-y', `${f.dir}/f%05d.png`,
727 ]
728 await cutFrames($, cutChunk, async () => Array.from({ length: n }, (_, k) => frameFile(f, first + k)))
729 debug(`cut chunk=${c} ms=${Date.now() - cutAt}`)
730 await prune($, f.dir, c, f.fps)
731 })().then(() => { cutChunks.add(key) }, () => undefined).finally(() => decoding.delete(key))
732 decoding.set(key, job)
733 return job
734}
735
736// Where each player is in each frames folder, as a chunk number.
737const watching = new Map<string, Map<string, number>>()
738function watch(dir: string, site: string, i: number) {
739 let at = watching.get(dir)
740 if (!at) watching.set(dir, (at = new Map()))
741 at.set(site, Math.floor(i / CHUNK))
742}
743
744// Chunks 5 s behind the playhead stay on disk and 5 s ahead are cut in
745// advance, so « 5s and 5s » land on frames that are ready, and playback has
746// room to spare when cutting runs slower than the clip.
747const BEHIND_SECONDS = 5
748const AHEAD_SECONDS = 5
749const chunksFor = (seconds: number, fps: number) => Math.max(1, Math.ceil((seconds * fps) / CHUNK))
750export const chunksBehind = (fps: number) => chunksFor(BEHIND_SECONDS, fps)
751export const chunksAhead = (fps: number) => chunksFor(AHEAD_SECONDS, fps)
752
753// Keeps, in a frames folder, the chunks a skip back or forward reaches around
754// the chunk just made and around every player on that folder, and the poster.
755async function prune($: EngineInterface, dir: string, c: number, fps: number) {
756 const keep = [c, ...(watching.get(dir)?.values() ?? [])]
757 const behind = chunksBehind(fps)
758 const ahead = chunksAhead(fps) + 1
759 const files = await $.fs.list(dir).catch(() => [])
760 const gone = files.map(f => f.name).filter(name => {
761 const m = /^f(\d+)\.png$/.exec(name)
762 if (!m) return false
763 const i = Number(m[1]) - 1
764 return i > 0 && !keep.some(k => i >= (k - behind) * CHUNK && i < (k + ahead + 1) * CHUNK)
765 })
766 if (gone.length) {
767 for (const k of [...cutChunks]) if (k.startsWith(`${dir}#`) && !keep.some(c2 => { const j = Number(k.slice(dir.length + 1)); return j >= c2 - behind && j <= c2 + ahead })) cutChunks.delete(k)
768 await $.process.run(['rm', '-f', ...gone.map(n => `${dir}/${n}`)]).catch(() => undefined)
769 }
770}
771
772// The frame a side shows, decoded if it has to be; then the chunks a 5s »
773// reaches are cut ahead, one at a time so a busy machine isn't swamped.
774export async function frameReady($: EngineInterface, media: Shown, i: number, site?: string): Promise<void> {
775 const f = media.frames
776 if (!f) return
777 if (site) watch(f.dir, site, i)
778 await ensureChunk($, f, media.source, i)
779 void cutAhead($, f, media.source, i)
780}
781
782// One cut at a time, nearest first: each already uses every core, and two
783// at once would double the memory for no gain.
784const CUT_WORKERS = 1
785const cuttingAhead = new Set<string>()
786async function cutAhead($: EngineInterface, f: Frames, source: string | undefined, i: number) {
787 if (cuttingAhead.has(f.dir)) return
788 cuttingAhead.add(f.dir)
789 try {
790 const todo: number[] = []
791 for (let d = 1; d <= chunksAhead(f.fps); d++) {
792 const j = i + d * CHUNK
793 if (j >= f.count) break
794 if (!cutChunks.has(chunkKey(f, j))) todo.push(j)
795 }
796 let taken = 0
797 const worker = async () => {
798 while (taken < todo.length) {
799 await ensureChunk($, f, source, todo[taken++]!)
800 }
801 }
802 await Promise.all(Array.from({ length: CUT_WORKERS }, worker))
803 } finally {
804 cuttingAhead.delete(f.dir)
805 }
806}
807
808// Before a video is shown, the first 5 s ahead are cut too, so playback
809// starts with room to spare. Never more than PREFILL_MS of waiting.
810const PREFILL_MS = 4000
811async function prefill($: EngineInterface, f: Frames, source: string | undefined) {
812 await Promise.race([cutAhead($, f, source, 0), $.clock.sleep(PREFILL_MS)]).catch(() => undefined)
813}
814
815// Moments both runs share (a check by the same name), as [updated, original]
816// seconds, kept only while both clocks move forward.
817export function anchors(updated: Check[] = [], original: Check[] = []): [number, number][] {
818 const at = new Map(original.filter(c => c.at !== undefined).map(c => [c.name, c.at!]))
819 const pairs = updated
820 .filter(c => c.at !== undefined && at.has(c.name))
821 .map(c => [c.at!, at.get(c.name)!] as [number, number])
822 .sort((a, b) => a[0] - b[0])
823 const kept: [number, number][] = []
824 for (const p of pairs) {
825 const last = kept.at(-1) ?? [0, 0]
826 if (p[0] > last[0] + 0.05 && p[1] > last[1] + 0.05) kept.push(p)
827 }
828
829 return kept
830}
831
832// The original clip's moment that matches a moment of the updated clip.
833export function mapTime(points: [number, number][], t: number, endA: number, endB: number): number {
834 const all: [number, number][] = [[0, 0], ...points, [endA, endB]]
835 for (let i = 1; i < all.length; i++) {
836 const [a0, b0] = all[i - 1]!
837 const [a1, b1] = all[i]!
838 if (t <= a1 || i === all.length - 1) {
839 const k = a1 > a0 ? (b1 - b0) / (a1 - a0) : 1
840 return Math.max(0, Math.min(endB, b0 + (t - a0) * k))
841 }
842 }
843
844 return t
845}
846
847// Maps a frame of one clip to the frame at the same moment in another.
848export function sameMoment(from: Frames | undefined, to: Frames | undefined, frame: number): number {
849 if (!from || !to) return 0
850
851 return Math.max(0, Math.min(to.count - 1, Math.round((frame / from.fps) * to.fps)))
852}
853
854// The same moment on the other clip: updated → original seconds, and back.
855export const toOriginal = (shown: Shown, t: number) =>
856 shown.frames && shown.compare?.frames
857 ? mapTime(shown.sync ?? anchors(shown.checks, shown.compare.checks), t, shown.frames.duration, shown.compare.frames.duration)
858 : t
859export const toUpdated = (shown: Shown, t: number) =>
860 shown.frames && shown.compare?.frames
861 ? mapTime((shown.sync ?? anchors(shown.checks, shown.compare.checks)).map(([a, b]) => [b, a] as [number, number]), t, shown.compare.frames.duration, shown.frames.duration)
862 : t
863
864// The compared side's frame at the moment the shown side is at.
865export const compareFrame = (shown: Shown, frame: number) => {
866 const a = shown.frames, b = shown.compare?.frames
867 if (!a || !b) return 0
868 const t = mapTime(shown.sync ?? anchors(shown.checks, shown.compare?.checks), frame / a.fps, a.duration, b.duration)
869 return Math.max(0, Math.min(b.count - 1, Math.round(t * b.fps)))
870}
871
872// Every `stride`-th frame as a 32×18 grey thumbnail, for matching the two
873// runs by eye. Small and sparse on purpose: matching costs frames × frames.
874async function thumbs($: EngineInterface, media: Shown, stride: number): Promise<number[][]> {
875 const f = media.frames!
876 const r = await $.process.run([
877 'sh', '-c',
878 `"$0" -v error ${f.lead ? `-ss ${f.lead} ` : ''}-i "$1" -vf "fps=${f.fps},select=not(mod(n\\,${stride})),scale=32:18,format=gray" -fps_mode passthrough -frames:v ${Math.ceil(f.count / stride)} -f rawvideo - | od -An -tu1 -v`,
879 state.ffmpeg, media.source ?? '',
880 ])
881 const px = r.stdout.trim().split(/\s+/).map(Number)
882 const out: number[][] = []
883 for (let i = 0; i + 576 <= px.length; i += 576) out.push(px.slice(i, i + 576))
884 return out
885}
886
887// How many frames apart to sample so neither run has more than 240.
888export const strideFor = (a: number, b: number) => Math.max(1, Math.ceil(Math.max(a, b) / 240))
889
890// A match made on sampled frames, spread back over every updated frame.
891export function spreadMatch(sampled: number[], stride: number, count: number, last: number): number[] {
892 return Array.from({ length: count }, (_, i) => {
893 const k = Math.min(sampled.length - 1, Math.floor(i / stride))
894 return Math.min(last, (sampled[k] ?? 0) * stride + (i % stride))
895 })
896}
897
898// What moved since the previous frame: the cursor, a fade, a scroll. The two
899// runs move the same way even where the designs differ.
900const motion = (f: number[][]) => f.map((px, i) => (i ? px.map((v, k) => v - f[i - 1]![k]!) : px.map(() => 0)))
901
902// The cheapest way to walk both runs in order, frame by frame (dynamic time
903// warping), matching how frames look and how they move: [updated, original]
904// frame pairs. Holding one side still costs a little, so it only holds where
905// the runs really differ. Within `band` samples of the same moment only, and
906// straying from it costs `drift`: two runs of the same steps keep time, so a
907// screen that looks different in one (an error the other never shows) can't
908// pull one side ahead of the other.
909export function align(a: number[][], b: number[][], hold = 0.01, band = Number.POSITIVE_INFINITY, drift = 0): [number, number][] {
910 const n = a.length, m = b.length
911 if (!n || !m) return []
912 const slope = n > 1 ? (m - 1) / (n - 1) : 0
913 // Typed rows: the inner loop runs n × m × pixels times.
914 const ta = a.map(x => Int16Array.from(x)), tb = b.map(x => Int16Array.from(x))
915 const ma = motion(a).map(x => Int16Array.from(x)), mb = motion(b).map(x => Int16Array.from(x))
916 const diff = (i: number, j: number) => {
917 let d = 0, e = 0
918 const pa = ta[i]!, pb = tb[j]!, qa = ma[i]!, qb = mb[j]!
919 for (let k = 0; k < pa.length; k++) {
920 const x = pa[k]! - pb[k]!, y = qa[k]! - qb[k]!
921 d += x < 0 ? -x : x
922 e += y < 0 ? -y : y
923 }
924 return (d + 4 * e) / (pa.length * 255)
925 }
926 const cost = new Float64Array(n * m)
927 const step = new Uint8Array(n * m) // 0 both, 1 updated only, 2 original only
928 for (let i = 0; i < n; i++) {
929 for (let j = 0; j < m; j++) {
930 const off = Math.abs(j - i * slope)
931 if (off > band && !(i === n - 1 && j === m - 1) && (i || j)) { cost[i * m + j] = Number.POSITIVE_INFINITY; step[i * m + j] = 0; continue }
932 const d = diff(i, j) + drift * off
933 if (!i && !j) { cost[0] = d; continue }
934 const both = i && j ? cost[(i - 1) * m + j - 1]! : Number.POSITIVE_INFINITY
935 const up = i ? cost[(i - 1) * m + j]! + hold : Number.POSITIVE_INFINITY
936 const left = j ? cost[i * m + j - 1]! + hold : Number.POSITIVE_INFINITY
937 const best = Math.min(both, up, left)
938 cost[i * m + j] = best + d
939 step[i * m + j] = best === both ? 0 : best === up ? 1 : 2
940 }
941 }
942 const path: [number, number][] = []
943 for (let i = n - 1, j = m - 1; ; ) {
944 path.push([i, j])
945 if (!i && !j) break
946 const s = step[i * m + j]
947 if (s === 0) { i--; j-- } else if (s === 1) i--
948 else j--
949 }
950 return path.reverse()
951}
952
953// For each updated frame, the original frame shown beside it.
954export function matchOf(path: [number, number][], count: number): number[] {
955 const out = new Array<number>(count).fill(0)
956 for (const [i, j] of path) if (i < count) out[i] = j
957 for (let i = 1; i < count; i++) out[i] = Math.max(out[i]!, out[i - 1]!)
958 return out
959}
960
961// The path cut to the few turns that matter, in seconds, to keep it small.
962export function turns(match: number[], fpsA: number, fpsB: number): [number, number][] {
963 const points: [number, number][] = []
964 for (let i = 1; i < match.length - 1; i++) {
965 const before = match[i]! - match[i - 1]!, after = match[i + 1]! - match[i]!
966 if ((before === 0) !== (after === 0) || Math.abs(before - after) > 1) points.push([+(i / fpsA).toFixed(2), +(match[i]! / fpsB).toFixed(2)])
967 }
968 return points.length > 40 ? points.filter((_, k) => k % Math.ceil(points.length / 40) === 0) : points
969}
970
971// The largest still kept whole.
972export const MAX_STILL = 3200
973
974// Pixels between Original and Updated in the merged clip.
975export const PAIR_GAP = 40
976// How tall the merged clip is cut: the shorter side's height, 720 px at most.
977// The terminal never draws a picture larger than it is, so 360 px kept the
978// side by side view small in any window.
979export const pairHeightOf = (updated: { height: number }, original: { height: number }) =>
980 Math.max(2, Math.floor(Math.min(720, updated.height || 720, original.height || 720) / 2) * 2)
981
982// Merges the original and updated recordings into one clip, side by side.
983// The original's frames are matched to the updated clip's by how they look,
984// so every step happens at the same moment on both sides.
985export async function preparePair($: EngineInterface, original: Shown, updated: Shown) {
986 const f = updated.frames!, g = original.frames!
987 state.generation += 1
988 // p2: pairs made before the time-first matching are never reused.
989 const dir = `${state.TMP}/p2-${keyOf(`${f.dir}|${g.dir}|${pairHeightOf(updated, original)}`)}`
990 type PairMeta = { pair: Omit<Frames, 'dir'>; pairWidth: number; pairHeight: number; sync: [number, number][] }
991 const known = (await readMeta($, dir)) as PairMeta | null
992 if (known) {
993 const pair = { ...known.pair, dir }
994 await $.process.run(['touch', dir]).catch(() => undefined)
995 await pairChunk($, pair, updated, original, i => compareFrame({ ...updated, compare: original, sync: known.sync }, i), 0)
996 return { pair, pairWidth: known.pairWidth, pairHeight: known.pairHeight, sync: known.sync }
997 }
998 // Two runs of the same steps take about as long: then the same moment on
999 // both sides is the same second (moved to the checks' own moments when
1000 // they're given). Only runs that differ a lot are matched by how they look.
1001 const byTime = () => Array.from({ length: f.count }, (_, i) => Math.min(g.count - 1, Math.round(mapTime(anchors(updated.checks, original.checks), i / f.fps, f.duration, g.duration) * g.fps)))
1002 const isSamePace = Math.abs(f.duration - g.duration) <= 0.15 * Math.max(f.duration, g.duration)
1003 const stride = strideFor(f.count, g.count)
1004 const [ta, tb] = isSamePace ? [[], []] : await Promise.all([thumbs($, updated, stride), thumbs($, original, stride)])
1005 const match = ta.length && tb.length
1006 ? spreadMatch(matchOf(align(ta, tb, 0.01, Math.max(2, Math.round((0.6 * f.fps) / stride)), 0.02), ta.length), stride, f.count, g.count - 1)
1007 : byTime()
1008 await $.process.run(['mkdir', '-p', dir])
1009 const pair = { dir, count: f.count, fps: f.fps, duration: f.duration }
1010 await pairChunk($, pair, updated, original, i => match[i] ?? 0, 0)
1011 if (!(await exists($, frameFile(pair, 0)))) return null
1012 const size = await pngSize($, frameFile(pair, 0))
1013 const made = { pair, pairWidth: size.width, pairHeight: size.height, sync: turns(match, f.fps, g.fps) }
1014 await writeMeta($, dir, { ...made, pair: { count: pair.count, fps: pair.fps, duration: pair.duration } })
1015
1016 return made
1017}
1018
1019// One chunk of the merged clip, Original left and Updated right, made from
1020// the two sides' frames for that stretch (decoded first if they have to be).
1021function pairChunk($: EngineInterface, pair: Frames, updated: Shown, original: Shown, jOf: (i: number) => number, i: number): Promise<void> {
1022 const c = Math.floor(Math.max(0, Math.min(i, pair.count - 1)) / CHUNK)
1023 const key = `${pair.dir}#${c}`
1024 const running = decoding.get(key)
1025 if (running) return running
1026 const f = updated.frames!, g = original.frames!
1027 const job = (async () => {
1028 const first = c * CHUNK, n = Math.min(CHUNK, pair.count - first)
1029 if (await exists($, frameFile(pair, Math.max(0, Math.min(i, pair.count - 1))))) return
1030 const js = Array.from({ length: n }, (_, k) => Math.max(0, Math.min(g.count - 1, jOf(first + k))))
1031 await ensureChunk($, f, updated.source, first)
1032 for (const jc of new Set(js.map(j => Math.floor(j / CHUNK)))) await ensureChunk($, g, original.source, jc * CHUNK)
1033 const tmp = `${pair.dir}/c${c}`
1034 await $.process.run(['mkdir', '-p', `${tmp}/o`, `${tmp}/u`])
1035 const links = js.map((j, k) => `ln -sf "${frameFile(g, j)}" "$0/o/f${String(k + 1).padStart(5, '0')}.png"; ln -sf "${frameFile(f, first + k)}" "$0/u/f${String(k + 1).padStart(5, '0')}.png"`).join('\n')
1036 await $.process.run(['sh', '-c', links, tmp])
1037 // Needed on screen now: normal priority.
1038 await $.process.run([
1039 state.ffmpeg, '-v', 'error', ...ONE_THREAD, '-framerate', String(f.fps), '-i', `${tmp}/o/f%05d.png`, '-framerate', String(f.fps), '-i', `${tmp}/u/f%05d.png`,
1040 '-filter_complex', `[0:v]scale=-2:${pairHeightOf(updated, original)},pad=iw+${PAIR_GAP}:ih:0:0:color=${SIDEBAR.replace('#', '0x')}[a];[1:v]scale=-2:${pairHeightOf(updated, original)}[b];[a][b]hstack=inputs=2`,
1041 '-frames:v', String(n), '-threads', '1', '-start_number', String(first + 1), '-compression_level', '1', `${pair.dir}/f%05d.png`,
1042 ])
1043 await $.process.run(['rm', '-rf', tmp])
1044 await prune($, pair.dir, c, pair.fps)
1045 })().catch(() => undefined).finally(() => decoding.delete(key))
1046 decoding.set(key, job)
1047 return job
1048}
1049
1050// The merged frame on screen, made if it has to be, the next chunk ahead.
1051export async function pairReady($: EngineInterface, shown: Shown, i: number, site?: string): Promise<void> {
1052 const pair = shown.pair
1053 if (!pair || !shown.compare) return
1054 if (site) watch(pair.dir, site, i)
1055 const jOf = (k: number) => compareFrame(shown, k)
1056 await pairChunk($, pair, shown, shown.compare, jOf, i)
1057 if (i % CHUNK >= CHUNK / 2 && i + CHUNK < pair.count) void pairChunk($, pair, shown, shown.compare, jOf, i + CHUNK)
1058}
1059
1060// Resolves a path to something the terminal can draw: a PNG (other image
1061// formats converted with macOS `sips`), or a video's frames.
1062export async function prepare($: EngineInterface, raw: string, title?: string, key?: string): Promise<Shown> {
1063 const path = expand(raw, state.cwd, state.home)
1064 const stat = await $.fs.stat(path, { resolve: true })
1065 const real = stat.realPath ?? path
1066 const name = title ?? real.split('/').pop()!
1067 if (VIDEO.test(real)) return prepareVideo($, real, name, key ?? (await identityOf($, real)))
1068 let png = real
1069 if (!/\.png$/i.test(real)) {
1070 state.generation += 1
1071 png = `${state.TMP}/${real.split('/').pop()!.replace(/\.[^.]+$/, '')}-${state.generation}.png`
1072 await $.process.run(['mkdir', '-p', state.TMP])
1073 if (!state.isMac && !(await exists($, state.ffmpeg))) throw new Error(noFfmpeg(false))
1074 const conv = state.isMac
1075 ? await $.process.run(['sips', '-s', 'format', 'png', real, '--out', png])
1076 : await $.process.run([state.ffmpeg, '-v', 'error', '-y', '-i', real, '-frames:v', '1', png])
1077 if (conv.exitCode !== 0) throw new Error(`could not convert ${real}: ${conv.stderr.trim()}`)
1078 }
1079 // The terminal reads the file itself, so only a picture past what any
1080 // screen shows is shrunk.
1081 const dims = await pngSize($, png)
1082 if (Math.max(dims.width, dims.height) > MAX_STILL) {
1083 state.generation += 1
1084 const small = `${state.TMP}/${png.split('/').pop()!.replace(/\.png$/i, '')}-${state.generation}-small.png`
1085 await $.process.run(['mkdir', '-p', state.TMP])
1086 const shrunk = state.isMac
1087 ? await $.process.run(['sips', '-Z', String(MAX_STILL), png, '--out', small])
1088 : await $.process.run([state.ffmpeg, '-v', 'error', '-y', '-i', png, '-vf', `scale='if(gt(iw,ih),min(${MAX_STILL},iw),-2)':'if(gt(iw,ih),-2,min(${MAX_STILL},ih))'`, small]).catch(() => ({ exitCode: 1 }))
1089 if (state.isMac || shrunk.exitCode === 0) png = small
1090 }
1091 // A picture narrower than the window shows it is drawn that wide, as a
1092 // video's frames are, so a picture and a video of one shape are one size.
1093 // Never past twice its own width: a small icon stays small.
1094 const now = await pngSize($, png)
1095 const wide = Math.min(frameWidth(now.width, now.height, state.termSize, state.cell), now.width * 2)
1096 if (wide > now.width) {
1097 state.generation += 1
1098 const big = `${state.TMP}/${png.split('/').pop()!.replace(/\.png$/i, '')}-${state.generation}-w${wide}.png`
1099 await $.process.run(['mkdir', '-p', state.TMP])
1100 const grown = state.isMac
1101 ? await $.process.run(['sips', '--resampleWidth', String(wide), png, '--out', big]).catch(() => ({ exitCode: 1 }))
1102 : await $.process.run([state.ffmpeg, '-v', 'error', '-y', '-i', png, '-vf', `scale=${wide}:-2:flags=lanczos`, big]).catch(() => ({ exitCode: 1 }))
1103 if (grown.exitCode === 0) png = big
1104 }
1105 state.generation += 1
1106
1107 return { kind: 'image', path: png, source: real, ...(await pngSize($, png)), sourceWidth: dims.width, sourceHeight: dims.height, title: name, generation: state.generation }
1108}
1109
1110// ── history.ts ────────────────────────────────────────────────────────────
1111// Version history: every shown file kept in .show-your-work/, linked to the
1112// one before, and the shown item a result's marker points to.
1113
1114
1115
1116export const MARK = 'show-your-work:'
1117
1118// A time is only worth a click when it points somewhere: a picture has no
1119// timeline, and a clip where every change sits at the same second isn't
1120// pointing anywhere either. Those rows are plain text.
1121export function timesThatMean(changes: KeyChange[] | undefined, isVideo: boolean): KeyChange[] | undefined {
1122 if (!changes) return changes
1123 const times = new Set(changes.filter(c => c.at !== undefined).map(c => c.at))
1124 const isPointing = isVideo && (times.size > 1 || (times.size === 1 && changes.length === 1))
1125
1126 return isPointing ? changes : changes.map(({ at: _, ...c }) => c)
1127}
1128
1129// The line a version is listed by: what changed in it.
1130// A version's label: its first change, and how many more there were.
1131export function noteOf(changes: KeyChange[] | undefined, change: string | undefined, title: string | undefined): string {
1132 const titles = (changes ?? []).map(c => c.title.replace(/\s+/g, ' ').trim()).filter(Boolean)
1133 const more = titles.length > 1 ? ` and ${titles.length - 1} more` : ''
1134 return (titles.length ? titles[0] + more : change ?? title ?? '').slice(0, 200)
1135}
1136
1137// Earlier versions as given: paths or { path, note }, as an array or the
1138// same array sent as JSON text.
1139export function versionsOf(value: unknown): { path: string; note?: string }[] {
1140 if (typeof value === 'string') {
1141 const text = value
1142 try { value = JSON.parse(text) } catch { return text ? [{ path: text }] : [] }
1143 }
1144 if (!Array.isArray(value)) return []
1145 return value.flatMap(v =>
1146 typeof v === 'string' ? [{ path: v }]
1147 : v && typeof v === 'object' && typeof (v as { path?: unknown }).path === 'string'
1148 ? [{ path: (v as { path: string }).path, note: typeof (v as { note?: unknown }).note === 'string' ? (v as { note: string }).note : undefined }]
1149 : [])
1150}
1151
1152// Every shown file is kept as a version, in .show-your-work/ inside the
1153// project (it ignores itself in git), so old rows keep their picture and the
1154// history survives restarts. Each version gets a short handle; a revision
1155// names its parent's handle as `previous`, so history is a chain of explicit
1156// links, like commits. No file names are matched: forget the link and there's
1157// no history, never a wrong one.
1158type Version = { id: string; parent?: string; note?: string; ext: string; title?: string; origin?: string }
1159export const handleOf = (value: unknown) => (typeof value === 'string' ? value.trim().replace(/^#/, '').toLowerCase() : '') || undefined
1160let storeDir = ''
1161// Everything the plugin keeps is at most 1 GB: 500 MB of frames (a cache, cut
1162// again when needed) and 500 MB of history across every project together.
1163const HISTORY_CAP_KB = 500_000
1164// Every history folder this install has used, so the cap spans all of them.
1165const HISTORY_DIRS = 'historyDirs'
1166// Deletes the oldest versions across the history folders in $3… until they
1167// hold $1 KB at most, never the one just kept ($2); only folders this user
1168// owns, never through a link, only the plugin's own record names.
1169export const HISTORY_TRIM_SH = [
1170 'cap=$1 keep=$2; shift 2',
1171 'ok() { [ -d "$1" ] && [ ! -L "$1" ] && [ -O "$1" ]; }',
1172 'total=0; for d in "$@"; do ok "$d" && total=$((total + $(du -sk "$d" | cut -f1))); done',
1173 '[ "$total" -le "$cap" ] && exit 0',
1174 'R="[0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f][0-9a-f]"',
1175 'for d in "$@"; do ok "$d" || continue; for f in "$d"/$R.json; do [ -f "$f" ] && printf "%s\\t%s\\n" "$(stat -f %m "$f" 2>/dev/null || stat -c %Y "$f")" "$f"; done; done |',
1176 ' sort -n | while IFS="$(printf "\\t")" read -r t f; do',
1177 ' [ "$total" -le "$cap" ] && break',
1178 ' [ "$f" = "$keep" ] && continue',
1179 ' base=${f%.json}; size=$(du -sk "$base".* 2>/dev/null | awk \'{s += $1} END {print s + 0}\'); rm -f -- "$base".*; total=$((total - size))',
1180 ' done; true',
1181].join('\n')
1182export async function storeOf($: EngineInterface): Promise<string> {
1183 if (storeDir) return storeDir
1184 for (const dir of [`${state.cwd || state.home}/.show-your-work`, `${state.TMP}/store`]) {
1185 // Never through a link (a repo could commit `.show-your-work -> ..`), and
1186 // only a folder this user owns.
1187 const r = await $.process.run(['sh', '-c', '[ -L "$0" ] && exit 1; mkdir -p "$0" && [ ! -L "$0" ] && [ -O "$0" ] && { [ -f "$0/.gitignore" ] || printf "*\\n" > "$0/.gitignore"; }', dir]).catch(() => null)
1188 if (r && r.exitCode === 0) {
1189 const dirs = ((await $.store.get(HISTORY_DIRS)) as string[] | undefined) ?? []
1190 if (!dirs.includes(dir)) await $.store.set(HISTORY_DIRS, [dir, ...dirs].slice(0, 200))
1191 return (storeDir = dir)
1192 }
1193 }
1194 return (storeDir = `${state.TMP}/store`)
1195}
1196async function readVersion($: EngineInterface, dir: string, id: string): Promise<Version | null> {
1197 if (!/^[0-9a-f]{4,12}$/.test(id)) return null
1198 const r = await $.process.run(['cat', `${dir}/${id}.json`]).catch(() => null)
1199 if (!r || r.exitCode !== 0) return null
1200 // A record's id and extension become paths that are later deleted: onlytypes/index.d.ts 69 lines1export type Frames = { dir: string; count: number; fps: number; duration: number; lead?: number; cut?: number }
2
3// One QA check: its name, whether it passed, and when it happens in a clip.
4export type Check = { name: string; ok: boolean; at?: number; url?: string }
5
6// One change to review: what changed, optionally when it shows in the clip and
7// the page it is on.
8export type KeyChange = { title: string; detail?: string; at?: number; url?: string }
9
10// One line of the QA summary: a group of checks, whether it passed, and how
11// many of its checks did.
12export type Summary = { label: string; ok: boolean; passed?: number; total?: number }
13
14// A play button over the centre of a paused video, or none. (A grid of
15// buttons over the whole picture was tried: it erases the picture.)
16export type Overlay = 'center' | 'none'
17
18export type Shown = {
19 kind?: 'image' | 'video'
20 // the PNG the terminal draws (a video's first frame)
21 path: string
22 // the file the user gave, for Open and Reveal
23 source?: string
24 /** The file as the user knows it (source is the kept copy). */
25 origin?: string
26 // the picture drawn (a video's frames), in pixels
27 width: number
28 height: number
29 /** The file's own size, for its label, when the picture drawn is another size. */
30 sourceWidth?: number
31 sourceHeight?: number
32 title: string
33 generation: number
34 frames?: Frames
35 // QA context: the change, its PR, the checks run
36 change?: string
37 pr?: string
38 // the page the recording or picture is of, to open it there
39 url?: string
40 checks?: Check[]
41 // what to review, and the QA in three lines
42 changes?: KeyChange[]
43 summary?: Summary[]
44 // the other side of a before/after, and the two sides' names
45 compare?: Shown
46 /** Earlier kept versions of the same file, oldest first; compare is the last. */
47 history?: { path: string; note?: string }[]
48 /** The heading over the changes list, when they aren't changes. */
49 changesTitle?: string
50 /** One line on this version, for the history list. */
51 note?: string
52 /** Which of history the compared side starts on. */
53 historyAt?: number
54 // Original and Updated merged into one clip, side by side, and its size
55 pair?: Frames
56 pairWidth?: number
57 pairHeight?: number
58 // moments that line up, [updated, original] seconds, matched by how the frames look
59 sync?: [number, number][]
60 label?: string
61 overlay?: Overlay
62}
63
64declare module 'claude-code' {
65 interface PluginState {
66 'show-your-work': { current: Shown | null; welcome: number }
67 }
68}
69