cuetake 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -6,12 +6,13 @@
6
6
 
7
7
  Built entirely for AI agents, CueTake turns browser interactions into sharp product demo videos with a precise cursor and continuous camera moves. Give an agent a scenario, then capture, render, and verify the result locally.
8
8
 
9
- ![A CueTake Final: the page in a browser window on a gradient, the camera zooming to the field being typed into](docs/media/demo.gif)
9
+ ![A CueTake Final: Excalidraw in a browser window over purple fluted glass, the camera following as a sign-up flow is drawn, labeled, linked and filled](docs/media/demo.gif)
10
10
 
11
11
  - Retina tab capture at 30 or 60 fps and a 2× pixel scale, headless by default.
12
12
  - An automatic camera in the style of Screen Studio: it arrives just before each click, field and drag, follows the cursor on a spring, and ends on the wide shot.
13
- - The page framed in a browser or macOS window on a gradient, brand-colored or blurred background, at 16:9, 1:1 or 9:16.
14
- - Cursor and click sparks drawn at Render time, so a Take can be restyled without recording again.
13
+ - The page framed in a browser or macOS window over fluted glass lit in the product's brand color, at any output size; backgrounds, chrome, cursors and click effects are shaders or drawing code the agent can write.
14
+ - A Cursor drawn at Render time in the shape the page asks for, pressing on each click, so a Take can be restyled without recording again.
15
+ - Keyboard shortcuts shown as keycaps, so a demo of a command palette or an editor teaches the keys it presses.
15
16
  - Styling chosen in conversation: the agent shows Previews of candidate Looks side by side in about a second, and the Look you pick is saved for later Takes.
16
17
  - Rendering in Chromium with WebGL and WebCodecs: no FFmpeg, 4K60 by default.
17
18
  - A separate folder for every Take: Source, Timeline, Edit, Final MP4, and verification.
@@ -47,6 +48,7 @@ Playwright is a local package dependency. Browser binaries use Playwright's norm
47
48
  ```sh
48
49
  bun src/cli.js doctor
49
50
  bun src/cli.js install-browser
51
+ bun src/cli.js uninstall --dry-run
50
52
  bun src/cli.js record ./my-scenario.mjs --out ./recordings/my-take [--headed]
51
53
  bun src/cli.js render ./recordings/my-take
52
54
  bun src/cli.js verify ./recordings/my-take
@@ -60,13 +62,13 @@ A successful command is a technical check, not an editorial approval. Watch the
60
62
 
61
63
  ## How it works
62
64
 
63
- Playwright drives an isolated Chromium tab. Chromium captures the tab at device-pixel resolution using `getDisplayMedia`; a VP9 `MediaRecorder` saves the source. An in-page probe records the pointer path, clicks, drags and typing into the Timeline. Render then composes the camera path in a headless Chromium page with WebGL and encodes H.264 with WebCodecs; see [ADR 0001](docs/adr/0001-render-in-browser-with-webgl-and-webcodecs.md).
65
+ Playwright drives an isolated Chromium tab. Chromium captures the tab at device-pixel resolution using `getDisplayMedia`; a VP9 `MediaRecorder` saves the source. An in-page probe records the pointer path, clicks, drags, typing and shortcuts into the Timeline. Render then composes the camera path in a headless Chromium page with WebGL and encodes H.264 with WebCodecs; see [ADR 0001](docs/adr/0001-render-in-browser-with-webgl-and-webcodecs.md).
64
66
 
65
67
  Source capture is variable frame rate. Static scenes may drop to approximately one captured frame per second, and busy scenes can drop frames. A 60 fps output does not imply 60 unique source frames every second. Capture callback statistics and output metadata are retained in each take. No motion interpolation is used.
66
68
 
67
69
  ## Current scope
68
70
 
69
- The supported workflow is a short, same-document browser demo, including SPA interactions. A full page navigation or reload destroys the in-page recorder; record those as separate takes. Audio and desktop/window capture are outside this workflow. Input inside cross-origin iframes is not seen by the Timeline probe, so the cursor and camera do not follow it there. Headless Chromium renders the generic `monospace` family as Courier rather than Menlo; record with `--headed` when a page relies on it. Browser automation and captured data stay local; the visited website still receives normal browser requests.
71
+ The supported workflow is a short, same-document browser demo, including SPA interactions. A full page navigation or reload destroys the in-page recorder; record those as separate takes. Page audio and desktop/window capture are outside this workflow; a Narration voiced by a separate speech tool is mixed in at Render, with Subtitles ([narration](skills/cuetake/narration.md)). Input inside cross-origin iframes is not seen by the Timeline probe, so the cursor and camera do not follow it there. Headless Chromium renders the generic `monospace` family as Courier rather than Menlo; record with `--headed` when a page relies on it. Browser automation and captured data stay local; the visited website still receives normal browser requests.
70
72
 
71
73
  The bundled [agent skill](skills/cuetake/SKILL.md) teaches planning and operation; site-specific scenarios stay in your application project. See [distribution](docs/distribution.md) and [login](skills/cuetake/authentication.md).
72
74
 
@@ -78,4 +80,4 @@ bun test tests/pipeline.test.js
78
80
  bun test tests/browser.test.js
79
81
  ```
80
82
 
