mirror of
https://github.com/windmill-labs/windmill.git
synced 2026-11-28 08:06:16 +00:00
add the demo-video skill as a shared agent skill (#12630)
* feat: add the demo-video skill as a shared agent skill Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: scope demo-video output waits to the take and map regions onto the cut Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: render demo-video cuts and holds at the planned frame times Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * fix: keep the frame rate after retiming demo-video cuts on FFmpeg 7 Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
a888954814
commit
0b32151f14
@@ -0,0 +1,132 @@
|
||||
---
|
||||
name: demo-video
|
||||
description: Record a demo video of a feature, either a narrated browser walkthrough (mp4 with burned-in captions and text-to-speech audio) driven by Playwright, or a terminal session (a CLI or TUI such as Codex or Claude Code) recorded with vhs, optionally beside the browser it drives, with its idle waits cut. Use when the user asks for a demo video, a recorded walkthrough, a terminal or CLI recording, a video to check a feature, a video for a PR, or to cut the waiting out of a recording.
|
||||
---
|
||||
|
||||
# Demo video
|
||||
|
||||
One scenario file in, one mp4 out. Do not snapshot or screenshot the page while writing the
|
||||
scenario: write selectors from the code you just changed, run once, and fix only the step the
|
||||
script reports as failed.
|
||||
|
||||
Every script lives in `.agents/skills/demo-video/`; the commands below are written from the repo
|
||||
root. Scratch files (scenarios, tapes, recordings) go in the session scratchpad, never in the
|
||||
repo: `record.mjs` writes only the mp4 you name, beside the scenario by default.
|
||||
|
||||
For a terminal session (vhs, optionally beside a browser), for cutting the waits out of any
|
||||
silent recording, and for adding a voice-over to a cut, follow
|
||||
`.agents/skills/demo-video/terminal.md`. A browser take whose waits depend on an AI (a chat
|
||||
turn) goes the same way: record it silent with Playwright's `recordVideo`, cut, then narrate,
|
||||
rather than through `record.mjs`, whose narration cannot survive a cut.
|
||||
|
||||
## What it needs
|
||||
|
||||
| Tool | Used by | Without it |
|
||||
| --- | --- | --- |
|
||||
| Playwright: `npm ci --prefix .agents/skills/demo-video`, once per worktree | every script | the script stops with that command |
|
||||
| Playwright's Chromium: `npx --prefix .agents/skills/demo-video playwright install chromium`, once per machine | every script | the script stops with that command |
|
||||
| `ffmpeg` and `ffprobe` (`brew install ffmpeg`) | every script | the script stops before recording |
|
||||
| macOS `say` | narration in `record.mjs` and `narrate.mjs` | set `voice: false` in the scenario or pass `--voice=none`: captions only, no audio, each line on screen for its reading time |
|
||||
| `vhs` (`brew install vhs`, brings `ttyd`) | terminal recordings | no terminal recordings; browser demos still work |
|
||||
|
||||
Homebrew's `ffmpeg` has no text filters, so captions and notes are drawn by the browser and
|
||||
overlaid as images.
|
||||
|
||||
## Write the scenario
|
||||
|
||||
`<scratch>/demo.mjs`, against this worktree's frontend (its URL is in the session's
|
||||
instructions, or `FRONTEND_PORT` in `.env.local`):
|
||||
|
||||
```js
|
||||
export default {
|
||||
baseURL: 'http://localhost:3000',
|
||||
start: '/?workspace=admins', // first page shown in the video
|
||||
// Runs unrecorded; its cookies carry into the recording. Log in here.
|
||||
setup: async ({ page }) => {
|
||||
const r = await page.request.post('/api/auth/login',
|
||||
{ data: { email: 'admin@windmill.dev', password: 'changeme' } })
|
||||
if (!r.ok()) throw new Error(`login: ${r.status()}`)
|
||||
},
|
||||
steps: [
|
||||
{ say: 'One sentence about what the viewer sees.' },
|
||||
{ say: 'Clicking the row opens it.', do: ({ click }) => click('text=Daily orders') },
|
||||
{ say: 'Hover shows the menu.', do: async ({ page, hover }) => { await hover('[aria-label="Menu"]') } },
|
||||
],
|
||||
}
|
||||
```
|
||||
|
||||
- `say`: narration, spoken and shown as the caption. It starts before the step's action, and
|
||||
the step stays on screen until it is spoken. Keep each to one short sentence.
|
||||
- `do`: gets `{ page, click, hover, wait }`. `click`/`hover` draw a ring on the target first, so
|
||||
prefer them over `page.click`. Strings are Playwright selectors (the first match is used);
|
||||
a locator is used as given, so a locator matching two elements fails the step. Assert the
|
||||
outcome inside the step by waiting on what proves it worked, e.g.
|
||||
`await page.getByText('Hello, Ada!').waitFor({ timeout: 30000 })`, so a broken feature fails
|
||||
the run instead of recording a wrong screen. There is no `expect` in a scenario.
|
||||
- Captions sit in a band of their own below the page (`captionAt: 'top'` puts it above), so
|
||||
they never cover the UI. The mp4 is the viewport plus that band: 1280x816 by default.
|
||||
- Optional: `hold` (extra ms after a step), `viewport` (default 1280x720), `voice` (macOS
|
||||
`say -v '?'`, default Samantha; `false` for no speech), `settle` (ms after `start` loads),
|
||||
`pad` (ms after each line, default 400), `captionHeight` (band height, default 96, two lines
|
||||
of text; viewport height + band must be even for H.264).
|
||||
- Text selectors (`text=…`) can match hidden copies; for menu items use a role locator,
|
||||
`({ page, hover }) => hover(page.getByRole('menuitem', { name: /Shared sessions/ }))`.
|
||||
- Aim for 5 to 10 steps, under a minute: the video is for checking a feature, not marketing.
|
||||
|
||||
## Test data must match the story
|
||||
|
||||
Plant the data the take needs before recording, and make it what the narration and the prompt
|
||||
say it is. An AI agent in the take reads that data back and reacts to it: given a "Supabase"
|
||||
connection string that pointed at `127.0.0.1`, Codex refused to call it a Supabase connection
|
||||
and the take was unusable. Hosts, names, providers and values must fit the story; when the demo
|
||||
needs the thing to really work, ask the user for a real instance of that kind rather than
|
||||
planting a local stand-in. Never put a real secret on screen.
|
||||
|
||||
## Run
|
||||
|
||||
```bash
|
||||
node .agents/skills/demo-video/record.mjs <scratch>/demo.mjs [<scratch>/demo.mp4]
|
||||
```
|
||||
|
||||
It prints the mp4 path, or `step N failed: …` plus a screenshot path. Read that screenshot
|
||||
only on failure.
|
||||
|
||||
## Deliver
|
||||
|
||||
The user may not be on this machine, so a local path is not a delivery.
|
||||
|
||||
- **Artifact page**: publish the mp4 through the Artifact `files` map (15 MB per file) and
|
||||
reference it from a `<video controls>`. The captions are burned in, so nothing else is
|
||||
needed. For a video made with `--no-band`, Artifacts do not serve `.vtt` files: write the
|
||||
cues with `narrate.mjs --cues=cues.json` and add them from inline JS:
|
||||
|
||||
```js
|
||||
const track = video.addTextTrack('captions', 'English', 'en')
|
||||
for (const [start, end, text] of CUES) track.addCue(new VTTCue(start, end, text))
|
||||
track.mode = 'showing'
|
||||
```
|
||||
|
||||
- **PR body**: GitHub strips `<video>` from PR bodies and plays no mp4 from a raw URL (it
|
||||
downloads), so embed a GIF and link the narrated mp4. Make the GIF (about 4 MB for 55 s):
|
||||
|
||||
```bash
|
||||
ffmpeg -v error -y -i demo.mp4 -vf "fps=10,scale=960:-1:flags=lanczos,split[a][b];[a]palettegen=stats_mode=diff[p];[b][p]paletteuse=diff_mode=rectangle" demo.gif
|
||||
```
|
||||
|
||||
Upload both to `windmill-labs/agent-screenshots-internal`, as the `pr` skill does for
|
||||
screenshots. The repo is public and its history permanent: nothing secret may appear in the
|
||||
video.
|
||||
|
||||
```bash
|
||||
REPO=windmill-labs/agent-screenshots-internal
|
||||
for F in demo.gif demo.mp4; do
|
||||
DEST="shots/$(git branch --show-current)/$(date +%s)-$(basename "$F")"
|
||||
base64 < "$F" | tr -d '\n' | jq -Rs --arg m "add $DEST" '{message:$m, content:.}' \
|
||||
| gh api -X PUT "repos/$REPO/contents/$DEST" --input - >/dev/null
|
||||
URL="https://raw.githubusercontent.com/$REPO/main/$DEST"
|
||||
echo "$URL $(curl -sI "$URL" | grep -i '^content-length')"
|
||||
done
|
||||
```
|
||||
|
||||
Check that each `content-length` matches the local file, then put
|
||||
`` and `[Narrated mp4](<mp4 url>)` in the body.
|
||||
@@ -0,0 +1,44 @@
|
||||
// Prints when each watched region of a recording changes, in seconds of the file itself, so
|
||||
// `--cut=` ranges and narration `at` times come from the picture rather than from wall-clock
|
||||
// logs (a vhs mp4 runs shorter than the session it recorded).
|
||||
//
|
||||
// usage: node activity.mjs <in.mp4> <regions.json> [from] [to] [--raw]
|
||||
//
|
||||
// Same sampling and regions.json as cut-waits.mjs (10 samples per second, `min`, `unlessLike`).
|
||||
// Each region gets one line of runs of consecutive changes, `12.3-14.1(952)`: first and last
|
||||
// changing sample, and the most pixels changed in one sample. --raw prints every sample in which
|
||||
// anything changed, marked * when it counts (above `min`) and ~ when `unlessLike` suppressed it.
|
||||
import { readFileSync } from 'node:fs'
|
||||
import { die, need, sampleRegions, SAMPLES } from './lib.mjs'
|
||||
|
||||
const args = process.argv.slice(2)
|
||||
const raw = args.includes('--raw')
|
||||
const [input, regionsFile, from, to] = args.filter((a) => a !== '--raw')
|
||||
if (!regionsFile) die('usage: node activity.mjs <in.mp4> <regions.json> [from] [to] [--raw]')
|
||||
need('ffmpeg', 'ffprobe')
|
||||
const regions = JSON.parse(readFileSync(regionsFile, 'utf8'))
|
||||
const samples = await sampleRegions(input, regions, {
|
||||
from: from === undefined ? 0 : Number(from),
|
||||
to: to === undefined ? undefined : Number(to)
|
||||
})
|
||||
|
||||
for (const [k, r] of regions.entries()) {
|
||||
const hits = samples.filter((s) => !s.suppressed[k] && s.changed[k] > r.min)
|
||||
if (raw) {
|
||||
const all = samples.filter((s) => s.changed[k] > 0)
|
||||
const mark = (s) => (s.suppressed[k] ? '~' : s.changed[k] > r.min ? '*' : '')
|
||||
console.log(`${r.name}: ${all.map((s) => `${s.t.toFixed(1)}(${s.changed[k]})${mark(s)}`).join(' ')}`)
|
||||
continue
|
||||
}
|
||||
const runs = []
|
||||
for (const s of hits) {
|
||||
const run = runs.at(-1)
|
||||
if (run && s.t - run.to <= 1.5 / SAMPLES) {
|
||||
run.to = s.t
|
||||
run.max = Math.max(run.max, s.changed[k])
|
||||
} else runs.push({ from: s.t, to: s.t, max: s.changed[k] })
|
||||
}
|
||||
const fmt = (run) =>
|
||||
(run.to > run.from ? `${run.from.toFixed(1)}-${run.to.toFixed(1)}` : run.from.toFixed(1)) + `(${run.max})`
|
||||
console.log(`${r.name}: ${runs.map(fmt).join(' ') || '-'}`)
|
||||
}
|
||||
@@ -0,0 +1,214 @@
|
||||
// Shrinks the idle stretches of a silent screen recording (a terminal session, a browser take)
|
||||
// to about a second each and marks every cut with a "N s later" note. It measures what changes,
|
||||
// it does not guess: a stretch is idle when no watched region changes.
|
||||
//
|
||||
// usage: node cut-waits.mjs <in.mp4> <out.mp4> <regions.json> [options]
|
||||
// --plan print the cuts and write the check sheets, render nothing
|
||||
// --min-gap=3 cut only stretches at least this long (s)
|
||||
// --head=0.7 keep this much of a stretch after the last change (s)
|
||||
// --tail=0.3 and this much before the next change (s)
|
||||
// --end-hold=5 keep this much after the last change, then end the video (s)
|
||||
// --label-y=12 top of the "N s later" note, in pixels
|
||||
// --cut=12.5-38 also remove this stretch, though the screen changes in it (repeatable)
|
||||
//
|
||||
// --cut is for a wait the measurement cannot see: an AI agent working, whose tool calls keep
|
||||
// scrolling in while the viewer only waits for its answer. Take its bounds from activity.mjs,
|
||||
// which prints when each region changes in seconds of <in.mp4>, never from wall-clock logs.
|
||||
//
|
||||
// regions.json lists the areas to watch, in pixels of <in.mp4>. A pixel changes when its gray
|
||||
// level moves by more than 40 between two samples (10 per second); a region is active when more
|
||||
// than `min` pixels change. Set `min` above what a blinking cursor changes (one cell, 170-210 px at
|
||||
// font size 15) and below what typing changes (several cells per sample).
|
||||
// `unlessLike` ignores a region's changes while a part of it still looks as it did at `at`
|
||||
// seconds, e.g. a status line whose timer ticks while the app works but whose row also receives
|
||||
// real output once the work is done.
|
||||
// [{ "name": "status", "x": 0, "y": 670, "w": 820, "h": 35, "min": 30,
|
||||
// "unlessLike": { "x": 40, "y": 675, "w": 72, "h": 22, "at": 40 } }]
|
||||
//
|
||||
// Writes <out>.regions.json, the regions with each unlessLike.at moved onto the output's timeline,
|
||||
// for activity.mjs and narrate.mjs on the cut file.
|
||||
// Writes <out>.cuts-<n>.png: for every cut, the last frame kept before it beside the first
|
||||
// frame kept after it. Read them before trusting the cut: the two frames of a row must show the
|
||||
// same content, apart from what ticks.
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { die, launchBrowser, need, probe, sampleRegions } from './lib.mjs'
|
||||
|
||||
const [input, output, regionsFile, ...rest] = process.argv.slice(2)
|
||||
if (!regionsFile) die('usage: node cut-waits.mjs <in.mp4> <out.mp4> <regions.json> [--plan] [--min-gap=3] ...')
|
||||
need('ffmpeg', 'ffprobe')
|
||||
const forced = rest
|
||||
.filter((a) => a.startsWith('--cut='))
|
||||
.map((a) => {
|
||||
const [from, to] = a.slice('--cut='.length).split('-').map(Number)
|
||||
if (!(to > from)) die(`bad ${a}: expected --cut=<from>-<to> in seconds`)
|
||||
return { from, to }
|
||||
})
|
||||
const opt = Object.fromEntries(
|
||||
rest
|
||||
.filter((a) => !a.startsWith('--cut='))
|
||||
.map((a) => {
|
||||
const [k, v] = a.replace(/^--/, '').split('=')
|
||||
return [k, v === undefined ? true : Number(v)]
|
||||
})
|
||||
)
|
||||
const minGap = opt['min-gap'] ?? 3
|
||||
const head = opt.head ?? 0.7
|
||||
const tail = opt.tail ?? 0.3
|
||||
const endHold = opt['end-hold'] ?? 5
|
||||
const labelY = opt['label-y'] ?? 12
|
||||
if (minGap < head + tail) die(`--min-gap must be at least --head + --tail (${head + tail} s)`)
|
||||
const regions = JSON.parse(readFileSync(regionsFile, 'utf8'))
|
||||
const { fps, duration, hasAudio } = probe(input)
|
||||
|
||||
// 1. Measure: the samples where any watched region changes.
|
||||
const active = (await sampleRegions(input, regions)).filter((s) => s.active).map((s) => s.t)
|
||||
if (!active.length) {
|
||||
console.error('nothing changes in the watched regions')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
// 2. Plan: shrink every stretch of at least minGap between two changes, and the ending.
|
||||
const measured = []
|
||||
if (active[0] >= minGap) measured.push({ from: head, to: active[0] - tail })
|
||||
for (let i = 1; i < active.length; i++) {
|
||||
const [a, b] = [active[i - 1], active[i]]
|
||||
if (b - a >= minGap) measured.push({ from: a + head, to: b - tail })
|
||||
}
|
||||
// Cuts less than half a second apart become one: the sliver between them would only flash.
|
||||
const cuts = []
|
||||
for (const c of [...measured, ...forced].sort((a, b) => a.from - b.from)) {
|
||||
const prev = cuts.at(-1)
|
||||
if (prev && c.from <= prev.to + 0.5) prev.to = Math.max(prev.to, c.to)
|
||||
else cuts.push({ ...c })
|
||||
}
|
||||
const last = active.at(-1)
|
||||
if (duration - last > endHold + 0.2) {
|
||||
const from = last + endHold
|
||||
const prev = cuts.at(-1)
|
||||
if (prev && prev.to >= from - 0.5) Object.assign(prev, { to: duration, end: true })
|
||||
else cuts.push({ from, to: duration, end: true })
|
||||
}
|
||||
// Cuts fall on frame times and the render keeps each segment half-open (select, below), so the
|
||||
// output has exactly the planned frames and the times printed and mapped here are the rendered ones.
|
||||
const snap = (t) => Math.round(t * fps) / fps
|
||||
for (const c of cuts) Object.assign(c, { from: snap(c.from), to: c.end ? duration : snap(c.to) })
|
||||
const kept = []
|
||||
let cursor = 0
|
||||
for (const c of cuts) {
|
||||
kept.push([cursor, c.from])
|
||||
cursor = c.to
|
||||
}
|
||||
if (cursor < duration) kept.push([cursor, duration])
|
||||
let outAt = 0
|
||||
cuts.forEach((c, k) => {
|
||||
outAt += kept[k][1] - kept[k][0]
|
||||
c.outAt = outAt
|
||||
c.label = `${Math.round(c.to - c.from)} s later`
|
||||
})
|
||||
const outDuration = kept.reduce((s, [a, b]) => s + b - a, 0)
|
||||
const clock = (s) => `${Math.floor(s / 60)}:${(s % 60).toFixed(1).padStart(4, '0')}`
|
||||
for (const c of cuts)
|
||||
console.log(
|
||||
`${c.end ? 'end' : 'cut'} ${c.from.toFixed(1).padStart(6)} -> ${c.to.toFixed(1).padStart(6)} ` +
|
||||
`${(c.to - c.from).toFixed(1).padStart(5)} s removed, at ${clock(c.outAt)} in the output` +
|
||||
(c.end ? '' : ` "${c.label}"`)
|
||||
)
|
||||
console.log(`duration ${duration.toFixed(1)} s -> ${outDuration.toFixed(1)} s`)
|
||||
|
||||
// The regions for the cut file: an `unlessLike.at` is a time of the file it samples, so it moves
|
||||
// with the cut. A time inside a cut moves to the cut's position in the output.
|
||||
const toOutput = (t) => {
|
||||
let base = 0
|
||||
for (const [a, b] of kept) {
|
||||
if (t < a) return base
|
||||
if (t <= b) return base + t - a
|
||||
base += b - a
|
||||
}
|
||||
return outDuration
|
||||
}
|
||||
const outRegions = output.replace(/\.mp4$/, '') + '.regions.json'
|
||||
writeFileSync(
|
||||
outRegions,
|
||||
JSON.stringify(
|
||||
regions.map((r) => (r.unlessLike ? { ...r, unlessLike: { ...r.unlessLike, at: +toOutput(r.unlessLike.at).toFixed(2) } } : r)),
|
||||
null,
|
||||
1
|
||||
)
|
||||
)
|
||||
console.log(`regions of the output: ${outRegions}`)
|
||||
|
||||
// 3. Check sheets: the frames on both sides of every cut.
|
||||
const work = mkdtempSync(join(tmpdir(), 'cut-waits-'))
|
||||
const shot = (t, file) =>
|
||||
execFileSync('ffmpeg', ['-v', 'error', '-y', '-ss', t.toFixed(3), '-i', input, '-frames:v', '1', '-vf', 'scale=640:-2', file])
|
||||
const rows = cuts.filter((c) => !c.end)
|
||||
for (let s = 0; s * 4 < rows.length; s++) {
|
||||
const files = []
|
||||
rows.slice(s * 4, s * 4 + 4).forEach((c, k) => {
|
||||
const a = join(work, `s${s}r${k}a.png`)
|
||||
const b = join(work, `s${s}r${k}b.png`)
|
||||
shot(Math.max(0, c.from - 1 / fps), a)
|
||||
shot(c.to, b)
|
||||
files.push(a, b)
|
||||
})
|
||||
const n = files.length / 2
|
||||
const graph =
|
||||
files.map((_, i) => (i % 2 ? '' : `[${i}][${i + 1}]hstack[r${i / 2}];`)).join('') +
|
||||
(n > 1 ? `${[...Array(n).keys()].map((i) => `[r${i}]`).join('')}vstack=inputs=${n}` : '[r0]null')
|
||||
const sheet = output.replace(/\.mp4$/, '') + `.cuts-${s + 1}.png`
|
||||
execFileSync('ffmpeg', ['-v', 'error', '-y', ...files.flatMap((f) => ['-i', f]), '-filter_complex', graph, sheet])
|
||||
console.log(`check: ${sheet}`)
|
||||
}
|
||||
if (opt.plan) process.exit(0)
|
||||
|
||||
// 4. Notes, drawn by the browser: Homebrew's ffmpeg has no text filters.
|
||||
const browser = await launchBrowser()
|
||||
const page = await browser.newPage({ viewport: { width: 600, height: 120 } })
|
||||
const notes = new Map()
|
||||
for (const c of rows) {
|
||||
if (notes.has(c.label)) continue
|
||||
await page.setContent(
|
||||
`<body style="margin:0;background:transparent"><div style="display:inline-block;padding:8px 16px;` +
|
||||
`border-radius:999px;background:rgba(17,17,17,.85);border:1px solid rgba(255,255,255,.3);` +
|
||||
`color:#fff;font:600 18px/1 system-ui,sans-serif"></div></body>`
|
||||
)
|
||||
await page.locator('div').evaluate((el, t) => (el.textContent = t), `⏩ ${c.label}`)
|
||||
const file = join(work, `note${notes.size}.png`)
|
||||
await page.locator('div').screenshot({ path: file, omitBackground: true })
|
||||
notes.set(c.label, file)
|
||||
}
|
||||
await browser.close()
|
||||
|
||||
// 5. Render: keep the segments, retime them, show each note for a moment after its cut.
|
||||
const noteFiles = [...notes.values()]
|
||||
// Half a frame below each bound, so a frame exactly on a bound is kept once, by the later segment.
|
||||
const half = 0.5 / fps
|
||||
const keep = kept.map(([a, b]) => `gte(t,${(a - half).toFixed(4)})*lt(t,${(b - half).toFixed(4)})`).join('+')
|
||||
// The second fps= restores the frame rate FFmpeg 7's setpts clears; without it the overlays
|
||||
// below fall back to 25 fps.
|
||||
const filters = [`[0:v]fps=${fps},select='${keep}',setpts=N/(${fps}*TB),fps=${fps}[v0]`]
|
||||
rows.forEach((c, k) => {
|
||||
const next = rows[k + 1]?.outAt ?? outDuration
|
||||
const e = Math.min(c.outAt + 1.4, next)
|
||||
const input = 1 + noteFiles.indexOf(notes.get(c.label))
|
||||
filters.push(
|
||||
`[v${k}][${input}:v]overlay=x=(W-w)/2:y=${labelY}:enable='between(t,${c.outAt.toFixed(3)},${e.toFixed(3)})'[v${k + 1}]`
|
||||
)
|
||||
})
|
||||
execFileSync(
|
||||
'ffmpeg',
|
||||
[
|
||||
'-v', 'error', '-y', '-i', input,
|
||||
...noteFiles.flatMap((f) => ['-i', f]),
|
||||
'-filter_complex', filters.join(';'),
|
||||
'-map', `[v${rows.length}]`, '-an',
|
||||
'-c:v', 'libx264', '-crf', '20', '-preset', 'medium', '-pix_fmt', 'yuv420p', '-movflags', '+faststart',
|
||||
output
|
||||
],
|
||||
{ stdio: ['ignore', 'inherit', 'inherit'] }
|
||||
)
|
||||
if (hasAudio) console.log('note: the input had audio; the output has none')
|
||||
console.log(output)
|
||||
@@ -0,0 +1,210 @@
|
||||
// Shared by the demo-video scripts, and imported by the browser scripts written for a terminal
|
||||
// take: `import { launchBrowser, waitForOutput } from '<repo>/.agents/skills/demo-video/lib.mjs'`.
|
||||
import { createRequire } from 'node:module'
|
||||
import { execFileSync, spawn } from 'node:child_process'
|
||||
import { readdirSync, readFileSync, realpathSync, statSync } from 'node:fs'
|
||||
import { homedir } from 'node:os'
|
||||
import { dirname, join } from 'node:path'
|
||||
import { fileURLToPath } from 'node:url'
|
||||
|
||||
export const CODEX_SESSIONS = join(homedir(), '.codex/sessions')
|
||||
export const CLAUDE_PROJECTS = join(homedir(), '.claude/projects')
|
||||
|
||||
export function die(message) {
|
||||
console.error(message)
|
||||
process.exit(2)
|
||||
}
|
||||
|
||||
const HINTS = {
|
||||
ffmpeg: 'brew install ffmpeg',
|
||||
ffprobe: 'brew install ffmpeg',
|
||||
vhs: 'brew install vhs',
|
||||
say: 'macOS only; use voice: false in a scenario or --voice=none for captions without speech'
|
||||
}
|
||||
export function need(...commands) {
|
||||
for (const c of commands) {
|
||||
try {
|
||||
execFileSync('which', [c], { stdio: 'ignore' })
|
||||
} catch {
|
||||
die(`${c} not found: ${HINTS[c] ?? 'install it'}`)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The skill pins its own Playwright rather than using frontend/'s, whose older pin may not
|
||||
// install its browser on a current Node.
|
||||
const SKILL = dirname(fileURLToPath(import.meta.url))
|
||||
export function playwright() {
|
||||
try {
|
||||
return createRequire(import.meta.url)('playwright')
|
||||
} catch {
|
||||
die(`Playwright not found: run \`npm ci --prefix ${SKILL}\``)
|
||||
}
|
||||
}
|
||||
export async function launchBrowser(options) {
|
||||
try {
|
||||
return await playwright().chromium.launch(options)
|
||||
} catch (err) {
|
||||
if (/Executable doesn't exist/.test(err.message))
|
||||
die(`Playwright's Chromium is not installed: run \`npx --prefix ${SKILL} playwright install chromium\``)
|
||||
throw err
|
||||
}
|
||||
}
|
||||
|
||||
export function probe(file) {
|
||||
const info = JSON.parse(
|
||||
execFileSync('ffprobe', ['-v', 'error', '-show_streams', '-show_format', '-of', 'json', file])
|
||||
)
|
||||
const vs = info.streams.find((s) => s.codec_type === 'video')
|
||||
const [num, den] = (vs?.r_frame_rate ?? '0/1').split('/').map(Number)
|
||||
return {
|
||||
width: vs?.width,
|
||||
height: vs?.height,
|
||||
fps: num / den,
|
||||
duration: Number(info.format.duration),
|
||||
hasAudio: info.streams.some((s) => s.codec_type === 'audio')
|
||||
}
|
||||
}
|
||||
|
||||
// One narration line as speech. With voice 'none' nothing is spoken and the line lasts as long
|
||||
// as it takes to read.
|
||||
export function speak(text, file, { voice, rate = 0 }) {
|
||||
if (voice === 'none') return { file: null, length: Math.max(1.5, text.split(/\s+/).length / 2.7) }
|
||||
execFileSync('say', ['-v', voice, ...(rate ? ['-r', String(rate)] : []), '-o', file, text])
|
||||
return { file, length: probe(file).duration }
|
||||
}
|
||||
|
||||
// Caption band images, drawn by the browser: Homebrew's ffmpeg has no text filters.
|
||||
export async function captionImages(browser, texts, { width, height, dir }) {
|
||||
const page = await browser.newPage({ viewport: { width, height } })
|
||||
const files = []
|
||||
for (const [k, text] of texts.entries()) {
|
||||
await page.setContent(
|
||||
`<body style="margin:0;height:${height}px;display:flex;align-items:center;justify-content:center;background:#111;">` +
|
||||
`<div style="max-width:88%;color:#fff;font:500 20px/1.35 system-ui,sans-serif;text-align:center;"></div></body>`
|
||||
)
|
||||
await page.locator('div').evaluate((el, t) => (el.textContent = t), text)
|
||||
files.push(join(dir, `caption${k}.png`))
|
||||
await page.screenshot({ path: files.at(-1) })
|
||||
}
|
||||
await page.close()
|
||||
return files
|
||||
}
|
||||
|
||||
// Samples <input> 10 times a second inside [from, to] and returns, for each sample, how many
|
||||
// pixels of each region changed since the previous one. A pixel changes when its gray level
|
||||
// moves by more than 40. `suppressed[k]` is true while region k's `unlessLike` part still looks
|
||||
// as it did at `unlessLike.at`; `active` is whether any region changed by more than its `min`.
|
||||
export const SAMPLES = 10
|
||||
export async function sampleRegions(input, regions, { from = 0, to } = {}) {
|
||||
const { width: W, height: H } = probe(input)
|
||||
const grayFrame = (t) =>
|
||||
execFileSync(
|
||||
'ffmpeg',
|
||||
['-v', 'error', '-ss', String(t), '-i', input, '-frames:v', '1', '-f', 'rawvideo', '-pix_fmt', 'gray', '-'],
|
||||
{ maxBuffer: W * H * 2 }
|
||||
)
|
||||
const lit = (frame, a) => {
|
||||
const bits = new Uint8Array(a.w * a.h)
|
||||
for (let y = 0; y < a.h; y++)
|
||||
for (let x = 0; x < a.w; x++) bits[y * a.w + x] = frame[(a.y + y) * W + a.x + x] > 70 ? 1 : 0
|
||||
return bits
|
||||
}
|
||||
const refs = regions.map((r) => {
|
||||
if (!r.unlessLike) return null
|
||||
const ref = lit(grayFrame(r.unlessLike.at), r.unlessLike)
|
||||
return { ref, lit: ref.reduce((s, b) => s + b, 0) }
|
||||
})
|
||||
const looksLike = (frame, k) => {
|
||||
const bits = lit(frame, regions[k].unlessLike)
|
||||
let diff = 0
|
||||
for (let i = 0; i < bits.length; i++) diff += bits[i] !== refs[k].ref[i]
|
||||
return diff < 0.25 * Math.max(refs[k].lit, 1)
|
||||
}
|
||||
const samples = []
|
||||
await new Promise((done, fail) => {
|
||||
const range = ['-ss', String(from), ...(to !== undefined ? ['-to', String(to)] : [])]
|
||||
const ff = spawn('ffmpeg', ['-v', 'error', ...range, '-i', input, '-vf', `fps=${SAMPLES},format=gray`, '-f', 'rawvideo', '-'])
|
||||
const size = W * H
|
||||
let buf = Buffer.alloc(0)
|
||||
let prev = null
|
||||
let prevLike = []
|
||||
let n = 0
|
||||
ff.stdout.on('data', (chunk) => {
|
||||
buf = Buffer.concat([buf, chunk])
|
||||
while (buf.length >= size) {
|
||||
const frame = Buffer.from(buf.subarray(0, size))
|
||||
buf = buf.subarray(size)
|
||||
const like = regions.map((r, k) => (r.unlessLike ? looksLike(frame, k) : false))
|
||||
if (prev) {
|
||||
const changed = regions.map((r) => {
|
||||
let c = 0
|
||||
for (let y = r.y; y < r.y + r.h; y++)
|
||||
for (let x = r.x, i = y * W + r.x; x < r.x + r.w; x++, i++) {
|
||||
const d = frame[i] - prev[i]
|
||||
if (d > 40 || d < -40) c++
|
||||
}
|
||||
return c
|
||||
})
|
||||
const suppressed = like.map((l, k) => l && prevLike[k])
|
||||
const active = regions.some((r, k) => !suppressed[k] && changed[k] > r.min)
|
||||
samples.push({ t: from + n / SAMPLES, changed, suppressed, active })
|
||||
}
|
||||
prev = frame
|
||||
prevLike = like
|
||||
n++
|
||||
}
|
||||
})
|
||||
ff.on('close', (code) => (code === 0 ? done() : fail(new Error(`ffmpeg exited ${code}`))))
|
||||
})
|
||||
return samples
|
||||
}
|
||||
|
||||
// Waits until the agent session started in `cwd` writes `pattern` to its log, and returns the
|
||||
// match. Only that folder's sessions count: other agents on the machine (a review running in
|
||||
// the same worktree, the recording agent itself) write logs at the same time.
|
||||
// - agent 'codex': files under ~/.codex/sessions whose session_meta names `cwd`. The per-day
|
||||
// folder may not exist when the wait starts; it is looked for again on every poll.
|
||||
// - agent 'claude': files under ~/.claude/projects/<cwd with every other character as ->.
|
||||
// - dirs: any other folders, searched without a cwd check.
|
||||
// Only files written after `since` are read. Logs are JSON: end the pattern before `"` and `\`;
|
||||
// JSON-escaped ampersands (backslash u0026) are turned back into `&` before matching.
|
||||
export async function waitForOutput(
|
||||
pattern,
|
||||
{ agent, cwd = process.cwd(), dirs, since = Date.now(), timeout = 300_000, every = 1000 } = {}
|
||||
) {
|
||||
const real = realpathSync(cwd)
|
||||
const roots =
|
||||
dirs ?? (agent === 'claude' ? [join(CLAUDE_PROJECTS, real.replace(/[^a-zA-Z0-9-]/g, '-'))] : [CODEX_SESSIONS])
|
||||
const mark = agent === 'codex' || (!agent && !dirs) ? `"cwd":${JSON.stringify(real)}` : null
|
||||
const walk = (dir, out) => {
|
||||
try {
|
||||
for (const e of readdirSync(dir, { withFileTypes: true })) {
|
||||
const p = join(dir, e.name)
|
||||
if (e.isDirectory()) walk(p, out)
|
||||
else if (e.isFile()) out.push(p)
|
||||
}
|
||||
} catch {
|
||||
// not created yet, or removed during the poll
|
||||
}
|
||||
return out
|
||||
}
|
||||
const deadline = Date.now() + timeout
|
||||
while (Date.now() < deadline) {
|
||||
for (const root of roots)
|
||||
for (const file of walk(root, [])) {
|
||||
try {
|
||||
if (statSync(file).mtimeMs < since) continue
|
||||
const text = readFileSync(file, 'utf8')
|
||||
if (mark && !text.includes(mark)) continue
|
||||
const m = text.replace(/\\u0026/g, '&').match(pattern)
|
||||
if (m) return m
|
||||
} catch {
|
||||
// written or removed while being read: look again on the next poll
|
||||
}
|
||||
}
|
||||
await new Promise((r) => setTimeout(r, every))
|
||||
}
|
||||
throw new Error(`no match for ${pattern} in ${roots.join(', ')} after ${Math.round(timeout / 1000)} s`)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,209 @@
|
||||
// Lays a spoken voice-over on a silent video: one text-to-speech line (macOS `say`) per entry,
|
||||
// started at the moment of the video it describes. When a line still runs at the next line's
|
||||
// moment, the video holds the frame of that moment until the line ends, so picture and speech
|
||||
// stay together.
|
||||
//
|
||||
// usage: node narrate.mjs <in.mp4> <lines.json> <out.mp4> [options]
|
||||
// --plan speak the lines and print where they land, render nothing
|
||||
// --regions=<file> regions.json of <in.mp4>: warn about a line whose `at` falls just after
|
||||
// a change started, since its caption would then land after that change
|
||||
// --voice=Samantha macOS voice (say -v '?'); --voice=none speaks nothing and gives each
|
||||
// line its reading time, for a machine without `say`
|
||||
// --rate=0 words per minute for say; 0 keeps the voice's own
|
||||
// --gap=0.4 silence between two lines (s)
|
||||
// --end-hold=1.5 keep the last frame this long after the last line (s)
|
||||
// --vtt=<file> also write the lines as WebVTT captions, on the output's timeline
|
||||
// --cues=<file> also write them as JSON [[start, end, text], ...], for a text track
|
||||
// added from inline JS on a page that cannot serve .vtt files
|
||||
// --caption-height=96 height of the caption band added below the video (two lines of text)
|
||||
// --caption-at=top put the band above the video instead
|
||||
// --no-band burn in no captions: the output keeps the input's size
|
||||
//
|
||||
// Each line shows in the band from its start until the next line starts, so captions never
|
||||
// cover the recording.
|
||||
//
|
||||
// lines.json: [{ "at": 0.4, "text": "One sentence about what is on screen." }, ...], `at` in
|
||||
// seconds of <in.mp4>, increasing. Anchor a line a little before the change it describes: a
|
||||
// hold freezes the frame at `at`, so a line anchored after its change starts only once that
|
||||
// change has already played.
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { mkdtempSync, readFileSync, writeFileSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join } from 'node:path'
|
||||
import { captionImages, die, launchBrowser, need, probe, sampleRegions, speak } from './lib.mjs'
|
||||
|
||||
const [input, linesFile, output, ...rest] = process.argv.slice(2)
|
||||
if (!output) die('usage: node narrate.mjs <in.mp4> <lines.json> <out.mp4> [--plan] [--voice=Samantha] [--gap=0.4] ...')
|
||||
const opt = Object.fromEntries(
|
||||
rest.map((a) => {
|
||||
const [k, ...v] = a.replace(/^--/, '').split('=')
|
||||
return [k, v.length ? v.join('=') : true]
|
||||
})
|
||||
)
|
||||
const voice = opt.voice || 'Samantha'
|
||||
need('ffmpeg', 'ffprobe', ...(voice === 'none' ? [] : ['say']))
|
||||
const rate = Number(opt.rate || 0)
|
||||
const gap = Number(opt.gap ?? 0.4)
|
||||
const endHold = Number(opt['end-hold'] ?? 1.5)
|
||||
const lines = JSON.parse(readFileSync(linesFile, 'utf8'))
|
||||
lines.forEach((l, i) => {
|
||||
if (i && l.at < lines[i - 1].at) die(`line ${i + 1} starts before line ${i}: sort them by "at"`)
|
||||
})
|
||||
|
||||
const vs = probe(input)
|
||||
const { fps, duration } = vs
|
||||
|
||||
// 1. Speak every line.
|
||||
const work = mkdtempSync(join(tmpdir(), 'narrate-'))
|
||||
const cues = lines.map((l, i) => ({ ...l, ...speak(l.text, join(work, `line${i}.aiff`), { voice, rate }) }))
|
||||
|
||||
// 2. Place them. A line that would start before the previous one ends holds the frame at its
|
||||
// own moment for the difference, which delays everything after it.
|
||||
const holds = new Map()
|
||||
const hold = (at, d) => {
|
||||
const near = [...holds.keys()].find((k) => Math.abs(k - at) < 1 / fps)
|
||||
holds.set(near ?? at, (holds.get(near ?? at) ?? 0) + d)
|
||||
}
|
||||
let shift = 0
|
||||
let prevEnd = -Infinity
|
||||
for (const c of cues) {
|
||||
c.start = c.at + shift
|
||||
c.held = 0
|
||||
// Under a frame of overlap only shortens the gap: a hold that short would show nothing.
|
||||
if (c.start < prevEnd + gap - 1 / fps) {
|
||||
c.held = prevEnd + gap - c.start
|
||||
hold(c.at, c.held)
|
||||
shift += c.held
|
||||
c.start += c.held
|
||||
}
|
||||
c.end = c.start + c.length
|
||||
prevEnd = c.end
|
||||
}
|
||||
let outDuration = duration + shift
|
||||
if (prevEnd + endHold > outDuration) {
|
||||
hold(duration, prevEnd + endHold - outDuration)
|
||||
outDuration = prevEnd + endHold
|
||||
}
|
||||
|
||||
// A change that starts in the 0.6 s before a line's `at` is one the line most likely describes.
|
||||
const late = new Map()
|
||||
if (opt.regions) {
|
||||
const regions = JSON.parse(readFileSync(opt.regions, 'utf8'))
|
||||
const samples = await sampleRegions(input, regions)
|
||||
const starts = []
|
||||
samples.forEach((s, i) => {
|
||||
if (!s.active) return
|
||||
const quietBefore = !samples.slice(Math.max(0, i - 5), i).some((p) => p.active)
|
||||
if (quietBefore)
|
||||
starts.push({ t: s.t, region: regions.find((r, k) => !s.suppressed[k] && s.changed[k] > r.min).name })
|
||||
})
|
||||
cues.forEach((c, i) => {
|
||||
const s = starts.find((s) => s.t > c.at - 0.6 && s.t <= c.at)
|
||||
if (s) late.set(i, s)
|
||||
})
|
||||
}
|
||||
|
||||
const clock = (s) => `${Math.floor(s / 60)}:${(s % 60).toFixed(1).padStart(4, '0')}`
|
||||
for (const [i, c] of cues.entries()) {
|
||||
console.log(
|
||||
`${clock(c.start)}-${clock(c.end)} at ${c.at.toFixed(1).padStart(5)}` +
|
||||
(c.held ? ` holds ${c.held.toFixed(1)} s` : '') +
|
||||
` ${c.text}`
|
||||
)
|
||||
if (c.held > 1)
|
||||
console.log(` ^ line ${i} runs ${c.held.toFixed(1)} s into this one's moment: shorten line ${i}`)
|
||||
const s = late.get(i)
|
||||
if (s)
|
||||
console.log(` ^ ${s.region} starts changing at ${s.t.toFixed(1)}, before this line: anchor it at ${Math.max(0, s.t - 0.3).toFixed(1)}`)
|
||||
}
|
||||
console.log(`duration ${duration.toFixed(1)} s -> ${outDuration.toFixed(1)} s`)
|
||||
|
||||
// The band shows each caption until the next line starts.
|
||||
const shown = cues.map((c, k) => [c.start, k + 1 < cues.length ? cues[k + 1].start : outDuration, c.text])
|
||||
if (opt.vtt) {
|
||||
const stamp = (s) => {
|
||||
const ms = Math.round(s * 1000)
|
||||
const p = (n, w = 2) => String(n).padStart(w, '0')
|
||||
return `${p(Math.floor(ms / 3600000))}:${p(Math.floor(ms / 60000) % 60)}:${p(Math.floor(ms / 1000) % 60)}.${p(ms % 1000, 3)}`
|
||||
}
|
||||
writeFileSync(
|
||||
opt.vtt,
|
||||
'WEBVTT\n\n' + cues.map((c, k) => `${k + 1}\n${stamp(c.start)} --> ${stamp(c.end)}\n${c.text}\n`).join('\n')
|
||||
)
|
||||
console.log(`captions: ${opt.vtt}`)
|
||||
}
|
||||
if (opt.cues) {
|
||||
writeFileSync(opt.cues, JSON.stringify(shown.map(([s, e, t]) => [+s.toFixed(2), +e.toFixed(2), t])))
|
||||
console.log(`cues: ${opt.cues}`)
|
||||
}
|
||||
if (opt.plan) process.exit(0)
|
||||
|
||||
// 3. Caption band images.
|
||||
const band = opt['no-band'] ? 0 : Number(opt['caption-height'] ?? 96)
|
||||
if (band % 2 || vs.height % 2 || vs.width % 2) die('video width, height and --caption-height must all be even for H.264')
|
||||
const top = opt['caption-at'] === 'top'
|
||||
if (band) {
|
||||
const browser = await launchBrowser()
|
||||
try {
|
||||
const images = await captionImages(
|
||||
browser,
|
||||
cues.map((c) => c.text),
|
||||
{ width: vs.width, height: band, dir: work }
|
||||
)
|
||||
images.forEach((f, k) => (cues[k].image = f))
|
||||
} finally {
|
||||
await browser.close()
|
||||
}
|
||||
}
|
||||
|
||||
// 4. Render: the video cut at every hold, each piece padded with its last frame, then the
|
||||
// lines delayed to their start and mixed.
|
||||
const filters = []
|
||||
const pieces = []
|
||||
let from = 0
|
||||
for (const p of [...holds.keys()].sort((a, b) => a - b)) {
|
||||
// fps= restores the frame rate FFmpeg 7's setpts clears; without it tpad adds no frames.
|
||||
filters.push(
|
||||
`[0:v]trim=start=${from.toFixed(3)}:end=${p.toFixed(3)},setpts=PTS-STARTPTS,fps=${fps},` +
|
||||
`tpad=stop_mode=clone:stop_duration=${holds.get(p).toFixed(3)}[p${pieces.length}]`
|
||||
)
|
||||
pieces.push(`[p${pieces.length}]`)
|
||||
from = p
|
||||
}
|
||||
if (duration - from > 1 / fps) {
|
||||
filters.push(`[0:v]trim=start=${from.toFixed(3)},setpts=PTS-STARTPTS[p${pieces.length}]`)
|
||||
pieces.push(`[p${pieces.length}]`)
|
||||
}
|
||||
filters.push(
|
||||
`${pieces.join('')}concat=n=${pieces.length}:v=1:a=0,fps=${fps}` +
|
||||
(band ? `,pad=${vs.width}:${vs.height + band}:0:${top ? band : 0}:color=#111111[c0]` : `,format=yuv420p[v]`)
|
||||
)
|
||||
const spoken = cues.filter((c) => c.file)
|
||||
if (band) {
|
||||
const firstImage = spoken.length + 1
|
||||
shown.forEach(([s, e], k) => {
|
||||
filters.push(
|
||||
`[c${k}][${firstImage + k}:v]overlay=0:${top ? 0 : vs.height}:` +
|
||||
`enable='between(t,${s.toFixed(3)},${e.toFixed(3)})'[c${k + 1}]`
|
||||
)
|
||||
})
|
||||
filters.push(`[c${cues.length}]format=yuv420p[v]`)
|
||||
}
|
||||
spoken.forEach((c, k) => filters.push(`[${k + 1}:a]adelay=${Math.round(c.start * 1000)}:all=1[a${k}]`))
|
||||
if (spoken.length)
|
||||
filters.push(`${spoken.map((_, k) => `[a${k}]`).join('')}amix=inputs=${spoken.length}:normalize=0,apad[a]`)
|
||||
execFileSync(
|
||||
'ffmpeg',
|
||||
[
|
||||
'-v', 'error', '-y', '-i', input,
|
||||
...spoken.flatMap((c) => ['-i', c.file]),
|
||||
...(band ? cues.flatMap((c) => ['-i', c.image]) : []),
|
||||
'-filter_complex', filters.join(';'),
|
||||
'-map', '[v]', ...(spoken.length ? ['-map', '[a]', '-c:a', 'aac', '-b:a', '128k'] : []),
|
||||
'-t', outDuration.toFixed(3),
|
||||
'-c:v', 'libx264', '-crf', '20', '-preset', 'medium', '-movflags', '+faststart',
|
||||
output
|
||||
],
|
||||
{ stdio: ['ignore', 'inherit', 'inherit'] }
|
||||
)
|
||||
console.log(output)
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
{
|
||||
"name": "demo-video",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "demo-video",
|
||||
"dependencies": {
|
||||
"playwright": "1.65.1"
|
||||
}
|
||||
},
|
||||
"node_modules/playwright": {
|
||||
"version": "1.65.1",
|
||||
"resolved": "https://registry.npmjs.org/playwright/-/playwright-1.65.1.tgz",
|
||||
"integrity": "sha512-vJ1FuoOrNwOKHUIVEvSt3jT1L+wjjDpwhwIstKtfvTh8XIG4FG4bIFuvNdMxi81LGfAhUgUZleVFaOLY4RIUUw==",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"playwright-core": "1.65.1"
|
||||
},
|
||||
"bin": {
|
||||
"playwright": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
},
|
||||
"node_modules/playwright-core": {
|
||||
"version": "1.65.1",
|
||||
"resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.65.1.tgz",
|
||||
"integrity": "sha512-hqPpz7blSMPxWVdoeE1yiBSzXsKiVOd2k+kjCvmUywD2GPO2Dd9HfcWnq9NN0GHbNZDFgZ9JfBFr+X5/BLo0qw==",
|
||||
"license": "Apache-2.0",
|
||||
"bin": {
|
||||
"playwright-core": "cli.js"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=20"
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"name": "demo-video",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"dependencies": {
|
||||
"playwright": "1.65.1"
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,154 @@
|
||||
#!/usr/bin/env node
|
||||
// Usage: node record.mjs <scenario.mjs> [out.mp4]
|
||||
// Prints the mp4 path on success; on a failed step, the step and a screenshot path.
|
||||
import { execFileSync } from 'node:child_process'
|
||||
import { mkdtempSync, readdirSync } from 'node:fs'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { join, resolve, dirname, basename } from 'node:path'
|
||||
import { pathToFileURL } from 'node:url'
|
||||
import { captionImages, die, launchBrowser, need, speak } from './lib.mjs'
|
||||
|
||||
const [scenarioPath, outArg] = process.argv.slice(2)
|
||||
if (!scenarioPath) die('usage: node record.mjs <scenario.mjs> [out.mp4]')
|
||||
const sc = (await import(pathToFileURL(resolve(scenarioPath)).href)).default
|
||||
const out = resolve(outArg ?? join(dirname(resolve(scenarioPath)), basename(scenarioPath, '.mjs') + '.mp4'))
|
||||
const work = mkdtempSync(join(tmpdir(), 'demo-video-'))
|
||||
const viewport = sc.viewport ?? { width: 1280, height: 720 }
|
||||
const voice = sc.voice === false ? 'none' : (sc.voice ?? 'Samantha')
|
||||
const BAND = sc.captionHeight ?? 96
|
||||
if (viewport.width % 2 || (viewport.height + BAND) % 2) die('viewport width and height + captionHeight must be even for H.264')
|
||||
need('ffmpeg', 'ffprobe', ...(voice === 'none' ? [] : ['say']))
|
||||
|
||||
// 1. Narration clips, before the browser starts, so recording time is not spent on TTS.
|
||||
const clips = sc.steps.map((s, i) => {
|
||||
if (!s.say) return null
|
||||
const { file, length } = speak(s.say, join(work, `say${i}.aiff`), { voice })
|
||||
return { file, ms: Math.round(length * 1000) }
|
||||
})
|
||||
|
||||
const browser = await launchBrowser()
|
||||
try {
|
||||
// 2. Setup (login, seeding) runs unrecorded; its cookies carry into the recorded context.
|
||||
let storageState
|
||||
if (sc.setup) {
|
||||
const ctx = await browser.newContext({ viewport, baseURL: sc.baseURL })
|
||||
try {
|
||||
await sc.setup({ context: ctx, page: await ctx.newPage(), baseURL: sc.baseURL })
|
||||
} catch (err) {
|
||||
die(`setup failed: ${err.message.split('\n')[0]}`)
|
||||
}
|
||||
storageState = await ctx.storageState()
|
||||
await ctx.close()
|
||||
}
|
||||
const ctx = await browser.newContext({
|
||||
viewport,
|
||||
storageState,
|
||||
baseURL: sc.baseURL,
|
||||
recordVideo: { dir: work, size: viewport }
|
||||
})
|
||||
const page = await ctx.newPage()
|
||||
const t0rec = Date.now()
|
||||
|
||||
// Helpers handed to each step: a visible ring on what is clicked, so the viewer can follow.
|
||||
const ring = (loc) =>
|
||||
loc
|
||||
.evaluate((el) => {
|
||||
const r = el.getBoundingClientRect()
|
||||
const d = document.createElement('div')
|
||||
d.style.cssText = `position:fixed;left:${r.left - 4}px;top:${r.top - 4}px;width:${r.width + 8}px;height:${r.height + 8}px;border:3px solid #f43f5e;border-radius:8px;z-index:2147483646;pointer-events:none`
|
||||
document.body.appendChild(d)
|
||||
setTimeout(() => d.remove(), 900)
|
||||
})
|
||||
.catch(() => {})
|
||||
const loc = (t) => (typeof t === 'string' ? page.locator(t).first() : t)
|
||||
const helpers = {
|
||||
page,
|
||||
click: async (t) => {
|
||||
const l = loc(t)
|
||||
await l.scrollIntoViewIfNeeded()
|
||||
await ring(l)
|
||||
await page.waitForTimeout(500)
|
||||
await l.click()
|
||||
},
|
||||
hover: async (t) => {
|
||||
const l = loc(t)
|
||||
await l.scrollIntoViewIfNeeded()
|
||||
await ring(l)
|
||||
await l.hover()
|
||||
},
|
||||
wait: (ms) => page.waitForTimeout(ms)
|
||||
}
|
||||
|
||||
if (sc.start) await page.goto(sc.start, { waitUntil: 'networkidle' })
|
||||
await page.waitForTimeout(sc.settle ?? 800)
|
||||
const trimStart = Date.now() - t0rec
|
||||
const cues = []
|
||||
// Each caption shows from its step's start to the next captioned step's start.
|
||||
const captions = []
|
||||
|
||||
// 3. A step's narration starts before its action, and the step stays on screen until both
|
||||
// are done, so a caption never lands after what it describes.
|
||||
for (const [i, s] of sc.steps.entries()) {
|
||||
const at = Date.now() - t0rec
|
||||
if (s.say) {
|
||||
if (captions.length) captions.at(-1).end = at - trimStart
|
||||
captions.push({ text: s.say, start: at - trimStart })
|
||||
}
|
||||
try {
|
||||
if (s.do) await s.do(helpers)
|
||||
} catch (err) {
|
||||
const shot = join(work, `failed-step${i}.png`)
|
||||
await page.screenshot({ path: shot }).catch(() => {})
|
||||
console.error(`step ${i} failed (${s.say ?? 'no narration'}): ${err.message.split('\n')[0]}`)
|
||||
console.error(`screenshot: ${shot}`)
|
||||
process.exitCode = 1
|
||||
break
|
||||
}
|
||||
const left = (clips[i]?.ms ?? 0) + (sc.pad ?? 400) - (Date.now() - t0rec - at)
|
||||
if (left > 0) await page.waitForTimeout(left)
|
||||
if (s.hold) await page.waitForTimeout(s.hold)
|
||||
if (clips[i]?.file) cues.push({ file: clips[i].file, delay: at - trimStart })
|
||||
}
|
||||
await page.waitForTimeout(600)
|
||||
const total = (Date.now() - t0rec - trimStart) / 1000
|
||||
if (captions.length) captions.at(-1).end = total * 1000
|
||||
await ctx.close()
|
||||
if (process.exitCode) process.exit()
|
||||
|
||||
// 4. Captions in a band of their own beside the page, so they never cover it.
|
||||
const images = await captionImages(
|
||||
browser,
|
||||
captions.map((c) => c.text),
|
||||
{ width: viewport.width, height: BAND, dir: work }
|
||||
)
|
||||
|
||||
// 5. Mux: cut the pre-roll, add the caption band, show each caption during its step, lay
|
||||
// each narration clip at its step's start, encode an mp4.
|
||||
const video = join(work, readdirSync(work).find((f) => f.endsWith('.webm')))
|
||||
const args = ['-y', '-loglevel', 'error', '-ss', String(trimStart / 1000), '-i', video]
|
||||
images.forEach((f) => args.push('-i', f))
|
||||
cues.forEach((c) => args.push('-i', c.file))
|
||||
const top = sc.captionAt === 'top'
|
||||
const filters = [
|
||||
`[0:v]pad=${viewport.width}:${viewport.height + BAND}:0:${top ? BAND : 0}:color=#111111[v0]`
|
||||
]
|
||||
captions.forEach((c, k) => {
|
||||
const s = (c.start / 1000).toFixed(2)
|
||||
const e = (c.end / 1000).toFixed(2)
|
||||
filters.push(
|
||||
`[v${k}][${k + 1}:v]overlay=0:${top ? 0 : viewport.height}:enable='between(t,${s},${e})'[v${k + 1}]`
|
||||
)
|
||||
})
|
||||
const audioBase = captions.length + 1
|
||||
cues.forEach((c, k) => filters.push(`[${audioBase + k}:a]adelay=${c.delay}:all=1[a${k}]`))
|
||||
if (cues.length) {
|
||||
filters.push(`${cues.map((_, k) => `[a${k}]`).join('')}amix=inputs=${cues.length}:normalize=0[a]`)
|
||||
}
|
||||
args.push('-filter_complex', filters.join(';'), '-map', `[v${captions.length}]`)
|
||||
if (cues.length) args.push('-map', '[a]', '-c:a', 'aac')
|
||||
args.push('-t', total.toFixed(2), '-c:v', 'libx264', '-pix_fmt', 'yuv420p', '-movflags', '+faststart', out)
|
||||
execFileSync('ffmpeg', args, { stdio: ['ignore', 'inherit', 'inherit'] })
|
||||
console.log(out)
|
||||
} finally {
|
||||
await browser.close()
|
||||
}
|
||||
@@ -0,0 +1,274 @@
|
||||
# Terminal recordings
|
||||
|
||||
A CLI or TUI session recorded with vhs, optionally beside a browser that reacts to it, then its
|
||||
waits cut and a voice-over added. What each tool needs is in `SKILL.md` next to this file.
|
||||
|
||||
The take runs from a folder of the session scratchpad: the tape, the browser script, `vhs` and
|
||||
the agent all start there, so the files they write (mp4, webm, markers, screenshots) never land
|
||||
in a repo. The skill's scripts are called by their path,
|
||||
`node <repo>/.agents/skills/demo-video/<script>.mjs`, from wherever you are.
|
||||
|
||||
Order of work: plant the test data (it must match the story, see `SKILL.md`), record, compose,
|
||||
measure with `activity.mjs`, cut, measure the cut, narrate.
|
||||
|
||||
## Record the terminal (vhs)
|
||||
|
||||
`brew install vhs` (brings ttyd). Tape skeleton:
|
||||
|
||||
```
|
||||
Output term.mp4
|
||||
Set Shell zsh
|
||||
Set FontSize 15
|
||||
Set Width 820
|
||||
Set Height 820
|
||||
Set Padding 16
|
||||
Set TypingSpeed 35ms
|
||||
Hide
|
||||
Type "export MY_TOKEN=$(cat <scratch>/token); clear"
|
||||
Enter
|
||||
Show
|
||||
Type "mycli"
|
||||
Enter
|
||||
Wait+Screen@150s /text that stays once it is done/
|
||||
Sleep 3s
|
||||
```
|
||||
|
||||
- Run `vhs` from the tape's folder with a relative `Output`: an absolute path fails to parse
|
||||
(`Expected file path after output`).
|
||||
- Everything between `Hide` and `Show` runs off camera: logins, tokens, aliases. Never type a
|
||||
secret after `Show`.
|
||||
- `Wait+Screen@150s /regex/` waits until the regex matches anywhere on the screen, up to 150 s.
|
||||
Plain `Wait /regex/` reads only the last line; without `@<time>` the timeout is
|
||||
`Set WaitTimeout`. The typed command is on the screen too, so wait on text it does not
|
||||
contain (`echo "build $(echo finished)"`, then wait on `/build finished/`). A timed-out wait
|
||||
ends the run with only `recording failed` and no mp4.
|
||||
- Once a plain shell's output scrolls, vhs 0.12's `Wait+Screen` no longer sees the bottom rows:
|
||||
`wmill script run` printed its result below the first screenful and a wait on it timed out
|
||||
while the text was on screen. Make the terminal tall enough that the take never scrolls
|
||||
(`Set Height`), or `clear` off camera before the command. Codex renders in the normal
|
||||
buffer and scrolls too: for a long agent turn, a generous `Sleep` is safer than a wait, and
|
||||
the cut removes the idle time. To see what a failing wait missed, replace it with `Sleep` +
|
||||
`Screenshot f.png`.
|
||||
- A CLI that may open with a dialog (Codex's trust prompt, its "Background server has
|
||||
incompatible feature set" prompt after another Codex run changed its settings) is started in
|
||||
the `Hide` block and the dialog answered there (`Type "1"` picks "Run without daemon this
|
||||
time"), so the take opens on the ready prompt.
|
||||
- Wait on text that stays (a question, the final answer), not on a spinner or a status that
|
||||
flips back. `Sleep` only for what the tape cannot see, such as another process acting; the
|
||||
cut step removes idle time afterwards, so err long.
|
||||
- Keep long command lines off camera: define a function in the `Hide` block
|
||||
(`Type "mycli() { command mycli --flag … \"$@\"; }; clear"`) and type only `mycli` after
|
||||
`Show`. 500 characters at 35 ms is 17 s of typing that the cut step keeps.
|
||||
- A Type string holding both quote kinds goes in backticks: ``Type `cmd -c 'a="b"'` ``.
|
||||
- `Screenshot f.png` takes a still. macOS `date` has no `%3N`: take ms timestamps with
|
||||
`node -e 'console.log(Date.now())'`.
|
||||
|
||||
### The mp4 runs shorter than the session
|
||||
|
||||
vhs drops frames when the machine is busy, so its mp4 is shorter than the wall-clock session:
|
||||
151.7 s of video for about 160 s of session in one Codex take, the gap growing over the take.
|
||||
A wall-clock timestamp (an agent's log, a `Date.now()` marker) therefore points at the wrong
|
||||
moment of the video, more so the later it is. Use wall clock only for a first guess at the
|
||||
start of a take; place every cut, alignment and narration line from the picture, with
|
||||
`activity.mjs` (below).
|
||||
|
||||
## Codex CLI, unattended
|
||||
|
||||
```
|
||||
codex -a never -s read-only \
|
||||
-c check_for_update_on_startup=false \
|
||||
-c 'mcp_servers.<name>.url="https://<host>/<mcp path>"' \
|
||||
-c 'mcp_servers.<name>.bearer_token_env_var="MY_TOKEN"' \
|
||||
-c 'mcp_servers.<name>.default_tools_approval_mode="approve"'
|
||||
```
|
||||
|
||||
- `-a never` never asks; without `default_tools_approval_mode="approve"` every MCP tool call is
|
||||
refused instead of run.
|
||||
- The folder trust prompt cannot be skipped from `-c` (a `projects."<folder>".trust_level`
|
||||
override still shows it, in Codex 0.159). Accept it once for the take folder in a throwaway
|
||||
tape: `Type "codex"`, `Enter`, `Wait+Screen@30s /Trust and continue/`, `Enter`, `Sleep 5s`,
|
||||
`Ctrl+C`, `Ctrl+C`. The answer is saved in `~/.codex/config.toml` under the folder's real
|
||||
path (on macOS, `/private/tmp/…` for the scratchpad).
|
||||
- `check_for_update_on_startup=false` keeps the update banner out of the shot.
|
||||
- The token stays in an env var exported in the `Hide` block. Windmill's own MCP server is
|
||||
`<frontend URL>/api/mcp`, with a token that has the `mcp:all` scope.
|
||||
- Codex writes each session to `~/.codex/sessions/YYYY/MM/DD/rollout-*.jsonl` as it goes.
|
||||
|
||||
## Claude Code, unattended
|
||||
|
||||
```
|
||||
claude --strict-mcp-config --mcp-config <scratch>/mcp.json --allowedTools mcp__<name>
|
||||
```
|
||||
|
||||
- `mcp.json` is `{"mcpServers": {"<name>": {"type": "http", "url": "…", "headers":
|
||||
{"Authorization": "Bearer …"}}}}`. It holds the token, so keep it in the scratchpad and never
|
||||
`cat` it on camera.
|
||||
- `--allowedTools mcp__<name>` runs that server's tools without asking; anything else still
|
||||
asks, which a demo usually wants to show.
|
||||
- The folder trust prompt is saved per folder: accept it once in a throwaway tape
|
||||
(`Type "claude"`, `Enter`, `Wait+Screen@30s /trust/`, `Enter`, `Sleep 5s`, `Ctrl+C`, `Ctrl+C`).
|
||||
- Claude Code writes each session to `~/.claude/projects/<folder path, each non-alphanumeric character as ->/*.jsonl`.
|
||||
- Its layout differs from Codex's: measure its regions from crops (below) rather than reusing
|
||||
the Codex example.
|
||||
|
||||
## Drive a browser beside it
|
||||
|
||||
A Playwright script that records its own video and waits for the agent's output:
|
||||
|
||||
```js
|
||||
import { writeFileSync, existsSync } from 'node:fs'
|
||||
import { launchBrowser, waitForOutput } from '<repo>/.agents/skills/demo-video/lib.mjs'
|
||||
|
||||
const since = Date.now()
|
||||
writeFileSync('browser.pid', String(process.pid))
|
||||
writeFileSync('browser-start.txt', String(since))
|
||||
const browser = await launchBrowser()
|
||||
const ctx = await browser.newContext({
|
||||
viewport: { width: 900, height: 820 },
|
||||
recordVideo: { dir: 'bvideo', size: { width: 900, height: 820 } }
|
||||
})
|
||||
const page = await ctx.newPage()
|
||||
await page.request.post(`${BASE}/api/auth/login`, { data: { email: 'admin@windmill.dev', password: 'changeme' } })
|
||||
await page.goto(`${BASE}/some/page`)
|
||||
const [link] = await waitForOutput(/https:\/\/[^\s"\\]+\/the-page\?[^\s"\\]+/, { agent: 'codex', since })
|
||||
await page.goto(link)
|
||||
try {
|
||||
await page.getByText(/the success message/).waitFor({ timeout: 40000 })
|
||||
} catch {
|
||||
await page.screenshot({ path: 'browser-fail.png' })
|
||||
console.log('end state not seen:', (await page.locator('body').innerText()).slice(0, 400))
|
||||
}
|
||||
while (!existsSync('done.txt')) await new Promise((r) => setTimeout(r, 1000))
|
||||
await ctx.close()
|
||||
await browser.close()
|
||||
```
|
||||
|
||||
- `waitForOutput(pattern, { agent, cwd, since, timeout })` polls the logs of the `agent`
|
||||
(`'codex'` or `'claude'`) sessions started in `cwd` (default: the folder `node` was started
|
||||
from, so start the browser script from the folder vhs starts the agent in) and returns the
|
||||
match. Other agents on the machine write logs during the take too, a review in the same
|
||||
worktree or the recording agent itself, and only this folder's sessions count. It finds a log
|
||||
folder created during the take (Codex's per-day folder), so never build a dated path yourself.
|
||||
Logs are JSON: end the pattern before `"` and `\`. Take `since` when the script starts, before
|
||||
the agent can answer.
|
||||
- `since` skips log files last written before it, but a file written after it is searched from
|
||||
the top. Start a new agent session for each take: a resumed session's log still holds the
|
||||
links of earlier takes, and the first match wins.
|
||||
- The log holds the prompt and every tool result too, and the first match wins. Make the
|
||||
pattern match only the reply: tool results carry look-alike URLs (Windmill's deploy tool
|
||||
returns the page under the instance's base URL, not the host the prompt asked for), and the
|
||||
prompt must not contain the full link. Pin the host the prompt names and the path it leaves
|
||||
for the agent to fill in.
|
||||
- Log in with `page.request.post(...)` before the first navigation.
|
||||
- Run both, then a marker: `node browser.mjs & vhs term.tape; touch done.txt`. The script closes
|
||||
its context once `done.txt` exists, which finishes the webm.
|
||||
- Before every take, stop the driver left by the previous one: `kill $(cat browser.pid)`. A
|
||||
stray one matches the new session's output and acts on it first. Never `pkill -f browser.mjs`,
|
||||
which also kills the takes of other worktrees.
|
||||
- End the browser script on the state the page settles in (the success message), not a
|
||||
transient one, and keep the try/catch so a failed take says why.
|
||||
|
||||
## Compose side by side
|
||||
|
||||
```bash
|
||||
ffmpeg -i term.mp4 -ss <offset> -i browser.webm -filter_complex \
|
||||
"[0:v]fps=25,scale=820:820,setsar=1[a];[1:v]fps=25,scale=900:820,setsar=1[b];[a][b]hstack=2,format=yuv420p[v]" \
|
||||
-map "[v]" -t <terminal duration> -c:v libx264 -crf 12 -preset veryfast side.mp4
|
||||
```
|
||||
|
||||
- `<offset>`: seconds the browser recording began before the terminal one, trimmed off the
|
||||
browser input. Take a first guess from the start timestamps, then set it from frames: the
|
||||
page must open right after the link prints. Check the last interaction between the two sides
|
||||
as well; when the terminal has drifted (above) and the browser reacts visibly early, split
|
||||
the composition at that interaction or retime the browser with `setpts=<factor>*PTS`.
|
||||
- Same height on both sides. crf 12 keeps text sharp for the cut step, which encodes again.
|
||||
|
||||
## Watch regions
|
||||
|
||||
`regions.json` lists the areas to watch, in pixels of the input. Example: a Codex TUI, 820x820
|
||||
at font size 15, left of a 900-wide browser:
|
||||
|
||||
```json
|
||||
[
|
||||
{ "name": "transcript", "x": 0, "y": 0, "w": 820, "h": 670, "min": 150 },
|
||||
{ "name": "status", "x": 0, "y": 670, "w": 820, "h": 35, "min": 30,
|
||||
"unlessLike": { "x": 40, "y": 675, "w": 72, "h": 22, "at": 40 } },
|
||||
{ "name": "composer", "x": 0, "y": 705, "w": 820, "h": 65, "min": 300 },
|
||||
{ "name": "browser", "x": 820, "y": 0, "w": 900, "h": 820, "min": 30 }
|
||||
]
|
||||
```
|
||||
|
||||
- Place the rows from two crops of the bottom of the terminal, one while the CLI works and one
|
||||
after: `ffmpeg -ss <t> -i side.mp4 -frames:v 1 -vf crop=820:180:0:640 f.png`.
|
||||
- Codex's `Working (12s • esc to interrupt)` row ticks and shimmers, so watch it only
|
||||
`unlessLike` its look at a time (`at`) it shows "Working": when the work ends, the newest line
|
||||
of the answer lands in that same row.
|
||||
- Composer: a cursor blink changes ~170 to 210 px per sample and typing 460 or more, so
|
||||
`min` 300. Leave the footer under it out.
|
||||
- A region whose `min` is too low keeps the whole take "active" and nothing gets cut: run
|
||||
`activity.mjs` first and look for a run of equal small counts every ~0.6 s (the blink).
|
||||
|
||||
## See when the screen changes
|
||||
|
||||
```bash
|
||||
node <repo>/.agents/skills/demo-video/activity.mjs side.mp4 regions.json [from] [to]
|
||||
```
|
||||
|
||||
prints, per region, the runs of change in seconds of that file: `48.0-48.5(4744)` is a change
|
||||
from 48.0 s to 48.5 s, 4744 pixels at most in one sample (`--raw` lists every sample). It
|
||||
samples exactly as `cut-waits.mjs` does. Use it for every time you write down: where an agent's
|
||||
work starts and ends (for `--cut=`), when the link prints and the page opens (for the offset),
|
||||
and, on the cut file, where each narration line goes.
|
||||
|
||||
## Cut the waits
|
||||
|
||||
```bash
|
||||
node <repo>/.agents/skills/demo-video/cut-waits.mjs side.mp4 out.mp4 regions.json --plan # cuts + check sheets
|
||||
node <repo>/.agents/skills/demo-video/cut-waits.mjs side.mp4 out.mp4 regions.json # render
|
||||
```
|
||||
|
||||
- Read every `<out>.cuts-N.png` row before rendering: the two frames of a row must show the
|
||||
same content, apart from timers and the cursor. Text appearing between them means a region
|
||||
missed it: fix the region and rerun `--plan`.
|
||||
- Defaults: stretches of 3 s or more shrink to 1 s (0.7 s kept before the cut, 0.3 s after), 5 s
|
||||
kept after the last change, and a "⏩ N s later" note at the top centre for 1.4 s after each
|
||||
cut. Override with `--min-gap`, `--head`, `--tail`, `--end-hold`, `--label-y`.
|
||||
- What changes stays: typing, tool calls appearing, links, the page being filled, the final
|
||||
answer. Time spent waiting on a tool is cut; the call and its result both stay on screen.
|
||||
- An AI agent's own work is not idle to the measurement: its tool calls keep scrolling in while
|
||||
the viewer only waits for the answer. Remove those stretches with `--cut=<from>-<to>`
|
||||
(seconds of the input, repeatable), from just after the agent's first reply to just before the
|
||||
output the viewer needs (its message, the link, the final answer). Take both bounds from
|
||||
`activity.mjs` on `side.mp4`, never from the agent's log timestamps (the mp4 drifts from the
|
||||
wall clock), and confirm them on the check sheet. A forced cut gets the same note.
|
||||
- Silent inputs only: the output carries no audio. Add the voice-over after cutting.
|
||||
|
||||
## Add a voice-over
|
||||
|
||||
```bash
|
||||
node <repo>/.agents/skills/demo-video/narrate.mjs out.mp4 lines.json narrated.mp4 --plan --regions=out.regions.json
|
||||
node <repo>/.agents/skills/demo-video/narrate.mjs out.mp4 lines.json narrated.mp4
|
||||
```
|
||||
|
||||
lines.json: `[{ "at": 0.3, "text": "One sentence." }, ...]`, `at` in seconds of the cut video.
|
||||
Take each `at` from `activity.mjs out.mp4 out.regions.json`: 0.3 s before the change the line
|
||||
describes. `out.regions.json` is written by `cut-waits.mjs`: the same regions, with each
|
||||
`unlessLike.at` moved onto the cut's timeline. If that `at` fell inside a cut, it now points at
|
||||
the first frame after it: check that frame still shows the look to ignore, or pick a new `at`.
|
||||
|
||||
- Each line is spoken by macOS `say` (`--voice`, default Samantha, ~3 words per second;
|
||||
`--voice=none` for captions only). When a line still runs at the next line's `at`, the video
|
||||
holds the frame at that `at` until it ends, so speech never runs over a later step.
|
||||
- A hold only waits at the next line's `at`: whatever happens between the previous line's `at`
|
||||
and that moment plays while the previous line is still speaking. A line anchored after its
|
||||
change therefore starts once the change is already over. `--plan` with `--regions` flags each
|
||||
line whose `at` falls just after a change started and prints the `at` to use instead.
|
||||
- `--plan` also flags each hold longer than 1 s: the line before it is too long for its stretch.
|
||||
Shorten that line rather than accept the freeze.
|
||||
- Read the narrated frames at each hold before delivering.
|
||||
- Each line is burned in as a caption in a band of its own below the video, from its start
|
||||
until the next line starts, so captions never cover the recording: a 1280x720 cut comes out
|
||||
1280x816. `--caption-at=top` puts the band above, `--caption-height` sets its height (default
|
||||
96, two lines of text; keep it even for H.264), `--no-band` leaves the video its own size.
|
||||
- `--vtt=<file>` writes the lines as WebVTT on the output's timeline; `--cues=<file>` writes
|
||||
them as JSON for a text track added from inline JS (see Deliver in `SKILL.md`).
|
||||
+1
@@ -0,0 +1 @@
|
||||
../../../.agents/skills/demo-video/SKILL.md
|
||||
@@ -67,6 +67,7 @@ Open-source platform for internal tools, workflows, API integrations, background
|
||||
- **Frontend patterns**: use the `svelte-frontend` skill when writing Svelte code. Do NOT edit svelte files unless you have read that skill.
|
||||
- **Frontend UUIDs**: do not call `crypto.randomUUID()` in frontend code. Import `randomUUID` from `$lib/utils/uuid` instead.
|
||||
- **Code review**: review the current PR or branch against the shared review policy in `REVIEW.md` (severity triage, public-surface checklist, AGENTS.md compliance, test-coverage assessment). The skill at `.agents/skills/local-review/SKILL.md` orchestrates it. All three CLIs auto-discover the same SKILL — Claude reads `.claude/skills/` (symlinked to the canonical `.agents/skills/` file), Codex and Pi read `.agents/skills/` directly. Invoke with `/local-review` in Claude Code, `$local-review` (or `/skills` selector) in Codex, or `pi --skill local-review` / `/skill:local-review` in Pi. For a Codex-driven pass that mirrors the `codex-pr-review` GitHub action against your unpushed work (committed + uncommitted) before you push, use `/local-review-codex` (`.agents/skills/local-review-codex/`) — same `REVIEW.md` policy, `gpt-6.1-sol` model and `xhigh` reasoning as the action; requires the `codex` CLI >= 0.159.3.
|
||||
- **Demo videos**: the `demo-video` skill (`.agents/skills/demo-video/`) records a narrated browser walkthrough with Playwright, or a terminal session (Codex, Claude Code, `wmill`) with vhs beside the browser it drives, cuts the idle waits, and covers putting the result in an Artifact or a PR body. Needs Homebrew `ffmpeg`, macOS `say` for speech, and `vhs` for terminal takes.
|
||||
- **Domain guides**: `.claude/skills/native-trigger/`
|
||||
- **Brand/UI guidelines**: `frontend/brand-guidelines.md`
|
||||
- **Domain vocabulary**: `CONTEXT.md` — the words this codebase uses for its own concepts (step, step setting, trigger step, …). Name things the way it does.
|
||||
|
||||
Reference in New Issue
Block a user