Files
llama.cpp/tools/ui/demo/helpers.ts
T
Aleksander Grygier 0943ca5472 ui: add Playwright harness for recording demo videos (#31318)
* ui: add Playwright harness for recording demo videos

Scripted walkthroughs under tools/ui/demo are recorded with Playwright and
exported as H.264 mp4 for pull requests (demo/pr) and docs (demo/docs).
Fixture MCP servers and seeded settings keep recordings deterministic, a
drawn cursor and captions make the flow readable, and DEMO_UI_DIR points
the recording at another checkout such as a PR worktree.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: record demo scripts from PR descriptions and a configurable storage

Demo scripts no longer live in the repo. `npm run demo:pr -- <number>`
records the `ts demo` block from a PR description against the PR head,
uploads the mp4, a GIF preview and the script to DEMO_STORAGE, and links
the preview in a `## Demo` section of the PR description.
`npm run demo:docs` records the docs scripts kept in DEMO_STORAGE.
DEMO_STORAGE (hf:// buckets or file://) and the public URL are read
from tools/ui/.env.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: import generated conversations into demo recordings

Demos can now start with existing chats: `test.use({ traces })` imports
llama.app JSONL traces through Settings > Import/Export before the video
starts. Built-in traces are generated deterministically, other names are
downloaded from DEMO_TRACES_DATASET, and `demo:traces` pushes the built-in
ones there. Adds `demo.scroll` for wheel scrolling.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: keep demo captions clear of the chat form and isolate concurrent runs

Captions move to the top of the frame, since at the bottom they covered
the chat form a demo is often about. Each recording run gets its own
Playwright output folder, so a run starting elsewhere no longer clears
another run's video before it is saved.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: record demos at 2x and 60 fps with human-like timing

Recording goes through Chromium's screencast instead of Playwright's
video, which encoded VP8 at about 1 Mbit/s at 1x. Frames are captured at
the device pixel ratio (DEMO_SCALE, default 2) and encoded into a 60 fps
H.264 mp4, starting once the page has settled.

The cursor now glides faster along a slight arc with Fitts-like
durations, settles briefly before each click, and typing and pauses vary
a little. The randomness is seeded per demo, so re-recording gives the
same motion.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: document the demo harness prerequisites

The demo README now lists the tools the harness needs and what each is
for, and walks through creating the Hugging Face bucket and the optional
traces dataset, with the matching .env settings.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: version linked demo URLs so re-recorded previews refresh

GitHub's image proxy caches a preview by URL, so a demo re-recorded at
the same PR head kept showing the old GIF. The Demo section now links
the files with a content hash in the query string.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: label PRs that feature a video demo

Adds a `video demo` label and a workflow that applies it when a PR
description has a demo written by the UI demo pipeline (the managed
demo:start/demo:end markers, or a preview linking to a demo video),
and removes it when that section is gone.

Assisted-by: Claude (Opus 5.5 Medium)

* ci: label video demos with gh instead of github-script

The label workflow now runs the gh CLI in a shell step, like
pr-draft-label.yml, so it needs no action outside the repository's
allowed list. The video link check only counts videos uploaded for the
PR itself, so a description linking other PRs' demos isn't labeled.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: zoom demos in on details with a two-finger pinch

demo.zoom pinches in on a control or a point, holds, and pinches back out
to 1x, so a detail too small to read in the frame can be shown up close.
It drives Chromium's own pinch gesture, so the page's fixed bars stay put,
and works at desktop and phone sizes alike.

The pinch is evened out where Chromium misses: one anchored near the top
does not zoom at all, so it starts lower, and one near the bottom
overshoots its ratio, so a small pinch from the middle corrects it. The
way out reads the real scale until the page is back at 1x, which the next
gesture needs.

The overlay also draws a fingertip per touch, so a pinch on a touch
device shows as two fingers.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: wait out a cold dev server before a demo starts

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,
so a demo failed before it started. The demo now waits up to 90 seconds
for the app; the recording only starts once it is ready.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: record a video per test in a PR demo, shown in a table

A large PR can split its demo into several shorter videos: each test()
in the ts demo block is recorded as its own video (<sha>-1.mp4, ...),
and the Demo section lays their previews out in a table, each column
headed by its test's title.

GIF previews now keep their longer side at DEMO_PREVIEW_WIDTH and shrink
until they are under 5 MB, since GitHub's image proxy refuses anything
larger and shows a broken image instead.

Importing traces works on a phone viewport too, where Settings sits in
the sidebar under the page until the menu key slides it aside.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: fix demo trace imports on desktop and lay landscape demos out two to a row

Importing traces failed on a desktop whose collapsed sidebar sits under
the page: it now expands the sidebar from the page's menu key on a phone
or from the sidebar's logo on a desktop, whichever makes Settings
reachable. Afterwards it forgets the expanded sidebar, so a demo starts
with it collapsed, as on a first visit.

A PR demo with several videos shows up to four portrait (phone) videos
to a row, or two landscape ones, so each preview stays readable.

Assisted-by: Claude (Opus 5.5 Medium)

* ui: only record other people's PR demos at a reviewed head commit

demo:pr runs the PR's code and demo script on this machine, with the
gh and hf logins, so a PR by someone else now needs --trust <sha>
naming the head commit that was read, and is refused again after new
pushes. Recordings also launch Chromium with its sandbox on, which
Playwright turns off by default.

Assisted-by: Claude (Opus 5.5 Medium)
2026-11-03 12:30:49 +01:00

501 lines
17 KiB
TypeScript

import { demoMcpServerSettings } from './fixtures/demo-config.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 { execFileSync } from 'node:child_process';
import { appendFileSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
import { basename, join, resolve } from 'node:path';
const VIDEOS_DIR = resolve(import.meta.dirname, 'videos');
/** 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 {
const key = 'LlamaUi.config';
if (localStorage.getItem(key) === null) {
localStorage.setItem(key, JSON.stringify(config));
}
}
/** 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.page.evaluate((t) => {
const el = document.getElementById('demo-caption');
if (!el) return;
el.textContent = t;
el.classList.add('visible');
}, text);
await this.page.waitForTimeout(ms);
await this.page.evaluate(() =>
document.getElementById('demo-caption')?.classList.remove('visible')
);
await this.page.waitForTimeout(250);
}
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;
}
async hover(target: Locator, ms = 350): Promise<void> {
await this.moveTo(target);
await this.pause(ms);
}
/** 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);
}
/** 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 };
}
/** 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;
}
}
interface DemoOptions {
/** Path the demo starts from. */
startPath: string;
/** Extra UI settings merged into the seeded config. */
settings: Record<string, unknown>;
/**
* Conversations imported before the demo starts: built-in traces from
* fixtures/traces.ts, or `<name>.jsonl` files from DEMO_TRACES_DATASET.
*/
traces: string[];
}
/** Reads a trace by name, generating built-in ones and downloading the rest. */
function loadTrace(name: string, dir: string): string {
const generated = generateTrace(name);
if (generated) return generated;
const dataset = process.env.DEMO_TRACES_DATASET;
if (!dataset)
throw new Error(`demo: no built-in trace "${name}" and DEMO_TRACES_DATASET is not set`);
execFileSync(
'hf',
['download', dataset, `${name}.jsonl`, '--repo-type', 'dataset', '--local-dir', dir],
{ stdio: 'inherit' }
);
return readFileSync(join(dir, `${name}.jsonl`), 'utf8');
}
/** Imports conversations through Settings > Import/Export, like a user would. */
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) =>
target.click({ timeout: 2000, trial: true }).then(
() => true,
() => false
);
// a collapsed sidebar can sit under the page: on a phone the page's menu key slides it aside,
// on a desktop its logo expands it
const keys = [
page.locator('xpath=//button[@aria-label="Expand navigation"][not(ancestor::aside)]'),
page.locator('aside button[aria-label="Expand navigation"]')
];
for (const key of keys) {
if (await reachable(settings)) break;
if ((await key.count()) > 0 && (await reachable(key.first()))) await key.first().click();
}
await settings.click();
const dialog = page.getByRole('dialog');
await dialog.getByText('Import/Export', { exact: true }).filter({ visible: true }).click();
const chooser = page.waitForEvent('filechooser');
await dialog.getByRole('button', { name: 'Import conversations' }).click();
await (await chooser).setFiles(file);
await page.getByRole('button', { name: /^Import \(\d+\)$/ }).click();
await page.getByRole('heading', { name: /^Imported \d+ conversation/ }).waitFor();
// the app remembers the sidebar the import expanded; a demo starts with it collapsed, as on a
// first visit
await page.evaluate(() => {
for (const key of Object.keys(localStorage)) {
if (key.endsWith('.sidebarExpanded')) localStorage.removeItem(key);
}
});
}
export const test = base.extend<DemoOptions & { demo: Demo }>({
demo: async ({ page }, use, testInfo) => {
await use(new Demo(page, `${testInfo.file}:${testInfo.title}`));
},
page: async ({ 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);
}
await page.goto(startPath);
// a hash route after the import doesn't reload, which the conversations list needs
if (traces.length > 0) await page.reload();
// 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 });
const viewport = page.viewportSize();
if (viewport) await page.mouse.move(viewport.width / 2, viewport.height / 2);
// let MCP connections and fonts settle before the recording starts
await page.waitForTimeout(1500);
const recorder = new ScreencastRecorder(testInfo.outputPath('frames'));
await recorder.start(page);
await use(page);
await recorder.stop();
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(VIDEOS_DIR, `${name}.mp4`);
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`
);
console.log(`demo video: ${mp4}`);
},
settings: [{}, { option: true }],
startPath: ['/', { 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, '');
}