# Day 83: Video index — Playwright-driven gallery

## Idea
An index page where every previous sketch is a 720×720 looping video preview that plays on hover. Each clip is recorded by a headless Chromium that an LLM agent has scripted to interact with the sketch the way a curious viewer would.

## Description
A grid of square tiles, one per sketch, sorted newest-first. The tile starts as a static poster JPG; on hover (or, on mobile, when it enters the viewport) a muted MP4 swaps in and loops. Click goes to the sketch itself. Some tiles are visually greyed out — sketches that need a webcam, microphone, or a Vite/React build step the static-file harness can't satisfy; those still render a poster of the page's empty/initial state so the user gets visual context, but they don't get a hover-video.

The interesting part isn't the gallery itself — it's the production pipeline that fills it. Each clip is generated by a Playwright scenario authored by an LLM agent: the agent reads the sketch's source (`index.html`, `script.js`, `interface.md`), decides what 3-4 seconds of behavior would make the best preview, and writes a small JS file that drives Playwright (cursor moves, clicks, key presses, slider drags). The harness loads the sketch in a 720×720 headless browser, runs the scenario, ffmpeg-trims and transcodes the recording, and rebuilds the gallery JSON. A re-shoot of any sketch is one command.

## Data Concepts
- **Primary**: Workflow / Tooling (browser automation, video capture, agent-authored interaction)
- **Secondary**: Gallery UI (poster→video swap, lazy video loading, disabled-state styling)

## Conceptual Tags
#playwright #headless-browser #video-gallery #agent-authored #scenario-as-code #ffmpeg-pipeline #lazy-media #poster-frame #square-grid

## Technical Tags
#playwright-record-video #chromium-headless-shell #ffmpeg-crop-scale-pad #fake-media-stream #intersection-observer #file-served-via-local-http #es-modules

## Stack
- **Playwright** (chromium headless shell) — browser automation + video recording
- **Node.js** ES modules — capture harness, scenario loader
- **ffmpeg** — trim warmup, scale/crop/pad, H.264 transcode, poster extraction
- **Vanilla HTML/CSS/JS** — gallery frontend
- **A local HTTP server** embedded in the harness (Node `http`) — so `fetch()` and ES modules in the captured sketches work; `file://` is too restrictive

## Mechanics

### Folder layout
```
83-video-index/
├── index.html, styles.css, script.js     ← the gallery shown to the visitor
├── assets/
│   ├── posters/<slug>.jpg                ← first-frame JPGs
│   ├── videos/<slug>.mp4                 ← H.264 loops
│   └── gallery.json                      ← auto-generated tile list
└── capture/
    ├── package.json                      ← playwright dep
    ├── capture.mjs                       ← the orchestration script
    ├── scenarios/<slug>.mjs              ← one per sketch (see "Scenario format")
    └── .raw/                             ← scratch WebM output, gitignored
```

### Scenario format
Each file under `scenarios/` exports a `meta` object and a `play(page)` async function:

```js
export const meta = {
    slug: '25-spotlight-grid',     // must match the sketch folder name
    title: 'Spotlight grid',       // shown on the tile
    warmupMs: 600,                 // trimmed off the front of the recording
    zoom: 1.5,                     // optional: CSS zoom applied to <html>
    crop: '440:440:140:200',       // optional: ffmpeg crop "w:h:x:y"
    vf: 'pad=720:720:0:210:black', // optional: extra ffmpeg filter chain after crop
    disabled: false,               // grey out + skip hover-video in the gallery
};

export async function play(page) {
    await page.mouse.move(200, 200, { steps: 30 });
    await page.locator('#hue').fill('60');
    await page.waitForTimeout(800);
    // ...should run for ~3000–4000 ms total
}
```

### The capture pipeline (one scenario)
1. **Discover** — `capture.mjs` reads every `scenarios/*.mjs`, validates `meta.slug` + `play`.
2. **Serve** — start an embedded HTTP server on `127.0.0.1:8766` rooted at the worktree, so the sketch can `fetch()` its own `data.json`, load ES modules, etc.
3. **Launch** — start chromium with `--use-fake-device-for-media-stream`, `--use-fake-ui-for-media-stream`, `--autoplay-policy=no-user-gesture-required`; grant `camera` and `microphone` permissions; viewport 720×720, `deviceScaleFactor: 2`, `recordVideo` directed at `.raw/<slug>/`.
4. **Navigate** — `goto` `http://127.0.0.1:8766/<slug>/`, wait for `load`.
5. **Zoom** (optional) — apply `document.documentElement.style.zoom` if `meta.zoom` is set, before `warmupMs` so the layout settles in the zoomed state.
6. **Warm up** — `waitForTimeout(warmupMs)` so the sketch reaches an interesting steady state before recording starts.
7. **Play** — invoke the scenario's `play(page)` — these are the recorded interactions.
8. **Flush** — `page.close()` then `context.close()` to write the WebM to disk.
9. **Trim + transcode** — `ffmpeg -ss <warmupMs/1000>` skips the warmup; `-vf` chains `crop=…,vf,scale=720:720:flags=lanczos`; `libx264 -crf 26 -preset slow -movflags +faststart -an` for a small, web-friendly, audio-free MP4.
10. **Poster** — second ffmpeg pass extracts frame 0 as JPG.
11. **Rewrite JSON** — `assets/gallery.json` is regenerated from every scenario whose poster exists on disk, sorted descending by the leading number in the slug.

### Failure modes the harness shrugs at
- Scenario throws (bad selector, mobile gate, timeout) → that one is skipped, the rest continue, the slug appears in the failed list at the end. Gallery JSON only includes entries with posters on disk, so a failure leaves a clean grid.
- Filtered runs (`node capture.mjs 25-spot`) only re-shoot matching scenarios but still rewrite the JSON from the **full** scenario set — re-shoot one tile without dropping the others.