81
- `pipeline.test.js` covers configuration and camera math; `browser.test.js` covers the probe, Auth profiles, and Render geometry, cursor and sparks at a 2× capture scale. No build step is required. Do not commit recordings, browser profiles, credentials, or product-specific scenarios into this generic tool repository.
83
+ `pipeline.test.js` covers configuration and camera math; `browser.test.js` covers the probe, Auth profiles, and Render geometry, the Cursor's shape, press and fade, and sparks at a 2× capture scale. No build step is required. Do not commit recordings, browser profiles, credentials, or product-specific scenarios into this generic tool repository.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "cuetake",
3
- "version": "0.2.0",
3
+ "version": "0.4.0",
4
4
  "description": "Local recording runtime for AI agents: plan a browser demo, capture it, and render a finished take.",
5
5
  "type": "module",
6
6
  "bin": {
@@ -39,5 +39,5 @@
39
39
  "engines": {
40
40
  "node": ">=20.10.0"
41
41
  },
42
- "packageManager": "bun@1.3.14"
42
+ "packageManager": "bun@1.4.4"
43
43
  }
package/src/auth.js CHANGED
@@ -5,8 +5,9 @@ import { join } from 'node:path';
5
5
  import { randomUUID } from 'node:crypto';
6
6
  import { setTimeout as sleep } from 'node:timers/promises';
7
7
  const root = () => process.env.CUETAKE_AUTH_DIR || join(homedir(), '.local/share/cuetake/auth');
8
+ const NAME = /^[a-z0-9][a-z0-9-]{0,63}$/;
8
9
  function profilePath(profile) {
9
- if (!/^[a-z0-9][a-z0-9-]{0,63}$/.test(profile)) throw new Error('Use a short lowercase profile name, such as product-demo');
10
+ if (!NAME.test(profile)) throw new Error('Use a short lowercase profile name, such as product-demo');
10
11
  return join(root(), `${profile}.json`);
11
12
  }
