proofed-cli 0.1.3 → 0.2.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.
Files changed (65) hide show
  1. package/README.md +176 -122
  2. package/dist/action/requests.js +130 -0
  3. package/dist/{server.js → action/server.js} +17 -3
  4. package/dist/changes.js +7 -1
  5. package/dist/{args.js → check/args.js} +31 -3
  6. package/dist/check/cache.js +89 -0
  7. package/dist/{check.js → check/check.js} +86 -40
  8. package/dist/{doctor.js → check/doctor.js} +55 -19
  9. package/dist/check/help.js +139 -0
  10. package/dist/{list.js → check/list.js} +27 -15
  11. package/dist/{pipeline.js → check/pipeline.js} +106 -68
  12. package/dist/{render.js → check/render.js} +22 -15
  13. package/dist/check/run.js +277 -0
  14. package/dist/check/targetfilter.js +10 -0
  15. package/dist/check/textcheck.js +162 -0
  16. package/dist/env.js +6 -0
  17. package/dist/fix/agent.js +21 -0
  18. package/dist/fix/claude.js +30 -0
  19. package/dist/fix/codex.js +71 -0
  20. package/dist/fix/fixsetup.js +76 -0
  21. package/dist/fix/fixtarget.js +48 -0
  22. package/dist/fix/models.js +67 -0
  23. package/dist/github.js +62 -14
  24. package/dist/integrations/claude-stop.js +104 -0
  25. package/dist/integrations/cli.js +63 -0
  26. package/dist/integrations/mcp.js +130 -0
  27. package/dist/kane/creditmeter.js +104 -0
  28. package/dist/kane/kane.js +131 -0
  29. package/dist/kane/kaneauth.js +84 -0
  30. package/dist/kane/kaneversion.js +13 -0
  31. package/dist/paths.js +32 -0
  32. package/dist/process.js +65 -0
  33. package/dist/proofed.js +34 -16
  34. package/dist/{live.js → report/live.js} +1 -1
  35. package/dist/{livefile.js → report/livefile.js} +1 -1
  36. package/dist/{report.js → report/report.js} +105 -125
  37. package/dist/report/reportdata.js +120 -0
  38. package/dist/{result.js → report/result.js} +12 -7
  39. package/dist/{runfile.js → report/runfile.js} +2 -2
  40. package/dist/report/runresult.js +5 -0
  41. package/dist/scenarios.js +41 -19
  42. package/dist/secrets.js +74 -0
  43. package/dist/{cdp.js → targets/cdp.js} +20 -6
  44. package/dist/targets/chrome.js +98 -0
  45. package/dist/{clip.js → targets/clip.js} +21 -11
  46. package/dist/{precheck.js → targets/precheck.js} +53 -20
  47. package/dist/targets/preparetarget.js +350 -0
  48. package/dist/{recorder.js → targets/recorder.js} +154 -19
  49. package/dist/{serve.js → targets/serve.js} +9 -13
  50. package/dist/{target.js → targets/target.js} +42 -7
  51. package/dist/targets/targetchecks.js +139 -0
  52. package/dist/timing.js +25 -0
  53. package/dist/types.js +1 -0
  54. package/dist/which.js +26 -13
  55. package/docs/cli.md +370 -0
  56. package/package.json +10 -5
  57. package/dist/cache.js +0 -48
  58. package/dist/chrome.js +0 -77
  59. package/dist/help.js +0 -133
  60. package/dist/kane.js +0 -75
  61. package/dist/kaneauth.js +0 -48
  62. package/dist/models.js +0 -44
  63. package/dist/requests.js +0 -58
  64. package/dist/run.js +0 -173
  65. /package/dist/{deps.js → targets/deps.js} +0 -0
