@capybara-hq/plugin-browser 0.1.0-rc.3 → 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,17 +436,155 @@ 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/;
481
+ function docUrl(raw) {
482
+ try {
483
+ const u = new URL(raw);
484
+ u.hash = "";
485
+ return u.href;
486
+ } catch {
487
+ return raw;
488
+ }
489
+ }
490
+ var NavWatch = class {
491
+ constructor(page, url, pending) {
492
+ this.page = page;
493
+ this.pending = pending;
494
+ this.target = docUrl(url);
495
+ const before = pending();
496
+ if (before !== void 0 && this.isOurs(before)) this.lastOurs = before;
497
+ page.on("request", this.onRequest);
498
+ page.on("framenavigated", this.onNavigated);
499
+ page.on("requestfailed", this.onFailed);
500
+ page.on("requestfinished", this.onFinished);
501
+ }
502
+ page;
503
+ pending;
504
+ target;
505
+ /** The newest main-frame navigation request to the target address (redirects included). */
506
+ lastOurs;
507
+ /** The request of `lastOurs`'s chain whose document the main frame committed. */
508
+ committedOurs;
509
+ /** The request of `lastOurs`'s chain that failed. */
510
+ failedOurs;
511
+ wake;
512
+ onRequest = (r) => {
513
+ if (!r.isNavigationRequest() || r.frame() !== this.page.mainFrame()) return;
514
+ this.lastOurs = this.isOurs(r) ? r : void 0;
515
+ this.wake?.();
516
+ };
517
+ onNavigated = (f) => {
518
+ if (f !== this.page.mainFrame()) return;
519
+ const ours = this.lastOurs;
520
+ if (ours !== void 0 && docUrl(this.page.mainFrame().url()) === docUrl(ours.url()))
521
+ this.committedOurs = ours;
522
+ this.wake?.();
523
+ };
524
+ onFailed = (r) => {
525
+ if (r === this.lastOurs) this.failedOurs = r;
526
+ this.wake?.();
527
+ };
528
+ /** After the session's own `requestfinished` handler (registered first) settled the request. */
529
+ onFinished = (r) => {
530
+ if (!r.isNavigationRequest() || r.frame() !== this.page.mainFrame()) return;
531
+ const wake = () => this.wake?.();
532
+ void r.response().then(wake, wake);
533
+ };
534
+ isOurs(r) {
535
+ let root = r;
536
+ for (let from = r.redirectedFrom(); from !== null; from = from.redirectedFrom()) root = from;
537
+ return docUrl(root.url()) === this.target;
538
+ }
539
+ /** Resolves on the next navigation event or after `ms`. */
540
+ next(ms) {
541
+ return new Promise((resolve) => {
542
+ const timer = setTimeout(done, ms);
543
+ function done() {
544
+ clearTimeout(timer);
545
+ resolve();
546
+ }
547
+ this.wake = () => {
548
+ this.wake = void 0;
549
+ done();
550
+ };
551
+ });
552
+ }
553
+ /**
554
+ * After an abort: waits (until `deadline`, the navigation's own) while a navigation to the
555
+ * target address is in flight, then tells whether it loaded (its document committed; a script
556
+ * may have moved the page on since), failed, or none of ours took over.
557
+ */
558
+ async follow(deadline) {
559
+ for (let r = this.pending(); r !== void 0; r = this.pending()) {
560
+ if (!this.isOurs(r)) return { kind: "none" };
561
+ const left2 = deadline - Date.now();
562
+ if (left2 <= 0) return { kind: "none" };
563
+ await this.next(left2);
564
+ }
565
+ const final = this.lastOurs;
566
+ if (final === void 0) return { kind: "none" };
567
+ if (this.failedOurs === final) {
568
+ return { kind: "failed", url: final.url(), error: final.failure()?.errorText ?? "" };
569
+ }
570
+ if (this.committedOurs !== final) return { kind: "none" };
571
+ const left = deadline - Date.now();
572
+ if (left <= 0) return { kind: "none" };
573
+ try {
574
+ await this.page.waitForLoadState("domcontentloaded", { timeout: left });
575
+ } catch {
576
+ return { kind: "none" };
577
+ }
578
+ return { kind: "loaded", response: await final.response().catch(() => null) };
579
+ }
580
+ dispose() {
581
+ this.page.off("request", this.onRequest);
582
+ this.page.off("framenavigated", this.onNavigated);
583
+ this.page.off("requestfailed", this.onFailed);
584
+ this.page.off("requestfinished", this.onFinished);
585
+ this.wake?.();
586
+ }
587
+ };
337
588
  function jpegSize(jpeg) {
338
589
  let i = 2;
339
590
  while (i + 9 < jpeg.length) {
@@ -443,6 +694,12 @@ var BrowserSession = class {
443
694
  ids = /* @__PURE__ */ new WeakMap();
444
695
  titles = /* @__PURE__ */ new Map();
445
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();
701
+ /** Each page's main-frame navigation request in flight (until it commits, fails or finishes). */
702
+ pendingNavs = /* @__PURE__ */ new WeakMap();
446
703
  listeners = /* @__PURE__ */ new Set();
447
704
  collectors = /* @__PURE__ */ new Set();
448
705
  probes = /* @__PURE__ */ new Map();
@@ -504,12 +761,16 @@ var BrowserSession = class {
504
761
  return this.ids.get(page) ?? "";
505
762
  }
506
763
  tabs() {
507
- return [...this.pages.entries()].map(([id, p]) => ({
508
- id,
509
- title: clip(this.titles.get(id) ?? "", MAX_TITLE_CHARS),
510
- url: clip(p.url(), MAX_URL_CHARS),
511
- active: id === this.active
512
- }));
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
+ });
513
774
  }
514
775
  /** Whether the active tab is loading a document. */
515
776
  get loading() {
@@ -529,16 +790,34 @@ var BrowserSession = class {
529
790
  this.ids.set(page, id);
530
791
  this.pages.set(id, page);
531
792
  const refresh = () => {
532
- 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" }));
533
794
  };
795
+ const settle = (r) => {
796
+ if (this.pendingNavs.get(page) === r) this.pendingNavs.delete(page);
797
+ };
798
+ page.on("requestfinished", (r) => {
799
+ if (this.pendingNavs.get(page) !== r) return;
800
+ void r.response().then(
801
+ (res) => {
802
+ const status = res?.status() ?? 0;
803
+ const redirects = status >= 300 && status < 400 && res?.headers().location;
804
+ if (!redirects) settle(r);
805
+ },
806
+ () => settle(r)
807
+ );
808
+ });
534
809
  page.on("request", (r) => {
535
810
  if (r.isNavigationRequest() && r.frame() === page.mainFrame()) {
811
+ this.pendingNavs.set(page, r);
536
812
  this.loadingTabs.add(id);
537
813
  this.emit({ type: "state" });
538
814
  }
539
815
  });
540
816
  page.on("framenavigated", (f) => {
541
- if (f === page.mainFrame()) refresh();
817
+ if (f !== page.mainFrame()) return;
818
+ this.pendingNavs.delete(page);
819
+ this.blockers.delete(id);
820
+ refresh();
542
821
  });
543
822
  page.on("domcontentloaded", refresh);
544
823
  page.on("load", () => {
@@ -546,6 +825,7 @@ var BrowserSession = class {
546
825
  refresh();
547
826
  });
548
827
  page.on("requestfailed", (r) => {
828
+ settle(r);
549
829
  const err = r.failure()?.errorText ?? "";
550
830
  if (r.isNavigationRequest() && r.frame() === page.mainFrame()) {
551
831
  this.loadingTabs.delete(id);
@@ -555,6 +835,8 @@ var BrowserSession = class {
555
835
  this.checkBlocked(r.url(), this.pageToOpen(page, r));
556
836
  });
557
837
  page.on("response", (r) => {
838
+ if (r.request().isNavigationRequest() && r.frame() === page.mainFrame())
839
+ this.docStatus.set(id, r.status());
558
840
  if (this.proxy !== void 0 && r.status() === 403 && r.url().startsWith("http:")) {
559
841
  this.checkBlocked(r.url(), this.pageToOpen(page, r.request()));
560
842
  }
@@ -566,9 +848,12 @@ var BrowserSession = class {
566
848
  this.emit({ type: "dialog", kind: "file", message: "" });
567
849
  });
568
850
  page.on("close", () => {
851
+ this.pendingNavs.delete(page);
569
852
  this.pages.delete(id);
570
853
  this.titles.delete(id);
571
854
  this.loadingTabs.delete(id);
855
+ this.blockers.delete(id);
856
+ this.docStatus.delete(id);
572
857
  if (this.active === id) {
573
858
  const next = [...this.pages.keys()].at(-1);
574
859
  this.active = next;
@@ -640,8 +925,7 @@ var BrowserSession = class {
640
925
  );
641
926
  return;
642
927
  }
643
- target = this.downloadTarget(workspace, safeFileName(d.suggestedFilename()));
644
- await d.saveAs(target);
928
+ target = this.saveDownload(workspace, safeFileName(d.suggestedFilename()), tmp);
645
929
  this.note(`Downloaded ${shown} to ${target}.`);
646
930
  } catch (e) {
647
931
  this.note(
@@ -656,8 +940,62 @@ var BrowserSession = class {
656
940
  })();
657
941
  for (const c of this.collectors) c.downloads.push(entry);
658
942
  }
659
- /** A free path in `<workspace>/downloads`, refusing a downloads directory that is a link. */
660
- 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) {
661
999
  const root = realpathSync(workspace);
662
1000
  const dir = join(root, "downloads");
663
1001
  mkdirSync(dir, { recursive: true });
@@ -668,14 +1006,7 @@ var BrowserSession = class {
668
1006
  `${dir} is not a plain directory in the workspace; remove it so downloads can be saved.`
669
1007
  );
670
1008
  }
671
- const ext = extname(name);
672
- const stem = name.slice(0, name.length - ext.length);
673
- let target = join(dir, name);
674
- for (let i = 1; !absent(target) || this.reservedDownloads.has(target); i++) {
675
- target = join(dir, `${stem} (${i})${ext}`);
676
- }
677
- this.reservedDownloads.add(target);
678
- return target;
1009
+ return dir;
679
1010
  }
680
1011
  /**
681
1012
  * While downloads run, sums the bytes of Playwright's in-progress files and cancels every
@@ -717,29 +1048,69 @@ var BrowserSession = class {
717
1048
  this.pollDownloads();
718
1049
  }, DOWNLOAD_POLL_MS);
719
1050
  }
720
- /** The real path of an upload, refused unless it is inside the workspace. */
721
- uploadPath(path) {
722
- const workspace = this.workspace;
723
- if (workspace === void 0) {
724
- throw new ActionError("failed", "Uploads are unavailable: the device has no workspace.");
725
- }
726
- const root = realpathSync(workspace);
727
- 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;
728
1061
  try {
729
- real = realpathSync(path);
730
- } catch {
1062
+ fd = openSync(path, fsc.O_RDONLY | fsc.O_NOFOLLOW | fsc.O_NONBLOCK);
1063
+ } catch (e) {
1064
+ const code = e.code;
731
1065
  throw new ActionError(
732
1066
  "failed",
733
- `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}).`
734
1068
  );
735
1069
  }
736
- if (real !== root && !real.startsWith(root.endsWith(sep) ? root : root + sep)) {
737
- throw new ActionError(
738
- "failed",
739
- `Upload paths must be inside the workspace (${root}); copy the file there first.`
740
- );
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);
741
1105
  }
742
- return real;
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.");
1112
+ }
1113
+ return realpathSync(workspace);
743
1114
  }
744
1115
  /**
745
1116
  * The page a viewer opens once the refused host is allowed: the navigation's target for a
@@ -804,7 +1175,12 @@ var BrowserSession = class {
804
1175
  await this.settleDownloads(c);
805
1176
  this.collectors.delete(c);
806
1177
  const page = await this.activePage();
807
- 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");
808
1184
  reply = {
809
1185
  ok: true,
810
1186
  page: await this.pageInfo(page),
@@ -858,6 +1234,27 @@ var BrowserSession = class {
858
1234
  await Promise.allSettled(all);
859
1235
  }
860
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
+ }
861
1258
  async pageInfo(page) {
862
1259
  let title = "";
863
1260
  try {
@@ -939,6 +1336,8 @@ var BrowserSession = class {
939
1336
  let res;
940
1337
  const download = page.waitForEvent("download", { timeout: ACTION_TIMEOUT_MS });
941
1338
  download.catch(() => void 0);
1339
+ const deadline = Date.now() + NAVIGATION_TIMEOUT_MS;
1340
+ const watch = new NavWatch(page, url, () => this.pendingNavs.get(page));
942
1341
  try {
943
1342
  res = await page.goto(url, { waitUntil: "domcontentloaded" });
944
1343
  } catch (e) {
@@ -948,7 +1347,16 @@ var BrowserSession = class {
948
1347
  return;
949
1348
  }
950
1349
  if (PROXY_FAILURE_RE.test(msg)) await this.checkBlocked(url);
951
- throw e;
1350
+ if (!msg.includes("net::ERR_ABORTED")) throw e;
1351
+ const out = await watch.follow(deadline);
1352
+ if (out.kind === "none") throw e;
1353
+ if (out.kind === "failed") {
1354
+ if (PROXY_FAILURE_RE.test(out.error)) await this.checkBlocked(out.url);
1355
+ throw new Error(`${out.error} at ${out.url}`);
1356
+ }
1357
+ res = out.response;
1358
+ } finally {
1359
+ watch.dispose();
952
1360
  }
953
1361
  if (res?.status() === 403 && await this.checkBlocked(res.url())) {
954
1362
  throw new ActionError(
@@ -1030,9 +1438,9 @@ var BrowserSession = class {
1030
1438
  }
1031
1439
  case "upload": {
1032
1440
  const page = await this.activePage();
1033
- const path = this.uploadPath(req.path);
1441
+ const file = this.readUpload(req.path);
1034
1442
  const loc = await this.locate(page, req.ref);
1035
- await loc.setInputFiles(path);
1443
+ await loc.setInputFiles(file);
1036
1444
  return {};
1037
1445
  }
1038
1446
  case "click_at":
@@ -1198,15 +1606,30 @@ var BrowserSession = class {
1198
1606
  };
1199
1607
 
1200
1608
  // daemon/chromium.ts
1201
- 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";
1202
1618
  import { createRequire } from "node:module";
1203
- import { dirname, join as join2 } from "node:path";
1619
+ import { dirname, isAbsolute, join as join2, relative } from "node:path";
1204
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
+ };
1205
1628
  function envValue(env, name) {
1206
1629
  const v = env[name] ?? env[name.toLowerCase()];
1207
1630
  return v === void 0 || v === "" ? void 0 : v;
1208
1631
  }
1209
- function headlessShellRevision() {
1632
+ function browserRelease(build) {
1210
1633
  const candidates = [new URL("./vendor/playwright-core/browsers.json", import.meta.url)];
1211
1634
  try {
1212
1635
  const pkg = createRequire(import.meta.url).resolve("playwright-core/package.json");
@@ -1216,13 +1639,25 @@ function headlessShellRevision() {
1216
1639
  for (const file of candidates) {
1217
1640
  try {
1218
1641
  const json = JSON.parse(readFileSync(fileURLToPath(file), "utf8"));
1219
- const rev = json.browsers?.find((b) => b.name === "chromium-headless-shell")?.revision;
1220
- 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
+ };
1221
1648
  } catch {
1222
1649
  }
1223
1650
  }
1224
1651
  return void 0;
1225
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
+ }
1226
1661
  function playwrightDownloadHosts(env) {
1227
1662
  const custom = envValue(env, "PLAYWRIGHT_CHROMIUM_DOWNLOAD_HOST") ?? envValue(env, "PLAYWRIGHT_DOWNLOAD_HOST");
1228
1663
  if (custom !== void 0) {
@@ -1234,15 +1669,76 @@ function playwrightDownloadHosts(env) {
1234
1669
  }
1235
1670
  return ["cdn.playwright.dev", "playwright.download.prss.microsoft.com", "storage.googleapis.com"];
1236
1671
  }
1237
- 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
+ }
1238
1708
  const cache = envValue(env, "PLAYWRIGHT_BROWSERS_PATH");
1239
- if (cache !== void 0 && revision !== void 0 && existsSync(join2(cache, `chromium_headless_shell-${revision}`)))
1240
- return cache;
1241
- 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 };
1242
1720
  }
1243
- function chromiumLaunchPlan(opts, revision = headlessShellRevision()) {
1244
- const args = ["--headless", "--use-mock-keychain"];
1245
- 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");
1246
1742
  const proxy = envValue(opts.env, "HTTPS_PROXY") ?? envValue(opts.env, "HTTP_PROXY");
1247
1743
  let proxyAuth;
1248
1744
  if (proxy !== void 0) {
@@ -1267,7 +1763,8 @@ function chromiumLaunchPlan(opts, revision = headlessShellRevision()) {
1267
1763
  }
1268
1764
  }
1269
1765
  return {
1270
- 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,
1271
1768
  profileDir: join2(opts.stateDir, "profile"),
1272
1769
  downloadsTmp: join2(opts.stateDir, "downloads-tmp"),
1273
1770
  args,
@@ -1290,30 +1787,44 @@ async function loadPlaywright(browsersPath) {
1290
1787
  loaded = { browsersPath, pw: pw.default ?? pw };
1291
1788
  return loaded.pw;
1292
1789
  }
1293
- async function headlessShell(browsersPath) {
1790
+ async function registryBrowser(browsersPath, build) {
1294
1791
  await loadPlaywright(browsersPath);
1295
1792
  const mod = await import("./vendor/playwright-core/lib/coreBundle.js");
1296
1793
  const registry = (mod.registry ?? mod.default?.registry)?.registry;
1297
1794
  if (registry === void 0) throw new Error("playwright-core has no browser registry");
1298
- const exe = registry.findExecutable("chromium-headless-shell");
1299
- 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}`);
1300
1797
  const executablePath = exe.executablePath();
1301
1798
  if (executablePath === void 0 || exe.directory === void 0)
1302
- 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`);
1303
1800
  return { registry, exe, executablePath, directory: exe.directory };
1304
1801
  }
1305
- async function ensureChromium(browsersPath) {
1306
- 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);
1307
1804
  const marked = existsSync(join2(directory, "INSTALLATION_COMPLETE"));
1308
- if (marked && existsSync(executablePath)) return executablePath;
1309
- 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 });
1310
1811
  if (!existsSync(executablePath)) {
1311
1812
  throw new Error("the Chromium download finished without an executable");
1312
1813
  }
1313
1814
  return executablePath;
1314
1815
  }
1315
1816
  async function launchChromium(plan) {
1316
- 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);
1317
1828
  const pw = await loadPlaywright(plan.browsersPath);
1318
1829
  return pw.chromium.launchPersistentContext(plan.profileDir, {
1319
1830
  headless: true,
@@ -1326,6 +1837,22 @@ async function launchChromium(plan) {
1326
1837
  ...plan.proxyAuth === void 0 ? {} : { proxy: plan.proxyAuth }
1327
1838
  });
1328
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
+ }
1329
1856
  async function browserProcessId(ctx) {
1330
1857
  const browser = ctx.browser();
1331
1858
  if (browser === null) return void 0;
@@ -1352,10 +1879,49 @@ function killChromium(pid) {
1352
1879
  }
1353
1880
  }
1354
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
+ }
1355
1890
 
1356
- // daemon/session-file.ts
1357
- 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";
1358
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";
1359
1925
  var RESTORE_MAX_AGE_MS = 10 * 6e4;
1360
1926
  var SessionFile = class {
1361
1927
  file;
@@ -1363,14 +1929,14 @@ var SessionFile = class {
1363
1929
  queued = false;
1364
1930
  forgotten = false;
1365
1931
  constructor(stateDir, clock) {
1366
- this.file = join3(stateDir, "session.json");
1932
+ this.file = join4(stateDir, "session.json");
1367
1933
  this.clock = clock;
1368
1934
  }
1369
1935
  /** The saved session when it is recent and well formed; undefined otherwise. */
1370
1936
  read() {
1371
1937
  let raw;
1372
1938
  try {
1373
- raw = JSON.parse(readFileSync2(this.file, "utf8"));
1939
+ raw = JSON.parse(readFileSync3(this.file, "utf8"));
1374
1940
  } catch {
1375
1941
  return void 0;
1376
1942
  }
@@ -1413,8 +1979,8 @@ var SessionFile = class {
1413
1979
  ...handoff === void 0 ? {} : { handoff }
1414
1980
  };
1415
1981
  try {
1416
- writeFileSync(`${this.file}.tmp`, JSON.stringify(body), { mode: 384 });
1417
- renameSync(`${this.file}.tmp`, this.file);
1982
+ writeFileSync3(`${this.file}.tmp`, JSON.stringify(body), { mode: 384 });
1983
+ renameSync2(`${this.file}.tmp`, this.file);
1418
1984
  } catch {
1419
1985
  }
1420
1986
  });
@@ -1422,7 +1988,7 @@ var SessionFile = class {
1422
1988
  /** Removes the file and stops saving (an idle stop). */
1423
1989
  forget() {
1424
1990
  this.forgotten = true;
1425
- rmSync(this.file, { force: true });
1991
+ rmSync2(this.file, { force: true });
1426
1992
  }
1427
1993
  /**
1428
1994
  * Opens the saved tabs in a browser that has only its first blank tab. The navigations are
@@ -1444,10 +2010,300 @@ var SessionFile = class {
1444
2010
  }
1445
2011
  };
1446
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
+
1447
2302
  // daemon/viewer.ts
1448
- var FRAME_JSON_OVERHEAD = 128;
1449
- var START_QUALITY = 60;
1450
- 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;
1451
2307
  var clampDim = (n, max) => typeof n === "number" && Number.isFinite(n) ? Math.max(16, Math.min(max, Math.floor(n))) : max;
1452
2308
  var ViewerSession = class {
1453
2309
  browser;
@@ -1458,9 +2314,13 @@ var ViewerSession = class {
1458
2314
  unsubscribe = [];
1459
2315
  maxWidth = VIEWPORT.width;
1460
2316
  maxHeight = VIEWPORT.height;
1461
- /** Lowered when a frame does not fit the message cap. */
1462
- quality = START_QUALITY;
1463
- 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;
1464
2324
  started = false;
1465
2325
  closed = false;
1466
2326
  page;
@@ -1470,14 +2330,42 @@ var ViewerSession = class {
1470
2330
  inputChain = Promise.resolve();
1471
2331
  /** Bumped on close and hand back: input queued before it is dropped, not replayed. */
1472
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();
1473
2352
  seq = 0;
1474
- acked = 0;
1475
- lastSentAt = 0;
1476
- /** 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
+ */
1477
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;
1478
2362
  pumpTimer;
2363
+ pingTimer;
2364
+ pingSeq = 0;
2365
+ pingsSent = /* @__PURE__ */ new Map();
1479
2366
  draining = false;
1480
2367
  stateQueued = false;
2368
+ lastControl = "agent";
1481
2369
  constructor(opts) {
1482
2370
  this.browser = opts.browser;
1483
2371
  this.state = opts.state;
@@ -1496,12 +2384,14 @@ var ViewerSession = class {
1496
2384
  if (m.t !== "hello") return;
1497
2385
  this.started = true;
1498
2386
  this.setSize(m.maxWidth, m.maxHeight);
2387
+ this.lastControl = this.state.control;
1499
2388
  this.unsubscribe.push(
1500
2389
  this.browser.on((e) => this.onSession(e)),
1501
- this.state.onChange(() => this.queueState())
2390
+ this.state.onChange(() => this.onControl())
1502
2391
  );
1503
2392
  this.sendState();
1504
2393
  void this.serial(() => this.attach());
2394
+ this.ping();
1505
2395
  return;
1506
2396
  }
1507
2397
  switch (m.t) {
@@ -1514,9 +2404,17 @@ var ViewerSession = class {
1514
2404
  });
1515
2405
  return;
1516
2406
  case "frame-ack":
1517
- 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));
1518
2408
  this.pump();
1519
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
+ }
1520
2418
  case "takeover":
1521
2419
  this.state.takeover();
1522
2420
  return;
@@ -1525,7 +2423,8 @@ var ViewerSession = class {
1525
2423
  this.state.handback();
1526
2424
  return;
1527
2425
  case "mouse":
1528
- this.input(() => this.mouse(m));
2426
+ if (m.kind === "move") this.move(m);
2427
+ else this.input(() => this.mouse(m));
1529
2428
  return;
1530
2429
  case "key":
1531
2430
  this.input(() => this.key(m));
@@ -1554,26 +2453,129 @@ var ViewerSession = class {
1554
2453
  return;
1555
2454
  }
1556
2455
  }
1557
- /** 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
+ */
1558
2461
  input(fn) {
2462
+ if (this.state.control !== "user") return;
2463
+ this.moveSlot = void 0;
1559
2464
  const gen = this.inputGen;
1560
- 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();
1561
2466
  const run = this.inputChain.then(guarded, guarded);
1562
2467
  this.inputChain = run.catch(() => void 0);
1563
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
+ }
1564
2541
  /** Ends the viewer: stops its screencast and its subscriptions. */
1565
2542
  async close() {
1566
2543
  if (this.closed) return;
1567
2544
  this.closed = true;
1568
2545
  this.inputGen++;
2546
+ await this.releaseHeld();
1569
2547
  for (const u of this.unsubscribe.splice(0)) u();
1570
- 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);
1571
2550
  await this.serial(() => this.detach());
1572
2551
  }
1573
2552
  setSize(w, h) {
1574
2553
  this.maxWidth = clampDim(w, VIEWPORT.width);
1575
2554
  this.maxHeight = clampDim(h, VIEWPORT.height);
1576
- 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();
1577
2579
  }
1578
2580
  serial(fn) {
1579
2581
  const run = this.chain.then(fn, fn);
@@ -1587,33 +2589,41 @@ var ViewerSession = class {
1587
2589
  */
1588
2590
  fitted(m) {
1589
2591
  const fits = (x) => Buffer.byteLength(JSON.stringify(x)) <= this.frameMaxBytes;
1590
- if (m.t === "frame" || fits(m)) return m;
2592
+ if (fits(m)) return m;
1591
2593
  let small;
1592
2594
  if (m.t === "state") {
1593
2595
  const handoff = m.handoff === void 0 ? {} : { handoff: { ...m.handoff, message: clip(m.handoff.message, 200) } };
1594
2596
  small = {
1595
2597
  ...m,
1596
- 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
+ })),
1597
2604
  ...handoff
1598
2605
  };
1599
2606
  } else if (m.t === "dialog") {
1600
2607
  small = { ...m, message: clip(m.message, 200) };
1601
- } else {
2608
+ } else if (m.t === "blocked") {
1602
2609
  small = { ...m, url: clip(m.url, 200) };
1603
- }
2610
+ } else return null;
1604
2611
  return fits(small) ? small : null;
1605
2612
  }
