The best way to control Claude Code, Codex and more from any computer or phone
| 1 | /** |
| 2 | * Runs every scene in `deck.ts` for real, in order, against one project |
| 3 | * folder (`work/shorty`), and writes what the video needs to `out/capture/`: |
| 4 | * |
| 5 | * out/capture/<scene>/scene.json beats (see shared/types.ts) |
| 6 | * out/capture/<scene>/terminal.mp4 the terminal, rendered by tcut |
| 7 | * out/capture/<scene>/browser-<n>.png real page captures |
| 8 | * |
| 9 | * The project starts empty and each scene brings it to the matching |
| 10 | * `chapters/<chapter>` folder: files typed on screen are written as they |
| 11 | * are typed, the rest are synced silently. The terminal is one tmux |
| 12 | * session for the whole talk: `alchemy dev` runs in the top pane from |
| 13 | * chapter 1 on, commands and tests run in the bottom pane. |
| 14 | * |
| 15 | * pnpm capture # all scenes, then tear everything down |
| 16 | * pnpm capture --keep # leave dev/live deployments up |
| 17 | * pnpm capture --only 03-tests # re-capture one scene (needs the previous ones' project state) |
| 18 | * |
| 19 | * Needs Bun >= 1.4.1 (tcut); the package script runs it with `bunx bun@1.4.2`. |
| 20 | * Deploys use the `ALCHEMY_PROFILE` profile (default `testing`). |
| 21 | */ |
| 22 | import { cp, mkdir, readdir, readFile, rm, stat, writeFile } from "node:fs/promises"; |
| 23 | import path from "node:path"; |
| 24 | import { parseArgs } from "node:util"; |
| 25 | import { buildTimeline, defineVideo, type TerminalSession } from "tcut"; |
| 26 | import { deck } from "../deck.ts"; |
| 27 | import { |
| 28 | BROWSER_VIEWPORT, |
| 29 | TERMINAL, |
| 30 | VIDEO, |
| 31 | type Beat, |
| 32 | type Desk, |
| 33 | type Graph, |
| 34 | type SceneCapture, |
| 35 | } from "../shared/types.ts"; |
| 36 | import { readGraph } from "./graph.ts"; |
| 37 | import type { Pane, SceneContext, SceneDefinition, Term } from "./scene.ts"; |
| 38 | |
| 39 | const { values: args } = parseArgs({ |
| 40 | options: { |
| 41 | keep: { type: "boolean", default: false }, |
| 42 | only: { type: "string" }, |
| 43 | }, |
| 44 | }); |
| 45 | |
| 46 | const root = path.resolve(import.meta.dir, ".."); |
| 47 | const project = "shorty"; |
| 48 | const dir = path.join(root, "work", project); |
| 49 | const chaptersDir = path.join(root, "chapters"); |
| 50 | const captureRoot = path.join(root, "out", "capture"); |
| 51 | const bin = path.join(root, "node_modules", ".bin"); |
| 52 | const profile = process.env.ALCHEMY_PROFILE ?? "testing"; |
| 53 | const tmuxConf = path.join(root, "capture", "tmux.conf"); |
| 54 | const zdot = path.join(root, "work", ".zdot"); |
| 55 | const SOCKET = "shorty-demo"; |
| 56 | const SESSION = "shorty"; |
| 57 | /** Terminal tabs are tmux windows, drawn by tmux's own status line so tab and content always agree. */ |
| 58 | const TABS: Pane[] = ["deploy", "test", "dev"]; |
| 59 | const PANES: Record<Pane, string> = { |
| 60 | deploy: `${SESSION}:0`, |
| 61 | test: `${SESSION}:1`, |
| 62 | dev: `${SESSION}:2`, |
| 63 | }; |
| 64 | /** The tab on screen; persists across scenes like the real terminal would. */ |
| 65 | let currentTab: Pane = "deploy"; |
| 66 | |
| 67 | /** Beat markers written into the tcut recording around terminal beats. */ |
| 68 | const BEAT = "prezzy-beat:"; |
| 69 | /** Markers recording which terminal tab is on screen. */ |
| 70 | const TAB = "prezzy-tab:"; |
| 71 | |
| 72 | /** Never copied into the project or shown in the explorer. */ |
| 73 | const IGNORED = new Set(["node_modules", ".alchemy", "dist", ".DS_Store", "tsconfig.tsbuildinfo"]); |
| 74 | |
| 75 | const listFiles = async (base: string, rel = ""): Promise<string[]> => { |
| 76 | const entries = await readdir(path.join(base, rel), { withFileTypes: true }).catch(() => []); |
| 77 | const files: string[] = []; |
| 78 | for (const entry of entries) { |
| 79 | if (IGNORED.has(entry.name)) continue; |
| 80 | const child = rel ? `${rel}/${entry.name}` : entry.name; |
| 81 | if (entry.isDirectory()) files.push(...(await listFiles(base, child))); |
| 82 | else files.push(child); |
| 83 | } |
| 84 | return files.sort(); |
| 85 | }; |
| 86 | |
| 87 | const readText = (file: string) => readFile(file, "utf8").catch(() => ""); |
| 88 | const exists = (file: string) => |
| 89 | stat(file).then( |
| 90 | () => true, |
| 91 | () => false, |
| 92 | ); |
| 93 | |
| 94 | const sh = async (cmd: string[], opts: { cwd?: string; quiet?: boolean } = {}) => { |
| 95 | const proc = Bun.spawn(cmd, { cwd: opts.cwd ?? dir, stdout: "pipe", stderr: "pipe" }); |
| 96 | const [out, err] = [ |
| 97 | await new Response(proc.stdout).text(), |
| 98 | await new Response(proc.stderr).text(), |
| 99 | ]; |
| 100 | const code = await proc.exited; |
| 101 | if (code !== 0 && !opts.quiet) |
| 102 | throw new Error(`${cmd.join(" ")} failed (${code}): ${err || out}`); |
| 103 | return out; |
| 104 | }; |
| 105 | const tmux = (...rest: string[]) => sh(["tmux", "-L", SOCKET, ...rest], { quiet: true }); |
| 106 | |
| 107 | const paneText = async (pane: Pane) => |
| 108 | tmux("capture-pane", "-p", "-J", "-S", "-", "-t", PANES[pane]); |
| 109 | |
| 110 | const waitFor = async (pane: Pane, pattern: RegExp, timeout = 120_000) => { |
| 111 | const deadline = Date.now() + timeout; |
| 112 | for (;;) { |
| 113 | const text = await paneText(pane); |
| 114 | if (pattern.test(text)) return text; |
| 115 | if (Date.now() > deadline) { |
| 116 | throw new Error( |
| 117 | `timed out waiting for ${pattern} in the ${pane} pane:\n${text.slice(-3000)}`, |
| 118 | ); |
| 119 | } |
| 120 | await Bun.sleep(300); |
| 121 | } |
| 122 | }; |
| 123 | |
| 124 | /** A fresh tmux session with a clean zsh in each pane, sized for the terminal clip. */ |
| 125 | const startTmux = async (cols: number, rows: number) => { |
| 126 | await mkdir(zdot, { recursive: true }); |
| 127 | await writeFile( |
| 128 | path.join(zdot, ".zshrc"), |
| 129 | [ |
| 130 | `PROMPT='%F{green}~/${project}%f %F{8}❯%f '`, |
| 131 | "PROMPT_EOL_MARK=''", |
| 132 | `export PATH="${bin}:$PATH" ALCHEMY_PROFILE=${profile} FORCE_HYPERLINK=1`, |
| 133 | "unset CI CURSOR_AGENT CLAUDECODE CLAUDE_CODE NO_COLOR FORCE_COLOR", |
| 134 | "", |
| 135 | ].join("\n"), |
| 136 | ); |
| 137 | await tmux("kill-server"); |
| 138 | const shell = `ZDOTDIR=${zdot} zsh -i`; |
| 139 | await sh([ |
| 140 | "tmux", |
| 141 | "-f", |
| 142 | tmuxConf, |
| 143 | "-L", |
| 144 | SOCKET, |
| 145 | "new-session", |
| 146 | "-d", |
| 147 | "-s", |
| 148 | SESSION, |
| 149 | "-n", |
| 150 | "deploy", |
| 151 | "-x", |
| 152 | String(cols), |
| 153 | "-y", |
| 154 | String(rows), |
| 155 | "-c", |
| 156 | dir, |
| 157 | shell, |
| 158 | ]); |
| 159 | for (const tab of TABS.slice(1)) { |
| 160 | await tmux("new-window", "-d", "-t", PANES[tab], "-n", tab, "-c", dir, shell); |
| 161 | } |
| 162 | await tmux("select-window", "-t", PANES.deploy); |
| 163 | currentTab = "deploy"; |
| 164 | await Bun.sleep(800); |
| 165 | }; |
| 166 | |
| 167 | /** Poll until `alchemy dev` is ready and its output has been still for a moment. */ |
| 168 | const waitDev = async (timeout = 180_000) => { |
| 169 | const deadline = Date.now() + timeout; |
| 170 | let last = ""; |
| 171 | let stableSince = Date.now(); |
| 172 | for (;;) { |
| 173 | const text = await paneText("dev"); |
| 174 | if (text !== last) { |
| 175 | last = text; |
| 176 | stableSince = Date.now(); |
| 177 | } |
| 178 | const ready = /Dev stack ready \((\d+)\/\1\)/.test( |
| 179 | text.trimEnd().split("\n").slice(-3).join("\n"), |
| 180 | ); |
| 181 | if (ready && Date.now() - stableSince > 2500) return; |
| 182 | if (Date.now() > deadline) throw new Error(`alchemy dev did not settle:\n${text.slice(-3000)}`); |
| 183 | await Bun.sleep(300); |
| 184 | } |
| 185 | }; |
| 186 | |
| 187 | /** Poll until `url` serves a page (fresh workers.dev hosts answer 404 for a few seconds). */ |
| 188 | const waitForPage = async (url: string) => { |
| 189 | for (let attempt = 0; attempt < 90; attempt++) { |
| 190 | const ok = await fetch(url, { signal: AbortSignal.timeout(5_000) }) |
| 191 | .then((r) => r.ok) |
| 192 | .catch(() => false); |
| 193 | if (ok) return; |
| 194 | await Bun.sleep(1_000); |
| 195 | } |
| 196 | throw new Error(`${url} did not serve a page after 90s`); |
| 197 | }; |
| 198 | |
| 199 | /** Wait until the page's text matches `waitFor` (or has any text), then let it settle. */ |
| 200 | const settlePage = async (view: Bun.WebView, url: string, waitFor?: RegExp) => { |
| 201 | let text = ""; |
| 202 | for (let attempt = 0; attempt < 120; attempt++) { |
| 203 | text = String(await view.evaluate("document.body ? document.body.innerText : ''")); |
| 204 | if (waitFor ? waitFor.test(text) : text.length > 0) break; |
| 205 | await Bun.sleep(250); |
| 206 | } |
| 207 | if (waitFor && !waitFor.test(text)) { |
| 208 | throw new Error(`${url} never showed ${waitFor}; page text: ${text.slice(0, 500)}`); |
| 209 | } |
| 210 | await Bun.sleep(600); |
| 211 | }; |
| 212 | |
| 213 | /** The element's box in page (CSS) pixels, which is also the video's viewport coordinates. */ |
| 214 | const boxOf = async (view: Bun.WebView, selector: string) => { |
| 215 | const json = String( |
| 216 | await view.evaluate(`(() => { |
| 217 | const el = document.querySelector(${JSON.stringify(selector)}); |
| 218 | if (!el) return ""; |
| 219 | const r = el.getBoundingClientRect(); |
| 220 | return JSON.stringify({ x: r.x, y: r.y, width: r.width, height: r.height }); |
| 221 | })()`), |
| 222 | ); |
| 223 | if (!json) throw new Error(`no element matches ${selector}`); |
| 224 | return JSON.parse(json) as { x: number; y: number; width: number; height: number }; |
| 225 | }; |
| 226 | |
| 227 | /** Window contents carried from scene to scene. */ |
| 228 | let desk: Desk = { files: [], tabs: [], active: undefined, terminalTabs: [] }; |
| 229 | const state: Record<string, string> = {}; |
| 230 | |
| 231 | const captureScene = async (id: string, scene: SceneDefinition) => { |
| 232 | const out = path.join(captureRoot, id); |
| 233 | await rm(out, { recursive: true, force: true }); |
| 234 | await mkdir(out, { recursive: true }); |
| 235 | const chapter = path.join(chaptersDir, scene.chapter); |
| 236 | |
| 237 | const beats: Beat[] = []; |
| 238 | const start: Desk = structuredClone({ ...desk, files: await listFiles(dir) }); |
| 239 | const tabs = new Map(desk.tabs.map((tab) => [tab.file, tab.content])); |
| 240 | let active = desk.active; |
| 241 | let browser = desk.browser; |
| 242 | let diagram = desk.diagram; |
| 243 | let terminalBeats = 0; |
| 244 | /** Tabs used so far; "dev" in here means `alchemy dev` is running. */ |
| 245 | const openedTabs = new Set<Pane>(desk.terminalTabs ?? []); |
| 246 | let shots = 0; |
| 247 | /** One real browser tab per scene, driven like a user would. */ |
| 248 | let view: Bun.WebView | undefined; |
| 249 | const shoot = async () => { |
| 250 | const title = String(await view!.evaluate("document.title")); |
| 251 | const png = (await view!.screenshot({ encoding: "buffer" })) as Uint8Array; |
| 252 | const screenshot = `${id}/browser-${++shots}.png`; |
| 253 | await Bun.write(path.join(captureRoot, screenshot), png); |
| 254 | return { title, screenshot }; |
| 255 | }; |
| 256 | |
| 257 | /** Edited text not yet on disk: intermediate edits never reach `alchemy dev`. */ |
| 258 | const pending = new Map<string, string>(); |
| 259 | const current = async (file: string) => |
| 260 | pending.get(file) ?? (await readText(path.join(dir, file))); |
| 261 | const flush = async () => { |
| 262 | for (const [file, content] of pending) await writeProjectFile(file, content); |
| 263 | pending.clear(); |
| 264 | }; |
| 265 | |
| 266 | const openTab = (file: string, content: string) => { |
| 267 | tabs.set(file, content); |
| 268 | active = file; |
| 269 | }; |
| 270 | |
| 271 | const writeProjectFile = async (file: string, content: string) => { |
| 272 | await mkdir(path.dirname(path.join(dir, file)), { recursive: true }); |
| 273 | await writeFile(path.join(dir, file), content); |
| 274 | }; |
| 275 | |
| 276 | const video = defineVideo( |
| 277 | { |
| 278 | output: [path.join(out, "terminal.mp4")], |
| 279 | cast: path.join(out, "terminal.cast"), |
| 280 | cache: false, |
| 281 | shell: "zsh", |
| 282 | cwd: dir, |
| 283 | width: TERMINAL.width, |
| 284 | height: TERMINAL.height, |
| 285 | scale: 1, |
| 286 | fps: VIDEO.fps, |
| 287 | margin: 0, |
| 288 | padding: 14, |
| 289 | windowBar: "none", |
| 290 | borderRadius: 0, |
| 291 | // Ghostty's defaults: its built-in dark theme and JetBrains Mono. |
| 292 | theme: "ghostty-default-style-dark", |
| 293 | font: { family: "JetBrains Mono", size: 16, lineHeight: 1.35 }, |
| 294 | cursor: { blink: false }, |
| 295 | typingSpeed: "40ms", |
| 296 | typingJitter: 0.4, |
| 297 | maxPause: "1.5s", |
| 298 | waitTimeout: "300s", |
| 299 | endPause: "0ms", |
| 300 | }, |
| 301 | async (t: TerminalSession) => { |
| 302 | await t.hide(async () => { |
| 303 | await t.run("clear"); |
| 304 | await t.type(`tmux -L ${SOCKET} attach -t ${SESSION}`); |
| 305 | await t.enter(); |
| 306 | await t.sleep("1500ms"); |
| 307 | }); |
| 308 | await t.marker(`${TAB}${currentTab}`); |
| 309 | |
| 310 | /** |
| 311 | * Click over to a terminal tab (a tmux window). The tab marker is written |
| 312 | * only once the recorded screen shows the new tab's content, so the tab |
| 313 | * bar and the terminal can't disagree. |
| 314 | */ |
| 315 | const showTab = async (pane: Pane) => { |
| 316 | openedTabs.add(pane); |
| 317 | if (pane === currentTab) return; |
| 318 | const visible = (text: string) => |
| 319 | text |
| 320 | .split("\n") |
| 321 | .map((line) => line.trimEnd()) |
| 322 | .join("\n") |
| 323 | .trimEnd(); |
| 324 | await tmux("select-window", "-t", PANES[pane]); |
| 325 | const target = visible(await tmux("capture-pane", "-p", "-t", PANES[pane])); |
| 326 | const deadline = Date.now() + 3_000; |
| 327 | while (visible(t.screen()) !== target && Date.now() < deadline) await t.sleep("30ms"); |
| 328 | currentTab = pane; |
| 329 | await t.marker(`${TAB}${pane}`); |
| 330 | await t.sleep("700ms"); |
| 331 | }; |
| 332 | |
| 333 | const term: Term = { |
| 334 | async type(pane, command) { |
| 335 | await showTab(pane); |
| 336 | await t.sleep("300ms"); |
| 337 | // The whole command appears at once; typing it out only slows the talk down. |
| 338 | await t.paste(command); |
| 339 | await t.sleep("400ms"); |
| 340 | await t.enter(); |
| 341 | }, |
| 342 | async key(pane, key) { |
| 343 | await tmux("send-keys", "-t", PANES[pane], key); |
| 344 | }, |
| 345 | async run(tab, command, opts) { |
| 346 | const prompts = (text: string) => |
| 347 | text.split("\n").filter((line) => /❯/.test(line)).length; |
| 348 | const before = prompts(await paneText(tab)); |
| 349 | await term.type(tab, command); |
| 350 | const deadline = Date.now() + (opts?.timeout ?? 120_000); |
| 351 | for (;;) { |
| 352 | const text = await paneText(tab); |
| 353 | const lines = text.trimEnd().split("\n"); |
| 354 | // Finished once a fresh, empty prompt follows the command. |
| 355 | const finished = opts?.until |
| 356 | ? opts.until.test(text) |
| 357 | : prompts(text) > before && /❯\s*$/.test(lines.at(-1) ?? ""); |
| 358 | if (finished) break; |
| 359 | if (Date.now() > deadline) |
| 360 | throw new Error(`\`${command}\` did not finish:\n${text.slice(-3000)}`); |
| 361 | await Bun.sleep(300); |
| 362 | } |
| 363 | await t.sleep("1200ms"); |
| 364 | return paneText(tab); |
| 365 | }, |
| 366 | async waitDev(opts) { |
| 367 | // Watch alchemy dev pick up the change on its own tab. |
| 368 | await showTab("dev"); |
| 369 | await waitDev(opts?.timeout); |
| 370 | }, |
| 371 | waitFor: (pane, pattern, opts) => waitFor(pane, pattern, opts?.timeout), |
| 372 | text: paneText, |
| 373 | sleep: (ms) => t.sleep(`${ms}ms`), |
| 374 | }; |
| 375 | |
| 376 | const context: SceneContext = { |
| 377 | dir, |
| 378 | state, |
| 379 | async chapterLines(file) { |
| 380 | if (!(await exists(path.join(chapter, file)))) |
| 381 | throw new Error(`${scene.chapter} has no ${file}`); |
| 382 | const lines = (await readText(path.join(chapter, file))).split("\n"); |
| 383 | return (from, to = from) => { |
| 384 | if (from < 1 || to > lines.length || to < from) |
| 385 | throw new Error(`${file} has no lines ${from}–${to}`); |
| 386 | return `${lines.slice(from - 1, to).join("\n")}\n`; |
| 387 | }; |
| 388 | }, |
| 389 | caption(text) { |
| 390 | beats.push({ kind: "caption", text }); |
| 391 | }, |
| 392 | slide(heading, opts) { |
| 393 | beats.push({ kind: "step", title: heading, notes: opts?.notes ?? opts?.subtitle ?? "" }); |
| 394 | beats.push({ |
| 395 | kind: "slide", |
| 396 | layout: "section", |
| 397 | props: { eyebrow: opts?.eyebrow, heading, subtitle: opts?.subtitle }, |
| 398 | }); |
| 399 | }, |
| 400 | step(title, notes) { |
| 401 | beats.push({ kind: "step", title, notes: notes ?? "" }); |
| 402 | }, |
| 403 | async sync(opts) { |
| 404 | const keep = new Set(opts?.except ?? []); |
| 405 | const want = await listFiles(chapter); |
| 406 | for (const file of await listFiles(dir)) { |
| 407 | if (!want.includes(file) && !keep.has(file)) await rm(path.join(dir, file)); |
| 408 | } |
| 409 | for (const file of want) { |
| 410 | if (keep.has(file)) continue; |
| 411 | await mkdir(path.dirname(path.join(dir, file)), { recursive: true }); |
| 412 | await cp(path.join(chapter, file), path.join(dir, file)); |
| 413 | if (tabs.has(file)) tabs.set(file, await readText(path.join(dir, file))); |
| 414 | } |
| 415 | }, |
| 416 | editor: { |
| 417 | async open(file) { |
| 418 | const content = await current(file); |
| 419 | openTab(file, content); |
| 420 | beats.push({ kind: "editor.open", file, content }); |
| 421 | }, |
| 422 | async patch(file, title, edit, notes) { |
| 423 | const before = await current(file); |
| 424 | const after = edit(before); |
| 425 | if (after === before) throw new Error(`patch "${title}" changed nothing in ${file}`); |
| 426 | pending.set(file, after); |
| 427 | openTab(file, after); |
| 428 | beats.push({ kind: "step", title, notes: notes ?? "" }); |
| 429 | beats.push({ kind: "editor.patch", file, title, before, after }); |
| 430 | }, |
| 431 | async show(file, title) { |
| 432 | if (!(await exists(path.join(chapter, file)))) |
| 433 | throw new Error(`${scene.chapter} has no ${file}`); |
| 434 | const after = await readText(path.join(chapter, file)); |
| 435 | await context.editor.patch(file, title ?? file, () => after); |
| 436 | }, |
| 437 | async remove(file) { |
| 438 | pending.delete(file); |
| 439 | await rm(path.join(dir, file), { force: true }); |
| 440 | tabs.delete(file); |
| 441 | if (active === file) active = [...tabs.keys()].pop(); |
| 442 | beats.push({ kind: "editor.delete", file }); |
| 443 | }, |
| 444 | }, |
| 445 | async terminal(fn) { |
| 446 | await flush(); |
| 447 | const index = terminalBeats++; |
| 448 | beats.push({ kind: "terminal", start: 0, end: 0 }); |
| 449 | await t.marker(`${BEAT}start:${index}`); |
| 450 | try { |
| 451 | return await fn(term); |
| 452 | } finally { |
| 453 | await t.marker(`${BEAT}end:${index}`); |
| 454 | } |
| 455 | }, |
| 456 | async diagram(opts) { |
| 457 | await flush(); |
| 458 | // Cut to the dev tab to watch alchemy dev pick up the change, then read the state it wrote. |
| 459 | if (openedTabs.has("dev")) { |
| 460 | await context.terminal(async (term) => { |
| 461 | await term.waitDev(); |
| 462 | await term.sleep(1200); |
| 463 | }); |
| 464 | } |
| 465 | const stateDir = path.join(dir, ".alchemy", "state", "Shorty"); |
| 466 | const deadline = Date.now() + 120_000; |
| 467 | let graph: Graph; |
| 468 | for (;;) { |
| 469 | graph = await readGraph(stateDir, opts.stage); |
| 470 | const ids = new Set(graph.nodes.map((n) => n.id)); |
| 471 | const edges = new Set(graph.edges.map((e) => e.id)); |
| 472 | const missing = [ |
| 473 | ...(opts.nodes ?? []).filter((n) => !ids.has(n)), |
| 474 | ...(opts.edges ?? []).filter((e) => !edges.has(e)), |
| 475 | ]; |
| 476 | if (missing.length === 0) break; |
| 477 | if (Date.now() > deadline) |
| 478 | throw new Error(`diagram never showed ${missing.join(", ")}`); |
| 479 | await Bun.sleep(500); |
| 480 | } |
| 481 | const previous = diagram; |
| 482 | const oldNodes = new Set(previous?.nodes.map((n) => n.id) ?? []); |
| 483 | const oldEdges = new Set(previous?.edges.map((e) => e.id) ?? []); |
| 484 | beats.push({ |
| 485 | kind: "diagram", |
| 486 | graph, |
| 487 | addedNodes: graph.nodes.filter((n) => !oldNodes.has(n.id)).map((n) => n.id), |
| 488 | addedEdges: graph.edges.filter((e) => !oldEdges.has(e.id)).map((e) => e.id), |
| 489 | }); |
| 490 | diagram = graph; |
| 491 | }, |
| 492 | browser: { |
| 493 | async open(url, opts) { |
| 494 | await flush(); |
| 495 | // Let alchemy dev pick up the latest code before the page loads. |
| 496 | if (openedTabs.has("dev")) await waitDev(); |
| 497 | await waitForPage(url); |
| 498 | view?.close(); |
| 499 | view = new Bun.WebView({ ...BROWSER_VIEWPORT, backend: "webkit" }); |
| 500 | await view.navigate(url); |
| 501 | await settlePage(view, url, opts?.waitFor); |
| 502 | const shot = await shoot(); |
| 503 | browser = { url, ...shot }; |
| 504 | beats.push({ kind: "browser", url, ...shot }); |
| 505 | }, |
| 506 | async update(opts) { |
| 507 | if (!browser || !view) throw new Error("browser.update before browser.open"); |
| 508 | await view.navigate(browser.url); |
| 509 | await settlePage(view, browser.url, opts.waitFor); |
| 510 | const shot = await shoot(); |
| 511 | browser = { ...browser, ...shot }; |
| 512 | beats.push({ kind: "browser.update", ...shot }); |
| 513 | }, |
| 514 | async fill(selector, text) { |
| 515 | if (!browser || !view) throw new Error("browser.fill before browser.open"); |
| 516 | const target = await boxOf(view, selector); |
| 517 | // Set the value the way React sees user input. |
| 518 | await view.evaluate(`(() => { |
| 519 | const el = document.querySelector(${JSON.stringify(selector)}); |
| 520 | el.focus(); |
| 521 | const set = Object.getOwnPropertyDescriptor(Object.getPrototypeOf(el), "value").set; |
| 522 | set.call(el, ${JSON.stringify(text)}); |
| 523 | el.dispatchEvent(new Event("input", { bubbles: true })); |
| 524 | })()`); |
| 525 | await Bun.sleep(300); |
| 526 | const shot = await shoot(); |
| 527 | browser = { ...browser, ...shot }; |
| 528 | beats.push({ kind: "browser.action", action: "fill", target, ...shot }); |
| 529 | }, |
| 530 | async click(selector, opts) { |
| 531 | if (!browser || !view) throw new Error("browser.click before browser.open"); |
| 532 | const target = await boxOf(view, selector); |
| 533 | await view.evaluate(`document.querySelector(${JSON.stringify(selector)}).click()`); |
| 534 | await settlePage(view, browser.url, opts?.waitFor); |
| 535 | const shot = await shoot(); |
| 536 | browser = { ...browser, ...shot }; |
| 537 | beats.push({ kind: "browser.action", action: "click", target, ...shot }); |
| 538 | }, |
| 539 | }, |
| 540 | focus(app) { |
| 541 | beats.push({ kind: "focus", app }); |
| 542 | }, |
| 543 | pause(seconds) { |
| 544 | beats.push({ kind: "pause", seconds }); |
| 545 | }, |
| 546 | }; |
| 547 | |
| 548 | try { |
| 549 | await scene.run(context); |
| 550 | } finally { |
| 551 | view?.close(); |
| 552 | } |
| 553 | await flush(); |
| 554 | |
| 555 | // The edits on screen must add up to the real, tested chapter. |
| 556 | const want = await listFiles(chapter); |
| 557 | const have = await listFiles(dir); |
| 558 | const problems: string[] = []; |
| 559 | for (const file of new Set([...want, ...have])) { |
| 560 | if (!want.includes(file)) problems.push(`extra file ${file}`); |
| 561 | else if (!have.includes(file)) problems.push(`missing file ${file}`); |
| 562 | else if ( |
| 563 | (await readText(path.join(dir, file))) !== (await readText(path.join(chapter, file))) |
| 564 | ) { |
| 565 | problems.push(`${file} differs from chapters/${scene.chapter}/${file}`); |
| 566 | } |
| 567 | } |
| 568 | if (problems.length > 0) |
| 569 | throw new Error(`${id} did not end at its chapter:\n ${problems.join("\n ")}`); |
| 570 | |
| 571 | await t.hide(async () => { |
| 572 | await tmux("detach-client", "-s", SESSION); |
| 573 | await t.sleep("500ms"); |
| 574 | }); |
| 575 | }, |
| 576 | ); |
| 577 | |
| 578 | // tmux resizes the window to the recording's terminal when it attaches. |
| 579 | if (!(await hasSession())) await startTmux(150, 40); |
| 580 | |
| 581 | console.log(`● ${id}: recording`); |
| 582 | const recording = await video.record({ force: true, log: (m) => console.log(` ${m}`) }); |
| 583 | |
| 584 | const capture: SceneCapture = { |
| 585 | id, |
| 586 | title: scene.title, |
| 587 | notes: scene.notes ?? "", |
| 588 | project, |
| 589 | start, |
| 590 | end: { |
| 591 | files: await listFiles(dir), |
| 592 | tabs: [...tabs].map(([file, content]) => ({ file, content })), |
| 593 | active, |
| 594 | browser, |
| 595 | diagram, |
| 596 | terminalTabs: [...openedTabs], |
| 597 | }, |
| 598 | terminal: undefined, |
| 599 | beats, |
| 600 | }; |
| 601 | |
| 602 | if (terminalBeats > 0) { |
| 603 | const timeline = buildTimeline(recording.events, video.config.playbackSpeed, { |
| 604 | maxPause: video.config.maxPause, |
| 605 | }); |
| 606 | const at = new Map<string, number>(); |
| 607 | const tabTimeline: { at: number; tab: Pane }[] = []; |
| 608 | for (const e of timeline.events) { |
| 609 | if (e.type !== "m") continue; |
| 610 | if (e.data.startsWith(BEAT)) at.set(e.data.slice(BEAT.length), e.vt); |
| 611 | if (e.data.startsWith(TAB)) |
| 612 | tabTimeline.push({ at: e.vt, tab: e.data.slice(TAB.length) as Pane }); |
| 613 | } |
| 614 | let index = 0; |
| 615 | for (const beat of beats) { |
| 616 | if (beat.kind !== "terminal") continue; |
| 617 | beat.start = at.get(`start:${index}`) ?? 0; |
| 618 | beat.end = at.get(`end:${index}`) ?? beat.start; |
| 619 | index++; |
| 620 | } |
| 621 | console.log(`● ${id}: rendering the terminal`); |
| 622 | const result = await video.render(recording); |
| 623 | capture.terminal = { |
| 624 | clip: `${id}/terminal.mp4`, |
| 625 | duration: result.durationSeconds, |
| 626 | tabs: tabTimeline, |
| 627 | }; |
| 628 | } |
| 629 | |
| 630 | desk = capture.end; |
| 631 | await writeFile(path.join(out, "scene.json"), `${JSON.stringify(capture, null, 2)}\n`); |
| 632 | console.log(`✔ ${id}: ${beats.length} beats`); |
| 633 | }; |
| 634 | |
| 635 | const hasSession = async () => |
| 636 | (await Bun.spawn(["tmux", "-L", SOCKET, "has-session", "-t", SESSION], { |
| 637 | stdout: "ignore", |
| 638 | stderr: "ignore", |
| 639 | }).exited) === 0; |
| 640 | |
| 641 | const teardown = async () => { |
| 642 | await tmux("kill-server"); |
| 643 | if (args.keep) return; |
| 644 | // Give `alchemy dev` a moment to exit, then remove what the talk created. |
| 645 | await Bun.sleep(2_000); |
| 646 | for (const stage of [`dev_${process.env.USER}`, "prod"]) { |
| 647 | console.log(`● destroying the ${stage} stage`); |
| 648 | const cmd = ["alchemy", "destroy", "--yes", "--profile", profile, "--stage", stage]; |
| 649 | const proc = Bun.spawn(cmd, { |
| 650 | cwd: dir, |
| 651 | env: { ...process.env, PATH: `${bin}:${process.env.PATH}`, CI: "" }, |
| 652 | stdout: "inherit", |
| 653 | stderr: "inherit", |
| 654 | }); |
| 655 | if ((await proc.exited) !== 0) |
| 656 | console.error(`✘ ${cmd.join(" ")} failed; run it by hand in work/${project}`); |
| 657 | } |
| 658 | }; |
| 659 | |
| 660 | const scenes = deck.filter((item) => item.kind === "scene"); |
| 661 | const selected = args.only ? scenes.filter((item) => item.id === args.only) : scenes; |
| 662 | if (selected.length === 0) throw new Error(`no scene ${args.only}`); |
| 663 | |
| 664 | if (!args.only) { |
| 665 | await rm(dir, { recursive: true, force: true }); |
| 666 | await mkdir(dir, { recursive: true }); |
| 667 | } else { |
| 668 | // Resume from the desk the previous scene left behind. |
| 669 | const index = scenes.findIndex((item) => item.id === args.only); |
| 670 | const previous = scenes[index - 1]; |
| 671 | await rm(dir, { recursive: true, force: true }); |
| 672 | await mkdir(dir, { recursive: true }); |
| 673 | if (previous) { |
| 674 | const prev = JSON.parse( |
| 675 | await readText(path.join(captureRoot, previous.id, "scene.json")), |
| 676 | ) as SceneCapture; |
| 677 | desk = prev.end; |
| 678 | const prevScene = (await import(path.join(root, "scenes", `${previous.id}.ts`))) |
| 679 | .default as SceneDefinition; |
| 680 | await cp(path.join(chaptersDir, prevScene.chapter), dir, { |
| 681 | recursive: true, |
| 682 | filter: (src) => !IGNORED.has(path.basename(src)), |
| 683 | }); |
| 684 | // Later chapters expect `alchemy dev` already running in its tab. |
| 685 | await startTmux(150, 40); |
| 686 | if (desk.terminalTabs?.includes("dev")) { |
| 687 | await tmux("send-keys", "-t", PANES.dev, "alchemy dev", "Enter"); |
| 688 | await waitDev(300_000); |
| 689 | await tmux("send-keys", "-t", PANES.dev, "C-l"); |
| 690 | } |
| 691 | currentTab = "deploy"; |
| 692 | } |
| 693 | } |
| 694 | |
| 695 | try { |
| 696 | for (const item of selected) { |
| 697 | const scene = (await import(path.join(root, "scenes", `${item.id}.ts`))) |
| 698 | .default as SceneDefinition; |
| 699 | await captureScene(item.id, scene); |
| 700 | } |
| 701 | } finally { |
| 702 | await teardown(); |
| 703 | } |