12
13
  export async function resolveAuthProfile(profile) {
@@ -14,6 +15,12 @@ export async function resolveAuthProfile(profile) {
14
15
  await fs.access(path).catch(() => { throw new Error(`Auth profile '${profile}' is missing. Run: cuetake login ${profile} <login-url>`); });
15
16
  return path;
16
17
  }
18
+ /** The saved Auth profile files, with any left over from an interrupted save; other files in the folder are not CueTake's. */
19
+ export async function authProfileFiles() {
20
+ const dir = root(), names = await fs.readdir(dir).catch(error => { if (error.code === 'ENOENT') return []; throw error; });
21
+ const paths = names.filter(name => { const [profile, ext, ...rest] = name.split('.'); return NAME.test(profile) && ext === 'json' && (rest.length === 0 || (rest.length === 2 && rest[1] === 'tmp')); });
22
+ return { dir, paths: paths.sort().map(name => join(dir, name)) };
23
+ }
17
24
  /** Accepts a browser context or an already-read storage state. */
18
25
  export async function saveAuthState(source, profile) {
19
26
  const path = profilePath(profile);
package/src/cli.js CHANGED
@@ -1,9 +1,11 @@
1
1
  #!/usr/bin/env node
2
2
  import { parseArgs } from 'node:util';
3
3
  import pkg from '../package.json' with { type: 'json' };
4
- import { recordScenario, renderTake, verifyTake, previewTake, applyLookToTake, saveLookFromTake } from './pipeline.js';
4
+ import { recordScenario, renderTake, verifyTake, previewTake, applyLookToTake, saveLookFromTake, importNarration } from './pipeline.js';
5
5
  import { listLooks, removeLook } from './look.js';
6
+ import { BUILTINS, BUILTIN_DIR } from './styles.js';
6
7
  import { doctor, installBrowser } from './environment.js';
8
+ import { uninstall } from './uninstall.js';
7
9
  import { login } from './auth.js';
8
10
  import { extractFrame } from './render.js';
9
11
  import { writeFile } from 'node:fs/promises';
@@ -13,7 +15,9 @@ const help = `CueTake ${pkg.version} — browser demos directed by code
13
15
 
14
16
  cuetake doctor
15
17
  cuetake install-browser
16
- cuetake record <scenario.mjs> [--out <new-directory>] [--auth-profile <name>] [--look <name|file.json>] [--headed]
18
+ cuetake uninstall [--auth] [--looks] [--dry-run]
19
+ cuetake record <scenario.mjs> [--out <new-directory>] [--auth-profile <name>] [--look <name|file.json>] [--narration <narration.json>] [--headed]
20
+ cuetake narrate import <take-directory> <narration.json>
17
21
  cuetake preview <take-directory> [--look <name|file.json>]... [--at <seconds>]
18
22
  cuetake render <take-directory>
19
23
  cuetake verify <take-directory>
@@ -23,28 +27,41 @@ const help = `CueTake ${pkg.version} — browser demos directed by code
23
27
  cuetake look save <name> <take-directory> [--global] [--replace]
24
28
  cuetake look apply <name|file.json> <take-directory>
25
29
  cuetake look rm <name> [--global]
30
+ cuetake styles
26
31
 
27
32
  install-browser downloads the Chromium build this CueTake version drives (about 150 MB).
33
+ uninstall removes CueTake's npx cache and its browser, unless another Playwright installation uses it.
34
+ It keeps Auth profiles unless --auth and global Looks unless --looks; Take folders and local Looks
35
+ are never touched. --dry-run lists what would go and removes nothing.
28
36
  record captures, renders and verifies a new take; an existing directory is never overwritten.
29
37
  Capture runs headless; --headed shows the browser window while recording.
30
38
  --look seeds the first Edit from a Look; fields the Scenario config names win.
31
- preview writes preview.png in the take: the current Edit beside up to five Looks, at --at seconds
39
+ --narration copies a Narration and its audio into the Take first: d.say(id) holds each Line for its audio.
40
+ narrate import copies a Narration and its audio into a recorded Take, replacing its earlier one. Lines keep
41
+ their start in edit.json; a new Line takes the start the file gives it. Render plays and subtitles them.
42
+ preview writes preview.png in the take: the current Edit beside each Look, at --at seconds
32
43
  or at the end with the camera wide. It never changes edit.json or final.mp4.
33
44
  render reuses source.webm, timeline.json and edit.json, replacing final.mp4 only on success.
34
45
  frame saves one Final frame as a PNG for inspection.
35
46
  login opens a separate browser; close its window after logging in to save the profile.
36
- A Look is a take's reusable styling. Looks are saved locally (.cuetake/looks in this directory)
37
- unless --global; a local Look hides a global one with the same name. apply rewrites edit.json.
38
- Scenario files are trusted JavaScript. Recording runs locally, without audio.
47
+ A Look is a take's reusable styling, with the files it draws with. Looks are saved locally
48
+ (.cuetake/looks in this directory) unless --global; a local Look hides a global one with the same
49
+ name. list names the code each Look runs. apply rewrites edit.json and copies files into styles/.
50
+ styles lists the built-in shaders and drawing code, with their files and starting parameters.
51
+ Styling is agent-written code and is not validated; the render page has no network.
52
+ Scenario files are trusted JavaScript. Recording runs locally and captures no page audio; Narration is
53
+ voiced beforehand by a speech tool of your choice.
39
54
  `;
40
55
  try {
41
- const { values, positionals } = parseArgs({ args: process.argv.slice(2), allowPositionals: true, options: { out: { type: 'string' }, help: { type: 'boolean', short: 'h' }, 'auth-profile': { type: 'string' }, headed: { type: 'boolean' }, look: { type: 'string', multiple: true }, at: { type: 'string' }, global: { type: 'boolean' }, replace: { type: 'boolean' } } });
56
+ const { values, positionals } = parseArgs({ args: process.argv.slice(2), allowPositionals: true, options: { out: { type: 'string' }, help: { type: 'boolean', short: 'h' }, 'auth-profile': { type: 'string' }, headed: { type: 'boolean' }, look: { type: 'string', multiple: true }, narration: { type: 'string' }, at: { type: 'string' }, global: { type: 'boolean' }, replace: { type: 'boolean' }, auth: { type: 'boolean' }, looks: { type: 'boolean' }, 'dry-run': { type: 'boolean' } } });
42
57
  const [command, target] = positionals, looks = values.look ?? [];
43
58
  const print = data => console.log(JSON.stringify(data, null, 2));
44
59
  if (values.help || !command) console.log(help);
45
60
  else if (command === 'doctor') { const result = await doctor(); console.log(JSON.stringify(result, null, 2)); if (!result.ok) process.exitCode = 1; }
46
61
  else if (command === 'install-browser') console.log(JSON.stringify(await installBrowser(), null, 2));
47
- else if (command === 'record' && target && looks.length <= 1) print(await recordScenario(target, values.out, { authProfile: values['auth-profile'], look: looks[0], headed: values.headed }));
62
+ else if (command === 'uninstall' && !target) print(await uninstall({ auth: values.auth, looks: values.looks, dryRun: values['dry-run'] }));
63
+ else if (command === 'record' && target && looks.length <= 1) print(await recordScenario(target, values.out, { authProfile: values['auth-profile'], look: looks[0], narration: values.narration, headed: values.headed }));
64
+ else if (command === 'narrate' && target === 'import' && positionals[3]) print(await importNarration(positionals[2], positionals[3]));
48
65
  else if (command === 'preview' && target) print(await previewTake(target, looks, { at: values.at === undefined ? undefined : Number(values.at) }));
49
66
  else if (command === 'render' && target) { await renderTake(target); console.log(JSON.stringify(await verifyTake(target), null, 2)); }
50
67
  else if (command === 'verify' && target) console.log(JSON.stringify(await verifyTake(target), null, 2));
@@ -58,5 +75,6 @@ try {
58
75
  else if (command === 'look' && target === 'save' && positionals[3]) print(await saveLookFromTake(positionals[2], positionals[3], { global: values.global, replace: values.replace }));
59
76
  else if (command === 'look' && target === 'apply' && positionals[3]) print(await applyLookToTake(positionals[2], positionals[3]));
60
77
  else if (command === 'look' && target === 'rm' && positionals[2]) print(await removeLook(positionals[2], { global: values.global }));
78
+ else if (command === 'styles') print(Object.entries(BUILTINS).map(([name, { file, params }]) => ({ name, kind: file.endsWith('.glsl') ? 'shader' : 'draw', path: join(BUILTIN_DIR, file), params })));
61
79
  else throw new Error(`Unknown or incomplete command.\n${help}`);
62
80
  } catch (error) { console.error(`CueTake: ${error.message}`); process.exitCode = 1; }
package/src/cursor.js CHANGED
@@ -3,11 +3,19 @@
3
3
  * Pure functions shared by Node and the render page; CSS pixels and seconds throughout.
4
4
  */
5
5
 
6
+ const PRESS_IN = 0.08, PRESS_OUT = 0.3; // seconds to shrink when a button goes down and to spring back after it is released
7
+
8
+ /** The index of the last entry of `list` (sorted by `time(entry)`) at or before `t`, or -1. */
9
+ function lastAt(list, t, time) {
10
+ let low = 0, high = list.length - 1, found = -1;
11
+ while (low <= high) { const mid = (low + high) >> 1; if (time(list[mid]) <= t) { found = mid; low = mid + 1; } else high = mid - 1; }
12
+ return found;
13
+ }
14
+
6
15
  /** The pointer position at `t`, interpolated between samples; null before the first sample. */
7
16
  export function pointerAt(pointer, t) {
8
- if (!pointer.length || t < pointer[0][0]) return null;
9
- let low = 0, high = pointer.length - 1;
10
- while (low < high) { const mid = (low + high + 1) >> 1; if (pointer[mid][0] <= t) low = mid; else high = mid - 1; }
17
+ const low = lastAt(pointer, t, sample => sample[0]);
18
+ if (low < 0) return null;
11
19
  const [t0, x0, y0] = pointer[low], next = pointer[low + 1];
12
20
  if (!next || next[0] === t0) return { x: x0, y: y0 };
13
21
  const k = (t - t0) / (next[0] - t0);
@@ -20,38 +28,57 @@ export function presses(events) {
20
28
  : event.type === 'drag' ? [{ t: event.t, ...event.from }] : []);
21
29
  }
22
30
 
23
- /** Sparks alive at `t`, each with its progress from 0 to 1. */
31
+ /** Click effects alive at `t`, each with its progress from 0 to 1; `clickEffect: false` shows none. */
24
32
  export function sparksAt(pressList, clickEffect, t) {
25
- if (clickEffect.style === 'none') return [];
26
- const life = clickEffect.duration / 1000;
33
+ if (!clickEffect) return [];
34
+ const life = (clickEffect.duration ?? 400) / 1000;
27
35
  return pressList.filter(p => t >= p.t && t < p.t + life).map(p => ({ x: p.x, y: p.y, progress: (t - p.t) / life }));
28
36
  }
29
37
 
30
- /** Arrow outline in its 28×36 design box; the hotspot is the tip at (2, 2). */
31
- export const ARROW_PATH = 'M2 2 L2 27 L8.5 21 L14 33 L19 30.5 L13.5 19 L23 19 Z';
38
+ /** When a button is held: each click and drag from press to release. */
39
+ export const heldSpans = events => events.filter(event => event.type === 'click' || event.type === 'drag').map(event => ({ t: event.t, end: event.end ?? event.t }));
40
+
41
+ const easeOut = u => 1 - (1 - u) ** 3;
42
+ const springBack = u => { const c = 1.70158; return 1 + (c + 1) * (u - 1) ** 3 + c * (u - 1) ** 2; };
43
+
44
+ /** The Cursor's scale at `t`: down to `press` while a button is held, springing back after; `press: false` keeps 1. */
45
+ export function pressScale(spans, press, t) {
46
+ if (typeof press !== 'number') return 1;
47
+ const span = spans[lastAt(spans, t, s => s.t)];
48
+ if (!span) return 1;
49
+ const down = held => 1 - (1 - press) * easeOut(Math.min(1, held / PRESS_IN));
50
+ if (t <= span.end) return down(t - span.t);
51
+ const u = (t - span.end) / PRESS_OUT, from = down(span.end - span.t);
52
+ return u >= 1 ? 1 : from + (1 - from) * springBack(u);
53
+ }
32
54
 
33
- /** Cursor sprite geometry in CSS pixels: drawn size and the hotspot offset from its top-left. */
34
- export function cursorGeometry(cursor) {
35
- return cursor.style === 'arrow'
36
- ? { width: cursor.size, height: cursor.size * 36 / 28, hotspot: { x: cursor.size * 2 / 28, y: cursor.size * 2 / 28 } }
37
- : { width: cursor.size, height: cursor.size, hotspot: { x: cursor.size / 2, y: cursor.size / 2 } };
55
+ /** The cursor shape the page asked for at `t`, as a CSS keyword; `default` before the first. */
56
+ export function shapeAt(shapes, t) {
57
+ return shapes[lastAt(shapes, t, entry => entry[0])]?.[1] ?? 'default';
38
58
  }
39
59
 
40
- /** Draws one spark centered in a 2D context whose unit is one CSS pixel. */
41
- export function drawSpark(ctx, x, y, progress, clickEffect, color) {
42
- const eased = 1 - (1 - progress) ** 3;
43
- const distance = 5 + eased * clickEffect.radius;
44
- const length = clickEffect.length * (1 - eased);
45
- ctx.globalAlpha = 1 - progress;
46
- ctx.lineCap = 'round';
47
- for (let i = 0; i < clickEffect.count; i++) {
48
- const angle = 2 * Math.PI * i / clickEffect.count + Math.PI / 8;
49
- ctx.beginPath();
50
- ctx.moveTo(x + distance * Math.cos(angle), y + distance * Math.sin(angle));
51
- ctx.lineTo(x + (distance + length) * Math.cos(angle), y + (distance + length) * Math.sin(angle));
52
- // A dark edge under a cursor-colored core stays legible on light and dark pages.
53
- ctx.strokeStyle = '#171717'; ctx.lineWidth = 4.5; ctx.stroke();
54
- ctx.strokeStyle = color; ctx.lineWidth = 2.5; ctx.stroke();
55
- }
56
- ctx.globalAlpha = 1;
60
+ // Keywords that name the same picture as one a cursor is more likely to draw.
61
+ const ALIASES = {
62
+ progress: 'wait', 'all-scroll': 'move', 'no-drop': 'not-allowed',
63
+ 'col-resize': 'ew-resize', 'e-resize': 'ew-resize', 'w-resize': 'ew-resize',
64
+ 'row-resize': 'ns-resize', 'n-resize': 'ns-resize', 's-resize': 'ns-resize',
65
+ 'ne-resize': 'nesw-resize', 'sw-resize': 'nesw-resize', 'nw-resize': 'nwse-resize', 'se-resize': 'nwse-resize',
66
+ };
67
+
68
+ /** The shape a cursor drawing `drawn` (a Set of names) shows for `keyword`: itself, its alias, or `default`. */
69
+ export const drawnShape = (keyword, drawn) => drawn.has(keyword) ? keyword : drawn.has(ALIASES[keyword]) ? ALIASES[keyword] : 'default';
70
+
71
+ /**
72
+ * The Cursor through a Take: `at(t)` gives its point, scale and the shape the page asked for,
73
+ * or null before the first pointer sample. `cursor` is the Edit's cursor item.
74
+ */
75
+ export function cursorTrack({ pointer, shapes = [], events }, cursor) {
76
+ const spans = heldSpans(events);
77
+ return {
78
+ at(t) {
79
+ const point = pointerAt(pointer, t);
80
+ if (!point) return null;
81
+ return { ...point, scale: pressScale(spans, cursor.press, t), shape: shapeAt(shapes, t) };
82
+ },
83
+ };
57
84
  }
package/src/director.js CHANGED
@@ -1,21 +1,31 @@
1
- /** Timed, viewport-aligned interactions shared by all scenarios. */
2
- export function createDirector(page, startedAt, fps, focusTargets, wideWindows) {
1
+ import { landing, pauseMs, random, reach, typingDelays } from './motion.js';
2
+
3
+ /**
4
+ * Timed, viewport-aligned interactions shared by all scenarios, moving like a person (see motion.js).
5
+ * `said` collects where each Line starts; `voiced` maps the Narration's Line ids to their audio's
6
+ * seconds, or is null without one. `speed` scales every move, pause and typing delay it chooses;
7
+ * `seed` picks one of many equally human ways to move.
8
+ */
9
+ export function createDirector(page, startedAt, fps, focusTargets, wideWindows, said = [], voiced = null, { speed = 1, seed = 1 } = {}) {
3
10
  let cursor = { x: 0, y: 0 };
11
+ const rand = random(seed);
4
12
  const wait = ms => page.waitForTimeout(Math.max(0, ms));
5
13
  const time = () => (Date.now() - startedAt) / 1000;
6
- async function move(x, y, duration = 500) {
7
- const from = { ...cursor };
14
+ const pause = name => wait(pauseMs(name, speed, rand));
15
+ async function glide(to, { size, duration, drag } = {}) {
16
+ const path = reach(cursor, to, { size, duration, speed, drag, rand });
17
+ // Progress follows the clock, so a page slow to take each move cannot stretch the move.
8
18
  const start = Date.now();
9
- const frames = Math.max(1, Math.round(duration * fps / 1000));
10
- for (let i = 1; i <= frames; i++) {
11
- const t = i / frames;
12
- const k = t * t * (3 - 2 * t);
13
- await page.mouse.move(from.x + (x - from.x) * k, from.y + (y - from.y) * k);
14
- await wait(start + i * duration / frames - Date.now());
19
+ for (let i = 1, t = 0; t < 1; i++) {
20
+ await wait(start + i * 1000 / fps - Date.now());
21
+ t = path.duration ? Math.min(1, (Date.now() - start) / path.duration) : 1;
22
+ const { x, y } = path.at(t);
23
+ await page.mouse.move(x, y);
15
24
  }
16
- cursor = { x, y };
25
+ cursor = { ...to };
17
26
  }
18
- // Clicks, typing and drags are recorded by the in-page probe; only deliberate camera choices live here.
27
+ const move = (x, y, duration) => glide({ x, y }, { duration });
28
+ // Clicks, typing, drags and cursor shapes are recorded by the in-page probe; only deliberate camera choices live here.
19
29
  const focus = (box, t = time()) => focusTargets.push({ t, box });
20
30
  /** Options may be a bare number for the action's main timing; `focus: false` keeps the camera wide. */
21
31
  const options = (value, key) => typeof value === 'number' ? { [key]: value } : value ?? {};
@@ -24,31 +34,76 @@ export function createDirector(page, startedAt, fps, focusTargets, wideWindows)
24
34
  try { return await action(); }
25
35
  finally { if (follow === false) wideWindows.push({ start, end: time() }); }
26
36
  }
37
+ /** Moves onto a target, landing a little off its center; returns the target and where it landed inside its box. */
38
+ async function approach(locator, duration, action) {
39
+ const target = typeof locator === 'string' ? page.locator(locator) : locator;
40
+ const box = await target.boundingBox();
41
+ if (!box) throw new Error(`${action} target has no visible bounding box`);
42
+ const point = landing(box, rand);
43
+ await glide(point, { size: Math.min(box.width, box.height), duration });
44
+ return { target, position: { x: point.x - box.x, y: point.y - box.y } };
45
+ }
46
+ /** `button: 'right'` opens the page's context menu instead. */
27
47
  function click(locator, opts) {
28
- const { duration = 450, ...rest } = options(opts, 'duration');
48
+ const { duration, button = 'left', ...rest } = options(opts, 'duration');
29
49
  return act(rest, async () => {
30
- const target = typeof locator === 'string' ? page.locator(locator) : locator;
31
- const box = await target.boundingBox();
32
- if (!box) throw new Error('Click target has no visible bounding box');
33
- await move(box.x + box.width / 2, box.y + box.height / 2, duration);
34
- await target.click();
50
+ const { target, position } = await approach(locator, duration, 'Click');
51
+ await pause('beforePress');
52
+ // A person holds the button for a moment, so the Cursor's press shows.
53
+ await target.click({ position, button, delay: pauseMs('press', speed, rand) });
54
+ await pause('afterRelease');
55
+ });
56
+ }
57
+ /** Presses a key or combination, such as 'Meta+K', on whatever has focus; the Final shows it as keycaps. */
58
+ function press(keys, opts) {
59
+ return act(options(opts), async () => {
60
+ await pause('beforeKey');
61
+ await page.keyboard.press(keys, { delay: pauseMs('press', speed, rand) });
62
+ await pause('afterKey');
35
63
  });
36
64
  }
65
+ /** Rests the cursor on a target without pressing, so the page shows its hover state. */
66
+ async function hover(locator, opts) {
67
+ const { duration } = options(opts, 'duration');
68
+ await approach(locator, duration, 'Hover');
69
+ }
37
70
  function type(locator, text, opts) {
38
- const { msPerChar = 70, ...rest } = options(opts, 'msPerChar');
71
+ const { msPerChar = 70 / speed, ...rest } = options(opts, 'msPerChar');
39
72
  return act(rest, async () => {
40
73
  await click(locator, rest);
41
- await page.keyboard.type(text, { delay: msPerChar });
74
+ const chars = [...text], delays = typingDelays(text, msPerChar, rand);
75
+ for (let i = 0; i < chars.length; i++) {
76
+ if (i) await wait(delays[i - 1]);
77
+ await page.keyboard.type(chars[i]);
78
+ }
42
79
  });
43
80
  }
44
81
  function drag(from, to, opts) {
45
- const { duration = 1200, ...rest } = options(opts, 'duration');
82
+ const { duration, ...rest } = options(opts, 'duration');
46
83
  return act(rest, async () => {
47
- await move(from.x, from.y, 400);
84
+ await glide(from);
85
+ await pause('beforePress');
48
86
  await page.mouse.down();
49
- try { await move(to.x, to.y, duration); }
50
- finally { await page.mouse.up(); }
87
+ try {
88
+ await pause('afterGrab');
89
+ await glide(to, { duration, drag: true });
90
+ await pause('beforeDrop');
91
+ } finally { await page.mouse.up(); }
92
+ await pause('afterRelease');
51
93
  });
52
94
  }
53
- return { page, wait, time, at: seconds => wait(seconds * 1000 - (Date.now() - startedAt)), move, click, type, drag, focus };
95
+ /** Starts a Line. With a Narration it holds for the Line's audio, so the picture follows the voice. */
96
+ async function say(id, text) {
97
+ const t = time(), earlier = said.find(line => line.id === id);
98
+ if (earlier) throw new Error(`Line '${id}' was already said at ${earlier.t.toFixed(2)} s`);
99
+ if (voiced) {
100
+ if (!voiced.has(id)) throw new Error(`The Narration has no Line '${id}'; its Lines are ${[...voiced.keys()].join(', ')}`);
101
+ said.push({ t, id });
102
+ await wait((t + voiced.get(id)) * 1000 - (Date.now() - startedAt));
103
+ } else {
104
+ if (typeof text !== 'string' || !text) throw new Error(`d.say('${id}') needs the Line's text when recording without --narration`);
105
+ said.push({ t, id, text });
106
+ }
107
+ }
108
+ return { page, wait, time, at: seconds => wait(seconds * 1000 - (Date.now() - startedAt)), move, hover, click, press, type, drag, focus, say };
54
109
  }
