:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
chore(skills): add a skill for recording branded, narrated demo videos (#118431)
Harley Alexanderddd855cee44c
diff --git a/.agents/skills/recording-demo-videos/SKILL.md b/.agents/skills/recording-demo-videos/SKILL.mdnew file mode 100644index 000000000000..a8ddc6423722--- /dev/null+++ b/.agents/skills/recording-demo-videos/SKILL.md@@ -0,0 +1,125 @@+---+name: recording-demo-videos+description: >+ Records a captioned, PostHog-branded walkthrough video (MP4) of a feature running on the local+ PostHog stack, for a Loom, a Slack demo, or a PR. Use when asked to record a video, demo,+ walkthrough, or Loom of a change end to end, including flows that leave the app, such as an API+ call shown as a terminal card or an email arriving in the local inbox. The recorder drives the+ real app with Playwright, adds RoundHog captions, a cursor, hedgehog stickers, and an optional+ ElevenLabs voiceover and music bed, frames the video with title and end cards that carry the logo and a hedgehog+ from @posthog/brand, and cuts loading time out. For a short animated WebP of one interaction in a+ PR description, use the reel mode of qa-frontend.+---++# Recording demo videos++A demo video shows a feature working, from the first click to the proof that it worked.+The recorder drives the real app on the local stack, so what the viewer sees is what the code does.+It writes a short MP4, usually under a minute, a contact sheet of frames to review, and a log.++The output looks like this: a title card with the logo and a hedgehog, the app with a caption bar and a cursor for each step, terminal cards for API calls, and an end card.+Waits for page loads and data are cut, so the video moves at reading speed.+A voiceover can read the captions, a music bed can sit under it, and a step can pop in a hedgehog sticker with a short sound.++Use [qa-frontend](../qa-frontend/SKILL.md) instead for a reel: a short animated WebP of one interaction, made from stills, for a PR description.+For a narrated or musical promo video, see [hogreel](references/branding.md#promo-videos).++## Workflow++### 1. Get the stack ready++The stack must be up and serving the code you want to show.+Start it with `hogli start -y -d` and `hogli wait`, or follow `/run-posthog`.+Check the processes the flow needs beyond the web app.+For example, workflow runs and email sends need the CDP workflow workers, which the default dev stack does not start.+[references/troubleshooting.md](references/troubleshooting.md) lists the ones that caught us.++The recorder needs `ffmpeg` and the repo's Python environment, which has Playwright.+It reads the brand assets from `frontend/node_modules/@posthog/brand`, so run `pnpm install` first if that directory is missing.++### 2. Seed the data the demo needs++Record in a local demo workspace, never in a workspace with real data, because the video can end up in a public PR.+`python manage.py setup_dev --no-data` creates one with the `[email protected]` user.+Seed everything else the flow needs with a short script: feature flags, objects to start from, API keys.++Invent all the data.+Use reserved domains (`example.com`) or a domain you control for addresses, and invented names.+Some flows validate a domain, for example the email sender refuses a domain without mail servers, so check what the flow accepts.++Each take changes state: it creates objects, sends emails, and bumps versions.+Write three small scripts for the demo: seed the starting state, reset it before every take, and check that the flow works once before the first take.+[references/seeding.md](references/seeding.md) shows how to work out what the flow needs and how to write each script.++### 3. Write the storyboard++A storyboard is a JSON file: optional title and end cards, then a list of steps.+Each step can navigate, click, type, wait, show a caption, or show an HTTP request as a terminal card and send it.+Read [references/storyboard.md](references/storyboard.md) for the format and a full example.++Plan the beats before you write steps:++1. The title card says what the feature does for the viewer, in one line.+2. Start in the state just before the new behavior. Skip the navigation a viewer already knows.+3. One step per action, with a caption that says what is happening and why it matters.+4. Show proof of the effect: the email in the inbox, the row in the table, the number in the chart.+5. The end card sums up the change in one line.++Captions are user-facing copy, so `/writing-user-facing-copy` applies: sentence case, one idea each, no em dashes.+Write them to be read aloud too, when the video has a voiceover.++#### Pacing++A demo that drags loses the viewer. Keep it short, and keep it moving.++- Aim for 30 to 60 seconds. Go past 90 seconds only when the flow needs every beat. Cut beats before you add time.+- Change something on screen at least every two seconds. A still frame is a pause, even with a caption on it.+- Show each idea once. Cut a step that proves nothing new.+- Keep captions under ten words. A long caption holds its step longer, and a long voiceover line holds it longer still.+- Leave `hold` unset. The defaults hold a caption for about a quarter of a second per word, at least one and a half seconds. With a voiceover, a step waits for its line to finish.+- Set `hold` only to give a sticker time to land or to make a navigation step shorter. Keep it at two seconds or less.++For a voiceover or music, add `voiceover` or `music` to the storyboard.+They need an ElevenLabs API key in `ELEVENLABS_API_KEY`. Do not ask the developer to paste the key into the chat.+Without the key, the recorder leaves out the voiceover and generated music and records a captioned video.+The log lists what it left out under `skipped_without_elevenlabs_key`. Tell the developer, and point them to [references/troubleshooting.md](references/troubleshooting.md#elevenlabs-calls-fail) to set the key.+Settle the captions in a silent take first, because every changed line costs credits.++### 4. Record++From the root of the checkout:++```bash+uv run python .agents/skills/recording-demo-videos/scripts/record_demo.py path/to/storyboard.json+```++The script logs in, loads every page once to warm the dev server, then records.+It writes `<output>.mp4`, `<output>.sheet.png` and `<output>.log.json` next to the storyboard.+When a step fails, it writes `<output>.error.png` and `<output>.failed.webm` instead and exits non-zero. The log names the step.++### 5. Review, then record again++Read the contact sheet before you share anything.+Most first takes need another one. Look for:++- pauses: frames where nothing changes for more than two seconds, or a `duration` in the log over 60 seconds. Remove the `hold`, shorten the caption, or cut the step.+- spinners, skeletons or empty tables where the step expected data. Add a `wait_for` on the content.+- numbers that disagree with what happened in the video.+- debug chrome, banners and toasts that distract. Add them to `hide_text` or `hide_selectors`.+- with a voiceover: the `voice` list in the log, which gives each line's start and length in the video. A line that runs long holds its step, so a step that lingers often has a long line. Trim the line.+- secrets, real names, or anything else that must not be public, in the pixels and in the captions.++Reset the data, then record again. Read individual frames with ffmpeg when the sheet is too small to judge.++### 6. Share++In a PostHog Desktop or cloud task, upload the MP4 as a task artifact.+For a PR, upload it with `hogli pr:upload-video` and paste the markdown it prints.+PR assets are public forever, so check the frames for private data before every upload.++## References++- [references/seeding.md](references/seeding.md): working out what a flow needs, and the seed, reset and check scripts.+- [references/storyboard.md](references/storyboard.md): the storyboard format, targets, variables and secrets, voiceover, music, and a full example.+- [references/branding.md](references/branding.md): where the brand assets come from, the rules for the logo, colors, type and hedgehogs, and hogreel.+- [references/troubleshooting.md](references/troubleshooting.md): failures we hit while recording, and their fixes.diff --git a/.agents/skills/recording-demo-videos/references/branding.md b/.agents/skills/recording-demo-videos/references/branding.mdnew file mode 100644index 000000000000..30eee438a20c--- /dev/null+++ b/.agents/skills/recording-demo-videos/references/branding.md@@ -0,0 +1,45 @@+# Branding++The recorder styles everything it adds with PostHog's brand: the title, end and terminal cards, the caption bar and the cursor.+The app itself is recorded as it is.++## Where the assets come from++Everything comes from `@posthog/brand`, the package behind [brand.posthog.com](https://brand.posthog.com), which the frontend already depends on.+The recorder reads it from `frontend/node_modules/@posthog/brand`, so nothing is downloaded and no brand file is copied into a skill or a PR.++- **Colors**: the brand palette, from the package's color tokens.+- **Type**: RoundHog, the brand typeface, embedded into the cards and the caption bar.+- **Logo**: rendered from the package's `Logo` component, full color on light cards and white on dark ones.+- **Hedgehogs**: the official illustrations, by slug.++The brand assets are PostHog trademarks under the PolyForm Strict License.+Use them in PostHog's own videos only.++## Rules++These come from brand.posthog.com and the brand handbook. The recorder follows them. Keep to them when you write a storyboard.++- **Logo**: the full-color logo goes on light backgrounds only, and the white logo on dark ones. Do not recolor, stretch or animate it, and never set "PostHog" in text next to the logomark.+- **Colors**: tangerine (`#FF5C1C`) is the accent, on the card bar, the caption edge and the cursor. A scene leans on two or three colors. Stage backgrounds are solid: cream (`#F4F3EE`) or dark (`#1D1F27`).+- **Type**: RoundHog in its brand weights: 500 Medium, 700 SemiBold, 800 Bold. There is no 600. Headings are sentence case.+- **Hedgehogs**: official art only. Never use AI-generated hedgehogs, and never edit one. Pick a hog that makes the card's point, not one that only fills space.++## Picking a hedgehog++List the slugs:++```bash+ls frontend/node_modules/@posthog/brand/dist/generated/hoggies/png | sed 's/\.png$//'+```++Or search them with their tags at [brand.posthog.com/hoggies](https://brand.posthog.com/hoggies).+Some that suit common demos: `mailbox` (email, messaging), `chart` (analytics), `explorer` (discovery, search), `robot` (AI, automation), `rocket` (launch), `party` (an end card).+An unknown slug fails the run and prints the full list.++## Promo videos++For a narrated or musical promo video, such as a launch reel, look at [PostHog/hogreel](https://github.com/PostHog/hogreel).+Team DevEx built it to render on-brand hype videos from HTML scenes, with a voiceover or a song.+It is private to the PostHog organization.+A demo video from this skill shows the real app working. A hogreel video sells it.diff --git a/.agents/skills/recording-demo-videos/references/seeding.md b/.agents/skills/recording-demo-videos/references/seeding.mdnew file mode 100644index 000000000000..0a7ffb6a314e--- /dev/null+++ b/.agents/skills/recording-demo-videos/references/seeding.md@@ -0,0 +1,96 @@+# Seeding, resetting and checking the demo++A demo needs data the flow can act on, the same starting point for every take, and proof that the flow works before the camera rolls.+Write three small scripts for each demo: seed, reset, and check.+Keep them outside the repo, for example in a `demo/` folder next to the storyboard.++## What the flow needs++List it before writing anything. Walk the flow once by hand, or read the code path, and note each thing that has to exist first:++- **Where it runs**: the demo user and project. `python manage.py setup_dev --no-data` gives `[email protected]` and one project, usually team 1.+- **What gates it**: feature flags, plan features, or settings that hide the UI or the endpoint.+- **What it starts from**: the objects on screen in the first step, such as a template, a dashboard, or a flag.+- **What it calls**: API keys and their scopes, verified integrations, or webhooks the flow needs.+- **What has to run**: workers, queues, and local services such as MailDev. The web app alone often is not enough. See [troubleshooting.md](troubleshooting.md).+- **What proves it worked**: the row, email, event, or metric the last steps show. Something has to produce it, so check that the process behind it runs.++## Seed++Create the starting state in one script, idempotent so a second run does no harm.+On a local stack, a Django shell script is the shortest path: it can create anything, including what the API refuses, such as a verified integration.++```bash+DEBUG=1 python manage.py shell < demo/seed.py > demo/seed.out+grep -E '^[A-Z_]+=' demo/seed.out > demo/demo.env+```++```python+# demo/seed.py: create what the flow starts from, then print what the storyboard needs as NAME=value.+from posthog.models import Team, User++team = Team.objects.order_by("id").first()+user = User.objects.first()++# 1. Gates: turn on the feature flag for the demo project.+# 2. Prerequisites: integrations, settings, API keys. Print new secrets once; nothing else stores them.+# 3. Starting objects: what the first step shows. Use invented names and example.com addresses.++print(f"TEAM={team.id}")+# print(f"TEMPLATE={template.id}")+# print(f"API_KEY={raw_key}")+```++Import models from the product that owns them, and use `get_or_create` so a rerun finds what the first run made.+When the app has an API for a step, calling it as the demo user exercises the same path as the UI. Use the shell for what the API cannot do.++The storyboard reads the printed values as `${NAME}`.+Pass them in the environment, and list secrets under `secrets` so the video shows `$NAME` instead of the value:++```bash+set -a; source demo/demo.env; set +a+uv run python .agents/skills/recording-demo-videos/scripts/record_demo.py demo/storyboard.json+```++Keep `demo.env` out of the repo. It holds working keys.++## Reset++A take changes state: it creates objects, sends emails, writes versions, and moves counters.+The reset script puts back the state the first step expects, so every take starts the same.++- Undo what the flow creates: delete the objects, unlink them, or restore the fields the flow edits.+- Clear outside state the video shows, such as the local inbox: `curl -s -X DELETE localhost:1080/email/all`.+- New objects start counters from zero. When the video shows a count, recreate the object rather than reuse it, because metrics and events that already exist stay attached to the old one.++Run it before every take, and make it print the state it left so a failed reset is visible:++```bash+bash demo/reset.sh && uv run python .agents/skills/recording-demo-videos/scripts/record_demo.py demo/storyboard.json+```++## Check++Run the flow once outside the recorder before the first take, then reset.+A failure is faster to find in a terminal than in a video.++- Call each endpoint the storyboard calls with `curl`, and check the status and the body.+- Check that the background work finished: the worker log, the row, the email in MailDev, the metric in ClickHouse.+- Open each page the storyboard visits, and check that the content each `wait_for` waits on appears.++When the recorder fails on a step, the log names it and `<output>.error.png` shows the screen. Fix the step, reset, and record again.++## Example++The transactional email demo needed:++- **Gates**: the feature flag that hides the send endpoint, created in team 1 at 100%.+- **Prerequisites**:+ - a verified email sender integration, set as the project's default sender+ - a project secret API key with the scope the endpoint checks+- **Starting objects**: an email template with a subject, a body and invented copy, plus a second template to show the library filter.+- **Running processes**:+ - the CDP workflow workers, which the default stack does not start+ - MailDev, to receive the email+- **Reset**: unlink the template from its workflow, delete the workflow, restore the edited subject, and clear MailDev.+- **Check**: one `curl` to the send endpoint returned `202`, and the email showed up in MailDev.diff --git a/.agents/skills/recording-demo-videos/references/storyboard.md b/.agents/skills/recording-demo-videos/references/storyboard.mdnew file mode 100644index 000000000000..896b21279430--- /dev/null+++ b/.agents/skills/recording-demo-videos/references/storyboard.md@@ -0,0 +1,346 @@+# Storyboard format++A storyboard is one JSON file. Paths in it are relative to the file.++```json+{+ "output": "my-feature-demo.mp4",+ "base_url": "http://localhost:8010",+ "viewport": { "width": 1440, "height": 900 },+ "login": { "email": "[email protected]", "password": "12345678" },+ "vars": { "TEAM": "1", "API_KEY": "phs_..." },+ "secrets": ["API_KEY"],+ "hide_text": ["Get more out of PostHog by inviting your team"],+ "hide_selectors": [],+ "voiceover": { "voice": "nPczCjzI2devNBz1zQrb" },+ "music": { "prompt": "Light, upbeat instrumental background music for a product demo." },+ "title": { "heading": "Feature name", "subheading": "What it does for you.", "hog": "mailbox" },+ "steps": [],+ "end": { "heading": "The change in one line", "subheading": "One supporting line.", "hog": "party" }+}+```++| Key | Meaning |+| ---------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `output` | The MP4 path. The sheet, log and error files go next to it. Default `demo.mp4` |+| `base_url` | The app. Relative step URLs resolve against it. Default `http://localhost:8010` |+| `viewport` | The video size in pixels. Default 1440×900, which suits Loom and Slack |+| `login` | The user the recorder logs in as before recording. Default `[email protected]` / `12345678` from `setup_dev` |+| `vars` | Values for `${NAME}` anywhere in the storyboard. Environment variables work too, and `vars` wins |+| `secrets` | Names in `vars` that requests use but the video shows as `$NAME`. Names that end in `KEY`, `TOKEN`, `SECRET` or `PASSWORD` are secret without being listed. List every other credential here |+| `hide_text` | Hides the smallest container that starts with this text, such as a banner. `DEBUG mode` is always hidden |+| `hide_selectors` | CSS selectors to hide. The debug bar (`.tricolor`) is always hidden |+| `title`, `end` | Cards before and after the steps: `heading`, `subheading`, `hog` (a slug, see [branding.md](branding.md)), `say` and `hold` seconds |+| `voiceover` | Optional. Narrates the video with ElevenLabs. See [Voiceover](#voiceover) |+| `music` | Optional. A music bed under the video. See [Music](#music) |++## Steps++A step runs its keys in this order: `goto`, then `caption` (and its voiceover line), `scroll`, `hover`, `click`, `type`, then `wait_for`, `sticker`, then `hold`.+A `card` or `http` step does only that.++| Key | Meaning |+| ---------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |+| `goto` | A path on `base_url` or a full URL, such as the local inbox at `http://localhost:1080`. The load is cut from the video |+| `caption` | Text in the caption bar, kept until the next caption. `""` hides it |+| `scroll` | Pixels to scroll down with the mouse wheel (negative scrolls up) |+| `hover` | A target. The cursor glides to it |+| `click` | A target. The cursor glides to it and clicks |+| `type` | `{ "target": …, "keys": ["Home", "ArrowRight x10"], "text": " new words" }`. Clicks the target, presses the keys (`x10` repeats), then types the text |+| `wait_for` | A target that must be visible. In a `goto` step it waits after the load, otherwise after the action. The wait is cut from the video, so wait on real content, not on a fixed time |+| `say` | The voiceover line for the step, when it should differ from the caption. `""` keeps the step silent |+| `sticker` | A hedgehog that pops in once the action is done: `{ "hog": "mailbox", "text": "You've got mail", "position": "bottom-right", "seconds": 3 }`. Positions: `bottom-right`, `bottom-left`, `top-right`, `top-left` |+| `hold` | Seconds to stay on the result. Default: a quarter of a second per caption word, at least 1.5. With a voiceover, half a second, and the step always waits for its line to finish. Usually leave it unset |+| `card` | A full-screen card mid-video, with the same fields as `title` |+| `http` | A terminal card that types out a curl command, sends the request, and shows the response. See below |++A step has one `wait_for`. JSON keeps only the last of two equal keys, so a step that needs to wait after a `goto` and again after a `click` must be two steps.++Use one or two stickers in a video, on the moments that pay off, such as the email arriving. More than that, and they stop meaning anything.++### Targets++| Form | Finds |+| -------------------------------------- | ------------------------------------------------------------------------------ |+| `{ "role": "tab", "name": "Metrics" }` | An element by its accessible role and exact name |+| `{ "label": "Email" }` | A form field by its label |+| `{ "text": "Password reset" }` | An element that contains the text. Add `"exact": true` to match the whole text |+| `{ "selector": "[data-attr=save]" }` | Any Playwright selector, including chains with `>>` |++Add `"within": "<css>"` to search inside one element, and `"nth": 1` to take a later match.+Prefer `data-attr` selectors and roles. They survive copy changes.++### HTTP steps++```json+{+ "http": {+ "title": "Send it from your code",+ "method": "POST",+ "url": "/api/projects/${TEAM}/messaging_templates/${TEMPLATE}/send/",+ "headers": { "Authorization": "Bearer ${API_KEY}" },+ "json": { "to": "[email protected]", "message_data": { "first_name": "Jane" } },+ "expect_status": 202+ }+}+```++The card types out the request as a curl command, with secrets shown as `$NAME`, then sends it and prints the status and the response body.+The video masks secret values in all the text it shows, including the response body. It also masks PostHog secret keys, such as `phx_` and `phs_` keys.+It cannot mask what a `type` step types into the app or what the app itself shows, so never type a secret in a demo.+With `expect_status`, any other status fails the recording, so a broken call never ends up in a finished video.++## Voiceover++`voiceover` narrates the video with ElevenLabs.+Each caption is spoken, unless the step has a `say` line. Cards say their heading and subheading, and HTTP steps their title.+The whole script goes to ElevenLabs as one take, so the delivery flows instead of restarting on each line.+The per-character timestamps cut the take into one clip per line, and each clip starts when its caption shows.++```json+{+ "voiceover": {+ "voice": "nPczCjzI2devNBz1zQrb",+ "model": "eleven_v3",+ "settings": { "stability": 0.5, "speed": 1.12 }+ }+}+```++All three fields are optional. The defaults are Brian, a premade voice, at the settings the DevEx videos use.+Use premade voices only: the account also holds cloned voices of real people.+v3 audio tags such as `[excited]` in a `say` line steer the delivery.++The voiceover needs `ELEVENLABS_API_KEY` in the environment.+Never put the key in a storyboard, a commit, or the chat. Ask the developer to set it in the shell or as a task secret.+Without the key, the recorder records the video with no voiceover and lists `voiceover` under `skipped_without_elevenlabs_key` in the log.+Takes are cached in `~/.cache/posthog-demo-videos/voiceover/` by text and voice, so recording again with the same script costs no credits.+A changed line reads the whole take again. A video is about 1,500 characters, and shared accounts have a monthly limit, so settle the captions before you add the voiceover.++## Music++`music` lays a quiet music bed under the whole video. It fades in and out, and dips while a line or a sticker sound plays.++```json+{ "music": { "prompt": "Light, upbeat instrumental background music for a product demo.", "volume": 0.18 } }+```++- `prompt`: what ElevenLabs Music generates. Optional, with a light, upbeat default. The track is always instrumental.+- `volume`: the bed's level before ducking, from 0 to 1. Default 0.18.+- `file`: a music file to use instead of generating one, relative to the storyboard. Use only music PostHog has the rights to.++Generated tracks match the video's length in 10 second steps, and are cached in `~/.cache/posthog-demo-videos/music/` by prompt and length, so another take of the same length costs nothing.+Music uses the same `ELEVENLABS_API_KEY`, and the key needs music access.+The final mix is normalized to -16 LUFS, the usual level for web video.++## Example++This storyboard records the narrated transactional email demo. It starts on the template library, makes a template transactional, sends it over the API, shows the email in the local inbox, edits the template, sends again, and ends on the metrics.+It sets `hold` only on the two sticker steps and on navigation steps that must stay short.+`TEAM`, `TEMPLATE` and `POSTHOG_PROJECT_SECRET_API_KEY` come from the seed script's env file, see [seeding.md](seeding.md).++```json+{+ "output": "transactional-email-demo.mp4",+ "secrets": ["POSTHOG_PROJECT_SECRET_API_KEY"],+ "hide_text": ["Get more out of PostHog by inviting your team"],+ "voiceover": {},+ "music": {},+ "title": {+ "heading": "Transactional emails",+ "subheading": "Send any email template from your code, and get workflow reporting for free.",+ "hog": "mailbox"+ },+ "steps": [+ {+ "goto": "/project/${TEAM}/workflows/library",+ "wait_for": {+ "text": "Password reset"+ },+ "caption": "Start from an ordinary email template"+ },+ {+ "click": {+ "text": "Password reset"+ },+ "wait_for": {+ "role": "tab",+ "name": "API"+ }+ },+ {+ "caption": "The API tab explains what transactional sending does",+ "click": {+ "role": "tab",+ "name": "API"+ }+ },+ {+ "caption": "Make transactional creates a hidden workflow with an API trigger",+ "click": {+ "selector": "[data-attr=make-message-template-transactional]"+ },+ "wait_for": {+ "role": "tab",+ "name": "Metrics"+ }+ },+ {+ "http": {+ "title": "Send it from your code with a project secret API key",+ "method": "POST",+ "url": "/api/projects/${TEAM}/messaging_templates/${TEMPLATE}/send/",+ "headers": {+ "Authorization": "Bearer ${POSTHOG_PROJECT_SECRET_API_KEY}"+ },+ "json": {+ "to": "[email protected]",+ "identifiers": {+ "distinct_id": "jane"+ },+ "message_data": {+ "first_name": "Jane",+ "reset_link": "https://posthog.com/reset"+ }+ },+ "expect_status": 202+ }+ },+ {+ "goto": "http://localhost:1080",+ "wait_for": {+ "text": "Reset your password, Jane"+ },+ "caption": "The email arrives with message_data filled into the template",+ "click": {+ "text": "Reset your password, Jane"+ },+ "hold": 2,+ "sticker": {+ "hog": "mailbox",+ "text": "You've got mail",+ "seconds": 3+ }+ },+ {+ "goto": "/project/${TEAM}/workflows/library/templates/${TEMPLATE}",+ "wait_for": {+ "role": "tab",+ "name": "Sends"+ },+ "hold": 0.5+ },+ {+ "caption": "Every send is a workflow run you can inspect",+ "click": {+ "role": "tab",+ "name": "Sends"+ },+ "wait_for": {+ "text": "SUCCEEDED"+ }+ },+ {+ "caption": "Edit the template like any other email",+ "click": {+ "role": "tab",+ "name": "Design"+ }+ },+ {+ "type": {+ "target": {+ "selector": "text=Subject >> nth=0 >> xpath=following-sibling::*[1]"+ },+ "keys": ["Control+Home", "Home", "ArrowRight x10"],+ "text": " PostHog"+ }+ },+ {+ "caption": "Saving publishes a new version for the next send",+ "click": {+ "role": "button",+ "name": "Save"+ }+ },+ {+ "click": {+ "role": "tab",+ "name": "Versions"+ },+ "caption": "Every save is a version you can restore"+ },+ {+ "http": {+ "title": "Send again",+ "method": "POST",+ "url": "/api/projects/${TEAM}/messaging_templates/${TEMPLATE}/send/",+ "headers": {+ "Authorization": "Bearer ${POSTHOG_PROJECT_SECRET_API_KEY}"+ },+ "json": {+ "to": "[email protected]",+ "identifiers": {+ "distinct_id": "sam"+ },+ "message_data": {+ "first_name": "Sam",+ "reset_link": "https://posthog.com/reset"+ }+ },+ "expect_status": 202+ }+ },+ {+ "goto": "http://localhost:1080",+ "wait_for": {+ "text": "Reset your PostHog password, Sam"+ },+ "caption": "The next email uses the new subject",+ "click": {+ "text": "Reset your PostHog password, Sam"+ }+ },+ {+ "goto": "/project/${TEAM}/workflows/library/templates/${TEMPLATE}",+ "wait_for": {+ "role": "tab",+ "name": "Metrics"+ },+ "hold": 0.5+ },+ {+ "caption": "Sends, opens and clicks show up in the metrics",+ "click": {+ "role": "tab",+ "name": "Metrics"+ },+ "wait_for": {+ "text": "Emails sent"+ },+ "hold": 2,+ "sticker": {+ "hog": "chart",+ "text": "Tracked",+ "seconds": 3,+ "position": "top-right"+ }+ },+ {+ "goto": "/project/${TEAM}/workflows/library",+ "wait_for": {+ "text": "Password reset"+ },+ "caption": "Transactional templates are tagged, with a filter in the library",+ "click": {+ "selector": "[data-attr=templates-transactional-only]"+ }+ }+ ],+ "end": {+ "heading": "Mark it transactional, call one endpoint",+ "subheading": "Everything else runs as a workflow, with metrics, sends and versions.",+ "hog": "party"+ }+}+```diff --git a/.agents/skills/recording-demo-videos/references/troubleshooting.md b/.agents/skills/recording-demo-videos/references/troubleshooting.mdnew file mode 100644index 000000000000..9a79a4c41afc--- /dev/null+++ b/.agents/skills/recording-demo-videos/references/troubleshooting.md@@ -0,0 +1,71 @@+# Troubleshooting++Failures we hit while recording demos, and their fixes.++## The video shows minutes of spinners++The dev server compiles each frontend chunk on its first request, which can take a minute per page.+The recorder loads every `goto` page once before recording, and cuts each `goto` and `wait_for` wait from the final video.+When a page still loads in view, the step clicks before the data arrives. Add a `wait_for` on content that only exists once the data has loaded, such as a table row or a chart title.++## A step waits until it times out++- Two `wait_for` keys in one step: JSON keeps only the last one, so the step waits for the wrong thing. Split it into two steps.+- The target matches text that is not visible yet, or matches a hidden duplicate first. Use `"exact": true`, `"within"`, or `"nth"`.+- The data never arrives. Check the process behind it, below.++## The flow works in the app but not in the recording++The recorder logs in as `login`, which defaults to `[email protected]`.+Feature flags, seeded objects and API keys must belong to that user's workspace.++## A background job never runs++The default dev stack does not start every worker.+For example, workflow runs and email sends need the CDP workflow workers.+Start them next to the stack from the checkout:++```bash+(set -a; source .env.development; set +a; export NODEJS_CAPABILITY_GROUPS=cdp_workflows NODE_ENV=dev; \+ cd nodejs && nohup npx tsx src/index.ts > /tmp/node-workflows.log 2>&1 &)+```++Wait for `All systems go` in the log.+A job queued before the worker started runs as soon as it does, so reset and record again.++## Emails do not reach the local inbox++The local inbox is MailDev at `http://localhost:1080`.+Start it with `docker compose -f docker-compose.dev.yml up -d maildev` when the stack did not.+The email worker checks that the recipient's domain has mail servers and skips the send when it does not, so `example.com` recipients never arrive.+Use a domain with mail servers. MailDev catches the email, so nothing reaches the real address.++## Numbers in the video disagree with what happened++Metrics arrive through Kafka and ClickHouse, a few seconds after the action.+Wait for the chart or counter to load with a `wait_for`, and read the number in the contact sheet.+A local stack can count a workflow run twice. Its ClickHouse has two Kafka tables, `kafka_app_metrics2` and `kafka_app_metrics2_ws`, that read the same topic into `app_metrics2`.+ClickHouse drops most of the copies as duplicate inserts, but not all, so a count can come out one or two high.+When a number is off in a take, reset and record again rather than share it, or keep the counter out of the shot.++## The local stack lost its data++A cloud sandbox can restart, which stops the containers and can leave an empty database.+Run `hogli start -y -d` and `hogli wait`, then the seed script. Start any extra workers again.++## ElevenLabs calls fail++- `ELEVENLABS_API_KEY` missing: the recorder leaves out the voiceover and generated music, and lists them under `skipped_without_elevenlabs_key` in the log. A music `file` still plays. To add them, the developer sets the key in the shell. In a cloud task, add it as an environment variable of the task's environment in PostHog Desktop, under Settings and Environments. Never paste it into a storyboard or a commit.+- `401` or `quota_exceeded`: the key is wrong, lacks access to the endpoint, or the account ran out of credits. Takes already in the cache still work.+- A certificate error: the recorder uses `certifi`'s certificates, which the repo's Python environment has. Run it with `uv run python` from the checkout.++## Inline HTML is refused++The app's Content Security Policy refuses inline scripts and styles, and the cards and the overlay are both.+The recorder turns the policy off in its own browser context only, with Playwright's `bypass_csp`. The app is unchanged.++## A text field ignores the typing++Some fields are code editors rather than inputs, such as fields that accept Liquid.+Click the field, move the caret with `keys` (`Control+Home`, `Home`, `ArrowRight x10`), then type.+To find the field, a selector chain from its label works: `text=Subject >> nth=0 >> xpath=following-sibling::*[1]`.diff --git a/.agents/skills/recording-demo-videos/scripts/record_demo.py b/.agents/skills/recording-demo-videos/scripts/record_demo.pynew file mode 100644index 000000000000..8637b596368e--- /dev/null+++ b/.agents/skills/recording-demo-videos/scripts/record_demo.py@@ -0,0 +1,831 @@+"""Record a captioned, PostHog-branded walkthrough video of a flow on the local stack.++Run from the root of a PostHog checkout, with the stack up:++ uv run python .agents/skills/recording-demo-videos/scripts/record_demo.py storyboard.json++The storyboard format is in references/storyboard.md. The script writes the MP4, a contact sheet+of frames to review, and a log with the cut list next to the `output` path in the storyboard.+"""++import os+import re+import sys+import json+import time+import base64+import shutil+import asyncio+import hashlib+import tempfile+import subprocess+from pathlib import Path+from typing import Any++import requests+from playwright.async_api import BrowserContext, Locator, Page, async_playwright++DEFAULT_VIEWPORT = {"width": 1440, "height": 900}+FIRST_LOAD_TIMEOUT_MS = 300_000+STEP_TIMEOUT_MS = 120_000+# A wait longer than this is cut from the final video, keeping this many seconds of it.+CUT_KEEP_SECONDS = 0.3+FPS = 25+# The debug chrome of a local dev stack. It is noise in a demo.+DEFAULT_HIDE_SELECTORS = [".tricolor"]+DEFAULT_HIDE_TEXT = ["DEBUG mode"]+ELEVEN_URL = "https://api.elevenlabs.io/v1/text-to-speech/{voice}/with-timestamps?output_format=mp3_44100_128"+# Brian, the premade ElevenLabs voice the DevEx videos use, at their settings.+DEFAULT_VOICEOVER = {+ "voice": "nPczCjzI2devNBz1zQrb",+ "model": "eleven_v3",+ "settings": {"stability": 0.5, "speed": 1.12},+}+VOICE_CACHE = Path.home() / ".cache" / "posthog-demo-videos" / "voiceover"+MUSIC_URL = "https://api.elevenlabs.io/v1/music?output_format=mp3_44100_128"+MUSIC_CACHE = Path.home() / ".cache" / "posthog-demo-videos" / "music"+DEFAULT_MUSIC_PROMPT = (+ "Light, upbeat, playful instrumental background music for a software product demo. Soft synth plucks, "+ "gentle drums, warm bass. Steady tempo, unobtrusive, no big drops."+)+# The bed sits well under the voice, and dips further while a line plays.+DEFAULT_MUSIC_VOLUME = 0.18+# Breath between a line ending and the next step starting.+VOICE_TAIL_SECONDS = 0.35+# Variables named like a credential are secret even when the storyboard does not list them in `secrets`.+SECRET_NAME = re.compile(r"(?:^|_)(?:KEY|TOKEN|SECRET|PASSWORD)$", re.IGNORECASE)+# Shorter secret values are too common to mask safely by value. The `$NAME` placeholder still hides them.+MIN_MASKED_LENGTH = 8+# PostHog's secret key formats, such as a key that a response body returns. `phc_` is public.+SECRET_TOKEN = re.compile(r"\b(ph[xshare])_[A-Za-z0-9_-]{16,}")+STICKER_POSITIONS = {+ "bottom-right": "right:56px;bottom:120px",+ "bottom-left": "left:56px;bottom:120px",+ "top-right": "right:56px;top:96px",+ "top-left": "left:56px;top:96px",+}+FALLBACK_COLORS = {+ "cobalt": "#0457FF",+ "tangerine": "#FF5C1C",+ "cream": "#F4F3EE",+ "dark": "#1D1F27",+ "green": "#47C861",+}++LOGO_JS = """+import { createElement } from "react"+import { renderToStaticMarkup } from "react-dom/server"+import { Logo } from "@posthog/brand/logo"+const variants = { color: { variant: "gradient" }, white: { variant: "mono", color: "#FFFFFF" } }+const out = {}+for (const [name, props] of Object.entries(variants)) {+ out[name] = renderToStaticMarkup(createElement(Logo, { ...props, size: "100%" }))+}+console.log(JSON.stringify(out))+"""+++class Brand:+ """PostHog brand assets from the @posthog/brand package the frontend already depends on."""++ def __init__(self, repo_root: Path) -> None:+ self.package = repo_root / "frontend" / "node_modules" / "@posthog" / "brand" / "dist"+ self.available = self.package.exists()+ self.colors = dict(FALLBACK_COLORS)+ self.font_css = ""+ self.logos = {"color": "", "white": ""}+ if not self.available:+ sys.stderr.write("warning: @posthog/brand not found, run pnpm install. Using fallback styling.\n")+ return+ self._load_colors()+ self._load_fonts()+ self._load_logos(repo_root / "frontend")++ def _load_colors(self) -> None:+ source = (self.package / "generated" / "colors" / "css.mjs").read_text()+ match = re.search(r'const colorsCss = ("(?:[^"\\]|\\.)*")', source)+ if not match:+ return+ css = json.loads(match.group(1))+ for name, value in re.findall(r"--posthog-([a-z-]+):\s*(#[0-9A-Fa-f]{6})", css):+ self.colors[name] = value+ self.colors.setdefault("cream", FALLBACK_COLORS["cream"])+ self.colors.setdefault("dark", FALLBACK_COLORS["dark"])++ def _load_fonts(self) -> None:+ faces = {500: "RoundHog-Medium.woff2", 700: "RoundHog-SemiBold.woff2", 800: "RoundHog-Bold.woff2"}+ rules = []+ for weight, filename in faces.items():+ path = self.package / "fonts" / filename+ if path.exists():+ data = base64.b64encode(path.read_bytes()).decode()+ rules.append(+ f'@font-face{{font-family:"RoundHog";font-weight:{weight};font-style:normal;'+ f'src:url(data:font/woff2;base64,{data}) format("woff2")}}'+ )+ self.font_css = "\n".join(rules)++ def _load_logos(self, frontend: Path) -> None:+ try:+ result = subprocess.run(+ ["node", "--input-type=module", "-e", LOGO_JS],+ cwd=frontend,+ capture_output=True,+ text=True,+ timeout=60,+ check=True,+ )+ self.logos = json.loads(result.stdout)+ except (subprocess.SubprocessError, json.JSONDecodeError, OSError) as error:+ sys.stderr.write(f"warning: could not render the logo ({error}). Cards go without it.\n")++ def hog(self, slug: str | None) -> str:+ if not slug or not self.available:+ return ""+ path = self.package / "generated" / "hoggies" / "png" / f"{slug}.png"+ if not path.exists():+ options = sorted(p.stem for p in path.parent.glob("*.png"))+ raise SystemExit(f'Unknown hog "{slug}". Pick one of: {", ".join(options)}')+ return "data:image/png;base64," + base64.b64encode(path.read_bytes()).decode()+++def overlay_script(brand: Brand, hide_selectors: list[str], hide_text: list[str]) -> str:+ """The caption bar, the cursor and the chrome hider, injected into every page of the recording."""+ config = {+ "fontCss": brand.font_css,+ "dark": brand.colors["dark"],+ "cream": brand.colors["cream"],+ "accent": brand.colors["tangerine"],+ "hideSelectors": hide_selectors,+ "hideText": hide_text,+ }+ return (+ "(() => { const C = "+ + json.dumps(config)+ + r""";+ // Hidden from the first frame of every page, before the app renders them.+ if (C.hideSelectors.length) {+ const early = document.createElement('style');+ early.textContent = C.hideSelectors.join(',') + '{display:none!important}';+ // The root element can be missing this early in a load. A failure here would stop the whole overlay.+ const attach = () => { if (!document.documentElement) return false; document.documentElement.appendChild(early); return true; };+ if (!attach()) { const watch = new MutationObserver(() => { if (attach()) watch.disconnect(); }); watch.observe(document, { childList: true }); }+ }+ const ensure = () => {+ if (!document.body || document.getElementById('__demo_cursor')) return;+ if (C.fontCss) { const s = document.createElement('style'); s.textContent = C.fontCss; document.head.appendChild(s); }+ const cursor = document.createElement('div'); cursor.id = '__demo_cursor';+ cursor.style.cssText = 'position:fixed;left:0;top:0;width:22px;height:22px;margin:-11px 0 0 -11px;border-radius:50%;'+ + 'background:' + C.accent + '55;border:2px solid ' + C.accent + ';z-index:2147483647;pointer-events:none;'+ + 'transition:transform .08s;transform:translate(-100px,-100px)';+ document.body.appendChild(cursor);+ const cap = document.createElement('div'); cap.id = '__demo_caption';+ cap.style.cssText = 'position:fixed;left:50%;bottom:32px;transform:translateX(-50%);max-width:1080px;padding:14px 24px;'+ + 'border-radius:10px;border-left:6px solid ' + C.accent + ';background:' + C.dark + 'ee;color:' + C.cream + ';'+ + 'font:700 21px/1.35 RoundHog,-apple-system,Inter,sans-serif;z-index:2147483646;pointer-events:none;'+ + 'text-align:left;box-shadow:0 10px 30px rgba(0,0,0,.25);display:none';+ document.body.appendChild(cap);+ let x = -100, y = -100, s = 1;+ const paint = () => { cursor.style.transform = `translate(${x}px,${y}px) scale(${s})`; };+ document.addEventListener('mousemove', e => { x = e.clientX; y = e.clientY; paint(); }, true);+ document.addEventListener('mousedown', () => { s = 0.7; paint(); }, true);+ document.addEventListener('mouseup', () => { s = 1; paint(); }, true);+ };+ const hide = () => {+ for (const sel of C.hideSelectors) document.querySelectorAll(sel).forEach(el => { el.style.display = 'none'; });+ if (!C.hideText.length) return;+ for (const el of document.querySelectorAll('div,section,aside,header,footer')) {+ const t = (el.textContent || '').trim();+ for (const text of C.hideText) {+ const parent = el.parentElement ? (el.parentElement.textContent || '').trim() : '';+ if (t.startsWith(text) && t.length < text.length + 120 && parent.length >= text.length + 120) el.style.display = 'none';+ }+ }+ };+ window.__sticker = (src, label, pos, seconds) => {+ ensure();+ const el = document.createElement('div');+ el.style.cssText = 'position:fixed;' + pos + ';z-index:2147483645;pointer-events:none;display:flex;flex-direction:column;'+ + 'align-items:center;gap:6px;transform:scale(.2) rotate(-14deg);opacity:0;'+ + 'transition:transform .42s cubic-bezier(.34,1.7,.5,1),opacity .2s';+ el.innerHTML = '<img src="' + src + '" style="width:190px;height:190px;object-fit:contain;filter:drop-shadow(0 8px 14px rgba(0,0,0,.22))">'+ + (label ? '<div style="background:' + C.accent + ';color:#fff;font:800 22px RoundHog,-apple-system,sans-serif;'+ + 'padding:6px 16px;border-radius:999px;transform:rotate(-4deg);box-shadow:0 6px 16px rgba(0,0,0,.2)"></div>' : '');+ if (label) el.lastChild.textContent = label;+ document.body.appendChild(el);+ requestAnimationFrame(() => requestAnimationFrame(() => { el.style.opacity = '1'; el.style.transform = 'scale(1) rotate(5deg)'; }));+ setTimeout(() => { el.style.transition = 'transform .3s ease-in,opacity .3s'; el.style.opacity = '0';+ el.style.transform = 'scale(.6) rotate(12deg)'; setTimeout(() => el.remove(), 400); }, seconds * 1000);+ };+ window.__caption = (t) => { ensure(); const el = document.getElementById('__demo_caption'); if (!el) return;+ el.textContent = t || ''; el.style.display = t ? 'block' : 'none'; };+ document.addEventListener('DOMContentLoaded', ensure);+ setInterval(() => { ensure(); hide(); }, 300);+})();"""+ )+++def card_html(brand: Brand, heading: str, subheading: str, hog: str, dark: bool = False) -> str:+ bg = brand.colors["dark"] if dark else brand.colors["cream"]+ fg = brand.colors["cream"] if dark else brand.colors["dark"]+ logo = brand.logos.get("white" if dark else "color", "")+ hog_img = f'<img src="{hog}" style="width:340px;height:340px;object-fit:contain">' if hog else ""+ return f"""<!doctype html><html><head><style>{brand.font_css}+body{{margin:0;height:100vh;background:{bg};color:{fg};font-family:RoundHog,-apple-system,Inter,sans-serif;+display:flex;align-items:center;justify-content:center;overflow:hidden}}+.logo{{position:absolute;top:44px;left:56px;width:180px}}+.wrap{{display:flex;align-items:center;gap:64px;max-width:1180px;padding:0 80px}}+h1{{font-weight:800;font-size:64px;line-height:1.05;margin:0 0 20px}}+p{{font-weight:500;font-size:28px;line-height:1.35;margin:0;opacity:.8}}+.bar{{width:72px;height:8px;border-radius:4px;background:{brand.colors["tangerine"]};margin-bottom:28px}}+</style></head><body><div class="logo">{logo}</div><div class="wrap"><div><div class="bar"></div>+<h1>{escape(heading)}</h1><p>{escape(subheading)}</p></div>{hog_img}</div></body></html>"""+++def terminal_html(brand: Brand, title: str) -> str:+ return f"""<!doctype html><html><head><style>{brand.font_css}+body{{margin:0;height:100vh;background:{brand.colors["dark"]};color:#d4d4d4;font:17px/1.6 Menlo,Consolas,monospace}}+.logo{{position:absolute;top:36px;right:48px;width:140px;opacity:.9}}+.title{{font:700 26px RoundHog,-apple-system,sans-serif;color:{brand.colors["cream"]};margin-bottom:24px}}+pre{{white-space:pre-wrap;margin:0}} #out{{margin-top:24px;color:{brand.colors["green"]}}}+#out.bad{{color:{brand.colors.get("coral", "#FF474D")}}}+</style></head><body><div class="logo">{brand.logos.get("white", "")}</div>+<div style="padding:56px 64px"><div class="title">{escape(title)}</div><pre id="cmd"></pre><pre id="out"></pre></div></body></html>"""+++def escape(text: str) -> str:+ return text.replace("&", "&").replace("<", "<").replace(">", ">")+++class Vars:+ """`${NAME}` substitution. Secret values are used for requests but shown as `$NAME`.++ Shown text is also masked by value, so a secret that reaches it another way, such as in a+ response body or an unlisted variable named like a key, still never appears in the video.+ """++ def __init__(self, values: dict[str, str], secrets: list[str]) -> None:+ self.values = values+ self.secrets = set(secrets) | {name for name in values if SECRET_NAME.search(name)}+ masks = [(values[name], name) for name in self.secrets if len(values.get(name, "")) >= MIN_MASKED_LENGTH]+ # Longest first, so a secret that contains another one is masked whole.+ self.masks = sorted(masks, key=lambda mask: -len(mask[0]))++ def real(self, value: Any) -> Any:+ return self._walk(value, show=False)++ def shown(self, value: Any) -> Any:+ return self._walk(value, show=True)++ def mask(self, text: str) -> str:+ for secret, name in self.masks:+ text = text.replace(secret, f"${name}")+ return SECRET_TOKEN.sub(lambda m: f"{m.group(1)}_********", text)++ def _walk(self, value: Any, show: bool) -> Any:+ if isinstance(value, str):+ text = re.sub(r"\$\{(\w+)\}", lambda m: self._one(m.group(1), show), value)+ return self.mask(text) if show else text+ if isinstance(value, list):+ return [self._walk(v, show) for v in value]+ if isinstance(value, dict):+ return {k: self._walk(v, show) for k, v in value.items()}+ return value++ def _one(self, name: str, show: bool) -> str:+ if show and name in self.secrets:+ return f"${name}"+ if name not in self.values:+ raise SystemExit(f"Storyboard uses ${{{name}}} but it is not in vars or the environment.")+ return self.values[name]+++def elevenlabs_post(url: str, body: dict[str, Any], timeout: int) -> bytes:+ api_key = os.environ.get("ELEVENLABS_API_KEY")+ if not api_key:+ raise SystemExit("Music and voiceover need ELEVENLABS_API_KEY in the environment.")+ try:+ response = requests.post(url, json=body, headers={"xi-api-key": api_key}, timeout=timeout)+ except requests.RequestException as error:+ raise SystemExit(f"Could not reach ElevenLabs: {error}") from error+ if not response.ok:+ raise SystemExit(f"ElevenLabs returned {response.status_code}: {response.text[:400]}")+ return response.content+++class Voiceover:+ """One ElevenLabs take of every spoken line, cut back into a clip per line.++ The whole script is read as one take, so the delivery flows instead of restarting on each line.+ The per-character timestamps from ElevenLabs cut it per line. Takes are cached by text and voice,+ so recording again with the same script costs no credits.+ """++ def __init__(self, config: dict[str, Any], lines: dict[str, str], workdir: Path) -> None:+ self.config = {**DEFAULT_VOICEOVER, **config}+ self.lines = {key: text for key, text in lines.items() if text.strip()}+ self.clips: dict[str, tuple[Path, float]] = {}+ if self.lines:+ self._prepare(workdir)++ def _prepare(self, workdir: Path) -> None:+ keys = list(self.lines)+ text = "\n\n".join(self.lines[key] for key in keys)+ mp3, alignment = self._take(text)+ chars = alignment["characters"]+ starts, ends = alignment["character_start_times_seconds"], alignment["character_end_times_seconds"]+ spoken = "".join(chars)+ cursor = 0+ for key in keys:+ at = spoken.find(self.lines[key], cursor)+ if at < 0:+ raise SystemExit(f"The voiceover take does not contain the line for {key}.")+ end = at + len(self.lines[key]) - 1+ cursor = end + 1+ begin, finish = max(starts[at] - 0.05, 0), ends[end] + 0.1+ clip = workdir / f"voice-{key}.wav"+ subprocess.run(+ [+ "ffmpeg",+ "-y",+ "-loglevel",+ "error",+ "-i",+ str(mp3),+ "-ss",+ f"{begin:.3f}",+ "-to",+ f"{finish:.3f}",+ str(clip),+ ],+ check=True,+ )+ self.clips[key] = (clip, finish - begin)++ def _take(self, text: str) -> tuple[Path, dict[str, Any]]:+ key = hashlib.sha256(json.dumps([text, self.config], sort_keys=True).encode()).hexdigest()[:20]+ mp3, timing = VOICE_CACHE / f"{key}.mp3", VOICE_CACHE / f"{key}.json"+ if mp3.exists() and timing.exists():+ return mp3, json.loads(timing.read_text())+ body = {"text": text, "model_id": self.config["model"], "voice_settings": self.config.get("settings", {})}+ data = json.loads(elevenlabs_post(ELEVEN_URL.format(voice=self.config["voice"]), body, timeout=300))+ VOICE_CACHE.mkdir(parents=True, exist_ok=True)+ mp3.write_bytes(base64.b64decode(data["audio_base64"]))+ # Written last, so a half-written take never counts as cached.+ timing.write_text(json.dumps(data["alignment"]))+ return mp3, data["alignment"]+++def spoken_lines(storyboard: dict[str, Any], variables: "Vars") -> dict[str, str]:+ """What the voiceover says, keyed by where it is said. A `say` key wins over the caption or card text."""++ def card_line(spec: dict[str, Any]) -> str:+ if "say" in spec:+ return spec["say"]+ return " ".join(part.rstrip(".") + "." for part in (spec.get("heading"), spec.get("subheading")) if part)++ lines: dict[str, str] = {}+ if "title" in storyboard:+ lines["title"] = card_line(storyboard["title"])+ for index, step in enumerate(storyboard["steps"]):+ if "card" in step:+ lines[f"step{index}"] = card_line(step["card"])+ elif "http" in step:+ lines[f"step{index}"] = step["http"].get("say", step["http"].get("title", ""))+ else:+ lines[f"step{index}"] = step.get("say", step.get("caption", ""))+ if "end" in storyboard:+ lines["end"] = card_line(storyboard["end"])+ return {key: variables.shown(text) for key, text in lines.items()}+++class Recorder:+ def __init__(self, storyboard: dict[str, Any], brand: Brand, variables: Vars) -> None:+ self.sb = storyboard+ self.brand = brand+ self.vars = variables+ self.base_url = storyboard.get("base_url", "http://localhost:8010").rstrip("/")+ self.cuts: list[tuple[float, float]] = []+ self.t0 = 0.0+ self.voice: Voiceover | None = None+ # Sounds to lay over the video: (seconds into the cut video, file).+ self.sounds: list[tuple[float, Path]] = []+ self.speaking_until = 0.0+ self.pop: Path | None = None+ self.voice_log: list[dict[str, Any]] = []+ self.base = Path(".")++ def now(self) -> float:+ return time.monotonic() - self.t0++ def video_now(self) -> float:+ """Seconds into the final video, after the cuts made so far."""+ return self.now() - sum(end - start for start, end in self.cuts)++ def speak(self, key: str) -> None:+ if not self.voice or key not in self.voice.clips:+ return+ clip, duration = self.voice.clips[key]+ self.sounds.append((self.video_now(), clip))+ self.voice_log.append({"line": key, "at": round(self.video_now(), 2), "seconds": round(duration, 2)})+ self.speaking_until = self.video_now() + duration + VOICE_TAIL_SECONDS++ async def finish_speaking(self) -> None:+ # Cuts made while a line plays shorten the video, so this waits on video time, not wall time.+ while self.video_now() < self.speaking_until:+ await asyncio.sleep(0.1)++ async def sticker(self, page: Page, spec: dict[str, Any]) -> None:+ position = STICKER_POSITIONS.get(spec.get("position", "bottom-right"), STICKER_POSITIONS["bottom-right"])+ await page.evaluate(+ "([src, label, pos, seconds]) => window.__sticker && window.__sticker(src, label, pos, seconds)",+ [+ self.brand.hog(spec.get("hog", "star")),+ self.vars.shown(spec.get("text", "")),+ position,+ spec.get("seconds", 3),+ ],+ )+ if self.pop:+ self.sounds.append((self.video_now() + 0.05, self.pop))++ async def waited(self, coro: Any, keep: float = CUT_KEEP_SECONDS) -> None:+ start = self.now()+ await coro+ end = self.now()+ if end - start > keep + 0.4:+ self.cuts.append((round(start + keep, 2), round(end - 0.2, 2)))++ def url(self, path: str) -> str:+ path = self.vars.real(path)+ return path if path.startswith("http") else f"{self.base_url}{path}"++ def locate(self, page: Page, target: dict[str, Any]) -> Locator:+ target = self.vars.real(target)+ scope = page.locator(target["within"]) if "within" in target else page.locator("body")+ if "selector" in target:+ loc = scope.locator(target["selector"])+ elif "role" in target:+ loc = scope.get_by_role(target["role"], name=target.get("name"), exact=True)+ elif "label" in target:+ loc = scope.get_by_label(target["label"], exact=True)+ elif "text" in target:+ loc = scope.get_by_text(target["text"], exact=target.get("exact", False))+ else:+ raise SystemExit(f"Target needs selector, role, label or text: {target}")+ return loc.nth(target.get("nth", 0))++ async def caption(self, page: Page, text: str) -> None:+ await page.evaluate("t => window.__caption && window.__caption(t)", self.vars.shown(text))++ async def glide(self, page: Page, loc: Locator) -> None:+ await loc.wait_for(state="visible", timeout=STEP_TIMEOUT_MS)+ await loc.scroll_into_view_if_needed()+ box = await loc.bounding_box()+ if box:+ await page.mouse.move(box["x"] + box["width"] / 2, box["y"] + box["height"] / 2, steps=25)+ await asyncio.sleep(0.25)++ async def log_in(self, context: BrowserContext) -> None:+ login = self.sb.get("login", {"email": "[email protected]", "password": "12345678"})+ page = await context.new_page()+ await page.goto(f"{self.base_url}/login", timeout=FIRST_LOAD_TIMEOUT_MS)+ status = await page.evaluate(+ """async ({email, password}) => (await fetch('/api/login/', {method: 'POST',+ headers: {'Content-Type': 'application/json'}, body: JSON.stringify({email, password})})).status""",+ self.vars.real(login),+ )+ if status != 200:+ raise SystemExit(f"Login returned {status}. Check `login` in the storyboard.")+ # The dev server compiles each chunk on its first request. Loading every page once here keeps+ # the recording from showing minutes of spinners.+ for step in self.sb["steps"]:+ if "goto" in step and self.url(step["goto"]).startswith(self.base_url):+ await page.goto(self.url(step["goto"]), timeout=FIRST_LOAD_TIMEOUT_MS)+ await page.wait_for_timeout(5000)+ await page.close()++ async def card(self, page: Page, spec: dict[str, Any], key: str, dark: bool = False) -> None:+ html = card_html(+ self.brand,+ self.vars.shown(spec.get("heading", "")),+ self.vars.shown(spec.get("subheading", "")),+ self.brand.hog(spec.get("hog")),+ dark=dark,+ )+ await page.set_content(html)+ self.speak(key)+ await asyncio.sleep(spec.get("hold", 1.0 if self.voice else 2.5))+ await self.finish_speaking()++ async def http(self, page: Page, spec: dict[str, Any], key: str) -> None:+ method = spec.get("method", "POST").upper()+ shown_url, real_url = self.url(self.vars.shown(spec["url"])), self.url(spec["url"])+ headers = spec.get("headers", {})+ body = spec.get("json")+ lines = [f"$ curl -X {method} {shown_url} \\"]+ for name, value in self.vars.shown(headers).items():+ lines.append(f' -H "{name}: {value}" \\')+ if body is not None:+ lines.append(' -H "Content-Type: application/json" \\')+ lines.append(f" -d '{json.dumps(self.vars.shown(body), indent=2)}'")+ command = "\n".join(lines).rstrip(" \\")+ await page.set_content(terminal_html(self.brand, self.vars.shown(spec.get("title", ""))))+ self.speak(key)+ await page.evaluate(+ """async (t) => { const el = document.getElementById('cmd');+ for (let i = 0; i < t.length; i += 3) { el.textContent = t.slice(0, i + 3); await new Promise(r => setTimeout(r, 12)); } }""",+ command,+ )+ await asyncio.sleep(0.5)+ response = requests.request(+ method,+ real_url,+ json=self.vars.real(body) if body is not None else None,+ headers=self.vars.real(headers),+ timeout=60,+ )+ status, raw = response.status_code, response.content+ try:+ text = json.dumps(json.loads(raw), indent=2)+ except ValueError:+ text = raw.decode(errors="replace")[:1500]+ text = self.vars.mask(text)+ await page.evaluate(+ "([t, bad]) => { const el = document.getElementById('out'); el.textContent = t; if (bad) el.className = 'bad'; }",+ [f"HTTP {status}\n{text}", status >= 400],+ )+ expected = spec.get("expect_status")+ if expected and status != expected:+ raise RuntimeError(f"{method} {shown_url} returned {status}, expected {expected}: {text[:300]}")+ await asyncio.sleep(spec.get("hold", 1.5 if self.voice else 3))+ await self.finish_speaking()++ async def step(self, page: Page, step: dict[str, Any], key: str) -> None:+ if "card" in step:+ await self.card(page, step["card"], key)+ return+ if "http" in step:+ await self.http(page, step["http"], key)+ return+ if "goto" in step:+ await self.waited(page.goto(self.url(step["goto"]), timeout=FIRST_LOAD_TIMEOUT_MS), keep=0.2)+ if "wait_for" in step and "goto" in step:+ await self.waited(self.locate(page, step["wait_for"]).wait_for(timeout=STEP_TIMEOUT_MS), keep=0.2)+ if "caption" in step:+ await self.caption(page, step["caption"])+ self.speak(key)+ if "scroll" in step:+ await page.mouse.wheel(0, step["scroll"])+ await asyncio.sleep(0.6)+ if "hover" in step:+ await self.glide(page, self.locate(page, step["hover"]))+ if "click" in step:+ loc = self.locate(page, step["click"])+ await self.glide(page, loc)+ await loc.click()+ if "type" in step:+ spec = step["type"]+ if "target" in spec:+ loc = self.locate(page, spec["target"])+ await self.glide(page, loc)+ await loc.click()+ for key in spec.get("keys", []):+ name, _, times = key.partition(" x")+ for _ in range(int(times or 1)):+ await page.keyboard.press(name)+ await page.keyboard.type(self.vars.real(spec.get("text", "")), delay=spec.get("delay_ms", 80))+ if "wait_for" in step and "goto" not in step:+ await self.waited(self.locate(page, step["wait_for"]).wait_for(timeout=STEP_TIMEOUT_MS))+ if "sticker" in step:+ await self.sticker(page, step["sticker"])+ default_hold = 0.5 if self.voice else max(1.5, len(step.get("caption", "").split()) * 0.25)+ await asyncio.sleep(step.get("hold", default_hold))+ await self.finish_speaking()++ async def run(self, output: Path) -> dict[str, Any]:+ viewport = self.sb.get("viewport", DEFAULT_VIEWPORT)+ video_dir = Path(tempfile.mkdtemp(prefix="demo-video-"))+ log: dict[str, Any] = {"output": str(output)}+ if "voiceover" in self.sb:+ self.voice = Voiceover(self.sb["voiceover"], spoken_lines(self.sb, self.vars), video_dir)+ if any("sticker" in step for step in self.sb["steps"]):+ self.pop = pop_sound(video_dir)+ async with async_playwright() as p:+ browser = await p.chromium.launch()+ setup = await browser.new_context(viewport=viewport)+ await self.log_in(setup)+ state = await setup.storage_state()+ await setup.close()+ context = await browser.new_context(+ viewport=viewport,+ storage_state=state,+ # Cards and the overlay are inline HTML, which the app's Content Security Policy refuses.+ bypass_csp=True,+ record_video_dir=str(video_dir),+ record_video_size=viewport,+ )+ await context.add_init_script(+ overlay_script(+ self.brand,+ DEFAULT_HIDE_SELECTORS + self.sb.get("hide_selectors", []),+ DEFAULT_HIDE_TEXT + self.sb.get("hide_text", []),+ )+ )+ page = await context.new_page()+ self.t0 = time.monotonic()+ try:+ if "title" in self.sb:+ await self.card(page, self.sb["title"], "title")+ for index, step in enumerate(self.sb["steps"]):+ log["step"] = index+ await self.step(page, step, f"step{index}")+ await self.caption(page, "")+ if "end" in self.sb:+ await self.card(page, self.sb["end"], "end")+ # The recording drops its last frames when the context closes.+ await asyncio.sleep(1.5)+ log["duration"] = round(self.now(), 2)+ except Exception as error:+ log["error"] = self.vars.mask(f"step {log.get('step')}: {error!r}")[:800]+ await page.screenshot(path=str(output.with_suffix(".error.png")))+ finally:+ raw_video = Path(await page.video.path()) if page.video else None+ await context.close()+ await browser.close()+ log["cuts"] = self.cuts+ if self.voice_log:+ log["voice"] = self.voice_log+ if raw_video and "error" not in log:+ encode(+ raw_video,+ output,+ self.cuts,+ log["duration"],+ self.sounds,+ self.sb["music"] if "music" in self.sb else None,+ self.base,+ )+ contact_sheet(output)+ elif raw_video:+ shutil.copy(raw_video, output.with_suffix(".failed.webm"))+ shutil.rmtree(video_dir, ignore_errors=True)+ return log+++def music_track(spec: dict[str, Any], seconds: float, base: Path) -> Path:+ """A music bed at least `seconds` long: a file from the storyboard, or one generated by ElevenLabs Music."""+ if "file" in spec:+ return (base / spec["file"]).resolve()+ prompt = spec.get("prompt", DEFAULT_MUSIC_PROMPT)+ # Generated in 10 second steps, so a slightly longer take reuses the cached track.+ length_ms = min(max(int((seconds + 9.99) // 10 * 10_000), 10_000), 300_000)+ key = hashlib.sha256(json.dumps([prompt, length_ms]).encode()).hexdigest()[:20]+ path = MUSIC_CACHE / f"{key}.mp3"+ if not path.exists():+ audio = elevenlabs_post(+ MUSIC_URL, {"prompt": prompt, "music_length_ms": length_ms, "force_instrumental": True}, timeout=600+ )+ MUSIC_CACHE.mkdir(parents=True, exist_ok=True)+ path.write_bytes(audio)+ return path+++def duration_of(path: Path) -> float:+ probe = subprocess.run(+ ["ffprobe", "-v", "error", "-show_entries", "format=duration", "-of", "csv=p=0", str(path)],+ capture_output=True, text=True, check=True,+ ) # fmt: skip+ return float(probe.stdout.strip())+++def encode(+ raw: Path,+ output: Path,+ cuts: list[tuple[float, float]],+ duration: float,+ sounds: list[tuple[float, Path]],+ music: dict[str, Any] | None,+ base: Path,+) -> None:+ keep = f"between(t,0,{duration + 0.5})"+ if cuts:+ keep += "*not(" + "+".join(f"between(t,{a},{b})" for a, b in cuts) + ")"+ silent = output.with_suffix(".silent.mp4") if sounds or music is not None else output+ subprocess.run(+ [+ "ffmpeg", "-y", "-loglevel", "error", "-i", str(raw),+ "-vf", f"fps={FPS},select='{keep}',setpts=N/{FPS}/TB",+ "-an", "-c:v", "libx264", "-preset", "medium", "-crf", "22",+ "-pix_fmt", "yuv420p", "-movflags", "+faststart", str(silent),+ ],+ check=True,+ ) # fmt: skip+ if not sounds and music is None:+ return+ inputs: list[str] = []+ chains: list[str] = []+ for index, (at, path) in enumerate(sounds, start=1):+ inputs += ["-i", str(path)]+ delay = max(int(at * 1000), 0)+ chains.append(f"[{index}:a]aresample=44100,aformat=channel_layouts=stereo,adelay={delay}|{delay}[s{index}]")+ if sounds:+ mix = "".join(f"[s{i}]" for i in range(1, len(sounds) + 1))+ chains.append(f"{mix}amix=inputs={len(sounds)}:normalize=0:dropout_transition=0[front]")+ if music is not None:+ length = duration_of(silent)+ inputs += ["-stream_loop", "-1", "-i", str(music_track(music, length, base))]+ volume = music.get("volume", DEFAULT_MUSIC_VOLUME)+ fade_out = max(length - 2.5, 0)+ chains.append(+ f"[{len(sounds) + 1}:a]aresample=44100,aformat=channel_layouts=stereo,atrim=0:{length:.2f},"+ f"volume={volume},afade=t=in:d=1.5,afade=t=out:st={fade_out:.2f}:d=2.5[bed]"+ )+ if sounds:+ # The bed ducks under the voice and sound effects, then comes back up between lines.+ chains.append("[front]asplit=2[front_mix][front_key]")+ chains.append("[bed][front_key]sidechaincompress=threshold=0.02:ratio=6:attack=30:release=400[ducked]")+ chains.append("[front_mix][ducked]amix=inputs=2:normalize=0:dropout_transition=0[mixed]")+ else:+ chains.append("[bed]anull[mixed]")+ else:+ chains.append("[front]anull[mixed]")+ # -16 LUFS, the usual level for web video, so it plays as loud as other videos in Slack or Loom.+ chains.append("[mixed]loudnorm=I=-16:TP=-1.5:LRA=11[aout]")+ graph = ";".join(chains)+ subprocess.run(+ [+ "ffmpeg", "-y", "-loglevel", "error", "-i", str(silent), *inputs,+ "-filter_complex", graph, "-map", "0:v", "-map", "[aout]",+ "-c:v", "copy", "-c:a", "aac", "-b:a", "160k", "-shortest", "-movflags", "+faststart", str(output),+ ],+ check=True,+ ) # fmt: skip+ silent.unlink()+++def pop_sound(workdir: Path) -> Path:+ """A short rising blip for stickers, synthesized so the skill ships no audio files."""+ path = workdir / "pop.wav"+ subprocess.run(+ [+ "ffmpeg", "-y", "-loglevel", "error", "-f", "lavfi",+ "-i", "aevalsrc='0.4*sin(2*PI*(420+2600*t)*t)*exp(-16*t)':s=44100:d=0.22",+ "-ac", "2", str(path),+ ],+ check=True,+ ) # fmt: skip+ return path+++def contact_sheet(video: Path) -> None:+ every = max(duration_of(video) / 16, 0.5)+ subprocess.run(+ [+ "ffmpeg", "-y", "-loglevel", "error", "-i", str(video),+ "-vf", f"fps=1/{every:.2f},scale=480:-1,tile=4x4", "-frames:v", "1",+ str(video.with_suffix(".sheet.png")),+ ],+ check=True,+ ) # fmt: skip+++def without_elevenlabs(storyboard: dict[str, Any]) -> tuple[dict[str, Any], list[str]]:+ """Drop the voiceover and generated music, so a developer without an ElevenLabs key still gets a captioned video."""+ skipped = []+ if "voiceover" in storyboard:+ skipped.append("voiceover")+ if "music" in storyboard and "file" not in storyboard["music"]:+ skipped.append("music")+ return {name: value for name, value in storyboard.items() if name not in skipped}, skipped+++def main() -> None:+ if len(sys.argv) != 2:+ raise SystemExit(__doc__)+ if not shutil.which("ffmpeg"):+ raise SystemExit("ffmpeg is missing. Install it first (apt-get install -y ffmpeg, or brew install ffmpeg).")+ storyboard_path = Path(sys.argv[1]).resolve()+ storyboard = json.loads(storyboard_path.read_text())+ skipped: list[str] = []+ if not os.environ.get("ELEVENLABS_API_KEY"):+ storyboard, skipped = without_elevenlabs(storyboard)+ repo_root = Path(+ subprocess.run(["git", "rev-parse", "--show-toplevel"], capture_output=True, text=True).stdout.strip() or "."+ )+ output = (storyboard_path.parent / storyboard.get("output", "demo.mp4")).resolve()+ output.parent.mkdir(parents=True, exist_ok=True)+ values = {**os.environ, **storyboard.get("vars", {})}+ recorder = Recorder(storyboard, Brand(repo_root), Vars(values, storyboard.get("secrets", [])))+ recorder.base = storyboard_path.parent+ log = asyncio.run(recorder.run(output))+ if skipped:+ log["skipped_without_elevenlabs_key"] = skipped+ output.with_suffix(".log.json").write_text(json.dumps(log, indent=2))+ sys.stdout.write(json.dumps(log, indent=2) + "\n")+ if "error" in log:+ raise SystemExit(1)+++if __name__ == "__main__":+ main()