Marketing skills for Claude Code and AI agents. CRO, copywriting, SEO, analytics, and growth engineering.
JavaScript agent-skillsai-agentsai-seoclaudeclaude-codeclaude-code-pluginclaude-skillscodexcontent-marketingconversion-rate-optimizationcopywritingcursoremail-marketinggenerative-engine-optimizationgrowth-marketingmarketingmarketing-automationsaas-marketingseoskill-md
feat: add feature-demo skill
Leon Klepfish37cb655f4017
diff --git a/.claude-plugin/marketplace.json b/.claude-plugin/marketplace.jsonindex 57c13c7..888115e 100644--- a/.claude-plugin/marketplace.json+++ b/.claude-plugin/marketplace.json@@ -6,13 +6,13 @@},"metadata": {"description": "Marketing skills for AI agents — conversion optimization, copywriting, SEO, paid ads, and growth",- "version": "2.3.0",+ "version": "2.4.0","repository": "https://github.com/coreyhaines31/marketingskills"},"plugins": [{"name": "marketing-skills",- "description": "43 marketing skills for technical marketers and founders: CRO, copywriting, cold email, prospecting, SEO, AI SEO, paid ads, SMS, ad creative, video production, image generation, co-marketing, churn prevention, pricing, referrals, revenue operations, sales enablement, customer research, site architecture, comprehensive AARRR-structured marketing plans, and more",+ "description": "44 marketing skills for technical marketers and founders: CRO, copywriting, cold email, prospecting, SEO, AI SEO, paid ads, SMS, ad creative, video production, image generation, co-marketing, churn prevention, pricing, referrals, revenue operations, sales enablement, customer research, site architecture, comprehensive AARRR-structured marketing plans, and more","source": "./"}]diff --git a/.claude-plugin/plugin.json b/.claude-plugin/plugin.jsonindex 19a880d..d54e390 100644--- a/.claude-plugin/plugin.json+++ b/.claude-plugin/plugin.json@@ -1,7 +1,7 @@{"name": "marketing-skills","description": "Marketing skills for AI agents — conversion optimization, copywriting, SEO, paid ads, ad creative, and growth",- "version": "2.3.0",+ "version": "2.4.0","author": {"name": "Corey Haines"},diff --git a/README.md b/README.mdindex 2628b64..0627c4b 100644--- a/README.md+++ b/README.md@@ -75,6 +75,7 @@ See each skill's **Related Skills** section for the full dependency map.| [customer-research](skills/customer-research/) | When the user wants to conduct, analyze, or synthesize customer research. Use when the user mentions "customer... || [directory-submissions](skills/directory-submissions/) | When the user wants to submit their product to startup, SaaS, AI, agent, MCP, no-code, or review directories for... || [emails](skills/emails/) | When the user wants to create or optimize an email sequence, drip campaign, automated email flow, or lifecycle email... |+| [feature-demo](skills/feature-demo/) | Record a Playwright-driven demo video of a web app feature (signup, onboarding, a settings flow, a dashboard... || [free-tools](skills/free-tools/) | When the user wants to plan, evaluate, or build a free tool for marketing purposes — lead generation, SEO value, or... || [image](skills/image/) | When the user wants to create, generate, edit, or optimize images for marketing — blog heroes, social graphics, product... || [launch](skills/launch/) | When the user wants to plan a product launch, feature announcement, or release strategy. Also use when the user... |diff --git a/VERSIONS.md b/VERSIONS.mdindex 42bd4e7..a0249ed 100644--- a/VERSIONS.md+++ b/VERSIONS.md@@ -22,6 +22,7 @@ Current versions of all skills. Agents can compare against local versions to che| customer-research | 2.0.0 | 2026-05-05 || directory-submissions | 2.0.0 | 2026-05-05 || emails | 2.0.0 | 2026-05-05 |+| feature-demo | 1.0.0 | 2026-06-04 || free-tools | 2.0.0 | 2026-05-05 || image | 2.0.1 | 2026-05-18 || launch | 2.0.0 | 2026-05-05 |@@ -50,6 +51,11 @@ Current versions of all skills. Agents can compare against local versions to che## Recent Changes+### 2.4.0 (2026-06-04)++- Added `feature-demo` skill for recording Playwright-driven demo videos of an in-app flow (signup, onboarding, settings, dashboard interactions) — branded title card, on-screen subtitles, an animated mouse cursor, and optional ElevenLabs TTS narration, delivered as an MP4. Ships a recorder template (copy in, then edit the BRAND / TITLE_CARD / FEATURE STEPS blocks) and a generic narrator that muxes voiceover onto the silent capture, plus references for scene-timing modes (`before` / `during` / `after`) and common local-app recording gotchas (HTTP cookie flags, CSP, demo-state reset). For AI-generated/marketing video, see `video`.+- Total skills: 44.+### 2.3.0 (2026-05-27)- Added `marketing-plan` skill — comprehensive AARRR-structured marketing plan generator. Produces a 13-section Notion-paste-ready plan document (executive summary, strategic frame, current state, AARRR breakdown, 90-day roadmap, 12-month outlook with funding-stage capability unlocks, marketing operations stack mapping skills + MCPs to AARRR stages, tactical idea bank cross-referencing all 139 `marketing-ideas` to AARRR + client-specific status, measurement framework, RACI, open decisions). Customized for current budget, team, stage, and tooling stack. Three-phase workflow: INIT (research + intake), REVIEW (section-by-section walkthrough), FINALIZE (compile + verify + optional publish to shared repo). References include methodology, plan-template, aarrr-framework, current-state-rubric (self-contained 17-section scoring rubric), ops-stack-mapping, idea-cross-reference (139-idea AARRR mapping), funding-stage-unlocks, measurement-framework, client-types (variations by B2B SaaS / D2C / hardware-hybrid / marketplace / dev tool / clinical / commerce), example-quietude (anonymized canonical reference plan, based on a real fCMO engagement with names/identifying details changed), budget-planning (two scientific methods for setting the marketing budget — Revenue-Based 5–40% of ARR, and Goal-Based formula reverse-engineered from the revenue target; plus blended CAC calculation, the 10–20% experimental buffer rule, the 3-3-2-2-2 VC growth path, and the forecasting reality check), growth-patterns (the real shape of SaaS growth — $0–10K / $10K–100K / $100K–1M phases with binding constraints, linear vs step-function vs S-curve patterns, and Channel × Product × Market layering), and team-and-agency-model (the strategy-in-house / execution-outsourced principle, three core functions Growth/Product/Content, π-shaped marketer framework, title progression Manager → Lead → Director → VP → Chief, agency selection framework, and the three-stage scaling model Early/Growth/Scale). Budget, growth-pattern, and team frameworks drawn from *Founding Marketing* by Corey Haines.diff --git a/skills/feature-demo/SKILL.md b/skills/feature-demo/SKILL.mdnew file mode 100644index 0000000..f6a9ebf--- /dev/null+++ b/skills/feature-demo/SKILL.md@@ -0,0 +1,292 @@+---+name: feature-demo+description: Record a Playwright-driven demo video of a web app feature (signup, onboarding, a settings flow, a dashboard interaction, etc.) with on-screen subtitles and optional ElevenLabs TTS narration, then deliver the MP4 to the user. Use when the user asks to "record a demo", "make a walkthrough", "screen-record this flow", "make a feature video", "show me a video of X", or wants a narrated screencast of any in-app flow. NOT for marketing/AI-generated video (use the `video` skill for HeyGen / Remotion / etc.).+metadata:+ version: 1.0.0+---++# Feature demo++You are an expert at recording in-app demo videos. Your goal is to+walk a user's web app through a feature flow in headless Chromium and+deliver a polished MP4 — branded title card, scene subtitles, real+mouse cursor, optional ElevenLabs voiceover — using the recorder+template and narrator that ship with this skill.++The skill ships two scripts:++- **`scripts/recorder.template.mjs`** — copy into `scripts/` and edit+ the BRAND, TITLE_CARD, and FEATURE STEPS sections to drive the flow.+- **`scripts/narrate.mjs`** — generic; takes the silent recording ++ the timings sidecar and produces a narrated MP4. Reuse as-is.++## Before Starting++**Check for product marketing context first:**+If `.agents/product-marketing-context.md` exists (or+`.claude/product-marketing-context.md` in older setups), read it+before asking questions. Use it to pre-fill the `BRAND` block (name,+demo domain, accent / background colors that match the product), to+inform the title-card copy + intro voiceover tone, and — critically —+to ground the demo in **who the audience is and what the product+does**. A demo that doesn't know its viewer falls flat: captions land+generic, the intro is hand-wavy, and the scene selection misses the+"aha" moment for that audience. Only ask the user about information+that isn't already covered or that's specific to this particular video.++Gather this context (ask if not provided):++### 1. Who is the video for, and what does the product do?++Both — together. Examples:++- *Audience*: prospects on the pricing page, existing customers+ rolling out a new feature, sales team for outbound demos,+ developers evaluating the API, support agents reviewing a flow,+ internal QA validating a release.+- *Product*: one or two sentences on what the app does and its core+ value proposition — the same shape as the product-marketing-context+ blurb if you have one.++Don't skip this question. It changes everything downstream: the+title card copy, the intro voiceover wording, scene captions+(jargon-light for prospects, feature-focused for existing customers,+implementation-detail for developers), even pacing (fast for sales+demos, deliberate for tutorials).++### 2. Which feature, and which scenes?++Get the entry URL (e.g. `/dashboard/settings/team`) and a one-line+summary of each scene the user wants to see. The scene list = the+on-screen subtitles, so write them as the captions you want narrated.++### 3. Narration?++Default to silent. If the user wants a voiceover, you'll need+`ELEVENLABS_API_KEY` in env (have them paste it in chat — do not+commit it). Confirm a voice — Bella (`EXAVITQu4vr4xnSDxMaL`) is the+default; Adam (`pNInz6obpgDQGcFmaJgB`) and Rachel+(`21m00Tcm4TlvDq8ikWAM`) are good alternates.++### 4. Auth state?++Does the demo need to start logged in? If so, plan to seed a user and+either use `page.context().addCookies()` or do a programmatic login at+the top of the recorder. Otherwise start at the public URL.++### 5. Brand defaults++If product-marketing context didn't supply them, ask for the values+that go in the recorder's `BRAND` block: app name (used as the+Chrome tab title + text wordmark fallback), demo domain (shown in+the fake URL bar), title-card background + accent colors, and+optionally a relative path to a logo SVG.++## Workflow++### 1. Bring the local app up++The recorder hits `BASE_URL` (default `http://127.0.0.1:8000`). Get+your local app running and reachable there before recording. Any+stack works — Laravel, Rails, Django, Next.js, etc. — the recorder+only needs HTTP + the page to render in headless Chromium.++Headline things that bite Playwright recordings on HTTP localhost+(see [references/local-app-gotchas.md](references/local-app-gotchas.md)+for the full list):++- **`Secure; SameSite=None` cookies are rejected** by Chromium over+ plain HTTP — sessions don't stick. Flip to `SameSite=Lax` (or+ serve HTTPS) for the recording run.+- **Strict CSP blocks the overlay's inline styles.** The recorder+ already sets `bypassCSP: true` on the context. Don't strip that.+- **SPA boot failures yield a blank video.** If the page renders+ blank in a real browser (empty env var crashing a constructor,+ etc.) the recorder captures the blank state silently.++### 2. Install Playwright + ffmpeg if missing++```bash+npx playwright install chromium --with-deps # ~100MB+which ffmpeg || sudo apt-get install -y --no-install-recommends ffmpeg+```++### 3. Write the recorder++Copy the template:++```bash+cp .agents/skills/feature-demo/scripts/recorder.template.mjs scripts/record-<feature>.mjs+```++**Edit the `BRAND` block** near the top of the file:++```js+const BRAND = {+ name: 'YourApp', // chrome tab title + text-wordmark fallback+ demoDomain: 'app.example.com', // shown in the fake URL bar+ logoPath: 'public/img/logo.svg', // optional; searched up from script+ backgroundColor: '#0f172a', // title-card bg+ accentColor: '#38bdf8', // title-card underline + tab favicon+};+```++`logoPath` is resolved by walking up from the recorder's location, so+a relative path like `public/img/logo.svg` works from anywhere under+the project. Leave it `undefined` to fall back to a text wordmark of+`BRAND.name`.++**Edit the `TITLE_CARD` block** with the video's title/subtitle/intro:++```js+const TITLE_CARD = {+ title: 'Get Started',+ subtitle: 'Sign up and create your first project',+ intro: "In this video we'll walk through signing up and creating your first project.",+};+```++**Edit the FEATURE STEPS section.** Pattern per scene:++```js+await step(+ 'short internal label', // logged to console+ 'On-screen + narrated caption.', // shown in subtitle bar AND read by TTS+ async () => {+ // Playwright actions: fill, click, waitForURL, etc.+ },+ { mode: 'before' }, // default — narrate first, then act+);+```++**Pick a `mode` per step** — this is what keeps audio + visual aligned.+Full decision matrix + examples in+[references/step-modes.md](references/step-modes.md); the short version:++- **`before`** (default) — narration plays in full, then `fn()` runs.+ Use for **transition steps** (click + navigate). Prevents the+ "speaker still describing the old page while we're on the new one"+ drift.+- **`during`** — narration and `fn()` run in parallel. Use for+ **in-place visible actions** like filling a form.+- **`after`** — `fn()` runs, then narration. Rare.++Other notes:++- **Reset backend state at the top of the script** if the demo+ depends on a known user/account. Re-runs accumulate side effects+ (extra rows, deleted entities, etc.) that confuse selectors. The+ template has a commented `resetDemoState` block — shell out to+ whatever tool clears the rows your demo touches (`php artisan+ tinker`, `rails runner`, a SQL one-liner, an admin API call).+ Demos that use a random email per run don't need this.+- **Always use `clickWithCursor(locator)` and+ `fillWithCursor(locator, val)`** inside step `fn()` bodies instead+ of `locator.click()` / `locator.fill()`. Playwright drives DOM+ events directly with no real cursor; the helpers animate the+ injected fake cursor to the target (~500 ms slide) and fire a+ click-ripple effect before the action so the viewer can see what's+ being clicked.+- Update `TOTAL_STEPS` at the top to match the count of `step()`+ calls + the opener — the on-screen "STEP N / TOTAL" badge uses it.+- Captions of ~50–80 chars are the sweet spot — long enough to be+ meaningful, short enough that `before` mode doesn't pause the demo+ too long.+- When `ELEVENLABS_API_KEY` is set, the recorder pre-generates each+ caption's TTS clip and uses its actual ffprobe-measured duration as+ the wait — clips are cached under `OUT_DIR/narration/step-N.mp3`,+ so re-records skip the API. Without the key, falls back to ~12+ chars/sec.+- Failures dump a screenshot to `<OUT_DIR>/fail-<label>.png` for+ triage.++### 4. Record++```bash+node scripts/record-<feature>.mjs+```++Outputs three things to `/tmp/playwright-recording/` (override with+`OUT_DIR`):++- `<hash>.webm` — the silent recording at viewport size (default+ 1280×800)+- `subtitle-timings.json` — `{ titleCard: {...}, subtitles: [...] }`,+ including the brand fields the narrator needs+- `browser-frame.png` — a macOS-Chrome chrome bar (tab strip ++ toolbar) rendered once via Playwright; the narrator stacks it on+ top of the recorded video with ffmpeg `vstack` so the demo reads+ as a real browser. The URL text is baked in once at render time as+ `DEMO_DOMAIN + entry_path`.++**Title card** — the narrator renders `TITLE_CARD` as a full-bleed+1280×888 PNG (logo or wordmark on `BRAND.backgroundColor`, with a+`BRAND.accentColor` underline), prepends it to the front of the video+as a held frame, and plays the `intro` line over it with the same+TTS voice. The first frame of the muxed MP4 is the title card, so+it's also the preview thumbnail.++If you only want the silent video with subtitles + chrome (no+audio), a one-liner does it:++```bash+ffmpeg -y -i /tmp/playwright-recording/*.webm \+ -i /tmp/playwright-recording/browser-frame.png \+ -filter_complex "[1:v][0:v]vstack=inputs=2" -c:v libx264 -crf 23 \+ out.mp4+```++### 5. Add narration (optional)++```bash+ELEVENLABS_API_KEY='sk_...' \+ node .agents/skills/feature-demo/scripts/narrate.mjs \+ /tmp/playwright-recording/*.webm \+ /tmp/playwright-recording/<feature>-narrated.mp4+```++The narrator:++- POSTs each caption to ElevenLabs (default voice Bella, model+ `eleven_v3` — the most expressive model; switch to+ `eleven_multilingual_v2` via `ELEVENLABS_MODEL_ID` if v3 sounds off,+ it's the marketed voiceover model)+- Caches MP3 clips under `<OUT_DIR>/narration/` so re-runs skip the+ API+- Auto-pushes back any clip that would overlap the previous one so+ the voiceover never doubles up+- Trims the `about:blank` + first-paint period off the front of the+ recording before muxing+- Pads the video tail with `tpad=clone` if the narration runs past+ the visual so playback stays in sync++Override the voice with `ELEVENLABS_VOICE_ID=...` or the model with+`ELEVENLABS_MODEL_ID=...`.++### 6. Deliver++Hand the finished MP4 back to the user with a one-line summary of what+the video shows. Use whatever file-delivery mechanism your agent+supports — attach or send the file if you can; otherwise give the user+its absolute path:++```+/tmp/playwright-recording/<feature>-narrated.mp4+```++### 7. Clean up before committing++If you changed any per-runtime config files (cookie flags, env+overrides, etc.) to make Playwright happy, **revert those before+committing** so the diff stays focused on the recorder script. Then+commit + push + open a PR per your standard workflow.++## What the skill's files are for++| Path | Purpose |+|---|---|+| `scripts/recorder.template.mjs` | Skeleton recorder; copy into `scripts/` per feature |+| `scripts/narrate.mjs` | Generic narrator; run directly, no edits needed |+| `references/step-modes.md` | Decision matrix + examples for `before` / `during` / `after` |+| `references/local-app-gotchas.md` | Cross-cutting issues on HTTP localhost (cookies, CSP, state) |+| `evals/evals.json` | Eval prompts that exercise the skill's expected behaviors |diff --git a/skills/feature-demo/evals/evals.json b/skills/feature-demo/evals/evals.jsonnew file mode 100644index 0000000..9ceb1e8--- /dev/null+++ b/skills/feature-demo/evals/evals.json@@ -0,0 +1,84 @@+{+ "skill_name": "feature-demo",+ "evals": [+ {+ "id": 1,+ "prompt": "Make a demo video of our signup flow.",+ "expected_output": "Should ask clarifying questions before writing code: which entry URL, list of scenes/captions, whether the demo needs narration (and if so prompt for ELEVENLABS_API_KEY), and what auth state to start in. Should NOT start coding the recorder until those answers are in. Should mention that the recorder is created by copying scripts/recorder.template.mjs to scripts/record-<feature>.mjs and editing the BRAND, TITLE_CARD, and FEATURE STEPS sections.",+ "assertions": [+ "Asks about the entry URL / feature being recorded",+ "Asks for the per-scene caption list before scaffolding",+ "Asks about narration (defaults to silent)",+ "Asks about auth state (logged in vs. anonymous)",+ "References the recorder template at scripts/recorder.template.mjs",+ "Does not start writing a recorder script until clarifications are answered"+ ],+ "files": []+ },+ {+ "id": 2,+ "prompt": "Record a tutorial showing how to add a team member, with voiceover narration. The brand is 'YourApp', dark navy bg, lime green accent. Logo at public/img/logo.svg.",+ "expected_output": "Should scaffold the recorder by copying scripts/recorder.template.mjs into scripts/. Should fill the BRAND block with name='YourApp', backgroundColor=<dark navy hex>, accentColor=<lime green hex>, logoPath='public/img/logo.svg'. Should ask for ELEVENLABS_API_KEY (or read it from env). Should set TITLE_CARD to a sensible title/subtitle/intro for the tutorial. Should pick mode='before' for transition-style clicks and mode='during' for in-place actions like filling the email field. Should use clickWithCursor / fillWithCursor in step fn bodies.",+ "assertions": [+ "Copies the recorder template into scripts/",+ "Fills the BRAND block with the user-supplied values",+ "Sets logoPath to public/img/logo.svg",+ "Asks for or uses ELEVENLABS_API_KEY",+ "Writes a TITLE_CARD with title/subtitle/intro",+ "Picks mode='before' for navigation clicks",+ "Picks mode='during' for form-fill scenes",+ "Uses clickWithCursor / fillWithCursor helpers (not raw locator.click / locator.fill)"+ ],+ "files": []+ },+ {+ "id": 3,+ "prompt": "Just record a quick silent demo of /pricing — no narration needed.",+ "expected_output": "Should still scaffold the recorder (BRAND, captions for the subtitle bar) but should NOT require ELEVENLABS_API_KEY. After running the recorder, should suggest the one-liner ffmpeg invocation that stacks the chrome PNG on the silent webm without involving narrate.mjs. The TITLE_CARD block can be left out or set with a short title; the title card only renders when intro narration is configured.",+ "assertions": [+ "Does not require / ask for ELEVENLABS_API_KEY",+ "Captions are still written for each scene (subtitle bar still appears)",+ "Suggests the silent ffmpeg one-liner from SKILL.md instead of narrate.mjs",+ "Does not call narrate.mjs in the final delivery"+ ],+ "files": []+ },+ {+ "id": 4,+ "prompt": "The narration is finishing a sentence about the previous page while the demo has already moved on to the next page. How do I fix this?",+ "expected_output": "Should diagnose this as scene-mode misalignment — the navigation click is firing before the narration finishes, leaving the speaker describing a page the viewer can no longer see. Should recommend changing the affected step's mode to 'before' so narration plays in full while the current page is visible, then fn() runs (and the transition happens silently between scenes). Should reference references/step-modes.md for the full decision matrix.",+ "assertions": [+ "Identifies the cause as a step-mode issue",+ "Recommends switching to mode='before' for the transition step",+ "Explains how mode='before' changes the timing (narration first, then fn())",+ "References step-modes.md or the mode picker in SKILL.md"+ ],+ "files": []+ },+ {+ "id": 5,+ "prompt": "When I re-run this recorder, the demo user already has the AI Call step from the last run. My click is landing on the existing step card instead of the modal option.",+ "expected_output": "Should diagnose this as DB state accumulating between runs and a selector ambiguity (':has-text' matching both the existing card and the modal option). Should recommend adding a resetDemoState() block at the top of the recorder that wipes the rows the demo creates (using spawnSync + the user's stack's CLI — php artisan tinker, rails runner, etc.). Should also recommend tightening the selector to getByRole('button', { name: 'AI Call', exact: true }) so the modal option matches uniquely.",+ "assertions": [+ "Diagnoses both DB state accumulation AND selector ambiguity",+ "Recommends adding a resetDemoState() block before recording starts",+ "References the commented resetDemoState example in the template",+ "Suggests tightening the selector with exact: true or a more specific locator chain",+ "Notes that spawnSync should use array-form args so the shell doesn't expand $vars"+ ],+ "files": []+ },+ {+ "id": 6,+ "prompt": "The video starts with a blank screen for about a second before the page appears.",+ "expected_output": "Should explain that Playwright video recording starts at context.newPage() while the page is still about:blank, and that the narrator already trims this by anchoring the trim to (firstSubtitleOffset - 150ms). If blank still leaks through, the page isn't fully rendered by the time subtitle() is called — fix is to wait for a real selector + small settle (e.g. 500ms) AFTER navigation BEFORE calling subtitle() for the first time. The opener block in the template shows this pattern.",+ "assertions": [+ "Explains the about:blank → first-paint → first-subtitle timing",+ "Notes the narrator already trims based on first-subtitle offset minus pre-roll",+ "Recommends a waitForSelector + small waitForTimeout after page.goto in the opener",+ "References the opener pattern in the recorder template"+ ],+ "files": []+ }+ ]+}diff --git a/skills/feature-demo/references/local-app-gotchas.md b/skills/feature-demo/references/local-app-gotchas.mdnew file mode 100644index 0000000..b7178f3--- /dev/null+++ b/skills/feature-demo/references/local-app-gotchas.md@@ -0,0 +1,74 @@+# Local-App Gotchas++The recorder hits `BASE_URL` (default `http://127.0.0.1:8000`) and+just needs the page to render in headless Chromium. Any stack works+— Laravel, Rails, Django, Next.js, etc. But a few cross-cutting+issues bite Playwright recordings on plain HTTP localhost.++## `Secure; SameSite=None` cookies are rejected++Chromium refuses to set cookies with `Secure` over plain HTTP. If+your session cookie is set with `Secure; SameSite=None`, the user+never stays logged in — every navigation is anonymous and the demo+bounces back to the login page. Two fixes:++- **Flip to `SameSite=Lax`** for the recording run (does not require+ Secure). Often just an `.env` flag or a one-line config tweak.+- **Or serve HTTPS** with a self-signed cert and pass+ `ignoreHTTPSErrors: true` in the Playwright context options+ (already on by default in the template).++## Strict CSP blocks the overlay++Pages that ship `Content-Security-Policy: style-src 'self'` (no+`unsafe-inline`) will block the subtitle bar + cursor overlay+because they're set via inline `style="..."` attributes. The+recorder template already sets `bypassCSP: true` on the Playwright+context to disable enforcement during the recording. **Don't strip+that.**++## SPA crashes on boot leave a blank video++If a required env var is empty and the SPA's bootstrap throws (e.g.+`new Pusher('')` because `VITE_PUSHER_APP_KEY` isn't set, an+analytics constructor that asserts on a missing token, etc.), the+page renders blank or partially. The recorder captures the blank+frames silently. Verify the page renders in a real browser before+recording.++The narrator trims the first frames anyway (anchored to the first+subtitle's offset), but it can only trim a few hundred ms before+hitting the first scene — it can't recover a permanently-broken+page.++## Pre-recording state accumulates across runs++If the demo depends on a known user/account, multiple runs leave+side-effect rows behind (extra steps in a sequence, extra leads,+etc.). Those then make `:has-text("X")` selectors ambiguous —+matching the new modal option AND the already-existing card from a+prior run.++Use a `resetDemoState()` block at the top of the recorder to wipe+just the rows your demo touches. Shell out via `spawnSync` (array+form so the shell doesn't expand `$vars` in the snippet) and run+your stack's appropriate tool — `php artisan tinker --execute`,+`bundle exec rails runner`, a SQL one-liner, an admin API call.++The recorder template has a commented Laravel/Tinker example you+can adapt.++## Production-pointing env vars in cloud sessions++Some session setups (e.g. agents that ship a DB-query skill) export+`DB_HOST` / `DB_PASSWORD` / `DB_SOCKET` pointing at **production**+RDS. Any `artisan` / `rails` / `psql` command that inherits the+shell env will silently hit prod. Always:++- Unset / override those vars when running schema or seed commands+- Use a local-only override at the start of your reset script++The recorder template doesn't import process.env wholesale; if you+adapt the Laravel example, the `env` object passed to `spawnSync`+should explicitly set `DB_HOST=127.0.0.1` (or wherever your local+DB lives) instead of forwarding `process.env`.diff --git a/skills/feature-demo/references/step-modes.md b/skills/feature-demo/references/step-modes.mdnew file mode 100644index 0000000..8eb3bf0--- /dev/null+++ b/skills/feature-demo/references/step-modes.md@@ -0,0 +1,87 @@+# Step Modes++Each `step(...)` call in the recorder takes an optional `{ mode }`+that controls the order of narration vs. action. Picking the right+mode per scene is what keeps audio and visuals aligned.++## The three modes++### `before` (default)++```+[ subtitle appears + narration plays ] → [ fn() runs ]+```++Use for **transition steps** — scenes where `fn()` ends with a click+that navigates to a new page. Without `before`, the click happens+early and the speaker keeps describing the old page while the viewer+is already on the new one ("one scene off").++Example:++```js+await step(+ 'submit form',+ 'Submitting creates the account and drops you into onboarding.',+ async () => {+ await Promise.all([+ page.waitForURL(/\/onboarding\//),+ clickWithCursor(page.getByRole('button', { name: /create account/i })),+ ]);+ },+ // mode: 'before' is the default+);+```++### `during`++```+[ subtitle appears ] ─┬─ narration plays ──┐+ └─ fn() runs ────────┘ → both must finish+```++Use for **in-place visible actions** — filling a form, scrubbing a+slider, dragging a card. The viewer should watch the action play out+under the narration.++```js+await step(+ 'fill register form',+ 'Filling in the company, name, email, and password.',+ async () => {+ await fillWithCursor(page.locator('input[name="company_name"]'), 'Acme');+ await fillWithCursor(page.locator('input[name="email"]'), '[email protected]');+ // ...+ },+ { mode: 'during' },+);+```++### `after`++```+[ fn() runs ] → [ subtitle appears + narration plays ]+```++Use to **describe a state the action just produced**. Rare — usually+`before` on the next scene is cleaner because each scene's caption+then describes the page that's actually visible during it.++## Picking a mode in practice++| Scene shape | Mode |+|---|---|+| Click a button → page navigates | `before` |+| Fill a form / type in a field | `during` |+| Skip / dismiss → page navigates | `before` |+| Hover / open a menu, no nav | `during` |+| Land on a final state (dashboard, success) | `during` (just narrate the now-visible state) |+| Click that triggers a modal you want to describe | `before` (so the click finishes during narration and the modal is visible by the time the speaker reaches the relevant phrase) |++## Why the modes exist++Narration durations vary widely (3-7 s for typical scenes). Actions+also vary (form-fill ~2 s, click+nav ~1.5 s). With a fixed mode the+two will drift apart on long scenes. `before` keeps the speaker's+words tied to the page the viewer sees; `during` lets short actions+play under the narration so dead air doesn't open up.diff --git a/skills/feature-demo/scripts/narrate.mjs b/skills/feature-demo/scripts/narrate.mjsnew file mode 100644index 0000000..fab1e4d--- /dev/null+++ b/skills/feature-demo/scripts/narrate.mjs@@ -0,0 +1,383 @@+// Narrates a recording produced by the feature-demo recorder+// (scripts/record-<feature>.mjs).+//+// Reads subtitle text + offsets from a timings JSON sidecar, fetches MP3+// narration for each subtitle from the ElevenLabs API, and muxes the audio+// onto the silent WebM at the matching timestamps with ffmpeg.+//+// Prereqs: ffmpeg in $PATH, ELEVENLABS_API_KEY set in env.+//+// Run: node .agents/skills/feature-demo/scripts/narrate.mjs <video.webm> [out.mp4]+// Env: ELEVENLABS_API_KEY (required)+// ELEVENLABS_VOICE_ID (default Bella: EXAVITQu4vr4xnSDxMaL)+// ELEVENLABS_MODEL_ID (default eleven_v3 — the most expressive model;+// switch to eleven_multilingual_v2 if v3 sounds+// off, it's the marketed voiceover model)+// TIMINGS_PATH (default <video-dir>/subtitle-timings.json)++import { mkdirSync, readFileSync, writeFileSync, existsSync } from 'fs';+import path from 'path';+import { fileURLToPath } from 'url';+import { spawn } from 'child_process';+import { chromium } from 'playwright';++// Walk up from the script location looking for a file under the project+// (e.g. public/img/...). This script ships in two places — scripts/ and+// .agents/skills/feature-demo/ — so a fixed relative path would only work+// for one of them, and an absolute path breaks on every machine but mine.+const findUpward = (relPath) => {+ let dir = path.dirname(fileURLToPath(import.meta.url));+ for (let i = 0; i < 8; i++) {+ const candidate = path.join(dir, relPath);+ if (existsSync(candidate)) return candidate;+ const parent = path.dirname(dir);+ if (parent === dir) break;+ dir = parent;+ }+ return null;+};++const videoPath = process.argv[2];+if (!videoPath) {+ console.error('usage: node .agents/skills/feature-demo/scripts/narrate.mjs <video.webm> [out.mp4]');+ process.exit(2);+}+const outPath = process.argv[3] || videoPath.replace(/\.(webm|mp4)$/i, '') + '-narrated.mp4';+const apiKey = process.env.ELEVENLABS_API_KEY;+if (!apiKey) {+ console.error('ELEVENLABS_API_KEY is required');+ process.exit(2);+}+const voiceId = process.env.ELEVENLABS_VOICE_ID || 'EXAVITQu4vr4xnSDxMaL';+const modelId = process.env.ELEVENLABS_MODEL_ID || 'eleven_v3';+const timingsPath = process.env.TIMINGS_PATH || path.join(path.dirname(videoPath), 'subtitle-timings.json');++if (!existsSync(videoPath)) {+ console.error(`video not found: ${videoPath}`);+ process.exit(2);+}+if (!existsSync(timingsPath)) {+ console.error(`timings not found: ${timingsPath}`);+ process.exit(2);+}++const timingsJson = JSON.parse(readFileSync(timingsPath, 'utf8'));+const { subtitles, titleCard } = timingsJson;+if (!subtitles?.length) {+ console.error('no subtitles in timings file');+ process.exit(2);+}++const workDir = path.join(path.dirname(videoPath), 'narration');+mkdirSync(workDir, { recursive: true });++const run = (cmd, args, { capture = false } = {}) =>+ new Promise((resolve, reject) => {+ const p = spawn(cmd, args, { stdio: capture ? ['ignore', 'pipe', 'inherit'] : 'inherit' });+ const chunks = [];+ if (capture) p.stdout.on('data', (c) => chunks.push(c));+ p.on('error', reject);+ p.on('close', (code) => (code === 0 ? resolve(Buffer.concat(chunks).toString('utf8')) : reject(new Error(`${cmd} exited ${code}`))));+ });++const probeDurationMs = async (file) => {+ const out = await run('ffprobe', ['-v', 'error', '-show_entries', 'format=duration', '-of', 'default=nw=1:nk=1', file], { capture: true });+ return Math.round(parseFloat(out.trim()) * 1000);+};++const fetchTts = async (text) => {+ const res = await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${voiceId}`, {+ method: 'POST',+ headers: {+ 'xi-api-key': apiKey,+ 'Content-Type': 'application/json',+ Accept: 'audio/mpeg',+ },+ body: JSON.stringify({+ text,+ model_id: modelId,+ voice_settings: { stability: 0.5, similarity_boost: 0.75, style: 0.0, use_speaker_boost: true },+ }),+ });+ if (!res.ok) {+ const body = await res.text();+ throw new Error(`ElevenLabs ${res.status}: ${body.slice(0, 200)}`);+ }+ return Buffer.from(await res.arrayBuffer());+};++// Renders the title-card PNG used as the first frame of the video.+// Reuses the Playwright already needed by the recorder pipeline.+const renderTitleCardPng = async (outPath, {+ width,+ height,+ title,+ subtitle,+ brandName,+ logoPath,+ backgroundColor = '#0f172a',+ accentColor = '#38bdf8',+}) => {+ // Project logo: read from logoPath (relative paths are resolved via+ // findUpward from the script location). Falls back to a text wordmark+ // built from brandName when no logo is configured or the file is missing.+ let logoMarkup;+ let resolvedLogo = null;+ if (logoPath) {+ resolvedLogo = path.isAbsolute(logoPath) ? logoPath : findUpward(logoPath);+ }+ if (resolvedLogo && existsSync(resolvedLogo)) {+ const svg = readFileSync(resolvedLogo, 'utf8')+ .replace(/<\?xml[^>]*\?>/, '')+ .replace(/<!--[\s\S]*?-->/g, '');+ logoMarkup = `<div class="logo">${svg}</div>`;+ } else {+ if (logoPath) {+ console.warn(`⚠ logoPath "${logoPath}" not found from any parent of script — falling back to text wordmark`);+ }+ logoMarkup = brandName+ ? `<div class="wordmark">${brandName}</div>`+ : '';+ }+ const html = `<!DOCTYPE html><html><head><meta charset="utf-8"><style>+ html,body{margin:0;padding:0;background:transparent}+ .card{+ box-sizing:border-box;width:${width}px;height:${height}px;+ background:${backgroundColor};+ display:flex;flex-direction:column;align-items:center;justify-content:center;+ color:#ffffff;+ font:400 22px/1.4 -apple-system,BlinkMacSystemFont,"Segoe UI",Roboto,sans-serif;+ position:relative;+ }+ .logo{width:340px;height:auto;display:block;margin-bottom:48px}+ .wordmark{color:#ffffff;font-size:64px;font-weight:700;letter-spacing:-0.02em;margin-bottom:48px}+ .title{font-size:60px;font-weight:700;line-height:1.1;text-align:center;letter-spacing:-0.02em;margin:0 0 18px 0;max-width:980px;padding:0 40px}+ .subtitle{font-size:24px;opacity:0.7;text-align:center;font-weight:400;letter-spacing:0.02em}+ .accent{position:absolute;left:50%;bottom:60px;transform:translateX(-50%);width:64px;height:3px;background:${accentColor};border-radius:2px}+ </style></head><body>+ <div class="card">+ ${logoMarkup}+ <div class="title">${title}</div>+ <div class="subtitle">${subtitle}</div>+ <div class="accent"></div>+ </div>+ </body></html>`;+ let browser;+ let ctx;+ try {+ browser = await chromium.launch({ headless: true });+ ctx = await browser.newContext({ viewport: { width, height } });+ const page = await ctx.newPage();+ await page.setContent(html, { waitUntil: 'load' });+ await page.screenshot({ path: outPath, clip: { x: 0, y: 0, width, height } });+ } finally {+ if (ctx) await ctx.close().catch(() => {});+ if (browser) await browser.close().catch(() => {});+ }+};++// Set up title card metadata (and pre-fetch intro narration) early.+// We don't shift subtitle offsets here — that happens AFTER the trim+// calculation below, so the trim only sees the ORIGINAL recording-time+// offsets, not the title-shifted ones.+// Probe the chrome PNG up-front (if present) so the title card can be+// rendered at the FULL output height — chrome doesn't overlay the+// title card, only the recorded scenes.+const framePath = path.join(path.dirname(videoPath), 'browser-frame.png');+const hasFrame = existsSync(framePath);+let chromeHeightPx = 0;+if (hasFrame) {+ const out = await run('ffprobe', ['-v', 'error', '-select_streams', 'v:0', '-show_entries', 'stream=height', '-of', 'default=nw=1:nk=1', framePath], { capture: true });+ chromeHeightPx = parseInt(out.trim(), 10) || 0;+ console.log(`🖼 Chrome frame ${framePath} (${chromeHeightPx}px tall)`);+}++let titleCardInfo = null;+if (titleCard?.title && titleCard?.intro) {+ const introPath = path.join(workDir, 'intro.mp3');+ if (!existsSync(introPath)) {+ console.log(`🎙 Generating intro narration: "${titleCard.intro.slice(0, 60)}…"`);+ writeFileSync(introPath, await fetchTts(titleCard.intro));+ } else {+ console.log(`🎙 Cached intro narration: ${introPath}`);+ }+ const introMs = await probeDurationMs(introPath);+ const TITLE_TAIL_MS = 700; // hold title slightly after intro audio ends+ const titleHoldMs = introMs + TITLE_TAIL_MS;++ const titlePngPath = path.join(workDir, 'title-card.png');+ const titleHeight = 800 + chromeHeightPx; // full output, no chrome overlay+ console.log(`🎬 Rendering title card "${titleCard.title}" (${titleHoldMs}ms hold, 1280×${titleHeight})`);+ await renderTitleCardPng(titlePngPath, {+ width: 1280,+ height: titleHeight,+ title: titleCard.title,+ subtitle: titleCard.subtitle || '',+ brandName: titleCard.brandName,+ logoPath: titleCard.logoPath,+ backgroundColor: titleCard.backgroundColor,+ accentColor: titleCard.accentColor,+ });++ titleCardInfo = { introPath, introMs, titleHoldMs, titlePngPath };+}++console.log(`🎙 Generating ${subtitles.length} narration clips with voice ${voiceId}…`);+for (const sub of subtitles) {+ const clipPath = path.join(workDir, `step-${sub.step}.mp3`);+ if (!existsSync(clipPath)) {+ writeFileSync(clipPath, await fetchTts(sub.text));+ }+ sub.clipPath = clipPath;+ sub.durationMs = await probeDurationMs(clipPath);+ console.log(` step ${sub.step}: ${clipPath} (${sub.durationMs}ms)`);+}++// Trim the blank `about:blank` + first-paint period off the front of+// the silent video. Anchor the trim to the first subtitle's offset,+// keeping a small pre-roll so the page is visible for a moment before+// the caption appears. The recorder calls subtitle() right after+// waitForSelector returns, so the page is rendered just before the+// subtitle is set; ~150ms of pre-roll lands roughly at first paint.+const PRE_ROLL_MS = 150;+const trimStartMs = Math.max(0, subtitles[0].offsetMs - PRE_ROLL_MS);+if (trimStartMs > 0) {+ console.log(`✂️ Trimming ${trimStartMs}ms of blank screen off the start`);+ for (const sub of subtitles) {+ sub.offsetMs = Math.max(0, sub.offsetMs - trimStartMs);+ }+}++// Now shift every scene's audio offset by the title-card hold time, so+// the recorded video plays AFTER the title card in the final timeline.+if (titleCardInfo) {+ for (const sub of subtitles) {+ sub.offsetMs += titleCardInfo.titleHoldMs;+ }+}++// Push back any clip that would start while the previous one is still+// playing, so the narration never doubles up. This keeps the voiceover+// intelligible even if a caption is longer than its on-screen scene.+for (let i = 1; i < subtitles.length; i++) {+ const prev = subtitles[i - 1];+ const earliestStart = prev.offsetMs + prev.durationMs + 200;+ if (subtitles[i].offsetMs < earliestStart) {+ const slip = earliestStart - subtitles[i].offsetMs;+ console.log(` ⏩ pushing step ${subtitles[i].step} back ${slip}ms to avoid overlap`);+ subtitles[i].offsetMs = earliestStart;+ }+}++// Build the ffmpeg mix.+// - input ordering: [title-card-png (looped)?] silent-video [chrome-png?] [intro-mp3?] scene-mp3s...+// - filter chain stacks chrome on top of (title + main) and mixes+// intro narration + all scene narrations together.+const fullVideoDurationMs = await probeDurationMs(videoPath);+const videoDurationMs = fullVideoDurationMs - trimStartMs;+const titleHoldMs = titleCardInfo ? titleCardInfo.titleHoldMs : 0;+const totalVisibleMs = titleHoldMs + videoDurationMs;+const lastClipEndMs = Math.max(...subtitles.map((s) => s.offsetMs + (s.durationMs || 0)));+const padNeeded = lastClipEndMs > totalVisibleMs;+console.log(`🎬 Title hold=${titleHoldMs}ms, video=${videoDurationMs}ms (trimmed ${trimStartMs}ms), last narration ends at ${lastClipEndMs}ms${padNeeded ? ' — will pad main video tail' : ''}`);++const ffArgs = ['-y'];+let inputIdx = 0;+let titleVidIdx = -1, videoIdx, chromeIdx = -1, introIdx = -1;++if (titleCardInfo) {+ ffArgs.push('-loop', '1', '-framerate', '25', '-t', `${(titleHoldMs / 1000).toFixed(3)}`, '-i', titleCardInfo.titlePngPath);+ titleVidIdx = inputIdx++;+}+if (trimStartMs > 0) {+ // Input seek — fast and frame-accurate enough for trimming blank+ // frames; the filter chain sees a video that starts at t=0.+ ffArgs.push('-ss', `${(trimStartMs / 1000).toFixed(3)}`);+}+ffArgs.push('-i', videoPath);+videoIdx = inputIdx++;+if (hasFrame) {+ ffArgs.push('-i', framePath);+ chromeIdx = inputIdx++;+}+if (titleCardInfo) {+ ffArgs.push('-i', titleCardInfo.introPath);+ introIdx = inputIdx++;+}+const sceneIdxStart = inputIdx;+for (const sub of subtitles) {+ ffArgs.push('-i', sub.clipPath);+ inputIdx++;+}++const filterChunks = [];++// Main (recorded) video, padded if narration overruns+const mainPadSeconds = padNeeded+ ? ((lastClipEndMs + 500 - totalVisibleMs) / 1000).toFixed(3)+ : '0';+const padFilter = padNeeded+ ? `[${videoIdx}:v]tpad=stop_mode=clone:stop_duration=${mainPadSeconds},format=yuv420p,fps=25[mainVid]`+ : `[${videoIdx}:v]format=yuv420p,fps=25[mainVid]`;+filterChunks.push(padFilter);++// Stack chrome on top of the MAIN scene only — title card already+// fills the full output height and should NOT have chrome over it.+let sceneLabel = '[mainVid]';+if (hasFrame) {+ filterChunks.push(`[${chromeIdx}:v]scale=iw:ih[chrome]`);+ filterChunks.push(`[chrome][mainVid]vstack=inputs=2[sceneFull]`);+ sceneLabel = '[sceneFull]';+}++// Then concat the (full-bleed) title card with the (chrome+scene) main.+if (titleCardInfo) {+ filterChunks.push(`[${titleVidIdx}:v]format=yuv420p,fps=25[titleVid]`);+ filterChunks.push(`[titleVid]${sceneLabel}concat=n=2:v=1[vout]`);+} else {+ filterChunks.push(`${sceneLabel}null[vout]`);+}++// Audio: intro at t=0 (if title card), then each scene narration at its+// (already shifted) offset.+const audioLabels = [];+if (titleCardInfo) {+ filterChunks.push(`[${introIdx}:a]adelay=0|0,apad=pad_dur=0.3[introA]`);+ audioLabels.push('[introA]');+}+subtitles.forEach((sub, i) => {+ const idx = sceneIdxStart + i;+ filterChunks.push(`[${idx}:a]adelay=${sub.offsetMs}|${sub.offsetMs},apad=pad_dur=0.3[a${i + 1}]`);+ audioLabels.push(`[a${i + 1}]`);+});+filterChunks.push(`${audioLabels.join('')}amix=inputs=${audioLabels.length}:duration=longest:normalize=0[mixed]`);++const outputDurationMs = Math.max(totalVisibleMs, lastClipEndMs + 500);++ffArgs.push(+ '-filter_complex',+ filterChunks.join(';'),+ '-map',+ '[vout]',+ '-map',+ '[mixed]',+ '-c:v',+ 'libx264',+ '-pix_fmt',+ 'yuv420p',+ '-preset',+ 'veryfast',+ '-crf',+ '23',+ '-c:a',+ 'aac',+ '-b:a',+ '160k',+ '-t',+ `${(outputDurationMs / 1000).toFixed(3)}`,+ outPath,+);++console.log('🧪 ffmpeg', ffArgs.map((a) => (/\s/.test(a) ? JSON.stringify(a) : a)).join(' '));+await run('ffmpeg', ffArgs);+console.log(`✅ Narrated video: ${outPath}`);diff --git a/skills/feature-demo/scripts/recorder.template.mjs b/skills/feature-demo/scripts/recorder.template.mjsnew file mode 100644index 0000000..1e93954--- /dev/null+++ b/skills/feature-demo/scripts/recorder.template.mjs@@ -0,0 +1,565 @@+// Per-feature recording skeleton produced by the feature-demo skill.+// Copy into scripts/ and edit the BRAND, TITLE_CARD, and FEATURE STEPS+// sections for your flow.+//+// Run: node scripts/<your-recording>.mjs+// Env: BASE_URL (default http://127.0.0.1:8000) — the URL the recorder hits+// OUT_DIR (default /tmp/playwright-recording)+// TIMINGS_PATH (default <OUT_DIR>/subtitle-timings.json)+// DEMO_DOMAIN — shown in the fake URL bar (overrides BRAND.demoDomain)+// ELEVENLABS_API_KEY — if set, the recorder pre-generates the TTS+// narration MP3 for each caption and waits for its ACTUAL+// duration before moving to the next scene, so audio and video+// stay in lockstep. Without it, falls back to a character-rate+// estimate.+// ELEVENLABS_VOICE_ID (default Bella EXAVITQu4vr4xnSDxMaL)+// ELEVENLABS_MODEL_ID (default eleven_v3)++import { mkdirSync, writeFileSync, existsSync } from 'fs';+import path from 'path';+import { spawn, spawnSync } from 'child_process';+import { chromium } from 'playwright';++// ─── BRAND ────────────────────────────────────────────────────────────────+// Edit per project. These end up in the chrome tab title + the title+// card. logoPath is searched up from the script location (so e.g. for a+// Laravel app `public/img/logo.svg` finds it from anywhere under the+// repo); leave it `undefined` to fall back to a text wordmark of `name`.+const BRAND = {+ name: '<YourApp>',+ demoDomain: 'app.example.com',+ logoPath: undefined, // e.g. 'public/img/logo.svg'+ backgroundColor: '#0f172a', // title-card background+ accentColor: '#38bdf8', // title-card underline + chrome tab favicon+};++// ─── CONFIG ───────────────────────────────────────────────────────────────+const BASE_URL = process.env.BASE_URL || 'http://127.0.0.1:8000';+const OUT_DIR = process.env.OUT_DIR || '/tmp/playwright-recording';+const TIMINGS_PATH = process.env.TIMINGS_PATH || path.join(OUT_DIR, 'subtitle-timings.json');+const DEMO_DOMAIN = process.env.DEMO_DOMAIN || BRAND.demoDomain;+const ELEVENLABS_API_KEY = process.env.ELEVENLABS_API_KEY;+const ELEVENLABS_VOICE_ID = process.env.ELEVENLABS_VOICE_ID || 'EXAVITQu4vr4xnSDxMaL';+const ELEVENLABS_MODEL_ID = process.env.ELEVENLABS_MODEL_ID || 'eleven_v3';+const NARRATION_DIR = path.join(OUT_DIR, 'narration');+mkdirSync(OUT_DIR, { recursive: true });+mkdirSync(NARRATION_DIR, { recursive: true });++// Update TOTAL_STEPS to match the number of `step(...)` calls below+// (including the opener) so the on-screen "Step N / TOTAL" badge is accurate.+const TOTAL_STEPS = 8;++// Title card + intro voiceover shown at the start of the final video.+// The narrator script renders this as the first frame (so it's also the+// preview thumbnail) and plays the intro over it. Brand fields from+// BRAND above are merged in at write-time so narrate.mjs has everything+// it needs in a single sidecar.+const TITLE_CARD = {+ title: '<Your video title>',+ subtitle: '<One-line subtitle>',+ intro: "<One-sentence intro spoken over the title card explaining what the video covers.>",+};++// ─── NARRATION TIMING ─────────────────────────────────────────────────────+// Tail buffer added to actual narration duration so the next scene doesn't+// jump in the moment the speaker finishes.+const NARRATION_TAIL_MS = 400;++// IMPORTANT: reset any per-feature backend state before recording so each+// run starts from the same place. Without this, leftover rows from prior+// runs (e.g. extra steps you added to a sequence) accumulate and confuse+// selectors. The pattern: shell out via spawnSync (array form so the+// shell doesn't expand `$vars`) and zero out the bits this demo touches.+// Skip if the demo doesn't need a known user (e.g. registration demos+// that use a random email per run).+//+// Example (Laravel):+// const resetDemoState = () => {+// const phpCode = `+// $u = \\App\\Models\\User::firstWhere("email", "[email protected]");+// if ($u) { /* delete extra rows the demo creates */ }+// `;+// const res = spawnSync('php', ['artisan', 'tinker', '--execute', phpCode], {+// env: process.env, encoding: 'utf8',+// });+// if (res.status !== 0) throw new Error(`reset failed: ${res.stderr || res.stdout}`);+// console.log(`🧹 ${res.stdout.trim()}`);+// };+// resetDemoState();++const runCapture = (cmd, args) =>+ new Promise((resolve, reject) => {+ const p = spawn(cmd, args, { stdio: ['ignore', 'pipe', 'inherit'] });+ const chunks = [];+ p.stdout.on('data', (c) => chunks.push(c));+ p.on('error', reject);+ p.on('close', (code) => (code === 0 ? resolve(Buffer.concat(chunks).toString('utf8')) : reject(new Error(`${cmd} exited ${code}`))));+ });++const probeDurationMs = async (file) => {+ try {+ const out = await runCapture('ffprobe', ['-v', 'error', '-show_entries', 'format=duration', '-of', 'default=nw=1:nk=1', file]);+ return Math.round(parseFloat(out.trim()) * 1000);+ } catch (e) {+ console.warn(`ffprobe failed on ${file}: ${e.message}`);+ return null;+ }+};++// Returns the duration each scene's wait should cover. Pre-generates the+// TTS clip and caches it on disk so the recorder waits for the actual+// narration length. Falls back to ~12 chars/sec if no API key is set.+const fallbackEstimateMs = (text) => Math.max(2500, Math.ceil(text.length / 12) * 1000);+const ensureNarrationDuration = async (step, text) => {+ if (!ELEVENLABS_API_KEY) return fallbackEstimateMs(text);+ const clipPath = path.join(NARRATION_DIR, `step-${step}.mp3`);+ if (!existsSync(clipPath)) {+ const res = await fetch(`https://api.elevenlabs.io/v1/text-to-speech/${ELEVENLABS_VOICE_ID}`, {+ method: 'POST',+ headers: {+ 'xi-api-key': ELEVENLABS_API_KEY,+ 'Content-Type': 'application/json',+ Accept: 'audio/mpeg',+ },+ body: JSON.stringify({+ text,+ model_id: ELEVENLABS_MODEL_ID,+ voice_settings: { stability: 0.5, similarity_boost: 0.75, style: 0.0, use_speaker_boost: true },+ }),+ });+ if (!res.ok) {+ const body = await res.text();+ console.warn(`ElevenLabs ${res.status} for step ${step}: ${body.slice(0, 200)} — using estimate`);+ return fallbackEstimateMs(text);+ }+ writeFileSync(clipPath, Buffer.from(await res.arrayBuffer()));+ }+ const dur = await probeDurationMs(clipPath);+ return (dur || fallbackEstimateMs(text)) + NARRATION_TAIL_MS;+};++// ─── OVERLAY ──────────────────────────────────────────────────────────────+// Injected on every page load. Adds:+// - a scene-caption subtitle bar pinned to the bottom+// - a fake mouse cursor that clickWithCursor/fillWithCursor steer to+// each target before the action, so the viewer can see what's being+// clicked (Playwright drives events with no real cursor by default)+// The browser chrome itself is rendered as a separate PNG (see+// renderChromeFramePng below) and stacked on top of the video by+// narrate.mjs — keeping it out of the recorded viewport means the page+// layout stays untouched.+const CAPTION_H = 70;+const CURSOR_TIP_X = 5;+const CURSOR_TIP_Y = 2;+const CURSOR_SVG = `<svg viewBox="0 0 28 28" xmlns="http://www.w3.org/2000/svg" width="22" height="22"><path d="M 5 2 L 5 22 L 9.5 17.5 L 12.5 25 L 15 24 L 12 16 L 18.5 16 Z" fill="black" stroke="white" stroke-width="1.2" stroke-linejoin="round"/></svg>`;+const overlayInit = () => `+(() => {+ if (window.__cgyOverlayInstalled) return;+ window.__cgyOverlayInstalled = true;+ const CAPTION_H = ${CAPTION_H};+ const CURSOR_TIP_X = ${CURSOR_TIP_X};+ const CURSOR_TIP_Y = ${CURSOR_TIP_Y};+ const CURSOR_SVG = ${JSON.stringify(CURSOR_SVG)};++ const ensure = () => {+ if (!document.body) return requestAnimationFrame(ensure);+ if (document.getElementById('__cgy_overlay')) return;++ const padStyle = document.createElement('style');+ padStyle.id = '__cgy_padstyle';+ padStyle.textContent =+ 'html,body{padding-bottom:' + CAPTION_H + 'px !important;box-sizing:border-box !important;}' ++ '@keyframes __cgyRipple { 0% { width:8px;height:8px;opacity:0.5; } 100% { width:48px;height:48px;opacity:0; } }' ++ '@keyframes __cgyClickPulse { 0% { transform:scale(1); } 50% { transform:scale(0.78); } 100% { transform:scale(1); } }';+ document.head.appendChild(padStyle);++ const bar = document.createElement('div');+ bar.id = '__cgy_overlay';+ bar.innerHTML = '<span id="__cgy_overlay_badge"></span><span id="__cgy_overlay_text"></span>';+ bar.setAttribute('style', [+ 'position:fixed','left:0','right:0','bottom:0','z-index:2147483647',+ 'background:rgba(15,23,42,0.92)','color:#f8fafc',+ 'font:500 20px/1.4 -apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif',+ 'padding:18px 28px','display:flex','align-items:center','gap:16px',+ 'box-shadow:0 -4px 16px rgba(0,0,0,0.25)','letter-spacing:0.01em',+ 'pointer-events:none','transition:opacity 200ms ease',+ 'border-top:3px solid #38bdf8',+ ].join(';'));+ document.body.appendChild(bar);+ bar.querySelector('#__cgy_overlay_badge').setAttribute('style', [+ 'background:#38bdf8','color:#0f172a','font-weight:700',+ 'padding:4px 12px','border-radius:999px','font-size:14px',+ 'letter-spacing:0.08em','text-transform:uppercase','flex:none',+ ].join(';'));++ const cur = document.createElement('div');+ cur.id = '__cgy_cursor';+ cur.setAttribute('style', [+ 'position:fixed',+ 'left:' + (window.__cgyCursorLastX != null ? window.__cgyCursorLastX - CURSOR_TIP_X : 60) + 'px',+ 'top:' + (window.__cgyCursorLastY != null ? window.__cgyCursorLastY - CURSOR_TIP_Y : 60) + 'px',+ 'width:22px','height:22px','pointer-events:none','z-index:2147483646',+ 'transition:left 0.5s cubic-bezier(.22,.61,.36,1),top 0.5s cubic-bezier(.22,.61,.36,1)',+ 'filter:drop-shadow(0 1px 2px rgba(0,0,0,0.35))',+ ].join(';'));+ cur.innerHTML = '<div id="__cgy_cursor_inner" style="width:100%;height:100%">' + CURSOR_SVG + '</div>';+ document.body.appendChild(cur);++ window.__cgyMoveCursor = (x, y) => {+ window.__cgyCursorLastX = x;+ window.__cgyCursorLastY = y;+ const el = document.getElementById('__cgy_cursor');+ if (!el) return;+ el.style.left = (x - CURSOR_TIP_X) + 'px';+ el.style.top = (y - CURSOR_TIP_Y) + 'px';+ };+ window.__cgyClickAt = (x, y) => {+ const inner = document.getElementById('__cgy_cursor_inner');+ if (inner) {+ inner.style.animation = '__cgyClickPulse 0.18s ease';+ setTimeout(() => { inner.style.animation = ''; }, 200);+ }+ const ripple = document.createElement('div');+ ripple.setAttribute('style', [+ 'position:fixed','left:' + x + 'px','top:' + y + 'px',+ 'width:8px','height:8px','border-radius:50%',+ 'background:rgba(15,23,42,0.35)','pointer-events:none',+ 'z-index:2147483645','transform:translate(-50%,-50%)',+ 'animation:__cgyRipple 0.5s ease-out forwards',+ ].join(';'));+ document.body.appendChild(ripple);+ setTimeout(() => ripple.remove(), 600);+ };++ if (window.__cgyOverlayPending) {+ window.__cgySetSubtitle(window.__cgyOverlayPending.badge, window.__cgyOverlayPending.text);+ }+ };+ window.__cgySetSubtitle = (badge, text) => {+ const el = document.getElementById('__cgy_overlay');+ if (!el) {+ window.__cgyOverlayPending = { badge, text };+ ensure();+ return;+ }+ el.querySelector('#__cgy_overlay_badge').textContent = badge;+ el.querySelector('#__cgy_overlay_text').textContent = text;+ };+ ensure();+})();+`;++// Renders a Chrome-on-macOS chrome frame PNG via a headless Playwright+// page — narrate.mjs stacks this on top of the recorded video with+// ffmpeg so the demo reads as a real Chrome window. Two rows: tab+// strip (traffic lights + active tab) + toolbar (nav buttons + omnibox+// + profile/extensions/menu). SVGs for icons so they render crisply.+const renderChromeFramePng = async (context, outPath, { width, demoDomain, initialPath, tabTitle, faviconColor }) => {+ const CHROME_H = 88; // 38 tab strip + 50 toolbar+ const url = demoDomain + (initialPath.startsWith('/') ? initialPath : '/' + initialPath);+ const faviconLetter = (tabTitle || 'A')[0].toUpperCase();+ const fav = faviconColor || '#38bdf8';+ const html = `<!DOCTYPE html><html><head><meta charset="utf-8"><style>+ html,body{margin:0;padding:0;background:transparent;font:13px/1.2 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;color:#3c4043}+ .chrome{box-sizing:border-box;width:${width}px}+ .tabs{display:flex;align-items:flex-end;height:38px;background:#dee1e6;padding:0 8px 0 18px;gap:1px}+ .lights{display:flex;gap:8px;flex:none;align-self:center;margin-right:12px}+ .light{width:12px;height:12px;border-radius:50%;display:block;box-shadow:inset 0 0 0 0.5px rgba(0,0,0,0.16)}+ .tab{height:32px;background:#fff;border-radius:8px 8px 0 0;display:flex;align-items:center;padding:0 12px 0 14px;gap:9px;min-width:160px;max-width:240px;font-size:12.5px;color:#3c4043;position:relative;box-shadow:inset 0 -1px 0 #dee1e6}+ .tab .fav{width:14px;height:14px;border-radius:3px;background:${fav};display:flex;align-items:center;justify-content:center;color:white;font-size:9px;font-weight:700;flex:none}+ .tab .title{flex:1;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}+ .tab .close{width:16px;height:16px;border-radius:50%;display:flex;align-items:center;justify-content:center;color:#5f6368;flex:none}+ .tab .close svg{width:10px;height:10px}+ .new-tab{align-self:center;width:28px;height:28px;display:flex;align-items:center;justify-content:center;color:#5f6368;border-radius:4px;margin-left:6px}+ .new-tab svg{width:14px;height:14px}+ .tabs-spacer{flex:1}+ .toolbar{height:50px;background:#f1f3f4;display:flex;align-items:center;padding:0 12px;gap:6px;border-bottom:1px solid #e1e3e6}+ .icon-btn{width:28px;height:28px;border-radius:50%;display:flex;align-items:center;justify-content:center;color:#5f6368;flex:none}+ .icon-btn svg{width:18px;height:18px}+ .icon-btn.dim{color:#bdc1c6}+ .omnibox{flex:1;height:34px;background:#e8eaed;border-radius:18px;display:flex;align-items:center;padding:0 14px;gap:10px;color:#3c4043;font-size:13px;margin:0 8px;overflow:hidden}+ .omnibox .lock{display:flex;align-items:center;color:#5f6368;flex:none}+ .omnibox .lock svg{width:14px;height:14px}+ .omnibox .url{flex:1;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}+ .omnibox .star{color:#5f6368;flex:none}+ .omnibox .star svg{width:16px;height:16px}+ .profile{width:30px;height:30px;border-radius:50%;background:#1a73e8;color:#fff;display:flex;align-items:center;justify-content:center;font-weight:600;font-size:13px;flex:none;margin-left:4px}+ </style></head><body><div class="chrome">+ <div class="tabs">+ <div class="lights">+ <span class="light" style="background:#ff5f57"></span>+ <span class="light" style="background:#febc2e"></span>+ <span class="light" style="background:#28c840"></span>+ </div>+ <div class="tab">+ <span class="fav">${faviconLetter}</span>+ <span class="title">${tabTitle}</span>+ <span class="close"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M19 6.41 17.59 5 12 10.59 6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 12 13.41 17.59 19 19 17.59 13.41 12z"/></svg></span>+ </div>+ <div class="new-tab"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M19 13h-6v6h-2v-6H5v-2h6V5h2v6h6z"/></svg></div>+ <div class="tabs-spacer"></div>+ </div>+ <div class="toolbar">+ <div class="icon-btn dim"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M20 11H7.83l5.59-5.59L12 4l-8 8 8 8 1.41-1.41L7.83 13H20z"/></svg></div>+ <div class="icon-btn dim"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 4l-1.41 1.41L16.17 11H4v2h12.17l-5.58 5.59L12 20l8-8z"/></svg></div>+ <div class="icon-btn"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M17.65 6.35A7.958 7.958 0 0012 4a8 8 0 100 16 8 8 0 007.41-5h-2.1A6 6 0 1112 6c1.66 0 3.14.69 4.22 1.78L13 11h7V4l-2.35 2.35z"/></svg></div>+ <div class="omnibox">+ <span class="lock"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M18 8h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2zM9 6c0-1.66 1.34-3 3-3s3 1.34 3 3v2H9V6zm9 14H6V10h12v10zm-6-3c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2z"/></svg></span>+ <span class="url">${url}</span>+ <span class="star"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 17.27L18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z"/></svg></span>+ </div>+ <div class="icon-btn"><svg viewBox="0 0 24 24" fill="currentColor"><path d="M20.5 11H19V7c0-1.1-.9-2-2-2h-4V3.5C13 2.12 11.88 1 10.5 1S8 2.12 8 3.5V5H4c-1.1 0-1.99.9-1.99 2v3.8H3.5c1.49 0 2.7 1.21 2.7 2.7s-1.21 2.7-2.7 2.7H2V20c0 1.1.9 2 2 2h3.8v-1.5c0-1.49 1.21-2.7 2.7-2.7s2.7 1.21 2.7 2.7V22H17c1.1 0 2-.9 2-2v-4h1.5c1.38 0 2.5-1.12 2.5-2.5S21.88 11 20.5 11z"/></svg></div>+ <div class="icon-btn"><svg viewBox="0 0 24 24" fill="currentColor"><circle cx="12" cy="5" r="2"/><circle cx="12" cy="12" r="2"/><circle cx="12" cy="19" r="2"/></svg></div>+ <div class="profile">${faviconLetter}</div>+ </div>+ </div></body></html>`;+ const page = await context.newPage();+ await page.setViewportSize({ width, height: CHROME_H });+ await page.setContent(html, { waitUntil: 'load' });+ await page.screenshot({ path: outPath, omitBackground: true, clip: { x: 0, y: 0, width, height: CHROME_H } });+ await page.close();+};++// ─── ENGINE ───────────────────────────────────────────────────────────────+const subtitleTimings = [];+let recordingStart = null;+let browser;+let context;+const consoleErrors = [];++try {+ browser = await chromium.launch({ headless: true });++ // Render the chrome PNG in a NON-RECORDING context so it doesn't+ // produce a stray second .webm in OUT_DIR.+ const setupCtx = await browser.newContext({ viewport: { width: 1280, height: 88 } });+ const framePath = path.join(OUT_DIR, 'browser-frame.png');+ await renderChromeFramePng(setupCtx, framePath, {+ width: 1280,+ demoDomain: DEMO_DOMAIN,+ initialPath: '/<YOUR-ENTRY-PATH>',+ tabTitle: BRAND.name,+ faviconColor: BRAND.accentColor,+ });+ await setupCtx.close();+ console.log(`🖼 Chrome frame → ${framePath}`);++ context = await browser.newContext({+ viewport: { width: 1280, height: 800 },+ deviceScaleFactor: 1,+ recordVideo: { dir: OUT_DIR, size: { width: 1280, height: 800 } },+ ignoreHTTPSErrors: true,+ // Strict CSP on some pages would block the overlay's inline styles.+ bypassCSP: true,+ });+ await context.addInitScript(overlayInit());++ const page = await context.newPage();+ recordingStart = Date.now();+ page.on('pageerror', (err) => consoleErrors.push(`pageerror: ${err.message}`));+ page.on('console', (msg) => {+ if (msg.type() === 'error') consoleErrors.push(`console.error: ${msg.text()}`);+ });++ let currentStep = 0;+ const subtitle = async (text) => {+ currentStep += 1;+ const badge = `Step ${currentStep} / ${TOTAL_STEPS}`;+ const offsetMs = Date.now() - recordingStart;+ subtitleTimings.push({ step: currentStep, badge, text, offsetMs });+ await page.evaluate(+ ({ badge, text }) => window.__cgySetSubtitle && window.__cgySetSubtitle(badge, text),+ { badge, text },+ );+ };++ // Move the fake cursor to the center of a locator and animate it+ // there (~500ms slide), optionally fire a click ripple, then perform+ // the actual Playwright action. Always prefer these over locator.click()+ // / locator.fill() so the viewer can see what's being clicked.+ //+ // If the target is outside the "safe zone" (above the top edge or+ // behind the bottom subtitle bar), smooth-scroll it into the middle+ // of the visible area first. SCROLL_DURATION_MS is intentionally+ // generous so the scroll feels deliberate, not snappy.+ const CURSOR_MOVE_MS = 520;+ const SAFE_BOTTOM_PAD = CAPTION_H + 24;+ const SAFE_TOP_PAD = 24;+ const SCROLL_DURATION_MS = parseInt(process.env.SCROLL_DURATION_MS, 10) || 1300;+ const TYPE_DELAY_MS = parseInt(process.env.TYPE_DELAY_MS, 10) || 65;+ const slowScrollBy = async (deltaY) => {+ if (Math.abs(deltaY) < 2) return;+ await page.evaluate(+ ({ deltaY, durationMs }) => new Promise((resolve) => {+ const startY = window.pageYOffset;+ const startT = performance.now();+ const ease = (t) => 0.5 * (1 - Math.cos(Math.PI * t));+ const step = () => {+ const elapsed = performance.now() - startT;+ const progress = Math.min(elapsed / durationMs, 1);+ window.scrollTo(0, startY + deltaY * ease(progress));+ if (progress < 1) requestAnimationFrame(step);+ else resolve();+ };+ requestAnimationFrame(step);+ }),+ { deltaY, durationMs: SCROLL_DURATION_MS },+ );+ };+ const cursorTo = async (locator) => {+ let box = await locator.boundingBox();+ if (!box) return null;+ const viewport = page.viewportSize();+ const safeTop = SAFE_TOP_PAD;+ const safeBottom = viewport.height - SAFE_BOTTOM_PAD;+ const outOfSafeZone = box.y < safeTop || box.y + box.height > safeBottom;+ if (outOfSafeZone) {+ const safeCenter = (safeTop + safeBottom) / 2;+ const elementCenter = box.y + box.height / 2;+ await slowScrollBy(elementCenter - safeCenter);+ box = await locator.boundingBox();+ if (!box) return null;+ }+ const x = box.x + box.width / 2;+ const y = box.y + box.height / 2;+ await page.evaluate(+ ({ x, y }) => window.__cgyMoveCursor && window.__cgyMoveCursor(x, y),+ { x, y },+ );+ await page.waitForTimeout(CURSOR_MOVE_MS);+ return { x, y };+ };+ const clickWithCursor = async (locator) => {+ const pt = await cursorTo(locator);+ if (pt) {+ await page.evaluate(({ x, y }) => window.__cgyClickAt && window.__cgyClickAt(x, y), pt);+ await page.waitForTimeout(120);+ }+ await locator.click();+ };+ // Types `value` one character at a time (~TYPE_DELAY_MS per char) so+ // the viewer can read along. Click first to focus, clear, then type.+ const fillWithCursor = async (locator, value) => {+ const pt = await cursorTo(locator);+ if (pt) {+ await page.evaluate(({ x, y }) => window.__cgyClickAt && window.__cgyClickAt(x, y), pt);+ await page.waitForTimeout(120);+ }+ await locator.click();+ await locator.fill('');+ await locator.pressSequentially(value, { delay: TYPE_DELAY_MS });+ };++ // ELEVENLABS_API_KEY makes each step wait for the actual TTS clip+ // duration; without it we use a character-rate estimate.+ //+ // mode 'before' (default) — narrate first, THEN run fn(). Use when+ // fn() transitions the page (click + navigate) so the viewer+ // finishes hearing the caption while still seeing the current+ // page, then watches the transition silently.+ // mode 'during' — run fn() in parallel with narration. Use for+ // visible in-place actions like filling a form, where you want+ // the action to play while it's being described.+ // mode 'after' — run fn() first, THEN narrate. Use to describe a+ // state that the action just produced.+ const step = async (label, captionText, fn, { mode = 'before' } = {}) => {+ console.log(`▶ ${label} [${mode}]`);+ try {+ let waitMs = 900;+ if (captionText) {+ await subtitle(captionText);+ waitMs = await ensureNarrationDuration(currentStep, captionText);+ console.log(` step ${currentStep} narration: ${waitMs}ms`);+ }+ if (mode === 'during') {+ await Promise.all([fn(), page.waitForTimeout(waitMs)]);+ } else if (mode === 'after') {+ await fn();+ if (captionText) await page.waitForTimeout(waitMs);+ } else {+ // 'before'+ await page.waitForTimeout(waitMs);+ await fn();+ }+ console.log(`✓ ${label}`);+ } catch (err) {+ console.error(`✗ ${label}: ${err.message}`);+ await page.screenshot({ path: `${OUT_DIR}/fail-${label.replace(/\W+/g, '-')}.png`, fullPage: true });+ throw err;+ }+ };++ // ─── FEATURE STEPS ────────────────────────────────────────────────────+ // Replace the steps below for your feature. Pattern:+ // await step('internal label', 'On-screen / narrated caption', async () => {+ // // Playwright actions for this scene — always use+ // // clickWithCursor / fillWithCursor (not locator.click / fill)+ // // so the viewer sees what's being clicked.+ // }, { mode: 'before' });+ //+ // Tips:+ // - Keep captions to one sentence; that's what gets read aloud.+ // - Use `await page.waitForTimeout(N)` inside the action when you need+ // the user to "see" a state before moving on.+ // - The first step usually navigates somewhere; the opener below+ // shows the bare-minimum pattern.++ console.log('▶ open the entry page');+ await page.goto(`${BASE_URL}/<YOUR-ENTRY-PATH>`, { waitUntil: 'networkidle', timeout: 15000 });+ // Extra settle so Inertia/Vue finishes hydrating + fonts paint before+ // we mark t=0 with the first subtitle — the narrator trims the front+ // of the video to (subtitle_offset - 150ms), so the page must be+ // fully visible by then or the trimmed video starts mid-render.+ await page.waitForTimeout(500);+ const openerCaption = `Opening the <feature name> in ${BRAND.name}.`;+ await subtitle(openerCaption);+ await page.waitForTimeout(await ensureNarrationDuration(currentStep, openerCaption));++ await step(+ 'fill the first thing',+ 'A one-sentence caption describing what happens in this scene.',+ async () => {+ // await fillWithCursor(page.locator('input[name="..."]'), '...');+ // await clickWithCursor(page.getByRole('button', { name: /save/i }));+ },+ );++ // ...repeat for each scene; bump TOTAL_STEPS above to match the count.++ console.log('\n🎬 Recording complete.');+} catch (err) {+ console.error('\n💥 Failure:', err.stack || err.message);+ process.exitCode = 1;+} finally {+ if (context) await context.close().catch(() => {});+ if (browser) await browser.close().catch(() => {});++ try {+ writeFileSync(+ TIMINGS_PATH,+ JSON.stringify(+ {+ titleCard: {+ ...TITLE_CARD,+ brandName: BRAND.name,+ logoPath: BRAND.logoPath,+ backgroundColor: BRAND.backgroundColor,+ accentColor: BRAND.accentColor,+ },+ subtitles: subtitleTimings,+ },+ null,+ 2,+ ),+ );+ console.log(`📝 Subtitle timings → ${TIMINGS_PATH}`);+ } catch (e) {+ console.error(`failed to write timings: ${e.message}`);+ }++ if (consoleErrors.length) {+ console.log('\nBrowser console errors collected:');+ for (const e of consoleErrors.slice(0, 20)) console.log(` - ${e}`);+ process.exitCode = 1;+ }+}