@@ -0,0 +1,350 @@
1
+ import { executableCommand, killTree } from "../process.js";
2
+ import { spawn } from "node:child_process";
3
+ import { appendFileSync, closeSync, constants, mkdirSync, mkdtempSync, openSync, readFileSync, renameSync, rmSync, writeFileSync } from "node:fs";
4
+ import { tmpdir } from "node:os";
5
+ import { basename, dirname, join } from "node:path";
6
+ import { adopt } from "../children.js";
7
+ import { log } from "../log.js";
8
+ import { launchChrome } from "./chrome.js";
9
+ import { cdpOccupied, command, isAppBundle, kaneTarget, localDevice, renderer, targetChecks } from "./targetchecks.js";
10
+ import { startRecorder } from "./recorder.js";
11
+ function owned(bin, args, cwd, env = process.env, shell = false, logDir) {
12
+ const command = shell ? { file: bin, args } : executableCommand(bin, args, env);
13
+ const stderrLog = logDir && join(logDir, "launch.stderr.log");
14
+ let stdout;
15
+ let stderr;
16
+ let proc;
17
+ try {
18
+ if (logDir)
19
+ stdout = openSync(join(logDir, "launch.stdout.log"), "w");
20
+ if (stderrLog)
21
+ stderr = openSync(stderrLog, "w");
22
+ proc = spawn(command.file, command.args, { cwd, env, shell, windowsHide: true, detached: true, stdio: ["ignore", stdout ?? "pipe", stderr ?? "pipe"] });
23
+ }
24
+ finally {
25
+ if (stderr !== undefined)
26
+ closeSync(stderr);
27
+ if (stdout !== undefined)
28
+ closeSync(stdout);
29
+ }
30
+ let output = "";
31
+ let error = "";
32
+ proc.stdout?.on("data", (data) => {
33
+ // Keep the beginning of adb's output, where the recording PID is printed.
34
+ if (output.length < 4096)
35
+ output += data.toString().slice(0, 4096 - output.length);
36
+ });
37
+ proc.stderr?.on("data", (data) => { error = (error + data.toString()).slice(-4096); });
38
+ const exited = new Promise((resolve) => {
39
+ proc.once("exit", () => resolve());
40
+ proc.once("error", (e) => {
41
+ error += String(e);
42
+ if (stderrLog) {
43
+ try {
44
+ appendFileSync(stderrLog, String(e));
45
+ }
46
+ catch { }
47
+ }
48
+ resolve();
49
+ });
50
+ });
51
+ const kill = (signal) => killTree(proc.pid, signal);
52
+ const release = adopt({ kill, exited });
53
+ let done = false;
54
+ void exited.then(() => { done = true; });
55
+ return {
56
+ exited, output: () => output, error: () => error, done: () => done,
57
+ async stop() {
58
+ kill("SIGINT");
59
+ await Promise.race([exited, new Promise((r) => setTimeout(r, 3000))]);
60
+ kill("SIGKILL");
61
+ release();
62
+ },
63
+ };
64
+ }
65
+ async function required(bin, args, timeout) {
66
+ const result = await command(bin, args, process.env, timeout);
67
+ if (!result.ok)
68
+ throw new Error(result.text);
69
+ return result.text;
70
+ }
71
+ async function nativeRecorder(target, dir, id) {
72
+ // Transferring and encoding long recordings can take minutes on CI runners.
73
+ const recordingTimeout = 10 * 60 * 1000;
74
+ const segments = [];
75
+ let stopped = false;
76
+ let current;
77
+ let remotePid;
78
+ let pendingPid;
79
+ let transferred = Promise.resolve();
80
+ let transferError;
81
+ const prefix = `proofed-${process.pid}-${Date.now()}`;
82
+ const started = Date.now() / 1000;
83
+ let began = () => { };
84
+ const ready = new Promise((r) => { began = r; });
85
+ const loop = (async () => {
86
+ try {
87
+ for (let index = 0; !stopped; index++) {
88
+ const file = join(dir, `native-${index}.mp4`);
89
+ const remote = `/sdcard/${prefix}-${index}.mp4`;
90
+ current = target.kind === "ios"
91
+ ? owned("xcrun", ["simctl", "io", id, "recordVideo", file])
92
+ // One argument: adb joins shell arguments with spaces, so `sh -c <script>` would lose the script's arguments.
93
+ : owned("adb", ["-s", id, "shell", `screenrecord --time-limit 175 ${remote} & p=$!; echo $p; wait $p`]);
94
+ remotePid = undefined;
95
+ if (target.kind === "android") {
96
+ const pid = Promise.withResolvers();
97
+ pendingPid = pid.promise;
98
+ for (let i = 0; i < 50 && !current.done(); i++) {
99
+ remotePid = /^\d+/m.exec(current.output())?.[0];
100
+ if (remotePid)
101
+ break;
102
+ await new Promise((r) => setTimeout(r, 100));
103
+ }
104
+ pendingPid = undefined;
105
+ pid.resolve();
106
+ }
107
+ if (target.kind === "android" && !remotePid) {
108
+ await current.stop();
109
+ throw new Error(`screenrecord did not return its PID: ${current.error()}`);
110
+ }
111
+ began();
112
+ await current.exited;
113
+ remotePid = undefined;
114
+ await current.stop();
115
+ if (target.kind === "ios") {
116
+ segments.push(file);
117
+ break;
118
+ }
119
+ // Start the next capture immediately while completed segments transfer in order.
120
+ transferred = transferred.then(async () => {
121
+ const remove = ["-s", id, "shell", "rm", remote];
122
+ try {
123
+ await required("adb", ["-s", id, "pull", remote, file], recordingTimeout);
124
+ }
125
+ catch (error) {
126
+ await command("adb", remove);
127
+ throw error;
128
+ }
129
+ segments.push(file);
130
+ const removed = await command("adb", remove);
131
+ if (!removed.ok) {
132
+ try {
133
+ log(`Could not remove Android recording ${remote}: ${removed.text}`);
134
+ }
135
+ catch { /* A log write failure should not discard the local segment. */ }
136
+ }
137
+ }).catch((cause) => { transferError ??= { cause }; });
138
+ }
139
+ }
140
+ finally {
141
+ await transferred;
142
+ }
143
+ if (transferError)
144
+ throw transferError.cause;
145
+ })();
146
+ // Attach the rejection handler now; stop() reports it after Kane finishes.
147
+ void loop.catch(() => { });
148
+ await Promise.race([ready, loop]);
149
+ let stopping;
150
+ return {
151
+ started,
152
+ stop() {
153
+ return stopping ??= (async () => {
154
+ stopped = true;
155
+ if (target.kind === "android") {
156
+ // A new segment can already be recording while adb is still reporting its PID.
157
+ if (!remotePid && pendingPid)
158
+ await pendingPid;
159
+ if (remotePid) {
160
+ const signal = await command("adb", ["-s", id, "shell", "kill", "-2", remotePid]);
161
+ // The segment can expire while adb is delivering the signal.
162
+ if (!signal.ok && !/no such process/i.test(signal.text))
163
+ throw new Error(signal.text);
164
+ }
165
+ }
166
+ else
167
+ await current?.stop();
168
+ await loop;
169
+ const list = join(dir, "segments.txt");
170
+ writeFileSync(list, segments.map((f) => `file '${f.replaceAll("\\", "/").replaceAll("'", "'\\''")}'`).join("\n"));
171
+ const mp4 = join(dir, "clip.mp4"), jpg = join(dir, "clip.jpg"), gif = join(dir, "clip.gif");
172
+ const untrimmed = join(dir, "clip-untrimmed.mp4");
173
+ try {
174
+ // Use a constant frame rate so the thumbnail seek finds a frame even when the Android screen stops changing.
175
+ await required("ffmpeg", ["-y", "-f", "concat", "-safe", "0", "-i", list, "-vf", "fps=10,scale=trunc(iw/2)*2:trunc(ih/2)*2", "-c:v", "libx264", "-bf", "0", "-pix_fmt", "yuv420p", untrimmed], recordingTimeout);
176
+ const { text } = await command("ffmpeg", ["-hide_banner", "-i", untrimmed], process.env, recordingTimeout);
177
+ const duration = /^\s*Duration: (\d+):(\d{2}):(\d{2}\.\d+),/m.exec(text);
178
+ const seconds = duration ? Number(duration[1]) * 3600 + Number(duration[2]) * 60 + Number(duration[3]) : 0;
179
+ // Kane closes the app at the end, so cut away the launcher frames.
180
+ if (seconds > 3)
181
+ await required("ffmpeg", ["-y", "-i", untrimmed, "-t", (seconds - 1.5).toFixed(2), "-c", "copy", mp4], recordingTimeout);
182
+ else
183
+ renameSync(untrimmed, mp4);
184
+ }
185
+ finally {
186
+ rmSync(untrimmed, { force: true });
187
+ }
188
+ await required("ffmpeg", ["-y", "-sseof", "-0.1", "-i", mp4, "-frames:v", "1", jpg], recordingTimeout);
189
+ await required("ffmpeg", ["-y", "-i", mp4, "-vf", "fps=6,scale=480:-1", gif], recordingTimeout);
190
+ return { mp4, jpg, gif };
191
+ })();
192
+ },
193
+ };
194
+ }
195
+ const alive = (pid) => {
196
+ if (!Number.isSafeInteger(pid) || pid <= 0)
197
+ return false;
198
+ try {
199
+ process.kill(pid, 0);
200
+ return true;
201
+ }
202
+ catch (e) {
203
+ return e.code === "EPERM";
204
+ }
205
+ };
206
+ // Darwin's O_EXLOCK is missing from Node's constants. Local devices only run on macOS.
207
+ const O_EXLOCK = 0x20;
208
+ export function lockDevice(id, dir = tmpdir()) {
209
+ if (process.platform !== "darwin")
210
+ throw new Error("Local mobile device locks require macOS");
211
+ const lock = join(dir, `proofed-device-${id.replace(/[^\w-]/g, "_")}.lock`);
212
+ const inUse = (owner) => new Error(`Device ${id} is in use by another Proofed run${owner ? ` (pid ${owner})` : ""}. Wait for it to finish.`);
213
+ // Keep the guard inode so every contender locks the same file, even during stale PID cleanup.
214
+ // The kernel releases the guard if its owner dies.
215
+ let guard;
216
+ try {
217
+ guard = openSync(`${lock}.guard`, constants.O_WRONLY | constants.O_CREAT | constants.O_NONBLOCK | constants.O_NOFOLLOW | O_EXLOCK, 0o600);
218
+ }
219
+ catch (e) {
220
+ if (e.code === "EAGAIN")
221
+ throw inUse();
222
+ throw e;
223
+ }
224
+ try {
225
+ try {
226
+ writeFileSync(lock, String(process.pid), { flag: "wx" });
227
+ }
228
+ catch (e) {
229
+ if (e.code !== "EEXIST")
230
+ throw e;
231
+ let owner = 0;
232
+ try {
233
+ owner = Number(readFileSync(lock, "utf8").trim());
234
+ }
235
+ catch { }
236
+ if (alive(owner))
237
+ throw inUse(owner);
238
+ rmSync(lock, { recursive: true, force: true });
239
+ writeFileSync(lock, String(process.pid), { flag: "wx" });
240
+ }
241
+ let released = false;
242
+ return () => {
243
+ if (released)
244
+ return;
245
+ released = true;
246
+ try {
247
+ rmSync(lock, { force: true });
248
+ }
249
+ finally {
250
+ closeSync(guard);
251
+ }
252
+ };
253
+ }
254
+ catch (e) {
255
+ closeSync(guard);
256
+ throw e;
257
+ }
258
+ }
259
+ export async function prepareTarget(target, options) {
260
+ mkdirSync(options.dir, { recursive: true });
261
+ const cleanups = [];
262
+ const cleanup = async () => {
263
+ for (const fn of cleanups.reverse()) {
264
+ try {
265
+ await fn();
266
+ }
267
+ catch { }
268
+ }
269
+ };
270
+ try {
271
+ if (target.kind === "web") {
272
+ const chrome = await launchChrome({ headless: options.headless ?? true });
273
+ cleanups.push(() => chrome.close());
274
+ const recorder = await startRecorder(chrome.endpoint, join(options.dir, "frames"));
275
+ cleanups.push(() => recorder.stop());
276
+ return { kaneArgs: ["--target", "desktop", "--url", options.url, "--cdp-endpoint", chrome.endpoint], recorder, clipEndpoint: chrome.endpoint, cleanup, metadata: { target } };
277
+ }
278
+ if (target.kind === "desktop") {
279
+ if (!target.cdp_endpoint || (!target.launch && !target.app && !target.reuse))
280
+ throw new Error("Desktop requires cdp_endpoint and launch or app, or explicit --reuse");
281
+ if (target.launch || target.app) {
282
+ const env = { ...process.env };
283
+ // Electron inherits this from some Node hosts and exits as a Node CLI instead of an app.
284
+ delete env.ELECTRON_RUN_AS_NODE;
285
+ let bin = target.launch ?? target.app;
286
+ const args = [];
287
+ if (!target.launch) {
288
+ if (bin.endsWith(".app")) {
289
+ const executable = (await required("/usr/bin/plutil", ["-extract", "CFBundleExecutable", "raw", "-o", "-", join(bin, "Contents/Info.plist")])).trim();
290
+ if (!executable || basename(executable) !== executable)
291
+ throw new Error("Desktop .app has no valid CFBundleExecutable");
292
+ bin = join(bin, "Contents/MacOS", executable);
293
+ }
294
+ const endpoint = new URL(target.cdp_endpoint);
295
+ args.push(`--remote-debugging-port=${endpoint.port || (endpoint.protocol === "https:" ? "443" : "80")}`);
296
+ }
297
+ if (await cdpOccupied(target.cdp_endpoint))
298
+ throw new Error("CDP endpoint already answers; omit launch and app and pass --reuse");
299
+ const app = owned(bin, args, target.dir, env, !!target.launch, options.dir);
300
+ cleanups.push(() => app.stop());
301
+ }
302
+ let page;
303
+ for (let i = 0; i < 100; i++) {
304
+ try {
305
+ page = await renderer(target.cdp_endpoint);
306
+ break;
307
+ }
308
+ catch (e) {
309
+ if (i === 99)
310
+ throw e;
311
+ }
312
+ await new Promise((r) => setTimeout(r, 200));
313
+ }
314
+ const recorder = await startRecorder(target.cdp_endpoint, join(options.dir, "frames"), page.id);
315
+ cleanups.push(() => recorder.stop());
316
+ return {
317
+ kaneArgs: ["--target", "desktop", "--cdp-endpoint", target.cdp_endpoint, "--allow-missing-url"], recorder, cleanup, metadata: { target },
318
+ montage: async () => { const chrome = await launchChrome(); cleanups.push(() => chrome.close()); return chrome.endpoint; },
319
+ };
320
+ }
321
+ const checks = await targetChecks(target);
322
+ const failed = checks.filter((c) => c.status === "fail");
323
+ if (failed.length)
324
+ throw new Error(failed.map((c) => `${c.name}: ${c.detail}. Fix: ${c.fix}`).join("\n"));
325
+ let app = target.app;
326
+ if (isAppBundle(app)) {
327
+ const temp = mkdtempSync(join(tmpdir(), "proofed-app-"));
328
+ cleanups.push(() => rmSync(temp, { recursive: true, force: true }));
329
+ const zip = join(temp, "simulator.zip");
330
+ const result = await command("/usr/bin/ditto", ["-c", "-k", "--keepParent", join(dirname(app), basename(app)), zip]);
331
+ if (!result.ok)
332
+ throw new Error(result.text);
333
+ app = zip;
334
+ }
335
+ const kaneArgs = ["--target", kaneTarget(target), "--app", app, ...(target.device ? ["--device-name", target.device] : []), ...(target.os_version ? ["--os-version", target.os_version] : [])];
336
+ // Pass the file on every run, never replace it with an APP ID. Kane hashes its bytes before
337
+ // looking up an upload, so a rebuild at the same path cannot select the old artifact.
338
+ if (target.execution === "cloud")
339
+ return { kaneArgs, cleanup, metadata: { target, recordingNote: "Cloud run, screenshot-only: no local MP4. Kane's report with the device screenshots is at kaneReport." } };
340
+ const id = await localDevice(target);
341
+ cleanups.push(lockDevice(id));
342
+ const native = await nativeRecorder(target, options.dir, id);
343
+ cleanups.push(() => native.stop());
344
+ return { kaneArgs, native, cleanup, metadata: { target } };
345
+ }
346
+ catch (error) {
347
+ await cleanup();
348
+ throw error;
349
+ }
350
+ }
@@ -1,5 +1,7 @@
1
1
  import { mkdirSync, writeFileSync } from "node:fs";
