@clipy/cli 0.15.1 → 0.16.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.
@@ -38,6 +38,7 @@ import { spawn, spawnSync } from "node:child_process";
38
38
  import { appendFileSync, copyFileSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
39
39
  import { dirname, join } from "node:path";
40
40
  import { fileURLToPath, pathToFileURL } from "node:url";
41
+ import { listenerPid, processArgs, processExists, terminateProcess } from "./processProbe.js";
41
42
  export const DEFAULT_CDP_PORT = 9333;
42
43
  /** Retitle a tab to start with this and the auto-select flag captures it.
43
44
  * Deliberately free of regex metacharacters: Chrome may treat the flag value
@@ -71,8 +72,51 @@ export function resolveChromeBinary(env, platform, home) {
71
72
  return existsSync(MACOS_CHROME) ? MACOS_CHROME : null;
72
73
  if (platform === "linux")
73
74
  return LINUX_CHROME_CANDIDATES.find((p) => existsSync(p)) ?? null;
75
+ if (platform === "win32")
76
+ return windowsChromeCandidates(env, platform).find((p) => existsSync(p)) ?? null;
74
77
  return null;
75
78
  }
79
+ /** Windows env names are case-insensitive, but a copied env object (`{...process.env}`) is not. */
80
+ function envValue(env, name) {
81
+ const lower = name.toLowerCase();
82
+ for (const [key, value] of Object.entries(env)) {
83
+ if (key.toLowerCase() === lower && value)
84
+ return value;
85
+ }
86
+ return undefined;
87
+ }
88
+ /** System-wide installs, then the per-user install, then whatever the
89
+ * installer registered under App Paths (covers a non-default install dir). */
90
+ export function windowsChromeCandidates(env, platform = "win32") {
91
+ const suffix = join("Google", "Chrome", "Application", "chrome.exe");
92
+ const out = [];
93
+ for (const root of ["ProgramFiles", "ProgramFiles(x86)", "ProgramW6432", "LOCALAPPDATA"]) {
94
+ const dir = envValue(env, root);
95
+ if (dir)
96
+ out.push(join(dir, suffix));
97
+ }
98
+ // The registry is only readable on a real Windows host.
99
+ if (platform === "win32" && process.platform === "win32") {
100
+ for (const hive of ["HKCU", "HKLM"]) {
101
+ const registered = readAppPath(`${hive}\\SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\App Paths\\chrome.exe`, env);
102
+ if (registered)
103
+ out.push(registered);
104
+ }
105
+ }
106
+ return [...new Set(out)];
107
+ }
108
+ function readAppPath(key, env) {
109
+ const result = spawnSync("reg", ["query", key, "/ve"], { encoding: "utf8", timeout: 5000, windowsHide: true });
110
+ if (result.error || result.status !== 0)
111
+ return null;
112
+ // " (Default) REG_SZ C:\...\chrome.exe". The value name is localized
113
+ // ("(Standard)", …), so anchor on the type token instead.
114
+ const match = /\bREG_(EXPAND_)?SZ\s+(.+?)\s*$/m.exec(result.stdout ?? "");
115
+ if (!match?.[2])
116
+ return null;
117
+ const value = match[2].replace(/^"(.*)"$/, "$1");
118
+ return match[1] ? value.replace(/%([^%]+)%/g, (whole, name) => envValue(env, name) ?? whole) : value;
119
+ }
76
120
  /** What makes a process OUR instance: the dedicated profile on our port. */
77
121
  function identityArgs(home, port) {
78
122
  return [`--user-data-dir=${profileDir(home)}`, `--remote-debugging-port=${port}`];
@@ -103,7 +147,9 @@ function seedProfileName(home) {
103
147
  export function readState(home) {
104
148
  try {
105
149
  const parsed = JSON.parse(readFileSync(stateFile(home), "utf8"));
106
- return Number.isInteger(parsed.pid) && parsed.pid > 0 &&
150
+ // pid 0: launched in the background, pid not known until CDP answers. The
151
+ // port is what matters then; status and stop find the listener on it.
152
+ return Number.isInteger(parsed.pid) && parsed.pid >= 0 &&
107
153
  Number.isInteger(parsed.port) && parsed.port > 0 && parsed.port <= 65535 &&
108
154
  typeof parsed.binary === "string" ? parsed : null;
109
155
  }
@@ -111,39 +157,46 @@ export function readState(home) {
111
157
  return null;
112
158
  }
113
159
  }
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;
160
+ /** The host cannot answer an ownership question (a probe tool is missing or
161
+ * failed). Surfaced as an explicit error: never guessed as "ours", which would
162
+ * let a reused PID or a foreign debugging port be adopted or signalled, and
163
+ * never as "not ours", which is what made every Windows start fail with a
164
+ * misleading "not owned" error. */
165
+ export class OwnershipUnverifiableError extends Error {
166
+ }
167
+ function probed(result, what) {
168
+ if (!result.supported) {
169
+ throw new OwnershipUnverifiableError(`Chrome for Clipy cannot verify ${what} on ${process.platform}: ${result.reason}`);
123
170
  }
171
+ return result.value;
124
172
  }
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
- });
173
+ /** The pid actually listening on the CDP port, for instances we did not spawn
174
+ * (the .app launcher, a profile-picker relaunch) whose pid our state file
175
+ * cannot know. */
176
+ function findListenerPid(port) {
177
+ return probed(listenerPid(port), `which process listens on port ${port}`);
134
178
  }
135
179
  /** 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. */
180
+ * before adopting it or sending a signal, including instances from the launcher.
181
+ * Returns the process's argument matcher when it is ours, so a follow-up flag
182
+ * check does not re-read the command line. */
183
+ function ownedInstance(pid, home, port) {
184
+ if (!pid || !processExists(pid))
185
+ return null;
186
+ const matcher = probed(processArgs(pid), `the launch arguments of pid ${pid}`);
187
+ return matcher && matcher(identityArgs(home, port)) ? matcher : null;
188
+ }
137
189
  function ownsChrome(pid, home, port) {
138
- if (!pid || !pidAlive(pid))
139
- return false;
140
- return commandHasArgs(pid, identityArgs(home, port));
190
+ return ownedInstance(pid, home, port) !== null;
141
191
  }
142
192
  /** Our instance, but started without today's flags (an older CLI, an old
143
193
  * launcher app, or a flag added since). It has to be relaunched: flags only
144
194
  * apply when Chrome starts. */
145
- function hasCurrentFlags(pid, home, port, env) {
146
- return commandHasArgs(pid, launchArgs(home, port, env));
195
+ function hasCurrentFlags(instance, home, port, env) {
196
+ return instance(launchArgs(home, port, env));
197
+ }
198
+ function errorMessage(error) {
199
+ return error instanceof Error ? error.message : String(error);
147
200
  }
148
201
  function extensionRecordingFile(home) {
149
202
  return join(chromeForClipyDir(home), "extension-recording.json");
@@ -162,7 +215,7 @@ function recordingInProgress(home) {
162
215
  const lock = join(chromeForClipyDir(home), "capture.lock");
163
216
  if (existsSync(lock)) {
164
217
  const owner = Number(readFileSync(lock, "utf8"));
165
- if (Number.isInteger(owner) && owner > 0 && pidAlive(owner))
218
+ if (Number.isInteger(owner) && owner > 0 && processExists(owner))
166
219
  return "a chrome-for-clipy session is recording";
167
220
  }
168
221
  try {
@@ -179,7 +232,7 @@ function recordingInProgress(home) {
179
232
  }
180
233
  async function waitForExit(pid, timeoutMs) {
181
234
  const deadline = Date.now() + timeoutMs;
182
- while (pidAlive(pid)) {
235
+ while (processExists(pid)) {
183
236
  if (Date.now() >= deadline)
184
237
  return false;
185
238
  await new Promise((r) => setTimeout(r, 200));
@@ -191,21 +244,25 @@ async function relaunchForFlags(pid, home) {
191
244
  if (busy) {
192
245
  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
246
  }
247
+ return (await stopProcess(pid)) ? null : `Chrome for Clipy (pid ${pid}) did not exit for a relaunch`;
248
+ }
249
+ /** Graceful stop, escalating to a kill after 10s. True once the pid is gone. */
250
+ async function stopProcess(pid) {
194
251
  try {
195
- process.kill(pid, "SIGTERM");
252
+ terminateProcess(pid, false);
196
253
  }
197
254
  catch {
198
- return null;
255
+ return !processExists(pid);
199
256
  }
200
257
  if (await waitForExit(pid, 10_000))
201
- return null;
258
+ return true;
202
259
  try {
203
- process.kill(pid, "SIGKILL");
260
+ terminateProcess(pid, true);
204
261
  }
205
262
  catch {
206
- return null;
263
+ return !processExists(pid);
207
264
  }
208
- return (await waitForExit(pid, 5_000)) ? null : `Chrome for Clipy (pid ${pid}) did not exit for a relaunch`;
265
+ return waitForExit(pid, 5_000);
209
266
  }
210
267
  async function cdpReachable(port) {
211
268
  try {
@@ -223,49 +280,168 @@ export async function chromeStatus(home, platform) {
223
280
  const state = readState(home);
224
281
  const port = state?.port ?? DEFAULT_CDP_PORT;
225
282
  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,
283
+ const base = {
240
284
  profileDir: profileDir(home),
241
285
  appInstalled: platform === "darwin" ? existsSync(appBundlePath(home)) : false,
242
286
  };
287
+ try {
288
+ // The pid can go stale after a relaunch. Verify the current listener before
289
+ // exposing its endpoint, even when the saved browser process is still alive.
290
+ const candidate = findListenerPid(port);
291
+ const listenerOwned = ownsChrome(candidate, home, port);
292
+ const pid = listenerOwned ? candidate
293
+ : state && ownsChrome(state.pid, home, port) ? state.pid : null;
294
+ const running = pid !== null;
295
+ return {
296
+ running,
297
+ pid,
298
+ port: running ? port : null,
299
+ cdpUrl: listenerOwned && cdp.ok ? `http://127.0.0.1:${port}` : null,
300
+ cdpReady: listenerOwned && cdp.ok,
301
+ browser: listenerOwned && cdp.ok ? cdp.browser ?? null : null,
302
+ ...base,
303
+ };
304
+ }
305
+ catch (error) {
306
+ if (!(error instanceof OwnershipUnverifiableError))
307
+ throw error;
308
+ return { running: false, pid: null, port: null, cdpUrl: null, cdpReady: false, browser: null, ...base, error: error.message };
309
+ }
243
310
  }
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) {
311
+ /** Whether this host can run the ownership checks at all, for `clipy doctor`.
312
+ * Probes the listener table and this very process's command line, so a pass
313
+ * means both tools ran and parsed real output. */
314
+ export function ownershipProbeStatus() {
248
315
  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;
316
+ findListenerPid(DEFAULT_CDP_PORT);
317
+ const self = probed(processArgs(process.pid), "the launch arguments of this process");
318
+ if (!self)
319
+ return { ok: false, error: "this process's own command line is not readable" };
320
+ return { ok: true };
252
321
  }
253
- catch {
322
+ catch (error) {
323
+ return { ok: false, error: errorMessage(error) };
324
+ }
325
+ }
326
+ /** `/Applications/Google Chrome.app` for a binary inside an app bundle. */
327
+ function appBundleOf(binary) {
328
+ return /^(.+\.app)\/Contents\/MacOS\/[^/]+$/.exec(binary)?.[1] ?? null;
329
+ }
330
+ /** The pid of the frontmost app. `lsappinfo` answers in a few milliseconds,
331
+ * which matters: the guard below races Chrome's own activation. */
332
+ function frontmostPid() {
333
+ const asn = spawnSync("lsappinfo", ["front"], { encoding: "utf8" }).stdout?.trim();
334
+ if (!asn)
254
335
  return null;
336
+ const info = spawnSync("lsappinfo", ["info", "-only", "pid", asn], { encoding: "utf8" }).stdout ?? "";
337
+ const pid = Number(/"pid"=(\d+)/.exec(info)?.[1]);
338
+ return Number.isInteger(pid) && pid > 0 ? pid : null;
339
+ }
340
+ /** Activate an app by pid. By pid, not bundle id, because the app the user was
341
+ * in may itself be Google Chrome, which shares our instance's bundle id. */
342
+ function activatePid(pid) {
343
+ spawnSync("osascript", [
344
+ "-l", "JavaScript", "-e",
345
+ `ObjC.import('AppKit'); $.NSRunningApplication.runningApplicationWithProcessIdentifier(${pid}).activateWithOptions(0)`,
346
+ ], { stdio: "ignore", timeout: 2000 });
347
+ }
348
+ /** `open -g` asks macOS not to bring Chrome forward, but Chrome activates
349
+ * itself about half a second into startup anyway. While the launch settles,
350
+ * hand focus back to whatever the user was in whenever OUR instance takes it.
351
+ * The user switching apps themselves is left alone. */
352
+ function guardFocus(home, port) {
353
+ const previous = frontmostPid();
354
+ if (previous === null)
355
+ return () => { };
356
+ const timer = setInterval(() => {
357
+ const front = frontmostPid();
358
+ if (front === null || front === previous)
359
+ return;
360
+ let ours;
361
+ try {
362
+ ours = ownsChrome(front, home, port);
363
+ }
364
+ catch {
365
+ return; // unverifiable: leave focus alone rather than guess
366
+ }
367
+ if (ours)
368
+ activatePid(previous);
369
+ }, 50);
370
+ return () => clearInterval(timer);
371
+ }
372
+ /** Brings an already-running instance forward for `--foreground`, which
373
+ * otherwise only affects a fresh launch. macOS activates the app by pid; other
374
+ * platforms ask Chrome to activate a page target over CDP, which raises its
375
+ * window. Best effort: a running browser is still a successful start. */
376
+ async function bringToForeground(pid, port, platform) {
377
+ if (platform === "darwin") {
378
+ activatePid(pid);
379
+ return;
380
+ }
381
+ try {
382
+ const res = await fetch(`http://127.0.0.1:${port}/json/list`, { signal: AbortSignal.timeout(2000) });
383
+ const targets = (await res.json());
384
+ const page = targets.find((t) => t.type === "page" && t.id);
385
+ if (page?.id) {
386
+ await fetch(`http://127.0.0.1:${port}/json/activate/${encodeURIComponent(page.id)}`, {
387
+ signal: AbortSignal.timeout(2000),
388
+ });
389
+ }
390
+ }
391
+ catch {
392
+ // nothing to raise, or CDP refused; the instance is still usable
393
+ }
394
+ }
395
+ /** How long a background launch with no pid yet counts as still starting. */
396
+ const PENDING_LAUNCH_MS = 60_000;
397
+ function launchPending(state) {
398
+ return state.pid === 0 && Date.now() - Date.parse(state.startedAt) < PENDING_LAUNCH_MS;
399
+ }
400
+ /** How long `stop` waits for a still-starting background launch to open CDP. */
401
+ const PENDING_STOP_WAIT_MS = 10_000;
402
+ async function waitForOwnedListener(home, port, timeoutMs) {
403
+ const deadline = Date.now() + timeoutMs;
404
+ for (;;) {
405
+ const listener = findListenerPid(port);
406
+ if (ownsChrome(listener, home, port))
407
+ return listener;
408
+ if (Date.now() >= deadline)
409
+ return null;
410
+ await new Promise((r) => setTimeout(r, 500));
255
411
  }
256
412
  }
257
- export async function startChrome(home, env, platform, port) {
413
+ /** Chrome's self-activation was observed 0.4-0.5s after launch; keep guarding
414
+ * past CDP coming up so a late activation is still caught. */
415
+ const FOCUS_GUARD_MIN_MS = 3000;
416
+ export async function startChrome(home, env, platform, port, opts = {}) {
258
417
  if (env.CLIPY_DISABLE_CDP === "1")
259
418
  return { ok: false, error: "Chrome for Clipy requires CDP, but CLIPY_DISABLE_CDP=1" };
419
+ try {
420
+ return await startChromeVerified(home, env, platform, port, opts);
421
+ }
422
+ catch (error) {
423
+ if (error instanceof OwnershipUnverifiableError)
424
+ return { ok: false, error: error.message };
425
+ throw error;
426
+ }
427
+ }
428
+ async function startChromeVerified(home, env, platform, port, opts) {
260
429
  const existing = readState(home);
261
- if (existing && ownsChrome(existing.pid, home, existing.port)) {
262
- if (!ownsChrome(findListenerPid(existing.port), home, existing.port)) {
430
+ const existingInstance = existing ? ownedInstance(existing.pid, home, existing.port) : null;
431
+ if (existing && existingInstance) {
432
+ // No listener yet (still booting) is not a foreign owner; the CDP check
433
+ // below reports it as not responding. Our own pid needs no second read.
434
+ const listener = findListenerPid(existing.port);
435
+ if (listener !== null && listener !== existing.pid && !ownsChrome(listener, home, existing.port)) {
263
436
  return { ok: false, error: `CDP port ${existing.port} is not owned by Chrome for Clipy` };
264
437
  }
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` };
438
+ if (hasCurrentFlags(existingInstance, home, existing.port, env)) {
439
+ if (!(await cdpReachable(existing.port)).ok) {
440
+ return { ok: false, error: `Chrome is running but CDP on port ${existing.port} is not responding` };
441
+ }
442
+ if (opts.foreground)
443
+ await bringToForeground(existing.pid, existing.port, platform);
444
+ return { ok: true, state: existing };
269
445
  }
270
446
  const failed = await relaunchForFlags(existing.pid, home);
271
447
  if (failed)
@@ -279,10 +455,11 @@ export async function startChrome(home, env, platform, port) {
279
455
  const listener = findListenerPid(port);
280
456
  const cdp = await cdpReachable(port);
281
457
  if (cdp.ok || listener) {
282
- if (!ownsChrome(listener, home, port)) {
458
+ const listenerInstance = ownedInstance(listener, home, port);
459
+ if (!listener || !listenerInstance) {
283
460
  return { ok: false, error: `Port ${port} is in use by a process not owned by Chrome for Clipy` };
284
461
  }
285
- if (hasCurrentFlags(listener, home, port, env)) {
462
+ if (hasCurrentFlags(listenerInstance, home, port, env)) {
286
463
  if (!cdp.ok) {
287
464
  return { ok: false, error: `Chrome is running but CDP on port ${port} is not responding` };
288
465
  }
@@ -294,6 +471,8 @@ export async function startChrome(home, env, platform, port) {
294
471
  };
295
472
  mkdirSync(chromeForClipyDir(home), { recursive: true });
296
473
  writeFileSync(stateFile(home), `${JSON.stringify(state, null, 2)}\n`);
474
+ if (opts.foreground)
475
+ await bringToForeground(listener, port, platform);
297
476
  return { ok: true, state };
298
477
  }
299
478
  const failed = await relaunchForFlags(listener, home);
@@ -301,67 +480,163 @@ export async function startChrome(home, env, platform, port) {
301
480
  return { ok: false, error: failed };
302
481
  }
303
482
  }
483
+ // A background launch that has not answered yet: a second instance into the
484
+ // same profile would race the first one's single-instance handoff.
485
+ if (existing && launchPending(existing)) {
486
+ return { ok: false, error: `Chrome for Clipy is still starting on port ${existing.port}; try again in a moment` };
487
+ }
304
488
  const binary = resolveChromeBinary(env, platform, home);
305
489
  if (!binary) {
306
490
  return { ok: false, error: "Google Chrome not found; install it or set CLIPY_CHROME_BINARY" };
307
491
  }
308
492
  mkdirSync(profileDir(home), { recursive: true });
309
493
  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,
494
+ const state = { pid: 0, port, startedAt: new Date().toISOString(), binary };
495
+ // Spawning the binary directly always activates Chrome on macOS. LaunchServices
496
+ // with -g does not, and -n starts a new instance instead of handing the
497
+ // arguments to the user's own running Chrome. It leaves us no child pid; the
498
+ // pid comes from the CDP listener below, as it already did for adoption.
499
+ const bundle = platform === "darwin" && !opts.foreground ? appBundleOf(binary) : null;
500
+ const launchedAt = Date.now();
501
+ let stopGuard = () => { };
502
+ // Only a browser we hold a child handle for can be stopped on a failed start:
503
+ // the handle, not a pid lookup, proves it is ours. An `open` launch has none.
504
+ let abandon = (error) => {
505
+ rmSync(stateFile(home), { force: true });
506
+ return { ok: false, error };
329
507
  };
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` };
508
+ if (bundle) {
509
+ stopGuard = guardFocus(home, port);
510
+ const opened = spawnSync("open", ["-g", "-n", "-a", bundle, "--args", ...launchArgs(home, port, env)], { encoding: "utf8" });
511
+ if (opened.status !== 0) {
512
+ stopGuard();
513
+ return { ok: false, error: `Chrome failed to launch: ${(opened.stderr || opened.error?.message || "open failed").trim()}` };
514
+ }
515
+ // Saved before CDP answers so a slow first boot on a non-default port stays
516
+ // discoverable by status and stop.
517
+ writeFileSync(stateFile(home), `${JSON.stringify(state, null, 2)}\n`);
518
+ }
519
+ else {
520
+ const child = spawn(binary, launchArgs(home, port, env), {
521
+ detached: true,
522
+ stdio: "ignore",
523
+ });
524
+ const spawnError = await new Promise((resolve) => {
525
+ child.once("error", resolve);
526
+ child.once("spawn", () => resolve(null));
527
+ });
528
+ if (spawnError)
529
+ return { ok: false, error: `Chrome failed to spawn: ${spawnError.message}` };
530
+ child.unref();
531
+ if (typeof child.pid !== "number") {
532
+ return { ok: false, error: "Chrome failed to spawn" };
533
+ }
534
+ const spawnedPid = child.pid;
535
+ state.pid = spawnedPid;
536
+ writeFileSync(stateFile(home), `${JSON.stringify(state, null, 2)}\n`);
537
+ // We launched this browser, so a start that fails after this point must not
538
+ // leave it running untracked (nothing else would ever stop it).
539
+ abandon = (error) => {
540
+ if (child.exitCode === null && child.signalCode === null && processExists(spawnedPid)) {
541
+ try {
542
+ terminateProcess(spawnedPid, true);
543
+ }
544
+ catch {
545
+ // already gone
546
+ }
338
547
  }
339
- state.pid = listenerPid;
340
- writeFileSync(stateFile(home), `${JSON.stringify(state, null, 2)}\n`);
341
- return { ok: true, state };
548
+ rmSync(stateFile(home), { force: true });
549
+ return { ok: false, error };
550
+ };
551
+ }
552
+ try {
553
+ // CDP takes a moment; callers that need it poll. We wait briefly so `start`
554
+ // failing to boot is reported here rather than on the caller's first request.
555
+ for (let i = 0; i < 20; i++) {
556
+ if ((await cdpReachable(port)).ok) {
557
+ let listenerPid;
558
+ try {
559
+ listenerPid = findListenerPid(port);
560
+ if (!ownsChrome(listenerPid, home, port)) {
561
+ return abandon(`CDP port ${port} is not owned by Chrome for Clipy`);
562
+ }
563
+ }
564
+ catch (error) {
565
+ if (error instanceof OwnershipUnverifiableError)
566
+ return abandon(error.message);
567
+ throw error;
568
+ }
569
+ state.pid = listenerPid;
570
+ writeFileSync(stateFile(home), `${JSON.stringify(state, null, 2)}\n`);
571
+ const settle = FOCUS_GUARD_MIN_MS - (Date.now() - launchedAt);
572
+ if (bundle && settle > 0)
573
+ await new Promise((r) => setTimeout(r, settle));
574
+ return { ok: true, state };
575
+ }
576
+ await new Promise((r) => setTimeout(r, 500));
342
577
  }
343
- await new Promise((r) => setTimeout(r, 500));
578
+ // Left running and tracked on purpose: a slow first boot (profile creation,
579
+ // an update) may still come up, and `clipy chrome stop` can verify and stop it.
580
+ return {
581
+ ok: false,
582
+ error: `Chrome started${state.pid ? ` (pid ${state.pid})` : ""} but CDP on port ${port} did not come up within 10s`,
583
+ };
584
+ }
585
+ finally {
586
+ stopGuard();
344
587
  }
345
- return { ok: false, error: `Chrome started (pid ${child.pid}) but CDP on port ${port} did not come up within 10s` };
346
588
  }
347
- export function stopChrome(home) {
589
+ export async function stopChrome(home) {
348
590
  const state = readState(home);
349
591
  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;
592
+ let pid;
593
+ try {
594
+ pid = state && ownsChrome(state.pid, home, port) ? state.pid : null;
595
+ if (!pid) {
596
+ const listener = findListenerPid(port);
597
+ pid = ownsChrome(listener, home, port) ? listener : null;
598
+ }
599
+ if (!pid && state && launchPending(state)) {
600
+ // A background launch that has not opened CDP yet. The state file is the
601
+ // only record of its port, so wait for it rather than forget it.
602
+ pid = await waitForOwnedListener(home, port, PENDING_STOP_WAIT_MS);
603
+ if (!pid) {
604
+ return {
605
+ ok: false,
606
+ stopped: false,
607
+ error: `Chrome for Clipy is still starting on port ${port}; run \`clipy chrome stop\` again in a moment`,
608
+ };
609
+ }
610
+ }
611
+ }
612
+ catch (error) {
613
+ // Unverifiable is not "not running": keep the state file so a later stop
614
+ // (with the probe fixed) still finds the browser.
615
+ if (error instanceof OwnershipUnverifiableError)
616
+ return { ok: false, stopped: false, error: error.message };
617
+ throw error;
618
+ }
353
619
  if (!pid) {
354
620
  rmSync(stateFile(home), { force: true });
355
621
  return { ok: true, stopped: false };
356
622
  }
357
- try {
358
- process.kill(pid, "SIGTERM");
623
+ if (process.platform !== "win32") {
624
+ // POSIX: SIGTERM is a clean Chrome shutdown; returning at once is the long-standing contract.
625
+ try {
626
+ terminateProcess(pid, false);
627
+ rmSync(stateFile(home), { force: true });
628
+ return { ok: true, stopped: true };
629
+ }
630
+ catch (error) {
631
+ return { ok: false, stopped: false, error: errorMessage(error) };
632
+ }
633
+ }
634
+ // Windows: WM_CLOSE is a request, so confirm the exit and escalate if ignored.
635
+ if (await stopProcess(pid)) {
359
636
  rmSync(stateFile(home), { force: true });
360
637
  return { ok: true, stopped: true };
361
638
  }
362
- catch (error) {
363
- return { ok: false, stopped: false, error: error instanceof Error ? error.message : String(error) };
364
- }
639
+ return { ok: false, stopped: false, error: `Chrome for Clipy (pid ${pid}) did not exit` };
365
640
  }
366
641
  const RECORDER_HTML = `<!doctype html>
367
642
  <title>Clipy session recorder</title>
@@ -413,6 +688,197 @@ const RECORDER_HTML = `<!doctype html>
413
688
  });
414
689
  </script>
415
690
  `;
691
+ /** Opens a tab without making Chrome the frontmost app. On macOS, Playwright's
692
+ * newPage(), bringToFront() and Target.activateTarget all activate Chrome
693
+ * (measured on Chrome 154); a background Target.createTarget does not. With
694
+ * `newWindow` the tab gets its own background window, where it is the active,
695
+ * visible tab without anything being activated. */
696
+ async function newBackgroundPage(browser, context, newWindow = false) {
697
+ const before = new Set(context.pages());
698
+ const cdp = await browser.newBrowserCDPSession();
699
+ let targetId;
700
+ try {
701
+ const created = (await cdp.send("Target.createTarget", { url: "about:blank", background: true, newWindow }));
702
+ targetId = created?.targetId;
703
+ }
704
+ finally {
705
+ await cdp.detach().catch(() => { });
706
+ }
707
+ if (!targetId)
708
+ throw new Error("Chrome for Clipy did not report the background tab it opened");
709
+ // Match by target id: an agent may open its own tab at the same moment, and
710
+ // "the first new page" would then be theirs.
711
+ const checked = new Set(before);
712
+ for (let i = 0; i < 100; i++) {
713
+ for (const page of context.pages()) {
714
+ if (checked.has(page))
715
+ continue;
716
+ checked.add(page);
717
+ if ((await pageTargetId(context, page)) === targetId)
718
+ return page;
719
+ }
720
+ await new Promise((r) => setTimeout(r, 50));
721
+ }
722
+ throw new Error("Chrome for Clipy did not open a background tab");
723
+ }
724
+ async function pageTargetId(context, page) {
725
+ try {
726
+ const session = await context.newCDPSession(page);
727
+ try {
728
+ const info = (await session.send("Target.getTargetInfo"));
729
+ return info?.targetInfo?.targetId ?? null;
730
+ }
731
+ finally {
732
+ await session.detach?.().catch(() => { });
733
+ }
734
+ }
735
+ catch {
736
+ return null; // closed while we looked
737
+ }
738
+ }
739
+ function guardTabFocus(chromePid, context, platform) {
740
+ if (platform !== "darwin" || chromePid <= 0)
741
+ return { ownTab: (create) => create(), stop: () => { } };
742
+ const guard = createTabStealGuard(chromePid, activatePid);
743
+ const stopWatching = watchFrontmost((pid) => guard.frontChanged(pid));
744
+ const tabs = trackAgentTabs(context, (at) => guard.tabOpened(at));
745
+ return {
746
+ ownTab: tabs.ownTab,
747
+ stop() {
748
+ tabs.stop();
749
+ stopWatching();
750
+ },
751
+ };
752
+ }
753
+ /** Calls `onAgentTab` with the creation time of each tab that appears in
754
+ * `context`, except the ones opened through `ownTab`. Uses Playwright's
755
+ * "page" event, which fires as the tab is created and well before Chrome
756
+ * activates (0.4-0.5s), so the time is the tab's own; contexts without
757
+ * events are polled. A page that appears while one of our own tabs is being
758
+ * opened is held back, with its time, until that tab is identified: ours is
759
+ * ignored, any other is the agent's. Exported for tests. */
760
+ export function trackAgentTabs(context, onAgentTab, intervalMs = 100) {
761
+ const seen = new Set(context.pages());
762
+ const ours = new Set();
763
+ const held = new Map();
764
+ let opening = 0;
765
+ const judge = (page, at) => {
766
+ if (seen.has(page))
767
+ return;
768
+ seen.add(page);
769
+ if (!ours.has(page))
770
+ onAgentTab(at);
771
+ };
772
+ const consider = (page) => {
773
+ if (seen.has(page) || held.has(page))
774
+ return;
775
+ if (opening > 0 && !ours.has(page))
776
+ held.set(page, Date.now());
777
+ else
778
+ judge(page, Date.now());
779
+ };
780
+ const events = typeof context.on === "function";
781
+ if (events)
782
+ context.on("page", consider);
783
+ const timer = events ? null : setInterval(() => context.pages().forEach(consider), intervalMs);
784
+ return {
785
+ async ownTab(create) {
786
+ opening++;
787
+ try {
788
+ const page = await create();
789
+ ours.add(page);
790
+ return page;
791
+ }
792
+ finally {
793
+ opening--;
794
+ if (opening === 0) {
795
+ const pending = [...held];
796
+ held.clear();
797
+ for (const [page, at] of pending)
798
+ judge(page, at);
799
+ }
800
+ }
801
+ },
802
+ stop() {
803
+ if (timer)
804
+ clearInterval(timer);
805
+ if (events)
806
+ context.off?.("page", consider);
807
+ },
808
+ };
809
+ }
810
+ /** Chrome activates within a few hundred ms of opening a tab. */
811
+ const TAB_STEAL_WINDOW_MS = 1000;
812
+ /** The decision part of the tab focus guard, fed by frontmost-app changes and
813
+ * agent tabs (with the time each tab was created) as they happen. Chrome
814
+ * coming forward after a tab was created and within the steal window is
815
+ * undone, back to the app it displaced; Chrome already in front when the tab
816
+ * was created was put there by the user and is left alone. Exported for tests. */
817
+ export function createTabStealGuard(chromePid, activate, now = Date.now) {
818
+ let lastOther = null;
819
+ let chromeFrontSince = null;
820
+ let armedFrom = 0;
821
+ let armedUntil = 0;
822
+ const caused = (at) => at >= armedFrom && at < armedUntil;
823
+ return {
824
+ frontChanged(pid) {
825
+ if (pid !== chromePid) {
826
+ if (pid > 0)
827
+ lastOther = pid;
828
+ chromeFrontSince = null;
829
+ return;
830
+ }
831
+ if (chromeFrontSince !== null)
832
+ return; // already in front: no new activation
833
+ chromeFrontSince = now();
834
+ if (caused(chromeFrontSince) && lastOther !== null)
835
+ activate(lastOther);
836
+ },
837
+ tabOpened(createdAt = now()) {
838
+ armedFrom = createdAt;
839
+ armedUntil = createdAt + TAB_STEAL_WINDOW_MS;
840
+ // Reported late (held while Clipy opened its own tab): Chrome may have
841
+ // come forward in between, after the tab existed.
842
+ if (chromeFrontSince !== null && caused(chromeFrontSince) && lastOther !== null)
843
+ activate(lastOther);
844
+ },
845
+ };
846
+ }
847
+ /** Reports every frontmost-app change on macOS from ONE long-lived process,
848
+ * instead of spawning `lsappinfo` on a timer. NSWorkspace only refreshes
849
+ * frontmostApplication while a run loop runs, hence runUntilDate. If the
850
+ * watcher cannot run, nothing is reported and the guard simply never acts. */
851
+ const FRONTMOST_WATCHER = `ObjC.import('AppKit');
852
+ var ws = $.NSWorkspace.sharedWorkspace, out = $.NSFileHandle.fileHandleWithStandardOutput, last = -1;
853
+ while (true) {
854
+ $.NSRunLoop.currentRunLoop.runUntilDate($.NSDate.dateWithTimeIntervalSinceNow(0.05));
855
+ var app = ws.frontmostApplication, pid = app.isNil() ? 0 : app.processIdentifier;
856
+ if (pid !== last) {
857
+ last = pid;
858
+ out.writeData($(String(pid) + '\\n').dataUsingEncoding($.NSUTF8StringEncoding));
859
+ }
860
+ }`;
861
+ function watchFrontmost(onChange) {
862
+ const child = spawn("osascript", ["-l", "JavaScript", "-e", FRONTMOST_WATCHER], { stdio: ["ignore", "pipe", "ignore"] });
863
+ child.on("error", () => { });
864
+ child.unref();
865
+ let pending = "";
866
+ child.stdout?.setEncoding("utf8");
867
+ child.stdout?.on("data", (chunk) => {
868
+ pending += chunk;
869
+ let nl;
870
+ while ((nl = pending.indexOf("\n")) >= 0) {
871
+ const pid = Number(pending.slice(0, nl).trim());
872
+ pending = pending.slice(nl + 1);
873
+ if (Number.isInteger(pid) && pid > 0)
874
+ onChange(pid);
875
+ }
876
+ });
877
+ child.stdout?.unref?.();
878
+ return () => {
879
+ child.kill();
880
+ };
881
+ }
416
882
  export async function startChromeForClipyCapture(chromium, opts) {
417
883
  const started = await startChrome(opts.home, opts.env, opts.platform, opts.port);
418
884
  if (!started.ok)
@@ -429,7 +895,9 @@ export async function startChromeForClipyCapture(chromium, opts) {
429
895
  let recorder;
430
896
  const captureLock = join(chromeForClipyDir(opts.home), "capture.lock");
431
897
  let locked = false;
898
+ const tabGuard = guardTabFocus(started.state.pid, context, opts.platform);
432
899
  const cleanup = async () => {
900
+ tabGuard.stop();
433
901
  if (target)
434
902
  await target.close().catch(() => { });
435
903
  if (recorder)
@@ -443,7 +911,7 @@ export async function startChromeForClipyCapture(chromium, opts) {
443
911
  try {
444
912
  if (existsSync(captureLock)) {
445
913
  const owner = Number(readFileSync(captureLock, "utf8"));
446
- if (Number.isInteger(owner) && owner > 0 && !pidAlive(owner))
914
+ if (Number.isInteger(owner) && owner > 0 && !processExists(owner))
447
915
  rmSync(captureLock, { force: true });
448
916
  }
449
917
  try {
@@ -466,7 +934,13 @@ export async function startChromeForClipyCapture(chromium, opts) {
466
934
  // getDisplayMedia rejects (InvalidStateError) instead of auto-selecting.
467
935
  // The marker title is pinned against SPA title rewrites only until capture
468
936
  // selects the tab; afterwards the capture follows the tab regardless.
469
- target = await context.newPage();
937
+ target = await tabGuard.ownTab(() => newBackgroundPage(browser, context));
938
+ try {
939
+ await opts.onTargetPage?.(target);
940
+ }
941
+ catch (err) {
942
+ opts.log(`target page hook failed: ${err.message}`);
943
+ }
470
944
  try {
471
945
  await target.goto(opts.targetUrl, { waitUntil: "load", timeout: 30_000 });
472
946
  }
@@ -497,7 +971,9 @@ export async function startChromeForClipyCapture(chromium, opts) {
497
971
  writeFileSync(videoPath, Buffer.alloc(0));
498
972
  let captureDone;
499
973
  const captureFinished = new Promise((r) => (captureDone = r));
500
- recorder = await context.newPage();
974
+ // getDisplayMedia rejects (InvalidStateError) from a tab that is not the
975
+ // active one, so the recorder gets its own background window.
976
+ recorder = await tabGuard.ownTab(() => newBackgroundPage(browser, context, true));
501
977
  await recorder.exposeFunction("clipyChunk", (b64) => {
502
978
  appendFileSync(videoPath, Buffer.from(b64, "base64"));
503
979
  });
@@ -506,10 +982,12 @@ export async function startChromeForClipyCapture(chromium, opts) {
506
982
  writeFileSync(recorderHtml, RECORDER_HTML);
507
983
  await recorder.goto(pathToFileURL(recorderHtml).href);
508
984
  // getDisplayMedia requires the calling document to be FOCUSED, and this
509
- // Chrome window is usually in the OS background while an agent drives it.
985
+ // Chrome window stays in the OS background while an agent drives it.
510
986
  // Playwright emulates focus for browsers it launches but not over CDP
511
987
  // attach, so enable it explicitly. Without this the capture rejects with
512
- // InvalidStateError whenever the window isn't frontmost.
988
+ // InvalidStateError whenever the window isn't frontmost. The recorder is
989
+ // already the active tab of its own window, so no bringToFront() is needed;
990
+ // on macOS that call activates Chrome.
513
991
  try {
514
992
  const cdp = await context.newCDPSession(recorder);
515
993
  await cdp.send("Emulation.setFocusEmulationEnabled", { enabled: true });
@@ -523,7 +1001,6 @@ export async function startChromeForClipyCapture(chromium, opts) {
523
1001
  for (let attempt = 1; attempt <= 3 && !resultRaw; attempt++) {
524
1002
  if (attempt > 1)
525
1003
  await recorder.goto(pathToFileURL(recorderHtml).href);
526
- await recorder.bringToFront();
527
1004
  await recorder.click("#go", { timeout: 5000 });
528
1005
  try {
529
1006
  // Plain EXPRESSION strings: an arrow-function string is itself a truthy