@clipy/cli 0.14.0 → 0.15.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.
@@ -0,0 +1,656 @@
1
+ /**
2
+ * Chrome for Clipy: a dedicated automation browser the CLI owns.
3
+ *
4
+ * A separate, persistent Chrome instance (own --user-data-dir, own identity)
5
+ * launched with the capability flags an agent needs and a daily browser should
6
+ * never run with:
7
+ *
8
+ * - --remote-debugging-port → CDP for any driver (Playwright, Puppeteer, raw)
9
+ * - --auto-select-tab-capture-source-by-title
10
+ * → getDisplayMedia picks its tab WITHOUT the
11
+ * picker. The regex matches the
12
+ * TAB_CAPTURE_TITLE_MARKER prefix, so the
13
+ * capture target is chosen AT RUNTIME by
14
+ * retitling the target tab. The flag is
15
+ * fixed at launch, the choice is not.
16
+ * - the three background-throttling disables
17
+ * → backgrounded tabs keep rendering, so
18
+ * screencast/capture of hidden tabs works.
19
+ * - --allowlisted-extension-id → the Clipy extension installed in this
20
+ * profile may call tabCapture without the
21
+ * toolbar click (see chromeExtensionCapture.ts).
22
+ * Verified on Chrome 154; it is a test
23
+ * switch, not a supported API.
24
+ *
25
+ * The user signs in once; the profile persists across launches. This is the
26
+ * agent-owned end of the capture-provider spectrum: everything here is
27
+ * gesture-free because Clipy launched the browser, which is precisely the line
28
+ * Chrome's security model draws (see docs/plans/2026-09-01-001).
29
+ *
30
+ * State lives at ~/.config/clipy/chrome-for-clipy/: `profile/` (user data dir)
31
+ * and `state.json` ({pid, port, startedAt}). `installApp()` writes a macOS
32
+ * launcher bundle "Chrome for Clipy.app" so the browser exists as a named app
33
+ * in Finder/Spotlight; while running, the Dock still shows Google Chrome's
34
+ * icon (macOS resolves the running bundle from the real binary; renaming that
35
+ * would mean copying the whole .app and breaking its code signature/updates).
36
+ */
37
+ import { spawn, spawnSync } from "node:child_process";
38
+ import { appendFileSync, copyFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
39
+ import { dirname, join } from "node:path";
40
+ import { fileURLToPath, pathToFileURL } from "node:url";
41
+ export const DEFAULT_CDP_PORT = 9333;
42
+ /** Retitle a tab to start with this and the auto-select flag captures it.
43
+ * Deliberately free of regex metacharacters: Chrome may treat the flag value
44
+ * as a pattern, and e.g. `[clipy-rec]` would become a character class. */
45
+ export const TAB_CAPTURE_TITLE_MARKER = "clipy-rec";
46
+ export const APP_NAME = "Chrome for Clipy";
47
+ /** The Web Store id of the Clipy extension. CLIPY_EXTENSION_ID overrides it
48
+ * for an unpacked development build. */
49
+ export const CLIPY_EXTENSION_STORE_ID = "kpoeghpnpjdaglohmnemgkljahinendl";
50
+ export function clipyExtensionId(env = process.env) {
51
+ const override = env.CLIPY_EXTENSION_ID?.trim();
52
+ return override && /^[a-p]{32}$/.test(override) ? override : CLIPY_EXTENSION_STORE_ID;
53
+ }
54
+ const MACOS_CHROME = "/Applications/Google Chrome.app/Contents/MacOS/Google Chrome";
55
+ const LINUX_CHROME_CANDIDATES = ["/usr/bin/google-chrome", "/usr/bin/google-chrome-stable", "/usr/bin/chromium"];
56
+ export function chromeForClipyDir(home) {
57
+ return join(home, ".config", "clipy", "chrome-for-clipy");
58
+ }
59
+ function profileDir(home) {
60
+ return join(chromeForClipyDir(home), "profile");
61
+ }
62
+ function stateFile(home) {
63
+ return join(chromeForClipyDir(home), "state.json");
64
+ }
65
+ export function resolveChromeBinary(env, platform, home) {
66
+ void home; // kept in the signature for a future fork-aware resolution
67
+ const override = env.CLIPY_CHROME_BINARY?.trim();
68
+ if (override)
69
+ return existsSync(override) ? override : null;
70
+ if (platform === "darwin")
71
+ return existsSync(MACOS_CHROME) ? MACOS_CHROME : null;
72
+ if (platform === "linux")
73
+ return LINUX_CHROME_CANDIDATES.find((p) => existsSync(p)) ?? null;
74
+ return null;
75
+ }
76
+ /** What makes a process OUR instance: the dedicated profile on our port. */
77
+ function identityArgs(home, port) {
78
+ return [`--user-data-dir=${profileDir(home)}`, `--remote-debugging-port=${port}`];
79
+ }
80
+ /** The launch argv, one place, shared by `clipy chrome start` and the .app launcher. */
81
+ export function launchArgs(home, port, env = process.env) {
82
+ return [
83
+ ...identityArgs(home, port),
84
+ // The regex is fixed at launch; the marker makes target selection dynamic.
85
+ `--auto-select-tab-capture-source-by-title=${TAB_CAPTURE_TITLE_MARKER}`,
86
+ `--allowlisted-extension-id=${clipyExtensionId(env)}`,
87
+ "--disable-background-timer-throttling",
88
+ "--disable-backgrounding-occluded-windows",
89
+ "--disable-renderer-backgrounding",
90
+ "--no-first-run",
91
+ "--no-default-browser-check",
92
+ "--hide-crash-restore-bubble",
93
+ ];
94
+ }
95
+ /** Name the profile before first launch so the avatar badge reads as the product. */
96
+ function seedProfileName(home) {
97
+ const prefs = join(profileDir(home), "Default", "Preferences");
98
+ if (existsSync(prefs))
99
+ return;
100
+ mkdirSync(join(profileDir(home), "Default"), { recursive: true });
101
+ writeFileSync(prefs, JSON.stringify({ profile: { name: APP_NAME } }));
102
+ }
103
+ export function readState(home) {
104
+ try {
105
+ const parsed = JSON.parse(readFileSync(stateFile(home), "utf8"));
106
+ return Number.isInteger(parsed.pid) && parsed.pid > 0 &&
107
+ Number.isInteger(parsed.port) && parsed.port > 0 && parsed.port <= 65535 &&
108
+ typeof parsed.binary === "string" ? parsed : null;
109
+ }
110
+ catch {
111
+ return null;
112
+ }
113
+ }
114
+ function pidAlive(pid) {
115
+ if (!Number.isInteger(pid) || pid <= 0)
116
+ return false;
117
+ try {
118
+ process.kill(pid, 0);
119
+ return true;
120
+ }
121
+ catch {
122
+ return false;
123
+ }
124
+ }
125
+ function commandHasArgs(pid, args) {
126
+ const result = spawnSync("ps", ["-ww", "-p", String(pid), "-o", "command="], { encoding: "utf8" });
127
+ if (result.status !== 0)
128
+ return false;
129
+ const command = result.stdout.trim();
130
+ return args.every((arg) => {
131
+ const escaped = arg.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
132
+ return new RegExp(`(?:^|\\s)${escaped}(?=\\s|$)`).test(command);
133
+ });
134
+ }
135
+ /** A PID or listening port can be reused. Check the process's launch arguments
136
+ * before adopting it or sending a signal, including instances from the launcher. */
137
+ function ownsChrome(pid, home, port) {
138
+ if (!pid || !pidAlive(pid))
139
+ return false;
140
+ return commandHasArgs(pid, identityArgs(home, port));
141
+ }
142
+ /** Our instance, but started without today's flags (an older CLI, an old
143
+ * launcher app, or a flag added since). It has to be relaunched: flags only
144
+ * apply when Chrome starts. */
145
+ function hasCurrentFlags(pid, home, port, env) {
146
+ return commandHasArgs(pid, launchArgs(home, port, env));
147
+ }
148
+ function extensionRecordingFile(home) {
149
+ return join(chromeForClipyDir(home), "extension-recording.json");
150
+ }
151
+ /** Notes that the Clipy extension is recording in Chrome for Clipy, until the
152
+ * recording's own deadline, so a relaunch for flags cannot kill it. */
153
+ export function markExtensionRecording(home, recording) {
154
+ if (!recording) {
155
+ rmSync(extensionRecordingFile(home), { force: true });
156
+ return;
157
+ }
158
+ mkdirSync(chromeForClipyDir(home), { recursive: true });
159
+ writeFileSync(extensionRecordingFile(home), JSON.stringify(recording), { mode: 0o600 });
160
+ }
161
+ function recordingInProgress(home) {
162
+ const lock = join(chromeForClipyDir(home), "capture.lock");
163
+ if (existsSync(lock)) {
164
+ const owner = Number(readFileSync(lock, "utf8"));
165
+ if (Number.isInteger(owner) && owner > 0 && pidAlive(owner))
166
+ return "a chrome-for-clipy session is recording";
167
+ }
168
+ try {
169
+ const marker = JSON.parse(readFileSync(extensionRecordingFile(home), "utf8"));
170
+ // Ten minutes of grace past the auto-stop covers the upload.
171
+ if (typeof marker.untilEpochMs === "number" && marker.untilEpochMs + 600_000 > Date.now()) {
172
+ return "the Clipy extension is recording";
173
+ }
174
+ }
175
+ catch {
176
+ // no marker
177
+ }
178
+ return null;
179
+ }
180
+ async function waitForExit(pid, timeoutMs) {
181
+ const deadline = Date.now() + timeoutMs;
182
+ while (pidAlive(pid)) {
183
+ if (Date.now() >= deadline)
184
+ return false;
185
+ await new Promise((r) => setTimeout(r, 200));
186
+ }
187
+ return true;
188
+ }
189
+ async function relaunchForFlags(pid, home) {
190
+ const busy = recordingInProgress(home);
191
+ if (busy) {
192
+ return `Chrome for Clipy was started without the current launch flags, but ${busy}. Finish that recording, then run \`clipy chrome stop\` and try again`;
193
+ }
194
+ try {
195
+ process.kill(pid, "SIGTERM");
196
+ }
197
+ catch {
198
+ return null;
199
+ }
200
+ if (await waitForExit(pid, 10_000))
201
+ return null;
202
+ try {
203
+ process.kill(pid, "SIGKILL");
204
+ }
205
+ catch {
206
+ return null;
207
+ }
208
+ return (await waitForExit(pid, 5_000)) ? null : `Chrome for Clipy (pid ${pid}) did not exit for a relaunch`;
209
+ }
210
+ async function cdpReachable(port) {
211
+ try {
212
+ const res = await fetch(`http://127.0.0.1:${port}/json/version`, { signal: AbortSignal.timeout(2000) });
213
+ if (!res.ok)
214
+ return { ok: false };
215
+ const body = (await res.json());
216
+ return { ok: true, browser: body.Browser };
217
+ }
218
+ catch {
219
+ return { ok: false };
220
+ }
221
+ }
222
+ export async function chromeStatus(home, platform) {
223
+ const state = readState(home);
224
+ const port = state?.port ?? DEFAULT_CDP_PORT;
225
+ const cdp = await cdpReachable(port);
226
+ // The pid can go stale after a relaunch. Verify the current listener before
227
+ // exposing its endpoint, even when the saved browser process is still alive.
228
+ const candidate = findListenerPid(port);
229
+ const listenerOwned = ownsChrome(candidate, home, port);
230
+ const pid = listenerOwned ? candidate
231
+ : state && ownsChrome(state.pid, home, port) ? state.pid : null;
232
+ const running = pid !== null;
233
+ return {
234
+ running,
235
+ pid,
236
+ port: running ? port : null,
237
+ cdpUrl: listenerOwned && cdp.ok ? `http://127.0.0.1:${port}` : null,
238
+ cdpReady: listenerOwned && cdp.ok,
239
+ browser: listenerOwned && cdp.ok ? cdp.browser ?? null : null,
240
+ profileDir: profileDir(home),
241
+ appInstalled: platform === "darwin" ? existsSync(appBundlePath(home)) : false,
242
+ };
243
+ }
244
+ /** The pid actually listening on the CDP port, for instances we did not spawn
245
+ * (the .app launcher, a profile-picker relaunch) whose pid our state file
246
+ * cannot know. */
247
+ function findListenerPid(port) {
248
+ try {
249
+ const out = spawnSync("lsof", ["-ti", `tcp:${port}`, "-sTCP:LISTEN"], { encoding: "utf8" });
250
+ const pid = Number.parseInt(out.stdout.trim().split("\n")[0] ?? "", 10);
251
+ return Number.isInteger(pid) && pid > 0 ? pid : null;
252
+ }
253
+ catch {
254
+ return null;
255
+ }
256
+ }
257
+ export async function startChrome(home, env, platform, port) {
258
+ if (env.CLIPY_DISABLE_CDP === "1")
259
+ return { ok: false, error: "Chrome for Clipy requires CDP, but CLIPY_DISABLE_CDP=1" };
260
+ const existing = readState(home);
261
+ if (existing && ownsChrome(existing.pid, home, existing.port)) {
262
+ if (!ownsChrome(findListenerPid(existing.port), home, existing.port)) {
263
+ return { ok: false, error: `CDP port ${existing.port} is not owned by Chrome for Clipy` };
264
+ }
265
+ if (hasCurrentFlags(existing.pid, home, existing.port, env)) {
266
+ return (await cdpReachable(existing.port)).ok
267
+ ? { ok: true, state: existing }
268
+ : { ok: false, error: `Chrome is running but CDP on port ${existing.port} is not responding` };
269
+ }
270
+ const failed = await relaunchForFlags(existing.pid, home);
271
+ if (failed)
272
+ return { ok: false, error: failed };
273
+ }
274
+ else {
275
+ // A live instance we did not spawn may already own the port (launched from
276
+ // the .app, or Chrome relaunched itself and our pid went stale). Spawning a
277
+ // duplicate into the same profile races the single-instance handoff: the
278
+ // connect that follows can land on the dying duplicate. Adopt instead.
279
+ const listener = findListenerPid(port);
280
+ const cdp = await cdpReachable(port);
281
+ if (cdp.ok || listener) {
282
+ if (!ownsChrome(listener, home, port)) {
283
+ return { ok: false, error: `Port ${port} is in use by a process not owned by Chrome for Clipy` };
284
+ }
285
+ if (hasCurrentFlags(listener, home, port, env)) {
286
+ if (!cdp.ok) {
287
+ return { ok: false, error: `Chrome is running but CDP on port ${port} is not responding` };
288
+ }
289
+ const state = {
290
+ pid: listener,
291
+ port,
292
+ startedAt: existing?.startedAt ?? new Date().toISOString(),
293
+ binary: existing?.binary ?? resolveChromeBinary(env, platform, home) ?? "",
294
+ };
295
+ mkdirSync(chromeForClipyDir(home), { recursive: true });
296
+ writeFileSync(stateFile(home), `${JSON.stringify(state, null, 2)}\n`);
297
+ return { ok: true, state };
298
+ }
299
+ const failed = await relaunchForFlags(listener, home);
300
+ if (failed)
301
+ return { ok: false, error: failed };
302
+ }
303
+ }
304
+ const binary = resolveChromeBinary(env, platform, home);
305
+ if (!binary) {
306
+ return { ok: false, error: "Google Chrome not found; install it or set CLIPY_CHROME_BINARY" };
307
+ }
308
+ mkdirSync(profileDir(home), { recursive: true });
309
+ seedProfileName(home);
310
+ const child = spawn(binary, launchArgs(home, port, env), {
311
+ detached: true,
312
+ stdio: "ignore",
313
+ });
314
+ const spawnError = await new Promise((resolve) => {
315
+ child.once("error", resolve);
316
+ child.once("spawn", () => resolve(null));
317
+ });
318
+ if (spawnError)
319
+ return { ok: false, error: `Chrome failed to spawn: ${spawnError.message}` };
320
+ child.unref();
321
+ if (typeof child.pid !== "number") {
322
+ return { ok: false, error: "Chrome failed to spawn" };
323
+ }
324
+ const state = {
325
+ pid: child.pid,
326
+ port,
327
+ startedAt: new Date().toISOString(),
328
+ binary,
329
+ };
330
+ writeFileSync(stateFile(home), `${JSON.stringify(state, null, 2)}\n`);
331
+ // CDP takes a moment; callers that need it poll. We wait briefly so `start`
332
+ // failing to boot is reported here rather than on the caller's first request.
333
+ for (let i = 0; i < 20; i++) {
334
+ if ((await cdpReachable(port)).ok) {
335
+ const listenerPid = findListenerPid(port);
336
+ if (!ownsChrome(listenerPid, home, port)) {
337
+ return { ok: false, error: `CDP port ${port} is not owned by Chrome for Clipy` };
338
+ }
339
+ state.pid = listenerPid;
340
+ writeFileSync(stateFile(home), `${JSON.stringify(state, null, 2)}\n`);
341
+ return { ok: true, state };
342
+ }
343
+ await new Promise((r) => setTimeout(r, 500));
344
+ }
345
+ return { ok: false, error: `Chrome started (pid ${child.pid}) but CDP on port ${port} did not come up within 10s` };
346
+ }
347
+ export function stopChrome(home) {
348
+ const state = readState(home);
349
+ const port = state?.port ?? DEFAULT_CDP_PORT;
350
+ const listener = findListenerPid(port);
351
+ const pid = state && ownsChrome(state.pid, home, port) ? state.pid
352
+ : ownsChrome(listener, home, port) ? listener : null;
353
+ if (!pid) {
354
+ rmSync(stateFile(home), { force: true });
355
+ return { ok: true, stopped: false };
356
+ }
357
+ try {
358
+ process.kill(pid, "SIGTERM");
359
+ rmSync(stateFile(home), { force: true });
360
+ return { ok: true, stopped: true };
361
+ }
362
+ catch (error) {
363
+ return { ok: false, stopped: false, error: error instanceof Error ? error.message : String(error) };
364
+ }
365
+ }
366
+ const RECORDER_HTML = `<!doctype html>
367
+ <title>Clipy session recorder</title>
368
+ <button id="go" style="font-size:32px">start capture</button>
369
+ <script>
370
+ let rec = null, stream = null, starting = false;
371
+ window.startCapture = async () => {
372
+ if (starting) return;
373
+ starting = true;
374
+ stream = await navigator.mediaDevices.getDisplayMedia({ video: { frameRate: 15 }, audio: true });
375
+ rec = new MediaRecorder(stream, { mimeType: "video/webm;codecs=vp8,opus" });
376
+ // Deliver chunks strictly in order: MediaRecorder events are ordered, but the
377
+ // async exposed-function calls are not, so chain them.
378
+ let sending = Promise.resolve();
379
+ rec.ondataavailable = (e) => {
380
+ if (!e.data.size) return;
381
+ const blob = e.data;
382
+ sending = sending.then(async () => {
383
+ const buf = new Uint8Array(await blob.arrayBuffer());
384
+ for (let i = 0; i < buf.length; i += 1 << 18) {
385
+ let s = "";
386
+ const slice = buf.subarray(i, i + (1 << 18));
387
+ for (let j = 0; j < slice.length; j += 0x8000)
388
+ s += String.fromCharCode.apply(null, slice.subarray(j, j + 0x8000));
389
+ await window.clipyChunk(btoa(s));
390
+ }
391
+ });
392
+ };
393
+ rec.onstop = () => {
394
+ sending.then(() => {
395
+ stream.getTracks().forEach((t) => t.stop());
396
+ return window.clipyCaptureDone();
397
+ }, (error) => {
398
+ stream.getTracks().forEach((t) => t.stop());
399
+ return window.clipyCaptureDone(String(error));
400
+ });
401
+ };
402
+ rec.start(2000);
403
+ rec.onerror = (event) => window.clipyCaptureDone(event.error?.message || "MediaRecorder failed");
404
+ return { video: stream.getVideoTracks().length, audio: stream.getAudioTracks().length };
405
+ };
406
+ window.stopCapture = () => { if (rec && rec.state !== "inactive") rec.stop(); else window.clipyCaptureDone(); };
407
+ document.getElementById("go").addEventListener("click", async () => {
408
+ try {
409
+ document.body.dataset.result = JSON.stringify(await window.startCapture());
410
+ } catch (e) {
411
+ document.body.dataset.result = JSON.stringify({ error: e.name + ": " + e.message });
412
+ }
413
+ });
414
+ </script>
415
+ `;
416
+ export async function startChromeForClipyCapture(chromium, opts) {
417
+ const started = await startChrome(opts.home, opts.env, opts.platform, opts.port);
418
+ if (!started.ok)
419
+ throw new Error(`Chrome for Clipy is not available: ${started.error}`);
420
+ opts.log(`chrome ready (pid ${started.state.pid || "adopted"}); connecting CDP`);
421
+ const browser = await chromium.connectOverCDP(`http://127.0.0.1:${started.state.port}`);
422
+ opts.log("CDP connected");
423
+ const context = browser.contexts()[0];
424
+ if (!context) {
425
+ await browser.close().catch(() => { });
426
+ throw new Error("Chrome for Clipy has no browser context to attach to");
427
+ }
428
+ let target;
429
+ let recorder;
430
+ const captureLock = join(chromeForClipyDir(opts.home), "capture.lock");
431
+ let locked = false;
432
+ const cleanup = async () => {
433
+ if (target)
434
+ await target.close().catch(() => { });
435
+ if (recorder)
436
+ await recorder.close().catch(() => { });
437
+ await browser.close().catch(() => { });
438
+ if (locked) {
439
+ rmSync(captureLock, { force: true });
440
+ locked = false;
441
+ }
442
+ };
443
+ try {
444
+ if (existsSync(captureLock)) {
445
+ const owner = Number(readFileSync(captureLock, "utf8"));
446
+ if (Number.isInteger(owner) && owner > 0 && !pidAlive(owner))
447
+ rmSync(captureLock, { force: true });
448
+ }
449
+ try {
450
+ writeFileSync(captureLock, String(process.pid), { flag: "wx", mode: 0o600 });
451
+ locked = true;
452
+ }
453
+ catch {
454
+ throw new Error("Chrome for Clipy already has an active capture; stop or abort it first");
455
+ }
456
+ // The launch flag selects by title across the entire browser. A leftover
457
+ // or unrelated marker-titled tab makes that selection ambiguous. Leave it
458
+ // alone and refuse capture rather than risk recording the wrong tab.
459
+ for (const existingPage of context.pages()) {
460
+ if ((await existingPage.title()).includes(TAB_CAPTURE_TITLE_MARKER)) {
461
+ throw new Error(`Another tab contains the capture marker "${TAB_CAPTURE_TITLE_MARKER}"; rename or close it before recording`);
462
+ }
463
+ }
464
+ // Navigate the target FIRST: an about:blank tab does not register a title
465
+ // with the capture source list, so the marker would match nothing and
466
+ // getDisplayMedia rejects (InvalidStateError) instead of auto-selecting.
467
+ // The marker title is pinned against SPA title rewrites only until capture
468
+ // selects the tab; afterwards the capture follows the tab regardless.
469
+ target = await context.newPage();
470
+ try {
471
+ await target.goto(opts.targetUrl, { waitUntil: "load", timeout: 30_000 });
472
+ }
473
+ catch {
474
+ opts.log("target page load timed out; capturing its current state anyway");
475
+ }
476
+ opts.log("target page loaded; starting capture");
477
+ const marker = `${TAB_CAPTURE_TITLE_MARKER} session target`;
478
+ await target.evaluate(`(() => {
479
+ let original = document.title;
480
+ document.title = ${JSON.stringify(marker)};
481
+ const el = document.querySelector("title");
482
+ const observer = new MutationObserver(() => {
483
+ if (document.title !== ${JSON.stringify(marker)}) {
484
+ original = document.title;
485
+ document.title = ${JSON.stringify(marker)};
486
+ }
487
+ });
488
+ if (el) observer.observe(el, { childList: true });
489
+ globalThis.__clipyRestoreCaptureTitle = () => {
490
+ observer.disconnect();
491
+ if (document.title === ${JSON.stringify(marker)}) document.title = original;
492
+ delete globalThis.__clipyRestoreCaptureTitle;
493
+ };
494
+ })()`);
495
+ const videoPath = join(opts.tmpDir, "capture.webm");
496
+ mkdirSync(opts.tmpDir, { recursive: true });
497
+ writeFileSync(videoPath, Buffer.alloc(0));
498
+ let captureDone;
499
+ const captureFinished = new Promise((r) => (captureDone = r));
500
+ recorder = await context.newPage();
501
+ await recorder.exposeFunction("clipyChunk", (b64) => {
502
+ appendFileSync(videoPath, Buffer.from(b64, "base64"));
503
+ });
504
+ await recorder.exposeFunction("clipyCaptureDone", (error) => captureDone(error));
505
+ const recorderHtml = join(opts.tmpDir, "recorder.html");
506
+ writeFileSync(recorderHtml, RECORDER_HTML);
507
+ await recorder.goto(pathToFileURL(recorderHtml).href);
508
+ // getDisplayMedia requires the calling document to be FOCUSED, and this
509
+ // Chrome window is usually in the OS background while an agent drives it.
510
+ // Playwright emulates focus for browsers it launches but not over CDP
511
+ // attach, so enable it explicitly. Without this the capture rejects with
512
+ // InvalidStateError whenever the window isn't frontmost.
513
+ try {
514
+ const cdp = await context.newCDPSession(recorder);
515
+ await cdp.send("Emulation.setFocusEmulationEnabled", { enabled: true });
516
+ }
517
+ catch (error) {
518
+ opts.log(`focus emulation unavailable (${error instanceof Error ? error.message : String(error)}); capture may require the window to be frontmost`);
519
+ }
520
+ // The trusted click is the user activation; first attempts can hang without
521
+ // resolving OR rejecting (observed on Chrome 152), hence the retry loop.
522
+ let resultRaw = null;
523
+ for (let attempt = 1; attempt <= 3 && !resultRaw; attempt++) {
524
+ if (attempt > 1)
525
+ await recorder.goto(pathToFileURL(recorderHtml).href);
526
+ await recorder.bringToFront();
527
+ await recorder.click("#go", { timeout: 5000 });
528
+ try {
529
+ // Plain EXPRESSION strings: an arrow-function string is itself a truthy
530
+ // expression to Playwright, which made this resolve instantly and the
531
+ // retry loop fire concurrent getDisplayMedia calls (→ InvalidStateError).
532
+ await recorder.waitForFunction("document.body.dataset.result", undefined, { timeout: 15000 });
533
+ resultRaw = (await recorder.evaluate("document.body.dataset.result")) ?? null;
534
+ }
535
+ catch {
536
+ opts.log(`capture attempt ${attempt} did not resolve within 15s; retrying`);
537
+ }
538
+ }
539
+ if (!resultRaw) {
540
+ throw new Error("getDisplayMedia never resolved. Is this Chrome running with the Chrome for Clipy launch flags?");
541
+ }
542
+ const tracks = JSON.parse(resultRaw);
543
+ if (tracks.error || !tracks.video) {
544
+ throw new Error(`tab capture failed: ${tracks.error ?? "no video track"}`);
545
+ }
546
+ await target.evaluate("globalThis.__clipyRestoreCaptureTitle?.()");
547
+ opts.log(`tab capture live (${tracks.video} video, ${tracks.audio ?? 0} audio track${tracks.audio === 1 ? "" : "s"})`);
548
+ const recorderPage = recorder;
549
+ const finish = async (keep) => {
550
+ let timer;
551
+ try {
552
+ if (keep) {
553
+ await recorderPage.evaluate("window.stopCapture()");
554
+ const error = await Promise.race([
555
+ captureFinished,
556
+ new Promise((_, reject) => {
557
+ timer = setTimeout(() => reject(new Error("Capture did not finish flushing within 15s")), 15_000);
558
+ }),
559
+ ]);
560
+ if (error)
561
+ throw new Error(`Capture failed: ${error}`);
562
+ }
563
+ return videoPath;
564
+ }
565
+ finally {
566
+ if (timer)
567
+ clearTimeout(timer);
568
+ await cleanup();
569
+ if (!keep)
570
+ rmSync(videoPath, { force: true });
571
+ }
572
+ };
573
+ return {
574
+ browser,
575
+ page: target,
576
+ stop: () => finish(true),
577
+ discard: async () => {
578
+ await finish(false);
579
+ },
580
+ };
581
+ }
582
+ catch (error) {
583
+ await cleanup();
584
+ throw error;
585
+ }
586
+ }
587
+ // ---------------------------------------------------------------------------
588
+ // macOS launcher bundle: "Chrome for Clipy.app"
589
+ // ---------------------------------------------------------------------------
590
+ export function appBundlePath(home) {
591
+ return join(home, "Applications", `${APP_NAME}.app`);
592
+ }
593
+ /**
594
+ * Install "Chrome for Clipy.app": a small launcher bundle carrying the name,
595
+ * the icon, and the baked-in launch flags. It gives the automation browser a
596
+ * saved, named identity in Finder/Spotlight/login items; while RUNNING, the
597
+ * Dock still shows Google Chrome, because macOS attributes a process to the
598
+ * bundle that owns its executable.
599
+ *
600
+ * A full FORK (copy Chrome.app, rename, re-icon, ad-hoc re-sign) was built
601
+ * and rejected on 2026-09-02: changing the bundle identifier and re-signing
602
+ * breaks Chrome's helper processes (pages stop loading and CDP wedges),
603
+ * even with entitlements preserved. Branded Chrome does not tolerate being
604
+ * forked. If full Dock branding becomes a requirement, base the fork on
605
+ * "Google Chrome for Testing" (unbranded, automation-tolerant, but ships
606
+ * without the proprietary codecs many sites need) rather than retrying this.
607
+ */
608
+ export function installApp(home, env, platform, port) {
609
+ if (platform !== "darwin") {
610
+ return { ok: false, error: "the launcher app is macOS-only; use `clipy chrome start` elsewhere" };
611
+ }
612
+ const binary = resolveChromeBinary(env, platform, home);
613
+ if (!binary) {
614
+ return { ok: false, error: "Google Chrome not found; install it or set CLIPY_CHROME_BINARY" };
615
+ }
616
+ const bundle = appBundlePath(home);
617
+ // A previous install may be the abandoned 1.3GB fork, so replace it wholesale.
618
+ rmSync(bundle, { recursive: true, force: true });
619
+ const macos = join(bundle, "Contents", "MacOS");
620
+ mkdirSync(macos, { recursive: true });
621
+ // The Chrome-roundel-with-Clipy-hub icon ships in the package's assets/.
622
+ // Best-effort: a missing asset (source checkout without the file) still
623
+ // produces a working, if blank-iconed, launcher.
624
+ let hasIcon = false;
625
+ try {
626
+ const iconSrc = join(dirname(fileURLToPath(import.meta.url)), "..", "assets", "chrome-for-clipy.icns");
627
+ if (existsSync(iconSrc)) {
628
+ const resources = join(bundle, "Contents", "Resources");
629
+ mkdirSync(resources, { recursive: true });
630
+ copyFileSync(iconSrc, join(resources, "chrome-for-clipy.icns"));
631
+ hasIcon = true;
632
+ }
633
+ }
634
+ catch {
635
+ // icon is cosmetic
636
+ }
637
+ const args = launchArgs(home, port, env)
638
+ .map((a) => `'${a.replace(/'/g, `'\\''`)}'`)
639
+ .join(" \\\n ");
640
+ writeFileSync(join(macos, "chrome-for-clipy"), `#!/bin/sh\nexec '${binary.replace(/'/g, `'\\''`)}' \\\n ${args}\n`, { mode: 0o755 });
641
+ writeFileSync(join(bundle, "Contents", "Info.plist"), `<?xml version="1.0" encoding="UTF-8"?>
642
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
643
+ <plist version="1.0">
644
+ <dict>
645
+ <key>CFBundleName</key><string>${APP_NAME}</string>
646
+ <key>CFBundleDisplayName</key><string>${APP_NAME}</string>
647
+ <key>CFBundleIdentifier</key><string>online.clipy.chrome-for-clipy</string>
648
+ <key>CFBundleVersion</key><string>1.0</string>
649
+ <key>CFBundleShortVersionString</key><string>1.0</string>
650
+ <key>CFBundlePackageType</key><string>APPL</string>
651
+ <key>CFBundleExecutable</key><string>chrome-for-clipy</string>${hasIcon ? "\n <key>CFBundleIconFile</key><string>chrome-for-clipy</string>" : ""}
652
+ </dict>
653
+ </plist>
654
+ `);
655
+ return { ok: true, path: bundle };
656
+ }