2
2
  import { join } from "node:path";
3
+ import { setTimeout as delay } from "node:timers/promises";
4
+ import { VISIBLE_TEXT } from "../check/textcheck.js";
3
5
  import { connectCdp } from "./cdp.js";
4
6
  const PAGE = `({ doc: performance.timeOrigin, href: location.href, sx: scrollX, sy: scrollY, w: innerWidth, h: innerHeight })`;
5
7
  const MAX_WIDTH = 1920;
@@ -12,6 +14,12 @@ const BINDING = "__proofedAction";
12
14
  // It also says which page the action was on, so the live view only draws a cursor over the same
13
15
  // page as it was then.
14
16
  const LISTENER = `(() => {
17
+ // Reusing a renderer can leave the previous recorder's handlers in this document.
18
+ const key = Symbol.for("proofed.actionListener");
19
+ globalThis[key]?.abort();
20
+ const controller = new AbortController();
21
+ globalThis[key] = controller;
22
+ const options = { capture: true, signal: controller.signal };
15
23
  const report = (kind, x, y, el) => {
16
24
  const r = el.getBoundingClientRect();
17
25
  const page = ${PAGE};
@@ -26,14 +34,14 @@ const LISTENER = `(() => {
26
34
  typingIn = null;
27
35
  clicked = { el: e.target, x: e.clientX, y: e.clientY };
28
36
  report("click", e.clientX, e.clientY, e.target);
29
- }, true);
37
+ }, options);
30
38
  // A click dispatched from script has no pointer events before it: place it on the element.
