cuetake 0.4.0 → 0.6.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 +5 -5
- package/examples/tabs.mjs +88 -0
- package/helper/bin/cuetake-capture +0 -0
- package/package.json +5 -3
- package/src/app-capture.js +128 -0
- package/src/app-director.js +208 -0
- package/src/app-locators.js +223 -0
- package/src/auth.js +3 -2
- package/src/camera.js +80 -33
- package/src/cli.js +29 -13
- package/src/cursor.js +24 -4
- package/src/desktop.js +108 -0
- package/src/director.js +340 -35
- package/src/edit.js +74 -16
- package/src/environment.js +34 -2
- package/src/follow-tabs.js +64 -0
- package/src/frames.js +41 -0
- package/src/home.js +23 -0
- package/src/look.js +36 -31
- package/src/mac-keys.js +47 -0
- package/src/masks.js +140 -0
- package/src/motion.js +13 -4
- package/src/pipeline.js +253 -48
- package/src/probe.js +315 -73
- package/src/recorder.js +46 -13
- package/src/render-page.js +545 -151
- package/src/render.js +38 -14
- package/src/shutter.js +42 -0
- package/src/styles/browser.js +2 -1
- package/src/styles/fast-forward.js +22 -0
- package/src/styles.js +3 -2
- package/src/tab-capture.js +225 -77
- package/src/tabs.js +126 -0
- package/src/time-map.js +106 -0
- package/src/uninstall.js +22 -9
package/README.md
CHANGED
|
@@ -6,7 +6,7 @@
|
|
|
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
|
-
|
|
9
|
+
https://github.com/user-attachments/assets/a4a56ac4-2ef4-476c-b9d7-de8142f98984
|
|
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.
|
|
@@ -24,7 +24,7 @@ If a user hands you this repository to set up CueTake:
|
|
|
24
24
|
1. Install the skill with `npx skills add levyxdev/cuetake`. In Claude Code you can instead run `/plugin marketplace add levyxdev/cuetake`, then `/plugin install cuetake`.
|
|
25
25
|
2. The skill's `scripts/cuetake` runs the pinned [`cuetake`](https://www.npmjs.com/package/cuetake) package with `npx`, so nothing else needs installing besides Node. To run a source checkout instead, export `CUETAKE_BIN="node /absolute/path/to/cuetake/src/cli.js"`.
|
|
26
26
|
3. Follow the skill's [setup guide](skills/cuetake/setup.md): run `scripts/cuetake doctor`, and install Node or the browser only after the user agrees to the option they pick.
|
|
27
|
-
4. Write a Scenario for the user's product with the [scenario API](skills/cuetake/scenarios.md), record it, and
|
|
27
|
+
4. Write a Scenario for the user's product with the [scenario API](skills/cuetake/scenarios.md), record it, and read the verification report it prints.
|
|
28
28
|
|
|
29
29
|
## Run from source
|
|
30
30
|
|
|
@@ -62,13 +62,13 @@ A successful command is a technical check, not an editorial approval. Watch the
|
|
|
62
62
|
|
|
63
63
|
## How it works
|
|
64
64
|
|
|
65
|
-
Playwright drives an isolated Chromium tab.
|
|
65
|
+
Playwright drives an isolated Chromium tab. A recorder page of its own captures that tab at device-pixel resolution using `getDisplayMedia`, so the capture outlives navigations and reloads; a VP9 `MediaRecorder` saves the source. A probe in every document and frame of the page 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).
|
|
66
66
|
|
|
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.
|
|
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. Without a GPU, Chromium rasterizes and encodes on the CPU, so a busy page at resolution scale 2 can get only a few frames per second: `record` then defaults to scale 1, and `verify` warns when the page got too few animation frames during Capture.
|
|
68
68
|
|
|
69
69
|
## Current scope
|
|
70
70
|
|
|
71
|
-
The supported workflow is a short
|
|
71
|
+
The supported workflow is a short browser demo, including SPA interactions, full page navigations, form posts that redirect, and reloads: the Source and the Timeline run on through each, and the Timeline notes each page load. The built-in browser chrome's address bar follows the page to each host it navigates to. A page the demo opens in a new tab or popup is recorded as its own Tab and shown in the Final. On macOS a Take can record one or several desktop Apps instead of a page ([Apps](skills/cuetake/scenarios.md#apps)). Page audio is not captured; a Narration voiced by a separate speech tool is mixed in at Render, with Subtitles ([narration](skills/cuetake/narration.md)). Input inside iframes, cross-origin and nested ones included, is followed like input on the page; an iframe that is rotated, skewed or 3D-transformed is placed as if it were only scaled, and verification warns. 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.
|
|
72
72
|
|
|
73
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).
|
|
74
74
|
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
// A demo across Tabs: a guide opens in a new tab, then a sign-in popup that closes itself.
|
|
2
|
+
// example.com only supplies a stable HTTPS origin. prepare() answers every page of it with a
|
|
3
|
+
// self-contained fixture, so this take never depends on that site's markup.
|
|
4
|
+
export const config = { name: 'tabs', url: 'https://example.com' };
|
|
5
|
+
|
|
6
|
+
const style = `<style>
|
|
7
|
+
body { margin:0; min-height:100vh; display:grid; place-items:center; font:16px/1.5 system-ui, sans-serif; color:#111827 }
|
|
8
|
+
.card { width:460px; padding:32px; border-radius:20px; background:white; box-shadow:0 20px 50px #1f29371f }
|
|
9
|
+
h1 { margin:0 0 4px; font-size:24px } p { margin:0 0 24px; color:#6b7280 }
|
|
10
|
+
a, button { display:block; box-sizing:border-box; width:100%; margin-top:12px; padding:14px; border:0; border-radius:10px;
|
|
11
|
+
background:#4f46e5; color:white; font:600 16px system-ui; text-align:center; text-decoration:none; cursor:pointer }
|
|
12
|
+
a { background:#eef2ff; color:#4338ca }
|
|
13
|
+
.status { margin-top:20px; padding:12px 14px; border-radius:10px; background:#ecfdf5; color:#065f46; display:none }
|
|
14
|
+
</style>`;
|
|
15
|
+
|
|
16
|
+
const pages = {
|
|
17
|
+
'/': `<!doctype html><title>Launch</title>${style}<body style="background:linear-gradient(135deg,#eef2ff,#fdf2f8)">
|
|
18
|
+
<main class="card">
|
|
19
|
+
<h1>Launch workspace</h1>
|
|
20
|
+
<p>Read the guide, then connect your repository.</p>
|
|
21
|
+
<a href="/guide" target="_blank">Read the guide</a>
|
|
22
|
+
<button id="connect">Connect GitHub</button>
|
|
23
|
+
<div class="status" role="status"></div>
|
|
24
|
+
</main>
|
|
25
|
+
<script>
|
|
26
|
+
document.querySelector('#connect').onclick = () => window.open('/connect', 'connect', 'popup,width=480,height=560');
|
|
27
|
+
addEventListener('message', event => {
|
|
28
|
+
if (event.origin !== location.origin) return;
|
|
29
|
+
const status = document.querySelector('.status');
|
|
30
|
+
status.textContent = 'Connected as ' + event.data.user;
|
|
31
|
+
status.style.display = 'block';
|
|
32
|
+
});
|
|
33
|
+
</script>`,
|
|
34
|
+
'/guide': `<!doctype html><title>Guide</title>${style}<body style="background:linear-gradient(135deg,#ecfeff,#f0fdf4)">
|
|
35
|
+
<main class="card">
|
|
36
|
+
<h1>Getting started</h1>
|
|
37
|
+
<p>Your API key opens the Launch API to your scripts.</p>
|
|
38
|
+
<button id="copy">Copy API key</button>
|
|
39
|
+
<div class="status" role="status">Copied to the clipboard</div>
|
|
40
|
+
</main>
|
|
41
|
+
<script>document.querySelector('#copy').onclick = () => { document.querySelector('.status').style.display = 'block'; };</script>`,
|
|
42
|
+
'/connect': `<!doctype html><title>Sign in</title>${style}<body style="background:#f9fafb">
|
|
43
|
+
<main class="card" style="width:auto;margin:24px;box-shadow:none">
|
|
44
|
+
<h1>Authorize Launch</h1>
|
|
45
|
+
<p>Launch will read your repositories.</p>
|
|
46
|
+
<button id="authorize">Authorize</button>
|
|
47
|
+
</main>
|
|
48
|
+
<script>
|
|
49
|
+
document.querySelector('#authorize').onclick = () => {
|
|
50
|
+
window.opener.postMessage({ user: 'ada' }, location.origin);
|
|
51
|
+
setTimeout(() => window.close(), 300);
|
|
52
|
+
};
|
|
53
|
+
</script>`,
|
|
54
|
+
};
|
|
55
|
+
|
|
56
|
+
export async function prepare(page) {
|
|
57
|
+
await page.context().route('https://example.com/**', route => {
|
|
58
|
+
const body = pages[new URL(route.request().url()).pathname];
|
|
59
|
+
return body ? route.fulfill({ contentType: 'text/html', body }) : route.fulfill({ status: 404 });
|
|
60
|
+
});
|
|
61
|
+
await page.goto('https://example.com/');
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export async function run(d) {
|
|
65
|
+
const workspace = d.page;
|
|
66
|
+
await d.move(720, 700, 0);
|
|
67
|
+
await d.at(0.8);
|
|
68
|
+
// A link with target="_blank" opens a Tab, which comes in front.
|
|
69
|
+
const guideOpened = workspace.waitForEvent('popup');
|
|
70
|
+
await d.click(workspace.getByRole('link', { name: 'Read the guide' }));
|
|
71
|
+
const guide = await guideOpened;
|
|
72
|
+
await d.click(guide.getByRole('button', { name: 'Copy API key' }));
|
|
73
|
+
await d.wait(1500);
|
|
74
|
+
// Back to the workspace, which stays open behind the guide.
|
|
75
|
+
await d.switchTo(workspace);
|
|
76
|
+
await d.wait(600);
|
|
77
|
+
// window.open opens a popup window over the workspace; it closes itself once authorized.
|
|
78
|
+
const popupOpened = workspace.waitForEvent('popup');
|
|
79
|
+
await d.click(workspace.getByRole('button', { name: 'Connect GitHub' }));
|
|
80
|
+
const popup = await popupOpened;
|
|
81
|
+
await d.wait(500);
|
|
82
|
+
await d.click(popup.getByRole('button', { name: 'Authorize' }));
|
|
83
|
+
await workspace.getByText('Connected as ada').waitFor();
|
|
84
|
+
await d.wait(2500);
|
|
85
|
+
const status = await workspace.getByRole('status').textContent();
|
|
86
|
+
if (status !== 'Connected as ada') throw new Error(`Unexpected status: ${status}`);
|
|
87
|
+
return { status, guideCopied: await guide.getByRole('status').isVisible() };
|
|
88
|
+
}
|
|
Binary file
|
package/package.json
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "cuetake",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.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": {
|
|
7
|
-
"cuetake": "
|
|
7
|
+
"cuetake": "src/cli.js"
|
|
8
8
|
},
|
|
9
9
|
"files": [
|
|
10
10
|
"src",
|
|
11
|
+
"helper/bin/cuetake-capture",
|
|
11
12
|
"examples",
|
|
12
13
|
"README.md",
|
|
13
14
|
"LICENSE"
|
|
@@ -15,7 +16,8 @@
|
|
|
15
16
|
"scripts": {
|
|
16
17
|
"start": "bun src/cli.js",
|
|
17
18
|
"test": "bun test tests/pipeline.test.js",
|
|
18
|
-
"doctor": "bun src/cli.js doctor"
|
|
19
|
+
"doctor": "bun src/cli.js doctor",
|
|
20
|
+
"build:helper": "sh helper/build.sh"
|
|
19
21
|
},
|
|
20
22
|
"keywords": [
|
|
21
23
|
"browser",
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import fs from 'node:fs/promises';
|
|
3
|
+
import { createInterface } from 'node:readline';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Capture of a Desktop of macOS Apps (ADR 0009), through cuetake-capture, the Swift helper shipped in
|
|
8
|
+
* the package (helper/). The helper runs as a child process, uses the grants of the process
|
|
9
|
+
* responsible for CueTake, and talks in JSON lines over stdio; runtime code here stays Node-only.
|
|
10
|
+
*/
|
|
11
|
+
export const HELPER = fileURLToPath(new URL('../helper/bin/cuetake-capture', import.meta.url));
|
|
12
|
+
const MISSING = 'This CueTake has no cuetake-capture helper, so it cannot record Apps. In a source checkout, run bun run build:helper on a Mac.';
|
|
13
|
+
|
|
14
|
+
/** The helper's path, made executable if packing lost the bit, or null when this CueTake has none. */
|
|
15
|
+
async function helper() {
|
|
16
|
+
try {
|
|
17
|
+
const { mode } = await fs.stat(HELPER);
|
|
18
|
+
if (!(mode & 0o111)) await fs.chmod(HELPER, mode | 0o755);
|
|
19
|
+
return HELPER;
|
|
20
|
+
} catch (error) { if (error.code === 'ENOENT') return null; throw error; }
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** What the helper prints for `args`, parsed, or an error naming its output. */
|
|
24
|
+
function run(path, args) {
|
|
25
|
+
return new Promise((resolve, reject) => {
|
|
26
|
+
const child = spawn(path, args, { stdio: ['ignore', 'pipe', 'pipe'] });
|
|
27
|
+
let out = '', err = '';
|
|
28
|
+
child.stdout.on('data', chunk => { out += chunk; });
|
|
29
|
+
child.stderr.on('data', chunk => { err += chunk; });
|
|
30
|
+
child.on('error', reject);
|
|
31
|
+
child.on('close', code => {
|
|
32
|
+
try { resolve(JSON.parse(out)); } catch { reject(new Error(`cuetake-capture ${args.join(' ')} exited with ${code}: ${(err || out).trim()}`)); }
|
|
33
|
+
});
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* The doctor checks a Take of Apps needs, each `for: 'Apps'`: the helper, and the Screen Recording,
|
|
39
|
+
* Accessibility and Input Monitoring grants of the app responsible for CueTake, read without prompting;
|
|
40
|
+
* Input Monitoring lets the helper notice input the Director did not make. Each fix names that app.
|
|
41
|
+
*/
|
|
42
|
+
export async function appChecks() {
|
|
43
|
+
const path = await helper();
|
|
44
|
+
if (!path) return [{ name: 'helper', for: 'Apps', ok: false, fix: MISSING }];
|
|
45
|
+
let granted;
|
|
46
|
+
try { granted = await run(path, ['preflight']); }
|
|
47
|
+
catch (error) { return [{ name: 'helper', for: 'Apps', ok: false, error: error.message, fix: 'Reinstall CueTake; its cuetake-capture helper does not run here.' }]; }
|
|
48
|
+
const { app, path: responsible } = granted.responsible;
|
|
49
|
+
const grant = (name, ok, pane) => ({ name, for: 'Apps', ok, app, ...(ok ? {} : { path: responsible, fix: `Allow ${app} in System Settings > Privacy & Security > ${pane}, then restart it. Ask the user first.` }) });
|
|
50
|
+
return [grant('screen-recording', granted.screenRecording, 'Screen Recording'), grant('accessibility', granted.accessibility, 'Accessibility'), grant('input-monitoring', granted.inputMonitoring, 'Input Monitoring')];
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Starts `apps` ([{ path, args }], in order) on a Desktop `desktop` points large ({ width, height }),
|
|
55
|
+
* recording at `fps` into `source` (an MP4) from `start()` on, and writing the last frame to `poster`.
|
|
56
|
+
* Resolves once the first App's first window fills the Desktop and every App shows a window, the first
|
|
57
|
+
* App in front, with `ready` (the Apps, as [{ name, bundle, pid, running }], the scale, the Desktop on the screen
|
|
58
|
+
* and the first window in Desktop points) and:
|
|
59
|
+
* - `start()`, which records and resolves with the wall-clock ms of the first frame;
|
|
60
|
+
* - `stop()`, which ends the Source, quits the Apps and resolves with the sidecar: `duration`, `frames`
|
|
61
|
+
* ([t, scale] per frame), `windows` (the Apps' windows over time), `shapes` (the system cursor's, as
|
|
62
|
+
* [t, keyword]), `focused` (each element the App focused, { t, box, role }), `watched` (the boxes of
|
|
63
|
+
* each masked element, { id, boxes }), `otherInput` (input the Director did not make, as [t, kind])
|
|
64
|
+
* and the names of the Apps that did not quit (`unquit`);
|
|
65
|
+
* - `request(message)`, which asks the helper to read the Apps' Accessibility trees, arrange their
|
|
66
|
+
* windows or post input for the Director (app-locators.js, app-director.js), in Desktop points, and
|
|
67
|
+
* resolves with its reply;
|
|
68
|
+
* - `kill()`, which ends it all, for a failure; the helper then quits the Apps.
|
|
69
|
+
* An App the user already runs is refused unless `useRunning`, the user's consent to record it as it
|
|
70
|
+
* is: then it is used as it runs (`running` in `ready`), never quit, and its windows are put back.
|
|
71
|
+
* The helper's refusals (a running App, a missing grant) reject with its message.
|
|
72
|
+
*/
|
|
73
|
+
export async function startDesktop({ apps, desktop, fps, source, poster, useRunning = false }) {
|
|
74
|
+
const path = await helper();
|
|
75
|
+
if (!path) throw new Error(MISSING);
|
|
76
|
+
const child = spawn(path, ['record'], { stdio: ['pipe', 'pipe', 'pipe'] });
|
|
77
|
+
let stderr = '';
|
|
78
|
+
child.stderr.on('data', chunk => { stderr = (stderr + chunk).slice(-4000); });
|
|
79
|
+
const waiting = [], requests = new Map();
|
|
80
|
+
let ended = null, next = 0;
|
|
81
|
+
const settle = (key, value) => { const i = waiting.findIndex(w => w.key === key || key === 'error'); if (i >= 0) waiting.splice(i, 1)[0][key === 'error' ? 'reject' : 'resolve'](value); };
|
|
82
|
+
const failed = message => {
|
|
83
|
+
ended = new Error(message);
|
|
84
|
+
for (const w of [...waiting.splice(0), ...requests.values()]) w.reject(ended);
|
|
85
|
+
requests.clear();
|
|
86
|
+
};
|
|
87
|
+
createInterface({ input: child.stdout }).on('line', line => {
|
|
88
|
+
let message;
|
|
89
|
+
try { message = JSON.parse(line); } catch { return; }
|
|
90
|
+
if (message.error) failed(message.error.message);
|
|
91
|
+
else if (requests.has(message.id)) {
|
|
92
|
+
const { resolve, reject } = requests.get(message.id);
|
|
93
|
+
requests.delete(message.id);
|
|
94
|
+
if ('failed' in message) reject(new Error(message.failed)); else resolve(message.reply);
|
|
95
|
+
}
|
|
96
|
+
else for (const key of ['ready', 'started', 'stopped']) if (message[key]) settle(key, message[key]);
|
|
97
|
+
});
|
|
98
|
+
child.on('error', error => failed(error.message));
|
|
99
|
+
child.on('close', code => failed(`cuetake-capture stopped (exit ${code})${stderr.trim() ? `: ${stderr.trim()}` : ''}`));
|
|
100
|
+
const reply = key => new Promise((resolve, reject) => { if (ended) reject(ended); else waiting.push({ key, resolve, reject }); });
|
|
101
|
+
const send = message => child.stdin.write(JSON.stringify(message) + '\n');
|
|
102
|
+
const ready = reply('ready');
|
|
103
|
+
send({ apps: apps.map(app => ({ path: app.path, args: app.args ?? [] })), desktop, fps, source, poster, useRunning });
|
|
104
|
+
try { await ready; } catch (error) { child.kill(); throw error; }
|
|
105
|
+
return {
|
|
106
|
+
ready: await ready,
|
|
107
|
+
async start() { const started = reply('started'); send({ start: true }); return (await started).epochMs; },
|
|
108
|
+
async stop() { const stopped = reply('stopped'); send({ stop: true }); return stopped; },
|
|
109
|
+
request(message) {
|
|
110
|
+
if (ended) return Promise.reject(ended);
|
|
111
|
+
const id = ++next;
|
|
112
|
+
return new Promise((resolve, reject) => { requests.set(id, { resolve, reject }); send({ id, ...message }); });
|
|
113
|
+
},
|
|
114
|
+
kill() { if (child.exitCode === null) child.stdin.end(); },
|
|
115
|
+
};
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* The Accessibility tree of a running App (`app`: its bundle id, name or .app path), as the helper lists
|
|
120
|
+
* it, for writing a Scenario's locators. It only reads, so it may look at an App the user started.
|
|
121
|
+
*/
|
|
122
|
+
export async function appTree(app) {
|
|
123
|
+
const path = await helper();
|
|
124
|
+
if (!path) throw new Error(MISSING);
|
|
125
|
+
const tree = await run(path, ['tree', app]);
|
|
126
|
+
if (tree.error) throw new Error(tree.error.message);
|
|
127
|
+
return tree;
|
|
128
|
+
}
|
|
@@ -0,0 +1,208 @@
|
|
|
1
|
+
import { clockOf, effectOf, followMask, options } from './director.js';
|
|
2
|
+
import { appLocators, isAppLocator, isAppWindow, resolveAll, resolveOne, resolveWindow } from './app-locators.js';
|
|
3
|
+
import { titleBarSpot } from './desktop.js';
|
|
4
|
+
import { landing, pauseMs, random, reach, typingDelays } from './motion.js';
|
|
5
|
+
import { macKeys } from './mac-keys.js';
|
|
6
|
+
import { shortcutKeys } from './shortcuts.js';
|
|
7
|
+
|
|
8
|
+
// The AX roles of an element that takes typing, where a key pressed alone is typing, not a Shortcut.
|
|
9
|
+
const FIELDS = new Set(['AXTextField', 'AXTextArea', 'AXComboBox', 'AXSearchField']);
|
|
10
|
+
// Characters typed as their key, since a text field takes them as a key press, not as text.
|
|
11
|
+
const TYPED_AS_KEYS = { '\n': 'Enter', '\t': 'Tab' };
|
|
12
|
+
// How long a window clicked into may take to come in front, and how often the Director looks.
|
|
13
|
+
const SWITCH_TIMEOUT_MS = 3000, SWITCH_POLL_MS = 50;
|
|
14
|
+
// The widest a title bar's empty stretch counts as a target, in points: a person aims at a spot of it, not the whole bar.
|
|
15
|
+
const TITLE_BAR_AIM = 24;
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* The Director of a Take of Apps (ADR 0009). It keeps time, says Lines, fast-forwards waits and adds
|
|
19
|
+
* camera focus targets as the page Director does, in Desktop points, and locates the App's elements by
|
|
20
|
+
* Accessibility role and name (app-locators.js). It acts with real input at a human pace (motion.js):
|
|
21
|
+
* it moves the real pointer at `fps`, presses, releases and posts keys through `helper`, whose
|
|
22
|
+
* `request` also answers:
|
|
23
|
+
* { move: { x, y } } moves the pointer there, dragging while a button is down
|
|
24
|
+
* { down: { x, y, button } } presses there, unless another app's window lies over the
|
|
25
|
+
* point, when it presses nothing and answers { covered: name },
|
|
26
|
+
* or nothing does, { nothing: true }
|
|
27
|
+
* { up: { x, y, button } } releases there
|
|
28
|
+
* { key: { keyCode, modifiers, down } } presses or releases a key with modifiers held
|
|
29
|
+
* { text: char } types one character
|
|
30
|
+
* { focused: {} } the focused element's { role, subrole }
|
|
31
|
+
* { watch: { id, refs } } reads the frames of these elements at the capture rate, as the boxes of
|
|
32
|
+
* the masked element `id`, until watched again
|
|
33
|
+
* { titleBar: { ref } } samples the window's title bar along its middle, every 4 points of it on
|
|
34
|
+
* the Desktop: { y, samples: [[x, empty]] }, `empty` where nothing lies, no
|
|
35
|
+
* control, no title and no window over it; null when it has none
|
|
36
|
+
* `apps` are the Take's Apps, { name, bundle, path }, in order: the first's first window fills the Desktop.
|
|
37
|
+
* Since the App draws no pointer of its own, the Director notes in `notes` everything Render draws:
|
|
38
|
+
* the pointer path (`pointer`, as [seconds, x, y]) and the clicks, drags, typing and Shortcuts (`events`),
|
|
39
|
+
* and each element masked (`elements`, { id, tab, name }) with its mask (`masks`). The pointer starts
|
|
40
|
+
* at the Desktop's top-left corner, where Capture puts it. `signal` aborts once the Scenario has run,
|
|
41
|
+
* when masks stop following their locators.
|
|
42
|
+
*/
|
|
43
|
+
export function createAppDirector({ startedAt, fps = 60, voiced = null, speed = 1, seed = 1, helper, apps = [], signal, switchTimeout = SWITCH_TIMEOUT_MS }, notes) {
|
|
44
|
+
const { elements = [], masks = [] } = notes;
|
|
45
|
+
Object.assign(notes, { elements, masks });
|
|
46
|
+
const clock = clockOf({ startedAt, voiced }, notes, () => 0), { wait, time } = clock, locators = appLocators(helper, apps);
|
|
47
|
+
const rand = random(seed), pause = name => wait(pauseMs(name, speed, rand));
|
|
48
|
+
// What the Director notes is rounded to the millisecond and to a hundredth of a point.
|
|
49
|
+
const now = () => Math.round(time() * 1000) / 1000, round = v => Math.round(v * 100) / 100;
|
|
50
|
+
let cursor = { x: 0, y: 0 };
|
|
51
|
+
|
|
52
|
+
async function point(x, y) {
|
|
53
|
+
notes.pointer.push([now(), round(x), round(y)]);
|
|
54
|
+
await helper.request({ move: { x: round(x), y: round(y) } });
|
|
55
|
+
}
|
|
56
|
+
async function glide(to, { size, duration, drag } = {}) {
|
|
57
|
+
const path = reach(cursor, to, { size, duration, speed, drag, rand });
|
|
58
|
+
const start = Date.now();
|
|
59
|
+
for (let i = 1, t = 0; t < 1; i++) {
|
|
60
|
+
await wait(start + i * 1000 / fps - Date.now());
|
|
61
|
+
t = path.duration ? Math.min(1, (Date.now() - start) / path.duration) : 1;
|
|
62
|
+
const { x, y } = path.at(t);
|
|
63
|
+
await point(x, y);
|
|
64
|
+
}
|
|
65
|
+
cursor = { x: to.x, y: to.y };
|
|
66
|
+
}
|
|
67
|
+
async function act({ focus: follow = true }, action) {
|
|
68
|
+
const start = time();
|
|
69
|
+
try { return await action(); }
|
|
70
|
+
finally { if (follow === false) notes.wide.push({ start, end: time() }); }
|
|
71
|
+
}
|
|
72
|
+
/** Where a target lies: an App locator's element, waited for, or a point or box in Desktop points. */
|
|
73
|
+
async function boxOf(target, action) {
|
|
74
|
+
if (isAppLocator(target)) return (await resolveOne(target)).frame;
|
|
75
|
+
if (typeof target?.x === 'number' && typeof target?.y === 'number') return { width: 0, height: 0, ...target };
|
|
76
|
+
throw new Error(`d.${action} needs a locator of the App, such as d.page.getByRole('button', { name: 'Save' }), or a point { x, y } in Desktop points`);
|
|
77
|
+
}
|
|
78
|
+
/** Moves onto a target, landing a little off its center; returns its box and where it landed. */
|
|
79
|
+
async function approach(target, duration, action) {
|
|
80
|
+
const box = await boxOf(target, action);
|
|
81
|
+
const land = box.width && box.height ? landing(box, rand) : box, at = { x: round(land.x), y: round(land.y) };
|
|
82
|
+
await glide(at, { size: Math.min(box.width, box.height) || undefined, duration });
|
|
83
|
+
return { box, at };
|
|
84
|
+
}
|
|
85
|
+
/** Presses at `at`, refused when another app's window, or nothing, lies there: the App would never get the press. */
|
|
86
|
+
async function down(at, button, action, target) {
|
|
87
|
+
const { covered, nothing } = await helper.request({ down: { ...at, button } }) ?? {}, where = `${Math.round(at.x)}, ${Math.round(at.y)}`;
|
|
88
|
+
const named = `d.${action} target${target ? `, ${target},` : ''}`;
|
|
89
|
+
if (covered) throw new Error(`${named} is covered by a window of ${covered} at ${where}; close or move that window, then record again`);
|
|
90
|
+
if (nothing) throw new Error(`${named} lands at ${where}, where no window shows; it may lie outside the Desktop`);
|
|
91
|
+
}
|
|
92
|
+
/** Presses and releases at `at`, where the pointer is, noting a click on `box` for the Cursor, click effect and camera. */
|
|
93
|
+
async function clickAt(at, box, button, action, target) {
|
|
94
|
+
await pause('beforePress');
|
|
95
|
+
await down(at, button, action, target);
|
|
96
|
+
const t = now();
|
|
97
|
+
// A person holds the button for a moment, so the Cursor's press shows.
|
|
98
|
+
await wait(pauseMs('press', speed, rand));
|
|
99
|
+
await helper.request({ up: { ...at, button } });
|
|
100
|
+
notes.events.push({ type: 'click', t, end: now(), x: at.x, y: at.y, box, ...(button === 'right' && { button }) });
|
|
101
|
+
await pause('afterRelease');
|
|
102
|
+
}
|
|
103
|
+
/** `button: 'right'` opens the App's context menu instead. */
|
|
104
|
+
function click(target, opts) {
|
|
105
|
+
const { duration, button = 'left', ...rest } = options(opts, 'duration');
|
|
106
|
+
return act(rest, async () => {
|
|
107
|
+
const { box, at } = await approach(target, duration, 'click');
|
|
108
|
+
await clickAt(at, box, button, 'click', isAppLocator(target) && String(target));
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
/**
|
|
112
|
+
* Brings a window in front as a person would: glides to an empty part of its title bar that shows on
|
|
113
|
+
* the Desktop and clicks it, so the switch shows in the Final, then waits for it to come in front. The
|
|
114
|
+
* camera frames the window. A window already in front needs nothing.
|
|
115
|
+
*/
|
|
116
|
+
function switchTo(target, opts) {
|
|
117
|
+
if (!isAppWindow(target)) return Promise.reject(new Error("d.switchTo needs a window of the Take, such as d.app('Script Editor') or d.app('TextEdit').window('Untitled')"));
|
|
118
|
+
return act(options(opts), async () => {
|
|
119
|
+
const window = await resolveWindow(target), named = `d.switchTo(${target})`;
|
|
120
|
+
if (window.focused) return;
|
|
121
|
+
const spot = titleBarSpot(await helper.request({ titleBar: { ref: window.ref } }));
|
|
122
|
+
if (!spot) throw new Error(`${named} finds no empty part of the window's title bar showing on the Desktop; arrange the windows in prepare with setFrame so that it shows, or press 'Meta+Tab'`);
|
|
123
|
+
const at = { x: round(spot.x), y: round(spot.y) };
|
|
124
|
+
await glide(at, { size: Math.min(spot.width, TITLE_BAR_AIM) });
|
|
125
|
+
await clickAt(at, window.frame, 'left', 'switchTo', String(target));
|
|
126
|
+
for (const deadline = Date.now() + switchTimeout; !(await resolveWindow(target)).focused;) {
|
|
127
|
+
if (Date.now() >= deadline) throw new Error(`${named} clicked the window's title bar at ${Math.round(at.x)}, ${Math.round(at.y)}, but the window did not come in front within ${switchTimeout} ms`);
|
|
128
|
+
await wait(SWITCH_POLL_MS);
|
|
129
|
+
}
|
|
130
|
+
});
|
|
131
|
+
}
|
|
132
|
+
async function key(keys, hold) {
|
|
133
|
+
const { keyCode, modifiers } = macKeys(keys);
|
|
134
|
+
await helper.request({ key: { keyCode, modifiers, down: true } });
|
|
135
|
+
await wait(hold);
|
|
136
|
+
await helper.request({ key: { keyCode, modifiers, down: false } });
|
|
137
|
+
}
|
|
138
|
+
/** Presses a key or combination, such as 'Meta+K', on whatever has focus; the Final shows a Shortcut as keycaps. */
|
|
139
|
+
function press(keys, opts) {
|
|
140
|
+
return act(options(opts), async () => {
|
|
141
|
+
const { down: keydown } = macKeys(keys);
|
|
142
|
+
await pause('beforeKey');
|
|
143
|
+
const { role, subrole } = await helper.request({ focused: {} }) ?? {}, t = now();
|
|
144
|
+
await key(keys, pauseMs('press', speed, rand));
|
|
145
|
+
const shown = shortcutKeys({ ...keydown, field: FIELDS.has(role) || FIELDS.has(subrole) });
|
|
146
|
+
if (shown) notes.events.push({ type: 'shortcut', t, keys: shown });
|
|
147
|
+
await pause('afterKey');
|
|
148
|
+
});
|
|
149
|
+
}
|
|
150
|
+
/** Rests the pointer on a target without pressing, so the App shows its hover state. */
|
|
151
|
+
async function hover(target, opts) {
|
|
152
|
+
const { duration, ...rest } = options(opts, 'duration');
|
|
153
|
+
await act(rest, () => approach(target, duration, 'hover'));
|
|
154
|
+
}
|
|
155
|
+
function type(target, text, opts) {
|
|
156
|
+
const { msPerChar = 70 / speed, ...rest } = options(opts, 'msPerChar');
|
|
157
|
+
return act(rest, async () => {
|
|
158
|
+
await click(target, rest);
|
|
159
|
+
const { box } = notes.events.at(-1), chars = [...text], delays = typingDelays(text, msPerChar, rand), t = now();
|
|
160
|
+
for (let i = 0; i < chars.length; i++) {
|
|
161
|
+
if (i) await wait(delays[i - 1]);
|
|
162
|
+
if (TYPED_AS_KEYS[chars[i]]) await key(TYPED_AS_KEYS[chars[i]], 0);
|
|
163
|
+
else await helper.request({ text: chars[i] });
|
|
164
|
+
}
|
|
165
|
+
notes.events.push({ type: 'type', t, end: now(), box });
|
|
166
|
+
});
|
|
167
|
+
}
|
|
168
|
+
function drag(from, to, opts) {
|
|
169
|
+
const { duration, ...rest } = options(opts, 'duration');
|
|
170
|
+
const point = p => !isAppLocator(p) && typeof p?.x === 'number' && typeof p?.y === 'number';
|
|
171
|
+
if (!point(from) || !point(to)) return Promise.reject(new Error('d.drag goes from one point { x, y } to another, in Desktop points'));
|
|
172
|
+
return act(rest, async () => {
|
|
173
|
+
await glide(from);
|
|
174
|
+
await pause('beforePress');
|
|
175
|
+
await down(from, 'left', 'drag');
|
|
176
|
+
const t = now();
|
|
177
|
+
try {
|
|
178
|
+
await pause('afterGrab');
|
|
179
|
+
await glide(to, { duration, drag: true });
|
|
180
|
+
await pause('beforeDrop');
|
|
181
|
+
} finally { await helper.request({ up: { x: to.x, y: to.y, button: 'left' } }); }
|
|
182
|
+
notes.events.push({ type: 'drag', t, end: now(), from: { x: from.x, y: from.y }, to: { x: to.x, y: to.y } });
|
|
183
|
+
await pause('afterRelease');
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
/**
|
|
187
|
+
* Masks every element `locator` matches from now until `end()` is called or the Take ends, as on a
|
|
188
|
+
* page: the helper reads their frames at the capture rate, and the locator is resolved again as a
|
|
189
|
+
* page's is, so an element the App replaced is followed.
|
|
190
|
+
*/
|
|
191
|
+
async function mask(locator, opts = {}) {
|
|
192
|
+
const { effect = 'blur', ...params } = opts;
|
|
193
|
+
effectOf(effect);
|
|
194
|
+
if (!isAppLocator(locator)) throw new Error("d.mask needs a locator of the App, such as d.page.getByRole('button', { name: 'Save' })");
|
|
195
|
+
const t = effect !== 'spotlight' && !clock.state.waited ? 0 : now(), id = elements.length;
|
|
196
|
+
const watch = async () => helper.request({ watch: { id, refs: (await resolveAll(locator)).map(element => element.ref) } });
|
|
197
|
+
await watch();
|
|
198
|
+
return followMask({ id, tab: 0, name: String(locator), t, effect, params }, notes, { watch, signal, time: now });
|
|
199
|
+
}
|
|
200
|
+
return {
|
|
201
|
+
/** The window in front, whichever App owns it, offering Accessibility locators. */
|
|
202
|
+
get page() { return locators.page('front'); },
|
|
203
|
+
app: locators.app,
|
|
204
|
+
wait, time, at: clock.at, focus: clock.focus, say: clock.say, fastForward: clock.fastForward,
|
|
205
|
+
move: (x, y, duration) => glide({ x, y }, { duration }), hover, click, press, type, drag, mask, switchTo,
|
|
206
|
+
async scroll() { throw new Error('d.scroll works only on pages for now, not in a Take of Apps'); },
|
|
207
|
+
};
|
|
208
|
+
}
|