@capybara-hq/plugin-browser 0.1.0-rc.4 → 0.1.0-rc.6

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.
@@ -1,8 +1,10 @@
1
1
  // @capybara-hq/plugin-browser daemon (generated by daemon/build.ts)
2
2
 
3
- // ../../node_modules/.pnpm/@capybara-hq+plugin-sdk@0.1.0-rc.70/node_modules/@capybara-hq/plugin-sdk/dist/device-service.js
3
+ // ../../node_modules/.pnpm/@capybara-hq+plugin-sdk@0.1.0-rc.74/node_modules/@capybara-hq/plugin-sdk/dist/device-service.js
4
4
  var DEVICE_SERVICE_SOCKET_ENV = "CAPYBARA_SERVICE_SOCKET";
5
5
  var DEVICE_SERVICE_STATE_ENV = "CAPYBARA_SERVICE_STATE";
6
+ var DEVICE_SERVICE_MACH_ENV = "CAPYBARA_SERVICE_MACH";
7
+ var DEVICE_SERVICE_MACH_CHROMIUM = "chromium";
6
8
  var DEVICE_SERVICE_MAX_MESSAGE = 8 * 1024 * 1024;
7
9
  var HEADER = 4;
8
10
  function encodeServiceMessage(body) {
@@ -69,11 +71,24 @@ var ServiceMessageDecoder = class {
69
71
  };
70
72
 
71
73
  // daemon/main.ts
72
- import { chmodSync, existsSync as existsSync2, mkdirSync as mkdirSync2, unlinkSync } from "node:fs";
74
+ import { chmodSync, existsSync as existsSync2, mkdirSync as mkdirSync2, unlinkSync as unlinkSync2 } from "node:fs";
73
75
  import { createServer } from "node:net";
74
76
 
75
77
  // daemon/actions.ts
76
- import { lstatSync, mkdirSync, readdirSync, realpathSync, statSync } from "node:fs";
78
+ import {
79
+ closeSync,
80
+ constants as fsc,
81
+ fstatSync,
82
+ lstatSync,
83
+ mkdirSync,
84
+ openSync,
85
+ readdirSync,
86
+ readSync,
87
+ realpathSync,
88
+ statSync,
89
+ unlinkSync,
90
+ writeSync
91
+ } from "node:fs";
77
92
  import { request as httpRequest } from "node:http";
78
93
  import { basename, extname, join, sep } from "node:path";
79
94
 
@@ -82,14 +97,138 @@ var VIEWPORT = { width: 1280, height: 800 };
82
97
  var SNAPSHOT_MAX_CHARS = 4e4;
83
98
  var IDLE_STOP_MS = 15 * 6e4;
84
99
  var TAKEOVER_GRACE_MS = 6e4;
85
- var VIEWER_MAX_FPS = 5;
100
+ var VIEWER_MAX_FPS = 15;
86
101
  var VIEWER_UNACKED_FRAMES = 2;
102
+ var VIEWER_TEXT_MAX_CHARS = 1e4;
103
+ function clipCodePoints(text, max) {
104
+ if (text.length <= max) return text;
105
+ return Array.from(text).slice(0, max).join("");
106
+ }
107
+ var VIEWER_CURSORS = [
108
+ "default",
109
+ "pointer",
110
+ "text",
111
+ "vertical-text",
112
+ "crosshair",
113
+ "move",
114
+ "grab",
115
+ "grabbing",
116
+ "not-allowed",
117
+ "no-drop",
118
+ "wait",
119
+ "progress",
120
+ "help",
121
+ "context-menu",
122
+ "cell",
123
+ "copy",
124
+ "alias",
125
+ "zoom-in",
126
+ "zoom-out",
127
+ "col-resize",
128
+ "row-resize",
129
+ "ew-resize",
130
+ "ns-resize",
131
+ "nesw-resize",
132
+ "nwse-resize",
133
+ "n-resize",
134
+ "e-resize",
135
+ "s-resize",
136
+ "w-resize",
137
+ "ne-resize",
138
+ "nw-resize",
139
+ "se-resize",
140
+ "sw-resize",
141
+ "all-scroll",
142
+ "none"
143
+ ];
144
+ function toViewerCursor(value) {
145
+ return typeof value === "string" && VIEWER_CURSORS.includes(value) ? value : "default";
146
+ }
147
+ var FRAME_TAG = 0;
148
+ var FRAME_HEADER_BYTES = 9;
149
+ function encodeFrame(f) {
150
+ const out = new Uint8Array(FRAME_HEADER_BYTES + f.jpeg.byteLength);
151
+ const v = new DataView(out.buffer);
152
+ v.setUint8(0, FRAME_TAG);
153
+ v.setUint32(1, f.seq >>> 0);
154
+ v.setUint16(5, f.width);
155
+ v.setUint16(7, f.height);
156
+ out.set(f.jpeg, FRAME_HEADER_BYTES);
157
+ return out;
158
+ }
87
159
  var DEFAULT_FRAME_MAX_BYTES = 256 * 1024;
88
160
  var HANDOFF_MAX_CHARS = 4096;
89
161
  var MAX_TABS = 10;
90
162
  var HANDOFF_KEEPALIVE_MS = 24 * 60 * 6e4;
91
163
  var DOWNLOAD_BLOCKED_PREFIX = "The browser could not be downloaded into the device: its network settings block ";
92
164
  var REPLY_TOO_LARGE_MESSAGE = "The reply was too large to send; ask for less (a smaller maxBytes).";
165
+ var FAVICON_MAX_BYTES = 8 * 1024;
166
+
167
+ // daemon/favicon.ts
168
+ var READ_MAX_BYTES = 64 * 1024;
169
+ function sniffIcon(b) {
170
+ const at = (i, ...xs) => xs.every((x, j) => b[i + j] === x);
171
+ if (at(0, 137, 80, 78, 71)) return "image/png";
172
+ if (at(0, 0, 0, 1, 0)) return "image/x-icon";
173
+ if (at(0, 71, 73, 70, 56)) return "image/gif";
174
+ if (at(0, 255, 216, 255)) return "image/jpeg";
175
+ if (at(0, 82, 73, 70, 70) && at(8, 87, 69, 66, 80)) return "image/webp";
176
+ const head = new TextDecoder().decode(b.subarray(0, 512)).trimStart().toLowerCase();
177
+ if (head.startsWith("<svg") || head.startsWith("<?xml") && head.includes("<svg"))
178
+ return "image/svg+xml";
179
+ return null;
180
+ }
181
+ function iconDataUrl(b) {
182
+ if (b.byteLength === 0 || b.byteLength > FAVICON_MAX_BYTES) return null;
183
+ const mime = sniffIcon(b);
184
+ if (mime === null) return null;
185
+ return `data:${mime};base64,${Buffer.from(b).toString("base64")}`;
186
+ }
187
+ async function iconUrlOf(page) {
188
+ let base;
189
+ try {
190
+ base = new URL(page.url());
191
+ } catch {
192
+ return null;
193
+ }
194
+ if (base.protocol !== "http:" && base.protocol !== "https:") return null;
195
+ const declared = await page.evaluate(
196
+ `(() => { const l = Array.from(document.querySelectorAll("link[rel][href]")).find((x) => /(^|\\s)icon(\\s|$)/i.test(x.rel)); return l ? l.href : null; })()`
197
+ ).catch(() => null);
198
+ if (typeof declared === "string") {
199
+ try {
200
+ const u = new URL(declared, base);
201
+ if (u.protocol === "http:" || u.protocol === "https:") return u.href;
202
+ } catch {
203
+ }
204
+ }
205
+ return new URL("/favicon.ico", base).href;
206
+ }
207
+ async function fetchIcon(cdp, url) {
208
+ const tree = await cdp.send("Page.getFrameTree");
209
+ const res = await cdp.send("Network.loadNetworkResource", {
210
+ frameId: tree.frameTree.frame.id,
211
+ url,
212
+ options: { disableCache: false, includeCredentials: false }
213
+ });
214
+ const r = res.resource;
215
+ if (!r.success || r.httpStatusCode !== 200 || r.stream === void 0) return null;
216
+ const chunks = [];
217
+ let size = 0;
218
+ try {
219
+ for (; ; ) {
220
+ const part = await cdp.send("IO.read", { handle: r.stream, size: 16 * 1024 });
221
+ const buf = Buffer.from(part.data, part.base64Encoded ? "base64" : "utf8");
222
+ size += buf.byteLength;
223
+ if (size > READ_MAX_BYTES) return null;
224
+ chunks.push(buf);
225
+ if (part.eof) break;
226
+ }
227
+ } finally {
228
+ await cdp.send("IO.close", { handle: r.stream }).catch(() => void 0);
229
+ }
230
+ return new Uint8Array(Buffer.concat(chunks));
231
+ }
93
232
 
94
233
  // daemon/snapshot.ts
95
234
  var isNode = (line) => line.trimStart().startsWith("- ");
@@ -274,6 +413,49 @@ var DaemonState = class {
274
413
  }
275
414
  };
276
415
 