package/src/edit.js CHANGED
@@ -1,61 +1,65 @@
1
1
  import { z } from 'zod';
2
- import { SHORT_SIDE, CHROME_HEIGHT, BACKGROUNDS } from './stage.js';
3
2
 
4
- /** An Edit holds every choice Render makes; a Scenario's config only seeds the first one. */
3
+ /**
4
+ * An Edit holds every choice Render makes; a Scenario's config only seeds the first one. Styling is
5
+ * agent-written and not validated (ADR 0005): defaults fill in what an Edit leaves out, and anything
6
+ * else an item names is passed to its shader or drawing code as a parameter.
7
+ *
8
+ * Drawn things are items: `{ shader }`, `{ draw }` or `{ image }` naming a file (relative to the Take)
9
+ * or a built-in (a name without an extension, see styles.js), plus optional `files` and parameters.
10
+ */
11
+ export const EDIT_VERSION = 3;
5
12
  export const evenSize = z.number().int().min(240).max(7680).refine(n => n % 2 === 0, 'Must be an even pixel count');
6
- const box = z.object({ x: z.number(), y: z.number(), width: z.number().nonnegative(), height: z.number().nonnegative() });
7
-
8
- // size names the Final's short side; quality is the H.264 quantizer (lower is sharper and larger).
9
- export const outputFields = z.object({
10
- size: z.union([z.enum(Object.keys(SHORT_SIDE)), evenSize]).default('2160p'),
11
- aspect: z.enum(['16:9', '1:1', '9:16']).default('16:9'),
12
- quality: z.number().int().min(10).max(40).default(22),
13
- });
14
-
15
- // The page in a window on a background. Radius is in 1080p pixels.
16
- export const frameFields = z.object({
17
- window: z.enum(Object.keys(CHROME_HEIGHT)).default('browser'),
18
- background: z.enum([...Object.keys(BACKGROUNDS), 'auto', 'blur']).default('aurora'),
19
- padding: z.number().min(0).max(0.3).default(0.08),
20
- radius: z.number().min(0).max(48).default(12),
21
- shadow: z.boolean().default(true),
22
- url: z.string().max(200).optional(),
23
- });
24
13
 
