Commit fa9f928f2 for llama.cpp

commit fa9f928f25a5fc765c7d0d1c7deb64e8f1a762a4
Author: Aleksander Grygier <aleksander.grygier@gmail.com>
Date:   Thu Nov 26 17:15:39 2026 +0100

    ui: move the demo harness to ui/lib/demo and render videos on the Llama brand (#33125)

    * ui: render demo videos in a window on a brand ground

    A demo video is now rendered from the recorded frames: the app in a rounded window on a Llama brand ground, camera zooms with motion blur, captions under the window, and an optional logo card. DEMO_POLISH=0 gives the plain screencast as before.

    Assisted-by: Claude (Opus 5.5 Medium)

    * ui: let demos mock llama-server and record Storybook stories

    Assisted-by: Claude (Opus 5.5 Medium)

    * ui: check chat search end to end against a mocked llama-server

    Assisted-by: Claude (Opus 5.5 Medium)

    * ui: add a skill to demo, test and document Llama Chat and Llama UI changes

    Assisted-by: Claude (Opus 5.5 Medium)

    * ui: describe the demo render in the README and the ui-demo skill

    Assisted-by: Claude (Opus 5.5 Medium)

    * ui: zoom the whole stage in demo videos, show taps on touch demos

    The camera now moves over the stage, so the window comes closer with its corners and the ground round it. The render runs in a Chromium of its own at 1x. A touch device shows a fingertip tap in place of the cursor.

    Assisted-by: Claude (Opus 5.5 Medium)

    * ui: make the demo camera moves shorter and snappier

    Assisted-by: Claude (Opus 5.5 Medium)

    * ui: fix tiled shadows when the demo camera zooms in

    Each copy of the window is now laid out where the camera puts it instead of scaled with a transform: Chromium cut the scaled shadow into tiles, which left light rectangles round a zoomed window. The motion blur now spans half a frame, like a 180 degree shutter.

    Assisted-by: Claude (Opus 5.5 Medium)

    * ui: draw the zoomed demo window on one canvas

    The motion blur copies are drawn on one stage canvas, with the squircle corners and the shadow in 2D, instead of as one layer each: twelve large layers overran Chromium's tile memory while the camera moved, and the dropped tiles showed as light blocks round the window.

    Assisted-by: Claude (Opus 5.5 Medium)

    * ui: leave phone demos unzoomed in the ui-demo skill and README

    Assisted-by: Claude (Opus 5.5 Medium)

    * ui: show each demo video beside its description in the PR

    A test's description annotation is written to the video manifest; when the tests have one, the Demo section puts one video to a row with its title and description.

    Assisted-by: Claude (Opus 5.5 Medium)

    * ui: move the demo harness to ui/lib/demo

    The recorder, the render, the Demo driver, storage and the pr and docs commands are now @ggml-org/llama-demo in ui/lib/demo, for any app in the suite. It imports only Playwright's types: the app passes in its page, so it runs from source with nothing installed. Llama Chat keeps its fixtures, servers and traces command in its demo folder.

    Assisted-by: Claude (Opus 5.5 Medium)

    * ui: harden the demo render and the pr command

    The render cleans up after a failure and removes the part-written mp4. A page the render cannot frame records plainly instead of losing its captions, demos fail early outside Chromium, and the render's extra time is added after the demo, so a test.setTimeout() in it cannot take it away. demo:pr finds the app in the worktree from git's own prefix, a description's line breaks stay inside its table cell, zoomIn scrolls its target into view, and a quick second tap keeps its fingertip.

    Assisted-by: Claude (Opus 5.5 Medium)

    * ui: teach the ui-demo skill to shape, check and publish a demo

    Assisted-by: Claude (Opus 5.5 Medium)

    * ui: import the demo harness as @ggml-org/llama-demo

    Llama Chat adds ui/lib/demo as a local file: dependency, which npm links, and imports it by name instead of by relative path. Nothing is published; npm ci leaves a link that only the demo commands follow.

    Assisted-by: Claude (Opus 5.5 Medium)

diff --git a/.github/workflows/pr-video-demo-label.yml b/.github/workflows/pr-video-demo-label.yml
index f6f856753..d6d59e710 100644
--- a/.github/workflows/pr-video-demo-label.yml
+++ b/.github/workflows/pr-video-demo-label.yml
@@ -22,7 +22,7 @@ jobs:
           BODY: ${{ github.event.pull_request.body }}
           HAS_LABEL: ${{ contains(github.event.pull_request.labels.*.name, 'video demo') }}
         run: |
-          # sections written by demo:pr (see ui/apps/chat/demo/cli.ts): the managed comment
+          # sections written by demo:pr (see ui/lib/demo/src/cli.ts): the managed comment
           # markers, or a preview linking to a demo video uploaded for this PR
           has_demo=false
           if { grep -qF '<!-- demo:start -->' <<< "$BODY" && grep -qF '<!-- demo:end -->' <<< "$BODY"; } ||
diff --git a/.github/workflows/ui.yml b/.github/workflows/ui.yml
index 3547bf4c6..0c32992d3 100644
--- a/.github/workflows/ui.yml
+++ b/.github/workflows/ui.yml
@@ -212,6 +212,29 @@ jobs:
         run: npm run prepack
         working-directory: ui/lib/harness

+  demo-checks:
+    name: Demo harness checks
+    runs-on: ubuntu-24.04
+    steps:
+      - name: Checkout code
+        uses: actions/checkout@v6
+        with:
+          ref: ${{ github.event.inputs.sha || github.event.pull_request.head.sha || github.sha || github.head_ref || github.ref_name }}
+
+      - name: Setup Node.js
+        uses: actions/setup-node@v6
+        with:
+          node-version: "24"
+          package-manager-cache: false
+
+      - name: Install dependencies
+        run: npm ci
+        working-directory: ui/lib/demo
+
+      - name: Run type checking
+        run: npm run check
+        working-directory: ui/lib/demo
+
   chat-only-build:
     name: Chat-only build
     runs-on: ubuntu-24.04
diff --git a/skills/ui-demo/SKILL.md b/skills/ui-demo/SKILL.md
new file mode 100644
index 000000000..8fc7c7319
--- /dev/null
+++ b/skills/ui-demo/SKILL.md
@@ -0,0 +1,232 @@
+---
+name: ui-demo
+description: Demo, test and document a change in Llama Chat (ui/apps/chat) or Llama UI (ui/lib/ui) with the Playwright demo harness - record a video for the PR, turn the same flow into an e2e check, and capture docs videos and screenshots. Use when a UI change needs a demo video, a Playwright check, or docs media.
+---
+
+# Demo, test and document a UI change
+
+One scripted flow serves three ends: a **demo** video in the PR, a Playwright **check** in `tests/e2e`, and **docs** media. The harness is `ui/lib/demo/`, and Llama Chat's fixtures for it are in `ui/apps/chat/demo/` (read both `README.md` files once). Everything below runs from `ui/apps/chat`.
+
+Use it when a change in `ui/apps/chat` or `ui/lib/ui` is visible: a new or changed screen, flow or component. Skip it for refactors with no visible effect.
+
+AGENTS.md still applies: the contributor writes the PR description and owns the script. `demo:pr` only fills the managed `## Demo` section.
+
+## Pick the target
+
+| Change in                         | Record                 | How                                           |
+| --------------------------------- | ---------------------- | --------------------------------------------- |
+| Llama Chat flow or screen         | the app, on vite dev   | default                                       |
+| Llama UI component (`ui/lib/ui`)  | its Storybook story    | `test.use({ story })` + `DEMO_STORYBOOK=ui`   |
+| Llama Chat component in isolation | Chat's Storybook story | `test.use({ story })` + `DEMO_STORYBOOK=chat` |
+
+A Storybook story is the harness page for a component: if none shows the state you need, add a story next to the others (`tests/stories/` in that package) rather than a new page.
+
+## Setup (once)
+
+```bash
+cd ui/apps/chat && npm ci
+```
+
+```bash
+npx playwright install chromium
+```
+
+Also `ffmpeg`, and `npm ci` in `ui/lib/ui` for Llama UI stories. `demo:pr` needs `gh` (edit rights on the PR) and, to link the video, an `hf` login plus `DEMO_STORAGE` and `DEMO_STORAGE_PUBLIC_URL` in `ui/apps/chat/.env` (see `.env.example`).
+
+## 1. Demo
+
+### Write the script
+
+Scripts get `test` and `expect` from `helpers.ts`. Drive the page with `demo.*` (visible cursor, human timing), assert with `expect`, set the scene with `test.use`:
+
+- `demo.click`, `demo.hover`, `demo.type`, `demo.press`, `demo.scroll`, `demo.pause`, `demo.caption(text, ms)` (a chip under the window), `demo.zoom(target, scale, ms)` (the camera moves onto a small detail and back), `demo.zoomIn(target, scale)` ... `demo.zoomOut()` (the camera stays on it across the actions between).
+- `test.use({ settings: {...} })` seeds UI settings, `startPath: '/#/...'` starts on a route.
+- Fixtures, so no real data or third-party server is needed:
+    - **MCP servers:** two fixture servers (Weather, Notes) are always configured; see `demo/fixtures/demo-config.ts`.
+    - **Conversations:** `traces: ['long-chat', 'agentic-debugging']` imports built-in chats (`demo/fixtures/traces.ts`); other names come from `DEMO_TRACES_DATASET`.
+    - **Models and replies:** `mockServer: { models: ['org/Model-GGUF:Q4_K_M'], reply: 'Markdown **reply**' }` answers llama-server's endpoints in the browser (`demo/fixtures/llama-server.ts`): the model list, props, load, tools and a streamed reply. Nothing reaches a server and no model loads. Use it for any demo that sends a message.
+    - **Stories:** `story: 'ui-forms-switch--default'`, the id from the Storybook URL (`?path=/story/<id>`).
+
+Without `mockServer` the app talks to the llama-server at `DEMO_SERVER_ORIGIN` (default `:9931`, started from `build/bin/llama-server` when none runs). Sending a message there loads a model: do not do that on someone's running server without asking.
+
+### Shape the video
+
+The video is rendered from the recording, not the raw screencast: the app in a window on a Llama brand ground, camera moves over the whole stage with motion blur, captions under the window, and on a touch viewport taps in place of the cursor (see "The render" in the harness README). Write for that:
+
+- **One thing per video.** A PR that changes several things gets several short `test()`s, not one long walk.
+- **Captions** are in the brand's voice: plain words, real numbers, no emoji, one line. `demo.caption(text, ms)` holds the caption for `ms` and the demo waits, so show it while the screen is still (before or after an action, not over one). A demo with no captions gets no caption row, and the window is larger.
+- **Zooms** are for a detail too small to read in the frame. The camera aims where the target is when the zoom starts and does not follow it, so zoom after the layout settles (wait with `expect` first), and zoom out before an action that moves the target, such as sending a message. Zoom on desktop demos; a phone's UI already fills a portrait video, so leave phone demos unzoomed unless a detail is too small to read even there.
+- **Phones:** `test.use({ hasTouch: true, isMobile: true, viewport: { height: 844, width: 390 } })` gives a 1080x1920 video with a phone's corners, and every click shows as a fingertip tap.
+- **Dark mode:** `test.use({ colorScheme: 'dark' })` records the dark theme on the night sky.
+- **Timing:** the harness adds the render's time to the test's timeout after the demo, so a demo needs no long `test.setTimeout`.
+
+`DEMO_POLISH_LOGO=end` adds a Llama logo card, for a video that goes out on its own; `DEMO_POLISH=0` gives the plain screencast.
+
+### Try it locally
+
+Save it as `demo/<name>.demo.ts` (git-ignored), importing from `./helpers.ts`, and run:
+
+```bash
+npm run demo:record -- demo/<name>
+```
+
+Add `DEMO_STORYBOOK=ui` (or `chat`) when the script has a `story`. `DEMO_POLISH=0` records faster while iterating (the render takes a few times the video's length). The mp4 lands in `demo/videos/`. Look at it before going further: a sheet of frames shows the whole flow, the camera moves and the captions at once, where one still frame misses most of it:
+
+```bash
+ffmpeg -loglevel error -i demo/videos/<name>.mp4 -vf "fps=2,scale=480:-1,tile=6x4" -frames:v 1 demo/videos/<name>-sheet.png
+```
+
+Check that each caption is readable and on screen long enough, that every zoom lands on its detail, and that nothing is cut off at the window's edge.
+
+`npm run demo:codegen` opens Playwright codegen on `:5180` for a first draft of the selectors.
+
+### Put it in the PR
+
+Paste the script into the PR description as a `ts demo` block, inside the last collapsible block of Additional information:
+
+````md
+<details>
+<summary>Demo script</summary>
+
+```ts demo
+test("demo", async ({ demo, page }) => {
+    // ...
+});
+```
+
+</details>
+````
+
+Push the branch first: `demo:pr` records the PR's head commit as GitHub has it. Then record it and write the `## Demo` section (between `<!-- demo:start -->` and `<!-- demo:end -->`):
+
+```bash
+npm run demo:pr -- <number>
+```
+
+It takes a few minutes, so run it in the background. The app's UI comes from the PR's head, in a temporary worktree, but the harness and fixtures come from your checkout: a PR that changes the harness itself is recorded with the harness you have checked out. Run it again after each push that changes what the videos show.
+
+- Each `test()` becomes its own video, shown in a table under its title. Give each test `{ annotation: { type: 'description', description: '...' } }` to get one video to a row with its description beside it, which reads better when the videos show different things (see the worked example). Group tests with their own `test.use` in `test.describe(() => { ... })`.
+- In a PR block, the helpers import is replaced with `test` and `expect`, so reach fixtures through `test.use` options only.
+- A PR on a fork: `DEMO_GITHUB_REPO=<owner>/llama.cpp`. A PR by someone else: read its diff and demo block, then pass `--trust <sha>`.
+
+## 2. Test
+
+Turn the same flow into a check in `tests/e2e/<feature>.e2e.ts`, which CI runs (`npm run test:e2e`) against the built app on `:8181`, with no llama-server:
+
+- `@playwright/test` instead of the helpers: `locator.click()` / `fill()` for `demo.*`, keep every `expect`, drop captions and pauses.
+- `mockLlamaServer(page, {...})` before `page.goto`, since nothing serves the API.
+- `importTraces(page, file)` and `generateTrace(name)` seed conversations, as in a demo.
+
+```bash
+npx playwright test tests/e2e/<feature>.e2e.ts
+```
+
+Locally it uses the installed Chrome with its sandbox on; in CI, Playwright's Chromium.
+
+For a component on its own, a `play` function on its story is the check instead (as in `ui/apps/chat/tests/stories/app/PwaRefreshAlert.stories.svelte`): both packages run their stories as vitest browser tests, `npm run test:ui` in `ui/apps/chat` and `npm test` in `ui/lib/ui`.
+
+## 3. Document
+
+- **Docs videos:** put the script in the storage target as `scripts/docs/<name>.demo.ts` (import `'../helpers.ts'`), then `npm run demo:docs` records every docs script and uploads `videos/docs/<name>.{mp4,gif}`. `DEMO_STORAGE=file:///some/dir` tries it without a bucket.
+- **Screenshots:** in any demo, `await page.screenshot({ path: 'demo/videos/<name>.png' })` for the frame, or `await locator.screenshot({ path })` for one component, rendered at `DEMO_SCALE` (2x by default). Paths are relative to `ui/apps/chat`.
+- **Component docs** belong in the package's Storybook: a story per state, prose in a `.svx` page (see `ui/apps/chat/AGENTS.md`).
+
+## Worked example
+
+A demo of chat search, then a reply from the mocked server, then a Llama UI story, in one PR block, each video with its description beside it in the `## Demo` table (record with `DEMO_STORYBOOK=ui npm run demo:pr -- <number>`):
+
+```ts
+const describe = (description: string) => ({
+    annotation: { description, type: "description" },
+});
+
+test.describe(() => {
+    test.use({ traces: ["long-chat", "agentic-debugging"] });
+
+    test(
+        "Search finds a chat by its title",
+        describe(
+            "Typing a word from a chat's title lists it, and opening the result shows the conversation.",
+        ),
+        async ({ demo, page }) => {
+            await demo.click(page.getByLabel("Expand navigation"));
+            await demo.click(page.getByRole("button", { name: /^Search/ }));
+
+            const search = page.getByRole("dialog", { name: "Search" });
+
+            await demo.type(
+                search.getByRole("combobox", { name: "Search" }),
+                "flaky",
+            );
+
+            const result = search.getByRole("option", {
+                name: /Fix the flaky cache tests/,
+            });
+
+            await expect(result).toBeVisible();
+            await demo.click(result, 1200);
+            await expect(page.getByRole("main")).toContainText(
+                "All 48 cache tests pass now",
+            );
+        },
+    );
+});
+
+test.describe(() => {
+    test.use({
+        mockServer: {
+            reply: "Rust is a systems language focused on **safety** and *speed*.",
+        },
+    });
+
+    test(
+        "A reply from a mocked server, no model loaded",
+        describe(
+            "The reply streams from mockServer, so the video looks the same on every machine.",
+        ),
+        async ({ demo, page }) => {
+            await demo.type(
+                page.getByRole("textbox", { name: "Type a message..." }),
+                "What is Rust?",
+            );
+            await demo.press("Enter", 1500);
+            await expect(page.getByRole("main")).toContainText(
+                "focused on safety",
+            );
+        },
+    );
+});
+
+test.describe(() => {
+    // a small viewport frames a small component, recorded at the same scale
+    test.use({
+        story: "ui-forms-switch--default",
+        viewport: { height: 450, width: 720 },
+    });
+
+    test(
+        "A Llama UI story: Switch",
+        describe(
+            "The Switch from Llama UI, recorded from its Storybook story.",
+        ),
+        async ({ demo, page }) => {
+            const off = page.getByRole("switch").first();
+
+            await demo.click(off, 900);
+            await expect(off).toBeChecked();
+        },
+    );
+});
+```
+
+The same search flow as a check is `tests/e2e/search-chats.e2e.ts`.
+
+## Pitfalls
+
+- **Ports:** vite dev `:5180` (`DEMO_UI_PORT`), fixture MCP `:8765`, llama-server `:9931`, Storybook `:6007` (`DEMO_STORYBOOK_PORT`), e2e `:8181`. Every server is reused when something already answers there, even another checkout's: stop stale servers, or pick other ports. `demo:pr` picks free ports itself.
+- **Chrome sandbox:** demos record in Playwright's bundled Chromium with the sandbox on (headless installed Chrome ignores the viewport in screencasts); local e2e runs in the installed Chrome with the sandbox on. Do not turn the sandbox off to make a run pass: a PR demo runs that PR's code.
+- **Waits:** wait on state, never on time. `expect(locator).toBeVisible()` / `toContainText()` before acting on something that appears late; `demo.pause` is pacing for the viewer only. The first load of a cold dev server reloads the page once; the harness waits for it before recording, so do not add sleeps for it.
+- **Selectors:** use roles and accessible names. Some names match twice (`Expand navigation` is both the logo and the button: use `page.getByLabel('Expand navigation')`); scope to a dialog with `page.getByRole('dialog', { name })`. A strict-mode error names both matches.
+- **Real server:** without `mockServer`, the model list and any reply come from the real llama-server and differ per machine. Mock them for anything a viewer should see the same way twice.
+- **Preview size:** keep a demo short (under ~20 s per test): the GIF preview must stay under 5 MB, so a long one is shrunk until it is hard to read.
+- **Chromium only:** the screencast and the render run on the Chrome DevTools Protocol, so a demo in Firefox or WebKit fails at its start. Show a Safari-only fix with a check in `tests/e2e`, not a demo.
diff --git a/ui/README.md b/ui/README.md
index 3d6521b58..6c7acf476 100644
--- a/ui/README.md
+++ b/ui/README.md
@@ -7,7 +7,8 @@ ui/
 ├── lib/
 │   ├── ui/       @ggml-org/llama-ui: design tokens, fonts, surfaces and components
 │   ├── voice/    @ggml-org/llama-voice: microphone capture, transcription and dictation
-│   └── harness/  @ggml-org/llama-harness: the agentic loop, headless
+│   ├── harness/  @ggml-org/llama-harness: the agentic loop, headless
+│   └── demo/     @ggml-org/llama-demo: scripted demo videos for PRs and docs
 └── apps/
     └── chat/       Llama Chat, the chat app that llama-server serves
 ```
@@ -20,12 +21,15 @@ ui/
   (`@ggml-org/llama-voice/svelte`). Apps in this repo compile its sources too. It is not published to npm yet.
 - [`lib/harness`](lib/harness/README.md) is the agentic loop: plain TypeScript with no UI and no dependencies. An app
   gives it an inference client and tools, and reads its events.
+- [`lib/demo`](lib/demo/README.md) records scripted demo videos of the apps for PRs and docs, and renders them on the
+  Llama brand. It is Node TypeScript that an app adds as a local `file:` dependency and imports by name, with the app's own
+  Playwright; it is private, not published to npm.
 - [`apps/chat`](apps/chat/README.md) talks to llama-server, stores conversations and runs the agentic loop through the
   harness. CMake builds it into llama-server (see `scripts/ui-assets.cmake`), and it is published to npm as
   `@ggml-org/llama-chat` (with `llama-chat` as its short name), so `npx llama-chat` runs it against any llama-server.

 Each folder is its own npm package with its own `package-lock.json`: run `npm ci` in the one you work on. Building,
-checking and testing `apps/chat` needs no install in `lib/ui`, `lib/voice` or `lib/harness`.
+checking and testing `apps/chat` needs no install in `lib/ui`, `lib/voice`, `lib/harness` or `lib/demo`.

 The split between library and app is not finished. Llama Chat takes its tokens, fonts, surfaces and base components
 from `lib/ui`, but still has its own versions of what the library holds above those (ActionIcon, SearchInput, Logo,
diff --git a/ui/apps/chat/.env.example b/ui/apps/chat/.env.example
index 269e65278..8941a8a90 100644
--- a/ui/apps/chat/.env.example
+++ b/ui/apps/chat/.env.example
@@ -17,7 +17,16 @@ VITE_PUBLIC_SERVER_ORIGIN='http://localhost:8033'
 # DEMO_SERVER_ORIGIN='http://localhost:9931'
 # DEMO_LLAMA_SERVER='../../../build/bin/llama-server'
 # DEMO_COLOR_SCHEME='light'
+# Also start a Storybook for story demos: ui (Llama UI) or chat (Llama Chat)
+# DEMO_STORYBOOK='ui'
+# DEMO_STORYBOOK_PORT='6007'
 # Device pixel ratio demos render and record at (1440x900 viewport)
 # DEMO_SCALE='2'
+# 0 records the plain screencast instead of the branded render
+# DEMO_POLISH='1'
+# Ground of the render: day | night | light | dark | sand (default: day, night for a dark recording)
+# DEMO_POLISH_GROUND='day'
+# A Llama logo card: start | end | both (default: none)
+# DEMO_POLISH_LOGO='end'
 # Longer side of the GIF preview, in pixels; it shrinks further to stay under 5 MB
 # DEMO_PREVIEW_WIDTH='800'
diff --git a/ui/apps/chat/AGENTS.md b/ui/apps/chat/AGENTS.md
index a80c128ca..31a21755a 100644
--- a/ui/apps/chat/AGENTS.md
+++ b/ui/apps/chat/AGENTS.md
@@ -3,6 +3,7 @@
 These add to the repository's [AGENTS.md](../../../AGENTS.md) for work in `ui/apps/chat`: **Llama Chat**, the chat client that llama-server bundles. **Llama UI**, the library, is `ui/lib/ui` (`@ggml-org/llama-ui`): Chat imports its tokens, fonts and base components from there (`@ggml-org/llama-ui/ui/<name>`) and keeps no copy of them. `DESIGN.md` and the Storybook live here; the brand book, `BRAND.md`, and the brand and communications pages are in [ggml-org/llama-brand](https://github.com/ggml-org/llama-brand), with their own Storybook. The agentic loop is `ui/lib/harness` (`@ggml-org/llama-harness`).

 - **Design:** [DESIGN.md](DESIGN.md) holds the tokens, roles and rules, written for agents. Follow it for anything visual. Its token sections (`colors`, `typography`, `rounded`) are generated from the CSS with `npm run design:tokens`, and CI checks they are current; the rest is written by hand, and when it and the CSS disagree, the CSS wins and DESIGN.md is updated.
+- **Demos, checks and docs media:** [skills/ui-demo](../../../skills/ui-demo/SKILL.md) records a PR's demo video, turns its flow into an e2e check and captures docs videos and screenshots, for Llama Chat and Llama UI alike.
 - **Stories:** a story lives with the code it shows. Llama UI's (its foundations, base components, app components and Model UI) are in `ui/lib/ui/tests/stories`, titled `Llama UI/...`, and run as the library's tests; this app's Storybook shows them too. Llama Chat's are in `tests/stories/<area>`, one folder per `src/lib/components/app/<area>` (`chat/` has one per Chat folder), titled `Llama Chat/<Area>/<Component>`. How the app works on a phone (the sidebar's keys, the sheets and the pages each pushes) is written up in `tests/stories/mobile`, titled `Llama Chat/Mobile/Flows`: update it when a sheet gains or loses a page. An accessibility story sits next to its component's, as `<Component>.a11y.stories.svelte`, titled `.../<Component>/Accessibility`. The story helpers both Storybooks use (the Editorial the prose pages are set in, `StateGallery`) live with the library's stories and are imported here as `$llama-ui-stories/...`; reuse them rather than copying them here.
 - **Releases:** `@ggml-org/llama-chat` and `@ggml-org/llama-ui` are versioned by hand and published by CI when a new version reaches `master` (see [Releases](../../README.md#releases)). Bump a version only when asked to release, never as a side effect of a change; Chat's version and its alias's (`alias/package.json`) always move together.
 - **Components:** the `SKILL.md` next to a component folder (such as [src/lib/components/app/SKILL.md](src/lib/components/app/SKILL.md)) holds that folder's conventions.
diff --git a/ui/apps/chat/demo/README.md b/ui/apps/chat/demo/README.md
index e92962687..f633d0841 100644
--- a/ui/apps/chat/demo/README.md
+++ b/ui/apps/chat/demo/README.md
@@ -1,57 +1,50 @@
-# Demo videos
+# Llama Chat demo videos

-Scripted Playwright walkthroughs of the UI, exported as mp4 with an animated GIF preview, for pull requests and documentation. The harness lives here; the demo scripts don't:
+Llama Chat's fixtures for the demo harness in [`ui/lib/demo`](../../../lib/demo/README.md), which records, renders and publishes the videos. Setup, PR and docs recording, the `demo.*` API and the render are described there; this folder sets the scene for Chat.

-- **PR demos** live in the PR description, as a `ts demo` code block.
-- **Docs demos** live in the storage target, under `scripts/docs/`.
-
-```
+```text
 demo/
-├── cli.ts      demo:pr, demo:docs and demo:traces
-├── storage.ts  storage targets (hf://, file://)
-├── helpers.ts  `test` with a `demo` fixture: cursor, captions, human-like timing
-├── recorder.ts screencast recording and mp4 export
-├── fixtures/   fixture MCP servers, seeded settings and demo conversations
-└── videos/     output (git-ignored)
+├── cli.ts                demo:pr, demo:docs and demo:traces
+├── helpers.ts            `test` with Chat's fixtures and the `demo` fixture
+├── playwright.config.ts  the servers: fixture MCP servers, llama-server, vite and Storybook
+├── fixtures/             fixture MCP servers, seeded settings, demo conversations, a mocked llama-server
+└── videos/               output (git-ignored)
 ```

-## Setup
-
-### Tools
+| Command                              | Does                                                              |
+| ------------------------------------ | ----------------------------------------------------------------- |
+| `npm run demo:record -- demo/<name>` | records `demo/<name>.demo.ts` (git-ignored) into `demo/videos/`   |
+| `npm run demo:pr -- <number>`        | records the PR's `ts demo` block and writes its `## Demo` section |
+| `npm run demo:docs`                  | records the docs scripts from `DEMO_STORAGE`                      |
+| `npm run demo:traces`                | writes the built-in traces to `demo/traces/`, and pushes them     |
+| `npm run demo:codegen`               | opens Playwright codegen against `:5180` for a first draft        |

-| Tool                                                 | Used for                                                                                                                                                                                                          |
-| ---------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
-| Node 22.18+                                          | runs `demo/cli.ts` directly (TypeScript type stripping)                                                                                                                                                           |
-| `npx playwright install chromium`                    | the browser demos record in, with its sandbox on                                                                                                                                                                  |
-| `ffmpeg`                                             | mp4 encoding and the GIF preview                                                                                                                                                                                  |
-| `gh`, logged in                                      | reads the PR description and writes the `## Demo` section, so you need edit rights on the PR                                                                                                                      |
-| `hf`, logged in with a write token (`hf auth login`) | uploads to the bucket and the traces dataset                                                                                                                                                                      |
-| `llama-server`                                       | `build/bin/llama-server`, or one already running at `DEMO_SERVER_ORIGIN` (default `:9931`). It runs in router mode, so demos can pick any model in the local cache; scripts that send messages need at least one. |
+Settings come from `ui/apps/chat/.env` (see `.env.example`).

-`gh` is only needed for `demo:pr`, and `hf` only with the bucket or dataset below. Without them, the video stays in `demo/videos/`.
+## Setting the scene

-Videos are recorded through Chromium's screencast at `DEMO_SCALE` (2x by default, so 2880x1800) and 60 fps, starting once the page has settled.
+Scripts get `test` and `expect` from `helpers.ts` without importing them. Use `test.use({ settings, startPath })` to seed other settings or start on another route, and `chats: <n>` to add empty conversations to the library.

-### Hugging Face bucket (videos, previews, scripts)
+### A mocked llama-server

-The bucket must be public, since GitHub loads the preview from it:
+`test.use({ mockServer: { models: ['org/Model-GGUF:Q4_K_M'], reply: 'A **Markdown** reply' } })` answers llama-server's endpoints in the browser (`fixtures/llama-server.ts`): the model list, props, model loading, tools and a streamed reply. Nothing reaches the server and no model loads, so a demo that sends a message looks the same on every machine. `tests/e2e` checks call `mockLlamaServer(page)` directly, since the e2e build runs without a server.

-```bash
-hf buckets create <owner>/llama-ui-demos
-```
+### Storybook stories

-Then set it in `ui/apps/chat/.env` (see `.env.example`):
+`test.use({ story: 'ui-forms-switch--default' })` records a Storybook story (the id from its `?path=/story/<id>` URL) instead of Llama Chat, from the Storybook that `DEMO_STORYBOOK` adds to the servers: `ui` for Llama UI (`ui/lib/ui`), `chat` for Llama Chat's. It runs on `DEMO_STORYBOOK_PORT` (default `:6007`). A small component reads better at a smaller `viewport` than zoomed in.

 ```bash
-DEMO_STORAGE='hf://buckets/<owner>/llama-ui-demos'
-DEMO_STORAGE_PUBLIC_URL='https://huggingface.co/buckets/<owner>/llama-ui-demos/resolve'
+DEMO_STORYBOOK=ui npm run demo:record -- demo/<name>
 ```

-Layout: `videos/pr/<number>/<sha>.{mp4,gif,demo.ts}`, `videos/docs/<name>.{mp4,gif}` and `scripts/docs/*.demo.ts` (the docs scripts). Without `DEMO_STORAGE_PUBLIC_URL`, videos are uploaded but not linked in the PR. `DEMO_STORAGE='file:///some/dir'` stores them in a local folder instead.
+### Conversations

-### Hugging Face dataset (conversations, optional)
+Demos that need existing chats import them with `test.use({ traces: ['long-chat'] })`, through Settings > Data before the video starts. Traces use the export format (llama.app JSONL), so the Hub shows them as Llama traces:

-Only needed for demos that import conversations other than the built-in ones, or to publish the built-in ones with `npm run demo:traces`. It can be private: it is read with your `hf` login.
+- `fixtures/traces.ts` generates the built-in ones: `long-chat` (36 tall exchanges) and `agentic-debugging` (long reasoning, shell output and code blocks).
+- Any other name is downloaded as `<name>.jsonl` from `DEMO_TRACES_DATASET`, e.g. an exported conversation uploaded there.
+
+The dataset is only needed for other conversations, or to publish the built-in ones with `npm run demo:traces`. It can be private: it is read with your `hf` login.

 ```bash
 hf repos create <owner>/llama-ui-demo-traces --repo-type dataset --private
@@ -61,73 +54,6 @@ hf repos create <owner>/llama-ui-demo-traces --repo-type dataset --private
 DEMO_TRACES_DATASET='<owner>/llama-ui-demo-traces'
 ```

-### Other storage
-
-Only Hugging Face buckets and `file://` folders are supported for now. S3, R2 or similar would be one more class in `storage.ts` (`upload` and `downloadDir`) plus the matching `DEMO_STORAGE_PUBLIC_URL`.
-
-## Recording a pull request
-
-Add the script to the PR description:
-
-````md
-<details>
-<summary>Demo script</summary>
-
-```ts demo
-test('demo', async ({ demo, page }) => {
-	await demo.click(page.getByRole('button', { exact: true, name: 'Settings' }));
-	await demo.caption('What this shows');
-});
-```
-
-</details>
-````
-
-Then run:
-
-```bash
-npm run demo:pr -- 31303
-```
-
-A PR by someone else runs its code and demo script on your machine, with your `gh` and `hf` logins, so `demo:pr` refuses it until you've read its diff and demo block and pass the head commit you read: `npm run demo:pr -- 31303 --trust <sha>`. If the PR gets new commits, it refuses again.
-
-It checks out the PR head in a temporary worktree, records the script against it, uploads `videos/pr/<number>/<sha>.{mp4,gif,demo.ts}` and adds or updates a `## Demo` section in the PR description with the preview linking to the video.
-
-A large PR can show its changes in several shorter videos: each `test()` in the block is recorded as its own video (`<sha>-1.mp4`, `<sha>-2.mp4`, ...), and the `## Demo` section shows their previews in a table, each headed by its test's title: up to four portrait (phone) videos to a row, or two landscape ones. Helpers and `test.use` at the top of the block are shared by all of them.
-
-````ts
-test('Header and safe areas', async ({ demo, page }) => {
-	// ...
-});
-
-test('Sidebar gestures', async ({ demo, page }) => {
-	// ...
-});
-``` GitHub has no API for attachments, so for an inline player drag `demo/videos/pr-<number>.mp4` into the description instead.
-
-## Recording docs
-
-```bash
-npm run demo:docs
-````
-
-Records every `scripts/docs/*.demo.ts` from the storage target and uploads `videos/docs/<name>.{mp4,gif}`.
-
-## Writing a demo
-
-Scripts get `test` and `expect` from `helpers.ts` without importing them. `demo.click`, `demo.hover` and `demo.type` glide a visible cursor to the target before acting, with timing varied like a person's (seeded per demo, so re-takes match); `demo.scroll` turns the mouse wheel over a target; `demo.zoom` pinches in on a control or a point to show a detail too small to read in the frame, holds, and pinches back out (with the fingertips drawn on a touch device); `demo.caption` shows a caption at the top of the frame. For voice input, `demo.microphone()` gives the page a microphone that hears nothing but `demo.speak(text)`, which reads the text in a synthetic voice (macOS `say`) and shows it as a caption, since the video has no sound. Use `test.use({ settings, startPath })` to seed other settings or start on another route.
-
-## Conversations
-
-Demos that need existing chats import them with `test.use({ traces: ['long-chat'] })`, through Settings > Import/Export before the video starts. Traces use the export format (llama.app JSONL), so the Hub shows them as Llama traces:
-
-- `fixtures/traces.ts` generates the built-in ones: `long-chat` (36 tall exchanges) and `agentic-debugging` (long reasoning, shell output and code blocks).
-- Any other name is downloaded as `<name>.jsonl` from `DEMO_TRACES_DATASET`, e.g. an exported conversation uploaded there.
-
-`npm run demo:traces` writes the built-in traces to `demo/traces/` and pushes them to `DEMO_TRACES_DATASET`.
-
-## Trying a script locally
-
-To try a script locally, put it in `demo/` as `<name>.demo.ts`, importing from `./helpers.ts`, and run `npm run demo:record -- demo/<name>`. `npm run demo:codegen` opens Playwright codegen against `:5180` for a first draft.
+## Servers

-The config starts, or reuses when already running, the fixture MCP servers on `:8765`, `llama-server` on `:9931` (router mode, `--tools all`) and the UI's vite dev server.
+The config starts, or reuses when already running, the fixture MCP servers on `:8765`, `llama-server` on `:9931` (`build/bin/llama-server` in router mode with `--tools all`, so demos can pick any model in the local cache), the UI's vite dev server and, with `DEMO_STORYBOOK`, a Storybook. Scripts that send messages to the real server need at least one model; `mockServer` needs none.
diff --git a/ui/apps/chat/demo/cli.ts b/ui/apps/chat/demo/cli.ts
index 775c361d6..363e6afd1 100644
--- a/ui/apps/chat/demo/cli.ts
+++ b/ui/apps/chat/demo/cli.ts
@@ -1,5 +1,5 @@
 /**
- * Records demo videos for pull requests and docs.
+ * Records Llama Chat's demo videos with the harness in ui/lib/demo:
  *
  *   node demo/cli.ts pr <number>   record the ```ts demo block from a PR description, a video per test
  *                                  (--trust <sha> to record someone else's PR at that head commit)
@@ -10,357 +10,13 @@
  */

 import { DEMO_TRACES, generateTrace } from './fixtures/traces.ts';
-import { type DemoStorage, getDemoStorage, getPublicUrl } from './storage.ts';
+import { runDemoCli } from '@ggml-org/llama-demo/cli';
 import { execFileSync } from 'node:child_process';
-import { createHash } from 'node:crypto';
-import {
-	existsSync,
-	mkdirSync,
-	readdirSync,
-	readFileSync,
-	rmSync,
-	statSync,
-	symlinkSync,
-	writeFileSync
-} from 'node:fs';
-import { createServer } from 'node:net';
-import { tmpdir } from 'node:os';
-import { basename, join, relative, resolve } from 'node:path';
+import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
+import { join, resolve } from 'node:path';

 const DEMO_DIR = import.meta.dirname;
-const UI_DIR = resolve(DEMO_DIR, '..');
-const RUNS_DIR = join(DEMO_DIR, '.runs');
-const VIDEOS_DIR = join(DEMO_DIR, 'videos');
 const TRACES_DIR = join(DEMO_DIR, 'traces');
-const DEMO_BLOCK = /```(?:ts|typescript)[ \t]+demo[ \t]*\r?\n([\s\S]*?)```/;
-const HELPERS_IMPORT = /^import\s[^;]*from\s+['"][^'"]*helpers(?:\.ts)?['"];?\s*$/gm;
-const SECTION_START = '<!-- demo:start -->';
-const SECTION_END = '<!-- demo:end -->';
-/** GitHub's image proxy refuses larger images, so a bigger preview shows as a broken image. */
-const PREVIEW_MAX_BYTES = 5 * 1024 * 1024;
-const envFile = join(UI_DIR, '.env');
-
-if (existsSync(envFile)) process.loadEnvFile(envFile);
-
-const REPO = process.env.DEMO_GITHUB_REPO ?? 'ggml-org/llama.cpp';
-
-function run(
-	cmd: string,
-	args: string[],
-	opts: { cwd?: string; env?: NodeJS.ProcessEnv } = {}
-): string {
-	return execFileSync(cmd, args, {
-		cwd: opts.cwd ?? UI_DIR,
-		encoding: 'utf8',
-		env: opts.env
-	}).trim();
-}
-
-/** Writes a demo script into .runs/, importing the harness helpers. */
-function writeDemoScript(name: string, source: string): string {
-	const file = join(RUNS_DIR, `${name}.demo.ts`);
-	const helpers = relative(RUNS_DIR, join(DEMO_DIR, 'helpers.ts'));
-	const body = source.replace(HELPERS_IMPORT, '').trim();
-
-	mkdirSync(RUNS_DIR, { recursive: true });
-	writeFileSync(file, `import { expect, test } from './${helpers}';\n\n${body}\n`);
-
-	return file;
-}
-
-async function freePort(): Promise<number> {
-	return new Promise((done, fail) => {
-		const server = createServer();
-
-		server.once('error', fail);
-		server.listen(0, () => {
-			const { port } = server.address() as { port: number };
-
-			server.close(() => done(port));
-		});
-	});
-}
-
-/** A video recorded from one `test()` of a script. */
-interface Video {
-	mp4: string;
-	title: string;
-}
-
-/** Records the given scripts; returns a video for each of their tests, in order. */
-async function record(scripts: string[], uiDir = UI_DIR): Promise<Video[]> {
-	const port = await freePort();
-	const manifests = scripts.map((s) => join(VIDEOS_DIR, `${basename(s, '.demo.ts')}.videos.jsonl`));
-
-	for (const manifest of manifests) rmSync(manifest, { force: true });
-
-	execFileSync(
-		'npx',
-		[
-			'playwright',
-			'test',
-			'--config=demo/playwright.config.ts',
-			...scripts.map((s) => relative(UI_DIR, s))
-		],
-		{
-			cwd: UI_DIR,
-			env: { ...process.env, DEMO_UI_DIR: uiDir, DEMO_UI_PORT: String(port) },
-			stdio: 'inherit'
-		}
-	);
-
-	// helpers.ts lists each video it encodes in the script's manifest
-	return manifests.flatMap((manifest) =>
-		readFileSync(manifest, 'utf8')
-			.trim()
-			.split('\n')
-			.map((line) => JSON.parse(line) as Video)
-	);
-}
-
-/**
- * Animated GIF preview that GitHub renders inline, its longer side DEMO_PREVIEW_WIDTH (so a
- * phone's portrait video is that tall), shrunk until it fits under PREVIEW_MAX_BYTES.
- */
-function makePreview(mp4: string): string {
-	const gif = mp4.replace(/\.mp4$/, '.gif');
-
-	for (let side = Number(process.env.DEMO_PREVIEW_WIDTH ?? 800); ; side = Math.round(side * 0.8)) {
-		execFileSync('ffmpeg', [
-			'-y',
-			'-loglevel',
-			'error',
-			'-i',
-			mp4,
-			'-vf',
-			`fps=10,scale='if(gt(iw,ih),${side},-2)':'if(gt(iw,ih),-2,${side})':flags=lanczos,split[a][b];[a]palettegen=stats_mode=diff[p];[b][p]paletteuse=dither=bayer:bayer_scale=5:diff_mode=rectangle`,
-			'-loop',
-			'0',
-			gif
-		]);
-
-		if (statSync(gif).size <= PREVIEW_MAX_BYTES || side < 320) return gif;
-	}
-}
-
-function upload(storage: DemoStorage, files: Record<string, string>): void {
-	for (const [key, file] of Object.entries(files)) {
-		storage.upload(file, key);
-		console.log(`uploaded ${key}`);
-	}
-}
-
-/**
- * Public URL with a content hash, so a re-recorded file at the same key gets a new
- * URL: GitHub's image proxy caches previews by URL.
- */
-function versionedUrl(key: string, file: string): null | string {
-	const url = getPublicUrl(key);
-	const version = createHash('sha1').update(readFileSync(file)).digest('hex').slice(0, 10);
-
-	return url && `${url}?v=${version}`;
-}
-
-/** Whether a video is taller than wide, like a phone's. */
-function isPortrait(mp4: string): boolean {
-	const [width, height] = run('ffprobe', [
-		'-v',
-		'error',
-		'-select_streams',
-		'v:0',
-		'-show_entries',
-		'stream=width,height',
-		'-of',
-		'csv=p=0',
-		mp4
-	])
-		.split(',')
-		.map(Number);
-
-	return height > width;
-}
-
-/**
- * One preview, or a table of them when the script has several tests, each headed by its
- * test's title: up to four portrait videos to a row, or two landscape ones, so each stays
- * large enough to read.
- */
-function demoSection(
-	links: { gif: string; mp4: string; title: string }[],
-	sha: string,
-	columns: number
-): string {
-	const preview = ({ gif, mp4, title }: (typeof links)[number]) =>
-		`[![${title.replace(/[[\]|]/g, '')}](${gif})](${mp4})`;
-	const cell = (text: string) => text.replace(/\|/g, '\\|');
-	const rows = Array.from({ length: Math.ceil(links.length / columns) }, (_, i) =>
-		links.slice(i * columns, (i + 1) * columns)
-	);
-	const pad = (cells: string[]) => [...cells, ...Array(columns - cells.length).fill(' ')];
-	const body =
-		links.length === 1
-			? [preview({ ...links[0], title: 'Demo' })]
-			: rows.flatMap((row, i) => [
-					// a table has one header row, so later rows title their videos in bold
-					`| ${pad(row.map((l) => (i === 0 ? cell(l.title) : `**${cell(l.title)}**`))).join(' | ')} |`,
-					...(i === 0 ? [`|${Array(columns).fill('---').join('|')}|`] : []),
-					`| ${pad(row.map(preview)).join(' | ')} |`
-				]);
-	const note =
-		links.length === 1 ? 'the preview for the full video' : 'a preview for its full video';
-
-	return [
-		SECTION_START,
-		...body,
-		'',
-		`Recorded at ${sha.slice(0, 10)}; click ${note}.`,
-		SECTION_END
-	].join('\n');
-}
-
-/** Replaces the managed demo section, or adds a `## Demo` section before the details. */
-function withDemoSection(body: string, section: string): string {
-	const start = body.indexOf(SECTION_START);
-	const end = body.indexOf(SECTION_END);
-
-	if (start !== -1 && end > start) {
-		return body.slice(0, start) + section + body.slice(end + SECTION_END.length);
-	}
-
-	const block = `## Demo\n\n${section}\n\n`;
-	const anchor = body.search(/^## (Additional information|Requirements)\b/m);
-
-	return anchor === -1
-		? `${body.trimEnd()}\n\n${block}`
-		: body.slice(0, anchor) + block + body.slice(anchor);
-}
-
-async function recordPr(number: string, trustedSha?: string): Promise<void> {
-	const pr = JSON.parse(
-		run('gh', ['pr', 'view', number, '--repo', REPO, '--json', 'author,body,headRefOid'])
-	) as { author: { login: string }; body: string; headRefOid: string };
-	const source = DEMO_BLOCK.exec(pr.body)?.[1];
-
-	if (!source) throw new Error(`PR #${number} has no \`\`\`ts demo block in its description`);
-
-	const sha = pr.headRefOid;
-
-	// the PR's code and demo script run on this machine, with the gh and hf logins,
-	// so someone else's PR only runs at a head commit you've read and passed to --trust
-	if (pr.author.login !== run('gh', ['api', 'user', '--jq', '.login'])) {
-		if (!trustedSha) {
-			throw new Error(
-				`PR #${number} is by ${pr.author.login}, and recording it runs its code here: ` +
-					`read its diff and demo block, then run again with --trust ${sha.slice(0, 10)}`
-			);
-		}
-
-		if (trustedSha.length < 7 || !sha.startsWith(trustedSha)) {
-			throw new Error(`PR #${number} head is ${sha.slice(0, 10)}, not the trusted ${trustedSha}`);
-		}
-	}
-
-	const worktree = join(tmpdir(), `llama-ui-demo-pr-${number}`);
-
-	run('git', ['fetch', '--no-tags', `https://github.com/${REPO}.git`, `pull/${number}/head`]);
-
-	if (run('git', ['rev-parse', 'FETCH_HEAD']) !== sha) {
-		throw new Error(`PR #${number} head moved while fetching, run again`);
-	}
-
-	rmSync(worktree, { force: true, recursive: true });
-	run('git', ['worktree', 'prune']);
-	run('git', ['worktree', 'add', '--detach', worktree, sha]);
-	symlinkSync(join(UI_DIR, 'node_modules'), join(worktree, 'ui/apps/chat/node_modules'));
-
-	const name = `pr-${number}`;
-	const script = writeDemoScript(name, source);
-
-	try {
-		const videos = (await record([script], join(worktree, 'ui/apps/chat'))).map((video) => ({
-			...video,
-			gif: makePreview(video.mp4)
-		}));
-		const storage = getDemoStorage();
-
-		for (const { gif, mp4 } of videos) console.log(`\nvideo:   ${mp4}\npreview: ${gif}`);
-
-		if (!storage) {
-			console.log('DEMO_STORAGE is not set: drag the mp4 into the PR description.');
-
-			return;
-		}
-
-		const prefix = `videos/pr/${number}/${sha.slice(0, 10)}`;
-		// a script with several tests gets <sha>-1.mp4, <sha>-2.mp4 and so on
-		const keys = videos.map((_, i) => (videos.length === 1 ? prefix : `${prefix}-${i + 1}`));
-
-		upload(storage, { [`${prefix}.demo.ts`]: script });
-		videos.forEach(({ gif, mp4 }, i) => {
-			upload(storage, { [`${keys[i]}.gif`]: gif, [`${keys[i]}.mp4`]: mp4 });
-		});
-
-		if (!getPublicUrl(prefix)) {
-			console.log('DEMO_STORAGE_PUBLIC_URL is not set: not linking the video in the PR.');
-
-			return;
-		}
-
-		const links = videos.map(({ gif, mp4, title }, i) => ({
-			gif: versionedUrl(`${keys[i]}.gif`, gif) ?? '',
-			mp4: versionedUrl(`${keys[i]}.mp4`, mp4) ?? '',
-			title
-		}));
-
-		execFileSync('gh', ['pr', 'edit', number, '--repo', REPO, '--body-file', '-'], {
-			cwd: UI_DIR,
-			input: withDemoSection(
-				pr.body,
-				demoSection(links, sha, Math.min(links.length, isPortrait(videos[0].mp4) ? 4 : 2))
-			),
-			stdio: ['pipe', 'inherit', 'inherit']
-		});
-		console.log(`linked the demo in https://github.com/${REPO}/pull/${number}`);
-	} finally {
-		rmSync(script, { force: true });
-		run('git', ['worktree', 'remove', '--force', worktree]);
-	}
-}
-
-async function recordDocs(): Promise<void> {
-	const storage = getDemoStorage();
-
-	if (!storage) throw new Error('DEMO_STORAGE is not set: docs demo scripts are read from it');
-
-	const downloaded = join(RUNS_DIR, 'docs-source');
-
-	rmSync(downloaded, { force: true, recursive: true });
-
-	if (!storage.downloadDir('scripts/docs', downloaded)) {
-		throw new Error('no scripts/docs/*.demo.ts in DEMO_STORAGE');
-	}
-
-	const scripts = readdirSync(downloaded)
-		.filter((f) => f.endsWith('.demo.ts'))
-		.map((f) =>
-			writeDemoScript(basename(f, '.demo.ts'), readFileSync(join(downloaded, f), 'utf8'))
-		);
-
-	try {
-		const videos = await record(scripts);
-
-		for (const { mp4 } of videos) {
-			const name = basename(mp4, '.mp4');
-
-			upload(storage, {
-				[`videos/docs/${name}.gif`]: makePreview(mp4),
-				[`videos/docs/${name}.mp4`]: mp4
-			});
-		}
-	} finally {
-		rmSync(RUNS_DIR, { force: true, recursive: true });
-	}
-}

 /** Writes the built-in traces to demo/traces/ and uploads them to the traces dataset. */
 function writeTraces(): void {
@@ -396,16 +52,10 @@ function writeTraces(): void {
 	);
 }

-const [command, arg, ...flags] = process.argv.slice(2);
-const trustIndex = flags.indexOf('--trust');
-
-if (command === 'pr' && arg) {
-	await recordPr(arg, trustIndex === -1 ? undefined : flags[trustIndex + 1]);
-} else if (command === 'docs') {
-	await recordDocs();
-} else if (command === 'traces') {
-	writeTraces();
-} else {
-	console.error('usage: node demo/cli.ts pr <number> [--trust <sha>] | docs | traces');
-	process.exit(1);
-}
+await runDemoCli({
+	commands: { traces: writeTraces },
+	demoDir: DEMO_DIR,
+	dir: resolve(DEMO_DIR, '..'),
+	// Chat builds Llama UI from source, and DEMO_STORYBOOK=ui runs its Storybook
+	linkNodeModules: ['../../lib/ui']
+});
diff --git a/ui/apps/chat/demo/fixtures/llama-server.ts b/ui/apps/chat/demo/fixtures/llama-server.ts
new file mode 100644
index 000000000..6cc985fce
--- /dev/null
+++ b/ui/apps/chat/demo/fixtures/llama-server.ts
@@ -0,0 +1,63 @@
+/**
+ * A canned llama-server for demos and e2e checks that should not need a real one, or a model:
+ * routes its endpoints in the browser, so nothing reaches a server and no model loads.
+ */
+
+import type { BrowserContext, Page } from '@playwright/test';
+
+export interface MockServerOptions {
+	/** Model ids the router lists, all loaded. */
+	models?: string[];
+	/** The assistant's reply to every message, streamed a word per chunk. */
+	reply?: string;
+}
+
+function completionStream(reply: string): string {
+	const words = reply.match(/\S+\s*/g) ?? [];
+	const chunk = (delta: object, finish: null | string = null) =>
+		`data: ${JSON.stringify({ choices: [{ delta, finish_reason: finish, index: 0 }], object: 'chat.completion.chunk' })}\n\n`;
+
+	return [
+		chunk({ role: 'assistant' }),
+		...words.map((word) => chunk({ content: word })),
+		chunk({}, 'stop'),
+		'data: [DONE]\n\n'
+	].join('');
+}
+
+/** Call before the page opens; a demo sets `test.use({ mockServer: {...} })` instead. */
+export async function mockLlamaServer(
+	target: BrowserContext | Page,
+	{
+		models = ['ggml-org/gemma-3-4b-it-GGUF:Q4_K_M'],
+		reply = 'Hello! How can I help?'
+	}: MockServerOptions = {}
+): Promise<void> {
+	const data = models.map((id) => ({
+		id,
+		object: 'model',
+		owned_by: 'llamacpp',
+		status: { value: 'loaded' }
+	}));
+
+	await target.route(/\/props(\?|$)/, (route) =>
+		route.fulfill({
+			json: { build_info: 'mock', model_path: 'none', role: 'router', ui_settings: {} }
+		})
+	);
+	await target.route(/\/(v1\/)?models(\?|$)/, (route) =>
+		route.fulfill({ json: { data, object: 'list' } })
+	);
+	await target.route(/\/models\/(load|unload)$/, (route) =>
+		route.fulfill({ json: { success: true } })
+	);
+	await target.route(/\/models\/sse$/, (route) => route.abort());
+	await target.route(/\/tools(\?|$)/, (route) => route.fulfill({ json: [] }));
+	await target.route(/\/v1\/streams\/lookup$/, (route) => route.fulfill({ status: 404 }));
+	await target.route(/\/v1\/chat\/completions$/, (route) =>
+		route.fulfill({
+			body: completionStream(reply),
+			headers: { 'content-type': 'text/event-stream' }
+		})
+	);
+}
diff --git a/ui/apps/chat/demo/helpers.ts b/ui/apps/chat/demo/helpers.ts
index f814922f3..28c199558 100644
--- a/ui/apps/chat/demo/helpers.ts
+++ b/ui/apps/chat/demo/helpers.ts
@@ -1,115 +1,21 @@
+/**
+ * Llama Chat's demo fixtures on the harness in ui/lib/demo: settings, conversations and a mocked
+ * llama-server set the scene, or a Storybook story stands in for the app.
+ */
+
 import { demoMcpServerSettings } from './fixtures/demo-config.ts';
+import { mockLlamaServer, type MockServerOptions } from './fixtures/llama-server.ts';
 import { generateTrace } from './fixtures/traces.ts';
-import { ScreencastRecorder } from './recorder.ts';
-import { type CDPSession, type Locator, type Page, test as base } from '@playwright/test';
+import { Demo, prepareDemoPage, recordDemo } from '@ggml-org/llama-demo';
+import { type Locator, type Page, test as base, type TestInfo } from '@playwright/test';
 import { execFileSync } from 'node:child_process';
-import {
-	appendFileSync,
-	mkdirSync,
-	mkdtempSync,
-	readFileSync,
-	rmSync,
-	writeFileSync
-} from 'node:fs';
-import { tmpdir } from 'node:os';
-import { basename, join, resolve } from 'node:path';
+import { mkdirSync, readFileSync, writeFileSync } from 'node:fs';
+import { join, resolve } from 'node:path';

 const VIDEOS_DIR = resolve(import.meta.dirname, 'videos');
+const BRAND_DIR = resolve(import.meta.dirname, '../node_modules/@ggml-org/llama-brand');
 /** How long a demo waits for the app to be ready before it starts recording. */
 const APP_READY_TIMEOUT_MS = 90000;
-/** How far below the viewport's top a pinch has to start for Chromium to zoom at all. */
-const ZOOM_TOP_INSET_PX = 64;
-
-/**
- * Draws a fake cursor and click ripples, since recorded videos don't include
- * the OS pointer, and a fingertip per touch, so a pinch shows as two fingers.
- * Runs in the page via addInitScript.
- */
-function installCursorOverlay(): void {
-	const mount = () => {
-		const style = document.createElement('style');
-
-		style.textContent = `
-			#demo-cursor { position: fixed; top: 0; left: 0; z-index: 2147483647; pointer-events: none;
-				width: 22px; height: 22px; margin: -3px 0 0 -3px; transition: transform 80ms ease-out; }
-			#demo-cursor.down { transform: scale(0.85); }
-			.demo-ripple { position: fixed; z-index: 2147483646; pointer-events: none; width: 36px; height: 36px;
-				margin: -18px 0 0 -18px; border-radius: 50%; background: rgba(59, 130, 246, 0.35);
-				animation: demo-ripple 450ms ease-out forwards; }
-			@keyframes demo-ripple { from { transform: scale(0.3); opacity: 1; } to { transform: scale(1.4); opacity: 0; } }
-			#demo-caption { position: fixed; left: 50%; top: 72px; z-index: 2147483647; pointer-events: none;
-				transform: translate(-50%, -8px); opacity: 0; transition: opacity 200ms ease, transform 200ms ease;
-				max-width: 80%; padding: 10px 18px; border-radius: 10px; background: rgba(17, 17, 17, 0.88);
-				color: #fff; font: 500 18px/1.4 system-ui, sans-serif; text-align: center; }
-			#demo-caption.visible { opacity: 1; transform: translate(-50%, 0); }
-			.demo-finger { position: fixed; z-index: 2147483646; pointer-events: none; width: 40px; height: 40px;
-				margin: -20px 0 0 -20px; border-radius: 50%; background: rgba(59, 130, 246, 0.3);
-				border: 2px solid rgba(59, 130, 246, 0.55); transition: opacity 200ms ease; }
-		`;
-		document.head.appendChild(style);
-
-		const cursor = document.createElement('div');
-
-		cursor.id = 'demo-cursor';
-		cursor.innerHTML = `<svg viewBox="0 0 24 24" width="22" height="22"><path d="M4 2l16 10.5-7 1.5-3.5 6.5z"
-			fill="#111" stroke="#fff" stroke-width="1.5" stroke-linejoin="round"/></svg>`;
-		document.documentElement.appendChild(cursor);
-
-		const caption = document.createElement('div');
-
-		caption.id = 'demo-caption';
-		document.documentElement.appendChild(caption);
-
-		document.addEventListener(
-			'mousemove',
-			(e) => (cursor.style.translate = `${e.clientX}px ${e.clientY}px`),
-			true
-		);
-		document.addEventListener(
-			'mousedown',
-			(e) => {
-				cursor.classList.add('down');
-				const ripple = document.createElement('div');
-
-				ripple.className = 'demo-ripple';
-				ripple.style.left = `${e.clientX}px`;
-				ripple.style.top = `${e.clientY}px`;
-				document.documentElement.appendChild(ripple);
-				setTimeout(() => ripple.remove(), 500);
-			},
-			true
-		);
-		document.addEventListener('mouseup', () => cursor.classList.remove('down'), true);
-
-		const fingers: HTMLDivElement[] = [];
-		const placeFingers = (e: TouchEvent) => {
-			Array.from(e.touches).forEach((touch, i) => {
-				const finger = (fingers[i] ??= Object.assign(document.createElement('div'), {
-					className: 'demo-finger'
-				}));
-
-				finger.style.left = `${touch.clientX}px`;
-				finger.style.top = `${touch.clientY}px`;
-				finger.style.opacity = '1';
-				document.documentElement.appendChild(finger);
-			});
-			fingers.slice(e.touches.length).forEach((finger) => (finger.style.opacity = '0'));
-		};
-
-		for (const type of ['touchstart', 'touchmove', 'touchend', 'touchcancel']) {
-			document.addEventListener(type, placeFingers as EventListener, {
-				capture: true,
-				passive: true
-			});
-		}
-	};
-
-	if (document.readyState === 'loading') {
-		document.addEventListener('DOMContentLoaded', mount);
-	} else {
-		mount();
-	}
-}

 /** Seeds UI settings once per demo, so later reloads keep what the demo changed. */
 function seedSettings(config: Record<string, unknown>): void {
@@ -120,364 +26,20 @@ function seedSettings(config: Record<string, unknown>): void {
 	}
 }

-/**
- * Swaps the page's microphone for one that hears only what `window.demoSpeak` plays into it,
- * silence otherwise. Chromium's fake capture device crashes the page, so voice input is
- * recorded with this instead. Runs in the page.
- */
-function installFakeMicrophone(): void {
-	const context = new AudioContext();
-	const output = context.createMediaStreamDestination();
-
-	navigator.mediaDevices.getUserMedia = async (constraints) => {
-		if (!constraints?.audio || constraints.video) {
-			throw new DOMException('demo: only the microphone is faked', 'NotSupportedError');
-		}
-
-		await context.resume();
-
-		// each opening gets its own tracks, so a recording that stops them leaves the source on
-		return new MediaStream(output.stream.getAudioTracks().map((track) => track.clone()));
-	};
-
-	Object.assign(window, {
-		demoSpeak: async (wavBase64: string) => {
-			const bytes = Uint8Array.from(atob(wavBase64), (c) => c.charCodeAt(0));
-			const source = context.createBufferSource();
-
-			source.buffer = await context.decodeAudioData(bytes.buffer);
-			source.connect(output);
-			await context.resume();
-			await new Promise((done) => {
-				source.onended = done;
-				source.start();
-			});
-		}
-	});
-}
-
-/** `text` read by a synthetic voice, as a base64 WAV. Uses macOS `say`. */
-function synthesizeSpeech(text: string, voice: string): string {
-	const dir = mkdtempSync(join(tmpdir(), 'demo-speech-'));
-	const file = join(dir, 'speech.wav');
-
-	try {
-		execFileSync('say', [
-			'-v',
-			voice,
-			'-o',
-			file,
-			'--file-format=WAVE',
-			'--data-format=LEI16@24000',
-			text
-		]);
-
-		return readFileSync(file).toString('base64');
-	} catch (error) {
-		throw new Error(`demo: speak() needs macOS \`say\` with the voice ${voice}`, {
-			cause: error
-		});
-	} finally {
-		rmSync(dir, { force: true, recursive: true });
-	}
-}
-
-/** Seeded randomness, so a demo moves the same way on every recording. */
-function createRandom(seed: string): () => number {
-	let state = [...seed].reduce((h, c) => Math.imul(h ^ c.charCodeAt(0), 2654435761), 1);
-
-	return () => {
-		state = (state + 0x6d2b79f5) | 0;
-
-		let t = Math.imul(state ^ (state >>> 15), 1 | state);
-
-		t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
-
-		return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
-	};
-}
-
-const easeInOut = (t: number) => (t < 0.5 ? 4 * t * t * t : 1 - (-2 * t + 2) ** 3 / 2);
-
-/**
- * Drives the page like a person: the cursor glides along a slight arc with
- * Fitts-like durations, settles briefly before pressing, and typing and pauses
- * vary a little.
- */
-export class Demo {
-	private cdp: CDPSession | undefined;
-	private readonly page: Page;
-	private readonly random: () => number;
-	private x = 0;
-	private y = 0;
-
-	/** Shows a caption at the top of the frame for `ms`, clear of the chat form. */
-	async caption(text: string, ms = 2200): Promise<void> {
-		await this.showCaption(text);
-		await this.page.waitForTimeout(ms);
-		await this.hideCaption();
-	}
-
-	async click(target: Locator, ms = 400): Promise<void> {
-		await this.moveTo(target);
-		await this.page.waitForTimeout(this.between(80, 160));
-		await this.page.mouse.down();
-		await this.page.waitForTimeout(this.between(50, 90));
-		await this.page.mouse.up();
-		await this.pause(ms);
-	}
-
-	constructor(page: Page, seed: string) {
-		this.page = page;
-		this.random = createRandom(seed);
-
-		const viewport = page.viewportSize();
-
-		this.x = (viewport?.width ?? 0) / 2;
-		this.y = (viewport?.height ?? 0) / 2;
-	}
-
-	/**
-	 * Touches `target` for `ms` and lifts: a tap, or with a longer `ms` a press-and-hold, as a
-	 * phone's held rows ask for. It needs a touch device (`hasTouch`), and shows a fingertip.
-	 */
-	async hold(target: Locator, ms = 900, after = 500): Promise<void> {
-		await target.scrollIntoViewIfNeeded();
-
-		const { x, y } = await this.center(target);
-		const cdp = await this.session();
-
-		await this.page.waitForTimeout(this.between(60, 140));
-		await cdp.send('Input.dispatchTouchEvent', { touchPoints: [{ x, y }], type: 'touchStart' });
-		await this.page.waitForTimeout(ms);
-		await cdp.send('Input.dispatchTouchEvent', { touchPoints: [], type: 'touchEnd' });
-		await this.liftFingers();
-		this.x = x;
-		this.y = y;
-		await this.pause(after);
-	}
-
-	async hover(target: Locator, ms = 350): Promise<void> {
-		await this.moveTo(target);
-		await this.pause(ms);
-	}
-
-	/**
-	 * Gives the page a microphone that hears only what `speak` says, and allows the page to
-	 * use it. Call it before the microphone is first used.
-	 */
-	async microphone(): Promise<void> {
-		await this.page.context().grantPermissions(['microphone']);
-		await this.page.evaluate(installFakeMicrophone);
-	}
-
-	/** Glides the cursor to a point near the center of `target`. */
-	async moveTo(target: Locator): Promise<void> {
-		await target.scrollIntoViewIfNeeded();
-		const box = await target.boundingBox();
-
-		if (!box) throw new Error(`demo: ${target} has no bounding box`);
-
-		const x = box.x + box.width * this.between(0.4, 0.6);
-		const y = box.y + box.height * this.between(0.4, 0.6);
-		const dx = x - this.x;
-		const dy = y - this.y;
-		const distance = Math.hypot(dx, dy);
-		const duration = 110 + 55 * Math.log2(distance / 40 + 1);
-		// bow the path a little to one side, like a wrist turning
-		const bow = distance * this.between(-0.08, 0.08);
-		const fromX = this.x;
-		const fromY = this.y;
-		const started = Date.now();
-
-		for (;;) {
-			const t = Math.min((Date.now() - started) / duration, 1);
-			const p = easeInOut(t);
-			const arc = Math.sin(Math.PI * p) * bow;
-
-			this.x = fromX + dx * p - (dy / (distance || 1)) * arc;
-			this.y = fromY + dy * p + (dx / (distance || 1)) * arc;
-			await this.page.mouse.move(this.x, this.y);
-
-			if (t === 1) break;
-
-			await this.page.waitForTimeout(8);
-		}
-	}
-
-	/** Waits about `ms`, varied by up to 15% so pauses don't feel metronomic. */
-	async pause(ms = 800): Promise<void> {
-		await this.page.waitForTimeout(ms * this.between(0.85, 1.15));
-	}
-
-	async press(key: string, ms = 600): Promise<void> {
-		await this.page.keyboard.press(key);
-		await this.pause(ms);
-	}
-
-	/** Scrolls the wheel over `target` by `dy` pixels (negative scrolls up), in small steps like a trackpad. */
-	async scroll(target: Locator, dy: number, ms = 500): Promise<void> {
-		await this.moveTo(target);
-
-		const step = Math.sign(dy) * 40;
-
-		for (let done = 0; Math.abs(done) < Math.abs(dy); done += step) {
-			await this.page.mouse.wheel(0, step);
-			await this.page.waitForTimeout(16);
-		}
-
-		await this.pause(ms);
-	}
-
-	/**
-	 * Says `text` into the microphone from `microphone` in a synthetic voice (macOS `say`), and
-	 * returns once it is said. The words show as a caption, since the video has no sound.
-	 */
-	async speak(text: string, voice = 'Samantha', ms = 400): Promise<void> {
-		const wav = synthesizeSpeech(text, voice);
-
-		await this.showCaption(`“${text}”`);
-		await this.page.evaluate(
-			(base64) =>
-				(window as unknown as { demoSpeak(wav: string): Promise<void> }).demoSpeak(base64),
-			wav
-		);
-		await this.hideCaption();
-		await this.pause(ms);
-	}
-
-	/** Taps `target` with a fingertip, on a touch device. */
-	tap(target: Locator, after = 500): Promise<void> {
-		return this.hold(target, this.between(60, 110), after);
-	}
-
-	/** Types quickly with uneven key timing, a little slower after spaces and punctuation. */
-	async type(target: Locator, text: string, ms = 500): Promise<void> {
-		await this.click(target, 200);
-
-		for (const char of text) {
-			await this.page.keyboard.type(char);
-			await this.page.waitForTimeout(
-				this.between(15, 45) + (/[\s.,!?]/.test(char) ? this.between(20, 60) : 0)
-			);
-		}
-
-		await this.pause(ms);
-	}
-
-	/**
-	 * Pinches in on `target`, a control or a point in the viewport, holds about `ms`, and pinches
-	 * back out to 1x: a two-finger zoom onto a detail too small to read in the frame. On a touch
-	 * device the fingertips show.
-	 */
-	async zoom(target: Locator | { x: number; y: number }, scale = 2.5, ms = 1400): Promise<void> {
-		const point = 'x' in target ? target : await this.center(target);
-		// a pinch anchored in the viewport's top band does not zoom at all
-		const at = { x: point.x, y: Math.max(point.y, ZOOM_TOP_INSET_PX) };
-		const viewport = this.page.viewportSize() ?? { height: 0, width: 0 };
-		const middle = { x: viewport.width / 2, y: viewport.height / 2 };
-
-		await this.pinch(at, scale, 1400);
-
-		// One near the bottom edge overshoots its ratio, and a pinch there again misses too. A small
-		// pinch from the middle evens it out, drawing the detail toward the middle, so it stays in view
-		const reached = await this.pageScale();
-
-		if (Math.abs(reached / scale - 1) > 0.03) await this.pinch(middle, scale / reached, 1400);
-
-		await this.liftFingers();
-		await this.pause(ms);
-
-		// back to exactly 1x, which the next gesture needs, in one quick pinch from the middle of
-		// the viewport, and another for what is left when one lands short
-		for (let tries = 0; ; tries++) {
-			const current = await this.pageScale();
-
-			if (current <= 1.001) break;
-
-			if (tries === 4) throw new Error(`demo: zoom stuck at ${current.toFixed(3)}x`);
-
-			await this.pinch(middle, 1 / current, 1800);
-		}
-
-		await this.liftFingers();
-		await this.pause(200);
-	}
-
-	private between(min: number, max: number): number {
-		return min + (max - min) * this.random();
-	}
-
-	private async center(target: Locator): Promise<{ x: number; y: number }> {
-		const box = await target.boundingBox();
-
-		if (!box) throw new Error(`demo: ${target} has no bounding box`);
-
-		return { x: box.x + box.width / 2, y: box.y + box.height / 2 };
-	}
-
-	private async hideCaption(): Promise<void> {
-		await this.page.evaluate(() =>
-			document.getElementById('demo-caption')?.classList.remove('visible')
-		);
-		await this.page.waitForTimeout(250);
-	}
-
-	/** A pinch that reaches the screen's edge can end without its last touchend reaching the page. */
-	private async liftFingers(): Promise<void> {
-		await this.page.evaluate(() =>
-			document
-				.querySelectorAll<HTMLElement>('.demo-finger')
-				.forEach((finger) => (finger.style.opacity = '0'))
-		);
-	}
-
-	private pageScale(): Promise<number> {
-		return this.page.evaluate(() => window.visualViewport?.scale ?? 1);
-	}
-
-	/**
-	 * A two-finger pinch by `factor` around `at`, in viewport pixels. While zoomed in, the gesture
-	 * reads its position in page-scale units, so it is divided by the scale the page is at.
-	 */
-	private async pinch(at: { x: number; y: number }, factor: number, speed: number): Promise<void> {
-		const cdp = await this.session();
-		const current = await this.pageScale();
-
-		await cdp.send('Input.synthesizePinchGesture', {
-			gestureSourceType: 'touch',
-			relativeSpeed: speed,
-			scaleFactor: factor,
-			x: at.x / current,
-			y: at.y / current
-		});
-	}
-
-	private async session(): Promise<CDPSession> {
-		this.cdp ??= await this.page.context().newCDPSession(this.page);
-
-		return this.cdp;
-	}
-
-	private async showCaption(text: string): Promise<void> {
-		await this.page.evaluate((t) => {
-			const el = document.getElementById('demo-caption');
-
-			if (!el) return;
-
-			el.textContent = t;
-			el.classList.add('visible');
-		}, text);
-	}
-}
-
 interface DemoOptions {
 	/** Empty conversations added to the library before the demo starts, e.g. to fill a list. */
 	chats: number;
+	/** Answers llama-server's endpoints in the browser instead (fixtures/llama-server.ts), so no model loads. */
+	mockServer: MockServerOptions | null;
 	/** Path the demo starts from. */
 	startPath: string;
 	/** Extra UI settings merged into the seeded config. */
 	settings: Record<string, unknown>;
+	/**
+	 * Storybook story id (`?path=/story/<id>`) recorded instead of Llama Chat, from the Storybook
+	 * that DEMO_STORYBOOK starts: `ui` (Llama UI) or `chat` (Llama Chat).
+	 */
+	story: string;
 	/**
 	 * Conversations imported before the demo starts: built-in traces from
 	 * fixtures/traces.ts, or `<name>.jsonl` files from DEMO_TRACES_DATASET.
@@ -506,7 +68,7 @@ function loadTrace(name: string, dir: string): string {
 }

 /** Imports conversations through Settings > Data, like a user would. */
-async function importTraces(page: Page, file: string): Promise<void> {
+export async function importTraces(page: Page, file: string): Promise<void> {
 	// the expanded sidebar adds the shortcut to the name
 	const settings = page.getByRole('button', { name: /^Settings(\s|$)/ }).first();
 	const reachable = (target: Locator) =>
@@ -629,87 +191,91 @@ async function seedChats(page: Page, count: number): Promise<void> {
 	);
 }

-export const test = base.extend<DemoOptions & { demo: Demo }>({
-	chats: [0, { option: true }],
-	demo: async ({ page }, use, testInfo) => {
-		await use(new Demo(page, `${testInfo.file}:${testInfo.title}`));
-	},
-
-	page: async ({ chats, page, settings, startPath, traces }, use, testInfo) => {
-		await page.addInitScript(installCursorOverlay);
-		await page.addInitScript(seedSettings, {
-			mcpServers: JSON.stringify(demoMcpServerSettings()),
-			...settings
-		});
-
-		if (traces.length > 0) {
-			const dir = testInfo.outputPath('traces');
-			const file = join(dir, 'import.jsonl');
-
-			mkdirSync(dir, { recursive: true });
-			writeFileSync(file, traces.map((name) => loadTrace(name, dir)).join('\n'));
-			await page.goto('/');
-			await page
-				.getByRole('textbox', { name: 'Type a message...' })
-				.waitFor({ timeout: APP_READY_TIMEOUT_MS });
-			await importTraces(page, file);
-		}
-
-		if (chats > 0) await seedChats(page, chats);
-
-		await page.goto(startPath);
+/** Seeds settings, imports the traces, adds the chats and opens `startPath` in Llama Chat. */
+async function openChat(
+	page: Page,
+	settings: Record<string, unknown>,
+	startPath: string,
+	traces: string[],
+	chats: number,
+	testInfo: TestInfo
+): Promise<void> {
+	await page.addInitScript(seedSettings, {
+		mcpServers: JSON.stringify(demoMcpServerSettings()),
+		...settings
+	});

-		// a hash route after the import doesn't reload, which the conversations list needs
-		if (traces.length > 0 || chats > 0) await page.reload();
+	if (traces.length > 0) {
+		const dir = testInfo.outputPath('traces');
+		const file = join(dir, 'import.jsonl');

-		// a fresh checkout's dev server optimizes its dependencies on the first load and reloads the
-		// page, which can take well past an action's timeout; the recording has not started yet
+		mkdirSync(dir, { recursive: true });
+		writeFileSync(file, traces.map((name) => loadTrace(name, dir)).join('\n'));
+		await page.goto('/');
 		await page
 			.getByRole('textbox', { name: 'Type a message...' })
 			.waitFor({ timeout: APP_READY_TIMEOUT_MS });
+		await importTraces(page, file);
+	}

-		const viewport = page.viewportSize();
+	if (chats > 0) await seedChats(page, chats);

-		if (viewport) await page.mouse.move(viewport.width / 2, viewport.height / 2);
+	await page.goto(startPath);

-		// let MCP connections and fonts settle before the recording starts
-		await page.waitForTimeout(1500);
+	// a hash route after the import doesn't reload, which the conversations list needs
+	if (traces.length > 0 || chats > 0) await page.reload();

-		const recorder = new ScreencastRecorder(testInfo.outputPath('frames'));
+	// a fresh checkout's dev server optimizes its dependencies on the first load and reloads the
+	// page, which can take well past an action's timeout; the recording has not started yet
+	await page
+		.getByRole('textbox', { name: 'Type a message...' })
+		.waitFor({ timeout: APP_READY_TIMEOUT_MS });
+}

-		await recorder.start(page);
-		await use(page);
-		await recorder.stop();
-		await page.close();
+export const test = base.extend<DemoOptions & { demo: Demo }>({
+	chats: [0, { option: true }],
+	demo: async ({ page }, use, testInfo) => {
+		await use(new Demo(page, `${testInfo.file}:${testInfo.title}`));
+	},
+	mockServer: [null, { option: true }],

-		if (testInfo.status !== testInfo.expectedStatus) return;
+	page: async (
+		{ chats, colorScheme, mockServer, page, settings, startPath, story, traces },
+		use,
+		testInfo
+	) => {
+		await prepareDemoPage(page, testInfo);

-		const file = basename(testInfo.file).replace(/\.demo\.ts$/, '');
-		const name = testInfo.title === 'demo' ? file : `${file}--${slugify(testInfo.title)}`;
-		const mp4 = resolve(VIDEOS_DIR, `${name}.mp4`);
+		if (story && !process.env.DEMO_STORYBOOK) {
+			throw new Error('demo: a story demo needs DEMO_STORYBOOK=ui (Llama UI) or chat (Llama Chat)');
+		}

-		mkdirSync(VIDEOS_DIR, { recursive: true });
-		recorder.encode(mp4);
-		// the CLI reads which videos a script made, in order, with their titles
-		appendFileSync(
-			resolve(VIDEOS_DIR, `${file}.videos.jsonl`),
-			`${JSON.stringify({ mp4, title: testInfo.title })}\n`
+		if (story) {
+			await page.goto(
+				`http://localhost:${process.env.DEMO_STORYBOOK_PORT}/iframe.html?id=${story}&viewMode=story`
+			);
+			await page.locator('#storybook-root > *').first().waitFor({ timeout: APP_READY_TIMEOUT_MS });
+		} else {
+			if (mockServer) await mockLlamaServer(page, mockServer);
+
+			await openChat(page, settings, startPath, traces, chats, testInfo);
+		}
+
+		await recordDemo(
+			page,
+			testInfo,
+			{ brandDir: BRAND_DIR, dark: colorScheme === 'dark', videosDir: VIDEOS_DIR },
+			() => use(page)
 		);
-		console.log(`demo video: ${mp4}`);
 	},

 	settings: [{}, { option: true }],

 	startPath: ['/', { option: true }],

+	story: ['', { option: true }],
+
 	traces: [[], { option: true }]
 });

 export { expect } from '@playwright/test';
-
-function slugify(text: string): string {
-	return text
-		.toLowerCase()
-		.replace(/[^a-z0-9]+/g, '-')
-		.replace(/^-|-$/g, '');
-}
diff --git a/ui/apps/chat/demo/playwright.config.ts b/ui/apps/chat/demo/playwright.config.ts
index bb5aeed08..5168bdfe1 100644
--- a/ui/apps/chat/demo/playwright.config.ts
+++ b/ui/apps/chat/demo/playwright.config.ts
@@ -16,6 +16,9 @@ if (existsSync(ENV_FILE)) process.loadEnvFile(ENV_FILE);
  *   DEMO_SERVER_ORIGIN  llama-server the UI proxies to (default: http://localhost:9931)
  *   DEMO_LLAMA_SERVER   llama-server binary started when none runs there (default: build/bin)
  *   DEMO_COLOR_SCHEME   light | dark (default: light)
+ *   DEMO_POLISH         0 for the plain screencast (default: the branded render, see polish.ts)
+ *   DEMO_STORYBOOK      ui | chat: also start that Storybook (Llama UI's or Llama Chat's), for story demos
+ *   DEMO_STORYBOOK_PORT port for it (default: 6007)
  */

 // Playwright clears outputDir when a run starts, so concurrent recordings each get
@@ -29,6 +32,10 @@ const SERVER_PORT = Number(new URL(SERVER_ORIGIN).port || 80);
 const LLAMA_SERVER =
 	process.env.DEMO_LLAMA_SERVER ??
 	resolve(import.meta.dirname, '../../../../build/bin/llama-server');
+const STORYBOOK = process.env.DEMO_STORYBOOK;
+
+// workers read it to open the stories
+process.env.DEMO_STORYBOOK_PORT ??= '6007';

 export const VIEWPORT = { height: 900, width: 1440 };
 /** Device pixel ratio the demos render and record at. */
@@ -82,7 +89,18 @@ export default defineConfig({
 			reuseExistingServer: true,
 			timeout: 120000,
 			url: `http://localhost:${UI_PORT}`
-		}
+		},
+		...(STORYBOOK
+			? [
+					{
+						command: `npx svelte-kit sync && npx storybook dev -p ${process.env.DEMO_STORYBOOK_PORT} --ci --exact-port`,
+						cwd: STORYBOOK === 'ui' ? resolve(UI_DIR, '../../lib/ui') : UI_DIR,
+						reuseExistingServer: true,
+						timeout: 120000,
+						url: `http://localhost:${process.env.DEMO_STORYBOOK_PORT}/iframe.html`
+					}
+				]
+			: [])
 	],
 	workers: 1
 });
diff --git a/ui/apps/chat/demo/recorder.ts b/ui/apps/chat/demo/recorder.ts
deleted file mode 100644
index 3d1faa9a4..000000000
--- a/ui/apps/chat/demo/recorder.ts
+++ /dev/null
@@ -1,109 +0,0 @@
-/**
- * Records a page through Chromium's screencast instead of Playwright's video,
- * which encodes VP8 at about 1 Mbit/s at 1x scale. Frames arrive at the page's
- * device pixel ratio, each with its timestamp, and are encoded once into an
- * H.264 mp4 (what GitHub accepts in PR descriptions).
- */
-
-import type { CDPSession, Page } from '@playwright/test';
-import { execFileSync } from 'node:child_process';
-import { mkdirSync, rmSync, writeFileSync } from 'node:fs';
-import { writeFile } from 'node:fs/promises';
-import { join } from 'node:path';
-
-const FPS = 60;
-const JPEG_QUALITY = 92;
-
-interface Frame {
-	file: string;
-	/** Seconds, on the same clock as Date.now(). */
-	time: number;
-}
-
-export class ScreencastRecorder {
-	private readonly dir: string;
-	private readonly frames: Frame[] = [];
-	private readonly pending: Promise<void>[] = [];
-	private session: CDPSession | undefined;
-	private stoppedAt = 0;
-
-	constructor(dir: string) {
-		this.dir = dir;
-	}
-
-	/** Encodes the frames, each held until the next one arrived (the screencast only sends changes). */
-	encode(mp4: string): void {
-		if (this.frames.length === 0) throw new Error('demo: the screencast captured no frames');
-
-		const list = this.frames.flatMap((frame, i) => {
-			const end = this.frames[i + 1]?.time ?? this.stoppedAt;
-
-			return [`file '${frame.file}'`, `duration ${Math.max(end - frame.time, 1 / FPS).toFixed(4)}`];
-		});
-		const listFile = join(this.dir, 'frames.txt');
-
-		// the concat demuxer ignores the last entry's duration unless the file is repeated
-		writeFileSync(listFile, [...list, `file '${this.frames.at(-1)!.file}'`, ''].join('\n'));
-		execFileSync(
-			'ffmpeg',
-			[
-				'-y',
-				'-loglevel',
-				'error',
-				'-f',
-				'concat',
-				'-safe',
-				'0',
-				'-i',
-				listFile,
-				'-vf',
-				`fps=${FPS},scale=trunc(iw/2)*2:trunc(ih/2)*2`,
-				'-c:v',
-				'libx264',
-				'-preset',
-				'slow',
-				'-crf',
-				'18',
-				'-pix_fmt',
-				'yuv420p',
-				'-movflags',
-				'+faststart',
-				mp4
-			],
-			{ stdio: 'inherit' }
-		);
-		rmSync(this.dir, { force: true, recursive: true });
-	}
-
-	async start(page: Page): Promise<void> {
-		const size = page.viewportSize();
-		const scale = await page.evaluate(() => window.devicePixelRatio);
-
-		rmSync(this.dir, { force: true, recursive: true });
-		mkdirSync(this.dir, { recursive: true });
-
-		this.session = await page.context().newCDPSession(page);
-		this.session.on('Page.screencastFrame', ({ data, metadata, sessionId }) => {
-			const file = join(this.dir, `${String(this.frames.length).padStart(6, '0')}.jpg`);
-
-			// acknowledged first: Chromium sends the next frame only after the ack
-			this.session?.send('Page.screencastFrameAck', { sessionId }).catch(() => {});
-			this.frames.push({ file, time: metadata.timestamp ?? Date.now() / 1000 });
-			this.pending.push(writeFile(file, Buffer.from(data, 'base64')));
-		});
-		await this.session.send('Page.startScreencast', {
-			everyNthFrame: 1,
-			format: 'jpeg',
-			maxHeight: size ? size.height * scale : undefined,
-			maxWidth: size ? size.width * scale : undefined,
-			quality: JPEG_QUALITY
-		});
-	}
-
-	async stop(): Promise<void> {
-		this.stoppedAt = Date.now() / 1000;
-		await this.session?.send('Page.stopScreencast').catch(() => {});
-		await this.session?.detach().catch(() => {});
-		await Promise.all(this.pending);
-	}
-}
diff --git a/ui/apps/chat/demo/storage.ts b/ui/apps/chat/demo/storage.ts
deleted file mode 100644
index def006d7b..000000000
--- a/ui/apps/chat/demo/storage.ts
+++ /dev/null
@@ -1,92 +0,0 @@
-/**
- * Storage targets for demo scripts and videos, picked by the scheme of the
- * DEMO_STORAGE URI:
- *
- *   hf://buckets/<owner>/<bucket>[/prefix]   Hugging Face bucket, via the `hf` CLI login
- *   file:///some/dir                         local or mounted directory
- */
-
-import { execFileSync } from 'node:child_process';
-import { copyFileSync, cpSync, existsSync, mkdirSync } from 'node:fs';
-import { dirname, join } from 'node:path';
-import { fileURLToPath } from 'node:url';
-
-export interface DemoStorage {
-	/** Copies every file under remote `dir` into local `target`; returns false when it has none. */
-	downloadDir(dir: string, target: string): boolean;
-	/** Copies local `file` to remote `key`. */
-	upload(file: string, key: string): void;
-}
-
-function joinKey(base: string, key: string): string {
-	return `${base.replace(/\/+$/, '')}/${key}`;
-}
-
-// plain fields: the CLI runs under Node's type stripping, which has no parameter properties
-class HfStorage implements DemoStorage {
-	private readonly base: string;
-
-	constructor(base: string) {
-		this.base = base;
-	}
-
-	downloadDir(dir: string, target: string): boolean {
-		mkdirSync(target, { recursive: true });
-
-		try {
-			execFileSync('hf', ['buckets', 'sync', joinKey(this.base, dir), target], {
-				stdio: 'inherit'
-			});
-		} catch {
-			return false;
-		}
-
-		return true;
-	}
-
-	upload(file: string, key: string): void {
-		execFileSync('hf', ['buckets', 'cp', file, joinKey(this.base, key)], { stdio: 'inherit' });
-	}
-}
-
-class FileStorage implements DemoStorage {
-	private readonly root: string;
-
-	constructor(root: string) {
-		this.root = root;
-	}
-
-	downloadDir(dir: string, target: string): boolean {
-		const source = join(this.root, dir);
-
-		if (!existsSync(source)) return false;
-
-		cpSync(source, target, { recursive: true });
-
-		return true;
-	}
-
-	upload(file: string, key: string): void {
-		const target = join(this.root, key);
-
-		mkdirSync(dirname(target), { recursive: true });
-		copyFileSync(file, target);
-	}
-}
-
-export function getDemoStorage(uri = process.env.DEMO_STORAGE): DemoStorage | null {
-	if (!uri) return null;
-
-	if (uri.startsWith('hf://')) return new HfStorage(uri);
-
-	if (uri.startsWith('file://')) return new FileStorage(fileURLToPath(uri));
-
-	throw new Error(`DEMO_STORAGE: unsupported scheme in "${uri}" (use hf:// or file://)`);
-}
-
-/** Public URL of a stored key, when DEMO_STORAGE_PUBLIC_URL is set. */
-export function getPublicUrl(key: string): string | null {
-	const base = process.env.DEMO_STORAGE_PUBLIC_URL;
-
-	return base ? joinKey(base, key) : null;
-}
diff --git a/ui/apps/chat/package-lock.json b/ui/apps/chat/package-lock.json
index d314541a4..2f400eaa0 100644
--- a/ui/apps/chat/package-lock.json
+++ b/ui/apps/chat/package-lock.json
@@ -21,6 +21,7 @@
 				"@eslint/compat": "2.1.1",
 				"@eslint/js": "10.0.1",
 				"@ggml-org/llama-brand": "0.1.0",
+				"@ggml-org/llama-demo": "file:../../lib/demo",
 				"@internationalized/date": "3.12.2",
 				"@lezer/highlight": "1.2.5",
 				"@lucide/svelte": "1.46.0",
@@ -100,6 +101,20 @@
 				"node": ">=20"
 			}
 		},
+		"../../lib/demo": {
+			"name": "@ggml-org/llama-demo",
+			"version": "0.1.0",
+			"dev": true,
+			"license": "MIT",
+			"devDependencies": {
+				"@playwright/test": "1.56.1",
+				"@types/node": "24.13.0",
+				"typescript": "6.0.3"
+			},
+			"engines": {
+				"node": ">=22.18"
+			}
+		},
 		"node_modules/@adobe/css-tools": {
 			"version": "4.5.0",
 			"resolved": "https://registry.npmjs.org/@adobe/css-tools/-/css-tools-4.5.0.tgz",
@@ -1083,6 +1098,10 @@
 			"dev": true,
 			"license": "CC-BY-NC-4.0 AND MIT AND OFL-1.1"
 		},
+		"node_modules/@ggml-org/llama-demo": {
+			"resolved": "../../lib/demo",
+			"link": true
+		},
 		"node_modules/@hono/node-server": {
 			"version": "2.1.6",
 			"resolved": "https://registry.npmjs.org/@hono/node-server/-/node-server-2.1.6.tgz",
diff --git a/ui/apps/chat/package.json b/ui/apps/chat/package.json
index 7f7f03d52..b0342802c 100644
--- a/ui/apps/chat/package.json
+++ b/ui/apps/chat/package.json
@@ -81,6 +81,8 @@
 		"@codemirror/view": "6.43.15",
 		"@eslint/compat": "2.1.1",
 		"@eslint/js": "10.0.1",
+		"@ggml-org/llama-brand": "0.1.0",
+		"@ggml-org/llama-demo": "file:../../lib/demo",
 		"@internationalized/date": "3.12.2",
 		"@lezer/highlight": "1.2.5",
 		"@lucide/svelte": "1.46.0",
@@ -119,7 +121,6 @@
 		"globals": "16.5.0",
 		"highlight.js": "11.11.1",
 		"http-server": "14.1.1",
-		"@ggml-org/llama-brand": "0.1.0",
 		"mdsvex": "0.12.7",
 		"mode-watcher": "1.1.0",
 		"pdfjs-dist": "5.4.54",
diff --git a/ui/apps/chat/tests/e2e/search-chats.e2e.ts b/ui/apps/chat/tests/e2e/search-chats.e2e.ts
new file mode 100644
index 000000000..e330ee4ad
--- /dev/null
+++ b/ui/apps/chat/tests/e2e/search-chats.e2e.ts
@@ -0,0 +1,25 @@
+import { mockLlamaServer } from '../../demo/fixtures/llama-server.ts';
+import { generateTrace } from '../../demo/fixtures/traces.ts';
+import { importTraces } from '../../demo/helpers.ts';
+import { expect, test } from '@playwright/test';
+import { writeFileSync } from 'node:fs';
+
+test('search finds a chat by its title and opens it', async ({ page }, testInfo) => {
+	const file = testInfo.outputPath('traces.jsonl');
+
+	writeFileSync(file, [generateTrace('long-chat'), generateTrace('agentic-debugging')].join('\n'));
+	await mockLlamaServer(page);
+	await page.goto('/');
+	await importTraces(page, file);
+	await page.reload();
+
+	await page.getByLabel('Expand navigation').click();
+	await page.getByRole('button', { name: /^Search/ }).click();
+
+	const search = page.getByRole('dialog', { name: 'Search' });
+
+	await search.getByRole('combobox', { name: 'Search' }).fill('flaky');
+	await search.getByRole('option', { name: /Fix the flaky cache tests/ }).click();
+
+	await expect(page.getByRole('main')).toContainText('All 48 cache tests pass now');
+});
diff --git a/ui/lib/demo/.gitignore b/ui/lib/demo/.gitignore
new file mode 100644
index 000000000..b3aa9e5bc
--- /dev/null
+++ b/ui/lib/demo/.gitignore
@@ -0,0 +1,5 @@
+node_modules
+
+# OS
+.DS_Store
+Thumbs.db
diff --git a/ui/lib/demo/LICENSE b/ui/lib/demo/LICENSE
new file mode 100644
index 000000000..50c59c51c
--- /dev/null
+++ b/ui/lib/demo/LICENSE
@@ -0,0 +1,21 @@
+MIT License
+
+Copyright (c) ggml
+
+Permission is hereby granted, free of charge, to any person obtaining a copy
+of this software and associated documentation files (the "Software"), to deal
+in the Software without restriction, including without limitation the rights
+to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
+copies of the Software, and to permit persons to whom the Software is
+furnished to do so, subject to the following conditions:
+
+The above copyright notice and this permission notice shall be included in all
+copies or substantial portions of the Software.
+
+THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
+IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
+FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
+AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
+LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
+OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
+SOFTWARE.
diff --git a/ui/lib/demo/README.md b/ui/lib/demo/README.md
new file mode 100644
index 000000000..da90f30b3
--- /dev/null
+++ b/ui/lib/demo/README.md
@@ -0,0 +1,141 @@
+# @ggml-org/llama-demo
+
+Scripted demo videos of the llama.cpp frontend apps, for pull requests and docs: a Playwright script drives the app like a person, and the harness records it and renders an mp4 with an animated GIF preview. It lives in llama.cpp at `ui/lib/demo`. It is a private package, not published to npm: an app in this repo adds it as a local dependency and imports it by name.
+
+- **PR demos** live in the PR description, as a `ts demo` code block.
+- **Docs demos** live in the storage target, under `scripts/docs/`.
+
+```text
+src/
+├── index.ts      the entry an app's demo fixtures import
+├── demo.ts       Demo: the cursor or fingertip, human timing, captions, voice, camera zooms
+├── recording.ts  prepareDemoPage and recordDemo, the recording round a demo
+├── recorder.ts   screencast recording and the plain mp4
+├── polish.ts     the render: window, ground, camera, captions
+├── cli.ts        runDemoCli: the pr and docs commands
+└── storage.ts    storage targets (hf://, file://)
+```
+
+Playwright is only a type here: the app passes in its page and test, so the harness loads no Playwright of its own, and runs with nothing installed in this folder. `npm ci` here is only for `npm run check`.
+
+## In an app
+
+Add it to the app's `devDependencies` as a local package, which npm links to this folder, so no copy is installed and nothing is published:
+
+```json
+"@ggml-org/llama-demo": "file:../../lib/demo"
+```
+
+Then import it by name: `@ggml-org/llama-demo` for the fixtures' parts (`Demo`, `prepareDemoPage`, `recordDemo`) and `@ggml-org/llama-demo/cli` for `runDemoCli`. Node runs its TypeScript sources directly, through the link.
+
+An app has a `demo/` folder with three files ([Llama Chat's](../../apps/chat/demo/README.md) is the example):
+
+- **`helpers.ts`**: a Playwright `test` with a `demo` fixture and a `page` fixture that sets the scene. The page fixture calls `prepareDemoPage(page, testInfo)` before the page loads, then `recordDemo(page, testInfo, options, () => use(page))` once the app is ready. `options` names `@ggml-org/llama-brand`'s folder, whether the page is dark, and where the videos go.
+- **`playwright.config.ts`**: the servers the app needs. `demo:pr` passes `DEMO_UI_DIR` (the PR's checkout of the app), `DEMO_UI_PORT` and `DEMO_STORYBOOK_PORT` to it.
+- **`cli.ts`**: `runDemoCli({ demoDir, dir, commands, linkNodeModules })`, with the app's own commands beside `pr` and `docs`.
+
+## Setup
+
+| Tool                                                 | Used for                                                                                     |
+| ---------------------------------------------------- | -------------------------------------------------------------------------------------------- |
+| Node 22.18+                                          | runs the TypeScript directly (type stripping)                                                |
+| `npx playwright install chromium`                    | the browser demos record in, with its sandbox on                                             |
+| `ffmpeg`                                             | mp4 encoding and the GIF preview                                                             |
+| `gh`, logged in                                      | reads the PR description and writes the `## Demo` section, so you need edit rights on the PR |
+| `hf`, logged in with a write token (`hf auth login`) | uploads to the bucket                                                                        |
+
+`gh` is only needed for `demo:pr`, and `hf` only with the bucket below. Without them, the video stays in the app's `demo/videos/`.
+
+The page is recorded through Chromium's screencast at the device pixel ratio the app's config sets (2x in Llama Chat) and 60 fps, starting once the page has settled. The video is then rendered from those frames at 1920x1080, or 1080x1920 for a portrait viewport (see [The render](#the-render)).
+
+### Hugging Face bucket (videos, previews, scripts)
+
+The bucket must be public, since GitHub loads the preview from it:
+
+```bash
+hf buckets create <owner>/llama-ui-demos
+```
+
+Then set it in the app's `.env`:
+
+```bash
+DEMO_STORAGE='hf://buckets/<owner>/llama-ui-demos'
+DEMO_STORAGE_PUBLIC_URL='https://huggingface.co/buckets/<owner>/llama-ui-demos/resolve'
+```
+
+Layout: `videos/pr/<number>/<sha>.{mp4,gif,demo.ts}`, `videos/docs/<name>.{mp4,gif}` and `scripts/docs/*.demo.ts` (the docs scripts). Without `DEMO_STORAGE_PUBLIC_URL`, videos are uploaded but not linked in the PR. `DEMO_STORAGE='file:///some/dir'` stores them in a local folder instead.
+
+Only Hugging Face buckets and `file://` folders are supported for now. S3, R2 or similar would be one more class in `storage.ts` (`upload` and `downloadDir`) plus the matching `DEMO_STORAGE_PUBLIC_URL`.
+
+## Recording a pull request
+
+Add the script to the PR description:
+
+````md
+<details>
+<summary>Demo script</summary>
+
+```ts demo
+test("demo", async ({ demo, page }) => {
+  await demo.click(page.getByRole("button", { exact: true, name: "Settings" }));
+  await demo.caption("What this shows");
+});
+```
+
+</details>
+````
+
+Then run `npm run demo:pr -- <number>` in the app. It checks out the PR head in a temporary worktree, records the script against it, uploads `videos/pr/<number>/<sha>.{mp4,gif,demo.ts}` and adds or updates a `## Demo` section in the PR description with the preview linking to the video. `DEMO_GITHUB_REPO` picks another repository, such as a fork.
+
+A PR by someone else runs its code and demo script on your machine, with your `gh` and `hf` logins, so `demo:pr` refuses it until you've read its diff and demo block and pass the head commit you read: `npm run demo:pr -- <number> --trust <sha>`. If the PR gets new commits, it refuses again.
+
+A large PR can show its changes in several shorter videos: each `test()` in the block is recorded as its own video (`<sha>-1.mp4`, `<sha>-2.mp4`, ...), and the `## Demo` section shows their previews in a table, each headed by its test's title: up to four portrait (phone) videos to a row, or two landscape ones. Helpers and `test.use` at the top of the block are shared by all of them.
+
+To say what each video shows, give its test a `description` annotation. When the tests have one, the table puts one video to a row, with its title and description beside it:
+
+```ts
+test(
+  "Taps instead of a cursor on a phone",
+  {
+    annotation: {
+      description: "A click shows as a fingertip tap.",
+      type: "description",
+    },
+  },
+  async ({ demo, page }) => {
+    // ...
+  },
+);
+```
+
+GitHub has no API for attachments, so for an inline player drag the mp4 from `demo/videos/` into the description instead.
+
+## Recording docs
+
+`npm run demo:docs` in the app records every `scripts/docs/*.demo.ts` from the storage target and uploads `videos/docs/<name>.{mp4,gif}`.
+
+## Writing a demo
+
+Scripts get `test` and `expect` from the app's `helpers.ts`. `demo.click`, `demo.hover` and `demo.type` glide a visible cursor to the target before acting, with timing varied like a person's (seeded per demo, so re-takes match); on a touch device (`hasTouch`) there is no cursor, and a click shows as a tap of a fingertip; `demo.scroll` turns the mouse wheel over a target; `demo.zoom` moves the camera in on a control or a point to show a detail too small to read in the frame, holds, and moves back out; `demo.zoomIn` and `demo.zoomOut` do the two halves, to keep the camera on a detail while the demo goes on (a phone demo rarely needs either, as a phone's UI already fills a portrait video); `demo.caption` shows a caption under the window. For voice input, `demo.microphone()` gives the page a microphone that hears nothing but `demo.speak(text)`, which reads the text in a synthetic voice (macOS `say`) and shows it as a caption, since the video has no sound.
+
+```ts
+await demo.zoomIn(page.getByRole("dialog"), 1.5);
+await demo.type(search, "Inkling-2-Mini");
+await demo.zoomOut();
+```
+
+## The render
+
+A video is not the raw screencast. The app sits in a rounded window on a ground of the Llama brand (the day sky, or the night sky for a dark recording), a phone's viewport gets a phone's rounder corners, and captions are chips under the window, in Llama Sans. `demo.zoom` moves a camera over the whole stage, with eased moves and motion blur: the window itself comes closer, with its corners and the ground round it, and the app is not cropped inside a fixed window. The grounds, the fonts and the lockup come from `@ggml-org/llama-brand`, which the app depends on, and sizes follow the brand's grid (u = the short side / 24, a margin of 2u).
+
+| Variable             | Values                                    | Default                                |
+| -------------------- | ----------------------------------------- | -------------------------------------- |
+| `DEMO_POLISH`        | `0` for the plain screencast              | on                                     |
+| `DEMO_POLISH_GROUND` | `day`, `night`, `light`, `dark`, `sand`   | `day`, or `night` for a dark recording |
+| `DEMO_POLISH_LOGO`   | `start`, `end`, `both`: a Llama logo card | none                                   |
+
+With `DEMO_POLISH=0` the video is the screencast as recorded: `demo.zoom` pinches the page (with the fingertips drawn on a touch device), captions show over the app, and `demo.zoomIn` and `demo.zoomOut` do nothing, as the cursor cannot act on a pinched page.
+
+The render needs no extra tool: a page in a Chromium of its own lays out each frame on one canvas from the recorded frames and the script's timeline, and `ffmpeg` encodes them. It takes a few times as long as the video, and longer with many camera moves.
+
+For agents, [skills/ui-demo](../../../skills/ui-demo/SKILL.md) walks through a demo, an e2e check and docs media for one change.
diff --git a/ui/lib/demo/package-lock.json b/ui/lib/demo/package-lock.json
new file mode 100644
index 000000000..5409ed30f
--- /dev/null
+++ b/ui/lib/demo/package-lock.json
@@ -0,0 +1,115 @@
+{
+  "name": "@ggml-org/llama-demo",
+  "version": "0.1.0",
+  "lockfileVersion": 3,
+  "requires": true,
+  "packages": {
+    "": {
+      "name": "@ggml-org/llama-demo",
+      "version": "0.1.0",
+      "license": "MIT",
+      "devDependencies": {
+        "@playwright/test": "1.56.1",
+        "@types/node": "24.13.0",
+        "typescript": "6.0.3"
+      },
+      "engines": {
+        "node": ">=22.18"
+      }
+    },
+    "node_modules/@playwright/test": {
+      "version": "1.56.1",
+      "resolved": "https://registry.npmjs.org/@playwright/test/-/test-1.56.1.tgz",
+      "integrity": "sha512-vSMYtL/zOcFpvJCW71Q/OEGQb7KYBPAdKh35WNSkaZA75JlAO8ED8UN6GUNTm3drWomcbcqRPFqQbLae8yBTdg==",
+      "dev": true,
+      "license": "Apache-2.0",
+      "dependencies": {
+        "playwright": "1.56.1"
+      },
+      "bin": {
+        "playwright": "cli.js"
+      },
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/@types/node": {
+      "version": "24.13.0",
+      "resolved": "https://registry.npmjs.org/@types/node/-/node-24.13.0.tgz",
+      "integrity": "sha512-5vtOqGQr4NJKeEzV441FcOi2MeG9UTWq9LqVLGneDdu4vlX17H8kQ2PA2UmNwCUGPVDj4oBjNhS7ReVEIWJJrg==",
+      "dev": true,
+      "license": "MIT",
+      "dependencies": {
+        "undici-types": "~7.18.0"
+      }
+    },
+    "node_modules/fsevents": {
+      "version": "2.3.2",
+      "resolved": "https://registry.npmjs.org/fsevents/-/fsevents-2.3.2.tgz",
+      "integrity": "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA==",
+      "dev": true,
+      "hasInstallScript": true,
+      "license": "MIT",
+      "optional": true,
+      "os": [
+        "darwin"
+      ],
+      "engines": {
+        "node": "^8.16.0 || ^10.6.0 || >=11.0.0"
+      }
+    },
+    "node_modules/playwright": {
+      "version": "1.56.1",
+      "resolved": "https://registry.npmjs.org/playwright/-/playwright-1.56.1.tgz",
+      "integrity": "sha512-aFi5B0WovBHTEvpM3DzXTUaeN6eN0qWnTkKx4NQaH4Wvcmc153PdaY2UBdSYKaGYw+UyWXSVyxDUg5DoPEttjw==",
+      "dev": true,
+      "license": "Apache-2.0",
+      "dependencies": {
+        "playwright-core": "1.56.1"
+      },
+      "bin": {
+        "playwright": "cli.js"
+      },
+      "engines": {
+        "node": ">=18"
+      },
+      "optionalDependencies": {
+        "fsevents": "2.3.2"
+      }
+    },
+    "node_modules/playwright-core": {
+      "version": "1.56.1",
+      "resolved": "https://registry.npmjs.org/playwright-core/-/playwright-core-1.56.1.tgz",
+      "integrity": "sha512-hutraynyn31F+Bifme+Ps9Vq59hKuUCz7H1kDOcBs+2oGguKkWTU50bBWrtz34OUWmIwpBTWDxaRPXrIXkgvmQ==",
+      "dev": true,
+      "license": "Apache-2.0",
+      "bin": {
+        "playwright-core": "cli.js"
+      },
+      "engines": {
+        "node": ">=18"
+      }
+    },
+    "node_modules/typescript": {
+      "version": "6.0.3",
+      "resolved": "https://registry.npmjs.org/typescript/-/typescript-6.0.3.tgz",
+      "integrity": "sha512-y2TvuxSZPDyQakkFRPZHKFm+KKVqIisdg9/CZwm9ftvKXLP8NRWj38/ODjNbr43SsoXqNuAisEf1GdCxqWcdBw==",
+      "dev": true,
+      "license": "Apache-2.0",
+      "bin": {
+        "tsc": "bin/tsc",
+        "tsserver": "bin/tsserver"
+      },
+      "engines": {
+        "node": ">=14.17"
+      }
+    },
+    "node_modules/undici-types": {
+      "version": "7.18.2",
+      "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-7.18.2.tgz",
+      "integrity": "sha512-AsuCzffGHJybSaRrmr5eHr81mwJU3kjw6M+uprWvCXiNeN9SOGwQ3Jn8jb8m3Z6izVgknn1R0FTCEAP2QrLY/w==",
+      "dev": true,
+      "license": "MIT"
+    }
+  }
+}
diff --git a/ui/lib/demo/package.json b/ui/lib/demo/package.json
new file mode 100644
index 000000000..128c3d25a
--- /dev/null
+++ b/ui/lib/demo/package.json
@@ -0,0 +1,29 @@
+{
+  "name": "@ggml-org/llama-demo",
+  "version": "0.1.0",
+  "private": true,
+  "description": "Scripted demo videos of llama.cpp frontend apps, for pull requests and docs.",
+  "homepage": "https://github.com/ggml-org/llama.cpp/tree/master/ui/lib/demo",
+  "license": "MIT",
+  "repository": {
+    "type": "git",
+    "url": "git+https://github.com/ggml-org/llama.cpp.git",
+    "directory": "ui/lib/demo"
+  },
+  "type": "module",
+  "exports": {
+    ".": "./src/index.ts",
+    "./cli": "./src/cli.ts"
+  },
+  "scripts": {
+    "check": "tsc --noEmit"
+  },
+  "devDependencies": {
+    "@playwright/test": "1.56.1",
+    "@types/node": "24.13.0",
+    "typescript": "6.0.3"
+  },
+  "engines": {
+    "node": ">=22.18"
+  }
+}
diff --git a/ui/lib/demo/src/cli.ts b/ui/lib/demo/src/cli.ts
new file mode 100644
index 000000000..f18bc74e0
--- /dev/null
+++ b/ui/lib/demo/src/cli.ts
@@ -0,0 +1,493 @@
+/**
+ * Records demo videos for pull requests and docs. An app runs it from its own demo/cli.ts:
+ *
+ *   pr <number>   record the ```ts demo block from a PR description, a video per test
+ *                 (--trust <sha> to record someone else's PR at that head commit)
+ *   docs          record every docs/*.demo.ts script in DEMO_STORAGE
+ *
+ * plus any commands of the app's own. Settings come from the app's .env.
+ */
+
+import { type DemoStorage, getDemoStorage, getPublicUrl } from "./storage.ts";
+import { execFileSync } from "node:child_process";
+import { createHash } from "node:crypto";
+import {
+  existsSync,
+  mkdirSync,
+  readdirSync,
+  readFileSync,
+  rmSync,
+  statSync,
+  symlinkSync,
+  writeFileSync,
+} from "node:fs";
+import { createServer } from "node:net";
+import { tmpdir } from "node:os";
+import { basename, join, relative } from "node:path";
+
+/** An app the CLI records demos of. */
+export interface DemoApp {
+  /** More commands, such as writing the app's fixtures, each given the arguments after it. */
+  commands?: Record<string, (args: string[]) => Promise<void> | void>;
+  /** The app's demo folder: its helpers.ts, playwright.config.ts and videos/. */
+  demoDir: string;
+  /** The app's folder, with its node_modules and .env, where Playwright runs. */
+  dir: string;
+  /**
+   * Folders, relative to `dir`, whose node_modules a PR's worktree also needs, such as a
+   * library the app builds from source. The app's own are always linked.
+   */
+  linkNodeModules?: string[];
+}
+
+let app: DemoApp;
+let REPO = "";
+const runsDir = () => join(app.demoDir, ".runs");
+const videosDir = () => join(app.demoDir, "videos");
+const DEMO_BLOCK = /```(?:ts|typescript)[ \t]+demo[ \t]*\r?\n([\s\S]*?)```/;
+const HELPERS_IMPORT =
+  /^import\s[^;]*from\s+['"][^'"]*helpers(?:\.ts)?['"];?\s*$/gm;
+const SECTION_START = "<!-- demo:start -->";
+const SECTION_END = "<!-- demo:end -->";
+/** GitHub's image proxy refuses larger images, so a bigger preview shows as a broken image. */
+const PREVIEW_MAX_BYTES = 5 * 1024 * 1024;
+function run(
+  cmd: string,
+  args: string[],
+  opts: { cwd?: string; env?: NodeJS.ProcessEnv } = {},
+): string {
+  return execFileSync(cmd, args, {
+    cwd: opts.cwd ?? app.dir,
+    encoding: "utf8",
+    env: opts.env,
+  }).trim();
+}
+
+/** Writes a demo script into .runs/, importing the harness helpers. */
+function writeDemoScript(name: string, source: string): string {
+  const file = join(runsDir(), `${name}.demo.ts`);
+  const helpers = relative(runsDir(), join(app.demoDir, "helpers.ts"));
+  const body = source.replace(HELPERS_IMPORT, "").trim();
+
+  mkdirSync(runsDir(), { recursive: true });
+  writeFileSync(
+    file,
+    `import { expect, test } from './${helpers}';\n\n${body}\n`,
+  );
+
+  return file;
+}
+
+async function freePort(): Promise<number> {
+  return new Promise((done, fail) => {
+    const server = createServer();
+
+    server.once("error", fail);
+    server.listen(0, () => {
+      const { port } = server.address() as { port: number };
+
+      server.close(() => done(port));
+    });
+  });
+}
+
+/** A video recorded from one `test()` of a script. */
+interface Video {
+  /** From the test's `description` annotation, shown beside its video in the PR. */
+  description?: string;
+  mp4: string;
+  title: string;
+}
+
+/** Records the given scripts; returns a video for each of their tests, in order. */
+async function record(scripts: string[], uiDir = app.dir): Promise<Video[]> {
+  const port = await freePort();
+  const manifests = scripts.map((s) =>
+    join(videosDir(), `${basename(s, ".demo.ts")}.videos.jsonl`),
+  );
+
+  for (const manifest of manifests) rmSync(manifest, { force: true });
+
+  execFileSync(
+    "npx",
+    [
+      "playwright",
+      "test",
+      `--config=${relative(app.dir, join(app.demoDir, "playwright.config.ts"))}`,
+      ...scripts.map((s) => relative(app.dir, s)),
+    ],
+    {
+      cwd: app.dir,
+      env: {
+        ...process.env,
+        DEMO_STORYBOOK_PORT: String(await freePort()),
+        DEMO_UI_DIR: uiDir,
+        DEMO_UI_PORT: String(port),
+      },
+      stdio: "inherit",
+    },
+  );
+
+  // helpers.ts lists each video it encodes in the script's manifest
+  return manifests.flatMap((manifest) =>
+    readFileSync(manifest, "utf8")
+      .trim()
+      .split("\n")
+      .map((line) => JSON.parse(line) as Video),
+  );
+}
+
+/**
+ * Animated GIF preview that GitHub renders inline, its longer side DEMO_PREVIEW_WIDTH (so a
+ * phone's portrait video is that tall), shrunk until it fits under PREVIEW_MAX_BYTES.
+ */
+function makePreview(mp4: string): string {
+  const gif = mp4.replace(/\.mp4$/, ".gif");
+
+  for (
+    let side = Number(process.env.DEMO_PREVIEW_WIDTH ?? 800);
+    ;
+    side = Math.round(side * 0.8)
+  ) {
+    execFileSync("ffmpeg", [
+      "-y",
+      "-loglevel",
+      "error",
+      "-i",
+      mp4,
+      "-vf",
+      `fps=10,scale='if(gt(iw,ih),${side},-2)':'if(gt(iw,ih),-2,${side})':flags=lanczos,split[a][b];[a]palettegen=stats_mode=diff[p];[b][p]paletteuse=dither=bayer:bayer_scale=5:diff_mode=rectangle`,
+      "-loop",
+      "0",
+      gif,
+    ]);
+
+    if (statSync(gif).size <= PREVIEW_MAX_BYTES || side < 320) return gif;
+  }
+}
+
+function upload(storage: DemoStorage, files: Record<string, string>): void {
+  for (const [key, file] of Object.entries(files)) {
+    storage.upload(file, key);
+    console.log(`uploaded ${key}`);
+  }
+}
+
+/**
+ * Public URL with a content hash, so a re-recorded file at the same key gets a new
+ * URL: GitHub's image proxy caches previews by URL.
+ */
+function versionedUrl(key: string, file: string): null | string {
+  const url = getPublicUrl(key);
+  const version = createHash("sha1")
+    .update(readFileSync(file))
+    .digest("hex")
+    .slice(0, 10);
+
+  return url && `${url}?v=${version}`;
+}
+
+/** Whether a video is taller than wide, like a phone's. */
+function isPortrait(mp4: string): boolean {
+  const [width, height] = run("ffprobe", [
+    "-v",
+    "error",
+    "-select_streams",
+    "v:0",
+    "-show_entries",
+    "stream=width,height",
+    "-of",
+    "csv=p=0",
+    mp4,
+  ])
+    .split(",")
+    .map(Number);
+
+  return height > width;
+}
+
+/**
+ * One preview, or a table of them when the script has several tests, each headed by its
+ * test's title: up to four portrait videos to a row, or two landscape ones, so each stays
+ * large enough to read. When the tests have descriptions, a video to a row instead, with its
+ * title and description beside it.
+ */
+function demoSection(
+  links: { description?: string; gif: string; mp4: string; title: string }[],
+  sha: string,
+  columns: number,
+): string {
+  const preview = ({ gif, mp4, title }: (typeof links)[number]) =>
+    `[![${title.replace(/[[\]|]/g, "")}](${gif})](${mp4})`;
+  // a line break would end the table row, so it becomes one inside the cell
+  const cell = (text: string) =>
+    text.replace(/\|/g, "\\|").replace(/\r?\n/g, "<br>");
+  const rows = Array.from(
+    { length: Math.ceil(links.length / columns) },
+    (_, i) => links.slice(i * columns, (i + 1) * columns),
+  );
+  const pad = (cells: string[]) => [
+    ...cells,
+    ...Array(columns - cells.length).fill(" "),
+  ];
+  const described = [
+    "| Video | What it shows |",
+    "|---|---|",
+    ...links.map(
+      (l) =>
+        `| ${preview(l)} | **${cell(l.title)}**${l.description ? `<br><br>${cell(l.description)}` : ""} |`,
+    ),
+  ];
+  const body = links.some((l) => l.description)
+    ? described
+    : links.length === 1
+      ? [preview({ ...links[0], title: "Demo" })]
+      : rows.flatMap((row, i) => [
+          // a table has one header row, so later rows title their videos in bold
+          `| ${pad(row.map((l) => (i === 0 ? cell(l.title) : `**${cell(l.title)}**`))).join(" | ")} |`,
+          ...(i === 0 ? [`|${Array(columns).fill("---").join("|")}|`] : []),
+          `| ${pad(row.map(preview)).join(" | ")} |`,
+        ]);
+  const note =
+    links.length === 1
+      ? "the preview for the full video"
+      : "a preview for its full video";
+
+  return [
+    SECTION_START,
+    ...body,
+    "",
+    `Recorded at ${sha.slice(0, 10)}; click ${note}.`,
+    SECTION_END,
+  ].join("\n");
+}
+
+/** Replaces the managed demo section, or adds a `## Demo` section before the details. */
+function withDemoSection(body: string, section: string): string {
+  const start = body.indexOf(SECTION_START);
+  const end = body.indexOf(SECTION_END);
+
+  if (start !== -1 && end > start) {
+    return (
+      body.slice(0, start) + section + body.slice(end + SECTION_END.length)
+    );
+  }
+
+  const block = `## Demo\n\n${section}\n\n`;
+  const anchor = body.search(/^## (Additional information|Requirements)\b/m);
+
+  return anchor === -1
+    ? `${body.trimEnd()}\n\n${block}`
+    : body.slice(0, anchor) + block + body.slice(anchor);
+}
+
+async function recordPr(number: string, trustedSha?: string): Promise<void> {
+  const pr = JSON.parse(
+    run("gh", [
+      "pr",
+      "view",
+      number,
+      "--repo",
+      REPO,
+      "--json",
+      "author,body,headRefOid",
+    ]),
+  ) as { author: { login: string }; body: string; headRefOid: string };
+  const source = DEMO_BLOCK.exec(pr.body)?.[1];
+
+  if (!source)
+    throw new Error(
+      `PR #${number} has no \`\`\`ts demo block in its description`,
+    );
+
+  const sha = pr.headRefOid;
+
+  // the PR's code and demo script run on this machine, with the gh and hf logins,
+  // so someone else's PR only runs at a head commit you've read and passed to --trust
+  if (pr.author.login !== run("gh", ["api", "user", "--jq", ".login"])) {
+    if (!trustedSha) {
+      throw new Error(
+        `PR #${number} is by ${pr.author.login}, and recording it runs its code here: ` +
+          `read its diff and demo block, then run again with --trust ${sha.slice(0, 10)}`,
+      );
+    }
+
+    if (trustedSha.length < 7 || !sha.startsWith(trustedSha)) {
+      throw new Error(
+        `PR #${number} head is ${sha.slice(0, 10)}, not the trusted ${trustedSha}`,
+      );
+    }
+  }
+
+  const worktree = join(tmpdir(), `llama-ui-demo-pr-${number}`);
+
+  run("git", [
+    "fetch",
+    "--no-tags",
+    `https://github.com/${REPO}.git`,
+    `pull/${number}/head`,
+  ]);
+
+  if (run("git", ["rev-parse", "FETCH_HEAD"]) !== sha) {
+    throw new Error(`PR #${number} head moved while fetching, run again`);
+  }
+
+  rmSync(worktree, { force: true, recursive: true });
+  run("git", ["worktree", "prune"]);
+  run("git", ["worktree", "add", "--detach", worktree, sha]);
+  // git's own path from the top to the app, so a symlinked checkout path cannot skew it
+  const appInWorktree = join(
+    worktree,
+    run("git", ["rev-parse", "--show-prefix"], { cwd: app.dir }),
+  );
+
+  for (const dir of [".", ...(app.linkNodeModules ?? [])]) {
+    const modules = join(app.dir, dir, "node_modules");
+
+    if (existsSync(modules))
+      symlinkSync(modules, join(appInWorktree, dir, "node_modules"));
+  }
+
+  const name = `pr-${number}`;
+  const script = writeDemoScript(name, source);
+
+  try {
+    const videos = (await record([script], appInWorktree)).map((video) => ({
+      ...video,
+      gif: makePreview(video.mp4),
+    }));
+    const storage = getDemoStorage();
+
+    for (const { gif, mp4 } of videos)
+      console.log(`\nvideo:   ${mp4}\npreview: ${gif}`);
+
+    if (!storage) {
+      console.log(
+        "DEMO_STORAGE is not set: drag the mp4 into the PR description.",
+      );
+
+      return;
+    }
+
+    const prefix = `videos/pr/${number}/${sha.slice(0, 10)}`;
+    // a script with several tests gets <sha>-1.mp4, <sha>-2.mp4 and so on
+    const keys = videos.map((_, i) =>
+      videos.length === 1 ? prefix : `${prefix}-${i + 1}`,
+    );
+
+    upload(storage, { [`${prefix}.demo.ts`]: script });
+    videos.forEach(({ gif, mp4 }, i) => {
+      upload(storage, { [`${keys[i]}.gif`]: gif, [`${keys[i]}.mp4`]: mp4 });
+    });
+
+    if (!getPublicUrl(prefix)) {
+      console.log(
+        "DEMO_STORAGE_PUBLIC_URL is not set: not linking the video in the PR.",
+      );
+
+      return;
+    }
+
+    const links = videos.map(({ description, gif, mp4, title }, i) => ({
+      description,
+      gif: versionedUrl(`${keys[i]}.gif`, gif) ?? "",
+      mp4: versionedUrl(`${keys[i]}.mp4`, mp4) ?? "",
+      title,
+    }));
+
+    execFileSync(
+      "gh",
+      ["pr", "edit", number, "--repo", REPO, "--body-file", "-"],
+      {
+        cwd: app.dir,
+        input: withDemoSection(
+          pr.body,
+          demoSection(
+            links,
+            sha,
+            Math.min(links.length, isPortrait(videos[0].mp4) ? 4 : 2),
+          ),
+        ),
+        stdio: ["pipe", "inherit", "inherit"],
+      },
+    );
+    console.log(`linked the demo in https://github.com/${REPO}/pull/${number}`);
+  } finally {
+    rmSync(script, { force: true });
+    run("git", ["worktree", "remove", "--force", worktree]);
+  }
+}
+
+async function recordDocs(): Promise<void> {
+  const storage = getDemoStorage();
+
+  if (!storage)
+    throw new Error(
+      "DEMO_STORAGE is not set: docs demo scripts are read from it",
+    );
+
+  const downloaded = join(runsDir(), "docs-source");
+
+  rmSync(downloaded, { force: true, recursive: true });
+
+  if (!storage.downloadDir("scripts/docs", downloaded)) {
+    throw new Error("no scripts/docs/*.demo.ts in DEMO_STORAGE");
+  }
+
+  const scripts = readdirSync(downloaded)
+    .filter((f) => f.endsWith(".demo.ts"))
+    .map((f) =>
+      writeDemoScript(
+        basename(f, ".demo.ts"),
+        readFileSync(join(downloaded, f), "utf8"),
+      ),
+    );
+
+  try {
+    const videos = await record(scripts);
+
+    for (const { mp4 } of videos) {
+      const name = basename(mp4, ".mp4");
+
+      upload(storage, {
+        [`videos/docs/${name}.gif`]: makePreview(mp4),
+        [`videos/docs/${name}.mp4`]: mp4,
+      });
+    }
+  } finally {
+    rmSync(runsDir(), { force: true, recursive: true });
+  }
+}
+
+/** Runs the command in process.argv for `demoApp`. */
+export async function runDemoCli(demoApp: DemoApp): Promise<void> {
+  app = demoApp;
+
+  const envFile = join(app.dir, ".env");
+
+  if (existsSync(envFile)) process.loadEnvFile(envFile);
+
+  REPO = process.env.DEMO_GITHUB_REPO ?? "ggml-org/llama.cpp";
+
+  const [command, ...args] = process.argv.slice(2);
+  const trustIndex = args.indexOf("--trust");
+  const extra = app.commands?.[command];
+
+  if (command === "pr" && args[0]) {
+    await recordPr(
+      args[0],
+      trustIndex === -1 ? undefined : args[trustIndex + 1],
+    );
+  } else if (command === "docs") {
+    await recordDocs();
+  } else if (extra) {
+    await extra(args);
+  } else {
+    const others = Object.keys(app.commands ?? {}).map((name) => ` | ${name}`);
+
+    console.error(
+      `usage: node demo/cli.ts pr <number> [--trust <sha>] | docs${others.join("")}`,
+    );
+    process.exit(1);
+  }
+}
diff --git a/ui/lib/demo/src/demo.ts b/ui/lib/demo/src/demo.ts
new file mode 100644
index 000000000..249b66508
--- /dev/null
+++ b/ui/lib/demo/src/demo.ts
@@ -0,0 +1,578 @@
+/**
+ * Drives a page like a person for a demo video: a visible cursor or fingertip, human timing,
+ * captions, a voice, and camera zooms that the render plays (see polish.ts). Playwright is only a
+ * type here: the app passes in its page, so this package loads none of its own.
+ */
+
+import { CAMERA_MOVE_MS, type PolishEvent } from "./polish.ts";
+import type { CDPSession, Locator, Page } from "@playwright/test";
+import { execFileSync } from "node:child_process";
+import { mkdtempSync, readFileSync, rmSync } from "node:fs";
+import { tmpdir } from "node:os";
+import { join } from "node:path";
+
+/** How far below the viewport's top a pinch has to start for Chromium to zoom at all. */
+const ZOOM_TOP_INSET_PX = 64;
+/** The timeline of each page's demo, which the polished render plays over the footage. */
+export const timelines = new WeakMap<Page, PolishEvent[]>();
+
+/**
+ * Draws a fake cursor and click ripples, since recorded videos don't include
+ * the OS pointer, and a fingertip per touch, so a pinch shows as two fingers.
+ * A touch device has no cursor: a click shows as a tap of a fingertip.
+ * Runs in the page via addInitScript.
+ */
+export function installCursorOverlay(): void {
+  const mount = () => {
+    const style = document.createElement("style");
+
+    style.textContent = `
+			#demo-cursor { position: fixed; top: 0; left: 0; z-index: 2147483647; pointer-events: none;
+				width: 22px; height: 22px; margin: -3px 0 0 -3px; transition: transform 80ms ease-out; }
+			#demo-cursor.down { transform: scale(0.85); }
+			.demo-ripple { position: fixed; z-index: 2147483646; pointer-events: none; width: 36px; height: 36px;
+				margin: -18px 0 0 -18px; border-radius: 50%; background: rgba(59, 130, 246, 0.35);
+				animation: demo-ripple 450ms ease-out forwards; }
+			@keyframes demo-ripple { from { transform: scale(0.3); opacity: 1; } to { transform: scale(1.4); opacity: 0; } }
+			#demo-caption { position: fixed; left: 50%; top: 72px; z-index: 2147483647; pointer-events: none;
+				transform: translate(-50%, -8px); opacity: 0; transition: opacity 200ms ease, transform 200ms ease;
+				max-width: 80%; padding: 10px 18px; border-radius: 10px; background: rgba(17, 17, 17, 0.88);
+				color: #fff; font: 500 18px/1.4 system-ui, sans-serif; text-align: center; }
+			#demo-caption.visible { opacity: 1; transform: translate(-50%, 0); }
+			.demo-finger { position: fixed; z-index: 2147483646; pointer-events: none; width: 40px; height: 40px;
+				margin: -20px 0 0 -20px; border-radius: 50%; background: rgba(59, 130, 246, 0.3);
+				border: 2px solid rgba(59, 130, 246, 0.55); transition: opacity 200ms ease; }
+		`;
+    document.head.appendChild(style);
+
+    const cursor = document.createElement("div");
+
+    cursor.id = "demo-cursor";
+    cursor.innerHTML = `<svg viewBox="0 0 24 24" width="22" height="22"><path d="M4 2l16 10.5-7 1.5-3.5 6.5z"
+			fill="#111" stroke="#fff" stroke-width="1.5" stroke-linejoin="round"/></svg>`;
+    document.documentElement.appendChild(cursor);
+
+    const caption = document.createElement("div");
+
+    caption.id = "demo-caption";
+    document.documentElement.appendChild(caption);
+
+    const touch = navigator.maxTouchPoints > 0;
+    const tap = Object.assign(document.createElement("div"), {
+      className: "demo-finger",
+    });
+    let lift: ReturnType<typeof setTimeout> | undefined;
+
+    if (touch) cursor.style.display = "none";
+
+    document.addEventListener(
+      "mousemove",
+      (e) => (cursor.style.translate = `${e.clientX}px ${e.clientY}px`),
+      true,
+    );
+    document.addEventListener(
+      "mousedown",
+      (e) => {
+        cursor.classList.add("down");
+
+        if (touch) {
+          tap.style.left = `${e.clientX}px`;
+          tap.style.top = `${e.clientY}px`;
+          tap.style.opacity = "1";
+          document.documentElement.appendChild(tap);
+          // a quick second tap restarts the fade, so the first one's timer does not hide it
+          clearTimeout(lift);
+          lift = setTimeout(() => (tap.style.opacity = "0"), 250);
+        }
+
+        const ripple = document.createElement("div");
+
+        ripple.className = "demo-ripple";
+        ripple.style.left = `${e.clientX}px`;
+        ripple.style.top = `${e.clientY}px`;
+        document.documentElement.appendChild(ripple);
+        setTimeout(() => ripple.remove(), 500);
+      },
+      true,
+    );
+    document.addEventListener(
+      "mouseup",
+      () => cursor.classList.remove("down"),
+      true,
+    );
+
+    const fingers: HTMLDivElement[] = [];
+    const placeFingers = (e: TouchEvent) => {
+      Array.from(e.touches).forEach((touch, i) => {
+        const finger = (fingers[i] ??= Object.assign(
+          document.createElement("div"),
+          {
+            className: "demo-finger",
+          },
+        ));
+
+        finger.style.left = `${touch.clientX}px`;
+        finger.style.top = `${touch.clientY}px`;
+        finger.style.opacity = "1";
+        document.documentElement.appendChild(finger);
+      });
+      fingers
+        .slice(e.touches.length)
+        .forEach((finger) => (finger.style.opacity = "0"));
+    };
+
+    for (const type of ["touchstart", "touchmove", "touchend", "touchcancel"]) {
+      document.addEventListener(type, placeFingers as EventListener, {
+        capture: true,
+        passive: true,
+      });
+    }
+  };
+
+  if (document.readyState === "loading") {
+    document.addEventListener("DOMContentLoaded", mount);
+  } else {
+    mount();
+  }
+}
+
+/**
+ * Swaps the page's microphone for one that hears only what `window.demoSpeak` plays into it,
+ * silence otherwise. Chromium's fake capture device crashes the page, so voice input is
+ * recorded with this instead. Runs in the page.
+ */
+function installFakeMicrophone(): void {
+  const context = new AudioContext();
+  const output = context.createMediaStreamDestination();
+
+  navigator.mediaDevices.getUserMedia = async (constraints) => {
+    if (!constraints?.audio || constraints.video) {
+      throw new DOMException(
+        "demo: only the microphone is faked",
+        "NotSupportedError",
+      );
+    }
+
+    await context.resume();
+
+    // each opening gets its own tracks, so a recording that stops them leaves the source on
+    return new MediaStream(
+      output.stream.getAudioTracks().map((track) => track.clone()),
+    );
+  };
+
+  Object.assign(window, {
+    demoSpeak: async (wavBase64: string) => {
+      const bytes = Uint8Array.from(atob(wavBase64), (c) => c.charCodeAt(0));
+      const source = context.createBufferSource();
+
+      source.buffer = await context.decodeAudioData(bytes.buffer);
+      source.connect(output);
+      await context.resume();
+      await new Promise((done) => {
+        source.onended = done;
+        source.start();
+      });
+    },
+  });
+}
+
+/** `text` read by a synthetic voice, as a base64 WAV. Uses macOS `say`. */
+function synthesizeSpeech(text: string, voice: string): string {
+  const dir = mkdtempSync(join(tmpdir(), "demo-speech-"));
+  const file = join(dir, "speech.wav");
+
+  try {
+    execFileSync("say", [
+      "-v",
+      voice,
+      "-o",
+      file,
+      "--file-format=WAVE",
+      "--data-format=LEI16@24000",
+      text,
+    ]);
+
+    return readFileSync(file).toString("base64");
+  } catch (error) {
+    throw new Error(
+      `demo: speak() needs macOS \`say\` with the voice ${voice}`,
+      {
+        cause: error,
+      },
+    );
+  } finally {
+    rmSync(dir, { force: true, recursive: true });
+  }
+}
+
+/** Seeded randomness, so a demo moves the same way on every recording. */
+function createRandom(seed: string): () => number {
+  let state = [...seed].reduce(
+    (h, c) => Math.imul(h ^ c.charCodeAt(0), 2654435761),
+    1,
+  );
+
+  return () => {
+    state = (state + 0x6d2b79f5) | 0;
+
+    let t = Math.imul(state ^ (state >>> 15), 1 | state);
+
+    t = (t + Math.imul(t ^ (t >>> 7), 61 | t)) ^ t;
+
+    return ((t ^ (t >>> 14)) >>> 0) / 4294967296;
+  };
+}
+
+const easeInOut = (t: number) =>
+  t < 0.5 ? 4 * t * t * t : 1 - (-2 * t + 2) ** 3 / 2;
+
+/**
+ * Drives the page like a person: the cursor glides along a slight arc with
+ * Fitts-like durations, settles briefly before pressing, and typing and pauses
+ * vary a little.
+ */
+export class Demo {
+  private cdp: CDPSession | undefined;
+  private readonly page: Page;
+  private readonly random: () => number;
+  private readonly timeline: PolishEvent[] | undefined;
+  private x = 0;
+  private y = 0;
+
+  /** Shows a caption at the top of the frame for `ms`, clear of the chat form. */
+  async caption(text: string, ms = 2200): Promise<void> {
+    await this.showCaption(text);
+    await this.page.waitForTimeout(ms);
+    await this.hideCaption();
+  }
+
+  async click(target: Locator, ms = 400): Promise<void> {
+    await this.moveTo(target);
+    await this.page.waitForTimeout(this.between(80, 160));
+    await this.page.mouse.down();
+    await this.page.waitForTimeout(this.between(50, 90));
+    await this.page.mouse.up();
+    await this.pause(ms);
+  }
+
+  constructor(page: Page, seed: string) {
+    this.page = page;
+    this.random = createRandom(seed);
+    this.timeline = timelines.get(page);
+
+    const viewport = page.viewportSize();
+
+    this.x = (viewport?.width ?? 0) / 2;
+    this.y = (viewport?.height ?? 0) / 2;
+  }
+
+  /**
+   * Touches `target` for `ms` and lifts: a tap, or with a longer `ms` a press-and-hold, as a
+   * phone's held rows ask for. It needs a touch device (`hasTouch`), and shows a fingertip.
+   */
+  async hold(target: Locator, ms = 900, after = 500): Promise<void> {
+    await target.scrollIntoViewIfNeeded();
+
+    const { x, y } = await this.center(target);
+    const cdp = await this.session();
+
+    await this.page.waitForTimeout(this.between(60, 140));
+    await cdp.send("Input.dispatchTouchEvent", {
+      touchPoints: [{ x, y }],
+      type: "touchStart",
+    });
+    await this.page.waitForTimeout(ms);
+    await cdp.send("Input.dispatchTouchEvent", {
+      touchPoints: [],
+      type: "touchEnd",
+    });
+    await this.liftFingers();
+    this.x = x;
+    this.y = y;
+    await this.pause(after);
+  }
+
+  async hover(target: Locator, ms = 350): Promise<void> {
+    await this.moveTo(target);
+    await this.pause(ms);
+  }
+
+  /**
+   * Gives the page a microphone that hears only what `speak` says, and allows the page to
+   * use it. Call it before the microphone is first used.
+   */
+  async microphone(): Promise<void> {
+    await this.page.context().grantPermissions(["microphone"]);
+    await this.page.evaluate(installFakeMicrophone);
+  }
+
+  /** Glides the cursor to a point near the center of `target`. */
+  async moveTo(target: Locator): Promise<void> {
+    await target.scrollIntoViewIfNeeded();
+    const box = await target.boundingBox();
+
+    if (!box) throw new Error(`demo: ${target} has no bounding box`);
+
+    const x = box.x + box.width * this.between(0.4, 0.6);
+    const y = box.y + box.height * this.between(0.4, 0.6);
+    const dx = x - this.x;
+    const dy = y - this.y;
+    const distance = Math.hypot(dx, dy);
+    const duration = 110 + 55 * Math.log2(distance / 40 + 1);
+    // bow the path a little to one side, like a wrist turning
+    const bow = distance * this.between(-0.08, 0.08);
+    const fromX = this.x;
+    const fromY = this.y;
+    const started = Date.now();
+
+    for (;;) {
+      const t = Math.min((Date.now() - started) / duration, 1);
+      const p = easeInOut(t);
+      const arc = Math.sin(Math.PI * p) * bow;
+
+      this.x = fromX + dx * p - (dy / (distance || 1)) * arc;
+      this.y = fromY + dy * p + (dx / (distance || 1)) * arc;
+      await this.page.mouse.move(this.x, this.y);
+
+      if (t === 1) break;
+
+      await this.page.waitForTimeout(8);
+    }
+  }
+
+  /** Waits about `ms`, varied by up to 15% so pauses don't feel metronomic. */
+  async pause(ms = 800): Promise<void> {
+    await this.page.waitForTimeout(ms * this.between(0.85, 1.15));
+  }
+
+  async press(key: string, ms = 600): Promise<void> {
+    await this.page.keyboard.press(key);
+    await this.pause(ms);
+  }
+
+  /** Scrolls the wheel over `target` by `dy` pixels (negative scrolls up), in small steps like a trackpad. */
+  async scroll(target: Locator, dy: number, ms = 500): Promise<void> {
+    await this.moveTo(target);
+
+    const step = Math.sign(dy) * 40;
+
+    for (let done = 0; Math.abs(done) < Math.abs(dy); done += step) {
+      await this.page.mouse.wheel(0, step);
+      await this.page.waitForTimeout(16);
+    }
+
+    await this.pause(ms);
+  }
+
+  /**
+   * Says `text` into the microphone from `microphone` in a synthetic voice (macOS `say`), and
+   * returns once it is said. The words show as a caption, since the video has no sound.
+   */
+  async speak(text: string, voice = "Samantha", ms = 400): Promise<void> {
+    const wav = synthesizeSpeech(text, voice);
+
+    await this.showCaption(`"${text}"`);
+    await this.page.evaluate(
+      (base64) =>
+        (
+          window as unknown as { demoSpeak(wav: string): Promise<void> }
+        ).demoSpeak(base64),
+      wav,
+    );
+    await this.hideCaption();
+    await this.pause(ms);
+  }
+
+  /** Taps `target` with a fingertip, on a touch device. */
+  tap(target: Locator, after = 500): Promise<void> {
+    return this.hold(target, this.between(60, 110), after);
+  }
+
+  /** Types quickly with uneven key timing, a little slower after spaces and punctuation. */
+  async type(target: Locator, text: string, ms = 500): Promise<void> {
+    await this.click(target, 200);
+
+    for (const char of text) {
+      await this.page.keyboard.type(char);
+      await this.page.waitForTimeout(
+        this.between(15, 45) +
+          (/[\s.,!?]/.test(char) ? this.between(20, 60) : 0),
+      );
+    }
+
+    await this.pause(ms);
+  }
+
+  /**
+   * Pinches in on `target`, a control or a point in the viewport, holds about `ms`, and pinches
+   * back out to 1x: a two-finger zoom onto a detail too small to read in the frame. On a touch
+   * device the fingertips show. In the polished render the camera moves in and out instead.
+   */
+  async zoom(
+    target: Locator | { x: number; y: number },
+    scale = 2.5,
+    ms = 1400,
+  ): Promise<void> {
+    if (this.timeline) {
+      await this.zoomIn(target, scale);
+      await this.pause(ms);
+      await this.zoomOut();
+
+      return;
+    }
+
+    const point = "x" in target ? target : await this.center(target);
+    // a pinch anchored in the viewport's top band does not zoom at all
+    const at = { x: point.x, y: Math.max(point.y, ZOOM_TOP_INSET_PX) };
+    const viewport = this.page.viewportSize() ?? { height: 0, width: 0 };
+    const middle = { x: viewport.width / 2, y: viewport.height / 2 };
+
+    await this.pinch(at, scale, 1400);
+
+    // One near the bottom edge overshoots its ratio, and a pinch there again misses too. A small
+    // pinch from the middle evens it out, drawing the detail toward the middle, so it stays in view
+    const reached = await this.pageScale();
+
+    if (Math.abs(reached / scale - 1) > 0.03)
+      await this.pinch(middle, scale / reached, 1400);
+
+    await this.liftFingers();
+    await this.pause(ms);
+
+    // back to exactly 1x, which the next gesture needs, in one quick pinch from the middle of
+    // the viewport, and another for what is left when one lands short
+    for (let tries = 0; ; tries++) {
+      const current = await this.pageScale();
+
+      if (current <= 1.001) break;
+
+      if (tries === 4)
+        throw new Error(`demo: zoom stuck at ${current.toFixed(3)}x`);
+
+      await this.pinch(middle, 1 / current, 1800);
+    }
+
+    await this.liftFingers();
+    await this.pause(200);
+  }
+
+  /**
+   * Moves the camera in on `target` and keeps it there while the demo goes on,
+   * until `zoomOut` or the next `zoomIn`. A plain recording (DEMO_POLISH=0) ignores it, as the cursor cannot act
+   * on a pinched page.
+   */
+  async zoomIn(
+    target: Locator | { x: number; y: number },
+    scale = 2.5,
+  ): Promise<void> {
+    if (!this.timeline) return;
+
+    if (!("x" in target)) await target.scrollIntoViewIfNeeded();
+
+    const point = "x" in target ? target : await this.center(target);
+
+    this.timeline.push({
+      scale,
+      time: Date.now() / 1000,
+      type: "camera",
+      ...point,
+    });
+    await this.page.waitForTimeout(CAMERA_MOVE_MS);
+  }
+
+  /** Moves the camera back out to the whole page. */
+  async zoomOut(): Promise<void> {
+    if (!this.timeline) return;
+
+    this.timeline.push({
+      scale: 1,
+      time: Date.now() / 1000,
+      type: "camera",
+      x: 0,
+      y: 0,
+    });
+    await this.page.waitForTimeout(CAMERA_MOVE_MS);
+  }
+
+  private between(min: number, max: number): number {
+    return min + (max - min) * this.random();
+  }
+
+  private async center(target: Locator): Promise<{ x: number; y: number }> {
+    const box = await target.boundingBox();
+
+    if (!box) throw new Error(`demo: ${target} has no bounding box`);
+
+    return { x: box.x + box.width / 2, y: box.y + box.height / 2 };
+  }
+
+  private async hideCaption(): Promise<void> {
+    this.timeline?.push({
+      text: null,
+      time: Date.now() / 1000,
+      type: "caption",
+    });
+    await this.page.evaluate(() =>
+      document.getElementById("demo-caption")?.classList.remove("visible"),
+    );
+    await this.page.waitForTimeout(250);
+  }
+
+  /** A pinch that reaches the screen's edge can end without its last touchend reaching the page. */
+  private async liftFingers(): Promise<void> {
+    await this.page.evaluate(() =>
+      document
+        .querySelectorAll<HTMLElement>(".demo-finger")
+        .forEach((finger) => (finger.style.opacity = "0")),
+    );
+  }
+
+  private pageScale(): Promise<number> {
+    return this.page.evaluate(() => window.visualViewport?.scale ?? 1);
+  }
+
+  /**
+   * A two-finger pinch by `factor` around `at`, in viewport pixels. While zoomed in, the gesture
+   * reads its position in page-scale units, so it is divided by the scale the page is at.
+   */
+  private async pinch(
+    at: { x: number; y: number },
+    factor: number,
+    speed: number,
+  ): Promise<void> {
+    const cdp = await this.session();
+    const current = await this.pageScale();
+
+    await cdp.send("Input.synthesizePinchGesture", {
+      gestureSourceType: "touch",
+      relativeSpeed: speed,
+      scaleFactor: factor,
+      x: at.x / current,
+      y: at.y / current,
+    });
+  }
+
+  private async session(): Promise<CDPSession> {
+    this.cdp ??= await this.page.context().newCDPSession(this.page);
+
+    return this.cdp;
+  }
+
+  private async showCaption(text: string): Promise<void> {
+    if (this.timeline) {
+      this.timeline.push({ text, time: Date.now() / 1000, type: "caption" });
+
+      return;
+    }
+
+    await this.page.evaluate((t) => {
+      const el = document.getElementById("demo-caption");
+
+      if (!el) return;
+
+      el.textContent = t;
+      el.classList.add("visible");
+    }, text);
+  }
+}
diff --git a/ui/lib/demo/src/index.ts b/ui/lib/demo/src/index.ts
new file mode 100644
index 000000000..c34b77e47
--- /dev/null
+++ b/ui/lib/demo/src/index.ts
@@ -0,0 +1,6 @@
+export { Demo } from "./demo.ts";
+export {
+  prepareDemoPage,
+  recordDemo,
+  type RecordingOptions,
+} from "./recording.ts";
diff --git a/ui/lib/demo/src/polish.ts b/ui/lib/demo/src/polish.ts
new file mode 100644
index 000000000..160c39c42
--- /dev/null
+++ b/ui/lib/demo/src/polish.ts
@@ -0,0 +1,572 @@
+/**
+ * Polish mode, on unless DEMO_POLISH=0: renders a demo as a branded video instead of the plain screencast.
+ * The app sits in a rounded window on a ground of the Llama brand, `demo.zoom` moves a camera over
+ * the whole stage with eased, motion-blurred moves, and captions sit under the window. A Chromium page styled by
+ * @ggml-org/llama-brand lays out each frame, and ffmpeg encodes its screenshots.
+ *
+ * Env:
+ *   DEMO_POLISH_GROUND  day | night | light | dark | sand (default: day, or night for a dark recording)
+ *   DEMO_POLISH_LOGO    start | end | both: a card with the Llama lockup (default: none)
+ */
+
+import { type Footage, FPS, H264_ARGS } from "./recorder.ts";
+import type { BrowserType } from "@playwright/test";
+import { type ChildProcessByStdio, spawn } from "node:child_process";
+import { rmSync } from "node:fs";
+import { once } from "node:events";
+import type { Writable } from "node:stream";
+import { join, resolve, sep } from "node:path";
+
+export const POLISH = process.env.DEMO_POLISH !== "0";
+export const CAMERA_MOVE_MS = 650;
+/** Added to a test's timeout, as the render runs in the test's teardown. */
+export const POLISH_RENDER_TIMEOUT_MS = 600_000;
+
+/** The grounds of the brand, and whether each takes the light mark of the lockup. */
+const GROUNDS = {
+  dark: true,
+  day: false,
+  light: false,
+  night: true,
+  sand: false,
+};
+const LOGO_CARDS = ["start", "end", "both"];
+const LANDSCAPE = { height: 1080, width: 1920 };
+const PORTRAIT = { height: 1920, width: 1080 };
+/** The brand's grid: every size is a multiple of u, this share of the format's short side. */
+const UNITS_PER_SHORT_SIDE = 24;
+const MARGIN_U = 2;
+const WINDOW_RADIUS_U = 0.55;
+/** A phone's screen has rounder corners than a window, and they are squircles. */
+const PHONE_RADIUS_U = 2.4;
+const CAPTION_HEIGHT_U = 1.6;
+const CAPTION_PAD_U = 0.8;
+const CAPTION_FONT_U = 0.84;
+/** The smallest type the brand allows, which a long caption shrinks to before it is cut. */
+const CAPTION_MIN_FONT_U = 0.58;
+const CAPTION_GAP_U = 0.5;
+const CAPTION_RISE_U = 0.3;
+const CAPTION_FADE_S = 0.35;
+const LOGO_HEIGHT_U = 3;
+const LOGO_CARD_S = 1.6;
+const LOGO_FADE_S = 0.5;
+/** Camera positions averaged into one frame while the camera moves. */
+const BLUR_SAMPLES = 12;
+/** The share of a frame's time those positions span: a film camera's 180 degree shutter. */
+const SHUTTER = 0.5;
+const SHADOW_Y_U = 0.5;
+const SHADOW_BLUR_U = 1.6;
+/** The shadow stops growing with the zoom here, so a close-up keeps a soft edge, not a cloud. */
+const SHADOW_MAX_BLUR_PX = 120;
+const SHADOW_COLOR = "rgb(0 0 0 / 0.18)";
+/** Points along each squircle corner. */
+const SQUIRCLE_STEPS = 24;
+const JPEG_QUALITY = 95;
+/** The stage page, the brand's files and the recorded frames are served from here. */
+const STAGE_ORIGIN = "http://demo.invalid";
+
+/** What a demo did, with the time (seconds, on the clock of Date.now()) it did it at. */
+export type PolishEvent =
+  | { scale: number; time: number; type: "camera"; x: number; y: number }
+  | { text: null | string; time: number; type: "caption" };
+
+interface Size {
+  height: number;
+  width: number;
+}
+
+/** A camera move: soft at both ends and fast through the middle, so it is quick without a jolt. */
+const CAMERA_EASE_POWER = 5;
+const cameraEase = (t: number) => {
+  const x = Math.min(Math.max(t, 0), 1);
+
+  return x < 0.5
+    ? 2 ** (CAMERA_EASE_POWER - 1) * x ** CAMERA_EASE_POWER
+    : 1 - (2 - 2 * x) ** CAMERA_EASE_POWER / 2;
+};
+
+/** Where the stage is drawn in a frame: scaled about its top left corner, then moved. */
+interface Camera {
+  scale: number;
+  x: number;
+  y: number;
+}
+
+/** Where the window sits on the stage, and how much larger it is than the page. */
+interface Layout {
+  fit: number;
+  height: number;
+  left: number;
+  maxWidth: number;
+  size: Size;
+  top: number;
+  u: number;
+  width: number;
+}
+
+interface Shot {
+  caption: null | { opacity: number; text: string };
+  cameras: Camera[];
+  frame: string;
+  /** How much of the logo card shows over the scene, 0 to 1. */
+  logo: number;
+}
+
+const smootherstep = (t: number) => {
+  const x = Math.min(Math.max(t, 0), 1);
+
+  return x * x * x * (x * (x * 6 - 15) + 10);
+};
+
+/**
+ * The camera at any time: each move eases from where the camera was to its target. It looks at the
+ * whole stage, so a zoom brings the window itself closer, with its corners and the ground round it.
+ */
+function cameraPath(
+  events: PolishEvent[],
+  layout: Layout,
+): (time: number) => Camera {
+  /** The point of the stage at the middle of the frame, and the natural log of the scale. */
+  interface View {
+    zoom: number;
+    x: number;
+    y: number;
+  }
+
+  const { height, width } = layout.size;
+  const rest: View = { x: width / 2, y: height / 2, zoom: 0 };
+  const moves: { from: View; start: number; to: View }[] = [];
+  const at = (time: number) => {
+    let view = rest;
+
+    for (const { from, start, to } of moves) {
+      if (time < start) break;
+
+      const k = cameraEase(((time - start) * 1000) / CAMERA_MOVE_MS);
+
+      view = {
+        x: from.x + (to.x - from.x) * k,
+        y: from.y + (to.y - from.y) * k,
+        zoom: from.zoom + (to.zoom - from.zoom) * k,
+      };
+    }
+
+    return view;
+  };
+
+  for (const event of events) {
+    if (event.type !== "camera") continue;
+
+    // the frame stays inside the stage
+    const halfWidth = width / 2 / event.scale;
+    const halfHeight = height / 2 / event.scale;
+    const x = layout.left + event.x * layout.fit;
+    const y = layout.top + event.y * layout.fit;
+
+    moves.push({
+      from: at(event.time),
+      start: event.time,
+      to: {
+        x: Math.min(Math.max(x, halfWidth), width - halfWidth),
+        y: Math.min(Math.max(y, halfHeight), height - halfHeight),
+        zoom: Math.log(event.scale),
+      },
+    });
+  }
+
+  return (time) => {
+    const { x, y, zoom } = at(time);
+    const scale = Math.exp(zoom);
+
+    return { scale, x: width / 2 - x * scale, y: height / 2 - y * scale };
+  };
+}
+
+/** The caption at any time, fading in and out. */
+function captionTrack(
+  events: PolishEvent[],
+  end: number,
+): (time: number) => Shot["caption"] {
+  const spans: { end: number; start: number; text: string }[] = [];
+
+  for (const event of events) {
+    if (event.type !== "caption") continue;
+
+    const last = spans.at(-1);
+
+    if (last && last.end > event.time) last.end = event.time;
+
+    if (event.text !== null)
+      spans.push({ end, start: event.time, text: event.text });
+  }
+
+  return (time) => {
+    const span = spans.find((s) => s.start < time && time < s.end);
+
+    if (!span) return null;
+
+    const opacity = smootherstep(
+      Math.min(time - span.start, span.end - time) / CAPTION_FADE_S,
+    );
+
+    return { opacity, text: span.text };
+  };
+}
+
+/** The window is the page's viewport, as large as fits inside the margin. */
+function stageLayout(viewport: Size, captions: boolean): Layout {
+  const size = viewport.height > viewport.width ? PORTRAIT : LANDSCAPE;
+  const u = Math.min(size.height, size.width) / UNITS_PER_SHORT_SIDE;
+  // the caption row is kept free under the window only when the demo has captions
+  const maxWidth = size.width - 2 * MARGIN_U * u;
+  const maxHeight =
+    size.height -
+    2 * MARGIN_U * u -
+    (captions ? (CAPTION_HEIGHT_U + CAPTION_GAP_U) * u : 0);
+  const fit = Math.min(maxWidth / viewport.width, maxHeight / viewport.height);
+  const width = Math.round(viewport.width * fit);
+  const height = Math.round(viewport.height * fit);
+
+  return {
+    fit,
+    height,
+    left: Math.round((size.width - width) / 2),
+    maxWidth,
+    size,
+    top: Math.round(MARGIN_U * u + (maxHeight - height) / 2),
+    u,
+    width,
+  };
+}
+
+/** The stage: a ground of the brand with the window, the caption chip and the logo card on it. */
+function stageHtml(layout: Layout, dark: boolean): string {
+  const { height, left, maxWidth, size, top, u, width } = layout;
+  const ground = process.env.DEMO_POLISH_GROUND ?? (dark ? "night" : "day");
+
+  if (!(ground in GROUNDS))
+    throw new Error(`demo: no ground "${ground}" in the brand`);
+
+  const phone = size.height > size.width;
+  const radius = (phone ? PHONE_RADIUS_U : WINDOW_RADIUS_U) * u;
+  const mark = GROUNDS[ground as keyof typeof GROUNDS] ? "dark" : "light";
+
+  return `<!doctype html>
+		<link rel="stylesheet" href="/brand/css/colors.css" />
+		<link rel="stylesheet" href="/brand/css/fonts.css" />
+		<link rel="stylesheet" href="/brand/css/communications.css" />
+		<style>
+			body { position: relative; overflow: hidden; margin: 0; width: ${size.width}px; height: ${size.height}px; --u: ${u}px; }
+			#scene, #logo { position: absolute; inset: 0; }
+			#window { position: absolute; inset: 0; }
+			#caption { position: absolute; left: 50%; bottom: calc(var(--u) * ${MARGIN_U}); display: flex; align-items: center;
+				box-sizing: border-box; height: calc(var(--u) * ${CAPTION_HEIGHT_U}); padding: 0 calc(var(--u) * ${CAPTION_PAD_U});
+				max-width: ${maxWidth}px; overflow: hidden; border-radius: 999px; background: var(--p-solid);
+				color: var(--p-solid-ink); white-space: nowrap; opacity: 0; }
+			#logo { opacity: 0; }
+			#logo img { position: absolute; left: 50%; top: 50%; height: calc(var(--u) * ${LOGO_HEIGHT_U}); translate: -50% -50%; }
+		</style>
+		<body class="ground ground-${ground}">
+			<div id="scene">
+				<canvas id="window" width="${size.width}" height="${size.height}" data-left="${left}" data-top="${top}"
+					data-width="${width}" data-height="${height}" data-radius="${radius}" data-squircle="${phone}"
+					data-shadow-y="${SHADOW_Y_U * u}" data-shadow-blur="${SHADOW_BLUR_U * u}"
+					data-shadow-max-blur="${SHADOW_MAX_BLUR_PX}" data-shadow-color="${SHADOW_COLOR}"
+					data-squircle-steps="${SQUIRCLE_STEPS}"></canvas>
+				<div id="caption" data-font="${CAPTION_FONT_U * u}" data-min-font="${CAPTION_MIN_FONT_U * u}"
+					data-rise="${CAPTION_RISE_U * u}"></div>
+			</div>
+			<div id="logo"><img src="/brand/logo/svg/lockup/llama/logo-llama-${mark}.svg" /></div>
+		</body>`;
+}
+
+/** Lays out one output frame on the stage. Runs in the page. */
+async function drawFrame(shot: Shot): Promise<void> {
+  const stage = window as unknown as {
+    demoFrame?: string;
+    demoImage?: ImageBitmap;
+  };
+  const caption = document.querySelector<HTMLElement>("#caption")!;
+
+  if (stage.demoFrame !== shot.frame) {
+    const response = await fetch(shot.frame);
+
+    if (!response.ok)
+      throw new Error(`demo: no frame at ${shot.frame} (${response.status})`);
+
+    stage.demoImage?.close();
+    stage.demoImage = await createImageBitmap(await response.blob());
+    stage.demoFrame = shot.frame;
+  }
+
+  const image = stage.demoImage!;
+  const canvas = document.querySelector<HTMLCanvasElement>("#window")!;
+  const box = { ...canvas.dataset } as Record<string, string>;
+  const [
+    left,
+    top,
+    width,
+    height,
+    radius,
+    shadowY,
+    shadowBlur,
+    shadowMaxBlur,
+    steps,
+  ] = [
+    "left",
+    "top",
+    "width",
+    "height",
+    "radius",
+    "shadowY",
+    "shadowBlur",
+    "shadowMaxBlur",
+    "squircleSteps",
+  ].map((key) => Number(box[key]));
+  const squircle = box.squircle === "true";
+  // a phone's corners are squircles, |x|^4 + |y|^4 = r^4, as CSS draws corner-shape: squircle
+  const outline = (x: number, y: number, w: number, h: number, r: number) => {
+    const path = new Path2D();
+
+    if (!squircle) {
+      path.roundRect(x, y, w, h, r);
+
+      return path;
+    }
+
+    const corners = [
+      [x + w - r, y + r, -Math.PI / 2],
+      [x + w - r, y + h - r, 0],
+      [x + r, y + h - r, Math.PI / 2],
+      [x + r, y + r, Math.PI],
+    ];
+
+    for (const [cx, cy, from] of corners) {
+      for (let step = 0; step <= steps; step++) {
+        const angle = from + (step / steps) * (Math.PI / 2);
+        const [cos, sin] = [Math.cos(angle), Math.sin(angle)];
+
+        path.lineTo(
+          cx + r * Math.sign(cos) * Math.sqrt(Math.abs(cos)),
+          cy + r * Math.sign(sin) * Math.sqrt(Math.abs(sin)),
+        );
+      }
+    }
+
+    path.closePath();
+
+    return path;
+  };
+  const output = canvas.getContext("2d")!;
+  const copy = new OffscreenCanvas(canvas.width, canvas.height).getContext(
+    "2d",
+  )!;
+
+  output.clearRect(0, 0, canvas.width, canvas.height);
+
+  // one copy of the window per camera position, each drawn at 1/n over the ones before, which
+  // leaves their mean: the motion blur. A still frame draws one copy. All of it goes on one canvas:
+  // a layer per copy overruns Chromium's tile memory when the copies are large, and drops tiles
+  shot.cameras.forEach(({ scale, x: cameraX, y: cameraY }, i) => {
+    const shadow = Math.min(scale, shadowMaxBlur / shadowBlur);
+    const [x, y, w, h] = [
+      cameraX + left * scale,
+      cameraY + top * scale,
+      width * scale,
+      height * scale,
+    ];
+    const path = outline(x, y, w, h, radius * scale);
+
+    copy.clearRect(0, 0, canvas.width, canvas.height);
+    copy.save();
+    Object.assign(copy, {
+      fillStyle: "#fff",
+      shadowBlur: shadowBlur * shadow,
+      shadowColor: box.shadowColor,
+      shadowOffsetY: shadowY * shadow,
+    });
+    copy.fill(path);
+    copy.restore();
+    copy.save();
+    copy.clip(path);
+    copy.imageSmoothingQuality = "high";
+    copy.drawImage(image, x, y, w, h);
+    copy.restore();
+    output.globalAlpha = 1 / (i + 1);
+    output.drawImage(copy.canvas, 0, 0);
+  });
+  output.globalAlpha = 1;
+
+  if (shot.caption && caption.textContent !== shot.caption.text) {
+    const font = Number(caption.dataset.font);
+
+    caption.textContent = shot.caption.text;
+    caption.style.fontSize = `${font}px`;
+
+    // a long caption gets smaller type, down to the smallest the brand allows
+    const fit = caption.clientWidth / caption.scrollWidth;
+
+    if (fit < 1) {
+      caption.style.fontSize = `${Math.max(font * fit, Number(caption.dataset.minFont))}px`;
+    }
+  }
+
+  const opacity = shot.caption?.opacity ?? 0;
+
+  caption.style.opacity = String(opacity);
+  caption.style.translate = `-50% ${(1 - opacity) * Number(caption.dataset.rise)}px`;
+  document.getElementById("scene")!.style.opacity = String(1 - shot.logo);
+  document.getElementById("logo")!.style.opacity = String(shot.logo);
+}
+
+/** Renders the recorded frames and the demo's timeline into `mp4`. */
+export async function renderPolished(
+  browserType: BrowserType,
+  brandDir: string,
+  footage: Footage,
+  timeline: PolishEvent[],
+  viewport: Size,
+  dark: boolean,
+  mp4: string,
+): Promise<void> {
+  const card = process.env.DEMO_POLISH_LOGO;
+
+  if (card && !LOGO_CARDS.includes(card))
+    throw new Error(`demo: DEMO_POLISH_LOGO is "${card}"`);
+
+  const layout = stageLayout(
+    viewport,
+    timeline.some((event) => event.type === "caption"),
+  );
+  const html = stageHtml(layout, dark);
+  const { size } = layout;
+  // a browser of its own: the demo's is launched at the recording's device scale, and draws
+  // every frame of this page that many times larger
+  const browser = await browserType.launch({
+    args: ["--force-device-scale-factor=1"],
+    chromiumSandbox: true,
+  });
+  let ffmpeg: ChildProcessByStdio<Writable, null, null> | undefined;
+
+  try {
+    const page = await browser.newPage({
+      deviceScaleFactor: 1,
+      viewport: size,
+    });
+
+    await page.route(`${STAGE_ORIGIN}/**`, (route) => {
+      const path = decodeURIComponent(new URL(route.request().url()).pathname);
+      const file = join(brandDir, path.replace(/^\/brand\//, ""));
+
+      if (path.startsWith("/frames/")) {
+        return route.fulfill({
+          path: footage.frames[Number(path.split("/")[2])].file,
+        });
+      }
+
+      return path.startsWith("/brand/") && file.startsWith(brandDir + sep)
+        ? route.fulfill({ path: file })
+        : route.fulfill({ body: html, contentType: "text/html" });
+    });
+    await page.goto(STAGE_ORIGIN);
+
+    const cdp = await page.context().newCDPSession(page);
+
+    await page.evaluate(async () => {
+      await Promise.all([...document.fonts].map((font) => font.load()));
+      await document.querySelector("img")!.decode();
+    });
+    ffmpeg = spawn(
+      "ffmpeg",
+      [
+        "-y",
+        "-loglevel",
+        "error",
+        "-f",
+        "image2pipe",
+        "-c:v",
+        "mjpeg",
+        "-framerate",
+        String(FPS),
+        "-i",
+        "-",
+        ...H264_ARGS,
+        mp4,
+      ],
+      { stdio: ["pipe", "inherit", "inherit"] },
+    );
+    const start = footage.frames[0].time;
+    const seconds = footage.end - start;
+    const intro = card === "start" || card === "both" ? LOGO_CARD_S : 0;
+    const outro = card === "end" || card === "both" ? LOGO_CARD_S : 0;
+    const cameraAt = cameraPath(timeline, layout);
+    const captionAt = captionTrack(timeline, footage.end);
+    const moved = (a: Camera, b: Camera) =>
+      Math.max(
+        Math.abs(a.x - b.x),
+        Math.abs(a.y - b.y),
+        Math.abs(a.scale - b.scale),
+      ) > 1e-3;
+
+    let source = 0;
+    let drawn = "";
+    let jpeg = Buffer.alloc(0);
+
+    for (let i = 0; i < Math.round((intro + seconds + outro) * FPS); i++) {
+      // the footage holds its first frame under the opening card and its last under the closing one
+      const elapsed = i / FPS - intro;
+      const time = start + Math.min(Math.max(elapsed, 0), seconds);
+
+      while ((footage.frames[source + 1]?.time ?? Infinity) <= time) source++;
+
+      const shot: Shot = {
+        cameras: moved(cameraAt(time), cameraAt(time + 1 / FPS))
+          ? Array.from({ length: BLUR_SAMPLES }, (_, s) =>
+              cameraAt(time + (s / BLUR_SAMPLES) * (SHUTTER / FPS)),
+            )
+          : [cameraAt(time)],
+        caption: captionAt(time),
+        frame: `${STAGE_ORIGIN}/frames/${source}`,
+        logo:
+          elapsed < 0
+            ? 1 - smootherstep(1 + elapsed / LOGO_FADE_S)
+            : smootherstep((elapsed - seconds) / LOGO_FADE_S),
+      };
+      const key = JSON.stringify(shot);
+
+      // a still frame is drawn once
+      if (key !== drawn) {
+        await page.evaluate(drawFrame, shot);
+
+        // straight from Chromium: Playwright's own screenshot is several times slower
+        const { data } = await cdp.send("Page.captureScreenshot", {
+          format: "jpeg",
+          optimizeForSpeed: true,
+          quality: JPEG_QUALITY,
+        });
+
+        jpeg = Buffer.from(data, "base64");
+        drawn = key;
+      }
+
+      if (!ffmpeg.stdin.write(jpeg)) await once(ffmpeg.stdin, "drain");
+    }
+
+    ffmpeg.stdin.end();
+
+    const [code] = await once(ffmpeg, "close");
+
+    if (code !== 0)
+      throw new Error(
+        `demo: ffmpeg exited with ${code} on the polished render`,
+      );
+  } catch (error) {
+    // a part-rendered mp4 would play as a shorter, valid video
+    ffmpeg?.kill("SIGKILL");
+    rmSync(mp4, { force: true });
+
+    throw error;
+  } finally {
+    await browser.close();
+  }
+}
diff --git a/ui/lib/demo/src/recorder.ts b/ui/lib/demo/src/recorder.ts
new file mode 100644
index 000000000..cc327da32
--- /dev/null
+++ b/ui/lib/demo/src/recorder.ts
@@ -0,0 +1,142 @@
+/**
+ * Records a page through Chromium's screencast instead of Playwright's video,
+ * which encodes VP8 at about 1 Mbit/s at 1x scale. Frames arrive at the page's
+ * device pixel ratio, each with its timestamp, and are encoded once into an
+ * H.264 mp4 (what GitHub accepts in PR descriptions).
+ */
+
+import type { CDPSession, Page } from "@playwright/test";
+import { execFileSync } from "node:child_process";
+import { mkdirSync, rmSync, writeFileSync } from "node:fs";
+import { writeFile } from "node:fs/promises";
+import { join } from "node:path";
+
+export const FPS = 60;
+export const H264_ARGS = [
+  "-c:v",
+  "libx264",
+  "-preset",
+  "slow",
+  "-crf",
+  "18",
+  "-pix_fmt",
+  "yuv420p",
+  "-movflags",
+  "+faststart",
+];
+const JPEG_QUALITY = 92;
+
+interface Frame {
+  file: string;
+  /** Seconds, on the same clock as Date.now(). */
+  time: number;
+}
+
+/** The frames as recorded, each shown until the next one's time, the last one until `end`. */
+export interface Footage {
+  end: number;
+  frames: Frame[];
+}
+
+export class ScreencastRecorder {
+  private readonly dir: string;
+  private readonly frames: Frame[] = [];
+  private readonly pending: Promise<void>[] = [];
+  private session: CDPSession | undefined;
+  private stoppedAt = 0;
+
+  /** For a render other than `encode`, which has to `discard` the frames after it. */
+  get footage(): Footage {
+    if (this.frames.length === 0)
+      throw new Error("demo: the screencast captured no frames");
+
+    return { end: this.stoppedAt, frames: this.frames };
+  }
+
+  constructor(dir: string) {
+    this.dir = dir;
+  }
+
+  discard(): void {
+    rmSync(this.dir, { force: true, recursive: true });
+  }
+
+  /** Encodes the frames, each held until the next one arrived (the screencast only sends changes). */
+  encode(mp4: string): void {
+    if (this.frames.length === 0)
+      throw new Error("demo: the screencast captured no frames");
+
+    const list = this.frames.flatMap((frame, i) => {
+      const end = this.frames[i + 1]?.time ?? this.stoppedAt;
+
+      return [
+        `file '${frame.file}'`,
+        `duration ${Math.max(end - frame.time, 1 / FPS).toFixed(4)}`,
+      ];
+    });
+    const listFile = join(this.dir, "frames.txt");
+
+    // the concat demuxer ignores the last entry's duration unless the file is repeated
+    writeFileSync(
+      listFile,
+      [...list, `file '${this.frames.at(-1)!.file}'`, ""].join("\n"),
+    );
+    execFileSync(
+      "ffmpeg",
+      [
+        "-y",
+        "-loglevel",
+        "error",
+        "-f",
+        "concat",
+        "-safe",
+        "0",
+        "-i",
+        listFile,
+        "-vf",
+        `fps=${FPS},scale=trunc(iw/2)*2:trunc(ih/2)*2`,
+        ...H264_ARGS,
+        mp4,
+      ],
+      { stdio: "inherit" },
+    );
+    this.discard();
+  }
+
+  async start(page: Page): Promise<void> {
+    const size = page.viewportSize();
+    const scale = await page.evaluate(() => window.devicePixelRatio);
+
+    rmSync(this.dir, { force: true, recursive: true });
+    mkdirSync(this.dir, { recursive: true });
+
+    this.session = await page.context().newCDPSession(page);
+    this.session.on("Page.screencastFrame", ({ data, metadata, sessionId }) => {
+      const file = join(
+        this.dir,
+        `${String(this.frames.length).padStart(6, "0")}.jpg`,
+      );
+
+      // acknowledged first: Chromium sends the next frame only after the ack
+      this.session
+        ?.send("Page.screencastFrameAck", { sessionId })
+        .catch(() => {});
+      this.frames.push({ file, time: metadata.timestamp ?? Date.now() / 1000 });
+      this.pending.push(writeFile(file, Buffer.from(data, "base64")));
+    });
+    await this.session.send("Page.startScreencast", {
+      everyNthFrame: 1,
+      format: "jpeg",
+      maxHeight: size ? size.height * scale : undefined,
+      maxWidth: size ? size.width * scale : undefined,
+      quality: JPEG_QUALITY,
+    });
+  }
+
+  async stop(): Promise<void> {
+    this.stoppedAt = Date.now() / 1000;
+    await this.session?.send("Page.stopScreencast").catch(() => {});
+    await this.session?.detach().catch(() => {});
+    await Promise.all(this.pending);
+  }
+}
diff --git a/ui/lib/demo/src/recording.ts b/ui/lib/demo/src/recording.ts
new file mode 100644
index 000000000..db11a8870
--- /dev/null
+++ b/ui/lib/demo/src/recording.ts
@@ -0,0 +1,128 @@
+/**
+ * The recording around a demo: the page is prepared before it loads, recorded while the demo drives
+ * it, and rendered into an mp4 that the app's manifest lists for the CLI.
+ */
+
+import { installCursorOverlay, timelines } from "./demo.ts";
+import {
+  POLISH,
+  POLISH_RENDER_TIMEOUT_MS,
+  type PolishEvent,
+  renderPolished,
+} from "./polish.ts";
+import { ScreencastRecorder } from "./recorder.ts";
+import type { Page, TestInfo } from "@playwright/test";
+import { appendFileSync, mkdirSync } from "node:fs";
+import { basename, resolve } from "node:path";
+
+/** How long the page settles (connections, fonts) before the recording starts. */
+const SETTLE_MS = 1500;
+
+export interface RecordingOptions {
+  /** @ggml-org/llama-brand's folder: the render takes its CSS, fonts and lockup from there. */
+  brandDir: string;
+  /** Whether the page is in its dark scheme, which gets the night sky. */
+  dark: boolean;
+  /** Where the videos go, with the manifest of each script that the CLI reads. */
+  videosDir: string;
+}
+
+/**
+ * Draws the cursor in `page` and, for the render, starts the timeline it plays. Call it before
+ * the page loads. A page the render cannot frame (no fixed viewport) records plainly, with
+ * captions and zooms in the page, rather than losing them.
+ */
+export async function prepareDemoPage(
+  page: Page,
+  testInfo: TestInfo,
+): Promise<void> {
+  // the screencast and the render both run on the Chrome DevTools Protocol
+  const browserName = page.context().browser()?.browserType().name();
+
+  if (browserName !== "chromium") {
+    throw new Error(
+      `demo: ${testInfo.title} runs in ${browserName ?? "a browser Playwright did not launch"}, and demos record in Chromium only`,
+    );
+  }
+
+  if (POLISH && page.viewportSize()) timelines.set(page, []);
+
+  await page.addInitScript(installCursorOverlay);
+}
+
+/** Records `page` while `run` drives it, then renders the video and lists it in the script's manifest. */
+export async function recordDemo(
+  page: Page,
+  testInfo: TestInfo,
+  options: RecordingOptions,
+  run: () => Promise<void>,
+): Promise<void> {
+  const timeline: PolishEvent[] | undefined = timelines.get(page);
+
+  const viewport = page.viewportSize();
+
+  if (viewport) await page.mouse.move(viewport.width / 2, viewport.height / 2);
+
+  await page.waitForTimeout(SETTLE_MS);
+
+  const browserType = page.context().browser()?.browserType();
+  const recorder = new ScreencastRecorder(testInfo.outputPath("frames"));
+
+  await recorder.start(page);
+  await run();
+  await recorder.stop();
+
+  // added once the demo is done, so a test.setTimeout() in it cannot take the render's time away
+  if (timeline)
+    testInfo.setTimeout(testInfo.timeout + POLISH_RENDER_TIMEOUT_MS);
+  await page.close();
+
+  if (testInfo.status !== testInfo.expectedStatus) return;
+
+  const file = basename(testInfo.file).replace(/\.demo\.ts$/, "");
+  const name =
+    testInfo.title === "demo" ? file : `${file}--${slugify(testInfo.title)}`;
+  const mp4 = resolve(options.videosDir, `${name}.mp4`);
+
+  mkdirSync(options.videosDir, { recursive: true });
+
+  if (timeline) {
+    if (!viewport || !browserType) {
+      throw new Error(
+        `demo: ${testInfo.title} lost its viewport or browser before the render`,
+      );
+    }
+
+    await renderPolished(
+      browserType,
+      options.brandDir,
+      recorder.footage,
+      timeline,
+      viewport,
+      options.dark,
+      mp4,
+    );
+    recorder.discard();
+  } else {
+    recorder.encode(mp4);
+  }
+
+  // the CLI reads which videos a script made, in order, with their titles
+  appendFileSync(
+    resolve(options.videosDir, `${file}.videos.jsonl`),
+    `${JSON.stringify({
+      description: testInfo.annotations.find((a) => a.type === "description")
+        ?.description,
+      mp4,
+      title: testInfo.title,
+    })}\n`,
+  );
+  console.log(`demo video: ${mp4}`);
+}
+
+function slugify(text: string): string {
+  return text
+    .toLowerCase()
+    .replace(/[^a-z0-9]+/g, "-")
+    .replace(/^-|-$/g, "");
+}
diff --git a/ui/lib/demo/src/storage.ts b/ui/lib/demo/src/storage.ts
new file mode 100644
index 000000000..bb4552527
--- /dev/null
+++ b/ui/lib/demo/src/storage.ts
@@ -0,0 +1,98 @@
+/**
+ * Storage targets for demo scripts and videos, picked by the scheme of the
+ * DEMO_STORAGE URI:
+ *
+ *   hf://buckets/<owner>/<bucket>[/prefix]   Hugging Face bucket, via the `hf` CLI login
+ *   file:///some/dir                         local or mounted directory
+ */
+
+import { execFileSync } from "node:child_process";
+import { copyFileSync, cpSync, existsSync, mkdirSync } from "node:fs";
+import { dirname, join } from "node:path";
+import { fileURLToPath } from "node:url";
+
+export interface DemoStorage {
+  /** Copies every file under remote `dir` into local `target`; returns false when it has none. */
+  downloadDir(dir: string, target: string): boolean;
+  /** Copies local `file` to remote `key`. */
+  upload(file: string, key: string): void;
+}
+
+function joinKey(base: string, key: string): string {
+  return `${base.replace(/\/+$/, "")}/${key}`;
+}
+
+// plain fields: the CLI runs under Node's type stripping, which has no parameter properties
+class HfStorage implements DemoStorage {
+  private readonly base: string;
+
+  constructor(base: string) {
+    this.base = base;
+  }
+
+  downloadDir(dir: string, target: string): boolean {
+    mkdirSync(target, { recursive: true });
+
+    try {
+      execFileSync("hf", ["buckets", "sync", joinKey(this.base, dir), target], {
+        stdio: "inherit",
+      });
+    } catch {
+      return false;
+    }
+
+    return true;
+  }
+
+  upload(file: string, key: string): void {
+    execFileSync("hf", ["buckets", "cp", file, joinKey(this.base, key)], {
+      stdio: "inherit",
+    });
+  }
+}
+
+class FileStorage implements DemoStorage {
+  private readonly root: string;
+
+  constructor(root: string) {
+    this.root = root;
+  }
+
+  downloadDir(dir: string, target: string): boolean {
+    const source = join(this.root, dir);
+
+    if (!existsSync(source)) return false;
+
+    cpSync(source, target, { recursive: true });
+
+    return true;
+  }
+
+  upload(file: string, key: string): void {
+    const target = join(this.root, key);
+
+    mkdirSync(dirname(target), { recursive: true });
+    copyFileSync(file, target);
+  }
+}
+
+export function getDemoStorage(
+  uri = process.env.DEMO_STORAGE,
+): DemoStorage | null {
+  if (!uri) return null;
+
+  if (uri.startsWith("hf://")) return new HfStorage(uri);
+
+  if (uri.startsWith("file://")) return new FileStorage(fileURLToPath(uri));
+
+  throw new Error(
+    `DEMO_STORAGE: unsupported scheme in "${uri}" (use hf:// or file://)`,
+  );
+}
+
+/** Public URL of a stored key, when DEMO_STORAGE_PUBLIC_URL is set. */
+export function getPublicUrl(key: string): string | null {
+  const base = process.env.DEMO_STORAGE_PUBLIC_URL;
+
+  return base ? joinKey(base, key) : null;
+}
diff --git a/ui/lib/demo/tsconfig.json b/ui/lib/demo/tsconfig.json
new file mode 100644
index 000000000..6f4b37c55
--- /dev/null
+++ b/ui/lib/demo/tsconfig.json
@@ -0,0 +1,16 @@
+{
+  "compilerOptions": {
+    "target": "ES2022",
+    "lib": ["ES2022", "DOM", "DOM.Iterable"],
+    "module": "NodeNext",
+    "moduleResolution": "NodeNext",
+    "strict": true,
+    "verbatimModuleSyntax": true,
+    "erasableSyntaxOnly": true,
+    "allowImportingTsExtensions": true,
+    "noEmit": true,
+    "skipLibCheck": true,
+    "types": ["node"]
+  },
+  "include": ["src"]
+}