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

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,6 +1,6 @@
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.72/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
6
  var DEVICE_SERVICE_MAX_MESSAGE = 8 * 1024 * 1024;
@@ -69,11 +69,24 @@ var ServiceMessageDecoder = class {
69
69
  };
70
70
 
71
71
  // daemon/main.ts
72
- import { chmodSync, existsSync as existsSync2, mkdirSync as mkdirSync2, unlinkSync } from "node:fs";
72
+ import { chmodSync, existsSync as existsSync2, mkdirSync as mkdirSync2, unlinkSync as unlinkSync2 } from "node:fs";
73
73
  import { createServer } from "node:net";
74
74
 
75
75
  // daemon/actions.ts
76
- import { lstatSync, mkdirSync, readdirSync, realpathSync, statSync } from "node:fs";
76
+ import {
77
+ closeSync,
78
+ constants as fsc,
79
+ fstatSync,
80
+ lstatSync,
81
+ mkdirSync,
82
+ openSync,
83
+ readdirSync,
84
+ readSync,
85
+ realpathSync,
86
+ statSync,
87
+ unlinkSync,
88
+ writeSync
89
+ } from "node:fs";
77
90
  import { request as httpRequest } from "node:http";
78
91
  import { basename, extname, join, sep } from "node:path";
79
92
 
@@ -82,8 +95,65 @@ var VIEWPORT = { width: 1280, height: 800 };
82
95
  var SNAPSHOT_MAX_CHARS = 4e4;
83
96
  var IDLE_STOP_MS = 15 * 6e4;
84
97
  var TAKEOVER_GRACE_MS = 6e4;
85
- var VIEWER_MAX_FPS = 5;
98
+ var VIEWER_MAX_FPS = 15;
86
99
  var VIEWER_UNACKED_FRAMES = 2;
100
+ var VIEWER_TEXT_MAX_CHARS = 1e4;
101
+ function clipCodePoints(text, max) {
102
+ if (text.length <= max) return text;
103
+ return Array.from(text).slice(0, max).join("");
104
+ }
105
+ var VIEWER_CURSORS = [
106
+ "default",
107
+ "pointer",
108
+ "text",
109
+ "vertical-text",
110
+ "crosshair",
111
+ "move",
112
+ "grab",
113
+ "grabbing",
114
+ "not-allowed",
115
+ "no-drop",
116
+ "wait",
117
+ "progress",
118
+ "help",
119
+ "context-menu",
120
+ "cell",
121
+ "copy",
122
+ "alias",
123
+ "zoom-in",
124
+ "zoom-out",
125
+ "col-resize",
126
+ "row-resize",
127
+ "ew-resize",
128
+ "ns-resize",
129
+ "nesw-resize",
130
+ "nwse-resize",
131
+ "n-resize",
132
+ "e-resize",
133
+ "s-resize",
134
+ "w-resize",
135
+ "ne-resize",
136
+ "nw-resize",
137
+ "se-resize",
138
+ "sw-resize",
139
+ "all-scroll",
140
+ "none"
141
+ ];
142
+ function toViewerCursor(value) {
143
+ return typeof value === "string" && VIEWER_CURSORS.includes(value) ? value : "default";
144
+ }
145
+ var FRAME_TAG = 0;
146
+ var FRAME_HEADER_BYTES = 9;
147
+ function encodeFrame(f) {
148
+ const out = new Uint8Array(FRAME_HEADER_BYTES + f.jpeg.byteLength);
149
+ const v = new DataView(out.buffer);
150
+ v.setUint8(0, FRAME_TAG);
151
+ v.setUint32(1, f.seq >>> 0);
152
+ v.setUint16(5, f.width);
153
+ v.setUint16(7, f.height);
154
+ out.set(f.jpeg, FRAME_HEADER_BYTES);
155
+ return out;
156
+ }
87
157
  var DEFAULT_FRAME_MAX_BYTES = 256 * 1024;
88
158
  var HANDOFF_MAX_CHARS = 4096;
89
159
  var MAX_TABS = 10;
@@ -274,6 +344,49 @@ var DaemonState = class {
274
344
  }
275
345
  };
276
346
 