416
+ // daemon/verification.ts
417
+ var VERIFICATION_NOTE = "This page is a verification (CAPTCHA or bot check) page. Do not try to solve it and do not switch to another site to get around it: call browser_handoff and ask the user to complete the verification, then continue.";
418
+ var URL_RE = /captcha|challenge|antispider|anti-spider|\/sorry\/|wappass\.baidu\.com|\/cdn-cgi\/|\/verify(?:[/?#]|$)|security-?check/i;
419
+ var TITLE_RE = /captcha|verif(?:y|ication)|are you (?:a )?(?:human|robot)|not a robot|just a moment|attention required|security check|unusual traffic|人机验证|安全验证|验证码|请完成验证|访问验证|异常访问|身份验证|滑动验证|拖动滑块/i;
420
+ var VERIFICATION_STATUSES = /* @__PURE__ */ new Set([418, 429]);
421
+ var WIDGET_SELECTOR = [
422
+ ...["recaptcha", "hcaptcha", "challenges.cloudflare.com", "turnstile", "geetest", "captcha"].map(
423
+ (s) => `iframe[src*="${s}" i]`
424
+ ),
425
+ '[id*="captcha" i]',
426
+ '[class*="captcha" i]'
427
+ ].join(", ");
428
+ var MAX_WIDGETS = 10;
429
+ async function hasWidget(page) {
430
+ const found = page.locator(WIDGET_SELECTOR);
431
+ const n = Math.min(await found.count(), MAX_WIDGETS);
432
+ for (let i = 0; i < n; i++) {
433
+ const box = await found.nth(i).boundingBox();
434
+ if (box !== null && box.width > 20 && box.height > 20) return true;
435
+ }
436
+ return false;
437
+ }
438
+ function looksLikeVerification(url, title) {
439
+ let target = url;
440
+ try {
441
+ const u = new URL(url);
442
+ target = `${u.hostname}${u.pathname}${u.search}`;
443
+ } catch {
444
+ }
445
+ return URL_RE.test(target) || TITLE_RE.test(title);
446
+ }
447
+ async function isVerificationPage(page, status) {
448
+ try {
449
+ if (status !== void 0 && VERIFICATION_STATUSES.has(status)) return true;
450
+ const url = page.url();
451
+ if (!/^https?:/.test(url)) return false;
452
+ if (looksLikeVerification(url, await page.title())) return true;
453
+ return await hasWidget(page);
454
+ } catch {
455
+ return false;
456
+ }
457
+ }
458
+
277
459
  // daemon/actions.ts
278
460
  var ActionError = class extends Error {
279
461
  constructor(code, message) {
@@ -289,6 +471,7 @@ var MAX_NAME_BYTES = 200;
289
471
  var ACTION_TIMEOUT_MS = 1e4;
290
472
  var NAVIGATION_TIMEOUT_MS = 3e4;
291
473
  var LOAD_GRACE_MS = 5e3;
474
+ var PAGE_QUERY_MS = 2e3;
292
475
  var MAX_WAIT_MS = 6e4;
293
476
  var MAX_SCREENSHOT_BYTES = Math.floor((8 * 1024 * 1024 - 64 * 1024) * 3 / 4);
294
477
  var MAX_TITLE_CHARS = 2048;
@@ -323,17 +506,65 @@ function safeFileName(raw) {
323
506
  if (Buffer.byteLength(ext) > 32) ext = "";
324
507
  return utf8Prefix(name.slice(0, name.length - ext.length), MAX_NAME_BYTES - Buffer.byteLength(ext)) + ext;
325
508
  }
326
- function absent(path) {
509
+ function copyInto(source, out) {
510
+ const src = openSync(source, fsc.O_RDONLY | fsc.O_NOFOLLOW);
327
511
  try {
328
- lstatSync(path);
329
- return false;
330
- } catch {
331
- return true;
512
+ const buf = Buffer.alloc(1024 * 1024);
513
+ for (; ; ) {
514
+ const n = readSync(src, buf, 0, buf.length, null);
515
+ if (n === 0) break;
516
+ let w = 0;
517
+ while (w < n) w += writeSync(out, buf, w, n - w);
518
+ }
519
+ } finally {
520
+ closeSync(src);
332
521
  }
333
522
  }
334
523
  var PROXY_PROBE_TIMEOUT_MS = 5e3;
524
+ var UPLOAD_MAX_BYTES = 50 * 1024 * 1024;
525
+ var UPLOAD_TYPES = {
526
+ ".png": "image/png",
527
+ ".jpg": "image/jpeg",
528
+ ".jpeg": "image/jpeg",
529
+ ".gif": "image/gif",
530
+ ".webp": "image/webp",
531
+ ".svg": "image/svg+xml",
532
+ ".pdf": "application/pdf",
533
+ ".txt": "text/plain",
534
+ ".md": "text/markdown",
535
+ ".csv": "text/csv",
536
+ ".json": "application/json",
537
+ ".html": "text/html",
538
+ ".zip": "application/zip",
539
+ ".mp4": "video/mp4",
540
+ ".mp3": "audio/mpeg",
541
+ ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
542
+ ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
543
+ ".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation"
544
+ };
545
+ function within(real, root) {
546
+ return real === root || real.startsWith(root.endsWith(sep) ? root : root + sep);
547
+ }
548
+ var sameFile = (a, b) => a.dev === b.dev && a.ino === b.ino;
335
549
  var REF_RE = /^(f\d+)?e\d+$/;
336
550
  var PROXY_FAILURE_RE = /ERR_TUNNEL_CONNECTION_FAILED|ERR_PROXY_CONNECTION_FAILED/;
551
+ var ERROR_PAGE_WAIT_MS = 2e3;
552
+ var isTimeout = (e) => e instanceof Error && e.name === "TimeoutError";
553
+ var NET_ERROR_MEANINGS = {
554
+ ERR_NAME_NOT_RESOLVED: "the host name does not resolve",
555
+ ERR_CONNECTION_REFUSED: "the host refused the connection",
556
+ ERR_CONNECTION_RESET: "the connection was reset",
557
+ ERR_CONNECTION_CLOSED: "the host closed the connection without an answer",
558
+ ERR_CONNECTION_TIMED_OUT: "the host did not answer the connection",
559
+ ERR_ADDRESS_UNREACHABLE: "the host's address is unreachable",
560
+ ERR_INTERNET_DISCONNECTED: "the device has no network connection",
561
+ ERR_EMPTY_RESPONSE: "the server sent an empty answer",
562
+ ERR_SSL_PROTOCOL_ERROR: "the secure connection failed",
563
+ ERR_CERT_AUTHORITY_INVALID: "the site's certificate is not trusted",
564
+ ERR_CERT_COMMON_NAME_INVALID: "the site's certificate is for another name",
565
+ ERR_CERT_DATE_INVALID: "the site's certificate has expired or is not yet valid",
566
+ ERR_TOO_MANY_REDIRECTS: "the page redirects in a loop"
567
+ };
337
568
  function docUrl(raw) {
338
569
  try {
339
570
  const u = new URL(raw);
@@ -433,6 +664,16 @@ var NavWatch = class {
433
664
  }
434
665
  return { kind: "loaded", response: await final.response().catch(() => null) };
435
666
  }
667
+ /**
668
+ * The status the newest navigation to the target address was answered with, when it finished
669
+ * without a document (a 204 or 205: Chromium keeps the page and aborts the navigation).
670
+ */
671
+ async emptyAnswer() {
672
+ const r = this.lastOurs;
673
+ if (r === void 0 || r === this.committedOurs) return void 0;
674
+ const status = (await r.response().catch(() => null))?.status();
675
+ return status === 204 || status === 205 ? status : void 0;
676
+ }
436
677
  dispose() {
437
678
  this.page.off("request", this.onRequest);
438
679
  this.page.off("framenavigated", this.onNavigated);
@@ -478,13 +719,16 @@ async function captureFitting(cdp, opts) {
478
719
  }
479
720
  return null;
480
721
  }
481
- function proxyRefuses(proxy, host, port) {
722
+ async function proxyRefuses(proxy, host, port) {
723
+ return await probeProxy(proxy, host, port) === "refused";
724
+ }
725
+ function probeProxy(proxy, host, port) {
482
726
  return new Promise((resolve) => {
483
727
  let url;
484
728
  try {
485
729
  url = new URL(proxy.includes("://") ? proxy : `http://${proxy}`);
486
730
  } catch {
487
- resolve(false);
731
+ resolve("unknown");
488
732
  return;
489
733
  }
490
734
  const headers = { host: `${host}:${port}` };
@@ -500,16 +744,20 @@ function proxyRefuses(proxy, host, port) {
500
744
  headers,
501
745
  timeout: PROXY_PROBE_TIMEOUT_MS
502
746
  });
747
+ const verdict = (status) => status === 403 ? "refused" : status === 200 ? "connected" : "unreachable";
503
748
  req.on("connect", (res, socket) => {
504
749
  socket.destroy();
505
- resolve(res.statusCode === 403);
750
+ resolve(verdict(res.statusCode));
506
751
  });
507
752
  req.on("response", (res) => {
508
753
  res.resume();
509
- resolve(res.statusCode === 403);
754
+ resolve(verdict(res.statusCode));
755
+ });
756
+ req.on("timeout", () => {
757
+ resolve("no_answer");
758
+ req.destroy();
510
759
  });
511
- req.on("timeout", () => req.destroy());
512
- req.on("error", () => resolve(false));
760
+ req.on("error", () => resolve("unknown"));
513
761
  req.end();
514
762
  });
515
763
  }
@@ -533,6 +781,7 @@ var BrowserSession = class {
533
781
  ctx;
534
782
  proxy;
535
783
  clock;
784
+ navigationTimeoutMs;
536
785
  /** The device's workspace root (CAPYBARA_SERVICE_WORKSPACE): uploads and downloads stay in it. */
537
786
  workspace;
538
787
  downloadsTmp;
@@ -550,6 +799,15 @@ var BrowserSession = class {
550
799
  ids = /* @__PURE__ */ new WeakMap();
551
800
  titles = /* @__PURE__ */ new Map();
552
801
  loadingTabs = /* @__PURE__ */ new Set();
802
+ /**
803
+ * Each tab's icon: the address it came from and its data URL (null: none or not usable). Kept
804
+ * across navigations until the new page's icon is known, so the strip does not flicker.
805
+ */
806
+ favicons = /* @__PURE__ */ new Map();
807
+ /** Tabs showing a verification page, by tab id (cleared on every main-frame navigation). */
808
+ blockers = /* @__PURE__ */ new Map();
809
+ /** The status of each tab's current document (main-frame response), by tab id. */
810
+ docStatus = /* @__PURE__ */ new Map();
553
811
  /** Each page's main-frame navigation request in flight (until it commits, fails or finishes). */
554
812
  pendingNavs = /* @__PURE__ */ new WeakMap();
555
813
  listeners = /* @__PURE__ */ new Set();
@@ -571,8 +829,9 @@ var BrowserSession = class {
571
829
  this.downloadMaxBytes = opts.downloadMaxBytes ?? DEFAULT_DOWNLOAD_MAX_BYTES;
572
830
  this.downloadWaitMs = opts.downloadWaitMs ?? DOWNLOAD_WAIT_MS;
573
831
  this.clock = opts.clock ?? systemClock;
832
+ this.navigationTimeoutMs = opts.navigationTimeoutMs ?? NAVIGATION_TIMEOUT_MS;
574
833
  ctx.setDefaultTimeout(ACTION_TIMEOUT_MS);
575
- ctx.setDefaultNavigationTimeout(NAVIGATION_TIMEOUT_MS);
834
+ ctx.setDefaultNavigationTimeout(this.navigationTimeoutMs);
576
835
  ctx.on("page", (p) => {
577
836
  if (!this.ids.has(p) && this.pages.size >= MAX_TABS) {
578
837
  p.close().catch(() => void 0);
@@ -613,12 +872,18 @@ var BrowserSession = class {
613
872
  return this.ids.get(page) ?? "";
614
873
  }
615
874
  tabs() {
616
- return [...this.pages.entries()].map(([id, p]) => ({
617
- id,
618
- title: clip(this.titles.get(id) ?? "", MAX_TITLE_CHARS),
619
- url: clip(p.url(), MAX_URL_CHARS),
620
- active: id === this.active
621
- }));
875
+ return [...this.pages.entries()].map(([id, p]) => {
876
+ const blocker = this.blockers.get(id);
877
+ const icon = this.favicons.get(id)?.data;
878
+ return {
879
+ id,
880
+ title: clip(this.titles.get(id) ?? "", MAX_TITLE_CHARS),
881
+ url: clip(p.url(), MAX_URL_CHARS),
882
+ active: id === this.active,
883
+ ...blocker === void 0 ? {} : { blocker },
884
+ ...icon === void 0 || icon === null ? {} : { favicon: icon }
885
+ };
886
+ });
622
887
  }
623
888
  /** Whether the active tab is loading a document. */
624
889
  get loading() {
@@ -638,7 +903,7 @@ var BrowserSession = class {
638
903
  this.ids.set(page, id);
639
904
  this.pages.set(id, page);
640
905
  const refresh = () => {
641
- page.title().then((t) => this.titles.set(id, t)).catch(() => void 0).finally(() => this.emit({ type: "state" }));
906
+ page.title().then((t) => this.titles.set(id, t)).catch(() => void 0).then(() => this.checkVerification(page, id)).finally(() => this.emit({ type: "state" }));
642
907
  };
643
908
  const settle = (r) => {
644
909
  if (this.pendingNavs.get(page) === r) this.pendingNavs.delete(page);
@@ -664,12 +929,14 @@ var BrowserSession = class {
664
929
  page.on("framenavigated", (f) => {
665
930
  if (f !== page.mainFrame()) return;
666
931
  this.pendingNavs.delete(page);
932
+ this.blockers.delete(id);
667
933
  refresh();
668
934
  });
669
935
  page.on("domcontentloaded", refresh);
670
936
  page.on("load", () => {
671
937
  this.loadingTabs.delete(id);
672
938
  refresh();
939
+ void this.resolveFavicon(page, id);
673
940
  });
674
941
  page.on("requestfailed", (r) => {
675
942
  settle(r);
@@ -682,6 +949,8 @@ var BrowserSession = class {
682
949
  this.checkBlocked(r.url(), this.pageToOpen(page, r));
683
950
  });
684
951
  page.on("response", (r) => {
952
+ if (r.request().isNavigationRequest() && r.frame() === page.mainFrame())
953
+ this.docStatus.set(id, r.status());
685
954
  if (this.proxy !== void 0 && r.status() === 403 && r.url().startsWith("http:")) {
686
955
  this.checkBlocked(r.url(), this.pageToOpen(page, r.request()));
687
956
  }
@@ -697,6 +966,9 @@ var BrowserSession = class {
697
966
  this.pages.delete(id);
698
967
  this.titles.delete(id);
699
968
  this.loadingTabs.delete(id);
969
+ this.blockers.delete(id);
970
+ this.favicons.delete(id);
971
+ this.docStatus.delete(id);
700
972
  if (this.active === id) {
701
973
  const next = [...this.pages.keys()].at(-1);
702
974
  this.active = next;
@@ -768,8 +1040,7 @@ var BrowserSession = class {
768
1040
  );
769
1041
  return;
770
1042
  }
771
- target = this.downloadTarget(workspace, safeFileName(d.suggestedFilename()));
772
- await d.saveAs(target);
1043
+ target = this.saveDownload(workspace, safeFileName(d.suggestedFilename()), tmp);
773
1044
  this.note(`Downloaded ${shown} to ${target}.`);
774
1045
  } catch (e) {
775
1046
  this.note(
@@ -784,8 +1055,62 @@ var BrowserSession = class {
784
1055
  })();
785
1056
  for (const c of this.collectors) c.downloads.push(entry);
786
1057
  }
787
- /** A free path in `<workspace>/downloads`, refusing a downloads directory that is a link. */
788
- downloadTarget(workspace, name) {
1058
+ /**
1059
+ * Copies a finished download from Playwright's private file into `<workspace>/downloads` and
1060
+ * returns where. The agent owns that directory, so the target is never written through a path
1061
+ * it could have swapped: each candidate is created exclusively without following a link
1062
+ * (`O_CREAT | O_EXCL | O_NOFOLLOW`), then checked to be the file the resolved path inside the
1063
+ * downloads directory names before any byte is written; a mismatch (a directory swapped for a
1064
+ * link meanwhile) writes nothing, removes the empty file it made (only while that name still
1065
+ * is the file it opened) and fails.
1066
+ */
1067
+ saveDownload(workspace, name, source) {
1068
+ const dir = this.downloadsDir(workspace);
1069
+ const dirStat = lstatSync(dir);
1070
+ const ext = extname(name);
1071
+ const stem = name.slice(0, name.length - ext.length);
1072
+ for (let i = 0; i < 1e3; i++) {
1073
+ const target = join(dir, i === 0 ? name : `${stem} (${i})${ext}`);
1074
+ if (this.reservedDownloads.has(target)) continue;
1075
+ let out;
1076
+ try {
1077
+ out = openSync(target, fsc.O_WRONLY | fsc.O_CREAT | fsc.O_EXCL | fsc.O_NOFOLLOW, 436);
1078
+ } catch (e) {
1079
+ if (e.code === "EEXIST") continue;
1080
+ throw e;
1081
+ }
1082
+ this.reservedDownloads.add(target);
1083
+ try {
1084
+ let real;
1085
+ try {
1086
+ real = realpathSync(target);
1087
+ } catch {
1088
+ real = "";
1089
+ }
1090
+ const opened = fstatSync(out);
1091
+ const placed = real !== "" && within(real, dir) && sameFile(opened, statSync(real));
1092
+ if (!placed || !sameFile(dirStat, lstatSync(dir))) {
1093
+ try {
1094
+ if (real !== "" && sameFile(opened, lstatSync(real)) && opened.size === 0)
1095
+ unlinkSync(real);
1096
+ } catch {
1097
+ }
1098
+ throw new ActionError(
1099
+ "failed",
1100
+ `${dir} changed while the download was saved; nothing was written. Retry the download.`
1101
+ );
1102
+ }
1103
+ copyInto(source, out);
1104
+ return target;
1105
+ } finally {
1106
+ closeSync(out);
1107
+ this.reservedDownloads.delete(target);
1108
+ }
1109
+ }
1110
+ throw new ActionError("failed", `No free name for ${name} in ${dir}; remove old downloads.`);
1111
+ }
1112
+ /** `<workspace>/downloads` resolved, refusing one that is a link or not a directory. */
1113
+ downloadsDir(workspace) {
789
1114
  const root = realpathSync(workspace);
790
1115
  const dir = join(root, "downloads");
791
1116
  mkdirSync(dir, { recursive: true });
@@ -796,14 +1121,7 @@ var BrowserSession = class {
796
1121
  `${dir} is not a plain directory in the workspace; remove it so downloads can be saved.`
797
1122
  );
798
1123
  }
799
- const ext = extname(name);
800
- const stem = name.slice(0, name.length - ext.length);
801
- let target = join(dir, name);
802
- for (let i = 1; !absent(target) || this.reservedDownloads.has(target); i++) {
803
- target = join(dir, `${stem} (${i})${ext}`);
804
- }
805
- this.reservedDownloads.add(target);
806
- return target;
1124
+ return dir;
807
1125
  }
808
1126
  /**
809
1127
  * While downloads run, sums the bytes of Playwright's in-progress files and cancels every
@@ -845,29 +1163,69 @@ var BrowserSession = class {
845
1163
  this.pollDownloads();
846
1164
  }, DOWNLOAD_POLL_MS);
847
1165
  }
848
- /** The real path of an upload, refused unless it is inside the workspace. */
849
- uploadPath(path) {
850
- const workspace = this.workspace;
851
- if (workspace === void 0) {
852
- throw new ActionError("failed", "Uploads are unavailable: the device has no workspace.");
853
- }
854
- const root = realpathSync(workspace);
855
- let real;
1166
+ /**
1167
+ * An upload's bytes, read here and handed to Chromium from memory (never a path Chromium would
1168
+ * open later, after the agent could have swapped it for a link to the service's own files):
1169
+ * opened without following a final link, then accepted only when the resolved path lies in the
1170
+ * workspace and names the very file opened (an intermediate link swapped in either way shows as
1171
+ * another file), a regular file of at most {@link UPLOAD_MAX_BYTES}.
1172
+ */
1173
+ readUpload(path) {
1174
+ const root = this.uploadRoot();
1175
+ let fd;
856
1176
  try {
857
- real = realpathSync(path);
858
- } catch {
1177
+ fd = openSync(path, fsc.O_RDONLY | fsc.O_NOFOLLOW | fsc.O_NONBLOCK);
1178
+ } catch (e) {
1179
+ const code = e.code;
859
1180
  throw new ActionError(
860
1181
  "failed",
861
- `No file at ${path}; give the absolute path of a file in the workspace (${root}).`
1182
+ code === "ELOOP" ? `${path} is a symbolic link; upload the file it points to by its own path in the workspace.` : `No readable file at ${path}; give the absolute path of a file in the workspace (${root}).`
862
1183
  );
863
1184
  }
864
- if (real !== root && !real.startsWith(root.endsWith(sep) ? root : root + sep)) {
865
- throw new ActionError(
866
- "failed",
867
- `Upload paths must be inside the workspace (${root}); copy the file there first.`
868
- );
1185
+ try {
1186
+ const opened = fstatSync(fd);
1187
+ let real = "";
1188
+ try {
1189
+ real = realpathSync(path);
1190
+ } catch {
1191
+ real = "";
1192
+ }
1193
+ if (!within(real, root) || !sameFile(opened, statSync(real)))
1194
+ throw new ActionError(
1195
+ "failed",
1196
+ `Upload paths must be inside the workspace (${root}); copy the file there first.`
1197
+ );
1198
+ if (!opened.isFile())
1199
+ throw new ActionError("failed", `${path} is not a regular file; upload a file.`);
1200
+ if (opened.size > UPLOAD_MAX_BYTES)
1201
+ throw new ActionError(
1202
+ "failed",
1203
+ `${path} is larger than ${UPLOAD_MAX_BYTES} bytes, the most an upload takes.`
1204
+ );
1205
+ const buffer = Buffer.alloc(opened.size);
1206
+ let off = 0;
1207
+ while (off < buffer.length) {
1208
+ const n = readSync(fd, buffer, off, buffer.length - off, off);
1209
+ if (n === 0) break;
1210
+ off += n;
1211
+ }
1212
+ const name = basename(real);
1213
+ return {
1214
+ name,
1215
+ mimeType: UPLOAD_TYPES[extname(name).toLowerCase()] ?? "application/octet-stream",
1216
+ buffer: buffer.subarray(0, off)
1217
+ };
1218
+ } finally {
1219
+ closeSync(fd);
1220
+ }
1221
+ }
1222
+ /** The resolved workspace uploads come from. */
1223
+ uploadRoot() {
1224
+ const workspace = this.workspace;
1225
+ if (workspace === void 0) {
1226
+ throw new ActionError("failed", "Uploads are unavailable: the device has no workspace.");
869
1227
  }
870
- return real;
1228
+ return realpathSync(workspace);
871
1229
  }
872
1230
  /**
873
1231
  * The page a viewer opens once the refused host is allowed: the navigation's target for a
@@ -906,7 +1264,21 @@ var BrowserSession = class {
906
1264
  for (const c of this.collectors) c.pending.push(probe);
907
1265
  return probe;
908
1266
  }
909
- /** Runs `fn` one at a time with the other actions (`wait` runs beside them). */
1267
+ /** `value`, or `fallback` when it takes longer than {@link PAGE_QUERY_MS} (never rejects). */
1268
+ async bounded(value, fallback) {
1269
+ let timer;
1270
+ try {
1271
+ return await Promise.race([
1272
+ value.catch(() => fallback),
1273
+ new Promise((r) => {
1274
+ timer = this.clock.schedule(() => r(fallback), PAGE_QUERY_MS);
1275
+ })
1276
+ ]);
1277
+ } finally {
1278
+ this.clock.cancel(timer);
1279
+ }
1280
+ }
1281
+ /** Runs `fn` one at a time with the other actions (`wait` and the tab list run beside them). */
910
1282
  serial(fn) {
911
1283
  const run = this.queue.then(fn, fn);
912
1284
  this.queue = run.catch(() => void 0);
@@ -923,7 +1295,7 @@ var BrowserSession = class {
923
1295
  this.collectors.add(c);
924
1296
  let reply;
925
1297
  try {
926
- const out = await (req.op === "wait" ? this.exec(req) : this.serial(() => {
1298
+ const out = await (req.op === "wait" || req.op === "tabs" && req.action === "list" ? this.exec(req) : this.serial(() => {
927
1299
  if (opts.takenOver?.() === true)
928
1300
  throw new ActionError("taken_over", TAKEN_OVER_MESSAGE);
929
1301
  return this.exec(req);
@@ -932,7 +1304,12 @@ var BrowserSession = class {
932
1304
  await this.settleDownloads(c);
933
1305
  this.collectors.delete(c);
934
1306
  const page = await this.activePage();
935
- const text = [...c.notes, ...out.text === void 0 ? [] : [out.text]].join("\n");
1307
+ const verifying = await this.checkVerification(page, this.tabIdOf(page));
1308
+ const text = [
1309
+ ...verifying ? [VERIFICATION_NOTE] : [],
1310
+ ...c.notes,
1311
+ ...out.text === void 0 ? [] : [out.text]
1312
+ ].join("\n");
936
1313
  reply = {
937
1314
  ok: true,
938
1315
  page: await this.pageInfo(page),
@@ -986,13 +1363,61 @@ var BrowserSession = class {
986
1363
  await Promise.allSettled(all);
987
1364
  }
988
1365
  }
989
- async pageInfo(page) {
990
- let title = "";
1366
+ /**
1367
+ * Finds the loaded page's icon and fetches it through the browser (the device's network rules
1368
+ * apply); a new address replaces the tab's icon, the same one is not fetched again. Any failure
1369
+ * leaves no icon (the panel's placeholder) and never affects the page.
1370
+ */
1371
+ async resolveFavicon(page, id) {
991
1372
  try {
992
- title = await page.title();
1373
+ const url = await iconUrlOf(page);
1374
+ if (this.pages.get(id) !== page) return;
1375
+ if (url === null) {
1376
+ if (this.favicons.delete(id)) this.emit({ type: "state" });
1377
+ return;
1378
+ }
1379
+ if (this.favicons.get(id)?.url === url) return;
1380
+ const cdp = await this.ctx.newCDPSession(page);
1381
+ let data = null;
1382
+ try {
1383
+ const bytes = await fetchIcon(cdp, url);
1384
+ data = bytes === null ? null : iconDataUrl(bytes);
1385
+ } finally {
1386
+ await cdp.detach().catch(() => void 0);
1387
+ }
1388
+ if (this.pages.get(id) !== page) return;
1389
+ this.favicons.set(id, { url, data });
1390
+ this.emit({ type: "state" });
993
1391
  } catch {
994
- title = this.titles.get(this.tabIdOf(page)) ?? "";
995
1392
  }
1393
+ }
1394
+ /**
1395
+ * Looks at the tab's page now and records or clears its verification blocker; true when it
1396
+ * shows a verification page.
1397
+ */
1398
+ async checkVerification(page, id) {
1399
+ if (id === "") return false;
1400
+ const blocked = await this.bounded(isVerificationPage(page, this.docStatus.get(id)), false);
1401
+ if (this.pages.get(id) !== page) return false;
1402
+ const before = this.blockers.get(id);
1403
+ if (blocked) {
1404
+ const url = clip(page.url(), MAX_URL_CHARS);
1405
+ if (before?.url !== url) {
1406
+ this.blockers.set(id, { kind: "verification", url });
1407
+ this.emit({ type: "state" });
1408
+ }
1409
+ } else if (before !== void 0) {
1410
+ this.blockers.delete(id);
1411
+ this.emit({ type: "state" });
1412
+ }
1413
+ return blocked;
1414
+ }
1415
+ async pageInfo(page) {
1416
+ const known = this.titles.get(this.tabIdOf(page)) ?? "";
1417
+ const title = await this.bounded(
1418
+ page.title().catch(() => known),
1419
+ known
1420
+ );
996
1421
  return {
997
1422
  url: clip(page.url(), MAX_URL_CHARS),
998
1423
  title: clip(title, MAX_TITLE_CHARS),
@@ -1039,7 +1464,7 @@ var BrowserSession = class {
1039
1464
  try {
1040
1465
  const out = await fn();
1041
1466
  if (navigating && !loaded2) {
1042
- await page.waitForEvent("domcontentloaded", { timeout: NAVIGATION_TIMEOUT_MS }).catch(() => void 0);
1467
+ await page.waitForEvent("domcontentloaded", { timeout: this.navigationTimeoutMs }).catch(() => void 0);
1043
1468
  }
1044
1469
  return out;
1045
1470
  } finally {
@@ -1067,7 +1492,7 @@ var BrowserSession = class {
1067
1492
  let res;
1068
1493
  const download = page.waitForEvent("download", { timeout: ACTION_TIMEOUT_MS });
1069
1494
  download.catch(() => void 0);
1070
- const deadline = Date.now() + NAVIGATION_TIMEOUT_MS;
1495
+ const deadline = Date.now() + this.navigationTimeoutMs;
1071
1496
  const watch = new NavWatch(page, url, () => this.pendingNavs.get(page));
1072
1497
  try {
1073
1498
  res = await page.goto(url, { waitUntil: "domcontentloaded" });
@@ -1077,13 +1502,25 @@ var BrowserSession = class {
1077
1502
  await download.catch(() => void 0);
1078
1503
  return;
1079
1504
  }
1080
- if (PROXY_FAILURE_RE.test(msg)) await this.checkBlocked(url);
1081
- if (!msg.includes("net::ERR_ABORTED")) throw e;
1505
+ if (isTimeout(e)) throw await this.navigationTimedOut(page, url);
1506
+ if (!msg.includes("net::ERR_ABORTED")) throw await this.navigationFailed(page, e, url, msg);
1082
1507
  const out = await watch.follow(deadline);
1508
+ if (out.kind !== "loaded") {
1509
+ const status = await watch.emptyAnswer();
1510
+ if (status !== void 0)
1511
+ throw new ActionError(
1512
+ "failed",
1513
+ `${url} answered ${status} with no page to show; the tab shows ${page.url()}.`
1514
+ );
1515
+ }
1083
1516
  if (out.kind === "none") throw e;
1084
1517
  if (out.kind === "failed") {
1085
- if (PROXY_FAILURE_RE.test(out.error)) await this.checkBlocked(out.url);
1086
- throw new Error(`${out.error} at ${out.url}`);
1518
+ throw await this.navigationFailed(
1519
+ page,
1520
+ new Error(`${out.error} at ${out.url}`),
1521
+ out.url,
1522
+ out.error
1523
+ );
1087
1524
  }
1088
1525
  res = out.response;
1089
1526
  } finally {
@@ -1097,6 +1534,101 @@ var BrowserSession = class {
1097
1534
  }
1098
1535
  await page.waitForLoadState("load", { timeout: LOAD_GRACE_MS }).catch(() => void 0);
1099
1536
  }
1537
+ /**
1538
+ * The error of a navigation that failed with Chromium's net error `error`: a host the proxy
1539
+ * refuses is reported as blocked (`run` turns `original` into the blocked reply); any other net
1540
+ * error is `unreachable`, saying what the device's network answered when it went through it.
1541
+ */
1542
+ async navigationFailed(page, original, url, error) {
1543
+ const net = /net::(ERR_[A-Z_]+)/.exec(error)?.[1];
1544
+ if (net === void 0 || net === "ERR_ABORTED") return original;
1545
+ await this.errorPageCommitted(page);
1546
+ if (PROXY_FAILURE_RE.test(error)) {
1547
+ if (await this.checkBlocked(url)) return original;
1548
+ const detail = await this.networkDetail(url);
1549
+ return new ActionError(
1550
+ "unreachable",
1551
+ `${url} could not be loaded (net::${net})${detail === "" ? "." : `: ${detail}`}`
1552
+ );
1553
+ }
1554
+ const meaning = NET_ERROR_MEANINGS[net];
1555
+ return new ActionError(
1556
+ "unreachable",
1557
+ `${url} could not be loaded (net::${net})${meaning === void 0 ? "." : `: ${meaning}.`}`
1558
+ );
1559
+ }
1560
+ /**
1561
+ * Waits (at most {@link ERROR_PAGE_WAIT_MS}) for the error page of the main frame's failed
1562
+ * navigation: Chromium commits it after Playwright reported the failure (the Linux full build
1563
+ * shows it), and a navigation started before that commit is interrupted by it.
1564
+ */
1565
+ async errorPageCommitted(page) {
1566
+ if (page.isClosed() || page.mainFrame().url().startsWith("chrome-error:")) return;
1567
+ await page.waitForEvent("framenavigated", {
1568
+ predicate: (f) => f === page.mainFrame() && f.url().startsWith("chrome-error:"),
1569
+ timeout: ERROR_PAGE_WAIT_MS
1570
+ }).catch(() => void 0);
1571
+ }
1572
+ /**
1573
+ * The error of a navigation that took longer than its time limit. The navigation is stopped
1574
+ * first (a navigation left in flight keeps the page's scripts and snapshots waiting for a
1575
+ * document that never comes), so the tab goes back to the page it showed and the next request
1576
+ * works on it; the message says what the device's network answered for the host.
1577
+ */
1578
+ async navigationTimedOut(page, url) {
1579
+ await this.stopNavigation(page);
1580
+ const seconds = Math.round(this.navigationTimeoutMs / 1e3);
1581
+ let detail = await this.networkDetail(url, true);
1582
+ if (detail === "") detail = "no page came in that time.";
1583
+ const now = page.isClosed() ? "" : ` The navigation was stopped; the tab shows ${page.url()}.`;
1584
+ return new ActionError(
1585
+ "unreachable",
1586
+ `${url} did not load within ${seconds} s: ${detail}${now}`
1587
+ );
1588
+ }
1589
+ /** Stops the page's navigation in flight (Chromium's stop button); never throws. */
1590
+ async stopNavigation(page) {
1591
+ if (page.isClosed()) return;
1592
+ try {
1593
+ const cdp = await this.ctx.newCDPSession(page);
1594
+ try {
1595
+ await cdp.send("Page.stopLoading");
1596
+ } finally {
1597
+ await cdp.detach().catch(() => void 0);
1598
+ }
1599
+ } catch {
1600
+ }
1601
+ this.pendingNavs.delete(page);
1602
+ const id = this.ids.get(page);
1603
+ if (id !== void 0 && this.loadingTabs.delete(id)) this.emit({ type: "state" });
1604
+ }
1605
+ /**
1606
+ * What the device's proxy answers for the URL's host, as a sentence ("" without a proxy, or when
1607
+ * the proxy failed itself). `timedOut`: the navigation got no page in time.
1608
+ */
1609
+ async networkDetail(rawUrl, timedOut = false) {
1610
+ if (this.proxy === void 0) return "";
1611
+ let url;
1612
+ try {
1613
+ url = new URL(rawUrl);
1614
+ } catch {
1615
+ return "";
1616
+ }
1617
+ const host = url.hostname;
1618
+ const port = Number(url.port || (url.protocol === "https:" ? 443 : 80));
1619
+ switch (await probeProxy(this.proxy, host, port)) {
1620
+ case "unreachable":
1621
+ return `the device's network could not connect to ${host}:${port} (the name did not resolve, or the host refused or did not answer the connection).`;
1622
+ case "no_answer":
1623
+ return `the device's network got no answer from ${host}:${port}.`;
1624
+ case "connected":
1625
+ return timedOut ? `${host} accepted the connection through the device's network but sent no page in that time.` : `the device's network connects to ${host}:${port}, but the connection failed.`;
1626
+ case "refused":
1627
+ return `the device's network settings block ${host}.`;
1628
+ default:
1629
+ return "";
1630
+ }
1631
+ }
1100
1632
  async exec(req) {
1101
1633
  switch (req.op) {
1102
1634
  case "navigate": {
@@ -1104,12 +1636,20 @@ var BrowserSession = class {
1104
1636
  if (req.url !== void 0) {
1105
1637
  await this.goto(page, normalizeUrl(req.url));
1106
1638
  } else if (req.action === "back" || req.action === "forward") {
1107
- const r = await (req.action === "back" ? page.goBack() : page.goForward());
1639
+ const r = await (req.action === "back" ? page.goBack() : page.goForward()).catch(
1640
+ async (e) => {
1641
+ if (isTimeout(e)) throw await this.navigationTimedOut(page, page.url());
1642
+ throw e;
1643
+ }
1644
+ );
1108
1645
  if (r === null && page.url() === "about:blank") {
1109
1646
  return { text: `No ${req.action === "back" ? "earlier" : "later"} page in this tab.` };
1110
1647
  }
1111
1648
  } else if (req.action === "reload") {
1112
- await page.reload({ waitUntil: "domcontentloaded" });
1649
+ await page.reload({ waitUntil: "domcontentloaded" }).catch(async (e) => {
1650
+ if (isTimeout(e)) throw await this.navigationTimedOut(page, page.url());
1651
+ throw e;
1652
+ });
1113
1653
  } else {
1114
1654
  throw new ActionError(
1115
1655
  "failed",
@@ -1169,9 +1709,9 @@ var BrowserSession = class {
1169
1709
  }
1170
1710
  case "upload": {
1171
1711
  const page = await this.activePage();
1172
- const path = this.uploadPath(req.path);
1712
+ const file = this.readUpload(req.path);
1173
1713
  const loc = await this.locate(page, req.ref);
1174
- await loc.setInputFiles(path);
1714
+ await loc.setInputFiles(file);
1175
1715
  return {};
1176
1716
  }
1177
1717
  case "click_at":
@@ -1219,7 +1759,7 @@ var BrowserSession = class {
1219
1759
  async tabsOp(req) {
1220
1760
  switch (req.action) {
1221
1761
  case "list": {
1222
- await this.activePage();
1762
+ if (this.pages.size === 0) await this.activePage();
1223
1763
  const lines = await Promise.all(
1224
1764
  [...this.pages.entries()].map(async ([id, p]) => {
1225
1765
  const info = await this.pageInfo(p);
@@ -1337,15 +1877,33 @@ var BrowserSession = class {
1337
1877
  };
1338
1878
 
1339
1879
  // daemon/chromium.ts
1340
- import { existsSync, readFileSync } from "node:fs";
1880
+ import {
1881
+ accessSync,
1882
+ constants,
1883
+ existsSync,
1884
+ lstatSync as lstatSync2,
1885
+ readdirSync as readdirSync2,
1886
+ readFileSync,
1887
+ writeFileSync
1888
+ } from "node:fs";
1341
1889
  import { createRequire } from "node:module";
1342
- import { dirname, join as join2 } from "node:path";
1890
+ import { dirname, isAbsolute, join as join2, relative } from "node:path";
1343
1891
  import { fileURLToPath } from "node:url";
1892
+ var SERVICE_MACH_ENV = DEVICE_SERVICE_MACH_ENV;
1893
+ var HEADLESS_SHELL_NOTE = "The browser runs as a headless shell, which sites flag as a bot more often: the machine's capybara-device predates the full browser; ask the user to update capybara-device on that machine.";
1894
+ function chromiumBuild(platform, env = process.env) {
1895
+ if (platform !== "darwin") return "chromium";
1896
+ return env[SERVICE_MACH_ENV] === DEVICE_SERVICE_MACH_CHROMIUM ? "chromium" : "chromium-headless-shell";
1897
+ }
1898
+ var BUILD_DIR = {
1899
+ chromium: "chromium",
1900
+ "chromium-headless-shell": "chromium_headless_shell"
1901
+ };
1344
1902
  function envValue(env, name) {
1345
1903
  const v = env[name] ?? env[name.toLowerCase()];
1346
1904
  return v === void 0 || v === "" ? void 0 : v;
1347
1905
  }
1348
- function headlessShellRevision() {
1906
+ function browserRelease(build) {
1349
1907
  const candidates = [new URL("./vendor/playwright-core/browsers.json", import.meta.url)];
1350
1908
  try {
1351
1909
  const pkg = createRequire(import.meta.url).resolve("playwright-core/package.json");
@@ -1355,13 +1913,25 @@ function headlessShellRevision() {
1355
1913
  for (const file of candidates) {
1356
1914
  try {
1357
1915
  const json = JSON.parse(readFileSync(fileURLToPath(file), "utf8"));
1358
- const rev = json.browsers?.find((b) => b.name === "chromium-headless-shell")?.revision;
1359
- if (typeof rev === "string" && rev !== "") return rev;
1916
+ const b = json.browsers?.find((x) => x.name === build);
1917
+ if (typeof b?.revision === "string" && b.revision !== "")
1918
+ return {
1919
+ revision: b.revision,
1920
+ version: typeof b.browserVersion === "string" ? b.browserVersion : ""
1921
+ };
1360
1922
  } catch {
1361
1923
  }
1362
1924
  }
1363
1925
  return void 0;
1364
1926
  }
1927
+ function browserRevision(build) {
1928
+ return browserRelease(build)?.revision;
1929
+ }
1930
+ function chromeUserAgent(platform, version) {
1931
+ const major = /^\d+/.exec(version)?.[0] ?? "0";
1932
+ const os = platform === "darwin" ? "Macintosh; Intel Mac OS X 10_15_7" : platform === "win32" ? "Windows NT 10.0; Win64; x64" : "X11; Linux x86_64";
1933
+ return `Mozilla/5.0 (${os}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${major}.0.0.0 Safari/537.36`;
1934
+ }
1365
1935
  function playwrightDownloadHosts(env) {
1366
1936
  const custom = envValue(env, "PLAYWRIGHT_CHROMIUM_DOWNLOAD_HOST") ?? envValue(env, "PLAYWRIGHT_DOWNLOAD_HOST");
1367
1937
  if (custom !== void 0) {
@@ -1373,15 +1943,105 @@ function playwrightDownloadHosts(env) {
1373
1943
  }
1374
1944
  return ["cdn.playwright.dev", "playwright.download.prss.microsoft.com", "storage.googleapis.com"];
1375
1945
  }
1376
- function browsersPathFor(stateDir, env, revision) {
1946
+ var MAX_REVISION_SKEW = 10;
1947
+ function shippedRevisionNote(dir, revision) {
1948
+ return `The browser runs ${dir} from the device image, not ${revision === void 0 ? "this plugin's" : `revision ${revision}`}: ask the user to recreate the device on the current image when convenient.`;
1949
+ }
1950
+ var BROWSER_UNAVAILABLE_MESSAGE = "This device offers the browser no place it cannot rewrite: on a local device, update capybara-device on that machine; on a cloud device, its image predates the pinned browser, so ask the user to delete the device and create it again (or wait until it is recreated after a period without use).";
1951
+ var SERVICE_INSTALL_ENV = "CAPYBARA_SERVICE_INSTALL";
1952
+ var SERVICE_INSTALL_SEAL = ".sealed";
1953
+ var BrowserInstalledError = class extends Error {
1954
+ constructor() {
1955
+ super("The browser was installed; the browser service restarts to run it read only.");
1956
+ this.name = "BrowserInstalledError";
1957
+ }
1958
+ };
1959
+ function inside(dir, root) {
1960
+ const rel = relative(root, dir);
1961
+ return rel === "" || !rel.startsWith("..") && !isAbsolute(rel);
1962
+ }
1963
+ function readOnlyForUs(dir) {
1964
+ try {
1965
+ accessSync(dir, constants.W_OK);
1966
+ return false;
1967
+ } catch {
1968
+ return true;
1969
+ }
1970
+ }
1971
+ function browsersPathFor(stateDir, env, revision, build) {
1972
+ const install = envValue(env, SERVICE_INSTALL_ENV);
1973
+ if (install !== void 0 && isAbsolute(install)) {
1974
+ let sealed = false;
1975
+ try {
1976
+ sealed = lstatSync2(join2(install, SERVICE_INSTALL_SEAL)).isFile();
1977
+ } catch {
1978
+ sealed = false;
1979
+ }
1980
+ return { browsersPath: install, install: { sealed } };
1981
+ }
1377
1982
  const cache = envValue(env, "PLAYWRIGHT_BROWSERS_PATH");
1378
- if (cache !== void 0 && revision !== void 0 && existsSync(join2(cache, `chromium_headless_shell-${revision}`)))
1379
- return cache;
1380
- return join2(stateDir, "browsers");
1983
+ const workspace = envValue(env, "CAPYBARA_SERVICE_WORKSPACE");
1984
+ if (cache !== void 0 && isAbsolute(cache) && (workspace === void 0 || !inside(cache, workspace)) && readOnlyForUs(cache)) {
1985
+ if (revision !== void 0 && existsSync(join2(cache, `${BUILD_DIR[build]}-${revision}`)))
1986
+ return { browsersPath: cache, shipped: true };
1987
+ const near = shippedRevisions(cache, build).filter(
1988
+ (d) => revision !== void 0 && Math.abs(Number(d.slice(BUILD_DIR[build].length + 1)) - Number(revision)) <= MAX_REVISION_SKEW
1989
+ );
1990
+ const newest = near.at(-1);
1991
+ if (newest !== void 0) return { browsersPath: cache, shipped: true, shippedDir: newest };
1992
+ }
1993
+ return { browsersPath: join2(stateDir, "browsers"), unavailable: BROWSER_UNAVAILABLE_MESSAGE };
1381
1994
  }
1382
- function chromiumLaunchPlan(opts, revision = headlessShellRevision()) {
1383
- const args = ["--headless", "--use-mock-keychain"];
1384
- if (opts.platform === "darwin") args.push("--single-process");
1995
+ function shippedRevisions(cache, build) {
1996
+ const re = new RegExp(`^${BUILD_DIR[build]}-(\\d+)$`);
1997
+ let names;
1998
+ try {
1999
+ names = readdirSync2(cache);
2000
+ } catch {
2001
+ return [];
2002
+ }
2003
+ return names.map((n) => ({ n, rev: Number(re.exec(n)?.[1] ?? Number.NaN) })).filter((x) => Number.isFinite(x.rev)).sort((a, b) => a.rev - b.rev).map((x) => x.n);
2004
+ }
2005
+ var PLAYWRIGHT_DISABLED_FEATURES = [
2006
+ "AvoidUnnecessaryBeforeUnloadCheckSync",
2007
+ "DestroyProfileOnBrowserClose",
2008
+ "HttpsUpgrades",
2009
+ "HttpsFirstBalancedModeAutoEnable",
2010
+ "LensOverlay",
2011
+ "MediaRouter",
2012
+ "PaintHolding",
2013
+ "ThirdPartyStoragePartitioning",
2014
+ "AvoidCorsURLLoaderRestartOnRedirect",
2015
+ "TcpPortRandomizationWin",
2016
+ "OptimizationHints",
2017
+ "NetworkTimeServiceQuerying",
2018
+ "AimEnabled",
2019
+ "PreconnectToSearch",
2020
+ "msForceBrowserSignIn",
2021
+ "msEdgeUpdateLaunchServicesPreferredVersion"
2022
+ ];
2023
+ var DISABLED_FEATURES = [...PLAYWRIGHT_DISABLED_FEATURES, "AcceptCHFrame"];
2024
+ function chromiumLaunchPlan(opts, release = browserRelease(
2025
+ chromiumBuild(opts.platform, opts.env)
2026
+ )) {
2027
+ const build = chromiumBuild(opts.platform, opts.env);
2028
+ const args = [
2029
+ "--headless",
2030
+ "--use-mock-keychain",
2031
+ `--window-size=${VIEWPORT.width},${VIEWPORT.height}`,
2032
+ `--user-agent=${chromeUserAgent(opts.platform, release?.version ?? "")}`,
2033
+ `--disable-features=${DISABLED_FEATURES.join(",")}`,
2034
+ // Chrome reloads a network error page by itself (after 1 s, then backing off): that reload
2035
+ // aborts the agent's next navigation in the tab and asks the proxy for the failed host again
2036
+ "--disable-auto-reload"
2037
+ ];
2038
+ if (build === "chromium-headless-shell") args.push("--single-process");
2039
+ let env;
2040
+ if (opts.platform === "darwin") {
2041
+ args.push("--disable-crash-reporter", "--disable-breakpad");
2042
+ const tmp = envValue(opts.env, "TMPDIR");
2043
+ if (tmp !== void 0) env = { MAC_CHROMIUM_TMPDIR: tmp };
2044
+ }
1385
2045
  const proxy = envValue(opts.env, "HTTPS_PROXY") ?? envValue(opts.env, "HTTP_PROXY");
1386
2046
  let proxyAuth;
1387
2047
  if (proxy !== void 0) {
@@ -1406,7 +2066,9 @@ function chromiumLaunchPlan(opts, revision = headlessShellRevision()) {
1406
2066
  }
1407
2067
  }
1408
2068
  return {
1409
- browsersPath: opts.browsersPath ?? browsersPathFor(opts.stateDir, opts.env, revision),
2069
+ ...opts.browsersPath === void 0 ? browsersPathFor(opts.stateDir, opts.env, release?.revision, build) : { browsersPath: opts.browsersPath },
2070
+ build,
2071
+ ...env === void 0 ? {} : { env },
1410
2072
  profileDir: join2(opts.stateDir, "profile"),
1411
2073
  downloadsTmp: join2(opts.stateDir, "downloads-tmp"),
1412
2074
  args,
@@ -1429,30 +2091,44 @@ async function loadPlaywright(browsersPath) {
1429
2091
  loaded = { browsersPath, pw: pw.default ?? pw };
1430
2092
  return loaded.pw;
1431
2093
  }
1432
- async function headlessShell(browsersPath) {
2094
+ async function registryBrowser(browsersPath, build) {
1433
2095
  await loadPlaywright(browsersPath);
1434
2096
  const mod = await import("./vendor/playwright-core/lib/coreBundle.js");
1435
2097
  const registry = (mod.registry ?? mod.default?.registry)?.registry;
1436
2098
  if (registry === void 0) throw new Error("playwright-core has no browser registry");
1437
- const exe = registry.findExecutable("chromium-headless-shell");
1438
- if (exe === void 0) throw new Error("playwright-core does not know chromium-headless-shell");
2099
+ const exe = registry.findExecutable(build);
2100
+ if (exe === void 0) throw new Error(`playwright-core does not know ${build}`);
1439
2101
  const executablePath = exe.executablePath();
1440
2102
  if (executablePath === void 0 || exe.directory === void 0)
1441
- throw new Error("playwright-core has no chromium-headless-shell for this platform");
2103
+ throw new Error(`playwright-core has no ${build} for this platform`);
1442
2104
  return { registry, exe, executablePath, directory: exe.directory };
1443
2105
  }
1444
- async function ensureChromium(browsersPath) {
1445
- const { registry, exe, executablePath, directory } = await headlessShell(browsersPath);
2106
+ async function ensureChromium(browsersPath, install = true, build = chromiumBuild(process.platform), fresh = false) {
2107
+ const { registry, exe, executablePath, directory } = await registryBrowser(browsersPath, build);
1446
2108
  const marked = existsSync(join2(directory, "INSTALLATION_COMPLETE"));
1447
- if (marked && existsSync(executablePath)) return executablePath;
1448
- await registry.install([exe], { gc: false, force: marked });
2109
+ if (!fresh && marked && existsSync(executablePath)) return executablePath;
2110
+ if (!install)
2111
+ throw new Error(
2112
+ `the browser in ${browsersPath} is incomplete and read only for the browser service; delete the device and create it again`
2113
+ );
2114
+ await registry.install([exe], { gc: false, force: marked || fresh });
1449
2115
  if (!existsSync(executablePath)) {
1450
2116
  throw new Error("the Chromium download finished without an executable");
1451
2117
  }
1452
2118
  return executablePath;
1453
2119
  }
1454
2120
  async function launchChromium(plan) {
1455
- const executablePath = await ensureChromium(plan.browsersPath);
2121
+ if (plan.unavailable !== void 0) throw new Error(plan.unavailable);
2122
+ if (plan.install?.sealed === false) {
2123
+ await ensureChromium(plan.browsersPath, true, plan.build, true);
2124
+ sealInstall(plan.browsersPath);
2125
+ throw new BrowserInstalledError();
2126
+ }
2127
+ const executablePath = plan.shippedDir === void 0 ? await ensureChromium(
2128
+ plan.browsersPath,
2129
+ plan.install === void 0 && plan.shipped !== true,
2130
+ plan.build
2131
+ ) : await shippedExecutable(plan.browsersPath, plan.shippedDir, plan.build);
1456
2132
  const pw = await loadPlaywright(plan.browsersPath);
1457
2133
  return pw.chromium.launchPersistentContext(plan.profileDir, {
1458
2134
  headless: true,
@@ -1462,9 +2138,26 @@ async function launchChromium(plan) {
1462
2138
  // downloads are saved into the workspace by the session (actions.ts)
1463
2139
  acceptDownloads: true,
1464
2140
  downloadsPath: plan.downloadsTmp,
1465
- ...plan.proxyAuth === void 0 ? {} : { proxy: plan.proxyAuth }
2141
+ ...plan.proxyAuth === void 0 ? {} : { proxy: plan.proxyAuth },
2142
+ ...plan.env === void 0 ? {} : { env: { ...process.env, ...plan.env } }
1466
2143
  });
1467
2144
  }
2145
+ async function shippedExecutable(cache, dir, build) {
2146
+ const { executablePath, directory } = await registryBrowser(cache, build);
2147
+ const path = join2(cache, dir, relative(directory, executablePath));
2148
+ if (!existsSync(path))
2149
+ throw new Error(
2150
+ `the browser shipped in ${join2(cache, dir)} has no executable; ${BROWSER_UNAVAILABLE_MESSAGE}`
2151
+ );
2152
+ return path;
2153
+ }
2154
+ function sealInstall(dir) {
2155
+ try {
2156
+ writeFileSync(join2(dir, SERVICE_INSTALL_SEAL), "", { flag: "wx", mode: 420 });
2157
+ } catch (e) {
2158
+ if (e.code !== "EEXIST") throw e;
2159
+ }
2160
+ }
1468
2161
  async function browserProcessId(ctx) {
1469
2162
  const browser = ctx.browser();
1470
2163
  if (browser === null) return void 0;
@@ -1491,10 +2184,49 @@ function killChromium(pid) {
1491
2184
  }
1492
2185
  }
1493
2186
  }
2187
+ function processAlive(pid) {
2188
+ try {
2189
+ process.kill(pid, 0);
2190
+ return true;
2191
+ } catch (e) {
2192
+ return e.code === "EPERM";
2193
+ }
2194
+ }
1494
2195
 
1495
- // daemon/session-file.ts
1496
- import { readFileSync as readFileSync2, renameSync, rmSync, writeFileSync } from "node:fs";
2196
+ // daemon/cookie-file.ts
2197
+ import { readFileSync as readFileSync2, renameSync, rmSync, writeFileSync as writeFileSync2 } from "node:fs";
1497
2198
  import { join as join3 } from "node:path";
2199
+ var key = (c) => `${c.domain}
2200
+ ${c.path}
2201
+ ${c.name}`;
2202
+ async function saveCookies(ctx, stateDir) {
2203
+ try {
2204
+ const cookies = (await ctx.cookies()).filter((c) => c.expires > 0);
2205
+ const file = join3(stateDir, "cookies.json");
2206
+ writeFileSync2(`${file}.tmp`, JSON.stringify(cookies), { mode: 384 });
2207
+ renameSync(`${file}.tmp`, file);
2208
+ } catch {
2209
+ }
2210
+ }
2211
+ async function restoreCookies(ctx, stateDir) {
2212
+ try {
2213
+ const saved = JSON.parse(readFileSync2(join3(stateDir, "cookies.json"), "utf8"));
2214
+ if (!Array.isArray(saved)) return;
2215
+ const have = new Set((await ctx.cookies()).map(key));
2216
+ const now = Date.now() / 1e3;
2217
+ const missing = saved.filter(
2218
+ (c) => typeof c?.name === "string" && typeof c.domain === "string" && typeof c.path === "string" && typeof c.value === "string" && typeof c.expires === "number" && c.expires > now && !have.has(key(c))
2219
+ );
2220
+ if (missing.length > 0) await ctx.addCookies(missing);
2221
+ } catch {
2222
+ } finally {
2223
+ rmSync(join3(stateDir, "cookies.json"), { force: true });
2224
+ }
2225
+ }
2226
+
2227
+ // daemon/session-file.ts
2228
+ import { readFileSync as readFileSync3, renameSync as renameSync2, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "node:fs";
2229
+ import { join as join4 } from "node:path";
1498
2230
  var RESTORE_MAX_AGE_MS = 10 * 6e4;
1499
2231
  var SessionFile = class {
1500
2232
  file;
@@ -1502,14 +2234,14 @@ var SessionFile = class {
1502
2234
  queued = false;
1503
2235
  forgotten = false;
1504
2236
  constructor(stateDir, clock) {
1505
- this.file = join3(stateDir, "session.json");
2237
+ this.file = join4(stateDir, "session.json");
1506
2238
  this.clock = clock;
1507
2239
  }
1508
2240
  /** The saved session when it is recent and well formed; undefined otherwise. */
1509
2241
  read() {
1510
2242
  let raw;
1511
2243
  try {
1512
- raw = JSON.parse(readFileSync2(this.file, "utf8"));
2244
+ raw = JSON.parse(readFileSync3(this.file, "utf8"));
1513
2245
  } catch {
1514
2246
  return void 0;
1515
2247
  }
@@ -1552,8 +2284,8 @@ var SessionFile = class {
1552
2284
  ...handoff === void 0 ? {} : { handoff }
1553
2285
  };
1554
2286
  try {
1555
- writeFileSync(`${this.file}.tmp`, JSON.stringify(body), { mode: 384 });
1556
- renameSync(`${this.file}.tmp`, this.file);
2287
+ writeFileSync3(`${this.file}.tmp`, JSON.stringify(body), { mode: 384 });
2288
+ renameSync2(`${this.file}.tmp`, this.file);
1557
2289
  } catch {
1558
2290
  }
1559
2291
  });
@@ -1561,7 +2293,7 @@ var SessionFile = class {
1561
2293
  /** Removes the file and stops saving (an idle stop). */
1562
2294
  forget() {
1563
2295
  this.forgotten = true;
1564
- rmSync(this.file, { force: true });
2296
+ rmSync2(this.file, { force: true });
1565
2297
  }
1566
2298
  /**
1567
2299
  * Opens the saved tabs in a browser that has only its first blank tab. The navigations are
@@ -1583,10 +2315,300 @@ var SessionFile = class {
1583
2315
  }
1584
2316
  };
1585
2317
 
2318
+ // daemon/cursor.ts
2319
+ var CURSOR_MAX_FRAMES = 20;
2320
+ var MAX_DEPTH = 3;
2321
+ var WORLD = "capybara-cursor";
2322
+ var CURSOR_FUNCTION = `function (x, y) {
2323
+ const el = this.nodeType === 1 ? this : this.parentElement;
2324
+ if (!el) return { cursor: "default" };
2325
+ if (el.tagName === "IFRAME" || el.tagName === "FRAME") return { frame: true };
2326
+ const doc = el.ownerDocument;
2327
+ const view = doc.defaultView;
2328
+ const style = view.getComputedStyle(el);
2329
+ // "url(a.cur) 4 4, pointer": an image cursor's keyword fallback is the last item
2330
+ const parts = String(style.cursor).split(",");
2331
+ const cursor = parts[parts.length - 1].trim();
2332
+ if (cursor !== "auto") return { cursor };
2333
+ const NOT_TEXT = ["button", "submit", "reset", "checkbox", "radio", "range", "color", "file", "image", "hidden"];
2334
+ const tag = el.tagName;
2335
+ const editable = el.isContentEditable || tag === "TEXTAREA" ||
2336
+ (tag === "INPUT" && !NOT_TEXT.includes(String(el.type).toLowerCase()));
2337
+ if (editable && !el.disabled) return { cursor: "text" };
2338
+ if (style.userSelect === "none") return { cursor: "default" };
2339
+ const range = doc.caretRangeFromPoint ? doc.caretRangeFromPoint(x, y) : null;
2340
+ const node = range ? range.startContainer : null;
2341
+ if (!node || node.nodeType !== 3) return { cursor: "default" };
2342
+ const probe = doc.createRange();
2343
+ for (const [a, b] of [[range.startOffset, range.startOffset + 1], [range.startOffset - 1, range.startOffset]]) {
2344
+ if (a < 0 || b > node.length) continue;
2345
+ probe.setStart(node, a);
2346
+ probe.setEnd(node, b);
2347
+ for (const r of probe.getClientRects())
2348
+ if (x >= r.left && x <= r.right && y >= r.top && y <= r.bottom) return { cursor: "text" };
2349
+ }
2350
+ return { cursor: "default" };
2351
+ }`;
2352
+ var CursorResolver = class {
2353
+ constructor(context, page, cdp) {
2354
+ this.context = context;
2355
+ this.page = page;
2356
+ this.cdp = cdp;
2357
+ page.on("framedetached", this.onFrameDetached);
2358
+ }
2359
+ context;
2360
+ page;
2361
+ cdp;
2362
+ /** Isolated world execution contexts, per CDP session and frame id. */
2363
+ worlds = /* @__PURE__ */ new WeakMap();
2364
+ /** Sessions of out-of-process frames entered, detached with their frame or on dispose. */
2365
+ sessions = /* @__PURE__ */ new Map();
2366
+ onFrameDetached = (frame) => {
2367
+ const cdp = this.sessions.get(frame);
2368
+ if (cdp === void 0) return;
2369
+ this.sessions.delete(frame);
2370
+ cdp.detach().catch(() => void 0);
2371
+ };
2372
+ /** How many out-of-process frame sessions are open (a test seam). */
2373
+ get openSessions() {
2374
+ return this.sessions.size;
2375
+ }
2376
+ /** Detaches the frame sessions this resolver opened (the viewer detached from the page). */
2377
+ dispose() {
2378
+ this.page.off("framedetached", this.onFrameDetached);
2379
+ for (const cdp of this.sessions.values()) cdp.detach().catch(() => void 0);
2380
+ this.sessions.clear();
2381
+ }
2382
+ /** The cursor Chromium would show at viewport point (x, y). */
2383
+ async at(x, y) {
2384
+ let cdp = this.cdp;
2385
+ let frame = this.page.mainFrame();
2386
+ let px = x;
2387
+ let py = y;
2388
+ for (let depth = 0; depth <= MAX_DEPTH; depth++) {
2389
+ const hit = await this.hitTest(cdp, px, py);
2390
+ const answer = await this.answerAt(cdp, hit, px, py);
2391
+ if (answer.cursor !== void 0) return toViewerCursor(answer.cursor);
2392
+ if (!answer.frame || depth === MAX_DEPTH) return "default";
2393
+ const box = await cdp.send("DOM.getBoxModel", { backendNodeId: hit.backendNodeId });
2394
+ const [left = 0, top = 0] = box.model.content;
2395
+ const [borderLeft = 0, borderTop = 0] = box.model.border;
2396
+ const child = await this.childAt(frame, borderLeft + (x - px), borderTop + (y - py));
2397
+ if (child === void 0) return "default";
2398
+ frame = child.frame;
2399
+ cdp = child.cdp;
2400
+ px = px - left;
2401
+ py = py - top;
2402
+ }
2403
+ return "default";
2404
+ }
2405
+ async hitTest(cdp, x, y) {
2406
+ return await cdp.send("DOM.getNodeForLocation", {
2407
+ x: Math.round(x),
2408
+ y: Math.round(y),
2409
+ includeUserAgentShadowDOM: false,
2410
+ ignorePointerEventsNone: false
2411
+ });
2412
+ }
2413
+ /** The answer for a hit node, at the point in the node's own frame. */
2414
+ async answerAt(cdp, hit, x, y) {
2415
+ const frameId = hit.frameId ?? await this.mainFrameId(cdp);
2416
+ const offset = await this.frameOffset(cdp, frameId);
2417
+ return this.run(cdp, frameId, hit.backendNodeId, x - offset.x, y - offset.y);
2418
+ }
2419
+ async run(cdp, frameId, backendNodeId, x, y) {
2420
+ for (let attempt = 0; attempt < 2; attempt++) {
2421
+ const contextId = await this.world(cdp, frameId, attempt > 0);
2422
+ try {
2423
+ const { object } = await cdp.send("DOM.resolveNode", {
2424
+ backendNodeId,
2425
+ executionContextId: contextId
2426
+ });
2427
+ if (object.objectId === void 0) return { cursor: "default" };
2428
+ const r = await cdp.send("Runtime.callFunctionOn", {
2429
+ objectId: object.objectId,
2430
+ functionDeclaration: CURSOR_FUNCTION,
2431
+ arguments: [{ value: x }, { value: y }],
2432
+ returnByValue: true
2433
+ });
2434
+ await cdp.send("Runtime.releaseObject", { objectId: object.objectId }).catch(() => {
2435
+ });
2436
+ return r.result.value ?? { cursor: "default" };
2437
+ } catch (e) {
2438
+ if (attempt > 0) throw e;
2439
+ }
2440
+ }
2441
+ return { cursor: "default" };
2442
+ }
2443
+ async world(cdp, frameId, fresh) {
2444
+ let byFrame = this.worlds.get(cdp);
2445
+ if (byFrame === void 0) {
2446
+ byFrame = /* @__PURE__ */ new Map();
2447
+ this.worlds.set(cdp, byFrame);
2448
+ }
2449
+ const known = byFrame.get(frameId);
2450
+ if (known !== void 0 && !fresh) return known;
2451
+ const { executionContextId } = await cdp.send("Page.createIsolatedWorld", {
2452
+ frameId,
2453
+ worldName: WORLD
2454
+ });
2455
+ byFrame.set(frameId, executionContextId);
2456
+ return executionContextId;
2457
+ }
2458
+ async mainFrameId(cdp) {
2459
+ const { frameTree } = await cdp.send("Page.getFrameTree");
2460
+ return frameTree.frame.id;
2461
+ }
2462
+ /** The offset of an in-process frame's viewport in the session's root (0 for its main frame). */
2463
+ async frameOffset(cdp, frameId) {
2464
+ if (frameId === await this.mainFrameId(cdp)) return { x: 0, y: 0 };
2465
+ const owner = await cdp.send("DOM.getFrameOwner", { frameId });
2466
+ const box = await cdp.send("DOM.getBoxModel", { backendNodeId: owner.backendNodeId });
2467
+ return { x: box.model.content[0] ?? 0, y: box.model.content[1] ?? 0 };
2468
+ }
2469
+ /**
2470
+ * The child frame of `parent` whose element's border box starts at (left, top), in the page's
2471
+ * (main frame) coordinates.
2472
+ */
2473
+ async childAt(parent, left, top) {
2474
+ for (const child of parent.childFrames().slice(0, CURSOR_MAX_FRAMES)) {
2475
+ const handle = await child.frameElement().catch(() => null);
2476
+ const box = await handle?.boundingBox().catch(() => null);
2477
+ await handle?.dispose();
2478
+ if (box === null || box === void 0) continue;
2479
+ if (Math.abs(box.x - left) > 3 || Math.abs(box.y - top) > 3) continue;
2480
+ let cdp = this.sessions.get(child);
2481
+ if (cdp === void 0) {
2482
+ cdp = await this.context.newCDPSession(child);
2483
+ this.sessions.set(child, cdp);
2484
+ }
2485
+ return { frame: child, cdp };
2486
+ }
2487
+ return void 0;
2488
+ }
2489
+ };
2490
+
2491
+ // daemon/viewer-pacing.ts
2492
+ var TARGET_LINK_MS = 120;
2493
+ var PING_WINDOW = 10;
2494
+ var RTT_WINDOW = 16;
2495
+ var LINK_ALPHA = 0.5;
2496
+ var FramePacer = class {
2497
+ minIntervalMs;
2498
+ maxUnacked;
2499
+ inFlight = [];
2500
+ pings = [];
2501
+ rtts = [];
2502
+ lastSentAt = Number.NEGATIVE_INFINITY;
2503
+ link;
2504
+ constructor(opts) {
2505
+ this.minIntervalMs = 1e3 / opts.maxFps;
2506
+ this.maxUnacked = opts.maxUnacked;
2507
+ }
2508
+ /** The smoothed time frames take over the path's own round trip; undefined before any ack. */
2509
+ get linkMs() {
2510
+ return this.link;
2511
+ }
2512
+ get unacked() {
2513
+ return this.inFlight.length;
2514
+ }
2515
+ /** The path's round trip without queueing, as far as measured. */
2516
+ get baseRttMs() {
2517
+ if (this.pings.length > 0) return Math.min(...this.pings);
2518
+ if (this.rtts.length > 0) return Math.min(...this.rtts);
2519
+ return void 0;
2520
+ }
2521
+ /** Whether a frame may be sent at `now`, and if only the rate cap holds it, for how long. */
2522
+ decide(now) {
2523
+ const n = this.inFlight.length;
2524
+ if (n >= this.maxUnacked) return { ok: false };
2525
+ if (n > 0 && this.link !== void 0 && this.link > TARGET_LINK_MS) return { ok: false };
2526
+ const wait = this.lastSentAt + this.minIntervalMs - now;
2527
+ return wait > 0 ? { ok: false, waitMs: wait } : { ok: true };
2528
+ }
2529
+ /** Records a frame sent at `now` (every frame counts, the first after an attach too). */
2530
+ sent(seq, now) {
2531
+ this.inFlight.push({ seq, at: now });
2532
+ this.lastSentAt = now;
2533
+ }
2534
+ /** Records the viewer's ack of every frame up to `seq` at `now`; returns the sample, if any. */
2535
+ acked(seq, now) {
2536
+ let last;
2537
+ while (this.inFlight.length > 0 && this.inFlight[0].seq <= seq) {
2538
+ last = this.inFlight.shift();
2539
+ }
2540
+ if (last === void 0) return void 0;
2541
+ const rtt = Math.max(0, now - last.at);
2542
+ this.rtts.push(rtt);
2543
+ if (this.rtts.length > RTT_WINDOW) this.rtts.shift();
2544
+ const sample = Math.max(0, rtt - (this.baseRttMs ?? rtt));
2545
+ this.link = this.link === void 0 ? sample : this.link * (1 - LINK_ALPHA) + sample * LINK_ALPHA;
2546
+ return sample;
2547
+ }
2548
+ /** Records a ping's round trip (a tiny message both ways on the same path as the frames). */
2549
+ pinged(rttMs) {
2550
+ if (!Number.isFinite(rttMs) || rttMs < 0) return;
2551
+ this.pings.push(rttMs);
2552
+ if (this.pings.length > PING_WINDOW) this.pings.shift();
2553
+ }
2554
+ /** Forgets frames in flight (a screencast restart: their acks may never come). */
2555
+ reset() {
2556
+ this.inFlight.length = 0;
2557
+ }
2558
+ };
2559
+ var QUALITY_STEPS = [60, 45, 35, 25];
2560
+ var SHRINK_STEPS = [1, 0.8, 0.65, 0.5, 0.35, 0.25];
2561
+ var ADAPT_SHRINK_STEPS = 4;
2562
+ var UP_AFTER_QUICK_FRAMES = 6;
2563
+ var FrameQuality = class {
2564
+ step = 0;
2565
+ quick = 0;
2566
+ get quality() {
2567
+ return QUALITY_STEPS[Math.min(this.step, QUALITY_STEPS.length - 1)];
2568
+ }
2569
+ get shrink() {
2570
+ const s = Math.max(0, this.step - (QUALITY_STEPS.length - 1));
2571
+ return SHRINK_STEPS[Math.min(s, SHRINK_STEPS.length - 1)];
2572
+ }
2573
+ /** The lowest step the link adaptation goes to. */
2574
+ get adaptMaxStep() {
2575
+ return QUALITY_STEPS.length - 1 + ADAPT_SHRINK_STEPS - 1;
2576
+ }
2577
+ get maxStep() {
2578
+ return QUALITY_STEPS.length - 1 + SHRINK_STEPS.length - 1;
2579
+ }
2580
+ /** One acked frame's link time; true when the step changed (restart the screencast). */
2581
+ observe(linkMs) {
2582
+ if (linkMs > TARGET_LINK_MS * 1.25) {
2583
+ this.quick = 0;
2584
+ if (this.step >= this.adaptMaxStep) return false;
2585
+ this.step++;
2586
+ return true;
2587
+ }
2588
+ if (linkMs < TARGET_LINK_MS / 2) {
2589
+ this.quick++;
2590
+ if (this.quick >= UP_AFTER_QUICK_FRAMES && this.step > 0) {
2591
+ this.step--;
2592
+ this.quick = 0;
2593
+ return true;
2594
+ }
2595
+ } else this.quick = 0;
2596
+ return false;
2597
+ }
2598
+ /** A frame too large for one message: always one step smaller. */
2599
+ tooLarge() {
2600
+ this.quick = 0;
2601
+ if (this.step >= this.maxStep) return false;
2602
+ this.step++;
2603
+ return true;
2604
+ }
2605
+ };
2606
+
1586
2607
  // daemon/viewer.ts
1587
- var FRAME_JSON_OVERHEAD = 128;
1588
- var START_QUALITY = 60;
1589
- var MIN_QUALITY = 20;
2608
+ var VIEWER_PING_MS = 1e3;
2609
+ var RESTART_MIN_MS = 500;
2610
+ var ENCODE_MAX_INTERVAL_MS = 500;
2611
+ var CURSOR_TIMEOUT_MS = 200;
1590
2612
  var clampDim = (n, max) => typeof n === "number" && Number.isFinite(n) ? Math.max(16, Math.min(max, Math.floor(n))) : max;
1591
2613
  var ViewerSession = class {
1592
2614
  browser;
@@ -1597,9 +2619,13 @@ var ViewerSession = class {
1597
2619
  unsubscribe = [];
1598
2620
  maxWidth = VIEWPORT.width;
1599
2621
  maxHeight = VIEWPORT.height;
1600
- /** Lowered when a frame does not fit the message cap. */
1601
- quality = START_QUALITY;
1602
- shrink = 1;
2622
+ pacer = new FramePacer({
2623
+ maxFps: VIEWER_MAX_FPS,
2624
+ maxUnacked: VIEWER_UNACKED_FRAMES
2625
+ });
2626
+ /** Quality and scale: lowered while frames are slow on the link or over the message cap. */
2627
+ frameQuality = new FrameQuality();
2628
+ lastRestartAt = Number.NEGATIVE_INFINITY;
1603
2629
  started = false;
1604
2630
  closed = false;
1605
2631
  page;
@@ -1609,14 +2635,42 @@ var ViewerSession = class {
1609
2635
  inputChain = Promise.resolve();
1610
2636
  /** Bumped on close and hand back: input queued before it is dropped, not replayed. */
1611
2637
  inputGen = 0;
2638
+ /**
2639
+ * The newest pointer position not yet applied, while a move for it waits on the input chain:
2640
+ * later moves replace it (the newest wins) instead of queueing behind it.
2641
+ */
2642
+ moveSlot;
2643
+ /** The cursor last sent (reset when control returns to the agent). */
2644
+ cursor;
2645
+ /** Resolves cursors on the attached page (off the input chain, see {@link wantCursor}). */
2646
+ cursorResolver;
2647
+ /** The newest pointer position whose cursor is wanted; one resolution runs at a time. */
2648
+ cursorPoint;
2649
+ /** The resolver a resolution loop runs for (one loop per resolver, one lookup at a time). */
2650
+ cursorLoop;
2651
+ /**
2652
+ * Keys and buttons this viewer pressed and has not released: released for the agent when
2653
+ * control returns to it or the viewer ends, whatever reached the page of the person's input.
2654
+ */
2655
+ heldKeys = /* @__PURE__ */ new Map();
2656
+ heldButtons = /* @__PURE__ */ new Map();
1612
2657
  seq = 0;
1613
- acked = 0;
1614
- lastSentAt = 0;
1615
- /** A screencast frame waiting for room (viewer acks, transport, rate cap); acked once sent. */
2658
+ /**
2659
+ * The newest screencast frame waiting for room (viewer acks, transport, rate cap). A newer one
2660
+ * replaces it: a frame is never queued behind a stale one.
2661
+ */
1616
2662
  pending;
2663
+ /** Chromium frames received but not acked to Chromium yet (it encodes the next after an ack). */
2664
+ encodeAck;
2665
+ encodeTimer;
2666
+ lastEncodeAckAt = Number.NEGATIVE_INFINITY;
1617
2667
  pumpTimer;
2668
+ pingTimer;
2669
+ pingSeq = 0;
2670
+ pingsSent = /* @__PURE__ */ new Map();
1618
2671
  draining = false;
1619
2672
  stateQueued = false;
2673
+ lastControl = "agent";
1620
2674
  constructor(opts) {
1621
2675
  this.browser = opts.browser;
1622
2676
  this.state = opts.state;
@@ -1635,12 +2689,14 @@ var ViewerSession = class {
1635
2689
  if (m.t !== "hello") return;
1636
2690
  this.started = true;
1637
2691
  this.setSize(m.maxWidth, m.maxHeight);
2692
+ this.lastControl = this.state.control;
1638
2693
  this.unsubscribe.push(
1639
2694
  this.browser.on((e) => this.onSession(e)),
1640
- this.state.onChange(() => this.queueState())
2695
+ this.state.onChange(() => this.onControl())
1641
2696
  );
1642
2697
  this.sendState();
1643
2698
  void this.serial(() => this.attach());
2699
+ this.ping();
1644
2700
  return;
1645
2701
  }
1646
2702
  switch (m.t) {
@@ -1653,9 +2709,17 @@ var ViewerSession = class {
1653
2709
  });
1654
2710
  return;
1655
2711
  case "frame-ack":
1656
- if (typeof m.seq === "number" && m.seq > this.acked) this.acked = Math.min(m.seq, this.seq);
2712
+ if (typeof m.seq === "number") this.onAck(Math.min(m.seq, this.seq));
1657
2713
  this.pump();
1658
2714
  return;
2715
+ case "pong": {
2716
+ const sentAt = typeof m.id === "number" ? this.pingsSent.get(m.id) : void 0;
2717
+ if (sentAt !== void 0) {
2718
+ this.pingsSent.delete(m.id);
2719
+ this.pacer.pinged(this.clock.now() - sentAt);
2720
+ }
2721
+ return;
2722
+ }
1659
2723
  case "takeover":
1660
2724
  this.state.takeover();
1661
2725
  return;
@@ -1664,7 +2728,8 @@ var ViewerSession = class {
1664
2728
  this.state.handback();
1665
2729
  return;
1666
2730
  case "mouse":
1667
- this.input(() => this.mouse(m));
2731
+ if (m.kind === "move") this.move(m);
2732
+ else this.input(() => this.mouse(m));
1668
2733
  return;
1669
2734
  case "key":
1670
2735
  this.input(() => this.key(m));
@@ -1693,26 +2758,129 @@ var ViewerSession = class {
1693
2758
  return;
1694
2759
  }
1695
2760
  }
1696
- /** Runs viewer input in arrival order, apart from the screencast chain. */
2761
+ /**
2762
+ * Runs viewer input in arrival order, apart from the screencast chain, and only while the person
2763
+ * holds control: input from a viewer in the watch state (the agent drives) is dropped, both when
2764
+ * it arrives and when its turn comes.
2765
+ */
1697
2766
  input(fn) {
2767
+ if (this.state.control !== "user") return;
2768
+ this.moveSlot = void 0;
1698
2769
  const gen = this.inputGen;
1699
- const guarded = () => gen === this.inputGen && !this.closed ? fn() : Promise.resolve();
2770
+ const guarded = () => gen === this.inputGen && !this.closed && this.state.control === "user" ? fn() : Promise.resolve();
1700
2771
  const run = this.inputChain.then(guarded, guarded);
1701
2772
  this.inputChain = run.catch(() => void 0);
1702
2773
  }
2774
+ /** A pointer move: coalesced while one waits (the newest position wins), then the cursor. */
2775
+ move(m) {
2776
+ if (this.state.control !== "user") return;
2777
+ const p = point(m);
2778
+ if (p === null) return;
2779
+ if (this.moveSlot !== void 0) {
2780
+ this.moveSlot.x = p.x;
2781
+ this.moveSlot.y = p.y;
2782
+ return;
2783
+ }
2784
+ const slot = { ...p };
2785
+ this.input(async () => {
2786
+ if (this.moveSlot === slot) this.moveSlot = void 0;
2787
+ const page = await this.browser.activePage();
2788
+ try {
2789
+ await page.mouse.move(slot.x, slot.y);
2790
+ } catch {
2791
+ return;
2792
+ }
2793
+ this.wantCursor(slot.x, slot.y);
2794
+ });
2795
+ this.moveSlot = slot;
2796
+ }
2797
+ /**
2798
+ * Asks for the page's cursor at (x, y): resolved off the input chain (a click never waits for
2799
+ * it), the newest position wins while one resolution runs, and an answer later than
2800
+ * CURSOR_TIMEOUT_MS is dropped.
2801
+ */
2802
+ wantCursor(x, y) {
2803
+ this.cursorPoint = { x, y };
2804
+ const resolver = this.cursorResolver;
2805
+ if (resolver === void 0 || this.cursorLoop === resolver) return;
2806
+ this.cursorLoop = resolver;
2807
+ void (async () => {
2808
+ try {
2809
+ while (!this.closed && this.cursorResolver === resolver) {
2810
+ const p = this.cursorPoint;
2811
+ this.cursorPoint = void 0;
2812
+ if (p === void 0) return;
2813
+ const started = this.clock.now();
2814
+ const cursor = await resolver.at(p.x, p.y).catch(() => void 0);
2815
+ if (cursor === void 0 || this.clock.now() - started > CURSOR_TIMEOUT_MS) continue;
2816
+ if (this.cursorPoint !== void 0) continue;
2817
+ if (cursor === this.cursor || this.closed || this.state.control !== "user") continue;
2818
+ this.cursor = cursor;
2819
+ this.send({ t: "cursor", cursor });
2820
+ }
2821
+ } finally {
2822
+ if (this.cursorLoop === resolver) this.cursorLoop = void 0;
2823
+ }
2824
+ })();
2825
+ }
2826
+ /**
2827
+ * Releases the keys and buttons this viewer still holds (straight, not on the input chain and
2828
+ * not through the control gate): the agent must not inherit a held Shift or a drag.
2829
+ */
2830
+ async releaseHeld() {
2831
+ if (this.heldKeys.size === 0 && this.heldButtons.size === 0) return;
2832
+ const keys = [...this.heldKeys];
2833
+ const buttons = [...this.heldButtons];
2834
+ this.heldKeys.clear();
2835
+ this.heldButtons.clear();
2836
+ for (const [key2, page] of keys) await page.keyboard.up(key2).catch(() => void 0);
2837
+ for (const [button, page] of buttons) {
2838
+ await page.mouse.move(-1, -1).catch(() => void 0);
2839
+ await page.mouse.up({ button }).catch(() => void 0);
2840
+ }
2841
+ }
2842
+ /** Whether input this viewer applied should stay applied (still in control, not closed). */
2843
+ get driving() {
2844
+ return !this.closed && this.state.control === "user";
2845
+ }
1703
2846
  /** Ends the viewer: stops its screencast and its subscriptions. */
1704
2847
  async close() {
1705
2848
  if (this.closed) return;
1706
2849
  this.closed = true;
1707
2850
  this.inputGen++;
2851
+ await this.releaseHeld();
1708
2852
  for (const u of this.unsubscribe.splice(0)) u();
1709
- if (this.pumpTimer !== void 0) this.clock.cancel(this.pumpTimer);
2853
+ for (const t of [this.pumpTimer, this.pingTimer, this.encodeTimer])
2854
+ if (t !== void 0) this.clock.cancel(t);
1710
2855
  await this.serial(() => this.detach());
1711
2856
  }
1712
2857
  setSize(w, h) {
1713
2858
  this.maxWidth = clampDim(w, VIEWPORT.width);
1714
2859
  this.maxHeight = clampDim(h, VIEWPORT.height);
1715
- this.shrink = 1;
2860
+ }
2861
+ /** Pings the viewer every VIEWER_PING_MS (its pong measures the path, see the pacing). */
2862
+ ping() {
2863
+ if (this.closed) return;
2864
+ const id = ++this.pingSeq;
2865
+ this.pingsSent.set(id, this.clock.now());
2866
+ for (const old of this.pingsSent.keys()) if (old < id - 4) this.pingsSent.delete(old);
2867
+ this.send({ t: "ping", id });
2868
+ this.pingTimer = this.clock.schedule(() => this.ping(), VIEWER_PING_MS);
2869
+ }
2870
+ /** Control changed (takeover, hand back): a new state, and input of the old control dropped. */
2871
+ onControl() {
2872
+ const control = this.state.control;
2873
+ if (control !== this.lastControl) {
2874
+ this.lastControl = control;
2875
+ this.moveSlot = void 0;
2876
+ this.cursor = void 0;
2877
+ this.cursorPoint = void 0;
2878
+ if (control === "agent") {
2879
+ this.inputGen++;
2880
+ void this.releaseHeld();
2881
+ }
2882
+ }
2883
+ this.queueState();
1716
2884
  }
1717
2885
  serial(fn) {
1718
2886
  const run = this.chain.then(fn, fn);
@@ -1726,33 +2894,44 @@ var ViewerSession = class {
1726
2894
  */
1727
2895
  fitted(m) {
1728
2896
  const fits = (x) => Buffer.byteLength(JSON.stringify(x)) <= this.frameMaxBytes;
1729
- if (m.t === "frame" || fits(m)) return m;
2897
+ if (fits(m)) return m;
1730
2898
  let small;
1731
2899
  if (m.t === "state") {
2900
+ const plain = { ...m, tabs: m.tabs.map(({ favicon: _icon, ...t }) => t) };
2901
+ if (fits(plain)) return plain;
2902
+ m = plain;
1732
2903
  const handoff = m.handoff === void 0 ? {} : { handoff: { ...m.handoff, message: clip(m.handoff.message, 200) } };
1733
2904
  small = {
1734
2905
  ...m,
1735
- tabs: m.tabs.map((t) => ({ ...t, title: clip(t.title, 200), url: clip(t.url, 200) })),
2906
+ tabs: m.tabs.map((t) => ({
2907
+ ...t,
2908
+ title: clip(t.title, 200),
2909
+ url: clip(t.url, 200),
2910
+ ...t.blocker === void 0 ? {} : { blocker: { ...t.blocker, url: clip(t.blocker.url, 200) } }
2911
+ })),
1736
2912
  ...handoff
1737
2913
  };
1738
2914
  } else if (m.t === "dialog") {
1739
2915
  small = { ...m, message: clip(m.message, 200) };
1740
- } else {
2916
+ } else if (m.t === "blocked") {
1741
2917
  small = { ...m, url: clip(m.url, 200) };
1742
- }
2918
+ } else return null;
1743
2919
  return fits(small) ? small : null;
1744
2920
  }
2921
+ /** Sends a JSON message at once: it never waits behind a held frame. */
1745
2922
  send(raw) {
1746
2923
  if (this.closed) return;
1747
2924
  const m = this.fitted(raw);
1748
2925
  if (m === null) return;
1749
- if (!this.out.send(m) && !this.draining) {
1750
- this.draining = true;
1751
- this.out.whenDrained().then(() => {
1752
- this.draining = false;
1753
- this.pump();
1754
- });
1755
- }
2926
+ if (!this.out.send(m)) this.awaitDrain();
2927
+ }
2928
+ awaitDrain() {
2929
+ if (this.draining) return;
2930
+ this.draining = true;
2931
+ this.out.whenDrained().then(() => {
2932
+ this.draining = false;
2933
+ this.pump();
2934
+ });
1756
2935
  }
1757
2936
  onSession(e) {
1758
2937
  if (e.type === "state") this.queueState();
@@ -1791,11 +2970,11 @@ var ViewerSession = class {
1791
2970
  });
1792
2971
  }
1793
2972
  get scale() {
1794
- return Math.min(1, this.maxWidth / VIEWPORT.width, this.maxHeight / VIEWPORT.height) * this.shrink;
2973
+ return Math.min(1, this.maxWidth / VIEWPORT.width, this.maxHeight / VIEWPORT.height) * this.frameQuality.shrink;
1795
2974
  }
1796
- /** Room for the JPEG's decoded bytes in one frame message. */
2975
+ /** Room for the JPEG in one frame message. */
1797
2976
  get jpegBudget() {
1798
- return Math.floor((this.frameMaxBytes - FRAME_JSON_OVERHEAD) * 3 / 4);
2977
+ return this.frameMaxBytes - FRAME_HEADER_BYTES;
1799
2978
  }
1800
2979
  async attach() {
1801
2980
  if (this.closed) return;
@@ -1804,12 +2983,19 @@ var ViewerSession = class {
1804
2983
  this.page = page;
1805
2984
  this.cdp = cdp;
1806
2985
  cdp.on("Page.screencastFrame", (f) => this.onFrame(cdp, f));
2986
+ this.cursorResolver = new CursorResolver(this.browser.context, page, cdp);
1807
2987
  const first = await captureFitting(cdp, {
1808
2988
  maxBytes: this.jpegBudget,
1809
2989
  maxScale: this.scale
1810
2990
  }).catch(() => null);
1811
2991
  if (first !== null && this.cdp === cdp) {
1812
- this.sendFrame(first.data, first.width, first.height);
2992
+ this.pending = {
2993
+ cdp,
2994
+ jpeg: Buffer.from(first.data, "base64"),
2995
+ width: first.width,
2996
+ height: first.height
2997
+ };
2998
+ this.pump();
1813
2999
  }
1814
3000
  await this.startScreencast(cdp);
1815
3001
  }
@@ -1817,7 +3003,7 @@ var ViewerSession = class {
1817
3003
  if (this.closed || this.cdp !== cdp) return;
1818
3004
  await cdp.send("Page.startScreencast", {
1819
3005
  format: "jpeg",
1820
- quality: this.quality,
3006
+ quality: this.frameQuality.quality,
1821
3007
  maxWidth: Math.max(16, Math.floor(VIEWPORT.width * this.scale)),
1822
3008
  maxHeight: Math.max(16, Math.floor(VIEWPORT.height * this.scale)),
1823
3009
  everyNthFrame: 1
@@ -1828,94 +3014,159 @@ var ViewerSession = class {
1828
3014
  this.cdp = void 0;
1829
3015
  this.page = void 0;
1830
3016
  this.pending = void 0;
3017
+ this.encodeAck = void 0;
3018
+ this.cursorResolver?.dispose();
3019
+ this.cursorResolver = void 0;
1831
3020
  if (cdp === void 0) return;
1832
3021
  await cdp.send("Page.stopScreencast").catch(() => void 0);
1833
3022
  await cdp.detach().catch(() => void 0);
1834
3023
  }
1835
3024
  sendFrame(jpeg, width, height) {
1836
3025
  this.seq++;
1837
- this.lastSentAt = this.clock.now();
1838
- this.send({ t: "frame", seq: this.seq, jpeg, width, height });
3026
+ this.pacer.sent(this.seq, this.clock.now());
3027
+ if (!this.out.sendFrame(encodeFrame({ seq: this.seq, width, height, jpeg }))) this.awaitDrain();
3028
+ }
3029
+ /** The viewer acked frames up to `seq`: the link time adapts quality and scale. */
3030
+ onAck(seq) {
3031
+ const sample = this.pacer.acked(seq, this.clock.now());
3032
+ if (sample === void 0) return;
3033
+ if (this.clock.now() - this.lastRestartAt < RESTART_MIN_MS) return;
3034
+ if (this.frameQuality.observe(this.pacer.linkMs ?? sample)) this.restart();
3035
+ }
3036
+ /** Restarts the screencast at the current quality and scale. */
3037
+ restart() {
3038
+ const cdp = this.cdp;
3039
+ if (cdp === void 0) return;
3040
+ this.lastRestartAt = this.clock.now();
3041
+ this.pacer.reset();
3042
+ void this.serial(async () => {
3043
+ if (this.cdp !== cdp) return;
3044
+ await cdp.send("Page.stopScreencast").catch(() => void 0);
3045
+ this.pending = void 0;
3046
+ this.encodeAck = void 0;
3047
+ await this.startScreencast(cdp);
3048
+ });
1839
3049
  }
1840
3050
  onFrame(cdp, f) {
1841
3051
  if (this.closed || this.cdp !== cdp) return;
1842
3052
  const bytes = Buffer.from(f.data, "base64");
1843
3053
  if (bytes.length > this.jpegBudget) {
1844
3054
  cdp.send("Page.screencastFrameAck", { sessionId: f.sessionId }).catch(() => void 0);
1845
- if (this.quality > MIN_QUALITY) this.quality = Math.max(MIN_QUALITY, this.quality - 15);
1846
- else this.shrink *= 0.75;
1847
- void this.serial(async () => {
1848
- if (this.cdp !== cdp) return;
1849
- await cdp.send("Page.stopScreencast").catch(() => void 0);
1850
- await this.startScreencast(cdp);
1851
- });
3055
+ if (this.frameQuality.tooLarge()) this.restart();
1852
3056
  return;
1853
3057
  }
1854
3058
  const { width, height } = jpegSize(bytes);
1855
- this.pending = { cdp, sessionId: f.sessionId, data: f.data, width, height };
3059
+ this.pending = { cdp, jpeg: bytes, width, height };
3060
+ this.encodeAck = { cdp, sessionId: f.sessionId };
1856
3061
  this.pump();
3062
+ this.scheduleEncodeAck();
3063
+ }
3064
+ /**
3065
+ * Lets Chromium encode its next frame (screencastFrameAck): at most at the viewer's frame rate
3066
+ * while frames flow, and while one waits for the viewer only every ENCODE_MAX_INTERVAL_MS, so
3067
+ * the frame sent when room comes is a recent one without encoding frames nobody gets.
3068
+ */
3069
+ scheduleEncodeAck() {
3070
+ if (this.encodeTimer !== void 0) this.clock.cancel(this.encodeTimer);
3071
+ this.encodeTimer = void 0;
3072
+ const ack = this.encodeAck;
3073
+ if (ack === void 0 || this.closed) return;
3074
+ const gap = this.pending === void 0 ? 1e3 / VIEWER_MAX_FPS : ENCODE_MAX_INTERVAL_MS;
3075
+ const wait = this.lastEncodeAckAt + gap - this.clock.now();
3076
+ if (wait > 0) {
3077
+ this.encodeTimer = this.clock.schedule(() => {
3078
+ this.encodeTimer = void 0;
3079
+ this.scheduleEncodeAck();
3080
+ }, wait);
3081
+ return;
3082
+ }
3083
+ this.encodeAck = void 0;
3084
+ if (this.cdp !== ack.cdp) return;
3085
+ this.lastEncodeAckAt = this.clock.now();
3086
+ ack.cdp.send("Page.screencastFrameAck", { sessionId: ack.sessionId }).catch(() => void 0);
1857
3087
  }
1858
3088
  /**
1859
- * Sends the held screencast frame and acks it (letting Chromium send the next) once the viewer
1860
- * has room for it, the transport is not backed up and the rate cap allows: a frame never follows
1861
- * the previous one sooner than 1000 / VIEWER_MAX_FPS ms, the first after an attach included.
3089
+ * Sends the newest screencast frame once the pacer allows (viewer acks, link time, rate cap)
3090
+ * and the transport is not backed up.
1862
3091
  */
1863
3092
  pump() {
1864
3093
  const pending = this.pending;
1865
3094
  if (pending === void 0 || this.closed || this.draining) return;
1866
- if (this.seq - this.acked >= VIEWER_UNACKED_FRAMES) return;
1867
- const wait = this.lastSentAt + 1e3 / VIEWER_MAX_FPS - this.clock.now();
1868
- if (wait > 0) {
1869
- if (this.pumpTimer === void 0) {
3095
+ const d = this.pacer.decide(this.clock.now());
3096
+ if (!d.ok) {
3097
+ if (d.waitMs !== void 0 && this.pumpTimer === void 0) {
1870
3098
  this.pumpTimer = this.clock.schedule(() => {
1871
3099
  this.pumpTimer = void 0;
1872
3100
  this.pump();
1873
- }, wait);
3101
+ }, d.waitMs);
1874
3102
  }
1875
3103
  return;
1876
3104
  }
1877
3105
  this.pending = void 0;
1878
3106
  if (this.cdp !== pending.cdp) return;
1879
- this.sendFrame(pending.data, pending.width, pending.height);
1880
- pending.cdp.send("Page.screencastFrameAck", { sessionId: pending.sessionId }).catch(() => void 0);
3107
+ this.sendFrame(pending.jpeg, pending.width, pending.height);
3108
+ this.scheduleEncodeAck();
1881
3109
  }
1882
3110
  async mouse(m) {
1883
3111
  const page = await this.browser.activePage();
1884
- if (!Number.isFinite(Number(m.x)) || !Number.isFinite(Number(m.y))) return;
1885
- const x = Math.max(0, Math.min(VIEWPORT.width - 1, Number(m.x)));
1886
- const y = Math.max(0, Math.min(VIEWPORT.height - 1, Number(m.y)));
3112
+ const p = point(m);
3113
+ if (p === null) return;
3114
+ const { x, y } = p;
1887
3115
  const button = m.button === "right" ? "right" : "left";
1888
3116
  try {
1889
- if (m.kind === "move") await page.mouse.move(x, y);
1890
- else if (m.kind === "down") {
3117
+ if (m.kind === "down") {
1891
3118
  await page.mouse.move(x, y);
1892
3119
  await page.mouse.down({ button });
3120
+ if (this.driving) this.heldButtons.set(button, page);
3121
+ else await page.mouse.up({ button });
1893
3122
  } else if (m.kind === "up") {
3123
+ this.heldButtons.delete(button);
1894
3124
  await page.mouse.move(x, y);
1895
3125
  await page.mouse.up({ button });
1896
3126
  } else if (m.kind === "wheel") {
1897
3127
  await page.mouse.move(x, y);
1898
3128
  await page.mouse.wheel(Number(m.dx) || 0, Number(m.dy) || 0);
1899
- }
3129
+ } else return;
1900
3130
  } catch {
3131
+ return;
1901
3132
  }
3133
+ if (m.kind !== "down") this.wantCursor(x, y);
1902
3134
  }
1903
3135
  async key(m) {
1904
3136
  const page = await this.browser.activePage();
1905
3137
  try {
1906
3138
  if (m.kind === "char") {
1907
3139
  const text = m.text ?? m.key;
1908
- if (typeof text === "string" && text !== "") await page.keyboard.insertText(text);
1909
- } else if (m.kind === "down") await page.keyboard.down(m.key);
1910
- else if (m.kind === "up") await page.keyboard.up(m.key);
3140
+ if (typeof text === "string" && text !== "")
3141
+ await page.keyboard.insertText(clipCodePoints(text, VIEWER_TEXT_MAX_CHARS));
3142
+ } else if (m.kind === "down") {
3143
+ await page.keyboard.down(m.key);
3144
+ if (this.driving) this.heldKeys.set(m.key, page);
3145
+ else await page.keyboard.up(m.key);
3146
+ } else if (m.kind === "up") {
3147
+ this.heldKeys.delete(m.key);
3148
+ await page.keyboard.up(m.key);
3149
+ }
1911
3150
  } catch {
1912
3151
  }
1913
3152
  }
1914
3153
  };
3154
+ function point(m) {
3155
+ const x = Number(m.x);
3156
+ const y = Number(m.y);
3157
+ if (!Number.isFinite(x) || !Number.isFinite(y)) return null;
3158
+ return {
3159
+ x: Math.max(0, Math.min(VIEWPORT.width - 1, x)),
3160
+ y: Math.max(0, Math.min(VIEWPORT.height - 1, y))
3161
+ };
3162
+ }
1915
3163
 
1916
3164
  // daemon/main.ts
3165
+ var SEALED_EXIT_GRACE_MS = 2e3;
1917
3166
  var SERVICE_WORKSPACE_ENV = "CAPYBARA_SERVICE_WORKSPACE";
1918
3167
  var BROWSER_CLOSE_GRACE_MS = 3e3;
3168
+ var PROCESS_POLL_MS = 10;
3169
+ var COOKIE_SAVE_MS = 500;
1919
3170
  var enc = new TextEncoder();
1920
3171
  var dec = new TextDecoder();
1921
3172
  var REQUEST_OPS = /* @__PURE__ */ new Set([
@@ -1999,7 +3250,7 @@ async function startDaemon(opts) {
1999
3250
  let current;
2000
3251
  let running;
2001
3252
  let restored = false;
2002
- function within(value, ms) {
3253
+ function within2(value, ms) {
2003
3254
  let timer;
2004
3255
  return Promise.race([
2005
3256
  value,
@@ -2041,9 +3292,9 @@ async function startDaemon(opts) {
2041
3292
  if (running?.launch === starting) running = void 0;
2042
3293
  if (!closing && !failed()) opts.onBrowserGone?.();
2043
3294
  });
2044
- const pid = await within(browserProcessId(ctx), BROWSER_CLOSE_GRACE_MS);
3295
+ const pid = await within2(browserProcessId(ctx), BROWSER_CLOSE_GRACE_MS);
2045
3296
  setPid(pid);
2046
- if (!gone) running = { launch: starting, pid };
3297
+ if (!gone) running = { launch: starting, pid, ctx };
2047
3298
  const workspace = opts.env[SERVICE_WORKSPACE_ENV];
2048
3299
  const session = new BrowserSession(ctx, {
2049
3300
  proxy: plan.proxy,
@@ -2051,8 +3302,14 @@ async function startDaemon(opts) {
2051
3302
  workspace: workspace === void 0 || workspace === "" ? void 0 : workspace,
2052
3303
  downloadsTmp: plan.downloadsTmp,
2053
3304
  downloadMaxBytes: downloadMaxBytes(opts.env),
2054
- ...opts.downloadWaitMs === void 0 ? {} : { downloadWaitMs: opts.downloadWaitMs }
3305
+ ...opts.downloadWaitMs === void 0 ? {} : { downloadWaitMs: opts.downloadWaitMs },
3306
+ ...opts.navigationTimeoutMs === void 0 ? {} : { navigationTimeoutMs: opts.navigationTimeoutMs }
2055
3307
  });
3308
+ if (plan.shippedDir !== void 0)
3309
+ session.note(shippedRevisionNote(plan.shippedDir, browserRevision(plan.build)));
3310
+ if (plan.build === "chromium-headless-shell" && opts.browsersPath === void 0)
3311
+ session.note(HEADLESS_SHELL_NOTE);
3312
+ if (!closing) await restoreCookies(ctx, opts.stateDir);
2056
3313
  if (!restored && !closing) {
2057
3314
  restored = true;
2058
3315
  if (saved !== void 0) await sessionFile.restoreTabs(session, saved);
@@ -2070,13 +3327,16 @@ async function startDaemon(opts) {
2070
3327
  () => true,
2071
3328
  () => true
2072
3329
  );
2073
- if (await within(done, closeGraceMs) === true) return;
3330
+ if (await within2(done, closeGraceMs) === true) return;
2074
3331
  const id = pid();
2075
3332
  if (id === void 0) return;
2076
3333
  killChromium(id);
2077
- await within(done, closeGraceMs);
3334
+ await within2(done, closeGraceMs);
2078
3335
  }
2079
3336
  async function launchFailure(e) {
3337
+ if (e instanceof BrowserInstalledError)
3338
+ return { ok: false, error: "restart", message: e.message, blockedHosts: [] };
3339
+ if (plan.unavailable !== void 0) return fail(plan.unavailable);
2080
3340
  const cause = e instanceof Error ? e.message.split("\n")[0] : String(e);
2081
3341
  const proxy = plan.proxy;
2082
3342
  const refused = proxy === void 0 ? [] : (await Promise.all(
@@ -2098,16 +3358,28 @@ async function startDaemon(opts) {
2098
3358
  async function stopBrowser() {
2099
3359
  const starting = current;
2100
3360
  if (starting === void 0) return;
3361
+ const r = running?.launch === starting ? running : void 0;
3362
+ const pid = r?.pid;
3363
+ if (r !== void 0) await within2(saveCookies(r.ctx, opts.stateDir), COOKIE_SAVE_MS);
2101
3364
  await closeOrKill(
2102
3365
  starting.then(
2103
- (session) => session.close(),
3366
+ async (session) => {
3367
+ await session.close();
3368
+ if (pid !== void 0) await processGone(pid);
3369
+ },
2104
3370
  () => void 0
2105
3371
  ),
2106
- () => running?.launch === starting ? running.pid : void 0
3372
+ () => pid
2107
3373
  );
2108
3374
  }
3375
+ async function processGone(pid) {
3376
+ while (processAlive(pid)) await new Promise((r) => clock.schedule(r, PROCESS_POLL_MS));
3377
+ }
2109
3378
  const ready = browser().then(() => void 0);
2110
- ready.catch(() => void 0);
3379
+ ready.catch((e) => {
3380
+ if (e instanceof BrowserInstalledError)
3381
+ clock.schedule(() => opts.onSealed?.(), SEALED_EXIT_GRACE_MS);
3382
+ });
2111
3383
  async function handoffOp(req) {
2112
3384
  if (typeof req.callId !== "string" || req.callId === "")
2113
3385
  return fail("The handoff needs a callId.");
@@ -2196,6 +3468,10 @@ async function startDaemon(opts) {
2196
3468
  });
2197
3469
  return ok || dropped || sock.destroyed;
2198
3470
  },
3471
+ sendFrame: (frame) => {
3472
+ if (sock.destroyed) return true;
3473
+ return sock.write(encodeServiceMessage(frame));
3474
+ },
2199
3475
  whenDrained: () => new Promise((r) => sock.once("drain", () => r()))
2200
3476
  }
2201
3477
  });
@@ -2212,6 +3488,7 @@ async function startDaemon(opts) {
2212
3488
  handleRequest(parse(raw)).catch((e) => fail(e instanceof ActionError ? e.message : String(e))).then((reply) => {
2213
3489
  write(sock, reply, () => write(sock, fail(REPLY_TOO_LARGE_MESSAGE), () => void 0));
2214
3490
  sock.end();
3491
+ if (!reply.ok && reply.error === "restart") sock.once("close", () => opts.onSealed?.());
2215
3492
  }).catch(() => sock.destroy()).finally(() => state.requestEnded());
2216
3493
  return;
2217
3494
  }
@@ -2230,7 +3507,7 @@ async function startDaemon(opts) {
2230
3507
  for (const m of msgs) onMessage(m);
2231
3508
  });
2232
3509
  }
2233
- if (existsSync2(opts.socketPath)) unlinkSync(opts.socketPath);
3510
+ if (existsSync2(opts.socketPath)) unlinkSync2(opts.socketPath);
2234
3511
  const server = createServer(onConnection);
2235
3512
  await new Promise((resolve, reject) => {
2236
3513
  server.once("error", reject);
@@ -2254,7 +3531,7 @@ async function startDaemon(opts) {
2254
3531
  await stopBrowser();
2255
3532
  if (existsSync2(opts.socketPath)) {
2256
3533
  try {
2257
- unlinkSync(opts.socketPath);
3534
+ unlinkSync2(opts.socketPath);
2258
3535
  } catch {
2259
3536
  }
2260
3537
  }
@@ -2290,7 +3567,9 @@ async function main() {
2290
3567
  stateDir,
2291
3568
  env: process.env,
2292
3569
  onIdle: () => stop(0, "idle"),
2293
- onBrowserGone: () => stop(1, "Chromium exited")
3570
+ onBrowserGone: () => stop(1, "Chromium exited"),
3571
+ // installed and sealed: the next start runs the browser read only
3572
+ onSealed: () => stop(0, "browser installed and sealed; restart to run it")
2294
3573
  });
2295
3574
  process.stderr.write(`browser daemon: listening on ${socketPath}
2296
3575
  `);