2613
+ /** Sends a JSON message at once: it never waits behind a held frame. */
1606
2614
  send(raw) {
1607
2615
  if (this.closed) return;
1608
2616
  const m = this.fitted(raw);
1609
2617
  if (m === null) return;
1610
- if (!this.out.send(m) && !this.draining) {
1611
- this.draining = true;
1612
- this.out.whenDrained().then(() => {
1613
- this.draining = false;
1614
- this.pump();
1615
- });
1616
- }
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
+ });
1617
2627
  }
1618
2628
  onSession(e) {
1619
2629
  if (e.type === "state") this.queueState();
@@ -1652,11 +2662,11 @@ var ViewerSession = class {
1652
2662
  });
1653
2663
  }
1654
2664
  get scale() {
1655
- 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;
1656
2666
  }
1657
- /** Room for the JPEG's decoded bytes in one frame message. */
2667
+ /** Room for the JPEG in one frame message. */
1658
2668
  get jpegBudget() {
1659
- return Math.floor((this.frameMaxBytes - FRAME_JSON_OVERHEAD) * 3 / 4);
2669
+ return this.frameMaxBytes - FRAME_HEADER_BYTES;
1660
2670
  }
1661
2671
  async attach() {
1662
2672
  if (this.closed) return;
@@ -1665,12 +2675,19 @@ var ViewerSession = class {
1665
2675
  this.page = page;
1666
2676
  this.cdp = cdp;
1667
2677
  cdp.on("Page.screencastFrame", (f) => this.onFrame(cdp, f));
2678
+ this.cursorResolver = new CursorResolver(this.browser.context, page, cdp);
1668
2679
  const first = await captureFitting(cdp, {
1669
2680
  maxBytes: this.jpegBudget,
1670
2681
  maxScale: this.scale
1671
2682
  }).catch(() => null);
1672
2683
  if (first !== null && this.cdp === cdp) {
1673
- 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();
1674
2691
  }
1675
2692
  await this.startScreencast(cdp);
1676
2693
  }
@@ -1678,7 +2695,7 @@ var ViewerSession = class {
1678
2695
  if (this.closed || this.cdp !== cdp) return;
1679
2696
  await cdp.send("Page.startScreencast", {
1680
2697
  format: "jpeg",
1681
- quality: this.quality,
2698
+ quality: this.frameQuality.quality,
1682
2699
  maxWidth: Math.max(16, Math.floor(VIEWPORT.width * this.scale)),
1683
2700
  maxHeight: Math.max(16, Math.floor(VIEWPORT.height * this.scale)),
1684
2701
  everyNthFrame: 1
@@ -1689,94 +2706,159 @@ var ViewerSession = class {
1689
2706
  this.cdp = void 0;
1690
2707
  this.page = void 0;
1691
2708
  this.pending = void 0;
2709
+ this.encodeAck = void 0;
2710
+ this.cursorResolver?.dispose();
2711
+ this.cursorResolver = void 0;
1692
2712
  if (cdp === void 0) return;
1693
2713
  await cdp.send("Page.stopScreencast").catch(() => void 0);
1694
2714
  await cdp.detach().catch(() => void 0);
1695
2715
  }
1696
2716
  sendFrame(jpeg, width, height) {
1697
2717
  this.seq++;
1698
- this.lastSentAt = this.clock.now();
1699
- 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
+ });
1700
2741
  }
1701
2742
  onFrame(cdp, f) {
1702
2743
  if (this.closed || this.cdp !== cdp) return;
1703
2744
  const bytes = Buffer.from(f.data, "base64");
1704
2745
  if (bytes.length > this.jpegBudget) {
1705
2746
  cdp.send("Page.screencastFrameAck", { sessionId: f.sessionId }).catch(() => void 0);
1706
- if (this.quality > MIN_QUALITY) this.quality = Math.max(MIN_QUALITY, this.quality - 15);
1707
- else this.shrink *= 0.75;
1708
- void this.serial(async () => {
1709
- if (this.cdp !== cdp) return;
1710
- await cdp.send("Page.stopScreencast").catch(() => void 0);
1711
- await this.startScreencast(cdp);
1712
- });
2747
+ if (this.frameQuality.tooLarge()) this.restart();
1713
2748
  return;
1714
2749
  }
1715
2750
  const { width, height } = jpegSize(bytes);
1716
- 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 };
1717
2753
  this.pump();
2754
+ this.scheduleEncodeAck();
1718
2755
  }
1719
2756
  /**
1720
- * Sends the held screencast frame and acks it (letting Chromium send the next) once the viewer
1721
- * has room for it, the transport is not backed up and the rate cap allows: a frame never follows
1722
- * 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.
1723
2783
  */
1724
2784
  pump() {
1725
2785
  const pending = this.pending;
1726
2786
  if (pending === void 0 || this.closed || this.draining) return;
1727
- if (this.seq - this.acked >= VIEWER_UNACKED_FRAMES) return;
1728
- const wait = this.lastSentAt + 1e3 / VIEWER_MAX_FPS - this.clock.now();
1729
- if (wait > 0) {
1730
- 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) {
1731
2790
  this.pumpTimer = this.clock.schedule(() => {
1732
2791
  this.pumpTimer = void 0;
1733
2792
  this.pump();
1734
- }, wait);
2793
+ }, d.waitMs);
1735
2794
  }