### Why scenarios are written by an LLM agent
Authoring a recording script for each of 80 sketches by hand is the bottleneck. Instead, for each new sketch we:
1. Spawn a fresh subagent with the sketch's path and the scenario contract (the shape above).
2. The agent reads the source, identifies the controls (sliders, buttons, hover regions, key handlers), and picks a 3-4s shot that shows the sketch off.
3. It writes the scenario file directly. We don't even read its output — the next run of `capture.mjs` picks it up.

This is the same pattern as a video producer briefing a camera operator: the producer (us) sets format constraints; the camera operator (agent) frames the shot.

### Square-fit toolbox
720×720 doesn't suit every sketch. Three knobs cover almost all cases:
- `meta.zoom` — CSS zoom on `<html>`. Use when the sketch is designed for ≥1024px and looks tiny at 720; e.g. `zoom: 1.6` enlarges all content, lets overflow get clipped at the edges (the centered subject stays visible). Cheap, no harness change.
- `meta.crop` — ffmpeg `crop=w:h:x:y`. Use when the sketch is laid out edge-to-edge but only one corner is interesting (e.g. info panel, controls). Captured 720×720 is cropped to the region, then scaled back up.
- `meta.vf` — raw ffmpeg filter chain. Combine `crop` + `pad` to letterbox a non-square shape (e.g. a wide horizontal heatmap strip rendered into a square frame with black bars).

### Gallery frontend
- Fetch `assets/gallery.json` on load, build one `<a class="tile">` per entry.
- Each tile: `<img>` poster (lazy-loaded), `<video preload="none" muted loop playsinline>` with `data-src` (no eager network requests for 79 MP4s).
- Desktop: `pointerenter` → set `video.src = data-src`, `video.play()`, add `.active`; `pointerleave` → pause, remove `.active`. Video opacity transitions from 0 to 1.
- Mobile / coarse pointer: `IntersectionObserver` at 0.5 threshold plays/pauses as tiles scroll into view.
- Disabled tiles: greyscale + brightness filter on the poster, no `<video>` element rendered, click still works.

## Parameters
- **Viewport**: 720×720 CSS px, `deviceScaleFactor: 2` (effective 1440×1440 internal render → crisp on retina).
- **Recording size**: 720×720 (Playwright `recordVideo.size`).
- **Output**: H.264 yuv420p, CRF 26, `-preset slow`, no audio, faststart.
- **Poster**: JPEG q=3, single frame from the trimmed MP4.
- **HTTP server port**: 8766 (chosen to avoid collision with the user's preview server on 8765).
- **Capture wall-clock**: ~5–8 s per sketch; ~8 minutes for all 79.
- **Disk footprint**: ~20 MB for 79 clips + posters.

## How to use

### One-time setup
```sh
cd 83-video-index/capture
npm install
npm run install:browsers   # downloads chromium headless shell, ~92 MB
```

### Capture
```sh
npm run capture                    # all scenarios
npm run capture -- 25-spot         # only scenarios whose slug contains this
```

### Add a sketch to the gallery
1. Drop a file under `capture/scenarios/<sketch-slug>.mjs` matching the contract above. The fastest path: copy `_template.mjs`, then either edit by hand or delegate to a subagent ("author a scenario for sketch X at path Y, following the shape in `scenarios/_template.mjs`").
2. `npm run capture -- <slug>` — produces MP4 + poster, rebuilds `gallery.json` from **all** scenarios.
3. Refresh the gallery in the browser.

### Toggle a tile to disabled
Edit the scenario file, add `disabled: true` to `meta`, re-run capture (any filter works). The harness writes the flag into `gallery.json` and the frontend greys it.

## Notes
- **Why not just screenshots?** A still doesn't carry intent. The whole point of the 100-days project is behavior under interaction; a poster of an idle initial state would be misleading for half the sketches.
- **Why HTTP, not `file://`?** Several sketches use `fetch()` to load `data.json` or use ES module imports. The Fetch API and CORS reject `file://` in Chromium. A 30-line embedded HTTP server is cheap and fixes both.
- **Why Playwright over screen recording?** Reproducibility. The scenario is code — committed, diff-able, re-runnable. A QuickTime capture is a one-shot that goes stale when the sketch is tweaked. Also: scripted interactions remove the human-shake from cursor paths, which makes tiny-tile previews much cleaner.
- **Agent failure modes seen in practice**: hallucinated selectors (the most common — agents invent `#play-pause` buttons that aren't in the DOM), timing assumptions (clicking before the sketch's React mount finishes), and mobile-gate blindness (writing scenarios for sketches that show "mobile is not available" at 720×720). The harness falls back to pure-observe in the worst cases; better fix is to retry the agent with the error message and the agent corrects with the actual DOM.
- **The disabled grey-out is intentional UX**: the tile is still informative (it shows where the broken/media-locked sketches live in the timeline) but the lack of motion tells the visitor that hover won't reward them.
- **gallery.json is treated as a build artifact** — it's overwritten every capture run from the union of (a) scenario files on disk and (b) posters that actually rendered. Don't hand-edit it.
- **The sort key** is `parseInt` on the leading digits of the slug, descending; `15b-binary-camera-grid-v2` sorts immediately after `15-binary-camera-grid` via stable-secondary `localeCompare`.
- **What still doesn't work well**: Vite/React sketches that need a build step (37-sentiment-analyzer, 36-spinning-globe); sketches whose interaction is mouse-driven heat-buildup but render at sub-pixel resolution at 720×720 (21-interaction-heatmap is letterboxed as a workaround); sketches with mobile gates that the agent didn't detect (41-metaball, 45-gravity-pills). All currently marked `disabled: true`.