31
39
  addEventListener("click", (e) => {
32
40
  if (Date.now() - pointerAt < 500 || !(e.target instanceof Element)) return;
33
41
  const r = e.target.getBoundingClientRect();
34
42
  clicked = { el: e.target, x: r.x + r.width / 2, y: r.y + r.height / 2 };
35
43
  report("click", clicked.x, clicked.y, e.target);
36
- }, true);
44
+ }, options);
37
45
  // Typing in the field Kane just clicked stays at the click point, still inside the field unless it
38
46
  // scrolled away; its centre would make the cursor jump a few pixels within the same field.
39
47
  addEventListener("input", (e) => {
@@ -44,7 +52,7 @@ const LISTENER = `(() => {
44
52
  ? clicked
45
53
  : { x: r.x + r.width / 2, y: r.y + r.height / 2 };
46
54
  report("type", at.x, at.y, e.target);
47
- }, true);
55
+ }, options);
48
56
  })();`;
49
57
  // Finds the smallest visible element that mentions most of the given words, so the end of the
50
58
  // clip can settle on what the final check was about (a total, a confirmation message).
@@ -86,41 +94,80 @@ export const samePage = (a, b) => a.doc === b.doc && a.href === b.href && Math.a
86
94
  // Kane doesn't record video, so we attach to the same Chrome over CDP and keep every
87
95
  // screencast frame with its timestamp. Frames are only sent when the page repaints,
88
96
  // which is why the clip later replays them with their real durations.
89
- export async function startRecorder(endpoint, outDir) {
97
+ export async function startRecorder(endpoint, outDir, targetId, discoveryTimeoutMs = 30_000) {
90
98
  mkdirSync(outDir, { recursive: true });
91
- const cdp = await connectCdp(endpoint);
99
+ const cdp = await connectCdp(endpoint, AbortSignal.timeout(targetId ? 5000 : 30_000));
92
100
  const frames = [];
101
+ let frameWriteError;
93
102
  const actions = [];
94
103
  let lastSession;
95
104
  let lastAction;
96
105
  // The latest screencast frame of each page. Chrome sends one on each repaint, so it shows the page
97
106
  // as it still is until the next comes in.
98
107
  const latest = new Map();
99
- const attached = new Set();
100
- cdp.on("Target.targetCreated", ({ targetInfo }) => {
101
- if (targetInfo.type !== "page" || attached.has(targetInfo.targetId))
108
+ let unexpectedPage = false;
109
+ let onUnexpectedPage;
110
+ const openPages = new Map();
111
+ const ready = Promise.withResolvers();
112
+ cdp.on("Target.targetCreated", ({ targetInfo: { type, targetId: id } }) => {
113
+ if (type !== "page" || openPages.has(id))
102
114
  return;
103
- attached.add(targetInfo.targetId);
104
- void cdp.send("Target.attachToTarget", { targetId: targetInfo.targetId, flatten: true }).catch(() => { });
115
+ openPages.set(id, undefined);
116
+ if (targetId && id !== targetId) {
117
+ unexpectedPage = true;
118
+ onUnexpectedPage?.();
119
+ return;
120
+ }
121
+ void cdp.send("Target.attachToTarget", { targetId: id, flatten: true }).catch((error) => {
122
+ if (targetId)
123
+ ready.reject(error);
124
+ });
125
+ });
126
+ cdp.on("Target.targetDestroyed", ({ targetId }) => openPages.delete(targetId));
127
+ cdp.on("Target.detachedFromTarget", ({ sessionId }) => {
128
+ for (const [id, session] of openPages) {
129
+ if (session !== sessionId)
130
+ continue;
131
+ openPages.delete(id);
132
+ break;
133
+ }
105
134
  });
106
135
  const prepare = async (sessionId) => {
107
136
  await cdp.send("Page.enable", {}, sessionId);
108
137
  await cdp.send("Runtime.enable", {}, sessionId);
109
138
  await cdp.send("Runtime.addBinding", { name: BINDING }, sessionId);
110
139
  await cdp.send("Page.addScriptToEvaluateOnNewDocument", { source: LISTENER }, sessionId);
140
+ if (targetId) {
141
+ const { exceptionDetails } = await cdp.send("Runtime.evaluate", { expression: LISTENER }, sessionId);
142
+ if (exceptionDetails) {
143
+ ready.reject(new Error(`Could not install the desktop recorder listener: ${exceptionDetails.exception?.description ?? exceptionDetails.text}`));
144
+ return;
145
+ }
146
+ }
111
147
  await cdp.send("Page.startScreencast", { format: "jpeg", quality: 80, maxWidth: MAX_WIDTH, maxHeight: MAX_HEIGHT }, sessionId);
148
+ ready.resolve();
112
149
  };
113
- let firstPage = () => { };
114
- const ready = new Promise((resolve) => (firstPage = resolve));
115
150
  cdp.on("Target.attachedToTarget", ({ sessionId, targetInfo }) => {
116
- if (targetInfo.type !== "page")
151
+ const id = targetInfo.targetId;
152
+ if (!openPages.has(id) || (targetId && id !== targetId))
117
153
  return;
118
- prepare(sessionId).then(() => firstPage(targetInfo), () => { });
154
+ openPages.set(id, sessionId);
155
+ // The page can close or navigate during setup.
156
+ void prepare(sessionId).catch(() => { });
119
157
  });
120
158
  cdp.on("Page.screencastFrame", ({ data, metadata, sessionId: ack }, sessionId) => {
121
159
  const file = join(outDir, `${String(frames.length).padStart(5, "0")}.jpg`);
122
160
  const jpeg = Buffer.from(data, "base64");
123
- writeFileSync(file, jpeg);
161
+ try {
162
+ writeFileSync(file, jpeg);
163
+ }
164
+ catch (error) {
165
+ frameWriteError ??= error;
166
+ return;
167
+ }
168
+ finally {
169
+ void cdp.send("Page.screencastFrameAck", { sessionId: ack }, sessionId).catch(() => { });
170
+ }
124
171
  const scale = Math.min(1, MAX_WIDTH / metadata.deviceWidth, MAX_HEIGHT / metadata.deviceHeight);
125
172
  frames.push({
126
173
  file,
@@ -133,7 +180,6 @@ export async function startRecorder(endpoint, outDir) {
133
180
  lastSession = sessionId;
134
181
  if (sessionId)
135
182
  latest.set(sessionId, { jpeg, meta: metadata });
136
- void cdp.send("Page.screencastFrameAck", { sessionId: ack }, sessionId).catch(() => { });
137
183
  });
138
184
  cdp.on("Runtime.bindingCalled", ({ name, payload }, sessionId) => {
139
185
  if (name !== BINDING)
@@ -158,10 +204,33 @@ export async function startRecorder(endpoint, outDir) {
158
204
  return undefined;
159
205
  return { jpeg: frame.jpeg, at: Date.now(), cursor: { x: action.x / page.w, y: action.y / page.h } };
160
206
  };
161
- await cdp.send("Target.setDiscoverTargets", { discover: true });
162
- // Don't let Kane navigate before the listener is installed on the starting tab.
163
- await Promise.race([ready, new Promise((r) => setTimeout(r, 5000))]);
164
207
  const recorder = {
208
+ async visibleText() {
209
+ // Kane doesn't report which tab it checked, so only read when one page is open.
210
+ let sessionId = openPages.values().next().value;
211
+ for (let i = 0; !sessionId && openPages.size < 2 && i < 20; i++) {
212
+ await new Promise((r) => setTimeout(r, 100));
213
+ sessionId = openPages.values().next().value;
214
+ }
215
+ if (!sessionId || openPages.size !== 1)
216
+ return;
217
+ try {
218
+ const busy = new Promise((_, reject) => setTimeout(reject, 5000).unref());
219
+ const expression = `({ document: performance.timeOrigin, href: location.href, text: ${VISIBLE_TEXT} })`;
220
+ const read = cdp.send("Runtime.evaluate", { expression, returnByValue: true }, sessionId);
221
+ const { result } = await Promise.race([read, busy]);
222
+ const value = result.value;
223
+ if (openPages.size === 1 && openPages.values().next().value === sessionId && typeof value?.text === "string") {
224
+ return { session: sessionId, ...value };
225
+ }
226
+ }
227
+ catch {
228
+ return undefined;
229
+ }
230
+ },
231
+ get unexpectedPage() { return unexpectedPage; },
232
+ set onUnexpectedPage(callback) { onUnexpectedPage = callback; },
233
+ get frameWriteError() { return frameWriteError; },
165
234
  frames,
166
235
  actions,
167
236
  // Called on each of Kane's clicks and the first keystroke in a field, with the frame from just
@@ -200,10 +269,76 @@ export async function startRecorder(endpoint, outDir) {
200
269
  return undefined; // The page is navigating or closed; the next one will do.
201
270
  }
202
271
  },
272
+ // A static page may still be visible when Chrome has sent no usable screencast frame.
273
+ async captureFrame() {
274
+ const sessions = [...openPages.values()].filter((session) => session !== undefined).reverse();
275
+ const capture = async (session) => {
276
+ const { result } = await cdp.send("Runtime.evaluate", { expression: "({ href: location.href, visible: document.visibilityState === 'visible', width: innerWidth, height: innerHeight, scale: devicePixelRatio })", returnByValue: true }, session);
277
+ const page = result.value;
278
+ if (!page || page.href === "about:blank" || (!page.visible && sessions.length > 1))
279
+ return;
280
+ const { data } = await cdp.send("Page.captureScreenshot", { format: "jpeg", quality: 80 }, session);
281
+ return { ...page, data };
282
+ };
283
+ let lastError;
284
+ for (const session of sessions) {
285
+ try {
286
+ const shot = await capture(session).catch(async (error) => {
287
+ if (!(error instanceof Error) || error.message !== "Unable to capture screenshot")
288
+ throw error;
289
+ // Give Chrome a chance to present a surface, then read the viewport again.
290
+ await cdp.send("Page.bringToFront", {}, session);
291
+ await delay(250);
292
+ const retry = await capture(session);
293
+ if (!retry)
294
+ throw error;
295
+ return retry;
296
+ });
297
+ if (!shot)
298
+ continue;
299
+ const { data, width, height, scale } = shot;
300
+ const time = Date.now() / 1000;
301
+ const jpeg = Buffer.from(data, "base64");
302
+ const file = join(outDir, "fallback.jpg");
303
+ writeFileSync(file, jpeg);
304
+ return { file, time, scale, width: Math.round(width * scale), height: Math.round(height * scale), bytes: jpeg.length };
305
+ }
306
+ catch (cause) {
307
+ lastError = { cause };
308
+ }
309
+ }
310
+ if (lastError)
311
+ throw lastError.cause;
312
+ },
203
313
  stop() {
204
314
  cdp.close();
205
315
  return { frames, actions };
206
316
  },
207
317
  };
318
+ // Don't let Kane navigate before the listener is installed on the starting tab.
319
+ const timer = setTimeout(() => ready.resolve(), 5000);
320
+ // A silent Chrome must not hang the run; a busy CI runner can take well over 5 s to answer.
321
+ const discoveryTimeout = Promise.withResolvers();
322
+ const discoveryTimer = setTimeout(() => discoveryTimeout.reject(new Error("Timed out discovering Chrome targets")), discoveryTimeoutMs);
323
+ discoveryTimeout.promise.catch(() => { }); // Only the web path awaits it.
324
+ try {
325
+ const discovery = cdp.send("Target.setDiscoverTargets", { discover: true });
326
+ if (targetId) {
327
+ // Desktop setup can continue even if discovery stalls or fails.
328
+ void discovery.catch(() => { });
329
+ await ready.promise;
330
+ }
331
+ else {
332
+ await Promise.all([Promise.race([discovery, discoveryTimeout.promise]), ready.promise]);
333
+ }
334
+ }
335
+ catch (error) {
336
+ cdp.close();
337
+ throw error;
338
+ }
339
+ finally {
340
+ clearTimeout(timer);
341
+ clearTimeout(discoveryTimer);
342
+ }
208
343
  return recorder;
209
344
  }
@@ -1,11 +1,12 @@
1
1
  // The app under test on this machine: used as it is when its URL already answers, otherwise built
2
2
  // and served for the check, then stopped. The commands run in a process group of their own, so
3
3
  // stopping the server also stops what it started (pnpm → vite), on Ctrl-C too.
4
+ import { killTree } from "../process.js";
4
5
  import { spawn } from "node:child_process";
5
6
  import { closeSync, openSync, readFileSync, writeSync } from "node:fs";
6
- import { adopt } from "./children.js";
7
+ import { adopt } from "../children.js";
7
8
  import { depsMissing, installCommand, stampInstall } from "./deps.js";
8
- import { SetupError } from "./setuperror.js";
9
+ import { SetupError } from "../setuperror.js";
9
10
  // Any HTTP answer below 500 means a server is there; a proxy in front of nothing gives 502.
10
11
  export async function answers(url, timeout = 2000) {
11
12
  try {
@@ -28,26 +29,18 @@ export function tail(file, lines = 20) {
28
29
  function start(command, cwd, logFile) {
29
30
  const fd = openSync(logFile, "a");
30
31
  writeSync(fd, `$ ${command}\n`);
31
- const proc = spawn(command, { cwd, shell: true, detached: true, stdio: ["ignore", fd, fd] });
32
+ const proc = spawn(command, { cwd, shell: true, detached: true, windowsHide: true, stdio: ["ignore", fd, fd] });
32
33
  closeSync(fd);
33
34
  const exited = new Promise((resolve) => {
34
35
  proc.once("exit", (code, signal) => resolve(code ?? (signal ? 128 : null)));
35
36
  proc.once("error", () => resolve(127));
36
37
  });
37
- const kill = (signal) => {
38
- try {
39
- if (proc.pid)
40
- process.kill(-proc.pid, signal);
41
- }
42
- catch {
43
- // Already gone.
44
- }
45
- };
38
+ const kill = (signal) => killTree(proc.pid, signal);
46
39
  const release = adopt({ kill, exited });
47
40
  void exited.then(release);
48
41
  return { proc, exited, kill, release };
49
42
  }
50
- export async function startApp(o) {
43
+ export async function buildApp(o) {
51
44
  const missing = depsMissing(o.cwd);
52
45
  if (missing) {
53
46
  const install = installCommand(o.cwd, o.install);
@@ -66,6 +59,9 @@ export async function startApp(o) {
66
59
  throw new SetupError("build_failed", `The build command exited with code ${code}: ${o.build}\n${tail(o.logFile)}`, `Make the build pass, or set another one with --build "<command>". Full output: ${o.logFile}`);
67
60
  }
68
61
  }
62
+ }
63
+ export async function startApp(o) {
64
+ await buildApp(o);
69
65
  o.onPhase?.(`Starting the app: ${o.serve}`);
70
66
  const server = start(o.serve, o.cwd, o.logFile);
71
67
  let exitCode;