1736
2795
  return;
1737
2796
  }
1738
2797
  this.pending = void 0;
1739
2798
  if (this.cdp !== pending.cdp) return;
1740
- this.sendFrame(pending.data, pending.width, pending.height);
1741
- pending.cdp.send("Page.screencastFrameAck", { sessionId: pending.sessionId }).catch(() => void 0);
2799
+ this.sendFrame(pending.jpeg, pending.width, pending.height);
2800
+ this.scheduleEncodeAck();
1742
2801
  }
1743
2802
  async mouse(m) {
1744
2803
  const page = await this.browser.activePage();
1745
- if (!Number.isFinite(Number(m.x)) || !Number.isFinite(Number(m.y))) return;
1746
- const x = Math.max(0, Math.min(VIEWPORT.width - 1, Number(m.x)));
1747
- 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;
1748
2807
  const button = m.button === "right" ? "right" : "left";
1749
2808
  try {
1750
- if (m.kind === "move") await page.mouse.move(x, y);
1751
- else if (m.kind === "down") {
2809
+ if (m.kind === "down") {
1752
2810
  await page.mouse.move(x, y);
1753
2811
  await page.mouse.down({ button });
2812
+ if (this.driving) this.heldButtons.set(button, page);
2813
+ else await page.mouse.up({ button });
1754
2814
  } else if (m.kind === "up") {
2815
+ this.heldButtons.delete(button);
1755
2816
  await page.mouse.move(x, y);
1756
2817
  await page.mouse.up({ button });
1757
2818
  } else if (m.kind === "wheel") {
1758
2819
  await page.mouse.move(x, y);
1759
2820
  await page.mouse.wheel(Number(m.dx) || 0, Number(m.dy) || 0);
1760
- }
2821
+ } else return;
1761
2822
  } catch {
2823
+ return;
1762
2824
  }
2825
+ if (m.kind !== "down") this.wantCursor(x, y);
1763
2826
  }