347
+ // daemon/verification.ts
348
+ 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.";
349
+ var URL_RE = /captcha|challenge|antispider|anti-spider|\/sorry\/|wappass\.baidu\.com|\/cdn-cgi\/|\/verify(?:[/?#]|$)|security-?check/i;
350
+ 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;
351
+ var VERIFICATION_STATUSES = /* @__PURE__ */ new Set([418, 429]);
352
+ var WIDGET_SELECTOR = [
353
+ ...["recaptcha", "hcaptcha", "challenges.cloudflare.com", "turnstile", "geetest", "captcha"].map(
354
+ (s) => `iframe[src*="${s}" i]`
355
+ ),
356
+ '[id*="captcha" i]',
357
+ '[class*="captcha" i]'
358
+ ].join(", ");
359
+ var MAX_WIDGETS = 10;
360
+ async function hasWidget(page) {
361
+ const found = page.locator(WIDGET_SELECTOR);
362
+ const n = Math.min(await found.count(), MAX_WIDGETS);
363
+ for (let i = 0; i < n; i++) {
364
+ const box = await found.nth(i).boundingBox();
365
+ if (box !== null && box.width > 20 && box.height > 20) return true;
366
+ }
367
+ return false;
368
+ }
369
+ function looksLikeVerification(url, title) {
370
+ let target = url;
371
+ try {
372
+ const u = new URL(url);
373
+ target = `${u.hostname}${u.pathname}${u.search}`;
374
+ } catch {
375
+ }
376
+ return URL_RE.test(target) || TITLE_RE.test(title);
377
+ }
378
+ async function isVerificationPage(page, status) {
379
+ try {
380
+ if (status !== void 0 && VERIFICATION_STATUSES.has(status)) return true;
381
+ const url = page.url();
382
+ if (!/^https?:/.test(url)) return false;
383
+ if (looksLikeVerification(url, await page.title())) return true;
384
+ return await hasWidget(page);
385
+ } catch {
386
+ return false;
387
+ }
388
+ }
389
+
277
390
  // daemon/actions.ts
278
391
  var ActionError = class extends Error {
279
392
  constructor(code, message) {
@@ -323,15 +436,46 @@ function safeFileName(raw) {
323
436
  if (Buffer.byteLength(ext) > 32) ext = "";
324
437
  return utf8Prefix(name.slice(0, name.length - ext.length), MAX_NAME_BYTES - Buffer.byteLength(ext)) + ext;
325
438
  }
326
- function absent(path) {
439
+ function copyInto(source, out) {
440
+ const src = openSync(source, fsc.O_RDONLY | fsc.O_NOFOLLOW);
327
441
  try {
328
- lstatSync(path);
329
- return false;
330
- } catch {
331
- return true;
442
+ const buf = Buffer.alloc(1024 * 1024);
443
+ for (; ; ) {
444
+ const n = readSync(src, buf, 0, buf.length, null);
445
+ if (n === 0) break;
446
+ let w = 0;
447
+ while (w < n) w += writeSync(out, buf, w, n - w);
448
+ }
449
+ } finally {
450
+ closeSync(src);
332
451
  }
333
452
  }
334
453
  var PROXY_PROBE_TIMEOUT_MS = 5e3;
454
+ var UPLOAD_MAX_BYTES = 50 * 1024 * 1024;
455
+ var UPLOAD_TYPES = {
456
+ ".png": "image/png",
457
+ ".jpg": "image/jpeg",
458
+ ".jpeg": "image/jpeg",
459
+ ".gif": "image/gif",
460
+ ".webp": "image/webp",
461
+ ".svg": "image/svg+xml",
462
+ ".pdf": "application/pdf",
463
+ ".txt": "text/plain",
464
+ ".md": "text/markdown",
465
+ ".csv": "text/csv",
466
+ ".json": "application/json",
467
+ ".html": "text/html",
468
+ ".zip": "application/zip",
469
+ ".mp4": "video/mp4",
470
+ ".mp3": "audio/mpeg",
471
+ ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
472
+ ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
473
+ ".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation"
474
+ };
475
+ function within(real, root) {
476
+ return real === root || real.startsWith(root.endsWith(sep) ? root : root + sep);
477
+ }
478
+ var sameFile = (a, b) => a.dev === b.dev && a.ino === b.ino;
335
479
  var REF_RE = /^(f\d+)?e\d+$/;
336
480
  var PROXY_FAILURE_RE = /ERR_TUNNEL_CONNECTION_FAILED|ERR_PROXY_CONNECTION_FAILED/;
337
481
  function docUrl(raw) {
@@ -550,6 +694,10 @@ var BrowserSession = class {
550
694
  ids = /* @__PURE__ */ new WeakMap();
551
695
  titles = /* @__PURE__ */ new Map();
552
696
  loadingTabs = /* @__PURE__ */ new Set();
697
+ /** Tabs showing a verification page, by tab id (cleared on every main-frame navigation). */
698
+ blockers = /* @__PURE__ */ new Map();
699
+ /** The status of each tab's current document (main-frame response), by tab id. */
700
+ docStatus = /* @__PURE__ */ new Map();
553
701
  /** Each page's main-frame navigation request in flight (until it commits, fails or finishes). */
554
702
  pendingNavs = /* @__PURE__ */ new WeakMap();
555
703
  listeners = /* @__PURE__ */ new Set();
@@ -613,12 +761,16 @@ var BrowserSession = class {
613
761
  return this.ids.get(page) ?? "";
614
762
  }
615
763
  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
- }));
764
+ return [...this.pages.entries()].map(([id, p]) => {
765
+ const blocker = this.blockers.get(id);
766
+ return {
767
+ id,
768
+ title: clip(this.titles.get(id) ?? "", MAX_TITLE_CHARS),
769
+ url: clip(p.url(), MAX_URL_CHARS),
770
+ active: id === this.active,
771
+ ...blocker === void 0 ? {} : { blocker }
772
+ };
773
+ });
622
774
  }
623
775
  /** Whether the active tab is loading a document. */
624
776
  get loading() {
@@ -638,7 +790,7 @@ var BrowserSession = class {
638
790
  this.ids.set(page, id);
639
791
  this.pages.set(id, page);
640
792
  const refresh = () => {
641
- page.title().then((t) => this.titles.set(id, t)).catch(() => void 0).finally(() => this.emit({ type: "state" }));
793
+ page.title().then((t) => this.titles.set(id, t)).catch(() => void 0).then(() => this.checkVerification(page, id)).finally(() => this.emit({ type: "state" }));
642
794
  };
643
795
  const settle = (r) => {
644
796
  if (this.pendingNavs.get(page) === r) this.pendingNavs.delete(page);
@@ -664,6 +816,7 @@ var BrowserSession = class {
664
816
  page.on("framenavigated", (f) => {
665
817
  if (f !== page.mainFrame()) return;
666
818
  this.pendingNavs.delete(page);
819
+ this.blockers.delete(id);
667
820
  refresh();
668
821
  });
669
822
  page.on("domcontentloaded", refresh);
@@ -682,6 +835,8 @@ var BrowserSession = class {
682
835
  this.checkBlocked(r.url(), this.pageToOpen(page, r));
683
836
  });
684
837
  page.on("response", (r) => {
838
+ if (r.request().isNavigationRequest() && r.frame() === page.mainFrame())
839
+ this.docStatus.set(id, r.status());
685
840
  if (this.proxy !== void 0 && r.status() === 403 && r.url().startsWith("http:")) {
686
841
  this.checkBlocked(r.url(), this.pageToOpen(page, r.request()));
687
842
  }
@@ -697,6 +852,8 @@ var BrowserSession = class {
697
852
  this.pages.delete(id);
698
853
  this.titles.delete(id);
699
854
  this.loadingTabs.delete(id);
855
+ this.blockers.delete(id);
856
+ this.docStatus.delete(id);
700
857
  if (this.active === id) {
701
858
  const next = [...this.pages.keys()].at(-1);
702
859
  this.active = next;
@@ -768,8 +925,7 @@ var BrowserSession = class {
768
925
  );
769
926
  return;
770
927
  }
771
- target = this.downloadTarget(workspace, safeFileName(d.suggestedFilename()));
772
- await d.saveAs(target);
928
+ target = this.saveDownload(workspace, safeFileName(d.suggestedFilename()), tmp);
773
929
  this.note(`Downloaded ${shown} to ${target}.`);
774
930
  } catch (e) {
775
931
  this.note(
@@ -784,8 +940,62 @@ var BrowserSession = class {
784
940
  })();
785
941
  for (const c of this.collectors) c.downloads.push(entry);
786
942
  }
787
- /** A free path in `<workspace>/downloads`, refusing a downloads directory that is a link. */
788
- downloadTarget(workspace, name) {
943
+ /**
944
+ * Copies a finished download from Playwright's private file into `<workspace>/downloads` and
945
+ * returns where. The agent owns that directory, so the target is never written through a path
946
+ * it could have swapped: each candidate is created exclusively without following a link
947
+ * (`O_CREAT | O_EXCL | O_NOFOLLOW`), then checked to be the file the resolved path inside the
948
+ * downloads directory names before any byte is written; a mismatch (a directory swapped for a
949
+ * link meanwhile) writes nothing, removes the empty file it made (only while that name still
950
+ * is the file it opened) and fails.
951
+ */
952
+ saveDownload(workspace, name, source) {
953
+ const dir = this.downloadsDir(workspace);
954
+ const dirStat = lstatSync(dir);
955
+ const ext = extname(name);
956
+ const stem = name.slice(0, name.length - ext.length);
957
+ for (let i = 0; i < 1e3; i++) {
958
+ const target = join(dir, i === 0 ? name : `${stem} (${i})${ext}`);
959
+ if (this.reservedDownloads.has(target)) continue;
960
+ let out;
961
+ try {
962
+ out = openSync(target, fsc.O_WRONLY | fsc.O_CREAT | fsc.O_EXCL | fsc.O_NOFOLLOW, 436);
963
+ } catch (e) {
964
+ if (e.code === "EEXIST") continue;
965
+ throw e;
966
+ }
967
+ this.reservedDownloads.add(target);
968
+ try {
969
+ let real;
970
+ try {
971
+ real = realpathSync(target);
972
+ } catch {
973
+ real = "";
974
+ }
975
+ const opened = fstatSync(out);
976
+ const placed = real !== "" && within(real, dir) && sameFile(opened, statSync(real));
977
+ if (!placed || !sameFile(dirStat, lstatSync(dir))) {
978
+ try {
979
+ if (real !== "" && sameFile(opened, lstatSync(real)) && opened.size === 0)
980
+ unlinkSync(real);
981
+ } catch {
982
+ }
983
+ throw new ActionError(
984
+ "failed",
985
+ `${dir} changed while the download was saved; nothing was written. Retry the download.`
986
+ );
987
+ }
988
+ copyInto(source, out);
989
+ return target;
990
+ } finally {
991
+ closeSync(out);
992
+ this.reservedDownloads.delete(target);
993
+ }
994
+ }
995
+ throw new ActionError("failed", `No free name for ${name} in ${dir}; remove old downloads.`);
996
+ }
997
+ /** `<workspace>/downloads` resolved, refusing one that is a link or not a directory. */
998
+ downloadsDir(workspace) {
789
999
  const root = realpathSync(workspace);
790
1000
  const dir = join(root, "downloads");
791
1001
  mkdirSync(dir, { recursive: true });
@@ -796,14 +1006,7 @@ var BrowserSession = class {
796
1006
  `${dir} is not a plain directory in the workspace; remove it so downloads can be saved.`
797
1007
  );
798
1008
  }
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;
1009
+ return dir;
807
1010
  }
808
1011
  /**
809
1012
  * While downloads run, sums the bytes of Playwright's in-progress files and cancels every
@@ -845,29 +1048,69 @@ var BrowserSession = class {
845
1048
  this.pollDownloads();
846
1049
  }, DOWNLOAD_POLL_MS);
847
1050
  }
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;
1051
+ /**
1052
+ * An upload's bytes, read here and handed to Chromium from memory (never a path Chromium would
1053
+ * open later, after the agent could have swapped it for a link to the service's own files):
1054
+ * opened without following a final link, then accepted only when the resolved path lies in the
1055
+ * workspace and names the very file opened (an intermediate link swapped in either way shows as
1056
+ * another file), a regular file of at most {@link UPLOAD_MAX_BYTES}.
1057
+ */
1058
+ readUpload(path) {
1059
+ const root = this.uploadRoot();
1060
+ let fd;
856
1061
  try {
857
- real = realpathSync(path);
858
- } catch {
1062
+ fd = openSync(path, fsc.O_RDONLY | fsc.O_NOFOLLOW | fsc.O_NONBLOCK);
1063
+ } catch (e) {
1064
+ const code = e.code;
859
1065
  throw new ActionError(
860
1066
  "failed",
861
- `No file at ${path}; give the absolute path of a file in the workspace (${root}).`
1067
+ 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
1068
  );
863
1069
  }
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
- );
1070
+ try {
1071
+ const opened = fstatSync(fd);
1072
+ let real = "";
1073
+ try {
1074
+ real = realpathSync(path);
1075
+ } catch {
1076
+ real = "";
1077
+ }
1078
+ if (!within(real, root) || !sameFile(opened, statSync(real)))
1079
+ throw new ActionError(
1080
+ "failed",
1081
+ `Upload paths must be inside the workspace (${root}); copy the file there first.`
1082
+ );
1083
+ if (!opened.isFile())
1084
+ throw new ActionError("failed", `${path} is not a regular file; upload a file.`);
1085
+ if (opened.size > UPLOAD_MAX_BYTES)
1086
+ throw new ActionError(
1087
+ "failed",
1088
+ `${path} is larger than ${UPLOAD_MAX_BYTES} bytes, the most an upload takes.`
1089
+ );
1090
+ const buffer = Buffer.alloc(opened.size);
1091
+ let off = 0;
1092
+ while (off < buffer.length) {
1093
+ const n = readSync(fd, buffer, off, buffer.length - off, off);
1094
+ if (n === 0) break;
1095
+ off += n;
1096
+ }
1097
+ const name = basename(real);
1098
+ return {
1099
+ name,
1100
+ mimeType: UPLOAD_TYPES[extname(name).toLowerCase()] ?? "application/octet-stream",
1101
+ buffer: buffer.subarray(0, off)
1102
+ };
1103
+ } finally {
1104
+ closeSync(fd);
1105
+ }
1106
+ }
1107
+ /** The resolved workspace uploads come from. */
1108
+ uploadRoot() {
1109
+ const workspace = this.workspace;
1110
+ if (workspace === void 0) {
1111
+ throw new ActionError("failed", "Uploads are unavailable: the device has no workspace.");
869
1112
  }
870
- return real;
1113
+ return realpathSync(workspace);
871
1114
  }
872
1115
  /**
873
1116
  * The page a viewer opens once the refused host is allowed: the navigation's target for a
@@ -932,7 +1175,12 @@ var BrowserSession = class {
932
1175
  await this.settleDownloads(c);
933
1176
  this.collectors.delete(c);
934
1177
  const page = await this.activePage();
935
- const text = [...c.notes, ...out.text === void 0 ? [] : [out.text]].join("\n");
1178
+ const verifying = await this.checkVerification(page, this.tabIdOf(page));
1179
+ const text = [
1180
+ ...verifying ? [VERIFICATION_NOTE] : [],
1181
+ ...c.notes,
1182
+ ...out.text === void 0 ? [] : [out.text]
1183
+ ].join("\n");
936
1184
  reply = {
937
1185
  ok: true,
938
1186
  page: await this.pageInfo(page),
@@ -986,6 +1234,27 @@ var BrowserSession = class {
986
1234
  await Promise.allSettled(all);
987
1235
  }
988
1236
  }
1237
+ /**
1238
+ * Looks at the tab's page now and records or clears its verification blocker; true when it
1239
+ * shows a verification page.
1240
+ */
1241
+ async checkVerification(page, id) {
1242
+ if (id === "") return false;
1243
+ const blocked = await isVerificationPage(page, this.docStatus.get(id));
1244
+ if (this.pages.get(id) !== page) return false;
1245
+ const before = this.blockers.get(id);
1246
+ if (blocked) {
1247
+ const url = clip(page.url(), MAX_URL_CHARS);
1248
+ if (before?.url !== url) {
1249
+ this.blockers.set(id, { kind: "verification", url });
1250
+ this.emit({ type: "state" });
1251
+ }
1252
+ } else if (before !== void 0) {
1253
+ this.blockers.delete(id);
1254
+ this.emit({ type: "state" });
1255
+ }
1256
+ return blocked;
1257
+ }
989
1258
  async pageInfo(page) {
990
1259
  let title = "";
991
1260
  try {
@@ -1169,9 +1438,9 @@ var BrowserSession = class {
1169
1438
  }
1170
1439
  case "upload": {
1171
1440
  const page = await this.activePage();
1172
- const path = this.uploadPath(req.path);
1441
+ const file = this.readUpload(req.path);
1173
1442
  const loc = await this.locate(page, req.ref);
1174
- await loc.setInputFiles(path);
1443
+ await loc.setInputFiles(file);
1175
1444
  return {};
1176
1445
  }
1177
1446
  case "click_at":
@@ -1337,15 +1606,30 @@ var BrowserSession = class {
1337
1606
  };
1338
1607
 
1339
1608
  // daemon/chromium.ts
1340
- import { existsSync, readFileSync } from "node:fs";
1609
+ import {
1610
+ accessSync,
1611
+ constants,
1612
+ existsSync,
1613
+ lstatSync as lstatSync2,
1614
+ readdirSync as readdirSync2,
1615
+ readFileSync,
1616
+ writeFileSync
1617
+ } from "node:fs";
1341
1618
  import { createRequire } from "node:module";
1342
- import { dirname, join as join2 } from "node:path";
1619
+ import { dirname, isAbsolute, join as join2, relative } from "node:path";
1343
1620
  import { fileURLToPath } from "node:url";
1621
+ function chromiumBuild(platform) {
1622
+ return platform === "darwin" ? "chromium-headless-shell" : "chromium";
1623
+ }
1624
+ var BUILD_DIR = {
1625
+ chromium: "chromium",
1626
+ "chromium-headless-shell": "chromium_headless_shell"
1627
+ };
1344
1628
  function envValue(env, name) {
1345
1629
  const v = env[name] ?? env[name.toLowerCase()];
1346
1630
  return v === void 0 || v === "" ? void 0 : v;
1347
1631
  }
1348
- function headlessShellRevision() {
1632
+ function browserRelease(build) {
1349
1633
  const candidates = [new URL("./vendor/playwright-core/browsers.json", import.meta.url)];
1350
1634
  try {
1351
1635
  const pkg = createRequire(import.meta.url).resolve("playwright-core/package.json");
@@ -1355,13 +1639,25 @@ function headlessShellRevision() {
1355
1639
  for (const file of candidates) {
1356
1640
  try {
1357
1641
  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;
1642
+ const b = json.browsers?.find((x) => x.name === build);
1643
+ if (typeof b?.revision === "string" && b.revision !== "")
1644
+ return {
1645
+ revision: b.revision,
1646
+ version: typeof b.browserVersion === "string" ? b.browserVersion : ""
1647
+ };
1360
1648
  } catch {
1361
1649
  }
1362
1650
  }
1363
1651
  return void 0;
1364
1652
  }
1653
+ function browserRevision(build) {
1654
+ return browserRelease(build)?.revision;
1655
+ }
1656
+ function chromeUserAgent(platform, version) {
1657
+ const major = /^\d+/.exec(version)?.[0] ?? "0";
1658
+ const os = platform === "darwin" ? "Macintosh; Intel Mac OS X 10_15_7" : platform === "win32" ? "Windows NT 10.0; Win64; x64" : "X11; Linux x86_64";
1659
+ return `Mozilla/5.0 (${os}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${major}.0.0.0 Safari/537.36`;
1660
+ }
1365
1661
  function playwrightDownloadHosts(env) {
1366
1662
  const custom = envValue(env, "PLAYWRIGHT_CHROMIUM_DOWNLOAD_HOST") ?? envValue(env, "PLAYWRIGHT_DOWNLOAD_HOST");
1367
1663
  if (custom !== void 0) {
@@ -1373,15 +1669,76 @@ function playwrightDownloadHosts(env) {
1373
1669
  }
1374
1670
  return ["cdn.playwright.dev", "playwright.download.prss.microsoft.com", "storage.googleapis.com"];
1375
1671
  }
1376
- function browsersPathFor(stateDir, env, revision) {
1672
+ var MAX_REVISION_SKEW = 10;
1673
+ function shippedRevisionNote(dir, revision) {
1674
+ 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.`;
1675
+ }
1676
+ 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).";
1677
+ var SERVICE_INSTALL_ENV = "CAPYBARA_SERVICE_INSTALL";
1678
+ var SERVICE_INSTALL_SEAL = ".sealed";
1679
+ var BrowserInstalledError = class extends Error {
1680
+ constructor() {
1681
+ super("The browser was installed; the browser service restarts to run it read only.");
1682
+ this.name = "BrowserInstalledError";
1683
+ }
1684
+ };
1685
+ function inside(dir, root) {
1686
+ const rel = relative(root, dir);
1687
+ return rel === "" || !rel.startsWith("..") && !isAbsolute(rel);
1688
+ }
1689
+ function readOnlyForUs(dir) {
1690
+ try {
1691
+ accessSync(dir, constants.W_OK);
1692
+ return false;
1693
+ } catch {
1694
+ return true;
1695
+ }
1696
+ }
1697
+ function browsersPathFor(stateDir, env, revision, build) {
1698
+ const install = envValue(env, SERVICE_INSTALL_ENV);
1699
+ if (install !== void 0 && isAbsolute(install)) {
1700
+ let sealed = false;
1701
+ try {
1702
+ sealed = lstatSync2(join2(install, SERVICE_INSTALL_SEAL)).isFile();
1703
+ } catch {
1704
+ sealed = false;
1705
+ }
1706
+ return { browsersPath: install, install: { sealed } };
1707
+ }
1377
1708
  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");
1709
+ const workspace = envValue(env, "CAPYBARA_SERVICE_WORKSPACE");
1710
+ if (cache !== void 0 && isAbsolute(cache) && (workspace === void 0 || !inside(cache, workspace)) && readOnlyForUs(cache)) {
1711
+ if (revision !== void 0 && existsSync(join2(cache, `${BUILD_DIR[build]}-${revision}`)))
1712
+ return { browsersPath: cache, shipped: true };
1713
+ const near = shippedRevisions(cache, build).filter(
1714
+ (d) => revision !== void 0 && Math.abs(Number(d.slice(BUILD_DIR[build].length + 1)) - Number(revision)) <= MAX_REVISION_SKEW
1715
+ );
1716
+ const newest = near.at(-1);
1717
+ if (newest !== void 0) return { browsersPath: cache, shipped: true, shippedDir: newest };
1718
+ }
1719
+ return { browsersPath: join2(stateDir, "browsers"), unavailable: BROWSER_UNAVAILABLE_MESSAGE };
1381
1720
  }
1382
- function chromiumLaunchPlan(opts, revision = headlessShellRevision()) {
1383
- const args = ["--headless", "--use-mock-keychain"];
1384
- if (opts.platform === "darwin") args.push("--single-process");
1721
+ function shippedRevisions(cache, build) {
1722
+ const re = new RegExp(`^${BUILD_DIR[build]}-(\\d+)$`);
1723
+ let names;
1724
+ try {
1725
+ names = readdirSync2(cache);
1726
+ } catch {
1727
+ return [];
1728
+ }
1729
+ 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);
1730
+ }
1731
+ function chromiumLaunchPlan(opts, release = browserRelease(
1732
+ chromiumBuild(opts.platform)
1733
+ )) {
1734
+ const build = chromiumBuild(opts.platform);
1735
+ const args = [
1736
+ "--headless",
1737
+ "--use-mock-keychain",
1738
+ `--window-size=${VIEWPORT.width},${VIEWPORT.height}`,
1739
+ `--user-agent=${chromeUserAgent(opts.platform, release?.version ?? "")}`
1740
+ ];
1741
+ if (build === "chromium-headless-shell") args.push("--single-process");
1385
1742
  const proxy = envValue(opts.env, "HTTPS_PROXY") ?? envValue(opts.env, "HTTP_PROXY");
1386
1743
  let proxyAuth;
1387
1744
  if (proxy !== void 0) {
@@ -1406,7 +1763,8 @@ function chromiumLaunchPlan(opts, revision = headlessShellRevision()) {
1406
1763
  }
1407
1764
  }
1408
1765
  return {
1409
- browsersPath: opts.browsersPath ?? browsersPathFor(opts.stateDir, opts.env, revision),
1766
+ ...opts.browsersPath === void 0 ? browsersPathFor(opts.stateDir, opts.env, release?.revision, build) : { browsersPath: opts.browsersPath },
1767
+ build,
1410
1768
  profileDir: join2(opts.stateDir, "profile"),
1411
1769
  downloadsTmp: join2(opts.stateDir, "downloads-tmp"),
1412
1770
  args,
@@ -1429,30 +1787,44 @@ async function loadPlaywright(browsersPath) {
1429
1787
  loaded = { browsersPath, pw: pw.default ?? pw };
1430
1788
  return loaded.pw;
1431
1789
  }
1432
- async function headlessShell(browsersPath) {
1790
+ async function registryBrowser(browsersPath, build) {
1433
1791
  await loadPlaywright(browsersPath);
1434
1792
  const mod = await import("./vendor/playwright-core/lib/coreBundle.js");
1435
1793
  const registry = (mod.registry ?? mod.default?.registry)?.registry;
1436
1794
  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");
1795
+ const exe = registry.findExecutable(build);
1796
+ if (exe === void 0) throw new Error(`playwright-core does not know ${build}`);
1439
1797
  const executablePath = exe.executablePath();
1440
1798
  if (executablePath === void 0 || exe.directory === void 0)
1441
- throw new Error("playwright-core has no chromium-headless-shell for this platform");
1799
+ throw new Error(`playwright-core has no ${build} for this platform`);
1442
1800
  return { registry, exe, executablePath, directory: exe.directory };
1443
1801
  }
1444
- async function ensureChromium(browsersPath) {
1445
- const { registry, exe, executablePath, directory } = await headlessShell(browsersPath);
1802
+ async function ensureChromium(browsersPath, install = true, build = chromiumBuild(process.platform), fresh = false) {
1803
+ const { registry, exe, executablePath, directory } = await registryBrowser(browsersPath, build);
1446
1804
  const marked = existsSync(join2(directory, "INSTALLATION_COMPLETE"));
1447
- if (marked && existsSync(executablePath)) return executablePath;
1448
- await registry.install([exe], { gc: false, force: marked });
1805
+ if (!fresh && marked && existsSync(executablePath)) return executablePath;
1806
+ if (!install)
1807
+ throw new Error(
1808
+ `the browser in ${browsersPath} is incomplete and read only for the browser service; delete the device and create it again`
1809
+ );
1810
+ await registry.install([exe], { gc: false, force: marked || fresh });
1449
1811
  if (!existsSync(executablePath)) {
1450
1812
  throw new Error("the Chromium download finished without an executable");
1451
1813
  }
1452
1814
  return executablePath;
1453
1815
  }
1454
1816
  async function launchChromium(plan) {
1455
- const executablePath = await ensureChromium(plan.browsersPath);
1817
+ if (plan.unavailable !== void 0) throw new Error(plan.unavailable);
1818
+ if (plan.install?.sealed === false) {
1819
+ await ensureChromium(plan.browsersPath, true, plan.build, true);
1820
+ sealInstall(plan.browsersPath);
1821
+ throw new BrowserInstalledError();
1822
+ }
1823
+ const executablePath = plan.shippedDir === void 0 ? await ensureChromium(
1824
+ plan.browsersPath,
1825
+ plan.install === void 0 && plan.shipped !== true,
1826
+ plan.build
1827
+ ) : await shippedExecutable(plan.browsersPath, plan.shippedDir, plan.build);
1456
1828
  const pw = await loadPlaywright(plan.browsersPath);
1457
1829
  return pw.chromium.launchPersistentContext(plan.profileDir, {
1458
1830
  headless: true,
@@ -1465,6 +1837,22 @@ async function launchChromium(plan) {
1465
1837
  ...plan.proxyAuth === void 0 ? {} : { proxy: plan.proxyAuth }
1466
1838
  });
1467
1839
  }
1840
+ async function shippedExecutable(cache, dir, build) {
1841
+ const { executablePath, directory } = await registryBrowser(cache, build);
1842
+ const path = join2(cache, dir, relative(directory, executablePath));
1843
+ if (!existsSync(path))
1844
+ throw new Error(
1845
+ `the browser shipped in ${join2(cache, dir)} has no executable; ${BROWSER_UNAVAILABLE_MESSAGE}`
1846
+ );
1847
+ return path;
1848
+ }
1849
+ function sealInstall(dir) {
1850
+ try {
1851
+ writeFileSync(join2(dir, SERVICE_INSTALL_SEAL), "", { flag: "wx", mode: 420 });
1852
+ } catch (e) {
1853
+ if (e.code !== "EEXIST") throw e;
1854
+ }
1855
+ }
1468
1856
  async function browserProcessId(ctx) {
1469
1857
  const browser = ctx.browser();
1470
1858
  if (browser === null) return void 0;
@@ -1491,10 +1879,49 @@ function killChromium(pid) {
1491
1879
  }
1492
1880
  }
1493
1881
  }
1882
+ function processAlive(pid) {
1883
+ try {
1884
+ process.kill(pid, 0);
1885
+ return true;
1886
+ } catch (e) {
1887
+ return e.code === "EPERM";
1888
+ }
1889
+ }
1494
1890
 
1495
- // daemon/session-file.ts
1496
- import { readFileSync as readFileSync2, renameSync, rmSync, writeFileSync } from "node:fs";
1891
+ // daemon/cookie-file.ts
1892
+ import { readFileSync as readFileSync2, renameSync, rmSync, writeFileSync as writeFileSync2 } from "node:fs";
1497
1893
  import { join as join3 } from "node:path";
1894
+ var key = (c) => `${c.domain}
1895
+ ${c.path}
1896
+ ${c.name}`;
1897
+ async function saveCookies(ctx, stateDir) {
1898
+ try {
1899
+ const cookies = (await ctx.cookies()).filter((c) => c.expires > 0);
1900
+ const file = join3(stateDir, "cookies.json");
1901
+ writeFileSync2(`${file}.tmp`, JSON.stringify(cookies), { mode: 384 });
1902
+ renameSync(`${file}.tmp`, file);
1903
+ } catch {
1904
+ }
1905
+ }
1906
+ async function restoreCookies(ctx, stateDir) {
1907
+ try {
1908
+ const saved = JSON.parse(readFileSync2(join3(stateDir, "cookies.json"), "utf8"));
1909
+ if (!Array.isArray(saved)) return;
1910
+ const have = new Set((await ctx.cookies()).map(key));
1911
+ const now = Date.now() / 1e3;
1912
+ const missing = saved.filter(
1913
+ (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))
1914
+ );
1915
+ if (missing.length > 0) await ctx.addCookies(missing);
1916
+ } catch {
1917
+ } finally {
1918
+ rmSync(join3(stateDir, "cookies.json"), { force: true });
1919
+ }
1920
+ }
1921
+
1922
+ // daemon/session-file.ts
1923
+ import { readFileSync as readFileSync3, renameSync as renameSync2, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "node:fs";
1924
+ import { join as join4 } from "node:path";
1498
1925
  var RESTORE_MAX_AGE_MS = 10 * 6e4;
1499
1926
  var SessionFile = class {
1500
1927
  file;
@@ -1502,14 +1929,14 @@ var SessionFile = class {
1502
1929
  queued = false;
1503
1930
  forgotten = false;
1504
1931
  constructor(stateDir, clock) {
1505
- this.file = join3(stateDir, "session.json");
1932
+ this.file = join4(stateDir, "session.json");
1506
1933
  this.clock = clock;
1507
1934
  }
1508
1935
  /** The saved session when it is recent and well formed; undefined otherwise. */
1509
1936
  read() {
1510
1937
  let raw;
1511
1938
  try {
1512
- raw = JSON.parse(readFileSync2(this.file, "utf8"));
1939
+ raw = JSON.parse(readFileSync3(this.file, "utf8"));
1513
1940
  } catch {
1514
1941
  return void 0;
1515
1942
  }
@@ -1552,8 +1979,8 @@ var SessionFile = class {
1552
1979
  ...handoff === void 0 ? {} : { handoff }
1553
1980
  };
1554
1981
  try {
1555
- writeFileSync(`${this.file}.tmp`, JSON.stringify(body), { mode: 384 });
1556
- renameSync(`${this.file}.tmp`, this.file);
1982
+ writeFileSync3(`${this.file}.tmp`, JSON.stringify(body), { mode: 384 });
1983
+ renameSync2(`${this.file}.tmp`, this.file);
1557
1984
  } catch {
1558
1985
  }
1559
1986
  });
@@ -1561,7 +1988,7 @@ var SessionFile = class {
1561
1988
  /** Removes the file and stops saving (an idle stop). */
1562
1989
  forget() {
1563
1990
  this.forgotten = true;
1564
- rmSync(this.file, { force: true });
1991
+ rmSync2(this.file, { force: true });
1565
1992
  }
1566
1993
  /**
1567
1994
  * Opens the saved tabs in a browser that has only its first blank tab. The navigations are
@@ -1583,10 +2010,300 @@ var SessionFile = class {
1583
2010
  }
1584
2011
  };
1585
2012
 
2013
+ // daemon/cursor.ts
2014
+ var CURSOR_MAX_FRAMES = 20;
2015
+ var MAX_DEPTH = 3;
2016
+ var WORLD = "capybara-cursor";
2017
+ var CURSOR_FUNCTION = `function (x, y) {
2018
+ const el = this.nodeType === 1 ? this : this.parentElement;
2019
+ if (!el) return { cursor: "default" };
2020
+ if (el.tagName === "IFRAME" || el.tagName === "FRAME") return { frame: true };
2021
+ const doc = el.ownerDocument;
2022
+ const view = doc.defaultView;
2023
+ const style = view.getComputedStyle(el);
2024
+ // "url(a.cur) 4 4, pointer": an image cursor's keyword fallback is the last item
2025
+ const parts = String(style.cursor).split(",");
2026
+ const cursor = parts[parts.length - 1].trim();
2027
+ if (cursor !== "auto") return { cursor };
2028
+ const NOT_TEXT = ["button", "submit", "reset", "checkbox", "radio", "range", "color", "file", "image", "hidden"];
2029
+ const tag = el.tagName;
2030
+ const editable = el.isContentEditable || tag === "TEXTAREA" ||
2031
+ (tag === "INPUT" && !NOT_TEXT.includes(String(el.type).toLowerCase()));
2032
+ if (editable && !el.disabled) return { cursor: "text" };
2033
+ if (style.userSelect === "none") return { cursor: "default" };
2034
+ const range = doc.caretRangeFromPoint ? doc.caretRangeFromPoint(x, y) : null;
2035
+ const node = range ? range.startContainer : null;
2036
+ if (!node || node.nodeType !== 3) return { cursor: "default" };
2037
+ const probe = doc.createRange();
2038
+ for (const [a, b] of [[range.startOffset, range.startOffset + 1], [range.startOffset - 1, range.startOffset]]) {
2039
+ if (a < 0 || b > node.length) continue;
2040
+ probe.setStart(node, a);
2041
+ probe.setEnd(node, b);
2042
+ for (const r of probe.getClientRects())
2043
+ if (x >= r.left && x <= r.right && y >= r.top && y <= r.bottom) return { cursor: "text" };
2044
+ }
2045
+ return { cursor: "default" };
2046
+ }`;
2047
+ var CursorResolver = class {
2048
+ constructor(context, page, cdp) {
2049
+ this.context = context;
2050
+ this.page = page;
2051
+ this.cdp = cdp;
2052
+ page.on("framedetached", this.onFrameDetached);
2053
+ }
2054
+ context;
2055
+ page;
2056
+ cdp;
2057
+ /** Isolated world execution contexts, per CDP session and frame id. */
2058
+ worlds = /* @__PURE__ */ new WeakMap();
2059
+ /** Sessions of out-of-process frames entered, detached with their frame or on dispose. */
2060
+ sessions = /* @__PURE__ */ new Map();
2061
+ onFrameDetached = (frame) => {
2062
+ const cdp = this.sessions.get(frame);
2063
+ if (cdp === void 0) return;
2064
+ this.sessions.delete(frame);
2065
+ cdp.detach().catch(() => void 0);
2066
+ };
2067
+ /** How many out-of-process frame sessions are open (a test seam). */
2068
+ get openSessions() {
2069
+ return this.sessions.size;
2070
+ }
2071
+ /** Detaches the frame sessions this resolver opened (the viewer detached from the page). */
2072
+ dispose() {
2073
+ this.page.off("framedetached", this.onFrameDetached);
2074
+ for (const cdp of this.sessions.values()) cdp.detach().catch(() => void 0);
2075
+ this.sessions.clear();
2076
+ }
2077
+ /** The cursor Chromium would show at viewport point (x, y). */
2078
+ async at(x, y) {
2079
+ let cdp = this.cdp;
2080
+ let frame = this.page.mainFrame();
2081
+ let px = x;
2082
+ let py = y;
2083
+ for (let depth = 0; depth <= MAX_DEPTH; depth++) {
2084
+ const hit = await this.hitTest(cdp, px, py);
2085
+ const answer = await this.answerAt(cdp, hit, px, py);
2086
+ if (answer.cursor !== void 0) return toViewerCursor(answer.cursor);
2087
+ if (!answer.frame || depth === MAX_DEPTH) return "default";
2088
+ const box = await cdp.send("DOM.getBoxModel", { backendNodeId: hit.backendNodeId });
2089
+ const [left = 0, top = 0] = box.model.content;
2090
+ const [borderLeft = 0, borderTop = 0] = box.model.border;
2091
+ const child = await this.childAt(frame, borderLeft + (x - px), borderTop + (y - py));
2092
+ if (child === void 0) return "default";
2093
+ frame = child.frame;
2094
+ cdp = child.cdp;
2095
+ px = px - left;
2096
+ py = py - top;
2097
+ }
2098
+ return "default";
2099
+ }
2100
+ async hitTest(cdp, x, y) {
2101
+ return await cdp.send("DOM.getNodeForLocation", {
2102
+ x: Math.round(x),
2103
+ y: Math.round(y),
2104
+ includeUserAgentShadowDOM: false,
2105
+ ignorePointerEventsNone: false
2106
+ });
2107
+ }
2108
+ /** The answer for a hit node, at the point in the node's own frame. */
2109
+ async answerAt(cdp, hit, x, y) {
2110
+ const frameId = hit.frameId ?? await this.mainFrameId(cdp);
2111
+ const offset = await this.frameOffset(cdp, frameId);
2112
+ return this.run(cdp, frameId, hit.backendNodeId, x - offset.x, y - offset.y);
2113
+ }
2114
+ async run(cdp, frameId, backendNodeId, x, y) {
2115
+ for (let attempt = 0; attempt < 2; attempt++) {
2116
+ const contextId = await this.world(cdp, frameId, attempt > 0);
2117
+ try {
2118
+ const { object } = await cdp.send("DOM.resolveNode", {
2119
+ backendNodeId,
2120
+ executionContextId: contextId
2121
+ });
2122
+ if (object.objectId === void 0) return { cursor: "default" };
2123
+ const r = await cdp.send("Runtime.callFunctionOn", {
2124
+ objectId: object.objectId,
2125
+ functionDeclaration: CURSOR_FUNCTION,
2126
+ arguments: [{ value: x }, { value: y }],
2127
+ returnByValue: true
2128
+ });
2129
+ await cdp.send("Runtime.releaseObject", { objectId: object.objectId }).catch(() => {
2130
+ });
2131
+ return r.result.value ?? { cursor: "default" };
2132
+ } catch (e) {
2133
+ if (attempt > 0) throw e;
2134
+ }
2135
+ }
2136
+ return { cursor: "default" };
2137
+ }
2138
+ async world(cdp, frameId, fresh) {
2139
+ let byFrame = this.worlds.get(cdp);
2140
+ if (byFrame === void 0) {
2141
+ byFrame = /* @__PURE__ */ new Map();
2142
+ this.worlds.set(cdp, byFrame);
2143
+ }
2144
+ const known = byFrame.get(frameId);
2145
+ if (known !== void 0 && !fresh) return known;
2146
+ const { executionContextId } = await cdp.send("Page.createIsolatedWorld", {
2147
+ frameId,
2148
+ worldName: WORLD
2149
+ });
2150
+ byFrame.set(frameId, executionContextId);
2151
+ return executionContextId;
2152
+ }
2153
+ async mainFrameId(cdp) {
2154
+ const { frameTree } = await cdp.send("Page.getFrameTree");
2155
+ return frameTree.frame.id;
2156
+ }
2157
+ /** The offset of an in-process frame's viewport in the session's root (0 for its main frame). */
2158
+ async frameOffset(cdp, frameId) {
2159
+ if (frameId === await this.mainFrameId(cdp)) return { x: 0, y: 0 };
2160
+ const owner = await cdp.send("DOM.getFrameOwner", { frameId });
2161
+ const box = await cdp.send("DOM.getBoxModel", { backendNodeId: owner.backendNodeId });
2162
+ return { x: box.model.content[0] ?? 0, y: box.model.content[1] ?? 0 };
2163
+ }
2164
+ /**
2165
+ * The child frame of `parent` whose element's border box starts at (left, top), in the page's
2166
+ * (main frame) coordinates.
2167
+ */
2168
+ async childAt(parent, left, top) {
2169
+ for (const child of parent.childFrames().slice(0, CURSOR_MAX_FRAMES)) {
2170
+ const handle = await child.frameElement().catch(() => null);
2171
+ const box = await handle?.boundingBox().catch(() => null);
2172
+ await handle?.dispose();
2173
+ if (box === null || box === void 0) continue;
2174
+ if (Math.abs(box.x - left) > 3 || Math.abs(box.y - top) > 3) continue;
2175
+ let cdp = this.sessions.get(child);
2176
+ if (cdp === void 0) {
2177
+ cdp = await this.context.newCDPSession(child);
2178
+ this.sessions.set(child, cdp);
2179
+ }
2180
+ return { frame: child, cdp };
2181
+ }
2182
+ return void 0;
2183
+ }
2184
+ };
2185
+
2186
+ // daemon/viewer-pacing.ts
2187
+ var TARGET_LINK_MS = 120;
2188
+ var PING_WINDOW = 10;
2189
+ var RTT_WINDOW = 16;
2190
+ var LINK_ALPHA = 0.5;
2191
+ var FramePacer = class {
2192
+ minIntervalMs;
2193
+ maxUnacked;
2194
+ inFlight = [];
2195
+ pings = [];
2196
+ rtts = [];
2197
+ lastSentAt = Number.NEGATIVE_INFINITY;
2198
+ link;
2199
+ constructor(opts) {
2200
+ this.minIntervalMs = 1e3 / opts.maxFps;
2201
+ this.maxUnacked = opts.maxUnacked;
2202
+ }
2203
+ /** The smoothed time frames take over the path's own round trip; undefined before any ack. */
2204
+ get linkMs() {
2205
+ return this.link;
2206
+ }
2207
+ get unacked() {
2208
+ return this.inFlight.length;
2209
+ }
2210
+ /** The path's round trip without queueing, as far as measured. */
2211
+ get baseRttMs() {
2212
+ if (this.pings.length > 0) return Math.min(...this.pings);
2213
+ if (this.rtts.length > 0) return Math.min(...this.rtts);
2214
+ return void 0;
2215
+ }
2216
+ /** Whether a frame may be sent at `now`, and if only the rate cap holds it, for how long. */
2217
+ decide(now) {
2218
+ const n = this.inFlight.length;
2219
+ if (n >= this.maxUnacked) return { ok: false };
2220
+ if (n > 0 && this.link !== void 0 && this.link > TARGET_LINK_MS) return { ok: false };
2221
+ const wait = this.lastSentAt + this.minIntervalMs - now;
2222
+ return wait > 0 ? { ok: false, waitMs: wait } : { ok: true };
2223
+ }
2224
+ /** Records a frame sent at `now` (every frame counts, the first after an attach too). */
2225
+ sent(seq, now) {
2226
+ this.inFlight.push({ seq, at: now });
2227
+ this.lastSentAt = now;
2228
+ }
2229
+ /** Records the viewer's ack of every frame up to `seq` at `now`; returns the sample, if any. */
2230
+ acked(seq, now) {
2231
+ let last;
2232
+ while (this.inFlight.length > 0 && this.inFlight[0].seq <= seq) {
2233
+ last = this.inFlight.shift();
2234
+ }
2235
+ if (last === void 0) return void 0;
2236
+ const rtt = Math.max(0, now - last.at);
2237
+ this.rtts.push(rtt);
2238
+ if (this.rtts.length > RTT_WINDOW) this.rtts.shift();
2239
+ const sample = Math.max(0, rtt - (this.baseRttMs ?? rtt));
2240
+ this.link = this.link === void 0 ? sample : this.link * (1 - LINK_ALPHA) + sample * LINK_ALPHA;
2241
+ return sample;
2242
+ }
2243
+ /** Records a ping's round trip (a tiny message both ways on the same path as the frames). */
2244
+ pinged(rttMs) {
2245
+ if (!Number.isFinite(rttMs) || rttMs < 0) return;
2246
+ this.pings.push(rttMs);
2247
+ if (this.pings.length > PING_WINDOW) this.pings.shift();
2248
+ }
2249
+ /** Forgets frames in flight (a screencast restart: their acks may never come). */
2250
+ reset() {
2251
+ this.inFlight.length = 0;
2252
+ }
2253
+ };
2254
+ var QUALITY_STEPS = [60, 45, 35, 25];
2255
+ var SHRINK_STEPS = [1, 0.8, 0.65, 0.5, 0.35, 0.25];
2256
+ var ADAPT_SHRINK_STEPS = 4;
2257
+ var UP_AFTER_QUICK_FRAMES = 6;
2258
+ var FrameQuality = class {
2259
+ step = 0;
2260
+ quick = 0;
2261
+ get quality() {
2262
+ return QUALITY_STEPS[Math.min(this.step, QUALITY_STEPS.length - 1)];
2263
+ }
2264
+ get shrink() {
2265
+ const s = Math.max(0, this.step - (QUALITY_STEPS.length - 1));
2266
+ return SHRINK_STEPS[Math.min(s, SHRINK_STEPS.length - 1)];
2267
+ }
2268
+ /** The lowest step the link adaptation goes to. */
2269
+ get adaptMaxStep() {
2270
+ return QUALITY_STEPS.length - 1 + ADAPT_SHRINK_STEPS - 1;
2271
+ }
2272
+ get maxStep() {
2273
+ return QUALITY_STEPS.length - 1 + SHRINK_STEPS.length - 1;
2274
+ }
2275
+ /** One acked frame's link time; true when the step changed (restart the screencast). */
2276
+ observe(linkMs) {
2277
+ if (linkMs > TARGET_LINK_MS * 1.25) {
2278
+ this.quick = 0;
2279
+ if (this.step >= this.adaptMaxStep) return false;
2280
+ this.step++;
2281
+ return true;
2282
+ }
2283
+ if (linkMs < TARGET_LINK_MS / 2) {
2284
+ this.quick++;
2285
+ if (this.quick >= UP_AFTER_QUICK_FRAMES && this.step > 0) {
2286
+ this.step--;
2287
+ this.quick = 0;
2288
+ return true;
2289
+ }
2290
+ } else this.quick = 0;
2291
+ return false;
2292
+ }
2293
+ /** A frame too large for one message: always one step smaller. */
2294
+ tooLarge() {
2295
+ this.quick = 0;
2296
+ if (this.step >= this.maxStep) return false;
2297
+ this.step++;
2298
+ return true;
2299
+ }
2300
+ };
2301
+
1586
2302
  // daemon/viewer.ts
1587
- var FRAME_JSON_OVERHEAD = 128;
1588
- var START_QUALITY = 60;
1589
- var MIN_QUALITY = 20;
2303
+ var VIEWER_PING_MS = 1e3;
2304
+ var RESTART_MIN_MS = 500;
2305
+ var ENCODE_MAX_INTERVAL_MS = 500;
2306
+ var CURSOR_TIMEOUT_MS = 200;
1590
2307
  var clampDim = (n, max) => typeof n === "number" && Number.isFinite(n) ? Math.max(16, Math.min(max, Math.floor(n))) : max;
1591
2308
  var ViewerSession = class {
1592
2309
  browser;
@@ -1597,9 +2314,13 @@ var ViewerSession = class {
1597
2314
  unsubscribe = [];
1598
2315
  maxWidth = VIEWPORT.width;
1599
2316
  maxHeight = VIEWPORT.height;
1600
- /** Lowered when a frame does not fit the message cap. */
1601
- quality = START_QUALITY;
1602
- shrink = 1;
2317
+ pacer = new FramePacer({
2318
+ maxFps: VIEWER_MAX_FPS,
2319
+ maxUnacked: VIEWER_UNACKED_FRAMES
2320
+ });
2321
+ /** Quality and scale: lowered while frames are slow on the link or over the message cap. */
2322
+ frameQuality = new FrameQuality();
2323
+ lastRestartAt = Number.NEGATIVE_INFINITY;
1603
2324
  started = false;
1604
2325
  closed = false;
1605
2326
  page;
@@ -1609,14 +2330,42 @@ var ViewerSession = class {
1609
2330
  inputChain = Promise.resolve();
1610
2331
  /** Bumped on close and hand back: input queued before it is dropped, not replayed. */
1611
2332
  inputGen = 0;
2333
+ /**
2334
+ * The newest pointer position not yet applied, while a move for it waits on the input chain:
2335
+ * later moves replace it (the newest wins) instead of queueing behind it.
2336
+ */
2337
+ moveSlot;
2338
+ /** The cursor last sent (reset when control returns to the agent). */
2339
+ cursor;
2340
+ /** Resolves cursors on the attached page (off the input chain, see {@link wantCursor}). */
2341
+ cursorResolver;
2342
+ /** The newest pointer position whose cursor is wanted; one resolution runs at a time. */
2343
+ cursorPoint;
2344
+ /** The resolver a resolution loop runs for (one loop per resolver, one lookup at a time). */
2345
+ cursorLoop;
2346
+ /**
2347
+ * Keys and buttons this viewer pressed and has not released: released for the agent when
2348
+ * control returns to it or the viewer ends, whatever reached the page of the person's input.
2349
+ */
2350
+ heldKeys = /* @__PURE__ */ new Map();
2351
+ heldButtons = /* @__PURE__ */ new Map();
1612
2352
  seq = 0;
1613
- acked = 0;
1614
- lastSentAt = 0;
1615
- /** A screencast frame waiting for room (viewer acks, transport, rate cap); acked once sent. */
2353
+ /**
2354
+ * The newest screencast frame waiting for room (viewer acks, transport, rate cap). A newer one
2355
+ * replaces it: a frame is never queued behind a stale one.
2356
+ */
1616
2357
  pending;
2358
+ /** Chromium frames received but not acked to Chromium yet (it encodes the next after an ack). */
2359
+ encodeAck;
2360
+ encodeTimer;
2361
+ lastEncodeAckAt = Number.NEGATIVE_INFINITY;
1617
2362
  pumpTimer;
2363
+ pingTimer;
2364
+ pingSeq = 0;
2365
+ pingsSent = /* @__PURE__ */ new Map();
1618
2366
  draining = false;
1619
2367
  stateQueued = false;
2368
+ lastControl = "agent";
1620
2369
  constructor(opts) {
1621
2370
  this.browser = opts.browser;
1622
2371
  this.state = opts.state;
@@ -1635,12 +2384,14 @@ var ViewerSession = class {
1635
2384
  if (m.t !== "hello") return;
1636
2385
  this.started = true;
1637
2386
  this.setSize(m.maxWidth, m.maxHeight);
2387
+ this.lastControl = this.state.control;
1638
2388
  this.unsubscribe.push(
1639
2389
  this.browser.on((e) => this.onSession(e)),
1640
- this.state.onChange(() => this.queueState())
2390
+ this.state.onChange(() => this.onControl())
1641
2391
  );
1642
2392
  this.sendState();
1643
2393
  void this.serial(() => this.attach());
2394
+ this.ping();
1644
2395
  return;
1645
2396
  }
1646
2397
  switch (m.t) {
@@ -1653,9 +2404,17 @@ var ViewerSession = class {
1653
2404
  });
1654
2405
  return;
1655
2406
  case "frame-ack":
1656
- if (typeof m.seq === "number" && m.seq > this.acked) this.acked = Math.min(m.seq, this.seq);
2407
+ if (typeof m.seq === "number") this.onAck(Math.min(m.seq, this.seq));
1657
2408
  this.pump();
1658
2409
  return;
2410
+ case "pong": {
2411
+ const sentAt = typeof m.id === "number" ? this.pingsSent.get(m.id) : void 0;
2412
+ if (sentAt !== void 0) {
2413
+ this.pingsSent.delete(m.id);
2414
+ this.pacer.pinged(this.clock.now() - sentAt);
2415
+ }
2416
+ return;
2417
+ }
1659
2418
  case "takeover":
1660
2419
  this.state.takeover();
1661
2420
  return;
@@ -1664,7 +2423,8 @@ var ViewerSession = class {
1664
2423
  this.state.handback();
1665
2424
  return;
1666
2425
  case "mouse":
1667
- this.input(() => this.mouse(m));
2426
+ if (m.kind === "move") this.move(m);
2427
+ else this.input(() => this.mouse(m));
1668
2428
  return;
1669
2429
  case "key":
1670
2430
  this.input(() => this.key(m));
@@ -1693,26 +2453,129 @@ var ViewerSession = class {
1693
2453
  return;
1694
2454
  }
1695
2455
  }
1696
- /** Runs viewer input in arrival order, apart from the screencast chain. */
2456
+ /**
2457
+ * Runs viewer input in arrival order, apart from the screencast chain, and only while the person
2458
+ * holds control: input from a viewer in the watch state (the agent drives) is dropped, both when
2459
+ * it arrives and when its turn comes.
2460
+ */
1697
2461
  input(fn) {
2462
+ if (this.state.control !== "user") return;
2463
+ this.moveSlot = void 0;
1698
2464
  const gen = this.inputGen;
1699
- const guarded = () => gen === this.inputGen && !this.closed ? fn() : Promise.resolve();
2465
+ const guarded = () => gen === this.inputGen && !this.closed && this.state.control === "user" ? fn() : Promise.resolve();
1700
2466
  const run = this.inputChain.then(guarded, guarded);
1701
2467
  this.inputChain = run.catch(() => void 0);
1702
2468
  }
2469
+ /** A pointer move: coalesced while one waits (the newest position wins), then the cursor. */
2470
+ move(m) {
2471
+ if (this.state.control !== "user") return;
2472
+ const p = point(m);
2473
+ if (p === null) return;
2474
+ if (this.moveSlot !== void 0) {
2475
+ this.moveSlot.x = p.x;
2476
+ this.moveSlot.y = p.y;
2477
+ return;
2478
+ }
2479
+ const slot = { ...p };
2480
+ this.input(async () => {
2481
+ if (this.moveSlot === slot) this.moveSlot = void 0;
2482
+ const page = await this.browser.activePage();
2483
+ try {
2484
+ await page.mouse.move(slot.x, slot.y);
2485
+ } catch {
2486
+ return;
2487
+ }
2488
+ this.wantCursor(slot.x, slot.y);
2489
+ });
2490
+ this.moveSlot = slot;
2491
+ }
2492
+ /**
2493
+ * Asks for the page's cursor at (x, y): resolved off the input chain (a click never waits for
2494
+ * it), the newest position wins while one resolution runs, and an answer later than
2495
+ * CURSOR_TIMEOUT_MS is dropped.
2496
+ */
2497
+ wantCursor(x, y) {
2498
+ this.cursorPoint = { x, y };
2499
+ const resolver = this.cursorResolver;
2500
+ if (resolver === void 0 || this.cursorLoop === resolver) return;
2501
+ this.cursorLoop = resolver;
2502
+ void (async () => {
2503
+ try {
2504
+ while (!this.closed && this.cursorResolver === resolver) {
2505
+ const p = this.cursorPoint;
2506
+ this.cursorPoint = void 0;
2507
+ if (p === void 0) return;
2508
+ const started = this.clock.now();
2509
+ const cursor = await resolver.at(p.x, p.y).catch(() => void 0);
2510
+ if (cursor === void 0 || this.clock.now() - started > CURSOR_TIMEOUT_MS) continue;
2511
+ if (this.cursorPoint !== void 0) continue;
2512
+ if (cursor === this.cursor || this.closed || this.state.control !== "user") continue;
2513
+ this.cursor = cursor;
2514
+ this.send({ t: "cursor", cursor });
2515
+ }
2516
+ } finally {
2517
+ if (this.cursorLoop === resolver) this.cursorLoop = void 0;
2518
+ }
2519
+ })();
2520
+ }
2521
+ /**
2522
+ * Releases the keys and buttons this viewer still holds (straight, not on the input chain and
2523
+ * not through the control gate): the agent must not inherit a held Shift or a drag.
2524
+ */
2525
+ async releaseHeld() {
2526
+ if (this.heldKeys.size === 0 && this.heldButtons.size === 0) return;
2527
+ const keys = [...this.heldKeys];
2528
+ const buttons = [...this.heldButtons];
2529
+ this.heldKeys.clear();
2530
+ this.heldButtons.clear();
2531
+ for (const [key2, page] of keys) await page.keyboard.up(key2).catch(() => void 0);
2532
+ for (const [button, page] of buttons) {
2533
+ await page.mouse.move(-1, -1).catch(() => void 0);
2534
+ await page.mouse.up({ button }).catch(() => void 0);
2535
+ }
2536
+ }
2537
+ /** Whether input this viewer applied should stay applied (still in control, not closed). */
2538
+ get driving() {
2539
+ return !this.closed && this.state.control === "user";
2540
+ }
1703
2541
  /** Ends the viewer: stops its screencast and its subscriptions. */
1704
2542
  async close() {
1705
2543
  if (this.closed) return;
1706
2544
  this.closed = true;
1707
2545
  this.inputGen++;
2546
+ await this.releaseHeld();
1708
2547
  for (const u of this.unsubscribe.splice(0)) u();
1709
- if (this.pumpTimer !== void 0) this.clock.cancel(this.pumpTimer);
2548
+ for (const t of [this.pumpTimer, this.pingTimer, this.encodeTimer])
2549
+ if (t !== void 0) this.clock.cancel(t);
1710
2550
  await this.serial(() => this.detach());
1711
2551
  }
1712
2552
  setSize(w, h) {
1713
2553
  this.maxWidth = clampDim(w, VIEWPORT.width);
1714
2554
  this.maxHeight = clampDim(h, VIEWPORT.height);
1715
- this.shrink = 1;
2555
+ }
2556
+ /** Pings the viewer every VIEWER_PING_MS (its pong measures the path, see the pacing). */
2557
+ ping() {
2558
+ if (this.closed) return;
2559
+ const id = ++this.pingSeq;
2560
+ this.pingsSent.set(id, this.clock.now());
2561
+ for (const old of this.pingsSent.keys()) if (old < id - 4) this.pingsSent.delete(old);
2562
+ this.send({ t: "ping", id });
2563
+ this.pingTimer = this.clock.schedule(() => this.ping(), VIEWER_PING_MS);
2564
+ }
2565
+ /** Control changed (takeover, hand back): a new state, and input of the old control dropped. */
2566
+ onControl() {
2567
+ const control = this.state.control;
2568
+ if (control !== this.lastControl) {
2569
+ this.lastControl = control;
2570
+ this.moveSlot = void 0;
2571
+ this.cursor = void 0;
2572
+ this.cursorPoint = void 0;
2573
+ if (control === "agent") {
2574
+ this.inputGen++;
2575
+ void this.releaseHeld();
2576
+ }
2577
+ }
2578
+ this.queueState();
1716
2579
  }
1717
2580
  serial(fn) {
1718
2581
  const run = this.chain.then(fn, fn);
@@ -1726,33 +2589,41 @@ var ViewerSession = class {
1726
2589
  */
1727
2590
  fitted(m) {
1728
2591
  const fits = (x) => Buffer.byteLength(JSON.stringify(x)) <= this.frameMaxBytes;
1729
- if (m.t === "frame" || fits(m)) return m;
2592
+ if (fits(m)) return m;
1730
2593
  let small;
1731
2594
  if (m.t === "state") {
1732
2595
  const handoff = m.handoff === void 0 ? {} : { handoff: { ...m.handoff, message: clip(m.handoff.message, 200) } };
1733
2596
  small = {
1734
2597
  ...m,
1735
- tabs: m.tabs.map((t) => ({ ...t, title: clip(t.title, 200), url: clip(t.url, 200) })),
2598
+ tabs: m.tabs.map((t) => ({
2599
+ ...t,
2600
+ title: clip(t.title, 200),
2601
+ url: clip(t.url, 200),
2602
+ ...t.blocker === void 0 ? {} : { blocker: { ...t.blocker, url: clip(t.blocker.url, 200) } }
2603
+ })),
1736
2604
  ...handoff
1737
2605
  };
1738
2606
  } else if (m.t === "dialog") {
1739
2607
  small = { ...m, message: clip(m.message, 200) };
1740
- } else {
2608
+ } else if (m.t === "blocked") {
1741
2609
  small = { ...m, url: clip(m.url, 200) };
1742
- }
2610
+ } else return null;
1743
2611
  return fits(small) ? small : null;
1744
2612
  }
2613
+ /** Sends a JSON message at once: it never waits behind a held frame. */
1745
2614
  send(raw) {
1746
2615
  if (this.closed) return;
1747
2616
  const m = this.fitted(raw);
1748
2617
  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
- }
2618
+ if (!this.out.send(m)) this.awaitDrain();
2619
+ }
2620
+ awaitDrain() {
2621
+ if (this.draining) return;
2622
+ this.draining = true;
2623
+ this.out.whenDrained().then(() => {
2624
+ this.draining = false;
2625
+ this.pump();
2626
+ });
1756
2627
  }
1757
2628
  onSession(e) {
1758
2629
  if (e.type === "state") this.queueState();
@@ -1791,11 +2662,11 @@ var ViewerSession = class {
1791
2662
  });
1792
2663
  }
1793
2664
  get scale() {
1794
- return Math.min(1, this.maxWidth / VIEWPORT.width, this.maxHeight / VIEWPORT.height) * this.shrink;
2665
+ return Math.min(1, this.maxWidth / VIEWPORT.width, this.maxHeight / VIEWPORT.height) * this.frameQuality.shrink;
1795
2666
  }
1796
- /** Room for the JPEG's decoded bytes in one frame message. */
2667
+ /** Room for the JPEG in one frame message. */
1797
2668
  get jpegBudget() {
1798
- return Math.floor((this.frameMaxBytes - FRAME_JSON_OVERHEAD) * 3 / 4);
2669
+ return this.frameMaxBytes - FRAME_HEADER_BYTES;
1799
2670
  }
1800
2671
  async attach() {
1801
2672
  if (this.closed) return;
@@ -1804,12 +2675,19 @@ var ViewerSession = class {
1804
2675
  this.page = page;
1805
2676
  this.cdp = cdp;
1806
2677
  cdp.on("Page.screencastFrame", (f) => this.onFrame(cdp, f));
2678
+ this.cursorResolver = new CursorResolver(this.browser.context, page, cdp);
1807
2679
  const first = await captureFitting(cdp, {
1808
2680
  maxBytes: this.jpegBudget,
1809
2681
  maxScale: this.scale
1810
2682
  }).catch(() => null);
1811
2683
  if (first !== null && this.cdp === cdp) {
1812
- this.sendFrame(first.data, first.width, first.height);
2684
+ this.pending = {
2685
+ cdp,
2686
+ jpeg: Buffer.from(first.data, "base64"),
2687
+ width: first.width,
2688
+ height: first.height
2689
+ };
2690
+ this.pump();
1813
2691
  }
1814
2692
  await this.startScreencast(cdp);
1815
2693
  }
@@ -1817,7 +2695,7 @@ var ViewerSession = class {
1817
2695
  if (this.closed || this.cdp !== cdp) return;
1818
2696
  await cdp.send("Page.startScreencast", {
1819
2697
  format: "jpeg",
1820
- quality: this.quality,
2698
+ quality: this.frameQuality.quality,
1821
2699
  maxWidth: Math.max(16, Math.floor(VIEWPORT.width * this.scale)),
1822
2700
  maxHeight: Math.max(16, Math.floor(VIEWPORT.height * this.scale)),
1823
2701
  everyNthFrame: 1
@@ -1828,94 +2706,159 @@ var ViewerSession = class {
1828
2706
  this.cdp = void 0;
1829
2707
  this.page = void 0;
1830
2708
  this.pending = void 0;
2709
+ this.encodeAck = void 0;
2710
+ this.cursorResolver?.dispose();
2711
+ this.cursorResolver = void 0;
1831
2712
  if (cdp === void 0) return;
1832
2713
  await cdp.send("Page.stopScreencast").catch(() => void 0);
1833
2714
  await cdp.detach().catch(() => void 0);
1834
2715
  }
1835
2716
  sendFrame(jpeg, width, height) {
1836
2717
  this.seq++;
1837
- this.lastSentAt = this.clock.now();
1838
- this.send({ t: "frame", seq: this.seq, jpeg, width, height });
2718
+ this.pacer.sent(this.seq, this.clock.now());
2719
+ if (!this.out.sendFrame(encodeFrame({ seq: this.seq, width, height, jpeg }))) this.awaitDrain();
2720
+ }
2721
+ /** The viewer acked frames up to `seq`: the link time adapts quality and scale. */
2722
+ onAck(seq) {
2723
+ const sample = this.pacer.acked(seq, this.clock.now());
2724
+ if (sample === void 0) return;
2725
+ if (this.clock.now() - this.lastRestartAt < RESTART_MIN_MS) return;
2726
+ if (this.frameQuality.observe(this.pacer.linkMs ?? sample)) this.restart();
2727
+ }
2728
+ /** Restarts the screencast at the current quality and scale. */
2729
+ restart() {
2730
+ const cdp = this.cdp;
2731
+ if (cdp === void 0) return;
2732
+ this.lastRestartAt = this.clock.now();
2733
+ this.pacer.reset();
2734
+ void this.serial(async () => {
2735
+ if (this.cdp !== cdp) return;
2736
+ await cdp.send("Page.stopScreencast").catch(() => void 0);
2737
+ this.pending = void 0;
2738
+ this.encodeAck = void 0;
2739
+ await this.startScreencast(cdp);
2740
+ });
1839
2741
  }
1840
2742
  onFrame(cdp, f) {
1841
2743
  if (this.closed || this.cdp !== cdp) return;
1842
2744
  const bytes = Buffer.from(f.data, "base64");
1843
2745
  if (bytes.length > this.jpegBudget) {
1844
2746
  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
- });
2747
+ if (this.frameQuality.tooLarge()) this.restart();
1852
2748
  return;
1853
2749
  }
1854
2750
  const { width, height } = jpegSize(bytes);
1855
- this.pending = { cdp, sessionId: f.sessionId, data: f.data, width, height };
2751
+ this.pending = { cdp, jpeg: bytes, width, height };
2752
+ this.encodeAck = { cdp, sessionId: f.sessionId };
1856
2753
  this.pump();
2754
+ this.scheduleEncodeAck();
1857
2755
  }
1858
2756
  /**
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.
2757
+ * Lets Chromium encode its next frame (screencastFrameAck): at most at the viewer's frame rate
2758
+ * while frames flow, and while one waits for the viewer only every ENCODE_MAX_INTERVAL_MS, so
2759
+ * the frame sent when room comes is a recent one without encoding frames nobody gets.
2760
+ */
2761
+ scheduleEncodeAck() {
2762
+ if (this.encodeTimer !== void 0) this.clock.cancel(this.encodeTimer);
2763
+ this.encodeTimer = void 0;
2764
+ const ack = this.encodeAck;
2765
+ if (ack === void 0 || this.closed) return;
2766
+ const gap = this.pending === void 0 ? 1e3 / VIEWER_MAX_FPS : ENCODE_MAX_INTERVAL_MS;
2767
+ const wait = this.lastEncodeAckAt + gap - this.clock.now();
2768
+ if (wait > 0) {
2769
+ this.encodeTimer = this.clock.schedule(() => {
2770
+ this.encodeTimer = void 0;
2771
+ this.scheduleEncodeAck();
2772
+ }, wait);
2773
+ return;
2774
+ }
2775
+ this.encodeAck = void 0;
2776
+ if (this.cdp !== ack.cdp) return;
2777
+ this.lastEncodeAckAt = this.clock.now();
2778
+ ack.cdp.send("Page.screencastFrameAck", { sessionId: ack.sessionId }).catch(() => void 0);
2779
+ }
2780
+ /**
2781
+ * Sends the newest screencast frame once the pacer allows (viewer acks, link time, rate cap)
2782
+ * and the transport is not backed up.
1862
2783
  */
1863
2784
  pump() {
1864
2785
  const pending = this.pending;
1865
2786
  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) {
2787
+ const d = this.pacer.decide(this.clock.now());
2788
+ if (!d.ok) {
2789
+ if (d.waitMs !== void 0 && this.pumpTimer === void 0) {
1870
2790
  this.pumpTimer = this.clock.schedule(() => {
1871
2791
  this.pumpTimer = void 0;
1872
2792
  this.pump();
1873
- }, wait);
2793
+ }, d.waitMs);
1874
2794
  }
1875
2795
  return;
1876
2796
  }
1877
2797
  this.pending = void 0;
1878
2798
  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);
2799
+ this.sendFrame(pending.jpeg, pending.width, pending.height);
2800
+ this.scheduleEncodeAck();
1881
2801
  }
1882
2802
  async mouse(m) {
1883
2803
  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)));
2804
+ const p = point(m);
2805
+ if (p === null) return;
2806
+ const { x, y } = p;
1887
2807
  const button = m.button === "right" ? "right" : "left";
1888
2808
  try {
1889
- if (m.kind === "move") await page.mouse.move(x, y);
1890
- else if (m.kind === "down") {
2809
+ if (m.kind === "down") {
1891
2810
  await page.mouse.move(x, y);
1892
2811
  await page.mouse.down({ button });
2812
+ if (this.driving) this.heldButtons.set(button, page);
2813
+ else await page.mouse.up({ button });
1893
2814
  } else if (m.kind === "up") {
2815
+ this.heldButtons.delete(button);
1894
2816
  await page.mouse.move(x, y);
1895
2817
  await page.mouse.up({ button });
1896
2818
  } else if (m.kind === "wheel") {
1897
2819
  await page.mouse.move(x, y);
1898
2820
  await page.mouse.wheel(Number(m.dx) || 0, Number(m.dy) || 0);
1899
- }
2821
+ } else return;
1900
2822
  } catch {
2823
+ return;
1901
2824
  }
2825
+ if (m.kind !== "down") this.wantCursor(x, y);
1902
2826
  }
1903
2827
  async key(m) {
1904
2828
  const page = await this.browser.activePage();
1905
2829
  try {
1906
2830
  if (m.kind === "char") {
1907
2831
  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);
2832
+ if (typeof text === "string" && text !== "")
2833
+ await page.keyboard.insertText(clipCodePoints(text, VIEWER_TEXT_MAX_CHARS));
2834
+ } else if (m.kind === "down") {
2835
+ await page.keyboard.down(m.key);
2836
+ if (this.driving) this.heldKeys.set(m.key, page);
2837
+ else await page.keyboard.up(m.key);
2838
+ } else if (m.kind === "up") {
2839
+ this.heldKeys.delete(m.key);
2840
+ await page.keyboard.up(m.key);
2841
+ }
1911
2842
  } catch {
1912
2843
  }
1913
2844
  }
1914
2845
  };
2846
+ function point(m) {
2847
+ const x = Number(m.x);
2848
+ const y = Number(m.y);
2849
+ if (!Number.isFinite(x) || !Number.isFinite(y)) return null;
2850
+ return {
2851
+ x: Math.max(0, Math.min(VIEWPORT.width - 1, x)),
2852
+ y: Math.max(0, Math.min(VIEWPORT.height - 1, y))
2853
+ };
2854
+ }
1915
2855
 
1916
2856
  // daemon/main.ts
2857
+ var SEALED_EXIT_GRACE_MS = 2e3;
1917
2858
  var SERVICE_WORKSPACE_ENV = "CAPYBARA_SERVICE_WORKSPACE";
1918
2859
  var BROWSER_CLOSE_GRACE_MS = 3e3;
2860
+ var PROCESS_POLL_MS = 10;
2861
+ var COOKIE_SAVE_MS = 500;
1919
2862
  var enc = new TextEncoder();
1920
2863
  var dec = new TextDecoder();
1921
2864
  var REQUEST_OPS = /* @__PURE__ */ new Set([
@@ -1999,7 +2942,7 @@ async function startDaemon(opts) {
1999
2942
  let current;
2000
2943
  let running;
2001
2944
  let restored = false;
2002
- function within(value, ms) {
2945
+ function within2(value, ms) {
2003
2946
  let timer;
2004
2947
  return Promise.race([
2005
2948
  value,
@@ -2041,9 +2984,9 @@ async function startDaemon(opts) {
2041
2984
  if (running?.launch === starting) running = void 0;
2042
2985
  if (!closing && !failed()) opts.onBrowserGone?.();
2043
2986
  });
2044
- const pid = await within(browserProcessId(ctx), BROWSER_CLOSE_GRACE_MS);
2987
+ const pid = await within2(browserProcessId(ctx), BROWSER_CLOSE_GRACE_MS);
2045
2988
  setPid(pid);
2046
- if (!gone) running = { launch: starting, pid };
2989
+ if (!gone) running = { launch: starting, pid, ctx };
2047
2990
  const workspace = opts.env[SERVICE_WORKSPACE_ENV];
2048
2991
  const session = new BrowserSession(ctx, {
2049
2992
  proxy: plan.proxy,
@@ -2053,6 +2996,9 @@ async function startDaemon(opts) {
2053
2996
  downloadMaxBytes: downloadMaxBytes(opts.env),
2054
2997
  ...opts.downloadWaitMs === void 0 ? {} : { downloadWaitMs: opts.downloadWaitMs }
2055
2998
  });
2999
+ if (plan.shippedDir !== void 0)
3000
+ session.note(shippedRevisionNote(plan.shippedDir, browserRevision(plan.build)));
3001
+ if (!closing) await restoreCookies(ctx, opts.stateDir);
2056
3002
  if (!restored && !closing) {
2057
3003
  restored = true;
2058
3004
  if (saved !== void 0) await sessionFile.restoreTabs(session, saved);
@@ -2070,13 +3016,16 @@ async function startDaemon(opts) {
2070
3016
  () => true,
2071
3017
  () => true
2072
3018
  );
2073
- if (await within(done, closeGraceMs) === true) return;
3019
+ if (await within2(done, closeGraceMs) === true) return;
2074
3020
  const id = pid();
2075
3021
  if (id === void 0) return;
2076
3022
  killChromium(id);
2077
- await within(done, closeGraceMs);
3023
+ await within2(done, closeGraceMs);
2078
3024
  }
2079
3025
  async function launchFailure(e) {
3026
+ if (e instanceof BrowserInstalledError)
3027
+ return { ok: false, error: "restart", message: e.message, blockedHosts: [] };
3028
+ if (plan.unavailable !== void 0) return fail(plan.unavailable);
2080
3029
  const cause = e instanceof Error ? e.message.split("\n")[0] : String(e);
2081
3030
  const proxy = plan.proxy;
2082
3031
  const refused = proxy === void 0 ? [] : (await Promise.all(
@@ -2098,16 +3047,28 @@ async function startDaemon(opts) {
2098
3047
  async function stopBrowser() {
2099
3048
  const starting = current;
2100
3049
  if (starting === void 0) return;
3050
+ const r = running?.launch === starting ? running : void 0;
3051
+ const pid = r?.pid;
3052
+ if (r !== void 0) await within2(saveCookies(r.ctx, opts.stateDir), COOKIE_SAVE_MS);
2101
3053
  await closeOrKill(
2102
3054
  starting.then(
2103
- (session) => session.close(),
3055
+ async (session) => {
3056
+ await session.close();
3057
+ if (pid !== void 0) await processGone(pid);
3058
+ },
2104
3059
  () => void 0
2105
3060
  ),
2106
- () => running?.launch === starting ? running.pid : void 0
3061
+ () => pid
2107
3062
  );
2108
3063
  }
3064
+ async function processGone(pid) {
3065
+ while (processAlive(pid)) await new Promise((r) => clock.schedule(r, PROCESS_POLL_MS));
3066
+ }
2109
3067
  const ready = browser().then(() => void 0);
2110
- ready.catch(() => void 0);
3068
+ ready.catch((e) => {
3069
+ if (e instanceof BrowserInstalledError)
3070
+ clock.schedule(() => opts.onSealed?.(), SEALED_EXIT_GRACE_MS);
3071
+ });
2111
3072
  async function handoffOp(req) {
2112
3073
  if (typeof req.callId !== "string" || req.callId === "")
2113
3074
  return fail("The handoff needs a callId.");
@@ -2196,6 +3157,10 @@ async function startDaemon(opts) {
2196
3157
  });
2197
3158
  return ok || dropped || sock.destroyed;
2198
3159
  },
3160
+ sendFrame: (frame) => {
3161
+ if (sock.destroyed) return true;
3162
+ return sock.write(encodeServiceMessage(frame));
3163
+ },
2199
3164
  whenDrained: () => new Promise((r) => sock.once("drain", () => r()))
2200
3165
  }
2201
3166
  });
@@ -2212,6 +3177,7 @@ async function startDaemon(opts) {
2212
3177
  handleRequest(parse(raw)).catch((e) => fail(e instanceof ActionError ? e.message : String(e))).then((reply) => {
2213
3178
  write(sock, reply, () => write(sock, fail(REPLY_TOO_LARGE_MESSAGE), () => void 0));
2214
3179
  sock.end();
3180
+ if (!reply.ok && reply.error === "restart") sock.once("close", () => opts.onSealed?.());
2215
3181
  }).catch(() => sock.destroy()).finally(() => state.requestEnded());
2216
3182
  return;
2217
3183
  }
@@ -2230,7 +3196,7 @@ async function startDaemon(opts) {
2230
3196
  for (const m of msgs) onMessage(m);
2231
3197
  });
2232
3198
  }
2233
- if (existsSync2(opts.socketPath)) unlinkSync(opts.socketPath);
3199
+ if (existsSync2(opts.socketPath)) unlinkSync2(opts.socketPath);
2234
3200
  const server = createServer(onConnection);
2235
3201
  await new Promise((resolve, reject) => {
2236
3202
  server.once("error", reject);
@@ -2254,7 +3220,7 @@ async function startDaemon(opts) {
2254
3220
  await stopBrowser();
2255
3221
  if (existsSync2(opts.socketPath)) {
2256
3222
  try {
2257
- unlinkSync(opts.socketPath);
3223
+ unlinkSync2(opts.socketPath);
2258
3224
  } catch {
2259
3225
  }
2260
3226
  }
@@ -2290,7 +3256,9 @@ async function main() {
2290
3256
  stateDir,
2291
3257
  env: process.env,
2292
3258
  onIdle: () => stop(0, "idle"),
2293
- onBrowserGone: () => stop(1, "Chromium exited")
3259
+ onBrowserGone: () => stop(1, "Chromium exited"),
3260
+ // installed and sealed: the next start runs the browser read only
3261
+ onSealed: () => stop(0, "browser installed and sealed; restart to run it")
2294
3262
  });
2295
3263
  process.stderr.write(`browser daemon: listening on ${socketPath}
2296
3264
  `);