25
14
  /** Times are seconds except clickEffect.duration, which is milliseconds; geometry is CSS pixels. */
26
- export const editFields = {
27
- cursor: z.object({ style: z.enum(['arrow', 'dot']).default('arrow'), size: z.number().min(12).max(64).default(24), color: z.string().regex(/^#[a-fA-F0-9]{6}$/).default('#ffffff') }).default({}),
28
- clickEffect: z.object({ style: z.enum(['spark', 'none']).default('spark'), radius: z.number().min(8).max(80).default(32), length: z.number().min(4).max(40).default(16), count: z.number().int().min(4).max(16).default(8), duration: z.number().min(150).max(1000).default(420) }).default({}),
29
- output: outputFields.default({}),
30
- // `false` lets the page fill the Final.
31
- frame: z.union([z.literal(false), frameFields]).default({}),
15
+ export const DEFAULT_STYLE = {
16
+ // The Cursor shrinks to `press` while a button is held; `false` turns that off. A click shows on the
17
+ // Cursor, so no click effect is drawn unless named.
18
+ cursor: { draw: 'arrow', size: 24, color: '#ffffff', press: 0.8 },
19
+ clickEffect: false,
20
+ // quality is the H.264 quantizer (lower is sharper and larger).
21
+ output: { width: 3840, height: 2160, quality: 22 },
22
+ // padding is a fraction of the short side, one number or [top, right, bottom, left]; radius is in 1080p pixels.
23
+ frame: { padding: 0.08, radius: 12, chrome: { draw: 'browser' }, background: [{ shader: 'fluted' }], effects: [{ shader: 'shadow' }] },
32
24
  // See camera.js. Each target is framed with `padding` CSS px around it, zooming at most `maxZoom`;
33
25
  // fits below `minZoom` stay wide. The camera arrives `lead` before an action, holds `hold` after the
34
26
  // last one in a segment, settles in about `response`, and returns wide `endWide` before the end.
35
- camera: z.object({
36
- maxZoom: z.number().min(1).max(4).default(2), minZoom: z.number().min(1).max(4).default(1.2), padding: z.number().min(0).max(400).default(48),
37
- lead: z.number().min(0).max(3).default(0.6), hold: z.number().min(0).max(30).default(1.5), chainGap: z.number().min(0).max(30).default(2),
38
- response: z.number().min(0.1).max(3).default(0.6), follow: z.boolean().default(true), endWide: z.number().min(0).max(10).default(1.5),
39
- }).default({}),
27
+ camera: { maxZoom: 2, minZoom: 1.2, padding: 48, lead: 0.6, hold: 1.5, chainGap: 2, response: 0.6, follow: true, endWide: 1.5 },
28
+ // Shortcuts show as keycaps over the Final, outside the camera, for `duration` seconds after each
29
+ // press; presses of the same keys meanwhile count up. A key pressed without Control, Alt, Shift or
30
+ // Meta shows only with `singleKeys`. `false` shows none.
31
+ keycaps: { draw: 'keycaps', duration: 1.5, singleKeys: false },
32
+ // Drawn over the Final, outside the camera, while a Line is spoken; `burn: false` keeps them to the
33
+ // subtitle files. Rows hold up to `maxChars` (about 16 in Chinese, 42 otherwise), `maxRows` to a cue,
34
+ // each shown at least `minDuration`.
35
+ subtitles: { draw: 'subtitles', burn: true },
40
36
  };
41
37
 
42
- /** A camera target is a CSS-pixel box the camera reaches at `t` seconds and holds at least until `until`, optionally at a fixed `zoom`. */
43
- const target = z.object({ t: z.number().nonnegative(), box, until: z.number().nonnegative().optional(), zoom: z.number().min(1).max(4).optional() });
38
+ const isObject = value => value !== null && typeof value === 'object' && !Array.isArray(value);
39
+ /** Naming what draws an item starts a new item, so the old drawing's parameters do not leak into it. */
40
+ const namesDrawing = value => ['shader', 'draw', 'image'].some(key => key in value);
41
+ /** `over` wins field by field: nested objects merge; anything else, including arrays and `false`, replaces. */
42
+ export function merge(base, over) {
43
+ const merged = { ...base };
44
+ for (const [key, value] of Object.entries(over ?? {})) {
45
+ if (value === undefined) continue;
46
+ merged[key] = isObject(value) && isObject(base?.[key]) && !namesDrawing(value) ? merge(base[key], value) : value;
47
+ }
48
+ return merged;
49
+ }
44
50
 
45
- export const editSchema = z.object({
46
- schemaVersion: z.literal(2),
47
- ...editFields,
48
- camera: editFields.camera.removeDefault().extend({ targets: z.array(target).default([]) }).default({}),
49
- // The Final's frame rate; a new Take takes it from the Scenario's capture rate.
50
- output: outputFields.extend({ fps: z.union([z.literal(30), z.literal(60)]).default(60) }).default({}),
51
- });
51
+ /** A complete Edit: the defaults under whatever `edit` names. */
52
+ export function withDefaults(edit) {
53
+ return merge({ schemaVersion: EDIT_VERSION, ...DEFAULT_STYLE, output: { ...DEFAULT_STYLE.output, fps: 60 }, camera: { ...DEFAULT_STYLE.camera, targets: [] }, shortcuts: [], narration: { volume: 1, lines: [] } }, edit);
54
+ }
52
55
 
53
56
  /**
54
57
  * Camera targets: observed clicks, typing and drags, except those inside a `wide` window ({ start, end }
55
58
  * seconds) from an action with `focus: false`. Like a manual zoom in Screen Studio, an explicit focus
56
59
  * target replaces only the automatic targets inside its own span (from `lead` before it to `hold` after).
57
60
  */
58
- export function cameraTargets(timeline, focus, wide = [], { lead, hold } = editFields.camera.parse({})) {
61
+ export function cameraTargets(timeline, focus, wide = [], camera = {}) {
62
+ const { lead, hold } = { ...DEFAULT_STYLE.camera, ...camera };
59
63
  const spans = focus.map(f => ({ start: f.t - lead, end: (f.until ?? f.t) + hold }));
60
64
  const inside = (t, windows) => windows.some(w => t >= w.start && t <= w.end);
61
65
  const automatic = timeline.events.filter(event => !inside(event.t, wide) && !inside(event.t, spans)).flatMap(event => {
@@ -70,12 +74,18 @@ export function cameraTargets(timeline, focus, wide = [], { lead, hold } = editF
70
74
  return [...automatic, ...focus].sort((a, b) => a.t - b.t);
71
75
  }
72
76
 
77
+ /**
78
+ * The first Edit of a Take. Each Line starts where the Scenario said it (`d.say`); its text, audio and
79
+ * word timings stay in the Take's Narration, since they change only with new audio. The Shortcuts the
80
+ * Timeline recorded are the ones shown, so one can be relabeled or removed without recording again.
81
+ */
73
82
  export function createEdit(config, timeline, focus, wide = []) {
74
- return editSchema.parse({
75
- schemaVersion: 2,
76
- cursor: config.cursor, clickEffect: config.clickEffect, output: { ...config.output, fps: config.capture.fps },
83
+ return withDefaults({
84
+ cursor: config.cursor, clickEffect: config.clickEffect, keycaps: config.keycaps, subtitles: config.subtitles, output: { ...config.output, fps: config.capture.fps },
77
85
  // The browser chrome shows the Scenario's host unless the config names something else.
78
- frame: config.frame && { url: new URL(config.url).host, ...config.frame },
86
+ frame: { url: new URL(config.url).host, ...config.frame },
79
87
  camera: { ...config.camera, targets: cameraTargets(timeline, focus, wide, config.camera) },
88
+ shortcuts: timeline.events.filter(event => event.type === 'shortcut').map(({ t, keys }) => ({ t, keys })),
89
+ narration: { lines: timeline.events.filter(event => event.type === 'say').map(event => ({ id: event.id, start: event.t })) },
80
90
  });
81
91
  }
@@ -21,16 +21,32 @@ export async function doctor() {
21
21
  return { ok: checks.every(c => c.ok), checks };
22
22
  }
23
23
 
24
- /**
25
- * Downloads the Chromium build that CueTake's own Playwright version drives. Running
26
- * `npx playwright install` instead may resolve a newer Playwright and fetch a build CueTake never uses.
27
- */
28
- export function installBrowser() {
24
+ function playwright(args) {
29
25
  const cli = join(dirname(createRequire(import.meta.url).resolve('playwright/package.json')), 'cli.js');
30
26
  return new Promise((resolve, reject) => {
31
27
  // Progress goes to stderr so stdout stays the JSON result.
32
- const child = spawn(process.execPath, [cli, 'install', 'chromium', '--no-shell'], { stdio: ['ignore', 2, 2] });
28
+ const child = spawn(process.execPath, [cli, ...args], { stdio: ['ignore', 2, 2] });
33
29
  child.on('error', reject);
34
- child.on('close', code => code === 0 ? resolve({ installed: true, path: chromium.executablePath() }) : reject(new Error(`Browser install exited with ${code}`)));
30
+ child.on('close', code => code === 0 ? resolve() : reject(new Error(`playwright ${args[0]} exited with ${code}`)));
35
31
  });
36
32
  }
33
+
34
+ /**
35
+ * Downloads the Chromium build that CueTake's own Playwright version drives. Running
36
+ * `npx playwright install` instead may resolve a newer Playwright and fetch a build CueTake never uses.
37
+ */
38
+ export async function installBrowser() {
39
+ await playwright(['install', 'chromium', '--no-shell']);
40
+ return { installed: true, path: chromium.executablePath() };
41
+ }
42
+
43
+ /**
44
+ * Unregisters CueTake's Playwright from the shared browser cache, which deletes each browser no other
45
+ * Playwright installation still uses. Browsers other tools need stay.
46
+ */
47
+ export async function uninstallBrowser({ dryRun = false } = {}) {
48
+ const path = chromium.executablePath(), exists = () => fs.access(path).then(() => true, () => false);
49
+ const existed = await exists();
50
+ if (existed && !dryRun) await playwright(['uninstall']);
51
+ return { path, existed, removed: existed && !dryRun && !await exists() };
52
+ }