1764
2827
  async key(m) {
1765
2828
  const page = await this.browser.activePage();
1766
2829
  try {
1767
2830
  if (m.kind === "char") {
1768
2831
  const text = m.text ?? m.key;
1769
- if (typeof text === "string" && text !== "") await page.keyboard.insertText(text);
1770
- } else if (m.kind === "down") await page.keyboard.down(m.key);
1771
- 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
+ }
1772
2842
  } catch {
1773
2843
  }
1774
2844
  }
1775
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
+ }
1776
2855
 
1777
2856
  // daemon/main.ts
2857
+ var SEALED_EXIT_GRACE_MS = 2e3;
1778
2858
  var SERVICE_WORKSPACE_ENV = "CAPYBARA_SERVICE_WORKSPACE";
1779
2859
  var BROWSER_CLOSE_GRACE_MS = 3e3;
2860
+ var PROCESS_POLL_MS = 10;
2861
+ var COOKIE_SAVE_MS = 500;
1780
2862
  var enc = new TextEncoder();
1781
2863
  var dec = new TextDecoder();
1782
2864
  var REQUEST_OPS = /* @__PURE__ */ new Set([
@@ -1860,7 +2942,7 @@ async function startDaemon(opts) {
1860
2942
  let current;
1861
2943
  let running;
1862
2944
  let restored = false;
1863
- function within(value, ms) {
2945
+ function within2(value, ms) {
1864
2946
  let timer;
1865
2947
  return Promise.race([
1866
2948
  value,
@@ -1902,9 +2984,9 @@ async function startDaemon(opts) {
1902
2984
  if (running?.launch === starting) running = void 0;
1903
2985
  if (!closing && !failed()) opts.onBrowserGone?.();
1904
2986
  });
1905
- const pid = await within(browserProcessId(ctx), BROWSER_CLOSE_GRACE_MS);
2987
+ const pid = await within2(browserProcessId(ctx), BROWSER_CLOSE_GRACE_MS);
1906
2988
  setPid(pid);
1907
- if (!gone) running = { launch: starting, pid };
2989
+ if (!gone) running = { launch: starting, pid, ctx };
1908
2990
  const workspace = opts.env[SERVICE_WORKSPACE_ENV];
1909
2991
  const session = new BrowserSession(ctx, {
1910
2992
  proxy: plan.proxy,
@@ -1914,6 +2996,9 @@ async function startDaemon(opts) {
1914
2996
  downloadMaxBytes: downloadMaxBytes(opts.env),
1915
2997
  ...opts.downloadWaitMs === void 0 ? {} : { downloadWaitMs: opts.downloadWaitMs }
1916
2998
  });
2999
+ if (plan.shippedDir !== void 0)
3000
+ session.note(shippedRevisionNote(plan.shippedDir, browserRevision(plan.build)));
3001
+ if (!closing) await restoreCookies(ctx, opts.stateDir);
1917
3002
  if (!restored && !closing) {
1918
3003
  restored = true;
1919
3004
  if (saved !== void 0) await sessionFile.restoreTabs(session, saved);
@@ -1931,13 +3016,16 @@ async function startDaemon(opts) {
1931
3016
  () => true,
1932
3017
  () => true
1933
3018
  );
1934
- if (await within(done, closeGraceMs) === true) return;
3019
+ if (await within2(done, closeGraceMs) === true) return;
1935
3020
  const id = pid();
1936
3021
  if (id === void 0) return;
1937
3022
  killChromium(id);
1938
- await within(done, closeGraceMs);
3023
+ await within2(done, closeGraceMs);
1939
3024
  }
1940
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);
1941
3029
  const cause = e instanceof Error ? e.message.split("\n")[0] : String(e);
1942
3030
  const proxy = plan.proxy;
1943
3031
  const refused = proxy === void 0 ? [] : (await Promise.all(
@@ -1959,16 +3047,28 @@ async function startDaemon(opts) {
1959
3047
  async function stopBrowser() {
1960
3048
  const starting = current;
1961
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);
1962
3053
  await closeOrKill(
1963
3054
  starting.then(
1964
- (session) => session.close(),
3055
+ async (session) => {
3056
+ await session.close();
3057
+ if (pid !== void 0) await processGone(pid);
3058
+ },
1965
3059
  () => void 0
1966
3060
  ),
1967
- () => running?.launch === starting ? running.pid : void 0
3061
+ () => pid
1968
3062
  );
1969
3063
  }
3064
+ async function processGone(pid) {
3065
+ while (processAlive(pid)) await new Promise((r) => clock.schedule(r, PROCESS_POLL_MS));
3066
+ }
1970
3067
  const ready = browser().then(() => void 0);
1971
- ready.catch(() => void 0);
3068
+ ready.catch((e) => {
3069
+ if (e instanceof BrowserInstalledError)
3070
+ clock.schedule(() => opts.onSealed?.(), SEALED_EXIT_GRACE_MS);
3071
+ });
1972
3072
  async function handoffOp(req) {
1973
3073
  if (typeof req.callId !== "string" || req.callId === "")
1974
3074
  return fail("The handoff needs a callId.");
@@ -2057,6 +3157,10 @@ async function startDaemon(opts) {
2057
3157
  });
2058
3158
  return ok || dropped || sock.destroyed;
2059
3159
  },
3160
+ sendFrame: (frame) => {
3161
+ if (sock.destroyed) return true;
3162
+ return sock.write(encodeServiceMessage(frame));
3163
+ },
2060
3164
  whenDrained: () => new Promise((r) => sock.once("drain", () => r()))
2061
3165
  }
2062
3166
  });
@@ -2073,6 +3177,7 @@ async function startDaemon(opts) {
2073
3177
  handleRequest(parse(raw)).catch((e) => fail(e instanceof ActionError ? e.message : String(e))).then((reply) => {
2074
3178
  write(sock, reply, () => write(sock, fail(REPLY_TOO_LARGE_MESSAGE), () => void 0));
2075
3179
  sock.end();
3180
+ if (!reply.ok && reply.error === "restart") sock.once("close", () => opts.onSealed?.());
2076
3181
  }).catch(() => sock.destroy()).finally(() => state.requestEnded());
2077
3182
  return;
2078
3183
  }
@@ -2091,7 +3196,7 @@ async function startDaemon(opts) {
2091
3196
  for (const m of msgs) onMessage(m);
2092
3197
  });
2093
3198
  }
2094
- if (existsSync2(opts.socketPath)) unlinkSync(opts.socketPath);
3199
+ if (existsSync2(opts.socketPath)) unlinkSync2(opts.socketPath);
2095
3200
  const server = createServer(onConnection);
2096
3201
  await new Promise((resolve, reject) => {
2097
3202
  server.once("error", reject);
@@ -2115,7 +3220,7 @@ async function startDaemon(opts) {
2115
3220
  await stopBrowser();
2116
3221
  if (existsSync2(opts.socketPath)) {
2117
3222
  try {
2118
- unlinkSync(opts.socketPath);
3223
+ unlinkSync2(opts.socketPath);
2119
3224
  } catch {
2120
3225
  }
2121
3226
  }
@@ -2151,7 +3256,9 @@ async function main() {
2151
3256
  stateDir,
2152
3257
  env: process.env,
2153
3258
  onIdle: () => stop(0, "idle"),
2154
- 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")
2155
3262
  });
2156
3263
  process.stderr.write(`browser daemon: listening on ${socketPath}
2157
3264
  `);