@capybara-hq/plugin-browser 0.1.0-rc.1 → 0.1.0-rc.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +1,53 @@
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.77/node_modules/@capybara-hq/plugin-sdk/dist/device-provider.js
4
+ var MAX_PATH_LENGTH = 4096;
5
+ var DEFAULT_SANDBOX_ROOTS = Object.freeze({
6
+ workspace: "/workspace",
7
+ skills: "/skills",
8
+ tmp: "/tmp"
9
+ });
10
+ function sandboxProxyRefusalLayer(reason) {
11
+ const r = reason.trim().toLowerCase();
12
+ if (r.startsWith("address is ") || r.startsWith("resolved to ") || r === "malformed host")
13
+ return "address";
14
+ if (r === "host is not on the allow list")
15
+ return "device";
16
+ return "unknown";
17
+ }
18
+ var DEVICE_REPORT_LIMITS = Object.freeze({
19
+ revisionChars: 128,
20
+ descriptionChars: 300,
21
+ limits: 8,
22
+ limitLabelChars: 60,
23
+ limitValueChars: 60,
24
+ homeChars: 4096,
25
+ changeHintChars: 400
26
+ });
27
+ var DEVICE_SERVICE_FILES_DIGEST_VECTOR = Object.freeze({
28
+ files: Object.freeze({
29
+ "main.js": "console.log(1)\n",
30
+ "lib/a.js": "export const a = 1;\n",
31
+ empty: ""
32
+ }),
33
+ digest: "sha256:7b3959ff2e10237b9f1a255bbecb5dacebd31422fe734b2867403e42913432a5"
34
+ });
35
+ var DEVICE_SCAN_SKIPPED_DIRS = Object.freeze(["node_modules"]);
36
+ var DEVICE_SCAN_SKIPPED_BASE_DIRS = Object.freeze(["Library"]);
37
+ var STOPS = /* @__PURE__ */ new Set([
38
+ "path must be a non-empty string",
39
+ `path must be at most ${MAX_PATH_LENGTH} characters`,
40
+ "path must not contain control characters",
41
+ "path must not contain backslashes",
42
+ "path must be absolute",
43
+ "path must not contain empty segments"
44
+ ]);
45
+
46
+ // ../../node_modules/.pnpm/@capybara-hq+plugin-sdk@0.1.0-rc.77/node_modules/@capybara-hq/plugin-sdk/dist/device-service.js
4
47
  var DEVICE_SERVICE_SOCKET_ENV = "CAPYBARA_SERVICE_SOCKET";
5
48
  var DEVICE_SERVICE_STATE_ENV = "CAPYBARA_SERVICE_STATE";
49
+ var DEVICE_SERVICE_MACH_ENV = "CAPYBARA_SERVICE_MACH";
50
+ var DEVICE_SERVICE_MACH_CHROMIUM = "chromium";
6
51
  var DEVICE_SERVICE_MAX_MESSAGE = 8 * 1024 * 1024;
7
52
  var HEADER = 4;
8
53
  function encodeServiceMessage(body) {
@@ -67,29 +112,233 @@ var ServiceMessageDecoder = class {
67
112
  return out;
68
113
  }
69
114
  };
115
+ function parseViewerContext(body) {
116
+ let msg;
117
+ try {
118
+ const text = typeof body === "string" ? body : new TextDecoder("utf-8", { fatal: true }).decode(body);
119
+ msg = JSON.parse(text);
120
+ } catch {
121
+ return null;
122
+ }
123
+ if (typeof msg !== "object" || msg === null || Array.isArray(msg))
124
+ return null;
125
+ const { kind, conversationId, rootConversationId } = msg;
126
+ if (kind !== "viewer")
127
+ return null;
128
+ if (typeof conversationId !== "string" || conversationId === "")
129
+ return null;
130
+ if (typeof rootConversationId !== "string" || rootConversationId === "")
131
+ return null;
132
+ return { kind: "viewer", conversationId, rootConversationId };
133
+ }
70
134
 
71
135
  // daemon/main.ts
72
- import { chmodSync, existsSync as existsSync2, mkdirSync as mkdirSync2, unlinkSync } from "node:fs";
136
+ import { chmodSync, existsSync as existsSync2, mkdirSync as mkdirSync2, unlinkSync as unlinkSync2 } from "node:fs";
73
137
  import { createServer } from "node:net";
74
138
 
75
139
  // daemon/actions.ts
76
- import { lstatSync, mkdirSync, readdirSync, realpathSync, statSync } from "node:fs";
140
+ import {
141
+ closeSync,
142
+ constants as fsc,
143
+ fstatSync,
144
+ lstatSync,
145
+ mkdirSync,
146
+ openSync,
147
+ readdirSync,
148
+ readSync,
149
+ realpathSync,
150
+ statSync,
151
+ unlinkSync,
152
+ writeSync
153
+ } from "node:fs";
77
154
  import { request as httpRequest } from "node:http";
78
155
  import { basename, extname, join, sep } from "node:path";
79
156
 
80
157
  // daemon/protocol.ts
158
+ var ROLL_CHECK_REQUEST = '{"capybara":"roll-check"}';
81
159
  var VIEWPORT = { width: 1280, height: 800 };
82
160
  var SNAPSHOT_MAX_CHARS = 4e4;
83
161
  var IDLE_STOP_MS = 15 * 6e4;
84
162
  var TAKEOVER_GRACE_MS = 6e4;
85
- var VIEWER_MAX_FPS = 5;
163
+ var VIEWER_MAX_FPS = 15;
86
164
  var VIEWER_UNACKED_FRAMES = 2;
165
+ var VIEWER_TEXT_MAX_CHARS = 1e4;
166
+ function clipCodePoints(text, max) {
167
+ if (text.length <= max) return text;
168
+ return Array.from(text).slice(0, max).join("");
169
+ }
170
+ var VIEWER_CURSORS = [
171
+ "default",
172
+ "pointer",
173
+ "text",
174
+ "vertical-text",
175
+ "crosshair",
176
+ "move",
177
+ "grab",
178
+ "grabbing",
179
+ "not-allowed",
180
+ "no-drop",
181
+ "wait",
182
+ "progress",
183
+ "help",
184
+ "context-menu",
185
+ "cell",
186
+ "copy",
187
+ "alias",
188
+ "zoom-in",
189
+ "zoom-out",
190
+ "col-resize",
191
+ "row-resize",
192
+ "ew-resize",
193
+ "ns-resize",
194
+ "nesw-resize",
195
+ "nwse-resize",
196
+ "n-resize",
197
+ "e-resize",
198
+ "s-resize",
199
+ "w-resize",
200
+ "ne-resize",
201
+ "nw-resize",
202
+ "se-resize",
203
+ "sw-resize",
204
+ "all-scroll",
205
+ "none"
206
+ ];
207
+ function toViewerCursor(value) {
208
+ return typeof value === "string" && VIEWER_CURSORS.includes(value) ? value : "default";
209
+ }
210
+ var FRAME_TAG = 0;
211
+ var FRAME_HEADER_BYTES = 9;
212
+ function encodeFrame(f) {
213
+ const out = new Uint8Array(FRAME_HEADER_BYTES + f.jpeg.byteLength);
214
+ const v = new DataView(out.buffer);
215
+ v.setUint8(0, FRAME_TAG);
216
+ v.setUint32(1, f.seq >>> 0);
217
+ v.setUint16(5, f.width);
218
+ v.setUint16(7, f.height);
219
+ out.set(f.jpeg, FRAME_HEADER_BYTES);
220
+ return out;
221
+ }
87
222
  var DEFAULT_FRAME_MAX_BYTES = 256 * 1024;
88
223
  var HANDOFF_MAX_CHARS = 4096;
89
224
  var MAX_TABS = 10;
225
+ var MAX_TABS_PER_CONVERSATION = 6;
226
+ var CONVERSATION_IDLE_MS = 15 * 6e4;
227
+ var EVICT_MIN_IDLE_MS = 5 * 6e4;
228
+ var NO_CONVERSATION_MESSAGE = "the request names no conversation";
90
229
  var HANDOFF_KEEPALIVE_MS = 24 * 60 * 6e4;
91
230
  var DOWNLOAD_BLOCKED_PREFIX = "The browser could not be downloaded into the device: its network settings block ";
92
231
  var REPLY_TOO_LARGE_MESSAGE = "The reply was too large to send; ask for less (a smaller maxBytes).";
232
+ var FAVICON_MAX_BYTES = 8 * 1024;
233
+
234
+ // daemon/favicon.ts
235
+ var READ_MAX_BYTES = 64 * 1024;
236
+ var RASTER_EDGE = 32;
237
+ function sniffIcon(b) {
238
+ const at = (i, ...xs) => xs.every((x, j) => b[i + j] === x);
239
+ if (at(0, 137, 80, 78, 71)) return "image/png";
240
+ if (at(0, 0, 0, 1, 0)) return "image/x-icon";
241
+ if (at(0, 71, 73, 70, 56)) return "image/gif";
242
+ if (at(0, 255, 216, 255)) return "image/jpeg";
243
+ if (at(0, 82, 73, 70, 70) && at(8, 87, 69, 66, 80)) return "image/webp";
244
+ const head = new TextDecoder().decode(b.subarray(0, 512)).trimStart().toLowerCase();
245
+ if (head.startsWith("<svg") || head.startsWith("<?xml") && head.includes("<svg"))
246
+ return "image/svg+xml";
247
+ return null;
248
+ }
249
+ function iconDataUrl(b) {
250
+ if (b.byteLength === 0 || b.byteLength > FAVICON_MAX_BYTES) return null;
251
+ const mime = sniffIcon(b);
252
+ if (mime === null) return null;
253
+ return `data:${mime};base64,${Buffer.from(b).toString("base64")}`;
254
+ }
255
+ async function iconUrlOf(page) {
256
+ let base;
257
+ try {
258
+ base = new URL(page.url());
259
+ } catch {
260
+ return null;
261
+ }
262
+ if (base.protocol !== "http:" && base.protocol !== "https:") return null;
263
+ const declared = await page.evaluate(
264
+ `(() => { const l = Array.from(document.querySelectorAll("link[rel][href]")).find((x) => /(^|\\s)icon(\\s|$)/i.test(x.rel)); return l ? l.href : null; })()`
265
+ ).catch(() => null);
266
+ if (typeof declared === "string") {
267
+ try {
268
+ const u = new URL(declared, base);
269
+ if (u.protocol === "http:" || u.protocol === "https:") return u.href;
270
+ } catch {
271
+ }
272
+ }
273
+ return new URL("/favicon.ico", base).href;
274
+ }
275
+ async function iconForPanel(cdp, bytes) {
276
+ const direct = iconDataUrl(bytes);
277
+ if (direct !== null) return direct;
278
+ const mime = sniffIcon(bytes);
279
+ if (mime === null || mime === "image/svg+xml") return null;
280
+ const png = await rasterize(cdp, bytes, mime).catch(() => null);
281
+ return png === null || sniffIcon(png) !== "image/png" ? null : iconDataUrl(png);
282
+ }
283
+ async function rasterize(cdp, bytes, mime) {
284
+ const tree = await cdp.send("Page.getFrameTree");
285
+ const world = await cdp.send("Page.createIsolatedWorld", {
286
+ frameId: tree.frameTree.frame.id,
287
+ worldName: "capybara-favicon"
288
+ });
289
+ const b64 = Buffer.from(bytes).toString("base64");
290
+ const n = RASTER_EDGE;
291
+ const expression = `(async () => {
292
+ const raw = atob(${JSON.stringify(b64)});
293
+ const bytes = new Uint8Array(raw.length);
294
+ for (let i = 0; i < raw.length; i++) bytes[i] = raw.charCodeAt(i);
295
+ const bmp = await createImageBitmap(new Blob([bytes], { type: ${JSON.stringify(mime)} }));
296
+ const c = new OffscreenCanvas(${n}, ${n});
297
+ const g = c.getContext("2d");
298
+ const k = Math.min(${n} / bmp.width, ${n} / bmp.height);
299
+ const w = bmp.width * k, h = bmp.height * k;
300
+ g.imageSmoothingQuality = "high";
301
+ g.drawImage(bmp, (${n} - w) / 2, (${n} - h) / 2, w, h);
302
+ const out = new Uint8Array(await (await c.convertToBlob({ type: "image/png" })).arrayBuffer());
303
+ let s = "";
304
+ for (let i = 0; i < out.length; i++) s += String.fromCharCode(out[i]);
305
+ return btoa(s);
306
+ })()`;
307
+ const res = await cdp.send("Runtime.evaluate", {
308
+ expression,
309
+ contextId: world.executionContextId,
310
+ awaitPromise: true,
311
+ returnByValue: true
312
+ });
313
+ const v = res.result?.value;
314
+ if (res.exceptionDetails !== void 0 || typeof v !== "string") return null;
315
+ return new Uint8Array(Buffer.from(v, "base64"));
316
+ }
317
+ async function fetchIcon(cdp, url) {
318
+ const tree = await cdp.send("Page.getFrameTree");
319
+ const res = await cdp.send("Network.loadNetworkResource", {
320
+ frameId: tree.frameTree.frame.id,
321
+ url,
322
+ options: { disableCache: false, includeCredentials: false }
323
+ });
324
+ const r = res.resource;
325
+ if (!r.success || r.httpStatusCode !== 200 || r.stream === void 0) return null;
326
+ const chunks = [];
327
+ let size = 0;
328
+ try {
329
+ for (; ; ) {
330
+ const part = await cdp.send("IO.read", { handle: r.stream, size: 16 * 1024 });
331
+ const buf = Buffer.from(part.data, part.base64Encoded ? "base64" : "utf8");
332
+ size += buf.byteLength;
333
+ if (size > READ_MAX_BYTES) return null;
334
+ chunks.push(buf);
335
+ if (part.eof) break;
336
+ }
337
+ } finally {
338
+ await cdp.send("IO.close", { handle: r.stream }).catch(() => void 0);
339
+ }
340
+ return new Uint8Array(Buffer.concat(chunks));
341
+ }
93
342
 
94
343
  // daemon/snapshot.ts
95
344
  var isNode = (line) => line.trimStart().startsWith("- ");
@@ -120,27 +369,35 @@ var systemClock = {
120
369
  schedule: (fn, ms) => setTimeout(fn, ms).unref(),
121
370
  cancel: (h) => clearTimeout(h)
122
371
  };
372
+ var HANDOFF_PARK = "handoff";
373
+ var HANDOFF_PARK_KEY = "";
374
+ var parkId = (kind, key2) => `${kind}\0${key2}`;
123
375
  var DaemonState = class {
124
376
  clock;
125
377
  idleMs;
126
378
  graceMs;
379
+ conversationIdleMs;
127
380
  onIdle;
381
+ onConversationIdle;
128
382
  listeners = /* @__PURE__ */ new Set();
383
+ conversations = /* @__PURE__ */ new Map();
129
384
  viewers = 0;
130
385
  inflight = 0;
131
386
  since;
132
- note;
387
+ /** Conversations the running takeover concerns (told on their next ok reply after it ends). */
388
+ concerned = /* @__PURE__ */ new Set();
389
+ /** Hand back notes not yet told: conversation id to when the takeover began. */
390
+ notes = /* @__PURE__ */ new Map();
133
391
  idleTimer;
134
392
  graceTimer;
135
393
  disposed = false;
136
- pendingHandoff;
137
- /** When the first notice of the pending handoff arrived (the keepalive counts from it). */
138
- handoffSince;
139
394
  constructor(opts) {
140
395
  this.clock = opts.clock ?? systemClock;
141
396
  this.idleMs = opts.idleMs ?? IDLE_STOP_MS;
142
397
  this.graceMs = opts.graceMs ?? TAKEOVER_GRACE_MS;
398
+ this.conversationIdleMs = opts.conversationIdleMs ?? CONVERSATION_IDLE_MS;
143
399
  this.onIdle = opts.onIdle;
400
+ this.onConversationIdle = opts.onConversationIdle ?? (() => void 0);
144
401
  this.armIdle();
145
402
  }
146
403
  get control() {
@@ -156,66 +413,218 @@ var DaemonState = class {
156
413
  get requestsInFlight() {
157
414
  return this.inflight;
158
415
  }
159
- /** Subscribes to control changes; returns the unsubscribe function. */
416
+ /** Subscribes to control, handoff and park changes; returns the unsubscribe function. */
160
417
  onChange(fn) {
161
418
  this.listeners.add(fn);
162
419
  return () => this.listeners.delete(fn);
163
420
  }
164
- /** The pending handoff question (the latest notice), if any. */
165
- get handoff() {
166
- return this.pendingHandoff;
421
+ // ---- conversations
422
+ /** The conversations the daemon keeps state for (tests, the session file). */
423
+ get conversationIds() {
424
+ return [...this.conversations.keys()];
167
425
  }
168
- /** Records a handoff question; it replaces any earlier one. */
169
- noticeHandoff(callId, message) {
170
- const m = message.length <= HANDOFF_MAX_CHARS ? message : `${message.slice(0, HANDOFF_MAX_CHARS - 1)}\u2026`;
171
- this.pendingHandoff = { callId, message: m };
172
- this.handoffSince ??= this.clock.now();
426
+ /** Whether the daemon keeps state for the conversation. */
427
+ known(conversationId) {
428
+ return this.conversations.has(conversationId);
429
+ }
430
+ /** The root of a conversation's tree, when the daemon knows the conversation. */
431
+ rootOf(conversationId) {
432
+ return this.conversations.get(conversationId)?.root;
433
+ }
434
+ entry(conversationId, root) {
435
+ let e = this.conversations.get(conversationId);
436
+ if (e === void 0) {
437
+ e = {
438
+ root,
439
+ inflight: 0,
440
+ lastActiveAt: this.clock.now(),
441
+ pins: 0,
442
+ parks: /* @__PURE__ */ new Map(),
443
+ handoff: void 0,
444
+ idleTimer: void 0
445
+ };
446
+ this.conversations.set(conversationId, e);
447
+ }
448
+ return e;
449
+ }
450
+ /**
451
+ * Records activity of a conversation that is not a request (it gained a tab: a restore, an
452
+ * adopt, a tab the person opened): its idle countdowns start again.
453
+ */
454
+ seen(conversationId, root) {
455
+ const e = this.entry(conversationId, root);
456
+ e.lastActiveAt = this.clock.now();
457
+ this.armConversation(conversationId, e);
458
+ }
459
+ /** A request of the conversation arrived (it is in use until {@link requestFinished}). */
460
+ requestArrived(conversationId, root) {
461
+ const e = this.entry(conversationId, root);
462
+ e.inflight++;
463
+ e.lastActiveAt = this.clock.now();
464
+ this.armConversation(conversationId, e);
465
+ }
466
+ /** The conversation's request got its reply. */
467
+ requestFinished(conversationId) {
468
+ const e = this.conversations.get(conversationId);
469
+ if (e === void 0) return;
470
+ e.inflight = Math.max(0, e.inflight - 1);
471
+ e.lastActiveAt = this.clock.now();
472
+ this.armConversation(conversationId, e);
473
+ }
474
+ /** A viewer pins the conversation (its own, or the owner of the tab it shows). */
475
+ pin(conversationId, root) {
476
+ const e = this.entry(conversationId, root);
477
+ e.pins++;
478
+ this.armConversation(conversationId, e);
479
+ }
480
+ unpin(conversationId) {
481
+ const e = this.conversations.get(conversationId);
482
+ if (e === void 0) return;
483
+ e.pins = Math.max(0, e.pins - 1);
484
+ e.lastActiveAt = this.clock.now();
485
+ this.armConversation(conversationId, e);
486
+ }
487
+ /**
488
+ * Whether the conversation is in use: a request in flight or a conversation park. Adopt of its
489
+ * tabs is refused meanwhile, and the cap eviction skips it.
490
+ */
491
+ busy(conversationId) {
492
+ const e = this.conversations.get(conversationId);
493
+ if (e === void 0) return false;
494
+ if (e.inflight > 0) return true;
495
+ for (const p of e.parks.values()) if (p.tabId === void 0) return true;
496
+ return false;
497
+ }
498
+ /** Whether a viewer pins the conversation. */
499
+ pinned(conversationId) {
500
+ return (this.conversations.get(conversationId)?.pins ?? 0) > 0;
501
+ }
502
+ /** How long the conversation has been without activity (unknown: forever). */
503
+ idleFor(conversationId) {
504
+ const e = this.conversations.get(conversationId);
505
+ return e === void 0 ? Number.POSITIVE_INFINITY : this.clock.now() - e.lastActiveAt;
506
+ }
507
+ /** The last activity of the conversation (unknown: never). */
508
+ lastActiveAt(conversationId) {
509
+ return this.conversations.get(conversationId)?.lastActiveAt ?? Number.NEGATIVE_INFINITY;
510
+ }
511
+ // ---- parks
512
+ /** Starts (or renews the spec of) a park; a park of the same kind and key keeps its start. */
513
+ park(conversationId, root, spec) {
514
+ const e = this.entry(conversationId, root);
515
+ const id = parkId(spec.kind, spec.key);
516
+ const since = e.parks.get(id)?.since ?? this.clock.now();
517
+ e.parks.set(id, { ...spec, since });
518
+ this.armConversation(conversationId, e);
519
+ this.armIdle();
520
+ this.emit();
521
+ }
522
+ /** Ends a park; an unknown one changes nothing. */
523
+ unpark(conversationId, kind, key2) {
524
+ const e = this.conversations.get(conversationId);
525
+ if (e === void 0 || !e.parks.delete(parkId(kind, key2))) return;
526
+ e.lastActiveAt = this.clock.now();
527
+ this.armConversation(conversationId, e);
528
+ this.armIdle();
173
529
  this.emit();
530
+ }
531
+ /** The conversation's parks. */
532
+ parksOf(conversationId) {
533
+ return [...this.conversations.get(conversationId)?.parks.values() ?? []];
534
+ }
535
+ /** Whether a tab park pins the tab. */
536
+ tabParked(tabId) {
537
+ for (const e of this.conversations.values())
538
+ for (const p of e.parks.values()) if (p.tabId === tabId) return true;
539
+ return false;
540
+ }
541
+ /** Drops the tab parks of a tab that closed. */
542
+ tabClosed(tabId) {
543
+ for (const [conv, e] of this.conversations) {
544
+ let changed = false;
545
+ for (const [id, p] of e.parks) if (p.tabId === tabId) changed = e.parks.delete(id) || changed;
546
+ if (changed) this.armConversation(conv, e);
547
+ }
174
548
  this.armIdle();
175
549
  }
176
- /** Clears the pending handoff when it is `callId`'s; a stale clear changes nothing. */
177
- clearHandoff(callId) {
178
- if (this.pendingHandoff?.callId !== callId) return;
179
- this.endHandoff();
550
+ // ---- handoffs (a park of kind HANDOFF_PARK)
551
+ /** The tree's or every pending handoff, oldest first. */
552
+ handoffs(root) {
553
+ const out = [];
554
+ for (const [conversationId, e] of this.conversations) {
555
+ if (e.handoff === void 0 || root !== void 0 && e.root !== root) continue;
556
+ const since = e.parks.get(parkId(HANDOFF_PARK, HANDOFF_PARK_KEY))?.since ?? 0;
557
+ out.push({ conversationId, rootConversationId: e.root, ...e.handoff, since });
558
+ }
559
+ return out.sort((a, b) => a.since - b.since);
560
+ }
561
+ /** The conversation's pending handoff, if any. */
562
+ handoffOf(conversationId) {
563
+ return this.conversations.get(conversationId)?.handoff;
564
+ }
565
+ /** Records the conversation's handoff question; it replaces an earlier one of the conversation. */
566
+ noticeHandoff(conversationId, root, callId, message) {
567
+ const m = message.length <= HANDOFF_MAX_CHARS ? message : `${message.slice(0, HANDOFF_MAX_CHARS - 1)}\u2026`;
568
+ const e = this.entry(conversationId, root);
569
+ e.handoff = { callId, message: m };
570
+ this.park(conversationId, root, { kind: HANDOFF_PARK, key: HANDOFF_PARK_KEY, persist: true });
571
+ this.emit();
572
+ }
573
+ /** Clears the conversation's pending handoff when it is `callId`'s; a stale clear changes nothing. */
574
+ clearHandoff(conversationId, callId) {
575
+ if (this.conversations.get(conversationId)?.handoff?.callId !== callId) return;
576
+ this.endHandoff(conversationId);
180
577
  }
181
578
  /**
182
- * Drops the pending handoff whatever its callId: the next agent tool request means its run has
183
- * moved on (an aborted run never sends handoff_clear). This is device-wide on purpose: a tool
184
- * call from any conversation of the device drops it, since they are all the owner's
185
- * conversations and the browser is one.
579
+ * Drops the conversation's pending handoff whatever its callId: the conversation's next tool
580
+ * request means its run moved on (an aborted run never sends handoff_clear). Other
581
+ * conversations' handoffs stay.
186
582
  */
187
- dropHandoff() {
188
- if (this.pendingHandoff === void 0) return;
189
- this.endHandoff();
583
+ dropHandoff(conversationId) {
584
+ if (this.conversations.get(conversationId)?.handoff === void 0) return;
585
+ this.endHandoff(conversationId);
190
586
  }
191
- endHandoff() {
192
- this.pendingHandoff = void 0;
193
- this.handoffSince = void 0;
587
+ endHandoff(conversationId) {
588
+ const e = this.conversations.get(conversationId);
589
+ if (e === void 0) return;
590
+ e.handoff = void 0;
591
+ this.unpark(conversationId, HANDOFF_PARK, HANDOFF_PARK_KEY);
194
592
  this.emit();
195
- this.armIdle();
196
593
  }
197
- takeover() {
594
+ // ---- takeover
595
+ /**
596
+ * The person takes control of the browser (every conversation's agent is refused meanwhile).
597
+ * `owners`: the conversations owning a tab now, told on hand back.
598
+ */
599
+ takeover(owners = []) {
198
600
  if (this.since !== void 0) return;
199
601
  this.since = this.clock.now();
200
- this.note = void 0;
602
+ this.concerned = new Set(owners);
201
603
  this.emit();
202
604
  }
605
+ /** The person used a tab of `conversationId` during the takeover: it is told on hand back. */
606
+ concern(conversationId) {
607
+ if (this.since === void 0 || conversationId === void 0) return;
608
+ this.concerned.add(conversationId);
609
+ }
203
610
  handback() {
204
611
  if (this.since === void 0) return;
205
- this.note = this.since;
612
+ for (const c of this.concerned) this.notes.set(c, this.since);
613
+ this.concerned = /* @__PURE__ */ new Set();
206
614
  this.since = void 0;
207
615
  this.clearGrace();
208
616
  this.emit();
209
617
  }
210
618
  /**
211
- * When the last takeover began (ISO), once: the first tool reply after a hand back carries it so
212
- * the agent learns the person drove the browser.
619
+ * When the last takeover that concerned the conversation began (ISO), once: its first ok reply
620
+ * after the hand back carries it so its agent learns the person drove the browser.
213
621
  */
214
- takeHandbackNote() {
215
- const n = this.note;
216
- this.note = void 0;
622
+ takeHandbackNote(conversationId) {
623
+ const n = this.notes.get(conversationId);
624
+ this.notes.delete(conversationId);
217
625
  return n === void 0 ? void 0 : new Date(n).toISOString();
218
626
  }
627
+ // ---- viewers and requests (the daemon's own idle stop)
219
628
  viewerOpened() {
220
629
  this.viewers++;
221
630
  this.clearGrace();
@@ -245,6 +654,10 @@ var DaemonState = class {
245
654
  this.clearGrace();
246
655
  if (this.idleTimer !== void 0) this.clock.cancel(this.idleTimer);
247
656
  this.idleTimer = void 0;
657
+ for (const e of this.conversations.values()) {
658
+ if (e.idleTimer !== void 0) this.clock.cancel(e.idleTimer);
659
+ e.idleTimer = void 0;
660
+ }
248
661
  this.listeners.clear();
249
662
  }
250
663
  emit() {
@@ -255,15 +668,49 @@ var DaemonState = class {
255
668
  this.graceTimer = void 0;
256
669
  }
257
670
  /**
258
- * (Re)starts the idle countdown when nothing is in use; stops it otherwise. A pending handoff
259
- * keeps the daemon running until {@link HANDOFF_KEEPALIVE_MS} after its notice (the person is
260
- * still to answer it); the device's idle suspension may still stop the device sooner.
671
+ * (Re)starts the conversation's idle countdown when it is not in use (no request in flight, no
672
+ * viewer pin, no conversation park); stops it otherwise.
673
+ */
674
+ armConversation(conversationId, e) {
675
+ if (e.idleTimer !== void 0) this.clock.cancel(e.idleTimer);
676
+ e.idleTimer = void 0;
677
+ if (this.disposed || e.pins > 0 || this.busy(conversationId)) return;
678
+ const wait = Math.max(0, e.lastActiveAt + this.conversationIdleMs - this.clock.now());
679
+ e.idleTimer = this.clock.schedule(() => {
680
+ e.idleTimer = void 0;
681
+ this.idleClose(conversationId, e);
682
+ }, wait);
683
+ }
684
+ /** Closes an idle conversation's tabs and deletes what the daemon keeps for it. */
685
+ idleClose(conversationId, e) {
686
+ if (this.conversations.get(conversationId) !== e) return;
687
+ try {
688
+ this.onConversationIdle(conversationId);
689
+ } finally {
690
+ this.notes.delete(conversationId);
691
+ this.concerned.delete(conversationId);
692
+ if (e.parks.size === 0) this.conversations.delete(conversationId);
693
+ }
694
+ }
695
+ /** When the oldest pending park began, if any. */
696
+ oldestPark() {
697
+ let oldest;
698
+ for (const e of this.conversations.values())
699
+ for (const p of e.parks.values())
700
+ if (oldest === void 0 || p.since < oldest) oldest = p.since;
701
+ return oldest;
702
+ }
703
+ /**
704
+ * (Re)starts the idle countdown when nothing is in use; stops it otherwise. Pending parks keep
705
+ * the daemon running until {@link HANDOFF_KEEPALIVE_MS} after the oldest one began (the person
706
+ * is still to answer a handoff); the device's idle suspension may still stop the device sooner.
261
707
  */
262
708
  armIdle() {
263
709
  if (this.idleTimer !== void 0) this.clock.cancel(this.idleTimer);
264
710
  this.idleTimer = void 0;
265
711
  if (this.disposed || this.viewers > 0 || this.inflight > 0) return;
266
- const keepalive = this.handoffSince === void 0 ? 0 : this.handoffSince + HANDOFF_KEEPALIVE_MS - this.clock.now();
712
+ const oldest = this.oldestPark();
713
+ const keepalive = oldest === void 0 ? 0 : oldest + HANDOFF_KEEPALIVE_MS - this.clock.now();
267
714
  this.idleTimer = this.clock.schedule(
268
715
  () => {
269
716
  this.idleTimer = void 0;
@@ -274,6 +721,49 @@ var DaemonState = class {
274
721
  }
275
722
  };
276
723
 
724
+ // daemon/verification.ts
725
+ 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.";
726
+ var URL_RE = /captcha|challenge|antispider|anti-spider|\/sorry\/|wappass\.baidu\.com|\/cdn-cgi\/|\/verify(?:[/?#]|$)|security-?check/i;
727
+ 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;
728
+ var VERIFICATION_STATUSES = /* @__PURE__ */ new Set([418, 429]);
729
+ var WIDGET_SELECTOR = [
730
+ ...["recaptcha", "hcaptcha", "challenges.cloudflare.com", "turnstile", "geetest", "captcha"].map(
731
+ (s) => `iframe[src*="${s}" i]`
732
+ ),
733
+ '[id*="captcha" i]',
734
+ '[class*="captcha" i]'
735
+ ].join(", ");
736
+ var MAX_WIDGETS = 10;
737
+ async function hasWidget(page) {
738
+ const found = page.locator(WIDGET_SELECTOR);
739
+ const n = Math.min(await found.count(), MAX_WIDGETS);
740
+ for (let i = 0; i < n; i++) {
741
+ const box = await found.nth(i).boundingBox();
742
+ if (box !== null && box.width > 20 && box.height > 20) return true;
743
+ }
744
+ return false;
745
+ }
746
+ function looksLikeVerification(url, title) {
747
+ let target = url;
748
+ try {
749
+ const u = new URL(url);
750
+ target = `${u.hostname}${u.pathname}${u.search}`;
751
+ } catch {
752
+ }
753
+ return URL_RE.test(target) || TITLE_RE.test(title);
754
+ }
755
+ async function isVerificationPage(page, status) {
756
+ try {
757
+ if (status !== void 0 && VERIFICATION_STATUSES.has(status)) return true;
758
+ const url = page.url();
759
+ if (!/^https?:/.test(url)) return false;
760
+ if (looksLikeVerification(url, await page.title())) return true;
761
+ return await hasWidget(page);
762
+ } catch {
763
+ return false;
764
+ }
765
+ }
766
+
277
767
  // daemon/actions.ts
278
768
  var ActionError = class extends Error {
279
769
  constructor(code, message) {
@@ -282,6 +772,19 @@ var ActionError = class extends Error {
282
772
  }
283
773
  code;
284
774
  };
775
+ function blockedHostsOf(c) {
776
+ return [...c.blocked].map(([host, layer]) => ({ host, layer }));
777
+ }
778
+ function blockedMessage(blocked) {
779
+ const device = blocked.filter((b) => b.layer === "device").map((b) => b.host);
780
+ const address = blocked.filter((b) => b.layer === "address").map((b) => b.host);
781
+ return [
782
+ ...device.length > 0 ? [`The device's network settings block ${device.join(", ")}.`] : [],
783
+ ...address.length > 0 ? [
784
+ `${address.join(", ")} ${address.length === 1 ? "resolves" : "resolve"} to a private or local address on the device, which the browser never reaches from the sandbox.`
785
+ ] : []
786
+ ].join(" ");
787
+ }
285
788
  var DOWNLOAD_WAIT_MS = 1e4;
286
789
  var DEFAULT_DOWNLOAD_MAX_BYTES = 200 * 1024 * 1024;
287
790
  var DOWNLOAD_POLL_MS = 250;
@@ -289,6 +792,7 @@ var MAX_NAME_BYTES = 200;
289
792
  var ACTION_TIMEOUT_MS = 1e4;
290
793
  var NAVIGATION_TIMEOUT_MS = 3e4;
291
794
  var LOAD_GRACE_MS = 5e3;
795
+ var PAGE_QUERY_MS = 1e3;
292
796
  var MAX_WAIT_MS = 6e4;
293
797
  var MAX_SCREENSHOT_BYTES = Math.floor((8 * 1024 * 1024 - 64 * 1024) * 3 / 4);
294
798
  var MAX_TITLE_CHARS = 2048;
@@ -323,17 +827,186 @@ function safeFileName(raw) {
323
827
  if (Buffer.byteLength(ext) > 32) ext = "";
324
828
  return utf8Prefix(name.slice(0, name.length - ext.length), MAX_NAME_BYTES - Buffer.byteLength(ext)) + ext;
325
829
  }
326
- function absent(path) {
830
+ function copyInto(source, out) {
831
+ const src = openSync(source, fsc.O_RDONLY | fsc.O_NOFOLLOW);
327
832
  try {
328
- lstatSync(path);
329
- return false;
330
- } catch {
331
- return true;
833
+ const buf = Buffer.alloc(1024 * 1024);
834
+ for (; ; ) {
835
+ const n = readSync(src, buf, 0, buf.length, null);
836
+ if (n === 0) break;
837
+ let w = 0;
838
+ while (w < n) w += writeSync(out, buf, w, n - w);
839
+ }
840
+ } finally {
841
+ closeSync(src);
332
842
  }
333
843
  }
334
844
  var PROXY_PROBE_TIMEOUT_MS = 5e3;
845
+ var UPLOAD_MAX_BYTES = 50 * 1024 * 1024;
846
+ var UPLOAD_TYPES = {
847
+ ".png": "image/png",
848
+ ".jpg": "image/jpeg",
849
+ ".jpeg": "image/jpeg",
850
+ ".gif": "image/gif",
851
+ ".webp": "image/webp",
852
+ ".svg": "image/svg+xml",
853
+ ".pdf": "application/pdf",
854
+ ".txt": "text/plain",
855
+ ".md": "text/markdown",
856
+ ".csv": "text/csv",
857
+ ".json": "application/json",
858
+ ".html": "text/html",
859
+ ".zip": "application/zip",
860
+ ".mp4": "video/mp4",
861
+ ".mp3": "audio/mpeg",
862
+ ".docx": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
863
+ ".xlsx": "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
864
+ ".pptx": "application/vnd.openxmlformats-officedocument.presentationml.presentation"
865
+ };
866
+ function within(real, root) {
867
+ return real === root || real.startsWith(root.endsWith(sep) ? root : root + sep);
868
+ }
869
+ var sameFile = (a, b) => a.dev === b.dev && a.ino === b.ino;
335
870
  var REF_RE = /^(f\d+)?e\d+$/;
336
871
  var PROXY_FAILURE_RE = /ERR_TUNNEL_CONNECTION_FAILED|ERR_PROXY_CONNECTION_FAILED/;
872
+ var NETWORK_ERROR_RE = /^ERR_(TIMED_OUT|CONNECTION_[A-Z_]+|NAME_NOT_RESOLVED|NAME_RESOLUTION_FAILED|ADDRESS_UNREACHABLE|EMPTY_RESPONSE|NETWORK_[A-Z_]+|SOCKET_NOT_CONNECTED)$/;
873
+ var NO_TAB_TO_WAIT_ON = "This conversation has no browser tab to wait on; call browser_navigate to open a page first.";
874
+ var ERROR_PAGE_INTERRUPT_RE = /is interrupted by another navigation to "chrome-error:/;
875
+ var NETWORK_CHANGED_ATTEMPTS = 4;
876
+ var ERROR_PAGE_WAIT_MS = 2e3;
877
+ var isTimeout = (e) => e instanceof Error && e.name === "TimeoutError";
878
+ var NET_ERROR_MEANINGS = {
879
+ ERR_NAME_NOT_RESOLVED: "the host name does not resolve",
880
+ ERR_CONNECTION_REFUSED: "the host refused the connection",
881
+ ERR_CONNECTION_RESET: "the connection was reset",
882
+ ERR_CONNECTION_CLOSED: "the host closed the connection without an answer",
883
+ ERR_CONNECTION_TIMED_OUT: "the host did not answer the connection",
884
+ ERR_ADDRESS_UNREACHABLE: "the host's address is unreachable",
885
+ ERR_INTERNET_DISCONNECTED: "the device has no network connection",
886
+ ERR_EMPTY_RESPONSE: "the server sent an empty answer",
887
+ ERR_SSL_PROTOCOL_ERROR: "the secure connection failed",
888
+ ERR_CERT_AUTHORITY_INVALID: "the site's certificate is not trusted",
889
+ ERR_CERT_COMMON_NAME_INVALID: "the site's certificate is for another name",
890
+ ERR_CERT_DATE_INVALID: "the site's certificate has expired or is not yet valid",
891
+ ERR_TOO_MANY_REDIRECTS: "the page redirects in a loop"
892
+ };
893
+ function docUrl(raw) {
894
+ try {
895
+ const u = new URL(raw);
896
+ u.hash = "";
897
+ return u.href;
898
+ } catch {
899
+ return raw;
900
+ }
901
+ }
902
+ var NavWatch = class {
903
+ constructor(page, url, pending) {
904
+ this.page = page;
905
+ this.pending = pending;
906
+ this.target = docUrl(url);
907
+ const before = pending();
908
+ if (before !== void 0 && this.isOurs(before)) this.lastOurs = before;
909
+ page.on("request", this.onRequest);
910
+ page.on("framenavigated", this.onNavigated);
911
+ page.on("requestfailed", this.onFailed);
912
+ page.on("requestfinished", this.onFinished);
913
+ }
914
+ page;
915
+ pending;
916
+ target;
917
+ /** The newest main-frame navigation request to the target address (redirects included). */
918
+ lastOurs;
919
+ /** The request of `lastOurs`'s chain whose document the main frame committed. */
920
+ committedOurs;
921
+ /** The request of `lastOurs`'s chain that failed. */
922
+ failedOurs;
923
+ wake;
924
+ onRequest = (r) => {
925
+ if (!r.isNavigationRequest() || r.frame() !== this.page.mainFrame()) return;
926
+ this.lastOurs = this.isOurs(r) ? r : void 0;
927
+ this.wake?.();
928
+ };
929
+ onNavigated = (f) => {
930
+ if (f !== this.page.mainFrame()) return;
931
+ const ours = this.lastOurs;
932
+ if (ours !== void 0 && docUrl(this.page.mainFrame().url()) === docUrl(ours.url()))
933
+ this.committedOurs = ours;
934
+ this.wake?.();
935
+ };
936
+ onFailed = (r) => {
937
+ if (r === this.lastOurs) this.failedOurs = r;
938
+ this.wake?.();
939
+ };
940
+ /** After the session's own `requestfinished` handler (registered first) settled the request. */
941
+ onFinished = (r) => {
942
+ if (!r.isNavigationRequest() || r.frame() !== this.page.mainFrame()) return;
943
+ const wake = () => this.wake?.();
944
+ void r.response().then(wake, wake);
945
+ };
946
+ isOurs(r) {
947
+ let root = r;
948
+ for (let from = r.redirectedFrom(); from !== null; from = from.redirectedFrom()) root = from;
949
+ return docUrl(root.url()) === this.target;
950
+ }
951
+ /** Resolves on the next navigation event or after `ms`. */
952
+ next(ms) {
953
+ return new Promise((resolve) => {
954
+ const timer = setTimeout(done, ms);
955
+ function done() {
956
+ clearTimeout(timer);
957
+ resolve();
958
+ }
959
+ this.wake = () => {
960
+ this.wake = void 0;
961
+ done();
962
+ };
963
+ });
964
+ }
965
+ /**
966
+ * After an abort: waits (until `deadline`, the navigation's own) while a navigation to the
967
+ * target address is in flight, then tells whether it loaded (its document committed; a script
968
+ * may have moved the page on since), failed, or none of ours took over.
969
+ */
970
+ async follow(deadline) {
971
+ for (let r = this.pending(); r !== void 0; r = this.pending()) {
972
+ if (!this.isOurs(r)) return { kind: "none" };
973
+ const left2 = deadline - Date.now();
974
+ if (left2 <= 0) return { kind: "none" };
975
+ await this.next(left2);
976
+ }
977
+ const final = this.lastOurs;
978
+ if (final === void 0) return { kind: "none" };
979
+ if (this.failedOurs === final) {
980
+ return { kind: "failed", url: final.url(), error: final.failure()?.errorText ?? "" };
981
+ }
982
+ if (this.committedOurs !== final) return { kind: "none" };
983
+ const left = deadline - Date.now();
984
+ if (left <= 0) return { kind: "none" };
985
+ try {
986
+ await this.page.waitForLoadState("domcontentloaded", { timeout: left });
987
+ } catch {
988
+ return { kind: "none" };
989
+ }
990
+ return { kind: "loaded", response: await final.response().catch(() => null) };
991
+ }
992
+ /**
993
+ * The status the newest navigation to the target address was answered with, when it finished
994
+ * without a document (a 204 or 205: Chromium keeps the page and aborts the navigation).
995
+ */
996
+ async emptyAnswer() {
997
+ const r = this.lastOurs;
998
+ if (r === void 0 || r === this.committedOurs) return void 0;
999
+ const status = (await r.response().catch(() => null))?.status();
1000
+ return status === 204 || status === 205 ? status : void 0;
1001
+ }
1002
+ dispose() {
1003
+ this.page.off("request", this.onRequest);
1004
+ this.page.off("framenavigated", this.onNavigated);
1005
+ this.page.off("requestfailed", this.onFailed);
1006
+ this.page.off("requestfinished", this.onFinished);
1007
+ this.wake?.();
1008
+ }
1009
+ };
337
1010
  function jpegSize(jpeg) {
338
1011
  let i = 2;
339
1012
  while (i + 9 < jpeg.length) {
@@ -371,13 +1044,28 @@ async function captureFitting(cdp, opts) {
371
1044
  }
372
1045
  return null;
373
1046
  }
374
- function proxyRefuses(proxy, host, port) {
1047
+ var PROXY_DOWN_CODES = /* @__PURE__ */ new Set([
1048
+ "ECONNREFUSED",
1049
+ "EHOSTUNREACH",
1050
+ "ENETUNREACH",
1051
+ "ENOTFOUND",
1052
+ "EAI_AGAIN"
1053
+ ]);
1054
+ async function proxyRefusal(proxy, host, port) {
1055
+ const answer = await probeProxy(proxy, host, port);
1056
+ if (answer.verdict !== "refused") return null;
1057
+ return refusalLayer(answer.reason);
1058
+ }
1059
+ function refusalLayer(reason) {
1060
+ return sandboxProxyRefusalLayer(reason) === "address" ? "address" : "device";
1061
+ }
1062
+ function probeProxy(proxy, host, port) {
375
1063
  return new Promise((resolve) => {
376
1064
  let url;
377
1065
  try {
378
1066
  url = new URL(proxy.includes("://") ? proxy : `http://${proxy}`);
379
1067
  } catch {
380
- resolve(false);
1068
+ resolve({ verdict: "unknown", reason: "" });
381
1069
  return;
382
1070
  }
383
1071
  const headers = { host: `${host}:${port}` };
@@ -393,16 +1081,34 @@ function proxyRefuses(proxy, host, port) {
393
1081
  headers,
394
1082
  timeout: PROXY_PROBE_TIMEOUT_MS
395
1083
  });
1084
+ const answer = (res) => ({
1085
+ verdict: res.statusCode === 403 ? "refused" : res.statusCode === 200 ? "connected" : "unreachable",
1086
+ reason: res.statusMessage ?? ""
1087
+ });
396
1088
  req.on("connect", (res, socket) => {
397
1089
  socket.destroy();
398
- resolve(res.statusCode === 403);
1090
+ resolve(answer(res));
399
1091
  });
400
1092
  req.on("response", (res) => {
401
1093
  res.resume();
402
- resolve(res.statusCode === 403);
1094
+ resolve(answer(res));
1095
+ });
1096
+ req.on("timeout", () => {
1097
+ resolve({ verdict: "no_answer", reason: "" });
1098
+ req.destroy();
1099
+ });
1100
+ let connected = false;
1101
+ req.on("socket", (sock) => {
1102
+ if (sock.connecting) sock.once("connect", () => connected = true);
1103
+ else connected = true;
403
1104
  });
404
- req.on("timeout", () => req.destroy());
405
- req.on("error", () => resolve(false));
1105
+ req.on(
1106
+ "error",
1107
+ (e) => resolve({
1108
+ verdict: !connected && PROXY_DOWN_CODES.has(e.code ?? "") ? "proxy_down" : "unknown",
1109
+ reason: ""
1110
+ })
1111
+ );
406
1112
  req.end();
407
1113
  });
408
1114
  }
@@ -422,10 +1128,46 @@ function normalizeUrl(raw) {
422
1128
  return url.href;
423
1129
  }
424
1130
  var firstLine = (e) => (e instanceof Error ? e.message : String(e)).split("\n")[0]?.replace(/^[a-zA-Z.]+: /, "") ?? "";
1131
+ var NO_USAGE = {
1132
+ busy: () => false,
1133
+ pinned: () => false,
1134
+ idleFor: () => Number.POSITIVE_INFINITY,
1135
+ lastActiveAt: () => Number.NEGATIVE_INFINITY,
1136
+ tabParked: () => false,
1137
+ tabClosed: () => void 0,
1138
+ seen: () => void 0,
1139
+ known: () => true
1140
+ };
1141
+ function isStartBlank(tab) {
1142
+ return tab.owner === void 0 && tab.url === "about:blank";
1143
+ }
1144
+ var OTHER_TITLE_CHARS = 120;
1145
+ var notYourTab = (id) => `Tab ${id} belongs to another conversation; call browser_tabs with action adopt and tabId ${id} first if the user asked you to use it.`;
1146
+ var tabInUse = (id) => `Tab ${id} is in use by another conversation right now; retry shortly or open your own tab.`;
1147
+ var tabMoved = (id, title) => `Tab ${id} (${title}) was moved to another conversation.`;
1148
+ var tabEvicted = (id, title) => `Tab ${id} (${title}) was closed to make room for another conversation.`;
1149
+ var CONVERSATION_CAP_MESSAGE = `This conversation has ${MAX_TABS_PER_CONVERSATION} tabs open, the most one conversation keeps; close one first.`;
1150
+ var deviceCapMessage = (own) => own > 0 ? `The browser has ${MAX_TABS} tabs open, the most it keeps (${own} ${own === 1 ? "is" : "are"} this conversation's); close one of yours first.` : `Other conversations hold all ${MAX_TABS} tabs of the browser; retry later or ask the user to close one in the browser panel.`;
1151
+ function bareUrl(raw) {
1152
+ try {
1153
+ const u = new URL(raw);
1154
+ u.search = "";
1155
+ u.hash = "";
1156
+ return u.href;
1157
+ } catch {
1158
+ return raw.replace(/[?#].*$/s, "");
1159
+ }
1160
+ }
1161
+ function isActing(req) {
1162
+ if (req.op === "handoff_notice" || req.op === "handoff_clear") return false;
1163
+ if (req.op === "tabs") return req.action !== "list" && req.action !== "adopt";
1164
+ return true;
1165
+ }
425
1166
  var BrowserSession = class {
426
1167
  ctx;
427
1168
  proxy;
428
1169
  clock;
1170
+ navigationTimeoutMs;
429
1171
  /** The device's workspace root (CAPYBARA_SERVICE_WORKSPACE): uploads and downloads stay in it. */
430
1172
  workspace;
431
1173
  downloadsTmp;
@@ -443,16 +1185,54 @@ var BrowserSession = class {
443
1185
  ids = /* @__PURE__ */ new WeakMap();
444
1186
  titles = /* @__PURE__ */ new Map();
445
1187
  loadingTabs = /* @__PURE__ */ new Set();
1188
+ /**
1189
+ * Each tab's icon: the address it came from and its data URL (null: none or not usable). Kept
1190
+ * across navigations until the new page's icon is known, so the strip does not flicker.
1191
+ */
1192
+ favicons = /* @__PURE__ */ new Map();
1193
+ /** Tabs showing a verification page, by tab id (cleared on every main-frame navigation). */
1194
+ blockers = /* @__PURE__ */ new Map();
1195
+ /** The status of each tab's current document (main-frame response), by tab id. */
1196
+ docStatus = /* @__PURE__ */ new Map();
1197
+ /** Each page's main-frame navigation request in flight (until it commits, fails or finishes). */
1198
+ pendingNavs = /* @__PURE__ */ new WeakMap();
446
1199
  listeners = /* @__PURE__ */ new Set();
447
1200
  collectors = /* @__PURE__ */ new Set();
448
1201
  probes = /* @__PURE__ */ new Map();
449
1202
  reservedDownloads = /* @__PURE__ */ new Set();
450
- unreported = [];
1203
+ /** Notes of a conversation's pages that arrived with none of its requests in flight. */
1204
+ unreported = /* @__PURE__ */ new Map();
1205
+ /** Device notes (no page: the browser build) for the next reply of any conversation. */
1206
+ unreportedAll = [];
451
1207
  nextId = 1;
452
- active;
453
- queue = Promise.resolve();
454
- /** The agent's latest click; `seq` grows with every click (viewers flash only new ones). */
455
- lastClick;
1208
+ /** Each owned tab's owner (an unowned tab has no entry). */
1209
+ owners = /* @__PURE__ */ new Map();
1210
+ /** Each conversation's active tab. */
1211
+ activeOf = /* @__PURE__ */ new Map();
1212
+ /** The action queues, by {@link queueKey}. */
1213
+ queues = /* @__PURE__ */ new Map();
1214
+ /** A conversation's first tab being claimed or opened (shared by its callers meanwhile). */
1215
+ claiming = /* @__PURE__ */ new Map();
1216
+ /** Tab allocations (claim, open, eviction) one at a time across conversations. */
1217
+ allocChain = Promise.resolve();
1218
+ /** Tabs being opened by the session (not yet tracked): they count toward the device cap. */
1219
+ reserved = 0;
1220
+ /**
1221
+ * Tabs whose close is under way (an idle-closed conversation's, an evicted one): no
1222
+ * conversation owns, claims, adopts or lists them any more, and the device cap leaves them out.
1223
+ */
1224
+ closing = /* @__PURE__ */ new Set();
1225
+ /** When an agent request last acted on each tab (the eviction's least recently used tab). */
1226
+ tabUsedAt = /* @__PURE__ */ new Map();
1227
+ /** When each tab went to its owner (the next active tab after a loss is the newest). */
1228
+ gainedAt = /* @__PURE__ */ new Map();
1229
+ gainSeq = 0;
1230
+ /** Order of the conversations' last acting requests (a viewer's default shown tab). */
1231
+ actedSeq = /* @__PURE__ */ new Map();
1232
+ actSeq = 0;
1233
+ usage;
1234
+ /** Each tab's latest agent click; `seq` grows with every click (viewers flash only new ones). */
1235
+ clicks = /* @__PURE__ */ new Map();
456
1236
  clickSeq = 0;
457
1237
  constructor(ctx, opts) {
458
1238
  this.ctx = ctx;
@@ -462,20 +1242,21 @@ var BrowserSession = class {
462
1242
  this.downloadMaxBytes = opts.downloadMaxBytes ?? DEFAULT_DOWNLOAD_MAX_BYTES;
463
1243
  this.downloadWaitMs = opts.downloadWaitMs ?? DOWNLOAD_WAIT_MS;
464
1244
  this.clock = opts.clock ?? systemClock;
1245
+ this.navigationTimeoutMs = opts.navigationTimeoutMs ?? NAVIGATION_TIMEOUT_MS;
1246
+ this.usage = opts.usage ?? NO_USAGE;
465
1247
  ctx.setDefaultTimeout(ACTION_TIMEOUT_MS);
466
- ctx.setDefaultNavigationTimeout(NAVIGATION_TIMEOUT_MS);
1248
+ ctx.setDefaultNavigationTimeout(this.navigationTimeoutMs);
467
1249
  ctx.on("page", (p) => {
468
- if (!this.ids.has(p) && this.pages.size >= MAX_TABS) {
469
- p.close().catch(() => void 0);
470
- this.note(
471
- `The page opened a popup, but the browser keeps at most ${MAX_TABS} tabs, so the popup was closed; close a tab and retry if it was needed.`
472
- );
473
- return;
474
- }
1250
+ if (this.ids.has(p)) return;
475
1251
  this.track(p);
476
- this.active = this.ids.get(p);
477
- this.emit({ type: "active" });
478
1252
  this.emit({ type: "state" });
1253
+ queueMicrotask(() => {
1254
+ void this.allocate(async () => {
1255
+ const id = this.ids.get(p);
1256
+ if (id === void 0 || this.owners.has(id) || p.isClosed()) return;
1257
+ if (this.live().length > MAX_TABS) await p.close().catch(() => void 0);
1258
+ });
1259
+ });
479
1260
  });
480
1261
  for (const p of ctx.pages()) this.track(p);
481
1262
  }
@@ -486,34 +1267,313 @@ var BrowserSession = class {
486
1267
  this.listeners.add(fn);
487
1268
  return () => this.listeners.delete(fn);
488
1269
  }
489
- /** The active tab, opening a blank one when none is left. */
490
- async activePage() {
491
- const cur = this.active === void 0 ? void 0 : this.pages.get(this.active);
492
- if (cur !== void 0 && !cur.isClosed()) return cur;
493
- const first = [...this.pages.values()].find((p2) => !p2.isClosed());
494
- if (first !== void 0) {
495
- this.active = this.ids.get(first);
496
- return first;
497
- }
498
- const p = await this.ctx.newPage();
499
- this.track(p);
500
- this.active = this.ids.get(p);
501
- return p;
502
- }
503
1270
  tabIdOf(page) {
504
1271
  return this.ids.get(page) ?? "";
505
1272
  }
1273
+ /** The live page of a tab, if it is open (and not closing). */
1274
+ pageById(tabId) {
1275
+ const page = tabId === void 0 ? void 0 : this.pages.get(tabId);
1276
+ return page === void 0 || page.isClosed() || this.closing.has(tabId) ? void 0 : page;
1277
+ }
1278
+ /** The open tabs that are not closing, in tab order. */
1279
+ live() {
1280
+ return [...this.pages.entries()].filter(([id, p]) => !p.isClosed() && !this.closing.has(id));
1281
+ }
1282
+ /** A tab's owner, if it has one. */
1283
+ ownerOf(tabId) {
1284
+ return this.owners.get(tabId);
1285
+ }
1286
+ /** The conversations owning a tab now. */
1287
+ owningConversations() {
1288
+ return [...new Set([...this.owners.values()].map((o) => o.owner))];
1289
+ }
1290
+ /** The conversation's tabs in tab order. */
1291
+ tabsOf(conversationId) {
1292
+ return this.live().map(([id]) => id).filter((id) => this.owners.get(id)?.owner === conversationId);
1293
+ }
1294
+ /** How many tabs the conversation owns. */
1295
+ countOf(conversationId) {
1296
+ return this.tabsOf(conversationId).length;
1297
+ }
1298
+ /** The conversation's active tab id, if it has a live one. */
1299
+ activeTabOf(conversationId) {
1300
+ const id = this.activeOf.get(conversationId);
1301
+ return this.pageById(id) === void 0 ? void 0 : id;
1302
+ }
1303
+ /** The conversation's active page, if it has one (never opens a tab). */
1304
+ currentPage(conversationId) {
1305
+ return this.pageById(this.activeOf.get(conversationId));
1306
+ }
1307
+ /** The order of the conversation's last acting request (higher: later; 0: never). */
1308
+ actedOrder(conversationId) {
1309
+ return this.actedSeq.get(conversationId) ?? 0;
1310
+ }
1311
+ /** The tab's latest agent click, if any. */
1312
+ lastClickOf(tabId) {
1313
+ return tabId === void 0 ? void 0 : this.clicks.get(tabId);
1314
+ }
1315
+ /** Whether the tab is loading a document. */
1316
+ isLoading(tabId) {
1317
+ return tabId !== void 0 && this.loadingTabs.has(tabId);
1318
+ }
506
1319
  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
- }));
1320
+ return this.live().map(([id, p]) => {
1321
+ const blocker = this.blockers.get(id);
1322
+ const icon = this.favicons.get(id)?.data;
1323
+ const o = this.owners.get(id);
1324
+ return {
1325
+ id,
1326
+ title: clip(this.titles.get(id) ?? "", MAX_TITLE_CHARS),
1327
+ url: clip(p.url(), MAX_URL_CHARS),
1328
+ active: o !== void 0 && this.activeOf.get(o.owner) === id,
1329
+ ...o === void 0 ? {} : { owner: o.owner, root: o.root },
1330
+ ...blocker === void 0 ? {} : { blocker },
1331
+ ...icon === void 0 || icon === null ? {} : { favicon: icon },
1332
+ ...this.loadingTabs.has(id) ? { loading: true } : {}
1333
+ };
1334
+ });
1335
+ }
1336
+ /** Makes a tab the conversation's active tab (it must own it). */
1337
+ setActive(conversationId, tabId) {
1338
+ if (this.owners.get(tabId)?.owner !== conversationId) return;
1339
+ if (this.activeOf.get(conversationId) === tabId) return;
1340
+ this.activeOf.set(conversationId, tabId);
1341
+ this.emit({ type: "active", conversationId });
1342
+ this.emit({ type: "state" });
513
1343
  }
514
- /** Whether the active tab is loading a document. */
515
- get loading() {
516
- return this.active !== void 0 && this.loadingTabs.has(this.active);
1344
+ /** Gives a tab to a conversation (owner and root); the previous owner's active moves on. */
1345
+ assign(tabId, to) {
1346
+ const before = this.owners.get(tabId);
1347
+ this.owners.set(tabId, to);
1348
+ this.gainedAt.set(tabId, ++this.gainSeq);
1349
+ if (before !== void 0 && before.owner !== to.owner) this.activeMovedOff(before.owner, tabId);
1350
+ return before;
1351
+ }
1352
+ /**
1353
+ * A conversation lost its tab `tabId` (closed or moved): when it was its active tab, the active
1354
+ * tab becomes its most recently opened remaining tab, or none.
1355
+ */
1356
+ activeMovedOff(conversationId, tabId) {
1357
+ if (this.activeOf.get(conversationId) !== tabId) return;
1358
+ const next = this.newestTabOf(conversationId, tabId);
1359
+ if (next === void 0) this.activeOf.delete(conversationId);
1360
+ else this.activeOf.set(conversationId, next);
1361
+ this.emit({ type: "active", conversationId });
1362
+ }
1363
+ /**
1364
+ * The conversation's tab it gained last (opened, claimed, adopted or restored), besides
1365
+ * `except`.
1366
+ */
1367
+ newestTabOf(conversationId, except) {
1368
+ let best;
1369
+ for (const id of this.tabsOf(conversationId)) {
1370
+ if (id === except) continue;
1371
+ if (best === void 0 || (this.gainedAt.get(id) ?? 0) > (this.gainedAt.get(best) ?? 0))
1372
+ best = id;
1373
+ }
1374
+ return best;
1375
+ }
1376
+ /** Runs a tab allocation (claim, open, eviction) one at a time across conversations. */
1377
+ allocate(fn) {
1378
+ const run = this.allocChain.then(fn, fn);
1379
+ this.allocChain = run.catch(() => void 0);
1380
+ return run;
1381
+ }
1382
+ /**
1383
+ * The page an acting request of the conversation acts on: its active tab; with no live tab, an
1384
+ * unowned tab it claims, else a new tab (subject to the caps). Callers that find no tab at the
1385
+ * same time share one claim, so the conversation gets exactly one tab.
1386
+ */
1387
+ async pageFor(conversationId, root) {
1388
+ const cur = this.currentPage(conversationId);
1389
+ if (cur !== void 0) return cur;
1390
+ const own = this.newestTabOf(conversationId);
1391
+ if (own !== void 0) {
1392
+ this.setActive(conversationId, own);
1393
+ const page = this.pageById(own);
1394
+ if (page !== void 0) return page;
1395
+ }
1396
+ let claim = this.claiming.get(conversationId);
1397
+ if (claim === void 0) {
1398
+ claim = this.allocate(async () => {
1399
+ const now = this.currentPage(conversationId) ?? this.pageById(this.newestTabOf(conversationId));
1400
+ if (now !== void 0) {
1401
+ this.setActive(conversationId, this.tabIdOf(now));
1402
+ return now;
1403
+ }
1404
+ const unowned = this.live().find(
1405
+ ([id, p]) => isStartBlank({ owner: this.owners.get(id)?.owner, url: p.url() }) && !this.usage.tabParked(id)
1406
+ );
1407
+ if (unowned !== void 0) {
1408
+ const [id, page] = unowned;
1409
+ this.assign(id, { owner: conversationId, root });
1410
+ this.activeOf.set(conversationId, id);
1411
+ this.emit({ type: "active", conversationId });
1412
+ this.emit({ type: "state" });
1413
+ return page;
1414
+ }
1415
+ return this.openLocked(conversationId, root);
1416
+ }).finally(() => {
1417
+ this.claiming.delete(conversationId);
1418
+ });
1419
+ this.claiming.set(conversationId, claim);
1420
+ }
1421
+ return claim;
1422
+ }
1423
+ /** Opens a new tab for the conversation (the caps apply) and makes it its active tab. */
1424
+ openTab(conversationId, root) {
1425
+ return this.allocate(() => this.openLocked(conversationId, root));
1426
+ }
1427
+ /** {@link openTab} inside the allocation chain. */
1428
+ async openLocked(conversationId, root) {
1429
+ const own = this.countOf(conversationId);
1430
+ if (own >= MAX_TABS_PER_CONVERSATION) throw new ActionError("failed", CONVERSATION_CAP_MESSAGE);
1431
+ if (this.live().length + this.reserved >= MAX_TABS && !await this.evict(conversationId))
1432
+ throw new ActionError("failed", deviceCapMessage(own));
1433
+ this.reserved++;
1434
+ let page;
1435
+ try {
1436
+ page = await this.ctx.newPage();
1437
+ } finally {
1438
+ this.reserved--;
1439
+ }
1440
+ this.track(page);
1441
+ const id = this.tabIdOf(page);
1442
+ this.assign(id, { owner: conversationId, root });
1443
+ this.activeOf.set(conversationId, id);
1444
+ this.emit({ type: "active", conversationId });
1445
+ this.emit({ type: "state" });
1446
+ return page;
1447
+ }
1448
+ /**
1449
+ * Closes one tab to make room at the device cap: an unowned tab first, else a tab of the least
1450
+ * recently active conversation that is evictable (not in use, not pinned by a viewer, idle for
1451
+ * at least EVICT_MIN_IDLE_MS), its least recently used non-active tab before its active one; tabs
1452
+ * a park pins are skipped. Its owner is told. False when no tab qualifies.
1453
+ */
1454
+ async evict(forConversation) {
1455
+ const live = this.live().filter(([id]) => !this.usage.tabParked(id));
1456
+ const unowned = live.find(([id]) => !this.owners.has(id));
1457
+ if (unowned !== void 0) {
1458
+ await this.closeEvicted(unowned[0], unowned[1]);
1459
+ return true;
1460
+ }
1461
+ const owners = /* @__PURE__ */ new Set();
1462
+ for (const [id] of live) {
1463
+ const o = this.owners.get(id)?.owner;
1464
+ if (o !== void 0 && o !== forConversation && !this.usage.busy(o) && !this.usage.pinned(o) && this.usage.idleFor(o) >= EVICT_MIN_IDLE_MS)
1465
+ owners.add(o);
1466
+ }
1467
+ const victim = [...owners].sort(
1468
+ (a, b) => this.usage.lastActiveAt(a) - this.usage.lastActiveAt(b)
1469
+ )[0];
1470
+ if (victim === void 0) return false;
1471
+ const active = this.activeOf.get(victim);
1472
+ const used = (id) => this.tabUsedAt.get(id) ?? 0;
1473
+ const [tabId, page] = live.filter(([id]) => this.owners.get(id)?.owner === victim).sort(
1474
+ ([a], [b]) => (a === active ? 1 : 0) - (b === active ? 1 : 0) || used(a) - used(b)
1475
+ )[0] ?? [];
1476
+ if (tabId === void 0 || page === void 0) return false;
1477
+ const title = clip(this.titles.get(tabId) ?? "", OTHER_TITLE_CHARS) || "no title";
1478
+ await this.closeEvicted(tabId, page);
1479
+ this.noteTo(victim, tabEvicted(tabId, title));
1480
+ return true;
1481
+ }
1482
+ /**
1483
+ * Closes an evicted tab, closing from the start: no request or adopt reaches it while its close
1484
+ * runs (the close handler forgets it; a tab that would not close is kept as it was).
1485
+ */
1486
+ async closeEvicted(tabId, page) {
1487
+ this.closing.add(tabId);
1488
+ await page.close().catch(() => {
1489
+ this.closing.delete(tabId);
1490
+ });
1491
+ }
1492
+ /**
1493
+ * Moves a tab to the conversation and makes it its active tab (the tool's and a viewer's adopt).
1494
+ * `in_use`: its owner has a request in flight or a park (or a park pins the tab); `cap`: the
1495
+ * conversation already owns MAX_TABS_PER_CONVERSATION tabs. The previous owner is told.
1496
+ */
1497
+ adopt(conversationId, root, tabId) {
1498
+ this.tabById(tabId);
1499
+ const before = this.owners.get(tabId);
1500
+ if (before?.owner === conversationId) {
1501
+ this.setActive(conversationId, tabId);
1502
+ return "ok";
1503
+ }
1504
+ if (before !== void 0 && this.usage.busy(before.owner) || this.usage.tabParked(tabId))
1505
+ return "in_use";
1506
+ if (this.countOf(conversationId) >= MAX_TABS_PER_CONVERSATION) return "cap";
1507
+ this.assign(tabId, { owner: conversationId, root });
1508
+ this.activeOf.set(conversationId, tabId);
1509
+ this.usage.seen(conversationId, root);
1510
+ if (before !== void 0) {
1511
+ const title = clip(this.titles.get(tabId) ?? "", OTHER_TITLE_CHARS) || "no title";
1512
+ this.noteTo(before.owner, tabMoved(tabId, title));
1513
+ }
1514
+ this.emit({ type: "active", conversationId });
1515
+ this.emit({ type: "state" });
1516
+ return "ok";
1517
+ }
1518
+ /**
1519
+ * Opens a restored tab for its owner (the first claims the start's blank tab) and starts its
1520
+ * navigation without waiting for it.
1521
+ */
1522
+ async restoreTab(owner, url) {
1523
+ const page = await this.allocate(async () => {
1524
+ const blank = this.live().find(
1525
+ ([id2, p]) => isStartBlank({ owner: this.owners.get(id2)?.owner, url: p.url() })
1526
+ );
1527
+ if (blank !== void 0) {
1528
+ this.assign(blank[0], owner);
1529
+ return blank[1];
1530
+ }
1531
+ this.reserved++;
1532
+ try {
1533
+ const p = await this.ctx.newPage();
1534
+ this.track(p);
1535
+ this.assign(this.tabIdOf(p), owner);
1536
+ return p;
1537
+ } finally {
1538
+ this.reserved--;
1539
+ }
1540
+ });
1541
+ const id = this.tabIdOf(page);
1542
+ if (!this.activeOf.has(owner.owner)) this.activeOf.set(owner.owner, id);
1543
+ this.usage.seen(owner.owner, owner.root);
1544
+ this.emit({ type: "active", conversationId: owner.owner });
1545
+ this.emit({ type: "state" });
1546
+ let target;
1547
+ try {
1548
+ target = normalizeUrl(url);
1549
+ } catch {
1550
+ }
1551
+ if (target !== void 0) void this.viewerNav(page, { url: target });
1552
+ return id;
1553
+ }
1554
+ /**
1555
+ * Closes an idle conversation's tabs (except those a park pins) and forgets what the session
1556
+ * keeps for it.
1557
+ */
1558
+ async closeConversation(conversationId) {
1559
+ const ids = this.tabsOf(conversationId).filter((id) => !this.usage.tabParked(id));
1560
+ for (const id of ids) {
1561
+ this.closing.add(id);
1562
+ this.owners.delete(id);
1563
+ }
1564
+ this.activeOf.delete(conversationId);
1565
+ this.queues.delete(this.queueKey(conversationId));
1566
+ this.unreported.delete(conversationId);
1567
+ this.claiming.delete(conversationId);
1568
+ this.actedSeq.delete(conversationId);
1569
+ await Promise.all(
1570
+ ids.map(
1571
+ (id) => this.pages.get(id)?.close().catch(() => {
1572
+ this.closing.delete(id);
1573
+ })
1574
+ )
1575
+ );
1576
+ this.emit({ type: "state" });
517
1577
  }
518
1578
  emit(e) {
519
1579
  for (const fn of [...this.listeners]) {
@@ -529,55 +1589,119 @@ var BrowserSession = class {
529
1589
  this.ids.set(page, id);
530
1590
  this.pages.set(id, page);
531
1591
  const refresh = () => {
532
- page.title().then((t) => this.titles.set(id, t)).catch(() => void 0).finally(() => this.emit({ type: "state" }));
1592
+ page.title().then((t) => this.titles.set(id, t)).catch(() => void 0).then(() => this.checkVerification(page, id)).finally(() => this.emit({ type: "state" }));
1593
+ };
1594
+ const settle = (r) => {
1595
+ if (this.pendingNavs.get(page) === r) this.pendingNavs.delete(page);
533
1596
  };
1597
+ page.on("requestfinished", (r) => {
1598
+ if (this.pendingNavs.get(page) !== r) return;
1599
+ void r.response().then(
1600
+ (res) => {
1601
+ const status = res?.status() ?? 0;
1602
+ const redirects = status >= 300 && status < 400 && res?.headers().location;
1603
+ if (!redirects) settle(r);
1604
+ },
1605
+ () => settle(r)
1606
+ );
1607
+ });
534
1608
  page.on("request", (r) => {
535
1609
  if (r.isNavigationRequest() && r.frame() === page.mainFrame()) {
1610
+ this.pendingNavs.set(page, r);
536
1611
  this.loadingTabs.add(id);
537
1612
  this.emit({ type: "state" });
538
1613
  }
539
1614
  });
540
1615
  page.on("framenavigated", (f) => {
541
- if (f === page.mainFrame()) refresh();
1616
+ if (f !== page.mainFrame()) return;
1617
+ this.pendingNavs.delete(page);
1618
+ this.blockers.delete(id);
1619
+ refresh();
542
1620
  });
543
1621
  page.on("domcontentloaded", refresh);
544
1622
  page.on("load", () => {
545
1623
  this.loadingTabs.delete(id);
546
1624
  refresh();
1625
+ void this.resolveFavicon(page, id);
547
1626
  });
548
1627
  page.on("requestfailed", (r) => {
1628
+ settle(r);
549
1629
  const err = r.failure()?.errorText ?? "";
550
1630
  if (r.isNavigationRequest() && r.frame() === page.mainFrame()) {
551
1631
  this.loadingTabs.delete(id);
552
1632
  this.emit({ type: "state" });
553
1633
  }
554
- if (this.proxy !== void 0 && PROXY_FAILURE_RE.test(err))
555
- this.checkBlocked(r.url(), this.pageToOpen(page, r));
1634
+ if (this.proxy !== void 0 && (PROXY_FAILURE_RE.test(err) || err.includes("ERR_NETWORK_CHANGED")))
1635
+ this.checkBlocked(page, r.url(), this.pageToOpen(page, r));
556
1636
  });
557
1637
  page.on("response", (r) => {
1638
+ if (r.request().isNavigationRequest() && r.frame() === page.mainFrame())
1639
+ this.docStatus.set(id, r.status());
558
1640
  if (this.proxy !== void 0 && r.status() === 403 && r.url().startsWith("http:")) {
559
- this.checkBlocked(r.url(), this.pageToOpen(page, r.request()));
1641
+ this.checkBlocked(page, r.url(), this.pageToOpen(page, r.request()));
560
1642
  }
561
1643
  });
562
- page.on("dialog", (d) => this.onDialog(d));
563
- page.on("download", (d) => this.onDownload(d));
1644
+ page.on("dialog", (d) => this.onDialog(page, d));
1645
+ page.on("download", (d) => this.onDownload(page, d));
564
1646
  page.on("filechooser", () => {
565
- this.note("The page opened a file chooser; use the upload tool with the file input's ref.");
566
- this.emit({ type: "dialog", kind: "file", message: "" });
1647
+ const o = this.owners.get(id);
1648
+ this.noteTo(
1649
+ o?.owner,
1650
+ "The page opened a file chooser; use the upload tool with the file input's ref."
1651
+ );
1652
+ if (o !== void 0) this.emit({ type: "dialog", kind: "file", message: "", root: o.root });
567
1653
  });
1654
+ page.on("popup", (p) => this.onPopup(page, p));
568
1655
  page.on("close", () => {
1656
+ this.pendingNavs.delete(page);
569
1657
  this.pages.delete(id);
1658
+ this.closing.delete(id);
570
1659
  this.titles.delete(id);
571
1660
  this.loadingTabs.delete(id);
572
- if (this.active === id) {
573
- const next = [...this.pages.keys()].at(-1);
574
- this.active = next;
575
- this.emit({ type: "active" });
576
- }
1661
+ this.blockers.delete(id);
1662
+ this.favicons.delete(id);
1663
+ this.docStatus.delete(id);
1664
+ this.tabUsedAt.delete(id);
1665
+ this.gainedAt.delete(id);
1666
+ this.clicks.delete(id);
1667
+ const o = this.owners.get(id);
1668
+ this.owners.delete(id);
1669
+ if (o !== void 0) this.activeMovedOff(o.owner, id);
1670
+ this.usage.tabClosed(id);
577
1671
  this.emit({ type: "state" });
578
1672
  });
579
1673
  }
580
- onDialog(d) {
1674
+ /**
1675
+ * A page opened a popup: it belongs to the opener's owner and becomes its active tab, as in a
1676
+ * desktop browser (an unowned opener leaves it unowned). Past the conversation's cap it is closed
1677
+ * at once; past the device cap a tab is evicted for it, else it is closed; the owner is told.
1678
+ */
1679
+ onPopup(opener, popup) {
1680
+ this.track(popup);
1681
+ const id = this.tabIdOf(popup);
1682
+ const o = this.owners.get(this.tabIdOf(opener));
1683
+ if (o === void 0 || this.owners.has(id) || popup.isClosed()) return;
1684
+ const closeIt = (why) => {
1685
+ popup.close().catch(() => void 0);
1686
+ this.noteTo(
1687
+ o.owner,
1688
+ `The page opened a popup, but ${why}, so the popup was closed; close a tab and retry if it was needed.`
1689
+ );
1690
+ };
1691
+ if (this.countOf(o.owner) >= MAX_TABS_PER_CONVERSATION) {
1692
+ closeIt(`this conversation keeps at most ${MAX_TABS_PER_CONVERSATION} tabs`);
1693
+ return;
1694
+ }
1695
+ this.assign(id, o);
1696
+ this.activeOf.set(o.owner, id);
1697
+ this.emit({ type: "active", conversationId: o.owner });
1698
+ this.emit({ type: "state" });
1699
+ void this.allocate(async () => {
1700
+ if (popup.isClosed() || this.live().length <= MAX_TABS) return;
1701
+ if (!await this.evict(o.owner)) closeIt(`the browser keeps at most ${MAX_TABS} tabs`);
1702
+ });
1703
+ }
1704
+ onDialog(page, d) {
581
1705
  const type = d.type();
582
1706
  if (type === "beforeunload") {
583
1707
  d.accept().catch(() => void 0);
@@ -587,24 +1711,50 @@ var BrowserSession = class {
587
1711
  const message = clip(d.message(), MAX_DIALOG_CHARS);
588
1712
  const settle = kind === "alert" ? d.accept() : d.dismiss();
589
1713
  settle.catch(() => void 0);
590
- this.note(
1714
+ const o = this.owners.get(this.tabIdOf(page));
1715
+ this.noteTo(
1716
+ o?.owner,
591
1717
  `The page showed ${kind === "alert" ? "an alert" : `a ${kind}`} dialog: ${JSON.stringify(message)} (${kind === "alert" ? "closed" : "dismissed"}).`
592
1718
  );
593
- this.emit({ type: "dialog", kind, message });
1719
+ if (o !== void 0) this.emit({ type: "dialog", kind, message, root: o.root });
594
1720
  }
595
1721
  /**
596
- * Adds a note to the replies of the requests in flight; with none in flight (a download that
597
- * finished after its click replied, a dialog the person caused) the next reply carries it.
1722
+ * A device note (not about a page: the browser build that runs): the replies of the requests in
1723
+ * flight carry it, else the next reply of any conversation.
598
1724
  */
599
1725
  note(text) {
600
1726
  const n = clip(text, MAX_DIALOG_CHARS + 200);
601
1727
  if (this.collectors.size === 0) {
602
- this.unreported.push(n);
603
- if (this.unreported.length > MAX_UNREPORTED) this.unreported.shift();
1728
+ this.unreportedAll.push(n);
1729
+ if (this.unreportedAll.length > MAX_UNREPORTED) this.unreportedAll.shift();
604
1730
  return;
605
1731
  }
606
1732
  for (const c of this.collectors) c.notes.push(n);
607
1733
  }
1734
+ /**
1735
+ * A note for a conversation (about one of its pages): its requests in flight carry it, else its
1736
+ * next reply. A note of an unowned page (`undefined`) reaches nobody.
1737
+ */
1738
+ noteTo(conversationId, text) {
1739
+ if (conversationId === void 0) return;
1740
+ if (this.countOf(conversationId) === 0 && !this.usage.known(conversationId)) return;
1741
+ const n = clip(text, MAX_DIALOG_CHARS + 200);
1742
+ let delivered = false;
1743
+ for (const c of this.collectors) {
1744
+ if (c.conv !== conversationId) continue;
1745
+ c.notes.push(n);
1746
+ delivered = true;
1747
+ }
1748
+ if (delivered) return;
1749
+ const list = this.unreported.get(conversationId) ?? [];
1750
+ list.push(n);
1751
+ if (list.length > MAX_UNREPORTED) list.shift();
1752
+ this.unreported.set(conversationId, list);
1753
+ }
1754
+ /** The owner of a page, if it has one. */
1755
+ ownerOfPage(page) {
1756
+ return page === null || page === void 0 ? void 0 : this.owners.get(this.tabIdOf(page));
1757
+ }
608
1758
  /**
609
1759
  * Saves a download into `<workspace>/downloads` under its suggested name (sanitized, numbered
610
1760
  * when taken). A request in flight waits for it at most `downloadWaitMs`, then says it is still
@@ -612,12 +1762,14 @@ var BrowserSession = class {
612
1762
  * cancelled when together they pass `downloadMaxBytes`, so a page cannot fill the disk.
613
1763
  * Without a workspace the download is cancelled.
614
1764
  */
615
- onDownload(d) {
1765
+ onDownload(page, d) {
616
1766
  const shown = JSON.stringify(clip(d.suggestedFilename(), 300));
617
1767
  const workspace = this.workspace;
1768
+ const owner = this.ownerOfPage(page)?.owner;
1769
+ const note = (text) => this.noteTo(owner, text);
618
1770
  if (workspace === void 0) {
619
1771
  d.cancel().catch(() => void 0);
620
- this.note(
1772
+ note(
621
1773
  `The page started a download (${shown}), which was cancelled: the device has no workspace.`
622
1774
  );
623
1775
  return;
@@ -630,21 +1782,20 @@ var BrowserSession = class {
630
1782
  try {
631
1783
  const failure = await d.failure();
632
1784
  if (failure !== null) {
633
- if (failure !== "canceled") this.note(`The download of ${shown} failed: ${failure}.`);
1785
+ if (failure !== "canceled") note(`The download of ${shown} failed: ${failure}.`);
634
1786
  return;
635
1787
  }
636
1788
  const tmp = await d.path();
637
1789
  if (statSync(tmp).size > this.downloadMaxBytes) {
638
- this.note(
1790
+ note(
639
1791
  `The download of ${shown} was not saved: it is larger than ${this.downloadMaxBytes} bytes.`
640
1792
  );
641
1793
  return;
642
1794
  }
643
- target = this.downloadTarget(workspace, safeFileName(d.suggestedFilename()));
644
- await d.saveAs(target);
645
- this.note(`Downloaded ${shown} to ${target}.`);
1795
+ target = this.saveDownload(workspace, safeFileName(d.suggestedFilename()), tmp);
1796
+ note(`Downloaded ${shown} to ${target}.`);
646
1797
  } catch (e) {
647
- this.note(
1798
+ note(
648
1799
  `The download of ${shown} was not saved: ${e instanceof ActionError ? e.message : firstLine(e)}`
649
1800
  );
650
1801
  } finally {
@@ -654,10 +1805,64 @@ var BrowserSession = class {
654
1805
  entry.finished = true;
655
1806
  }
656
1807
  })();
657
- for (const c of this.collectors) c.downloads.push(entry);
1808
+ for (const c of this.collectors) if (c.conv === owner) c.downloads.push(entry);
658
1809
  }
659
- /** A free path in `<workspace>/downloads`, refusing a downloads directory that is a link. */
660
- downloadTarget(workspace, name) {
1810
+ /**
1811
+ * Copies a finished download from Playwright's private file into `<workspace>/downloads` and
1812
+ * returns where. The agent owns that directory, so the target is never written through a path
1813
+ * it could have swapped: each candidate is created exclusively without following a link
1814
+ * (`O_CREAT | O_EXCL | O_NOFOLLOW`), then checked to be the file the resolved path inside the
1815
+ * downloads directory names before any byte is written; a mismatch (a directory swapped for a
1816
+ * link meanwhile) writes nothing, removes the empty file it made (only while that name still
1817
+ * is the file it opened) and fails.
1818
+ */
1819
+ saveDownload(workspace, name, source) {
1820
+ const dir = this.downloadsDir(workspace);
1821
+ const dirStat = lstatSync(dir);
1822
+ const ext = extname(name);
1823
+ const stem = name.slice(0, name.length - ext.length);
1824
+ for (let i = 0; i < 1e3; i++) {
1825
+ const target = join(dir, i === 0 ? name : `${stem} (${i})${ext}`);
1826
+ if (this.reservedDownloads.has(target)) continue;
1827
+ let out;
1828
+ try {
1829
+ out = openSync(target, fsc.O_WRONLY | fsc.O_CREAT | fsc.O_EXCL | fsc.O_NOFOLLOW, 436);
1830
+ } catch (e) {
1831
+ if (e.code === "EEXIST") continue;
1832
+ throw e;
1833
+ }
1834
+ this.reservedDownloads.add(target);
1835
+ try {
1836
+ let real;
1837
+ try {
1838
+ real = realpathSync(target);
1839
+ } catch {
1840
+ real = "";
1841
+ }
1842
+ const opened = fstatSync(out);
1843
+ const placed = real !== "" && within(real, dir) && sameFile(opened, statSync(real));
1844
+ if (!placed || !sameFile(dirStat, lstatSync(dir))) {
1845
+ try {
1846
+ if (real !== "" && sameFile(opened, lstatSync(real)) && opened.size === 0)
1847
+ unlinkSync(real);
1848
+ } catch {
1849
+ }
1850
+ throw new ActionError(
1851
+ "failed",
1852
+ `${dir} changed while the download was saved; nothing was written. Retry the download.`
1853
+ );
1854
+ }
1855
+ copyInto(source, out);
1856
+ return target;
1857
+ } finally {
1858
+ closeSync(out);
1859
+ this.reservedDownloads.delete(target);
1860
+ }
1861
+ }
1862
+ throw new ActionError("failed", `No free name for ${name} in ${dir}; remove old downloads.`);
1863
+ }
1864
+ /** `<workspace>/downloads` resolved, refusing one that is a link or not a directory. */
1865
+ downloadsDir(workspace) {
661
1866
  const root = realpathSync(workspace);
662
1867
  const dir = join(root, "downloads");
663
1868
  mkdirSync(dir, { recursive: true });
@@ -668,14 +1873,7 @@ var BrowserSession = class {
668
1873
  `${dir} is not a plain directory in the workspace; remove it so downloads can be saved.`
669
1874
  );
670
1875
  }
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;
1876
+ return dir;
679
1877
  }
680
1878
  /**
681
1879
  * While downloads run, sums the bytes of Playwright's in-progress files and cancels every
@@ -706,7 +1904,8 @@ var BrowserSession = class {
706
1904
  if (bytes > this.downloadMaxBytes) {
707
1905
  for (const f of names) this.cancelledTmp.add(f);
708
1906
  for (const d of this.activeDownloads) {
709
- this.note(
1907
+ this.noteTo(
1908
+ this.ownerOfPage(d.page())?.owner,
710
1909
  `The download of ${JSON.stringify(clip(d.suggestedFilename(), 300))} was cancelled: downloads in progress passed ${this.downloadMaxBytes} bytes.`
711
1910
  );
712
1911
  d.cancel().catch(() => void 0);
@@ -717,29 +1916,69 @@ var BrowserSession = class {
717
1916
  this.pollDownloads();
718
1917
  }, DOWNLOAD_POLL_MS);
719
1918
  }
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;
1919
+ /**
1920
+ * An upload's bytes, read here and handed to Chromium from memory (never a path Chromium would
1921
+ * open later, after the agent could have swapped it for a link to the service's own files):
1922
+ * opened without following a final link, then accepted only when the resolved path lies in the
1923
+ * workspace and names the very file opened (an intermediate link swapped in either way shows as
1924
+ * another file), a regular file of at most {@link UPLOAD_MAX_BYTES}.
1925
+ */
1926
+ readUpload(path) {
1927
+ const root = this.uploadRoot();
1928
+ let fd;
728
1929
  try {
729
- real = realpathSync(path);
730
- } catch {
1930
+ fd = openSync(path, fsc.O_RDONLY | fsc.O_NOFOLLOW | fsc.O_NONBLOCK);
1931
+ } catch (e) {
1932
+ const code = e.code;
731
1933
  throw new ActionError(
732
1934
  "failed",
733
- `No file at ${path}; give the absolute path of a file in the workspace (${root}).`
1935
+ 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
1936
  );
735
1937
  }
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
- );
1938
+ try {
1939
+ const opened = fstatSync(fd);
1940
+ let real = "";
1941
+ try {
1942
+ real = realpathSync(path);
1943
+ } catch {
1944
+ real = "";
1945
+ }
1946
+ if (!within(real, root) || !sameFile(opened, statSync(real)))
1947
+ throw new ActionError(
1948
+ "failed",
1949
+ `Upload paths must be inside the workspace (${root}); copy the file there first.`
1950
+ );
1951
+ if (!opened.isFile())
1952
+ throw new ActionError("failed", `${path} is not a regular file; upload a file.`);
1953
+ if (opened.size > UPLOAD_MAX_BYTES)
1954
+ throw new ActionError(
1955
+ "failed",
1956
+ `${path} is larger than ${UPLOAD_MAX_BYTES} bytes, the most an upload takes.`
1957
+ );
1958
+ const buffer = Buffer.alloc(opened.size);
1959
+ let off = 0;
1960
+ while (off < buffer.length) {
1961
+ const n = readSync(fd, buffer, off, buffer.length - off, off);
1962
+ if (n === 0) break;
1963
+ off += n;
1964
+ }
1965
+ const name = basename(real);
1966
+ return {
1967
+ name,
1968
+ mimeType: UPLOAD_TYPES[extname(name).toLowerCase()] ?? "application/octet-stream",
1969
+ buffer: buffer.subarray(0, off)
1970
+ };
1971
+ } finally {
1972
+ closeSync(fd);
1973
+ }
1974
+ }
1975
+ /** The resolved workspace uploads come from. */
1976
+ uploadRoot() {
1977
+ const workspace = this.workspace;
1978
+ if (workspace === void 0) {
1979
+ throw new ActionError("failed", "Uploads are unavailable: the device has no workspace.");
741
1980
  }
742
- return real;
1981
+ return realpathSync(workspace);
743
1982
  }
744
1983
  /**
745
1984
  * The page a viewer opens once the refused host is allowed: the navigation's target for a
@@ -752,8 +1991,9 @@ var BrowserSession = class {
752
1991
  * Probes the proxy for the URL's host and reports it when refused; the viewers' `blocked`
753
1992
  * message carries `pageUrl` (default: the URL itself), the page to open once allowed.
754
1993
  */
755
- checkBlocked(rawUrl, pageUrl) {
1994
+ checkBlocked(page, rawUrl, pageUrl) {
756
1995
  const proxy = this.proxy;
1996
+ const owner = this.ownerOfPage(page);
757
1997
  if (proxy === void 0) return Promise.resolve(false);
758
1998
  let url;
759
1999
  try {
@@ -763,39 +2003,81 @@ var BrowserSession = class {
763
2003
  }
764
2004
  const host = url.hostname;
765
2005
  const port = Number(url.port || (url.protocol === "https:" ? 443 : 80));
766
- let probe = this.probes.get(host);
2006
+ const key2 = `${owner?.owner ?? ""}\0${host}`;
2007
+ let probe = this.probes.get(key2);
767
2008
  if (probe === void 0) {
768
- probe = proxyRefuses(proxy, host, port).then((refused) => {
769
- this.probes.delete(host);
770
- if (refused) {
771
- for (const c of this.collectors) c.blocked.add(host);
772
- this.emit({ type: "blocked", host, url: pageUrl ?? url.href });
2009
+ probe = proxyRefusal(proxy, host, port).then((layer) => {
2010
+ this.probes.delete(key2);
2011
+ if (layer !== null && owner !== void 0) {
2012
+ for (const c of this.collectors) if (c.conv === owner.owner) c.blocked.set(host, layer);
2013
+ if (layer === "device")
2014
+ this.emit({ type: "blocked", host, url: pageUrl ?? url.href, root: owner.root });
773
2015
  }
774
- return refused;
2016
+ return layer !== null;
775
2017
  });
776
- this.probes.set(host, probe);
2018
+ this.probes.set(key2, probe);
777
2019
  }
778
- for (const c of this.collectors) c.pending.push(probe);
2020
+ for (const c of this.collectors) if (c.conv === owner?.owner) c.pending.push(probe);
779
2021
  return probe;
780
2022
  }
781
- /** Runs `fn` one at a time with the other actions (`wait` runs beside them). */
782
- serial(fn) {
783
- const run = this.queue.then(fn, fn);
784
- this.queue = run.catch(() => void 0);
2023
+ /** `value`, or `fallback` when it takes longer than {@link PAGE_QUERY_MS} (never rejects). */
2024
+ async bounded(value, fallback) {
2025
+ let timer;
2026
+ try {
2027
+ return await Promise.race([
2028
+ value.catch(() => fallback),
2029
+ new Promise((r) => {
2030
+ timer = this.clock.schedule(() => r(fallback), PAGE_QUERY_MS);
2031
+ })
2032
+ ]);
2033
+ } finally {
2034
+ this.clock.cancel(timer);
2035
+ }
2036
+ }
2037
+ /**
2038
+ * The action queue a conversation's requests run in: one per conversation, so one
2039
+ * conversation's slow navigation does not stall another (ruling 7). Falling back to one
2040
+ * device-wide queue is returning a constant here.
2041
+ */
2042
+ queueKey(conversationId) {
2043
+ return conversationId;
2044
+ }
2045
+ /**
2046
+ * Runs `fn` one at a time with the conversation's other actions (`wait`, the tab list and adopt
2047
+ * run beside them).
2048
+ */
2049
+ serial(conversationId, fn) {
2050
+ const key2 = this.queueKey(conversationId);
2051
+ const run = (this.queues.get(key2) ?? Promise.resolve()).then(fn, fn);
2052
+ const tail = run.catch(() => void 0);
2053
+ this.queues.set(key2, tail);
2054
+ void tail.then(() => {
2055
+ if (this.queues.get(key2) === tail) this.queues.delete(key2);
2056
+ });
785
2057
  return run;
786
2058
  }
787
2059
  /**
788
- * Runs a tool request; never throws. `takenOver` is checked when a queued request leaves the
789
- * queue: a takeover that began while it waited refuses it. An action already running is left to
790
- * finish (stopping it halfway would leave the page in an unknown state).
2060
+ * Runs a tool request of its conversation; never throws. `takenOver` is checked when a queued
2061
+ * request leaves the queue: a takeover that began while it waited refuses it. An action already
2062
+ * running is left to finish (stopping it halfway would leave the page in an unknown state).
791
2063
  */
792
2064
  async run(req, opts = {}) {
793
- const late = this.unreported.splice(0);
794
- const c = { blocked: /* @__PURE__ */ new Set(), notes: [...late], pending: [], downloads: [] };
2065
+ const conv = req.conversationId;
2066
+ const lateOwn = this.unreported.get(conv) ?? [];
2067
+ this.unreported.delete(conv);
2068
+ const lateAll = this.unreportedAll.splice(0);
2069
+ const c = {
2070
+ conv,
2071
+ blocked: /* @__PURE__ */ new Map(),
2072
+ notes: [...lateAll, ...lateOwn],
2073
+ pending: [],
2074
+ downloads: []
2075
+ };
795
2076
  this.collectors.add(c);
796
2077
  let reply;
797
2078
  try {
798
- const out = await (req.op === "wait" ? this.exec(req) : this.serial(() => {
2079
+ const beside = req.op === "wait" || req.op === "tabs" && (req.action === "list" || req.action === "adopt");
2080
+ const out = await (beside ? this.exec(req) : this.serial(conv, () => {
799
2081
  if (opts.takenOver?.() === true)
800
2082
  throw new ActionError("taken_over", TAKEN_OVER_MESSAGE);
801
2083
  return this.exec(req);
@@ -803,12 +2085,21 @@ var BrowserSession = class {
803
2085
  await this.settleProbes(c);
804
2086
  await this.settleDownloads(c);
805
2087
  this.collectors.delete(c);
806
- const page = await this.activePage();
807
- const text = [...c.notes, ...out.text === void 0 ? [] : [out.text]].join("\n");
2088
+ const page = this.currentPage(conv);
2089
+ if (page !== void 0 && isActing(req)) {
2090
+ this.tabUsedAt.set(this.tabIdOf(page), this.clock.now());
2091
+ this.actedSeq.set(conv, ++this.actSeq);
2092
+ }
2093
+ const verifying = page === void 0 || req.op === "tabs" && (req.action === "list" || req.action === "adopt") ? false : await this.checkVerification(page, this.tabIdOf(page));
2094
+ const text = [
2095
+ ...verifying ? [VERIFICATION_NOTE] : [],
2096
+ ...c.notes,
2097
+ ...out.text === void 0 ? [] : [out.text]
2098
+ ].join("\n");
808
2099
  reply = {
809
2100
  ok: true,
810
- page: await this.pageInfo(page),
811
- blockedHosts: [...c.blocked],
2101
+ ...page === void 0 ? {} : { page: await this.pageInfo(page) },
2102
+ blockedHosts: blockedHostsOf(c),
812
2103
  ...text === "" ? {} : { text },
813
2104
  ...out.image === void 0 ? {} : { image: out.image }
814
2105
  };
@@ -821,10 +2112,12 @@ var BrowserSession = class {
821
2112
  }
822
2113
  if (c.blocked.size > 0 && code !== "no_such_ref" && code !== "taken_over") {
823
2114
  code = "blocked";
824
- message = `The device's network settings block ${[...c.blocked].join(", ")}.`;
2115
+ message = blockedMessage(blockedHostsOf(c));
825
2116
  }
826
- reply = { ok: false, error: code, message, blockedHosts: [...c.blocked] };
827
- this.unreported.unshift(...late);
2117
+ reply = { ok: false, error: code, message, blockedHosts: blockedHostsOf(c) };
2118
+ if (lateOwn.length > 0)
2119
+ this.unreported.set(conv, [...lateOwn, ...this.unreported.get(conv) ?? []]);
2120
+ this.unreportedAll.unshift(...lateAll);
828
2121
  } finally {
829
2122
  this.collectors.delete(c);
830
2123
  }
@@ -858,13 +2151,61 @@ var BrowserSession = class {
858
2151
  await Promise.allSettled(all);
859
2152
  }
860
2153
  }
861
- async pageInfo(page) {
862
- let title = "";
2154
+ /**
2155
+ * Finds the loaded page's icon and fetches it through the browser (the device's network rules
2156
+ * apply); a new address replaces the tab's icon, the same one is not fetched again. Any failure
2157
+ * leaves no icon (the panel's placeholder) and never affects the page.
2158
+ */
2159
+ async resolveFavicon(page, id) {
863
2160
  try {
864
- title = await page.title();
2161
+ const url = await iconUrlOf(page);
2162
+ if (this.pages.get(id) !== page) return;
2163
+ if (url === null) {
2164
+ if (this.favicons.delete(id)) this.emit({ type: "state" });
2165
+ return;
2166
+ }
2167
+ if (this.favicons.get(id)?.url === url) return;
2168
+ const cdp = await this.ctx.newCDPSession(page);
2169
+ let data = null;
2170
+ try {
2171
+ const bytes = await fetchIcon(cdp, url);
2172
+ data = bytes === null ? null : await iconForPanel(cdp, bytes);
2173
+ } finally {
2174
+ await cdp.detach().catch(() => void 0);
2175
+ }
2176
+ if (this.pages.get(id) !== page) return;
2177
+ this.favicons.set(id, { url, data });
2178
+ this.emit({ type: "state" });
865
2179
  } catch {
866
- title = this.titles.get(this.tabIdOf(page)) ?? "";
867
2180
  }
2181
+ }
2182
+ /**
2183
+ * Looks at the tab's page now and records or clears its verification blocker; true when it
2184
+ * shows a verification page.
2185
+ */
2186
+ async checkVerification(page, id) {
2187
+ if (id === "") return false;
2188
+ const blocked = await this.bounded(isVerificationPage(page, this.docStatus.get(id)), false);
2189
+ if (this.pages.get(id) !== page) return false;
2190
+ const before = this.blockers.get(id);
2191
+ if (blocked) {
2192
+ const url = clip(page.url(), MAX_URL_CHARS);
2193
+ if (before?.url !== url) {
2194
+ this.blockers.set(id, { kind: "verification", url });
2195
+ this.emit({ type: "state" });
2196
+ }
2197
+ } else if (before !== void 0) {
2198
+ this.blockers.delete(id);
2199
+ this.emit({ type: "state" });
2200
+ }
2201
+ return blocked;
2202
+ }
2203
+ async pageInfo(page) {
2204
+ const known = this.titles.get(this.tabIdOf(page)) ?? "";
2205
+ const title = await this.bounded(
2206
+ page.title().catch(() => known),
2207
+ known
2208
+ );
868
2209
  return {
869
2210
  url: clip(page.url(), MAX_URL_CHARS),
870
2211
  title: clip(title, MAX_TITLE_CHARS),
@@ -911,7 +2252,7 @@ var BrowserSession = class {
911
2252
  try {
912
2253
  const out = await fn();
913
2254
  if (navigating && !loaded2) {
914
- await page.waitForEvent("domcontentloaded", { timeout: NAVIGATION_TIMEOUT_MS }).catch(() => void 0);
2255
+ await page.waitForEvent("domcontentloaded", { timeout: this.navigationTimeoutMs }).catch(() => void 0);
915
2256
  }
916
2257
  return out;
917
2258
  } finally {
@@ -932,25 +2273,48 @@ var BrowserSession = class {
932
2273
  );
933
2274
  }
934
2275
  }
935
- markClick(x, y) {
936
- this.lastClick = { x, y, seq: ++this.clickSeq };
2276
+ markClick(page, x, y) {
2277
+ this.clicks.set(this.tabIdOf(page), { x, y, seq: ++this.clickSeq });
937
2278
  }
938
2279
  async goto(page, url) {
939
2280
  let res;
940
2281
  const download = page.waitForEvent("download", { timeout: ACTION_TIMEOUT_MS });
941
2282
  download.catch(() => void 0);
2283
+ const deadline = Date.now() + this.navigationTimeoutMs;
2284
+ const watch = new NavWatch(page, url, () => this.pendingNavs.get(page));
942
2285
  try {
943
- res = await page.goto(url, { waitUntil: "domcontentloaded" });
2286
+ res = await this.gotoPastNetworkChange(page, url, watch, deadline);
944
2287
  } catch (e) {
945
2288
  const msg = firstLine(e);
946
2289
  if (msg.includes("Download is starting")) {
947
2290
  await download.catch(() => void 0);
948
2291
  return;
949
2292
  }
950
- if (PROXY_FAILURE_RE.test(msg)) await this.checkBlocked(url);
951
- throw e;
2293
+ if (isTimeout(e)) throw await this.navigationTimedOut(page, url);
2294
+ if (!msg.includes("net::ERR_ABORTED")) throw await this.navigationFailed(page, e, url, msg);
2295
+ const out = await watch.follow(deadline);
2296
+ if (out.kind !== "loaded") {
2297
+ const status = await watch.emptyAnswer();
2298
+ if (status !== void 0)
2299
+ throw new ActionError(
2300
+ "failed",
2301
+ `${url} answered ${status} with no page to show; the tab shows ${page.url()}.`
2302
+ );
2303
+ }
2304
+ if (out.kind === "none") throw e;
2305
+ if (out.kind === "failed") {
2306
+ throw await this.navigationFailed(
2307
+ page,
2308
+ new Error(`${out.error} at ${out.url}`),
2309
+ out.url,
2310
+ out.error
2311
+ );
2312
+ }
2313
+ res = out.response;
2314
+ } finally {
2315
+ watch.dispose();
952
2316
  }
953
- if (res?.status() === 403 && await this.checkBlocked(res.url())) {
2317
+ if (res?.status() === 403 && await this.checkBlocked(page, res.url())) {
954
2318
  throw new ActionError(
955
2319
  "blocked",
956
2320
  `The device's network settings block ${new URL(res.url()).hostname}.`
@@ -958,19 +2322,182 @@ var BrowserSession = class {
958
2322
  }
959
2323
  await page.waitForLoadState("load", { timeout: LOAD_GRACE_MS }).catch(() => void 0);
960
2324
  }
2325
+ /**
2326
+ * `goto` past a change of the device's network (an interface came or went: Wi-Fi, a VPN, a
2327
+ * container network): Chromium answers net::ERR_NETWORK_CHANGED and may keep or restart the
2328
+ * navigation itself, so it is followed first (like one another navigation took over) and run
2329
+ * again only when none goes on, at most {@link NETWORK_CHANGED_ATTEMPTS} times, within the
2330
+ * navigation's deadline.
2331
+ */
2332
+ async gotoPastNetworkChange(page, url, watch, deadline) {
2333
+ for (let attempt = 1; ; attempt++) {
2334
+ try {
2335
+ return await this.gotoPastLateErrorPage(page, url, watch, deadline);
2336
+ } catch (e) {
2337
+ if (!firstLine(e).includes("net::ERR_NETWORK_CHANGED")) throw e;
2338
+ const out = await watch.follow(deadline);
2339
+ if (out.kind === "loaded") return out.response;
2340
+ if (out.kind === "failed" && !out.error.includes("ERR_NETWORK_CHANGED"))
2341
+ throw new Error(`${out.error} at ${out.url}`);
2342
+ if (attempt >= NETWORK_CHANGED_ATTEMPTS || Date.now() >= deadline) throw e;
2343
+ }
2344
+ }
2345
+ }
2346
+ /**
2347
+ * `page.goto`, past the late error page of the tab's previous failed or stopped navigation:
2348
+ * Chromium can commit that page after Playwright reported the failure (the Linux full build),
2349
+ * and its commit interrupts a navigation started meanwhile. Then this navigation is followed
2350
+ * when it went on in Chromium, and otherwise started once more (the error page is in now),
2351
+ * within the navigation's own deadline.
2352
+ */
2353
+ async gotoPastLateErrorPage(page, url, watch, deadline) {
2354
+ try {
2355
+ return await page.goto(url, { waitUntil: "domcontentloaded" });
2356
+ } catch (e) {
2357
+ if (!ERROR_PAGE_INTERRUPT_RE.test(firstLine(e))) throw e;
2358
+ const out = await watch.follow(deadline);
2359
+ if (out.kind === "loaded") return out.response;
2360
+ if (out.kind === "failed" && !out.error.includes("net::ERR_ABORTED"))
2361
+ throw new Error(`${out.error} at ${out.url}`);
2362
+ return page.goto(url, {
2363
+ waitUntil: "domcontentloaded",
2364
+ timeout: Math.max(1, deadline - Date.now())
2365
+ });
2366
+ }
2367
+ }
2368
+ /**
2369
+ * The error of a navigation that failed with Chromium's net error `error`: a host the proxy
2370
+ * refuses is reported as blocked (`run` turns `original` into the blocked reply); any other net
2371
+ * error is `unreachable`, saying what the device's network answered when it went through it.
2372
+ */
2373
+ async navigationFailed(page, original, url, error) {
2374
+ const net = /net::(ERR_[A-Z_]+)/.exec(error)?.[1];
2375
+ if (net === void 0 || net === "ERR_ABORTED") return original;
2376
+ await this.errorPageCommitted(page);
2377
+ const proxied = PROXY_FAILURE_RE.test(error);
2378
+ if (proxied && await this.checkBlocked(page, url)) return original;
2379
+ if (proxied || NETWORK_ERROR_RE.test(net)) {
2380
+ const verdict = await this.networkVerdict(url);
2381
+ if (verdict?.kind === "proxy_down")
2382
+ return new ActionError(
2383
+ "network_unavailable",
2384
+ `${url} could not be loaded (net::${net}): ${verdict.text}`
2385
+ );
2386
+ if (verdict !== void 0 && verdict.text !== "")
2387
+ return new ActionError(
2388
+ "unreachable",
2389
+ `${url} could not be loaded (net::${net}): ${verdict.text}`
2390
+ );
2391
+ }
2392
+ const meaning = NET_ERROR_MEANINGS[net];
2393
+ return new ActionError(
2394
+ "unreachable",
2395
+ `${url} could not be loaded (net::${net})${meaning === void 0 ? "." : `: ${meaning}.`}`
2396
+ );
2397
+ }
2398
+ /**
2399
+ * Waits (at most {@link ERROR_PAGE_WAIT_MS}) for the error page of the main frame's failed
2400
+ * navigation: Chromium commits it after Playwright reported the failure (the Linux full build
2401
+ * shows it), and a navigation started before that commit is interrupted by it.
2402
+ */
2403
+ async errorPageCommitted(page) {
2404
+ if (page.isClosed() || page.mainFrame().url().startsWith("chrome-error:")) return;
2405
+ await page.waitForEvent("framenavigated", {
2406
+ predicate: (f) => f === page.mainFrame() && f.url().startsWith("chrome-error:"),
2407
+ timeout: ERROR_PAGE_WAIT_MS
2408
+ }).catch(() => void 0);
2409
+ }
2410
+ /**
2411
+ * The error of a navigation that took longer than its time limit. The navigation is stopped
2412
+ * first (a navigation left in flight keeps the page's scripts and snapshots waiting for a
2413
+ * document that never comes), so the tab goes back to the page it showed and the next request
2414
+ * works on it; the message says what the device's network answered for the host.
2415
+ */
2416
+ async navigationTimedOut(page, url) {
2417
+ await this.stopNavigation(page);
2418
+ const seconds = Math.round(this.navigationTimeoutMs / 1e3);
2419
+ const verdict = await this.networkVerdict(url, true);
2420
+ const detail = verdict === void 0 || verdict.text === "" ? "no page came in that time." : verdict.text;
2421
+ const now = page.isClosed() ? "" : ` The navigation was stopped; the tab shows ${page.url()}.`;
2422
+ return new ActionError(
2423
+ verdict?.kind === "proxy_down" ? "network_unavailable" : "unreachable",
2424
+ `${url} did not load within ${seconds} s: ${detail}${now}`
2425
+ );
2426
+ }
2427
+ /** Stops the page's navigation in flight (Chromium's stop button); never throws. */
2428
+ async stopNavigation(page) {
2429
+ if (page.isClosed()) return;
2430
+ try {
2431
+ const cdp = await this.ctx.newCDPSession(page);
2432
+ try {
2433
+ await cdp.send("Page.stopLoading");
2434
+ } finally {
2435
+ await cdp.detach().catch(() => void 0);
2436
+ }
2437
+ } catch {
2438
+ }
2439
+ this.pendingNavs.delete(page);
2440
+ const id = this.ids.get(page);
2441
+ if (id !== void 0 && this.loadingTabs.delete(id)) this.emit({ type: "state" });
2442
+ }
2443
+ /**
2444
+ * What the device's proxy answers for the URL's host, and as a sentence (undefined without a
2445
+ * proxy). `timedOut`: the navigation got no page in time.
2446
+ */
2447
+ async networkVerdict(rawUrl, timedOut = false) {
2448
+ if (this.proxy === void 0) return void 0;
2449
+ let url;
2450
+ try {
2451
+ url = new URL(rawUrl);
2452
+ } catch {
2453
+ return void 0;
2454
+ }
2455
+ const host = url.hostname;
2456
+ const port = Number(url.port || (url.protocol === "https:" ? 443 : 80));
2457
+ const answer = await probeProxy(this.proxy, host, port);
2458
+ return { kind: answer.verdict, text: this.verdictText(answer, host, port, timedOut) };
2459
+ }
2460
+ /** The sentence for a proxy's {@link ProxyAnswer} ("" when it says nothing). */
2461
+ verdictText(answer, host, port, timedOut) {
2462
+ switch (answer.verdict) {
2463
+ case "proxy_down":
2464
+ return "the device's network proxy is not reachable, so no page loads on the device right now; this is not a problem of the address.";
2465
+ case "unreachable":
2466
+ return `the device's network could not connect to ${host}:${port} (the name did not resolve, or the host refused or did not answer the connection).`;
2467
+ case "no_answer":
2468
+ return `the device's network got no answer from ${host}:${port}.`;
2469
+ case "connected":
2470
+ return timedOut ? `${host} accepted the connection through the device's network but sent no page in that time.` : `the device's network connects to ${host}:${port}, but the connection failed.`;
2471
+ case "refused":
2472
+ return refusalLayer(answer.reason) === "address" ? `${host} resolves to a private or local address on the device, which the browser never reaches from the sandbox.` : `the device's network settings block ${host}.`;
2473
+ default:
2474
+ return "";
2475
+ }
2476
+ }
961
2477
  async exec(req) {
2478
+ const conv = req.conversationId;
2479
+ const root = req.rootConversationId;
2480
+ const activePage = () => this.pageFor(conv, root);
962
2481
  switch (req.op) {
963
2482
  case "navigate": {
964
- const page = await this.activePage();
2483
+ const page = await activePage();
965
2484
  if (req.url !== void 0) {
966
2485
  await this.goto(page, normalizeUrl(req.url));
967
2486
  } else if (req.action === "back" || req.action === "forward") {
968
- const r = await (req.action === "back" ? page.goBack() : page.goForward());
2487
+ const r = await (req.action === "back" ? page.goBack() : page.goForward()).catch(
2488
+ async (e) => {
2489
+ if (isTimeout(e)) throw await this.navigationTimedOut(page, page.url());
2490
+ throw e;
2491
+ }
2492
+ );
969
2493
  if (r === null && page.url() === "about:blank") {
970
2494
  return { text: `No ${req.action === "back" ? "earlier" : "later"} page in this tab.` };
971
2495
  }
972
2496
  } else if (req.action === "reload") {
973
- await page.reload({ waitUntil: "domcontentloaded" });
2497
+ await page.reload({ waitUntil: "domcontentloaded" }).catch(async (e) => {
2498
+ if (isTimeout(e)) throw await this.navigationTimedOut(page, page.url());
2499
+ throw e;
2500
+ });
974
2501
  } else {
975
2502
  throw new ActionError(
976
2503
  "failed",
@@ -982,40 +2509,40 @@ var BrowserSession = class {
982
2509
  case "tabs":
983
2510
  return this.tabsOp(req);
984
2511
  case "snapshot":
985
- return { text: await takeSnapshot(await this.activePage()) };
2512
+ return { text: await takeSnapshot(await activePage()) };
986
2513
  case "click":
987
2514
  case "hover": {
988
- const page = await this.activePage();
2515
+ const page = await activePage();
989
2516
  const loc = await this.locate(page, req.ref);
990
2517
  if (req.op === "hover") {
991
2518
  await loc.hover();
992
2519
  return {};
993
2520
  }
994
2521
  const at = await this.centerOf(loc);
995
- if (at !== void 0) this.markClick(at.x, at.y);
2522
+ if (at !== void 0) this.markClick(page, at.x, at.y);
996
2523
  await this.settled(page, () => loc.click());
997
2524
  return {};
998
2525
  }
999
2526
  case "type": {
1000
- const page = await this.activePage();
2527
+ const page = await activePage();
1001
2528
  const loc = await this.locate(page, req.ref);
1002
2529
  await loc.fill(req.text);
1003
2530
  if (req.submit === true) await this.settled(page, () => loc.press("Enter"));
1004
2531
  return {};
1005
2532
  }
1006
2533
  case "select": {
1007
- const page = await this.activePage();
2534
+ const page = await activePage();
1008
2535
  const loc = await this.locate(page, req.ref);
1009
2536
  const chosen = await this.settled(page, () => loc.selectOption(req.values));
1010
2537
  return { text: `Selected ${JSON.stringify(chosen)}.` };
1011
2538
  }
1012
2539
  case "press": {
1013
- const page = await this.activePage();
2540
+ const page = await activePage();
1014
2541
  await this.settled(page, () => page.keyboard.press(req.key));
1015
2542
  return {};
1016
2543
  }
1017
2544
  case "scroll": {
1018
- const page = await this.activePage();
2545
+ const page = await activePage();
1019
2546
  if (req.ref !== void 0) {
1020
2547
  const loc = await this.locate(page, req.ref);
1021
2548
  await loc.scrollIntoViewIfNeeded();
@@ -1029,25 +2556,25 @@ var BrowserSession = class {
1029
2556
  return {};
1030
2557
  }
1031
2558
  case "upload": {
1032
- const page = await this.activePage();
1033
- const path = this.uploadPath(req.path);
2559
+ const page = await activePage();
2560
+ const file = this.readUpload(req.path);
1034
2561
  const loc = await this.locate(page, req.ref);
1035
- await loc.setInputFiles(path);
2562
+ await loc.setInputFiles(file);
1036
2563
  return {};
1037
2564
  }
1038
2565
  case "click_at":
1039
2566
  case "type_at": {
1040
- const page = await this.activePage();
2567
+ const page = await activePage();
1041
2568
  this.checkPoint(req.x, req.y);
1042
- this.markClick(Math.round(req.x), Math.round(req.y));
2569
+ this.markClick(page, Math.round(req.x), Math.round(req.y));
1043
2570
  await this.settled(page, () => page.mouse.click(req.x, req.y));
1044
2571
  if (req.op === "type_at") await page.keyboard.type(req.text);
1045
2572
  return {};
1046
2573
  }
1047
2574
  case "wait":
1048
- return this.waitOp(req);
2575
+ return this.waitOp(req, this.currentPage(conv));
1049
2576
  case "screenshot": {
1050
- const page = await this.activePage();
2577
+ const page = await activePage();
1051
2578
  const maxBytes = Math.min(MAX_SCREENSHOT_BYTES, Math.floor(req.maxBytes));
1052
2579
  if (!(maxBytes > 0))
1053
2580
  throw new ActionError("failed", "screenshot needs a positive maxBytes.");
@@ -1078,56 +2605,79 @@ var BrowserSession = class {
1078
2605
  );
1079
2606
  }
1080
2607
  async tabsOp(req) {
2608
+ const conv = req.conversationId;
2609
+ const root = req.rootConversationId;
1081
2610
  switch (req.action) {
1082
- case "list": {
1083
- await this.activePage();
1084
- const lines = await Promise.all(
1085
- [...this.pages.entries()].map(async ([id, p]) => {
1086
- const info = await this.pageInfo(p);
1087
- return `${id}${id === this.active ? " (active)" : ""}: ${info.title || "(no title)"} ${info.url}`;
1088
- })
1089
- );
1090
- return { text: lines.join("\n") };
1091
- }
2611
+ case "list":
2612
+ return { text: await this.listText(conv, root) };
1092
2613
  case "open": {
1093
- const page = await this.openTab();
2614
+ const page = this.countOf(conv) === 0 ? await this.pageFor(conv, root) : await this.openTab(conv, root);
1094
2615
  if (req.url !== void 0) await this.goto(page, normalizeUrl(req.url));
1095
2616
  return {};
1096
2617
  }
1097
2618
  case "switch": {
1098
- const page = this.tabById(req.tabId);
1099
- this.active = req.tabId;
1100
- await page.bringToFront().catch(() => void 0);
1101
- this.emit({ type: "active" });
2619
+ this.ownTab(conv, req.tabId);
2620
+ this.setActive(conv, req.tabId);
1102
2621
  return {};
1103
2622
  }
1104
2623
  case "close": {
1105
- const page = this.tabById(req.tabId);
2624
+ const page = this.ownTab(conv, req.tabId);
1106
2625
  await page.close();
1107
- await this.activePage();
2626
+ return {};
2627
+ }
2628
+ case "adopt": {
2629
+ const id = req.tabId;
2630
+ const result = this.adopt(conv, root, this.tabIdOf(this.tabById(id)));
2631
+ if (result === "in_use") throw new ActionError("failed", tabInUse(id ?? ""));
2632
+ if (result === "cap") throw new ActionError("failed", CONVERSATION_CAP_MESSAGE);
1108
2633
  return {};
1109
2634
  }
1110
2635
  }
1111
- throw new ActionError("failed", "tabs needs an action: list, open, switch or close.");
2636
+ throw new ActionError("failed", "tabs needs an action: list, open, switch, close or adopt.");
1112
2637
  }
1113
- /** Opens a blank tab and makes it active. */
1114
- async openTab() {
1115
- if (this.pages.size >= MAX_TABS) {
1116
- throw new ActionError(
1117
- "failed",
1118
- `The browser has ${MAX_TABS} tabs open, the most it keeps; close one first.`
1119
- );
1120
- }
1121
- const page = await this.ctx.newPage();
1122
- this.track(page);
1123
- this.active = this.ids.get(page);
1124
- this.emit({ type: "active" });
1125
- this.emit({ type: "state" });
2638
+ /** The conversation's own tab `tabId`; another conversation's is refused with what to do. */
2639
+ ownTab(conversationId, tabId) {
2640
+ const page = this.tabById(tabId);
2641
+ if (this.owners.get(tabId)?.owner !== conversationId)
2642
+ throw new ActionError("failed", notYourTab(tabId));
1126
2643
  return page;
1127
2644
  }
2645
+ /**
2646
+ * The tab list of a conversation: its own tabs, then its tree's other tabs, then other trees'
2647
+ * tabs (unowned ones too, but not a blank start tab), with ids, titles clipped to
2648
+ * OTHER_TITLE_CHARS and URLs without query or fragment outside its own; no conversation ids.
2649
+ */
2650
+ async listText(conversationId, root) {
2651
+ const own = [];
2652
+ const tree = [];
2653
+ const device = [];
2654
+ for (const [id, p] of this.live()) {
2655
+ const o = this.owners.get(id);
2656
+ if (o?.owner === conversationId) {
2657
+ const info = await this.pageInfo(p);
2658
+ const active = this.activeOf.get(conversationId) === id ? " (active)" : "";
2659
+ own.push(`${id}${active}: ${info.title || "(no title)"} ${info.url}`);
2660
+ continue;
2661
+ }
2662
+ if (isStartBlank({ owner: o?.owner, url: p.url() })) continue;
2663
+ const title = clip(this.titles.get(id) ?? "", OTHER_TITLE_CHARS) || "(no title)";
2664
+ const line = `${id}: ${title} ${bareUrl(clip(p.url(), MAX_URL_CHARS))}`;
2665
+ if (o !== void 0 && o.root === root) tree.push(line);
2666
+ else device.push(line);
2667
+ }
2668
+ const lines = [...own];
2669
+ if (tree.length > 0) lines.push("Tabs of other conversations in this task:", ...tree);
2670
+ if (device.length > 0) lines.push("Tabs of other conversations on this device:", ...device);
2671
+ if (tree.length + device.length > 0)
2672
+ lines.push(
2673
+ "To use another conversation's tab, call browser_tabs with action adopt and its tabId."
2674
+ );
2675
+ if (lines.length === 0) return "No browser tabs are open.";
2676
+ return lines.join("\n");
2677
+ }
1128
2678
  tabById(tabId) {
1129
- const page = tabId === void 0 ? void 0 : this.pages.get(tabId);
1130
- if (page === void 0 || page.isClosed()) {
2679
+ const page = this.pageById(tabId);
2680
+ if (page === void 0) {
1131
2681
  throw new ActionError(
1132
2682
  "failed",
1133
2683
  `No tab ${JSON.stringify(tabId ?? "")}; list the tabs to see their ids.`
@@ -1135,18 +2685,13 @@ var BrowserSession = class {
1135
2685
  }
1136
2686
  return page;
1137
2687
  }
1138
- /** Makes a tab active (a viewer's tab switch). */
1139
- async switchTo(tabId) {
1140
- const page = this.tabById(tabId);
1141
- this.active = tabId;
1142
- await page.bringToFront().catch(() => void 0);
1143
- this.emit({ type: "active" });
1144
- this.emit({ type: "state" });
2688
+ /** Brings a tab to the front of the window (only a viewer in control decides what is front). */
2689
+ async bringToFront(tabId) {
2690
+ await this.pageById(tabId)?.bringToFront().catch(() => void 0);
1145
2691
  }
1146
- /** Navigates the active tab for a viewer (address bar, back, forward, reload); never throws. */
1147
- async viewerNav(nav) {
2692
+ /** Navigates a tab for a viewer (address bar, back, forward, reload); never throws. */
2693
+ async viewerNav(page, nav) {
1148
2694
  try {
1149
- const page = await this.activePage();
1150
2695
  if (nav.url !== void 0) await this.goto(page, normalizeUrl(nav.url));
1151
2696
  else if (nav.action === "back") await page.goBack();
1152
2697
  else if (nav.action === "forward") await page.goForward();
@@ -1154,10 +2699,15 @@ var BrowserSession = class {
1154
2699
  } catch {
1155
2700
  }
1156
2701
  }
1157
- async waitOp(req) {
2702
+ async waitOp(req, page) {
1158
2703
  const asked = Number(req.timeoutMs);
1159
2704
  const timeout = Number.isFinite(asked) ? Math.max(0, Math.min(MAX_WAIT_MS, Math.floor(asked))) : DEFAULT_WAIT_MS;
1160
- const page = await this.activePage();
2705
+ if (page === void 0) {
2706
+ if (req.text !== void 0 || req.ref !== void 0 || req.navigation === true)
2707
+ throw new ActionError("failed", NO_TAB_TO_WAIT_ON);
2708
+ await new Promise((r) => this.clock.schedule(r, timeout));
2709
+ return {};
2710
+ }
1161
2711
  if (req.text !== void 0) {
1162
2712
  await page.getByText(req.text).first().waitFor({ state: "visible", timeout }).catch((e) => {
1163
2713
  throw e instanceof Error && e.name === "TimeoutError" ? new ActionError(
@@ -1198,15 +2748,33 @@ var BrowserSession = class {
1198
2748
  };
1199
2749
 
1200
2750
  // daemon/chromium.ts
1201
- import { existsSync, readFileSync } from "node:fs";
2751
+ import {
2752
+ accessSync,
2753
+ constants,
2754
+ existsSync,
2755
+ lstatSync as lstatSync2,
2756
+ readdirSync as readdirSync2,
2757
+ readFileSync,
2758
+ writeFileSync
2759
+ } from "node:fs";
1202
2760
  import { createRequire } from "node:module";
1203
- import { dirname, join as join2 } from "node:path";
2761
+ import { dirname, isAbsolute, join as join2, relative } from "node:path";
1204
2762
  import { fileURLToPath } from "node:url";
2763
+ var SERVICE_MACH_ENV = DEVICE_SERVICE_MACH_ENV;
2764
+ var HEADLESS_SHELL_NOTE = "The browser runs as a headless shell, which sites flag as a bot more often: the machine's capybara-device predates the full browser; ask the user to update capybara-device on that machine.";
2765
+ function chromiumBuild(platform, env = process.env) {
2766
+ if (platform !== "darwin") return "chromium";
2767
+ return env[SERVICE_MACH_ENV] === DEVICE_SERVICE_MACH_CHROMIUM ? "chromium" : "chromium-headless-shell";
2768
+ }
2769
+ var BUILD_DIR = {
2770
+ chromium: "chromium",
2771
+ "chromium-headless-shell": "chromium_headless_shell"
2772
+ };
1205
2773
  function envValue(env, name) {
1206
2774
  const v = env[name] ?? env[name.toLowerCase()];
1207
2775
  return v === void 0 || v === "" ? void 0 : v;
1208
2776
  }
1209
- function headlessShellRevision() {
2777
+ function browserRelease(build) {
1210
2778
  const candidates = [new URL("./vendor/playwright-core/browsers.json", import.meta.url)];
1211
2779
  try {
1212
2780
  const pkg = createRequire(import.meta.url).resolve("playwright-core/package.json");
@@ -1216,13 +2784,25 @@ function headlessShellRevision() {
1216
2784
  for (const file of candidates) {
1217
2785
  try {
1218
2786
  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;
2787
+ const b = json.browsers?.find((x) => x.name === build);
2788
+ if (typeof b?.revision === "string" && b.revision !== "")
2789
+ return {
2790
+ revision: b.revision,
2791
+ version: typeof b.browserVersion === "string" ? b.browserVersion : ""
2792
+ };
1221
2793
  } catch {
1222
2794
  }
1223
2795
  }
1224
2796
  return void 0;
1225
2797
  }
2798
+ function browserRevision(build) {
2799
+ return browserRelease(build)?.revision;
2800
+ }
2801
+ function chromeUserAgent(platform, version) {
2802
+ const major = /^\d+/.exec(version)?.[0] ?? "0";
2803
+ const os = platform === "darwin" ? "Macintosh; Intel Mac OS X 10_15_7" : platform === "win32" ? "Windows NT 10.0; Win64; x64" : "X11; Linux x86_64";
2804
+ return `Mozilla/5.0 (${os}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/${major}.0.0.0 Safari/537.36`;
2805
+ }
1226
2806
  function playwrightDownloadHosts(env) {
1227
2807
  const custom = envValue(env, "PLAYWRIGHT_CHROMIUM_DOWNLOAD_HOST") ?? envValue(env, "PLAYWRIGHT_DOWNLOAD_HOST");
1228
2808
  if (custom !== void 0) {
@@ -1232,17 +2812,107 @@ function playwrightDownloadHosts(env) {
1232
2812
  return [];
1233
2813
  }
1234
2814
  }
1235
- return ["cdn.playwright.dev", "playwright.download.prss.microsoft.com"];
2815
+ return ["cdn.playwright.dev", "playwright.download.prss.microsoft.com", "storage.googleapis.com"];
2816
+ }
2817
+ var MAX_REVISION_SKEW = 10;
2818
+ function shippedRevisionNote(dir, revision) {
2819
+ 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.`;
2820
+ }
2821
+ 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).";
2822
+ var SERVICE_INSTALL_ENV = "CAPYBARA_SERVICE_INSTALL";
2823
+ var SERVICE_INSTALL_SEAL = ".sealed";
2824
+ var BrowserInstalledError = class extends Error {
2825
+ constructor() {
2826
+ super("The browser was installed; the browser service restarts to run it read only.");
2827
+ this.name = "BrowserInstalledError";
2828
+ }
2829
+ };
2830
+ function inside(dir, root) {
2831
+ const rel = relative(root, dir);
2832
+ return rel === "" || !rel.startsWith("..") && !isAbsolute(rel);
2833
+ }
2834
+ function readOnlyForUs(dir) {
2835
+ try {
2836
+ accessSync(dir, constants.W_OK);
2837
+ return false;
2838
+ } catch {
2839
+ return true;
2840
+ }
1236
2841
  }
1237
- function browsersPathFor(stateDir, env, revision) {
2842
+ function browsersPathFor(stateDir, env, revision, build) {
2843
+ const install = envValue(env, SERVICE_INSTALL_ENV);
2844
+ if (install !== void 0 && isAbsolute(install)) {
2845
+ let sealed = false;
2846
+ try {
2847
+ sealed = lstatSync2(join2(install, SERVICE_INSTALL_SEAL)).isFile();
2848
+ } catch {
2849
+ sealed = false;
2850
+ }
2851
+ return { browsersPath: install, install: { sealed } };
2852
+ }
1238
2853
  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");
2854
+ const workspace = envValue(env, "CAPYBARA_SERVICE_WORKSPACE");
2855
+ if (cache !== void 0 && isAbsolute(cache) && (workspace === void 0 || !inside(cache, workspace)) && readOnlyForUs(cache)) {
2856
+ if (revision !== void 0 && existsSync(join2(cache, `${BUILD_DIR[build]}-${revision}`)))
2857
+ return { browsersPath: cache, shipped: true };
2858
+ const near = shippedRevisions(cache, build).filter(
2859
+ (d) => revision !== void 0 && Math.abs(Number(d.slice(BUILD_DIR[build].length + 1)) - Number(revision)) <= MAX_REVISION_SKEW
2860
+ );
2861
+ const newest = near.at(-1);
2862
+ if (newest !== void 0) return { browsersPath: cache, shipped: true, shippedDir: newest };
2863
+ }
2864
+ return { browsersPath: join2(stateDir, "browsers"), unavailable: BROWSER_UNAVAILABLE_MESSAGE };
2865
+ }
2866
+ function shippedRevisions(cache, build) {
2867
+ const re = new RegExp(`^${BUILD_DIR[build]}-(\\d+)$`);
2868
+ let names;
2869
+ try {
2870
+ names = readdirSync2(cache);
2871
+ } catch {
2872
+ return [];
2873
+ }
2874
+ 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);
1242
2875
  }
1243
- function chromiumLaunchPlan(opts, revision = headlessShellRevision()) {
1244
- const args = ["--headless", "--use-mock-keychain"];
1245
- if (opts.platform === "darwin") args.push("--single-process");
2876
+ var PLAYWRIGHT_DISABLED_FEATURES = [
2877
+ "AvoidUnnecessaryBeforeUnloadCheckSync",
2878
+ "DestroyProfileOnBrowserClose",
2879
+ "HttpsUpgrades",
2880
+ "HttpsFirstBalancedModeAutoEnable",
2881
+ "LensOverlay",
2882
+ "MediaRouter",
2883
+ "PaintHolding",
2884
+ "ThirdPartyStoragePartitioning",
2885
+ "AvoidCorsURLLoaderRestartOnRedirect",
2886
+ "TcpPortRandomizationWin",
2887
+ "OptimizationHints",
2888
+ "NetworkTimeServiceQuerying",
2889
+ "AimEnabled",
2890
+ "PreconnectToSearch",
2891
+ "msForceBrowserSignIn",
2892
+ "msEdgeUpdateLaunchServicesPreferredVersion"
2893
+ ];
2894
+ var DISABLED_FEATURES = [...PLAYWRIGHT_DISABLED_FEATURES, "AcceptCHFrame"];
2895
+ function chromiumLaunchPlan(opts, release = browserRelease(
2896
+ chromiumBuild(opts.platform, opts.env)
2897
+ )) {
2898
+ const build = chromiumBuild(opts.platform, opts.env);
2899
+ const args = [
2900
+ "--headless",
2901
+ "--use-mock-keychain",
2902
+ `--window-size=${VIEWPORT.width},${VIEWPORT.height}`,
2903
+ `--user-agent=${chromeUserAgent(opts.platform, release?.version ?? "")}`,
2904
+ `--disable-features=${DISABLED_FEATURES.join(",")}`,
2905
+ // Chrome reloads a network error page by itself (after 1 s, then backing off): that reload
2906
+ // aborts the agent's next navigation in the tab and asks the proxy for the failed host again
2907
+ "--disable-auto-reload"
2908
+ ];
2909
+ if (build === "chromium-headless-shell") args.push("--single-process");
2910
+ let env;
2911
+ if (opts.platform === "darwin") {
2912
+ args.push("--disable-crash-reporter", "--disable-breakpad");
2913
+ const tmp = envValue(opts.env, "TMPDIR");
2914
+ if (tmp !== void 0) env = { MAC_CHROMIUM_TMPDIR: tmp };
2915
+ }
1246
2916
  const proxy = envValue(opts.env, "HTTPS_PROXY") ?? envValue(opts.env, "HTTP_PROXY");
1247
2917
  let proxyAuth;
1248
2918
  if (proxy !== void 0) {
@@ -1267,7 +2937,9 @@ function chromiumLaunchPlan(opts, revision = headlessShellRevision()) {
1267
2937
  }
1268
2938
  }
1269
2939
  return {
1270
- browsersPath: opts.browsersPath ?? browsersPathFor(opts.stateDir, opts.env, revision),
2940
+ ...opts.browsersPath === void 0 ? browsersPathFor(opts.stateDir, opts.env, release?.revision, build) : { browsersPath: opts.browsersPath },
2941
+ build,
2942
+ ...env === void 0 ? {} : { env },
1271
2943
  profileDir: join2(opts.stateDir, "profile"),
1272
2944
  downloadsTmp: join2(opts.stateDir, "downloads-tmp"),
1273
2945
  args,
@@ -1290,24 +2962,44 @@ async function loadPlaywright(browsersPath) {
1290
2962
  loaded = { browsersPath, pw: pw.default ?? pw };
1291
2963
  return loaded.pw;
1292
2964
  }
1293
- async function ensureChromium(browsersPath) {
2965
+ async function registryBrowser(browsersPath, build) {
1294
2966
  await loadPlaywright(browsersPath);
1295
2967
  const mod = await import("./vendor/playwright-core/lib/coreBundle.js");
1296
2968
  const registry = (mod.registry ?? mod.default?.registry)?.registry;
1297
2969
  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");
1300
- const path = exe.executablePath();
1301
- if (path !== void 0 && existsSync(path)) return path;
1302
- await registry.install([exe], { gc: false });
1303
- const installed = exe.executablePath();
1304
- if (installed === void 0 || !existsSync(installed)) {
2970
+ const exe = registry.findExecutable(build);
2971
+ if (exe === void 0) throw new Error(`playwright-core does not know ${build}`);
2972
+ const executablePath = exe.executablePath();
2973
+ if (executablePath === void 0 || exe.directory === void 0)
2974
+ throw new Error(`playwright-core has no ${build} for this platform`);
2975
+ return { registry, exe, executablePath, directory: exe.directory };
2976
+ }
2977
+ async function ensureChromium(browsersPath, install = true, build = chromiumBuild(process.platform), fresh = false) {
2978
+ const { registry, exe, executablePath, directory } = await registryBrowser(browsersPath, build);
2979
+ const marked = existsSync(join2(directory, "INSTALLATION_COMPLETE"));
2980
+ if (!fresh && marked && existsSync(executablePath)) return executablePath;
2981
+ if (!install)
2982
+ throw new Error(
2983
+ `the browser in ${browsersPath} is incomplete and read only for the browser service; delete the device and create it again`
2984
+ );
2985
+ await registry.install([exe], { gc: false, force: marked || fresh });
2986
+ if (!existsSync(executablePath)) {
1305
2987
  throw new Error("the Chromium download finished without an executable");
1306
2988
  }
1307
- return installed;
2989
+ return executablePath;
1308
2990
  }
1309
2991
  async function launchChromium(plan) {
1310
- const executablePath = await ensureChromium(plan.browsersPath);
2992
+ if (plan.unavailable !== void 0) throw new Error(plan.unavailable);
2993
+ if (plan.install?.sealed === false) {
2994
+ await ensureChromium(plan.browsersPath, true, plan.build, true);
2995
+ sealInstall(plan.browsersPath);
2996
+ throw new BrowserInstalledError();
2997
+ }
2998
+ const executablePath = plan.shippedDir === void 0 ? await ensureChromium(
2999
+ plan.browsersPath,
3000
+ plan.install === void 0 && plan.shipped !== true,
3001
+ plan.build
3002
+ ) : await shippedExecutable(plan.browsersPath, plan.shippedDir, plan.build);
1311
3003
  const pw = await loadPlaywright(plan.browsersPath);
1312
3004
  return pw.chromium.launchPersistentContext(plan.profileDir, {
1313
3005
  headless: true,
@@ -1317,72 +3009,181 @@ async function launchChromium(plan) {
1317
3009
  // downloads are saved into the workspace by the session (actions.ts)
1318
3010
  acceptDownloads: true,
1319
3011
  downloadsPath: plan.downloadsTmp,
1320
- ...plan.proxyAuth === void 0 ? {} : { proxy: plan.proxyAuth }
3012
+ ...plan.proxyAuth === void 0 ? {} : { proxy: plan.proxyAuth },
3013
+ ...plan.env === void 0 ? {} : { env: { ...process.env, ...plan.env } }
1321
3014
  });
1322
3015
  }
3016
+ async function shippedExecutable(cache, dir, build) {
3017
+ const { executablePath, directory } = await registryBrowser(cache, build);
3018
+ const path = join2(cache, dir, relative(directory, executablePath));
3019
+ if (!existsSync(path))
3020
+ throw new Error(
3021
+ `the browser shipped in ${join2(cache, dir)} has no executable; ${BROWSER_UNAVAILABLE_MESSAGE}`
3022
+ );
3023
+ return path;
3024
+ }
3025
+ function sealInstall(dir) {
3026
+ try {
3027
+ writeFileSync(join2(dir, SERVICE_INSTALL_SEAL), "", { flag: "wx", mode: 420 });
3028
+ } catch (e) {
3029
+ if (e.code !== "EEXIST") throw e;
3030
+ }
3031
+ }
3032
+ async function browserProcessId(ctx) {
3033
+ const browser = ctx.browser();
3034
+ if (browser === null) return void 0;
3035
+ try {
3036
+ const cdp = await browser.newBrowserCDPSession();
3037
+ try {
3038
+ const info = await cdp.send("SystemInfo.getProcessInfo");
3039
+ return info.processInfo.find((p) => p.type === "browser")?.id;
3040
+ } finally {
3041
+ await cdp.detach().catch(() => void 0);
3042
+ }
3043
+ } catch {
3044
+ return void 0;
3045
+ }
3046
+ }
3047
+ function killChromium(pid) {
3048
+ if (!Number.isInteger(pid) || pid <= 1 || pid === process.pid) return;
3049
+ try {
3050
+ process.kill(-pid, "SIGKILL");
3051
+ } catch {
3052
+ try {
3053
+ process.kill(pid, "SIGKILL");
3054
+ } catch {
3055
+ }
3056
+ }
3057
+ }
3058
+ function processAlive(pid) {
3059
+ try {
3060
+ process.kill(pid, 0);
3061
+ return true;
3062
+ } catch (e) {
3063
+ return e.code === "EPERM";
3064
+ }
3065
+ }
1323
3066
 
1324
- // daemon/session-file.ts
1325
- import { readFileSync as readFileSync2, renameSync, rmSync, writeFileSync } from "node:fs";
3067
+ // daemon/cookie-file.ts
3068
+ import { readFileSync as readFileSync2, renameSync, rmSync, writeFileSync as writeFileSync2 } from "node:fs";
1326
3069
  import { join as join3 } from "node:path";
3070
+ var key = (c) => `${c.domain}
3071
+ ${c.path}
3072
+ ${c.name}`;
3073
+ async function saveCookies(ctx, stateDir) {
3074
+ try {
3075
+ const cookies = (await ctx.cookies()).filter((c) => c.expires > 0);
3076
+ const file = join3(stateDir, "cookies.json");
3077
+ writeFileSync2(`${file}.tmp`, JSON.stringify(cookies), { mode: 384 });
3078
+ renameSync(`${file}.tmp`, file);
3079
+ } catch {
3080
+ }
3081
+ }
3082
+ async function restoreCookies(ctx, stateDir) {
3083
+ try {
3084
+ const saved = JSON.parse(readFileSync2(join3(stateDir, "cookies.json"), "utf8"));
3085
+ if (!Array.isArray(saved)) return;
3086
+ const have = new Set((await ctx.cookies()).map(key));
3087
+ const now = Date.now() / 1e3;
3088
+ const missing = saved.filter(
3089
+ (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))
3090
+ );
3091
+ if (missing.length > 0) await ctx.addCookies(missing);
3092
+ } catch {
3093
+ } finally {
3094
+ rmSync(join3(stateDir, "cookies.json"), { force: true });
3095
+ }
3096
+ }
3097
+
3098
+ // daemon/session-file.ts
3099
+ import { readFileSync as readFileSync3, renameSync as renameSync2, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "node:fs";
3100
+ import { join as join4 } from "node:path";
1327
3101
  var RESTORE_MAX_AGE_MS = 10 * 6e4;
3102
+ var SESSION_FILE_VERSION = 2;
3103
+ var isId = (v) => typeof v === "string" && v !== "";
1328
3104
  var SessionFile = class {
1329
3105
  file;
1330
3106
  clock;
1331
3107
  queued = false;
1332
3108
  forgotten = false;
1333
3109
  constructor(stateDir, clock) {
1334
- this.file = join3(stateDir, "session.json");
3110
+ this.file = join4(stateDir, "session.json");
1335
3111
  this.clock = clock;
1336
3112
  }
1337
- /** The saved session when it is recent and well formed; undefined otherwise. */
3113
+ /** The saved session when it is recent, of this format and well formed; undefined otherwise. */
1338
3114
  read() {
1339
3115
  let raw;
1340
3116
  try {
1341
- raw = JSON.parse(readFileSync2(this.file, "utf8"));
3117
+ raw = JSON.parse(readFileSync3(this.file, "utf8"));
1342
3118
  } catch {
1343
3119
  return void 0;
1344
3120
  }
1345
3121
  const s = raw;
1346
- if (typeof s !== "object" || s === null || typeof s.savedAt !== "number" || this.clock.now() - s.savedAt > RESTORE_MAX_AGE_MS || !Array.isArray(s.tabs))
3122
+ if (typeof s !== "object" || s === null || s.version !== SESSION_FILE_VERSION || typeof s.savedAt !== "number" || this.clock.now() - s.savedAt > RESTORE_MAX_AGE_MS || !Array.isArray(s.tabs) || !Array.isArray(s.conversations))
1347
3123
  return void 0;
1348
3124
  const tabs = s.tabs.filter(
1349
- (u) => typeof u === "string" && /^https?:\/\//i.test(u)
1350
- );
1351
- const h = s.handoff;
1352
- const handoff = typeof h === "object" && h !== null && typeof h.callId === "string" && h.callId !== "" && typeof h.message === "string" ? { callId: h.callId, message: h.message.slice(0, HANDOFF_MAX_CHARS) } : void 0;
1353
- return {
1354
- savedAt: s.savedAt,
1355
- tabs: tabs.slice(0, MAX_TABS),
1356
- active: typeof s.active === "number" ? s.active : 0,
1357
- ...handoff === void 0 ? {} : { handoff }
1358
- };
3125
+ (t) => typeof t === "object" && t !== null && typeof t.url === "string" && /^https?:\/\//i.test(t.url) && isId(t.owner) && isId(t.root)
3126
+ ).slice(0, MAX_TABS).map((t) => ({ url: t.url, owner: t.owner, root: t.root }));
3127
+ const conversations = [];
3128
+ for (const c of s.conversations) {
3129
+ if (typeof c !== "object" || c === null) continue;
3130
+ const x = c;
3131
+ if (!isId(x.id) || !isId(x.root)) continue;
3132
+ const h = x.handoff;
3133
+ const handoff = typeof h === "object" && h !== null && isId(h.callId) && typeof h.message === "string" ? { callId: h.callId, message: h.message.slice(0, HANDOFF_MAX_CHARS) } : void 0;
3134
+ const parks = Array.isArray(x.parks) ? x.parks.filter(
3135
+ (p) => typeof p === "object" && p !== null && isId(p.kind) && typeof p.key === "string"
3136
+ ).map((p) => ({ kind: p.kind, key: p.key })) : [];
3137
+ conversations.push({
3138
+ id: x.id,
3139
+ root: x.root,
3140
+ ...typeof x.active === "number" ? { active: x.active } : {},
3141
+ ...handoff === void 0 ? {} : { handoff },
3142
+ ...parks.length === 0 ? {} : { parks }
3143
+ });
3144
+ }
3145
+ return { version: SESSION_FILE_VERSION, savedAt: s.savedAt, tabs, conversations };
1359
3146
  }
1360
3147
  /**
1361
- * Writes the session soon (coalesced): the tabs' URLs and the pending handoff, both read when
1362
- * the write runs.
3148
+ * Writes the session soon (coalesced): the tabs with their owners, and per conversation its
3149
+ * active tab, pending handoff and persistent parks, all read when the write runs.
1363
3150
  */
1364
- save(session, handoffNow) {
3151
+ save(session, state) {
1365
3152
  if (this.queued || this.forgotten) return;
1366
3153
  this.queued = true;
1367
3154
  queueMicrotask(() => {
1368
3155
  this.queued = false;
1369
3156
  if (this.forgotten) return;
1370
- const handoff = handoffNow();
1371
- const all = session.tabs();
1372
- const kept = all.filter((t) => /^https?:\/\//i.test(t.url));
1373
- const active = Math.max(
1374
- 0,
1375
- kept.findIndex((t) => t.active)
3157
+ const kept = session.tabs().filter(
3158
+ (t) => t.owner !== void 0 && t.root !== void 0 && /^https?:\/\//i.test(t.url)
1376
3159
  );
3160
+ const tabs = kept.map((t) => ({ url: t.url, owner: t.owner, root: t.root }));
3161
+ const ids = /* @__PURE__ */ new Set([...kept.map((t) => t.owner), ...state.conversationIds]);
3162
+ const conversations = [];
3163
+ for (const id of ids) {
3164
+ const root = kept.find((t) => t.owner === id)?.root ?? state.rootOf(id);
3165
+ if (root === void 0) continue;
3166
+ const active = kept.findIndex((t) => t.owner === id && t.active);
3167
+ const handoff = state.handoffOf(id);
3168
+ const parks = state.parksOf(id).filter((p) => p.persist === true && p.tabId === void 0 && p.kind !== HANDOFF_PARK).map((p) => ({ kind: p.kind, key: p.key }));
3169
+ if (active < 0 && handoff === void 0 && parks.length === 0) continue;
3170
+ conversations.push({
3171
+ id,
3172
+ root,
3173
+ ...active < 0 ? {} : { active },
3174
+ ...handoff === void 0 ? {} : { handoff },
3175
+ ...parks.length === 0 ? {} : { parks }
3176
+ });
3177
+ }
1377
3178
  const body = {
3179
+ version: SESSION_FILE_VERSION,
1378
3180
  savedAt: this.clock.now(),
1379
- tabs: kept.map((t) => t.url),
1380
- active,
1381
- ...handoff === void 0 ? {} : { handoff }
3181
+ tabs,
3182
+ conversations
1382
3183
  };
1383
3184
  try {
1384
- writeFileSync(`${this.file}.tmp`, JSON.stringify(body), { mode: 384 });
1385
- renameSync(`${this.file}.tmp`, this.file);
3185
+ writeFileSync3(`${this.file}.tmp`, JSON.stringify(body), { mode: 384 });
3186
+ renameSync2(`${this.file}.tmp`, this.file);
1386
3187
  } catch {
1387
3188
  }
1388
3189
  });
@@ -1390,45 +3191,361 @@ var SessionFile = class {
1390
3191
  /** Removes the file and stops saving (an idle stop). */
1391
3192
  forget() {
1392
3193
  this.forgotten = true;
1393
- rmSync(this.file, { force: true });
3194
+ rmSync2(this.file, { force: true });
3195
+ }
3196
+ /** Gives the conversations their pending handoffs and persistent parks back. */
3197
+ restoreState(state, saved) {
3198
+ for (const c of saved.conversations) {
3199
+ if (c.handoff !== void 0)
3200
+ state.noticeHandoff(c.id, c.root, c.handoff.callId, c.handoff.message);
3201
+ for (const p of c.parks ?? []) state.park(c.id, c.root, { ...p, persist: true });
3202
+ }
1394
3203
  }
1395
3204
  /**
1396
- * Opens the saved tabs in a browser that has only its first blank tab. The navigations are
1397
- * started, not awaited: the first request after a restart does not wait for every page to load.
3205
+ * Opens the saved tabs, each for its owner, in a browser that has only its first blank tab, and
3206
+ * gives each conversation its active tab back. The navigations are started, not awaited: the
3207
+ * first request after a restart does not wait for every page to load.
1398
3208
  */
1399
3209
  async restoreTabs(session, saved) {
1400
- if (saved.tabs.length === 0) return;
1401
3210
  const ids = [];
1402
- for (const [i, url] of saved.tabs.entries()) {
3211
+ for (const t of saved.tabs) {
1403
3212
  try {
1404
- const page = i === 0 ? await session.activePage() : await session.openTab();
1405
- ids.push(session.tabIdOf(page));
1406
- void session.viewerNav({ url: normalizeUrl(url) });
3213
+ ids.push(await session.restoreTab({ owner: t.owner, root: t.root }, t.url));
1407
3214
  } catch {
3215
+ ids.push(void 0);
3216
+ }
3217
+ }
3218
+ for (const c of saved.conversations) {
3219
+ const id = c.active === void 0 ? void 0 : ids[c.active];
3220
+ if (id !== void 0) session.setActive(c.id, id);
3221
+ }
3222
+ }
3223
+ };
3224
+
3225
+ // daemon/cursor.ts
3226
+ var CURSOR_MAX_FRAMES = 20;
3227
+ var MAX_DEPTH = 3;
3228
+ var WORLD = "capybara-cursor";
3229
+ var CURSOR_FUNCTION = `function (x, y) {
3230
+ const el = this.nodeType === 1 ? this : this.parentElement;
3231
+ if (!el) return { cursor: "default" };
3232
+ if (el.tagName === "IFRAME" || el.tagName === "FRAME") return { frame: true };
3233
+ const doc = el.ownerDocument;
3234
+ const view = doc.defaultView;
3235
+ const style = view.getComputedStyle(el);
3236
+ // "url(a.cur) 4 4, pointer": an image cursor's keyword fallback is the last item
3237
+ const parts = String(style.cursor).split(",");
3238
+ const cursor = parts[parts.length - 1].trim();
3239
+ if (cursor !== "auto") return { cursor };
3240
+ const NOT_TEXT = ["button", "submit", "reset", "checkbox", "radio", "range", "color", "file", "image", "hidden"];
3241
+ const tag = el.tagName;
3242
+ const editable = el.isContentEditable || tag === "TEXTAREA" ||
3243
+ (tag === "INPUT" && !NOT_TEXT.includes(String(el.type).toLowerCase()));
3244
+ if (editable && !el.disabled) return { cursor: "text" };
3245
+ if (style.userSelect === "none") return { cursor: "default" };
3246
+ const range = doc.caretRangeFromPoint ? doc.caretRangeFromPoint(x, y) : null;
3247
+ const node = range ? range.startContainer : null;
3248
+ if (!node || node.nodeType !== 3) return { cursor: "default" };
3249
+ const probe = doc.createRange();
3250
+ for (const [a, b] of [[range.startOffset, range.startOffset + 1], [range.startOffset - 1, range.startOffset]]) {
3251
+ if (a < 0 || b > node.length) continue;
3252
+ probe.setStart(node, a);
3253
+ probe.setEnd(node, b);
3254
+ for (const r of probe.getClientRects())
3255
+ if (x >= r.left && x <= r.right && y >= r.top && y <= r.bottom) return { cursor: "text" };
3256
+ }
3257
+ return { cursor: "default" };
3258
+ }`;
3259
+ var CursorResolver = class {
3260
+ constructor(context, page, cdp) {
3261
+ this.context = context;
3262
+ this.page = page;
3263
+ this.cdp = cdp;
3264
+ page.on("framedetached", this.onFrameDetached);
3265
+ }
3266
+ context;
3267
+ page;
3268
+ cdp;
3269
+ /** Isolated world execution contexts, per CDP session and frame id. */
3270
+ worlds = /* @__PURE__ */ new WeakMap();
3271
+ /** Sessions of out-of-process frames entered, detached with their frame or on dispose. */
3272
+ sessions = /* @__PURE__ */ new Map();
3273
+ onFrameDetached = (frame) => {
3274
+ const cdp = this.sessions.get(frame);
3275
+ if (cdp === void 0) return;
3276
+ this.sessions.delete(frame);
3277
+ cdp.detach().catch(() => void 0);
3278
+ };
3279
+ /** How many out-of-process frame sessions are open (a test seam). */
3280
+ get openSessions() {
3281
+ return this.sessions.size;
3282
+ }
3283
+ /** Detaches the frame sessions this resolver opened (the viewer detached from the page). */
3284
+ dispose() {
3285
+ this.page.off("framedetached", this.onFrameDetached);
3286
+ for (const cdp of this.sessions.values()) cdp.detach().catch(() => void 0);
3287
+ this.sessions.clear();
3288
+ }
3289
+ /** The cursor Chromium would show at viewport point (x, y). */
3290
+ async at(x, y) {
3291
+ let cdp = this.cdp;
3292
+ let frame = this.page.mainFrame();
3293
+ let px = x;
3294
+ let py = y;
3295
+ for (let depth = 0; depth <= MAX_DEPTH; depth++) {
3296
+ const hit = await this.hitTest(cdp, px, py);
3297
+ const answer = await this.answerAt(cdp, hit, px, py);
3298
+ if (answer.cursor !== void 0) return toViewerCursor(answer.cursor);
3299
+ if (!answer.frame || depth === MAX_DEPTH) return "default";
3300
+ const box = await cdp.send("DOM.getBoxModel", { backendNodeId: hit.backendNodeId });
3301
+ const [left = 0, top = 0] = box.model.content;
3302
+ const [borderLeft = 0, borderTop = 0] = box.model.border;
3303
+ const child = await this.childAt(frame, borderLeft + (x - px), borderTop + (y - py));
3304
+ if (child === void 0) return "default";
3305
+ frame = child.frame;
3306
+ cdp = child.cdp;
3307
+ px = px - left;
3308
+ py = py - top;
3309
+ }
3310
+ return "default";
3311
+ }
3312
+ async hitTest(cdp, x, y) {
3313
+ return await cdp.send("DOM.getNodeForLocation", {
3314
+ x: Math.round(x),
3315
+ y: Math.round(y),
3316
+ includeUserAgentShadowDOM: false,
3317
+ ignorePointerEventsNone: false
3318
+ });
3319
+ }
3320
+ /** The answer for a hit node, at the point in the node's own frame. */
3321
+ async answerAt(cdp, hit, x, y) {
3322
+ const frameId = hit.frameId ?? await this.mainFrameId(cdp);
3323
+ const offset = await this.frameOffset(cdp, frameId);
3324
+ return this.run(cdp, frameId, hit.backendNodeId, x - offset.x, y - offset.y);
3325
+ }
3326
+ async run(cdp, frameId, backendNodeId, x, y) {
3327
+ for (let attempt = 0; attempt < 2; attempt++) {
3328
+ const contextId = await this.world(cdp, frameId, attempt > 0);
3329
+ try {
3330
+ const { object } = await cdp.send("DOM.resolveNode", {
3331
+ backendNodeId,
3332
+ executionContextId: contextId
3333
+ });
3334
+ if (object.objectId === void 0) return { cursor: "default" };
3335
+ const r = await cdp.send("Runtime.callFunctionOn", {
3336
+ objectId: object.objectId,
3337
+ functionDeclaration: CURSOR_FUNCTION,
3338
+ arguments: [{ value: x }, { value: y }],
3339
+ returnByValue: true
3340
+ });
3341
+ await cdp.send("Runtime.releaseObject", { objectId: object.objectId }).catch(() => {
3342
+ });
3343
+ return r.result.value ?? { cursor: "default" };
3344
+ } catch (e) {
3345
+ if (attempt > 0) throw e;
1408
3346
  }
1409
3347
  }
1410
- const active = ids[saved.active];
1411
- if (active !== void 0) await session.switchTo(active).catch(() => void 0);
3348
+ return { cursor: "default" };
3349
+ }
3350
+ async world(cdp, frameId, fresh) {
3351
+ let byFrame = this.worlds.get(cdp);
3352
+ if (byFrame === void 0) {
3353
+ byFrame = /* @__PURE__ */ new Map();
3354
+ this.worlds.set(cdp, byFrame);
3355
+ }
3356
+ const known = byFrame.get(frameId);
3357
+ if (known !== void 0 && !fresh) return known;
3358
+ const { executionContextId } = await cdp.send("Page.createIsolatedWorld", {
3359
+ frameId,
3360
+ worldName: WORLD
3361
+ });
3362
+ byFrame.set(frameId, executionContextId);
3363
+ return executionContextId;
3364
+ }
3365
+ async mainFrameId(cdp) {
3366
+ const { frameTree } = await cdp.send("Page.getFrameTree");
3367
+ return frameTree.frame.id;
3368
+ }
3369
+ /** The offset of an in-process frame's viewport in the session's root (0 for its main frame). */
3370
+ async frameOffset(cdp, frameId) {
3371
+ if (frameId === await this.mainFrameId(cdp)) return { x: 0, y: 0 };
3372
+ const owner = await cdp.send("DOM.getFrameOwner", { frameId });
3373
+ const box = await cdp.send("DOM.getBoxModel", { backendNodeId: owner.backendNodeId });
3374
+ return { x: box.model.content[0] ?? 0, y: box.model.content[1] ?? 0 };
3375
+ }
3376
+ /**
3377
+ * The child frame of `parent` whose element's border box starts at (left, top), in the page's
3378
+ * (main frame) coordinates.
3379
+ */
3380
+ async childAt(parent, left, top) {
3381
+ for (const child of parent.childFrames().slice(0, CURSOR_MAX_FRAMES)) {
3382
+ const handle = await child.frameElement().catch(() => null);
3383
+ const box = await handle?.boundingBox().catch(() => null);
3384
+ await handle?.dispose();
3385
+ if (box === null || box === void 0) continue;
3386
+ if (Math.abs(box.x - left) > 3 || Math.abs(box.y - top) > 3) continue;
3387
+ let cdp = this.sessions.get(child);
3388
+ if (cdp === void 0) {
3389
+ cdp = await this.context.newCDPSession(child);
3390
+ this.sessions.set(child, cdp);
3391
+ }
3392
+ return { frame: child, cdp };
3393
+ }
3394
+ return void 0;
3395
+ }
3396
+ };
3397
+
3398
+ // daemon/viewer-pacing.ts
3399
+ var TARGET_LINK_MS = 120;
3400
+ var PING_WINDOW = 10;
3401
+ var RTT_WINDOW = 16;
3402
+ var LINK_ALPHA = 0.5;
3403
+ var FramePacer = class {
3404
+ minIntervalMs;
3405
+ maxUnacked;
3406
+ inFlight = [];
3407
+ pings = [];
3408
+ rtts = [];
3409
+ lastSentAt = Number.NEGATIVE_INFINITY;
3410
+ link;
3411
+ constructor(opts) {
3412
+ this.minIntervalMs = 1e3 / opts.maxFps;
3413
+ this.maxUnacked = opts.maxUnacked;
3414
+ }
3415
+ /** The smoothed time frames take over the path's own round trip; undefined before any ack. */
3416
+ get linkMs() {
3417
+ return this.link;
3418
+ }
3419
+ get unacked() {
3420
+ return this.inFlight.length;
3421
+ }
3422
+ /** The path's round trip without queueing, as far as measured. */
3423
+ get baseRttMs() {
3424
+ if (this.pings.length > 0) return Math.min(...this.pings);
3425
+ if (this.rtts.length > 0) return Math.min(...this.rtts);
3426
+ return void 0;
3427
+ }
3428
+ /** Whether a frame may be sent at `now`, and if only the rate cap holds it, for how long. */
3429
+ decide(now) {
3430
+ const n = this.inFlight.length;
3431
+ if (n >= this.maxUnacked) return { ok: false };
3432
+ if (n > 0 && this.link !== void 0 && this.link > TARGET_LINK_MS) return { ok: false };
3433
+ const wait = this.lastSentAt + this.minIntervalMs - now;
3434
+ return wait > 0 ? { ok: false, waitMs: wait } : { ok: true };
3435
+ }
3436
+ /** Records a frame sent at `now` (every frame counts, the first after an attach too). */
3437
+ sent(seq, now) {
3438
+ this.inFlight.push({ seq, at: now });
3439
+ this.lastSentAt = now;
3440
+ }
3441
+ /** Records the viewer's ack of every frame up to `seq` at `now`; returns the sample, if any. */
3442
+ acked(seq, now) {
3443
+ let last;
3444
+ while (this.inFlight.length > 0 && this.inFlight[0].seq <= seq) {
3445
+ last = this.inFlight.shift();
3446
+ }
3447
+ if (last === void 0) return void 0;
3448
+ const rtt = Math.max(0, now - last.at);
3449
+ this.rtts.push(rtt);
3450
+ if (this.rtts.length > RTT_WINDOW) this.rtts.shift();
3451
+ const sample = Math.max(0, rtt - (this.baseRttMs ?? rtt));
3452
+ this.link = this.link === void 0 ? sample : this.link * (1 - LINK_ALPHA) + sample * LINK_ALPHA;
3453
+ return sample;
3454
+ }
3455
+ /** Records a ping's round trip (a tiny message both ways on the same path as the frames). */
3456
+ pinged(rttMs) {
3457
+ if (!Number.isFinite(rttMs) || rttMs < 0) return;
3458
+ this.pings.push(rttMs);
3459
+ if (this.pings.length > PING_WINDOW) this.pings.shift();
3460
+ }
3461
+ /** Forgets frames in flight (a screencast restart: their acks may never come). */
3462
+ reset() {
3463
+ this.inFlight.length = 0;
3464
+ }
3465
+ };
3466
+ var QUALITY_STEPS = [60, 45, 35, 25];
3467
+ var SHRINK_STEPS = [1, 0.8, 0.65, 0.5, 0.35, 0.25];
3468
+ var ADAPT_SHRINK_STEPS = 4;
3469
+ var UP_AFTER_QUICK_FRAMES = 6;
3470
+ var FrameQuality = class {
3471
+ step = 0;
3472
+ quick = 0;
3473
+ get quality() {
3474
+ return QUALITY_STEPS[Math.min(this.step, QUALITY_STEPS.length - 1)];
3475
+ }
3476
+ get shrink() {
3477
+ const s = Math.max(0, this.step - (QUALITY_STEPS.length - 1));
3478
+ return SHRINK_STEPS[Math.min(s, SHRINK_STEPS.length - 1)];
3479
+ }
3480
+ /** The lowest step the link adaptation goes to. */
3481
+ get adaptMaxStep() {
3482
+ return QUALITY_STEPS.length - 1 + ADAPT_SHRINK_STEPS - 1;
3483
+ }
3484
+ get maxStep() {
3485
+ return QUALITY_STEPS.length - 1 + SHRINK_STEPS.length - 1;
3486
+ }
3487
+ /** One acked frame's link time; true when the step changed (restart the screencast). */
3488
+ observe(linkMs) {
3489
+ if (linkMs > TARGET_LINK_MS * 1.25) {
3490
+ this.quick = 0;
3491
+ if (this.step >= this.adaptMaxStep) return false;
3492
+ this.step++;
3493
+ return true;
3494
+ }
3495
+ if (linkMs < TARGET_LINK_MS / 2) {
3496
+ this.quick++;
3497
+ if (this.quick >= UP_AFTER_QUICK_FRAMES && this.step > 0) {
3498
+ this.step--;
3499
+ this.quick = 0;
3500
+ return true;
3501
+ }
3502
+ } else this.quick = 0;
3503
+ return false;
3504
+ }
3505
+ /** A frame too large for one message: always one step smaller. */
3506
+ tooLarge() {
3507
+ this.quick = 0;
3508
+ if (this.step >= this.maxStep) return false;
3509
+ this.step++;
3510
+ return true;
1412
3511
  }
1413
3512
  };
1414
3513
 
1415
3514
  // daemon/viewer.ts
1416
- var FRAME_JSON_OVERHEAD = 128;
1417
- var START_QUALITY = 60;
1418
- var MIN_QUALITY = 20;
3515
+ var VIEWER_PING_MS = 1e3;
3516
+ var RESTART_MIN_MS = 500;
3517
+ var ENCODE_MAX_INTERVAL_MS = 500;
3518
+ var CURSOR_TIMEOUT_MS = 200;
1419
3519
  var clampDim = (n, max) => typeof n === "number" && Number.isFinite(n) ? Math.max(16, Math.min(max, Math.floor(n))) : max;
1420
3520
  var ViewerSession = class {
1421
3521
  browser;
1422
3522
  state;
3523
+ /** The viewer's conversation and the root of its tree (from the kernel's viewer context). */
3524
+ conv;
3525
+ root;
3526
+ /** The tab the person (or a new handoff) chose to show; cleared when it leaves the tree. */
3527
+ choice;
3528
+ /** The tab shown now (computed with every state). */
3529
+ shown;
3530
+ /** The other conversation the viewer pins because it shows one of its tabs. */
3531
+ pinnedOwner;
3532
+ /** Group keys of the tree's other conversations, in order of first appearance. */
3533
+ groups = /* @__PURE__ */ new Map();
3534
+ /** The tree's handoffs seen so far (a new one moves the shown tab to its conversation). */
3535
+ seenHandoffs = /* @__PURE__ */ new Set();
1423
3536
  out;
1424
3537
  clock;
1425
3538
  frameMaxBytes;
1426
3539
  unsubscribe = [];
1427
3540
  maxWidth = VIEWPORT.width;
1428
3541
  maxHeight = VIEWPORT.height;
1429
- /** Lowered when a frame does not fit the message cap. */
1430
- quality = START_QUALITY;
1431
- shrink = 1;
3542
+ pacer = new FramePacer({
3543
+ maxFps: VIEWER_MAX_FPS,
3544
+ maxUnacked: VIEWER_UNACKED_FRAMES
3545
+ });
3546
+ /** Quality and scale: lowered while frames are slow on the link or over the message cap. */
3547
+ frameQuality = new FrameQuality();
3548
+ lastRestartAt = Number.NEGATIVE_INFINITY;
1432
3549
  started = false;
1433
3550
  closed = false;
1434
3551
  page;
@@ -1438,17 +3555,48 @@ var ViewerSession = class {
1438
3555
  inputChain = Promise.resolve();
1439
3556
  /** Bumped on close and hand back: input queued before it is dropped, not replayed. */
1440
3557
  inputGen = 0;
3558
+ /**
3559
+ * The newest pointer position not yet applied, while a move for it waits on the input chain:
3560
+ * later moves replace it (the newest wins) instead of queueing behind it.
3561
+ */
3562
+ moveSlot;
3563
+ /** The cursor last sent (reset when control returns to the agent). */
3564
+ cursor;
3565
+ /** Resolves cursors on the attached page (off the input chain, see {@link wantCursor}). */
3566
+ cursorResolver;
3567
+ /** The newest pointer position whose cursor is wanted; one resolution runs at a time. */
3568
+ cursorPoint;
3569
+ /** The resolver a resolution loop runs for (one loop per resolver, one lookup at a time). */
3570
+ cursorLoop;
3571
+ /**
3572
+ * Keys and buttons this viewer pressed and has not released: released for the agent when
3573
+ * control returns to it or the viewer ends, whatever reached the page of the person's input.
3574
+ */
3575
+ heldKeys = /* @__PURE__ */ new Map();
3576
+ heldButtons = /* @__PURE__ */ new Map();
1441
3577
  seq = 0;
1442
- acked = 0;
1443
- lastSentAt = 0;
1444
- /** A screencast frame waiting for room (viewer acks, transport, rate cap); acked once sent. */
3578
+ /**
3579
+ * The newest screencast frame waiting for room (viewer acks, transport, rate cap). A newer one
3580
+ * replaces it: a frame is never queued behind a stale one.
3581
+ */
1445
3582
  pending;
3583
+ /** Chromium frames received but not acked to Chromium yet (it encodes the next after an ack). */
3584
+ encodeAck;
3585
+ encodeTimer;
3586
+ lastEncodeAckAt = Number.NEGATIVE_INFINITY;
1446
3587
  pumpTimer;
3588
+ pingTimer;
3589
+ pingSeq = 0;
3590
+ pingsSent = /* @__PURE__ */ new Map();
1447
3591
  draining = false;
1448
3592
  stateQueued = false;
3593
+ lastControl = "agent";
1449
3594
  constructor(opts) {
1450
3595
  this.browser = opts.browser;
1451
3596
  this.state = opts.state;
3597
+ this.conv = opts.conversationId;
3598
+ this.root = opts.rootConversationId;
3599
+ this.state.pin(this.conv, this.root);
1452
3600
  this.out = opts.transport;
1453
3601
  this.clock = opts.clock;
1454
3602
  this.frameMaxBytes = opts.frameMaxBytes;
@@ -1464,12 +3612,17 @@ var ViewerSession = class {
1464
3612
  if (m.t !== "hello") return;
1465
3613
  this.started = true;
1466
3614
  this.setSize(m.maxWidth, m.maxHeight);
3615
+ this.lastControl = this.state.control;
1467
3616
  this.unsubscribe.push(
1468
3617
  this.browser.on((e) => this.onSession(e)),
1469
- this.state.onChange(() => this.queueState())
3618
+ this.state.onChange(() => this.onControl())
1470
3619
  );
3620
+ const pending = this.state.handoffs(this.root);
3621
+ this.seenHandoffs = new Set(pending.map(handoffKey));
3622
+ const newest = pending.at(-1);
3623
+ if (newest !== void 0) this.choice = this.browser.activeTabOf(newest.conversationId);
1471
3624
  this.sendState();
1472
- void this.serial(() => this.attach());
3625
+ this.ping();
1473
3626
  return;
1474
3627
  }
1475
3628
  switch (m.t) {
@@ -1482,39 +3635,64 @@ var ViewerSession = class {
1482
3635
  });
1483
3636
  return;
1484
3637
  case "frame-ack":
1485
- if (typeof m.seq === "number" && m.seq > this.acked) this.acked = Math.min(m.seq, this.seq);
3638
+ if (typeof m.seq === "number") this.onAck(Math.min(m.seq, this.seq));
1486
3639
  this.pump();
1487
3640
  return;
3641
+ case "pong": {
3642
+ const sentAt = typeof m.id === "number" ? this.pingsSent.get(m.id) : void 0;
3643
+ if (sentAt !== void 0) {
3644
+ this.pingsSent.delete(m.id);
3645
+ this.pacer.pinged(this.clock.now() - sentAt);
3646
+ }
3647
+ return;
3648
+ }
1488
3649
  case "takeover":
1489
- this.state.takeover();
3650
+ this.state.takeover(this.browser.owningConversations());
1490
3651
  return;
1491
3652
  case "handback":
1492
3653
  this.inputGen++;
1493
3654
  this.state.handback();
1494
3655
  return;
1495
3656
  case "mouse":
1496
- this.input(() => this.mouse(m));
3657
+ if (m.kind === "move") this.move(m);
3658
+ else this.input(() => this.mouse(m));
1497
3659
  return;
1498
3660
  case "key":
1499
3661
  this.input(() => this.key(m));
1500
3662
  return;
1501
3663
  case "nav":
1502
- this.input(
1503
- () => this.browser.viewerNav({
3664
+ this.input(async () => {
3665
+ let page = this.shownPage();
3666
+ if (page === void 0) {
3667
+ if (typeof m.url !== "string") return;
3668
+ page = await this.openOwnTab();
3669
+ if (page === void 0) return;
3670
+ }
3671
+ this.concern(this.browser.tabIdOf(page));
3672
+ await this.browser.viewerNav(page, {
1504
3673
  ...typeof m.url === "string" ? { url: m.url } : {},
1505
3674
  ...m.action === void 0 ? {} : { action: m.action }
1506
- })
1507
- );
3675
+ });
3676
+ });
3677
+ return;
3678
+ case "show":
3679
+ if (typeof m.tabId === "string" && this.inTree(m.tabId)) {
3680
+ this.choice = m.tabId;
3681
+ this.queueState();
3682
+ }
1508
3683
  return;
1509
3684
  case "tab":
3685
+ if (m.action === "adopt") {
3686
+ this.adopt(m.tabId);
3687
+ return;
3688
+ }
1510
3689
  this.input(async () => {
1511
3690
  try {
1512
- if (m.action === "open") await this.browser.openTab();
1513
- else if (m.action === "switch" && m.tabId !== void 0)
1514
- await this.browser.switchTo(m.tabId);
1515
- else if (m.action === "close" && m.tabId !== void 0) {
3691
+ if (m.action === "open") await this.openOwnTab();
3692
+ else if (m.action === "switch" && m.tabId !== void 0) this.switchTo(m.tabId);
3693
+ else if (m.action === "close" && m.tabId !== void 0 && this.inTree(m.tabId)) {
3694
+ this.concern(m.tabId);
1516
3695
  await this.browser.tabById(m.tabId).close();
1517
- await this.browser.activePage();
1518
3696
  }
1519
3697
  } catch {
1520
3698
  }
@@ -1522,26 +3700,206 @@ var ViewerSession = class {
1522
3700
  return;
1523
3701
  }
1524
3702
  }
1525
- /** Runs viewer input in arrival order, apart from the screencast chain. */
3703
+ /** Whether a tab belongs to the viewer's tree. */
3704
+ inTree(tabId) {
3705
+ return this.browser.ownerOf(tabId)?.root === this.root && this.browser.pageById(tabId) !== void 0;
3706
+ }
3707
+ /** The shown tab's page, if the tree has one. */
3708
+ shownPage() {
3709
+ return this.browser.pageById(this.shown);
3710
+ }
3711
+ /** The person used a tab during the takeover: its owner gets the hand back note. */
3712
+ concern(tabId) {
3713
+ if (tabId === void 0) return;
3714
+ this.state.concern(this.browser.ownerOf(tabId)?.owner);
3715
+ }
3716
+ /**
3717
+ * A tab the person opens: owned by the viewer's conversation, made its active tab and shown
3718
+ * (the caps apply; a refusal opens nothing).
3719
+ */
3720
+ async openOwnTab() {
3721
+ try {
3722
+ const page = this.browser.countOf(this.conv) === 0 ? await this.browser.pageFor(this.conv, this.root) : await this.browser.openTab(this.conv, this.root);
3723
+ this.state.concern(this.conv);
3724
+ this.choice = void 0;
3725
+ this.queueState();
3726
+ return page;
3727
+ } catch {
3728
+ return void 0;
3729
+ }
3730
+ }
3731
+ /**
3732
+ * Shows a tab of the tree and brings it to the front (a viewer in control decides what is
3733
+ * front). A tab of the viewer's own conversation also becomes its active tab (the person chose
3734
+ * it); another conversation's tab changes only the shown tab, never that agent's active tab.
3735
+ */
3736
+ switchTo(tabId) {
3737
+ if (!this.inTree(tabId)) return;
3738
+ if (this.browser.ownerOf(tabId)?.owner === this.conv) {
3739
+ this.browser.setActive(this.conv, tabId);
3740
+ this.choice = void 0;
3741
+ } else this.choice = tabId;
3742
+ void this.browser.bringToFront(tabId);
3743
+ this.queueState();
3744
+ }
3745
+ /**
3746
+ * Moves another tree's tab (or an unowned one) to the viewer's conversation, as the tool's adopt;
3747
+ * a tab of the viewer's own tree is ignored (inside the tree the person drives tabs without
3748
+ * moving them). A tab whose owner is in use answers the `tab_in_use` notice.
3749
+ */
3750
+ adopt(tabId) {
3751
+ if (typeof tabId !== "string" || this.browser.pageById(tabId) === void 0) return;
3752
+ if (this.browser.ownerOf(tabId)?.root === this.root) return;
3753
+ let result;
3754
+ try {
3755
+ result = this.browser.adopt(this.conv, this.root, tabId);
3756
+ } catch {
3757
+ return;
3758
+ }
3759
+ if (result === "in_use") this.send({ t: "notice", code: "tab_in_use" });
3760
+ else if (result === "cap") this.send({ t: "notice", code: "tab_cap" });
3761
+ else if (result === "ok") {
3762
+ this.choice = void 0;
3763
+ this.queueState();
3764
+ }
3765
+ }
3766
+ /**
3767
+ * Runs viewer input in arrival order, apart from the screencast chain, and only while the person
3768
+ * holds control: input from a viewer in the watch state (the agent drives) is dropped, both when
3769
+ * it arrives and when its turn comes.
3770
+ */
1526
3771
  input(fn) {
3772
+ if (this.state.control !== "user") return;
3773
+ this.moveSlot = void 0;
1527
3774
  const gen = this.inputGen;
1528
- const guarded = () => gen === this.inputGen && !this.closed ? fn() : Promise.resolve();
3775
+ const guarded = () => gen === this.inputGen && !this.closed && this.state.control === "user" ? fn() : Promise.resolve();
1529
3776
  const run = this.inputChain.then(guarded, guarded);
1530
3777
  this.inputChain = run.catch(() => void 0);
1531
3778
  }
1532
- /** Ends the viewer: stops its screencast and its subscriptions. */
3779
+ /** A pointer move: coalesced while one waits (the newest position wins), then the cursor. */
3780
+ move(m) {
3781
+ if (this.state.control !== "user") return;
3782
+ const p = point(m);
3783
+ if (p === null) return;
3784
+ if (this.moveSlot !== void 0) {
3785
+ this.moveSlot.x = p.x;
3786
+ this.moveSlot.y = p.y;
3787
+ return;
3788
+ }
3789
+ const slot = { ...p };
3790
+ this.input(async () => {
3791
+ if (this.moveSlot === slot) this.moveSlot = void 0;
3792
+ const page = this.shownPage();
3793
+ if (page === void 0) return;
3794
+ try {
3795
+ await page.mouse.move(slot.x, slot.y);
3796
+ } catch {
3797
+ return;
3798
+ }
3799
+ this.wantCursor(slot.x, slot.y);
3800
+ });
3801
+ this.moveSlot = slot;
3802
+ }
3803
+ /**
3804
+ * Asks for the page's cursor at (x, y): resolved off the input chain (a click never waits for
3805
+ * it), the newest position wins while one resolution runs, and an answer later than
3806
+ * CURSOR_TIMEOUT_MS is dropped.
3807
+ */
3808
+ wantCursor(x, y) {
3809
+ this.cursorPoint = { x, y };
3810
+ const resolver = this.cursorResolver;
3811
+ if (resolver === void 0 || this.cursorLoop === resolver) return;
3812
+ this.cursorLoop = resolver;
3813
+ void (async () => {
3814
+ try {
3815
+ while (!this.closed && this.cursorResolver === resolver) {
3816
+ const p = this.cursorPoint;
3817
+ this.cursorPoint = void 0;
3818
+ if (p === void 0) return;
3819
+ const started = this.clock.now();
3820
+ const cursor = await resolver.at(p.x, p.y).catch(() => void 0);
3821
+ if (cursor === void 0 || this.clock.now() - started > CURSOR_TIMEOUT_MS) continue;
3822
+ if (this.cursorPoint !== void 0) continue;
3823
+ if (cursor === this.cursor || this.closed || this.state.control !== "user") continue;
3824
+ this.cursor = cursor;
3825
+ this.send({ t: "cursor", cursor });
3826
+ }
3827
+ } finally {
3828
+ if (this.cursorLoop === resolver) this.cursorLoop = void 0;
3829
+ }
3830
+ })();
3831
+ }
3832
+ /**
3833
+ * Releases the keys and buttons this viewer still holds (straight, not on the input chain and
3834
+ * not through the control gate): the agent must not inherit a held Shift or a drag.
3835
+ */
3836
+ async releaseHeld() {
3837
+ if (this.heldKeys.size === 0 && this.heldButtons.size === 0) return;
3838
+ const keys = [...this.heldKeys];
3839
+ const buttons = [...this.heldButtons];
3840
+ this.heldKeys.clear();
3841
+ this.heldButtons.clear();
3842
+ for (const [key2, page] of keys) await page.keyboard.up(key2).catch(() => void 0);
3843
+ for (const [button, page] of buttons) {
3844
+ await page.mouse.move(-1, -1).catch(() => void 0);
3845
+ await page.mouse.up({ button }).catch(() => void 0);
3846
+ }
3847
+ }
3848
+ /** Whether input this viewer applied should stay applied (still in control, not closed). */
3849
+ get driving() {
3850
+ return !this.closed && this.state.control === "user";
3851
+ }
3852
+ /** Ends the viewer: stops its screencast and its subscriptions, and lets go of its pins. */
1533
3853
  async close() {
1534
3854
  if (this.closed) return;
1535
3855
  this.closed = true;
1536
3856
  this.inputGen++;
3857
+ this.state.unpin(this.conv);
3858
+ if (this.pinnedOwner !== void 0) this.state.unpin(this.pinnedOwner);
3859
+ this.pinnedOwner = void 0;
3860
+ await this.releaseHeld();
1537
3861
  for (const u of this.unsubscribe.splice(0)) u();
1538
- if (this.pumpTimer !== void 0) this.clock.cancel(this.pumpTimer);
3862
+ for (const t of [this.pumpTimer, this.pingTimer, this.encodeTimer])
3863
+ if (t !== void 0) this.clock.cancel(t);
1539
3864
  await this.serial(() => this.detach());
1540
3865
  }
1541
3866
  setSize(w, h) {
1542
3867
  this.maxWidth = clampDim(w, VIEWPORT.width);
1543
3868
  this.maxHeight = clampDim(h, VIEWPORT.height);
1544
- this.shrink = 1;
3869
+ }
3870
+ /** Pings the viewer every VIEWER_PING_MS (its pong measures the path, see the pacing). */
3871
+ ping() {
3872
+ if (this.closed) return;
3873
+ const id = ++this.pingSeq;
3874
+ this.pingsSent.set(id, this.clock.now());
3875
+ for (const old of this.pingsSent.keys()) if (old < id - 4) this.pingsSent.delete(old);
3876
+ this.send({ t: "ping", id });
3877
+ this.pingTimer = this.clock.schedule(() => this.ping(), VIEWER_PING_MS);
3878
+ }
3879
+ /**
3880
+ * Control or handoffs changed: a new state; input of the old control dropped; a new handoff of
3881
+ * the tree shows its conversation's active tab.
3882
+ */
3883
+ onControl() {
3884
+ const pending = this.state.handoffs(this.root);
3885
+ const fresh = pending.filter((h) => !this.seenHandoffs.has(handoffKey(h))).at(-1);
3886
+ this.seenHandoffs = new Set(pending.map(handoffKey));
3887
+ if (fresh !== void 0) {
3888
+ const tab = this.browser.activeTabOf(fresh.conversationId);
3889
+ if (tab !== void 0) this.choice = tab;
3890
+ }
3891
+ const control = this.state.control;
3892
+ if (control !== this.lastControl) {
3893
+ this.lastControl = control;
3894
+ this.moveSlot = void 0;
3895
+ this.cursor = void 0;
3896
+ this.cursorPoint = void 0;
3897
+ if (control === "agent") {
3898
+ this.inputGen++;
3899
+ void this.releaseHeld();
3900
+ }
3901
+ }
3902
+ this.queueState();
1545
3903
  }
1546
3904
  serial(fn) {
1547
3905
  const run = this.chain.then(fn, fn);
@@ -1555,45 +3913,58 @@ var ViewerSession = class {
1555
3913
  */
1556
3914
  fitted(m) {
1557
3915
  const fits = (x) => Buffer.byteLength(JSON.stringify(x)) <= this.frameMaxBytes;
1558
- if (m.t === "frame" || fits(m)) return m;
3916
+ if (fits(m)) return m;
1559
3917
  let small;
1560
3918
  if (m.t === "state") {
1561
- const handoff = m.handoff === void 0 ? {} : { handoff: { ...m.handoff, message: clip(m.handoff.message, 200) } };
3919
+ const plain = { ...m, tabs: m.tabs.map(({ favicon: _icon, ...t }) => t) };
3920
+ if (fits(plain)) return plain;
3921
+ m = plain;
1562
3922
  small = {
1563
3923
  ...m,
1564
- tabs: m.tabs.map((t) => ({ ...t, title: clip(t.title, 200), url: clip(t.url, 200) })),
1565
- ...handoff
3924
+ tabs: m.tabs.map((t) => ({
3925
+ ...t,
3926
+ title: clip(t.title, 200),
3927
+ url: clip(t.url, 200),
3928
+ ...t.blocker === void 0 ? {} : { blocker: { ...t.blocker, url: clip(t.blocker.url, 200) } }
3929
+ })),
3930
+ otherTabs: m.otherTabs.map((t) => ({
3931
+ ...t,
3932
+ title: clip(t.title, 200),
3933
+ url: clip(t.url, 200)
3934
+ })),
3935
+ handoffs: m.handoffs.map((h) => ({ ...h, message: clip(h.message, 200) }))
1566
3936
  };
1567
3937
  } else if (m.t === "dialog") {
1568
3938
  small = { ...m, message: clip(m.message, 200) };
1569
- } else {
3939
+ } else if (m.t === "blocked") {
1570
3940
  small = { ...m, url: clip(m.url, 200) };
1571
- }
3941
+ } else return null;
1572
3942
  return fits(small) ? small : null;
1573
3943
  }
3944
+ /** Sends a JSON message at once: it never waits behind a held frame. */
1574
3945
  send(raw) {
1575
3946
  if (this.closed) return;
1576
3947
  const m = this.fitted(raw);
1577
3948
  if (m === null) return;
1578
- if (!this.out.send(m) && !this.draining) {
1579
- this.draining = true;
1580
- this.out.whenDrained().then(() => {
1581
- this.draining = false;
1582
- this.pump();
1583
- });
1584
- }
3949
+ if (!this.out.send(m)) this.awaitDrain();
3950
+ }
3951
+ awaitDrain() {
3952
+ if (this.draining) return;
3953
+ this.draining = true;
3954
+ this.out.whenDrained().then(() => {
3955
+ this.draining = false;
3956
+ this.pump();
3957
+ });
1585
3958
  }
1586
3959
  onSession(e) {
1587
3960
  if (e.type === "state") this.queueState();
1588
3961
  else if (e.type === "active") {
3962
+ if (e.conversationId === this.conv) this.choice = void 0;
3963
+ else if (this.shown !== void 0 && this.browser.ownerOf(this.shown)?.owner === e.conversationId)
3964
+ this.choice = this.browser.activeTabOf(e.conversationId);
1589
3965
  this.queueState();
1590
- void this.serial(async () => {
1591
- const page = await this.browser.activePage();
1592
- if (page === this.page) return;
1593
- await this.detach();
1594
- await this.attach();
1595
- });
1596
- } else if (e.type === "blocked") this.send({ t: "blocked", host: e.host, url: e.url });
3966
+ } else if (e.root !== this.root) return;
3967
+ else if (e.type === "blocked") this.send({ t: "blocked", host: e.host, url: e.url });
1597
3968
  else this.send({ t: "dialog", kind: e.kind, message: e.message });
1598
3969
  }
1599
3970
  /** Coalesces bursts of changes into one state message. */
@@ -1605,40 +3976,119 @@ var ViewerSession = class {
1605
3976
  this.sendState();
1606
3977
  });
1607
3978
  }
3979
+ /**
3980
+ * The tab to show: the chosen one while it is in the tree; else the viewer's conversation's
3981
+ * active tab; else the active tab of the tree's conversation that acted last; else the tree's
3982
+ * first tab; none when the tree owns no tab.
3983
+ */
3984
+ computeShown(tree) {
3985
+ if (this.choice !== void 0 && tree.some((t) => t.id === this.choice)) return this.choice;
3986
+ this.choice = void 0;
3987
+ const own = this.browser.activeTabOf(this.conv);
3988
+ if (own !== void 0) return own;
3989
+ let best;
3990
+ for (const owner of new Set(tree.map((t) => t.owner))) {
3991
+ if (owner === void 0) continue;
3992
+ const tab = this.browser.activeTabOf(owner);
3993
+ const order = this.browser.actedOrder(owner);
3994
+ if (tab !== void 0 && (best === void 0 || order > best.order)) best = { tab, order };
3995
+ }
3996
+ return best?.tab ?? tree[0]?.id;
3997
+ }
3998
+ /** Pins the owner of the shown tab (besides the viewer's own conversation). */
3999
+ pinShownOwner() {
4000
+ const owner = this.shown === void 0 ? void 0 : this.browser.ownerOf(this.shown);
4001
+ const next = owner === void 0 || owner.owner === this.conv ? void 0 : owner.owner;
4002
+ if (next === this.pinnedOwner) return;
4003
+ if (next !== void 0 && owner !== void 0) this.state.pin(next, owner.root);
4004
+ if (this.pinnedOwner !== void 0) this.state.unpin(this.pinnedOwner);
4005
+ this.pinnedOwner = next;
4006
+ }
4007
+ groupOf(owner) {
4008
+ if (owner === this.conv || owner === void 0) return "own";
4009
+ let g = this.groups.get(owner);
4010
+ if (g === void 0) {
4011
+ g = `sub${this.groups.size + 1}`;
4012
+ this.groups.set(owner, g);
4013
+ }
4014
+ return g;
4015
+ }
1608
4016
  sendState() {
1609
- const tabs = this.browser.tabs();
1610
- const active = tabs.find((t) => t.active);
1611
- const last = this.browser.lastClick;
4017
+ if (this.closed) return;
4018
+ const all = this.browser.tabs();
4019
+ const tree = all.filter((t) => t.root === this.root);
4020
+ this.shown = this.computeShown(tree);
4021
+ this.pinShownOwner();
4022
+ if (this.browser.pageById(this.shown) !== this.page) {
4023
+ void this.serial(async () => {
4024
+ if (this.browser.pageById(this.shown) === this.page) return;
4025
+ await this.detach();
4026
+ await this.attach();
4027
+ });
4028
+ }
4029
+ const order = /* @__PURE__ */ new Map([["own", 0]]);
4030
+ const tabs = tree.map((t) => {
4031
+ const group = this.groupOf(t.owner);
4032
+ if (!order.has(group)) order.set(group, order.size);
4033
+ return {
4034
+ id: t.id,
4035
+ title: t.title,
4036
+ url: t.url,
4037
+ active: t.id === this.shown,
4038
+ group,
4039
+ ...t.blocker === void 0 ? {} : { blocker: t.blocker },
4040
+ ...t.favicon === void 0 ? {} : { favicon: t.favicon },
4041
+ ...t.loading === true ? { loading: true } : {}
4042
+ };
4043
+ });
4044
+ tabs.sort((a, b) => (order.get(a.group) ?? 0) - (order.get(b.group) ?? 0));
4045
+ const shownTab = tree.find((t) => t.id === this.shown);
4046
+ const last = this.browser.lastClickOf(this.shown);
1612
4047
  this.send({
1613
4048
  t: "state",
1614
4049
  tabs,
1615
- loading: this.browser.loading,
1616
- secure: active?.url.startsWith("https:") ?? false,
4050
+ ...this.shown === void 0 ? {} : { shown: this.shown },
4051
+ otherTabs: all.filter((t) => t.root !== this.root && !isStartBlank(t)).map((t) => ({ id: t.id, title: t.title, url: t.url })),
4052
+ loading: this.browser.isLoading(this.shown),
4053
+ secure: shownTab?.url.startsWith("https:") ?? false,
1617
4054
  control: this.state.control,
1618
4055
  ...last === void 0 ? {} : { lastClick: last },
1619
- ...this.state.handoff === void 0 ? {} : { handoff: this.state.handoff }
4056
+ handoffs: this.state.handoffs(this.root).map((h) => ({
4057
+ callId: h.callId,
4058
+ conversationId: h.conversationId,
4059
+ message: h.message,
4060
+ tabIds: this.browser.tabsOf(h.conversationId)
4061
+ }))
1620
4062
  });
1621
4063
  }
1622
4064
  get scale() {
1623
- return Math.min(1, this.maxWidth / VIEWPORT.width, this.maxHeight / VIEWPORT.height) * this.shrink;
4065
+ return Math.min(1, this.maxWidth / VIEWPORT.width, this.maxHeight / VIEWPORT.height) * this.frameQuality.shrink;
1624
4066
  }
1625
- /** Room for the JPEG's decoded bytes in one frame message. */
4067
+ /** Room for the JPEG in one frame message. */
1626
4068
  get jpegBudget() {
1627
- return Math.floor((this.frameMaxBytes - FRAME_JSON_OVERHEAD) * 3 / 4);
4069
+ return this.frameMaxBytes - FRAME_HEADER_BYTES;
1628
4070
  }
1629
4071
  async attach() {
1630
4072
  if (this.closed) return;
1631
- const page = await this.browser.activePage();
4073
+ const page = this.shownPage();
4074
+ if (page === void 0) return;
1632
4075
  const cdp = await this.browser.context.newCDPSession(page);
1633
4076
  this.page = page;
1634
4077
  this.cdp = cdp;
1635
4078
  cdp.on("Page.screencastFrame", (f) => this.onFrame(cdp, f));
4079
+ this.cursorResolver = new CursorResolver(this.browser.context, page, cdp);
1636
4080
  const first = await captureFitting(cdp, {
1637
4081
  maxBytes: this.jpegBudget,
1638
4082
  maxScale: this.scale
1639
4083
  }).catch(() => null);
1640
4084
  if (first !== null && this.cdp === cdp) {
1641
- this.sendFrame(first.data, first.width, first.height);
4085
+ this.pending = {
4086
+ cdp,
4087
+ jpeg: Buffer.from(first.data, "base64"),
4088
+ width: first.width,
4089
+ height: first.height
4090
+ };
4091
+ this.pump();
1642
4092
  }
1643
4093
  await this.startScreencast(cdp);
1644
4094
  }
@@ -1646,7 +4096,7 @@ var ViewerSession = class {
1646
4096
  if (this.closed || this.cdp !== cdp) return;
1647
4097
  await cdp.send("Page.startScreencast", {
1648
4098
  format: "jpeg",
1649
- quality: this.quality,
4099
+ quality: this.frameQuality.quality,
1650
4100
  maxWidth: Math.max(16, Math.floor(VIEWPORT.width * this.scale)),
1651
4101
  maxHeight: Math.max(16, Math.floor(VIEWPORT.height * this.scale)),
1652
4102
  everyNthFrame: 1
@@ -1657,93 +4107,163 @@ var ViewerSession = class {
1657
4107
  this.cdp = void 0;
1658
4108
  this.page = void 0;
1659
4109
  this.pending = void 0;
4110
+ this.encodeAck = void 0;
4111
+ this.cursorResolver?.dispose();
4112
+ this.cursorResolver = void 0;
1660
4113
  if (cdp === void 0) return;
1661
4114
  await cdp.send("Page.stopScreencast").catch(() => void 0);
1662
4115
  await cdp.detach().catch(() => void 0);
1663
4116
  }
1664
4117
  sendFrame(jpeg, width, height) {
1665
4118
  this.seq++;
1666
- this.lastSentAt = this.clock.now();
1667
- this.send({ t: "frame", seq: this.seq, jpeg, width, height });
4119
+ this.pacer.sent(this.seq, this.clock.now());
4120
+ if (!this.out.sendFrame(encodeFrame({ seq: this.seq, width, height, jpeg }))) this.awaitDrain();
4121
+ }
4122
+ /** The viewer acked frames up to `seq`: the link time adapts quality and scale. */
4123
+ onAck(seq) {
4124
+ const sample = this.pacer.acked(seq, this.clock.now());
4125
+ if (sample === void 0) return;
4126
+ if (this.clock.now() - this.lastRestartAt < RESTART_MIN_MS) return;
4127
+ if (this.frameQuality.observe(this.pacer.linkMs ?? sample)) this.restart();
4128
+ }
4129
+ /** Restarts the screencast at the current quality and scale. */
4130
+ restart() {
4131
+ const cdp = this.cdp;
4132
+ if (cdp === void 0) return;
4133
+ this.lastRestartAt = this.clock.now();
4134
+ this.pacer.reset();
4135
+ void this.serial(async () => {
4136
+ if (this.cdp !== cdp) return;
4137
+ await cdp.send("Page.stopScreencast").catch(() => void 0);
4138
+ this.pending = void 0;
4139
+ this.encodeAck = void 0;
4140
+ await this.startScreencast(cdp);
4141
+ });
1668
4142
  }
1669
4143
  onFrame(cdp, f) {
1670
4144
  if (this.closed || this.cdp !== cdp) return;
1671
4145
  const bytes = Buffer.from(f.data, "base64");
1672
4146
  if (bytes.length > this.jpegBudget) {
1673
4147
  cdp.send("Page.screencastFrameAck", { sessionId: f.sessionId }).catch(() => void 0);
1674
- if (this.quality > MIN_QUALITY) this.quality = Math.max(MIN_QUALITY, this.quality - 15);
1675
- else this.shrink *= 0.75;
1676
- void this.serial(async () => {
1677
- if (this.cdp !== cdp) return;
1678
- await cdp.send("Page.stopScreencast").catch(() => void 0);
1679
- await this.startScreencast(cdp);
1680
- });
4148
+ if (this.frameQuality.tooLarge()) this.restart();
1681
4149
  return;
1682
4150
  }
1683
4151
  const { width, height } = jpegSize(bytes);
1684
- this.pending = { cdp, sessionId: f.sessionId, data: f.data, width, height };
4152
+ this.pending = { cdp, jpeg: bytes, width, height };
4153
+ this.encodeAck = { cdp, sessionId: f.sessionId };
1685
4154
  this.pump();
4155
+ this.scheduleEncodeAck();
4156
+ }
4157
+ /**
4158
+ * Lets Chromium encode its next frame (screencastFrameAck): at most at the viewer's frame rate
4159
+ * while frames flow, and while one waits for the viewer only every ENCODE_MAX_INTERVAL_MS, so
4160
+ * the frame sent when room comes is a recent one without encoding frames nobody gets.
4161
+ */
4162
+ scheduleEncodeAck() {
4163
+ if (this.encodeTimer !== void 0) this.clock.cancel(this.encodeTimer);
4164
+ this.encodeTimer = void 0;
4165
+ const ack = this.encodeAck;
4166
+ if (ack === void 0 || this.closed) return;
4167
+ const gap = this.pending === void 0 ? 1e3 / VIEWER_MAX_FPS : ENCODE_MAX_INTERVAL_MS;
4168
+ const wait = this.lastEncodeAckAt + gap - this.clock.now();
4169
+ if (wait > 0) {
4170
+ this.encodeTimer = this.clock.schedule(() => {
4171
+ this.encodeTimer = void 0;
4172
+ this.scheduleEncodeAck();
4173
+ }, wait);
4174
+ return;
4175
+ }
4176
+ this.encodeAck = void 0;
4177
+ if (this.cdp !== ack.cdp) return;
4178
+ this.lastEncodeAckAt = this.clock.now();
4179
+ ack.cdp.send("Page.screencastFrameAck", { sessionId: ack.sessionId }).catch(() => void 0);
1686
4180
  }
1687
4181
  /**
1688
- * Sends the held screencast frame and acks it (letting Chromium send the next) once the viewer
1689
- * has room for it, the transport is not backed up and the rate cap allows: a frame never follows
1690
- * the previous one sooner than 1000 / VIEWER_MAX_FPS ms, the first after an attach included.
4182
+ * Sends the newest screencast frame once the pacer allows (viewer acks, link time, rate cap)
4183
+ * and the transport is not backed up.
1691
4184
  */
1692
4185
  pump() {
1693
4186
  const pending = this.pending;
1694
4187
  if (pending === void 0 || this.closed || this.draining) return;
1695
- if (this.seq - this.acked >= VIEWER_UNACKED_FRAMES) return;
1696
- const wait = this.lastSentAt + 1e3 / VIEWER_MAX_FPS - this.clock.now();
1697
- if (wait > 0) {
1698
- if (this.pumpTimer === void 0) {
4188
+ const d = this.pacer.decide(this.clock.now());
4189
+ if (!d.ok) {
4190
+ if (d.waitMs !== void 0 && this.pumpTimer === void 0) {
1699
4191
  this.pumpTimer = this.clock.schedule(() => {
1700
4192
  this.pumpTimer = void 0;
1701
4193
  this.pump();
1702
- }, wait);
4194
+ }, d.waitMs);
1703
4195
  }
1704
4196
  return;
1705
4197
  }
1706
4198
  this.pending = void 0;
1707
4199
  if (this.cdp !== pending.cdp) return;
1708
- this.sendFrame(pending.data, pending.width, pending.height);
1709
- pending.cdp.send("Page.screencastFrameAck", { sessionId: pending.sessionId }).catch(() => void 0);
4200
+ this.sendFrame(pending.jpeg, pending.width, pending.height);
4201
+ this.scheduleEncodeAck();
1710
4202
  }
1711
4203
  async mouse(m) {
1712
- const page = await this.browser.activePage();
1713
- if (!Number.isFinite(Number(m.x)) || !Number.isFinite(Number(m.y))) return;
1714
- const x = Math.max(0, Math.min(VIEWPORT.width - 1, Number(m.x)));
1715
- const y = Math.max(0, Math.min(VIEWPORT.height - 1, Number(m.y)));
4204
+ const page = this.shownPage();
4205
+ const p = point(m);
4206
+ if (p === null || page === void 0) return;
4207
+ this.concern(this.browser.tabIdOf(page));
4208
+ const { x, y } = p;
1716
4209
  const button = m.button === "right" ? "right" : "left";
1717
4210
  try {
1718
- if (m.kind === "move") await page.mouse.move(x, y);
1719
- else if (m.kind === "down") {
4211
+ if (m.kind === "down") {
1720
4212
  await page.mouse.move(x, y);
1721
4213
  await page.mouse.down({ button });
4214
+ if (this.driving) this.heldButtons.set(button, page);
4215
+ else await page.mouse.up({ button });
1722
4216
  } else if (m.kind === "up") {
4217
+ this.heldButtons.delete(button);
1723
4218
  await page.mouse.move(x, y);
1724
4219
  await page.mouse.up({ button });
1725
4220
  } else if (m.kind === "wheel") {
1726
4221
  await page.mouse.move(x, y);
1727
4222
  await page.mouse.wheel(Number(m.dx) || 0, Number(m.dy) || 0);
1728
- }
4223
+ } else return;
1729
4224
  } catch {
4225
+ return;
1730
4226
  }
4227
+ if (m.kind !== "down") this.wantCursor(x, y);
1731
4228
  }
1732
4229
  async key(m) {
1733
- const page = await this.browser.activePage();
4230
+ const page = this.shownPage();
4231
+ if (page === void 0) return;
4232
+ this.concern(this.browser.tabIdOf(page));
1734
4233
  try {
1735
4234
  if (m.kind === "char") {
1736
4235
  const text = m.text ?? m.key;
1737
- if (typeof text === "string" && text !== "") await page.keyboard.insertText(text);
1738
- } else if (m.kind === "down") await page.keyboard.down(m.key);
1739
- else if (m.kind === "up") await page.keyboard.up(m.key);
4236
+ if (typeof text === "string" && text !== "")
4237
+ await page.keyboard.insertText(clipCodePoints(text, VIEWER_TEXT_MAX_CHARS));
4238
+ } else if (m.kind === "down") {
4239
+ await page.keyboard.down(m.key);
4240
+ if (this.driving) this.heldKeys.set(m.key, page);
4241
+ else await page.keyboard.up(m.key);
4242
+ } else if (m.kind === "up") {
4243
+ this.heldKeys.delete(m.key);
4244
+ await page.keyboard.up(m.key);
4245
+ }
1740
4246
  } catch {
1741
4247
  }
1742
4248
  }
1743
4249
  };
4250
+ var handoffKey = (h) => `${h.conversationId}\0${h.callId}`;
4251
+ function point(m) {
4252
+ const x = Number(m.x);
4253
+ const y = Number(m.y);
4254
+ if (!Number.isFinite(x) || !Number.isFinite(y)) return null;
4255
+ return {
4256
+ x: Math.max(0, Math.min(VIEWPORT.width - 1, x)),
4257
+ y: Math.max(0, Math.min(VIEWPORT.height - 1, y))
4258
+ };
4259
+ }
1744
4260
 
1745
4261
  // daemon/main.ts
4262
+ var SEALED_EXIT_GRACE_MS = 2e3;
1746
4263
  var SERVICE_WORKSPACE_ENV = "CAPYBARA_SERVICE_WORKSPACE";
4264
+ var BROWSER_CLOSE_GRACE_MS = 3e3;
4265
+ var PROCESS_POLL_MS = 10;
4266
+ var COOKIE_SAVE_MS = 500;
1747
4267
  var enc = new TextEncoder();
1748
4268
  var dec = new TextDecoder();
1749
4269
  var REQUEST_OPS = /* @__PURE__ */ new Set([
@@ -1781,6 +4301,10 @@ function parse(raw) {
1781
4301
  return void 0;
1782
4302
  }
1783
4303
  }
4304
+ var HANDOFF_HOLDS_ROLL_MS = 30 * 6e4;
4305
+ function isRollCheck(body) {
4306
+ return typeof body === "object" && body !== null && body.capybara === JSON.parse(ROLL_CHECK_REQUEST).capybara;
4307
+ }
1784
4308
  function write(sock, value, tooLarge) {
1785
4309
  if (sock.destroyed) return false;
1786
4310
  let framed;
@@ -1812,78 +4336,168 @@ async function startDaemon(opts) {
1812
4336
  let closing = false;
1813
4337
  const sessionFile = new SessionFile(opts.stateDir, clock);
1814
4338
  const saved = sessionFile.read();
4339
+ let live;
1815
4340
  const state = new DaemonState({
1816
4341
  clock,
1817
4342
  ...opts.idleMs === void 0 ? {} : { idleMs: opts.idleMs },
4343
+ ...opts.conversationIdleMs === void 0 ? {} : { conversationIdleMs: opts.conversationIdleMs },
1818
4344
  onIdle: () => {
1819
4345
  sessionFile.forget();
1820
4346
  opts.onIdle?.();
4347
+ },
4348
+ onConversationIdle: (conversationId) => {
4349
+ void live?.closeConversation(conversationId);
1821
4350
  }
1822
4351
  });
1823
- if (saved?.handoff !== void 0)
1824
- state.noticeHandoff(saved.handoff.callId, saved.handoff.message);
4352
+ if (saved !== void 0) sessionFile.restoreState(state, saved);
1825
4353
  const launch = opts.launch ?? launchChromium;
4354
+ const closeGraceMs = opts.browserCloseGraceMs ?? BROWSER_CLOSE_GRACE_MS;
1826
4355
  let current;
4356
+ let running;
1827
4357
  let restored = false;
4358
+ function within2(value, ms) {
4359
+ let timer;
4360
+ return Promise.race([
4361
+ value,
4362
+ new Promise((r) => {
4363
+ timer = clock.schedule(() => r(void 0), ms);
4364
+ })
4365
+ ]).finally(() => clock.cancel(timer));
4366
+ }
1828
4367
  function browser() {
1829
4368
  if (current !== void 0) return current;
4369
+ if (closing) return Promise.reject(new Error("The browser daemon is stopping."));
1830
4370
  const starting = launch(plan).then(async (ctx) => {
4371
+ let pid;
4372
+ let failed = false;
4373
+ try {
4374
+ return await sessionOn(
4375
+ ctx,
4376
+ (id) => {
4377
+ pid = id;
4378
+ },
4379
+ () => failed
4380
+ );
4381
+ } catch (e) {
4382
+ failed = true;
4383
+ await closeOrKill(ctx.close(), () => pid);
4384
+ throw e;
4385
+ }
4386
+ });
4387
+ current = starting;
4388
+ starting.catch(() => {
4389
+ if (current === starting) current = void 0;
4390
+ live = void 0;
4391
+ if (running?.launch === starting) running = void 0;
4392
+ });
4393
+ return starting;
4394
+ async function sessionOn(ctx, setPid, failed) {
4395
+ let gone = false;
1831
4396
  ctx.on("close", () => {
1832
- if (!closing) opts.onBrowserGone?.();
4397
+ gone = true;
4398
+ if (running?.launch === starting) running = void 0;
4399
+ if (!closing && !failed()) opts.onBrowserGone?.();
1833
4400
  });
4401
+ const pid = await within2(browserProcessId(ctx), BROWSER_CLOSE_GRACE_MS);
4402
+ setPid(pid);
4403
+ if (!gone) running = { launch: starting, pid, ctx };
1834
4404
  const workspace = opts.env[SERVICE_WORKSPACE_ENV];
1835
4405
  const session = new BrowserSession(ctx, {
1836
4406
  proxy: plan.proxy,
1837
4407
  clock,
4408
+ usage: state,
1838
4409
  workspace: workspace === void 0 || workspace === "" ? void 0 : workspace,
1839
4410
  downloadsTmp: plan.downloadsTmp,
1840
4411
  downloadMaxBytes: downloadMaxBytes(opts.env),
1841
- ...opts.downloadWaitMs === void 0 ? {} : { downloadWaitMs: opts.downloadWaitMs }
4412
+ ...opts.downloadWaitMs === void 0 ? {} : { downloadWaitMs: opts.downloadWaitMs },
4413
+ ...opts.navigationTimeoutMs === void 0 ? {} : { navigationTimeoutMs: opts.navigationTimeoutMs }
1842
4414
  });
1843
- if (!restored) {
4415
+ if (plan.shippedDir !== void 0)
4416
+ session.note(shippedRevisionNote(plan.shippedDir, browserRevision(plan.build)));
4417
+ if (plan.build === "chromium-headless-shell" && opts.browsersPath === void 0)
4418
+ session.note(HEADLESS_SHELL_NOTE);
4419
+ if (!closing) await restoreCookies(ctx, opts.stateDir);
4420
+ if (!restored && !closing) {
1844
4421
  restored = true;
1845
4422
  if (saved !== void 0) await sessionFile.restoreTabs(session, saved);
1846
4423
  }
1847
- const save = () => sessionFile.save(session, () => state.handoff);
1848
- session.on(save);
1849
- state.onChange(save);
4424
+ if (!closing) {
4425
+ const save = () => sessionFile.save(session, state);
4426
+ session.on(save);
4427
+ state.onChange(save);
4428
+ }
4429
+ if (!failed()) live = session;
1850
4430
  return session;
1851
- });
1852
- current = starting;
1853
- starting.catch(() => {
1854
- if (current === starting) current = void 0;
1855
- });
1856
- return starting;
4431
+ }
4432
+ }
4433
+ async function closeOrKill(closingBrowser, pid) {
4434
+ const done = closingBrowser.then(
4435
+ () => true,
4436
+ () => true
4437
+ );
4438
+ if (await within2(done, closeGraceMs) === true) return;
4439
+ const id = pid();
4440
+ if (id === void 0) return;
4441
+ killChromium(id);
4442
+ await within2(done, closeGraceMs);
1857
4443
  }
1858
4444
  async function launchFailure(e) {
4445
+ if (e instanceof BrowserInstalledError)
4446
+ return { ok: false, error: "restart", message: e.message, blockedHosts: [] };
4447
+ if (plan.unavailable !== void 0) return fail(plan.unavailable);
1859
4448
  const cause = e instanceof Error ? e.message.split("\n")[0] : String(e);
1860
4449
  const proxy = plan.proxy;
1861
4450
  const refused = proxy === void 0 ? [] : (await Promise.all(
1862
- playwrightDownloadHosts(opts.env).map(
1863
- async (h) => await proxyRefuses(proxy, h, 443) ? h : void 0
1864
- )
4451
+ playwrightDownloadHosts(opts.env).map(async (host) => {
4452
+ const layer = await proxyRefusal(proxy, host, 443);
4453
+ return layer === null ? void 0 : { host, layer };
4454
+ })
1865
4455
  )).filter((h) => h !== void 0);
1866
4456
  if (refused.length > 0)
1867
4457
  return {
1868
4458
  ok: false,
1869
4459
  error: "blocked",
1870
- message: `${DOWNLOAD_BLOCKED_PREFIX}${refused.join(", ")}.`,
4460
+ message: `${DOWNLOAD_BLOCKED_PREFIX}${refused.map((r) => r.host).join(", ")}.`,
1871
4461
  blockedHosts: refused
1872
4462
  };
1873
4463
  return fail(
1874
4464
  `The browser could not start in the device: ${cause}. The next browser call tries again.`
1875
4465
  );
1876
4466
  }
4467
+ async function stopBrowser() {
4468
+ const starting = current;
4469
+ if (starting === void 0) return;
4470
+ const r = running?.launch === starting ? running : void 0;
4471
+ const pid = r?.pid;
4472
+ if (r !== void 0) await within2(saveCookies(r.ctx, opts.stateDir), COOKIE_SAVE_MS);
4473
+ await closeOrKill(
4474
+ starting.then(
4475
+ async (session) => {
4476
+ await session.close();
4477
+ if (pid !== void 0) await processGone(pid);
4478
+ },
4479
+ () => void 0
4480
+ ),
4481
+ () => pid
4482
+ );
4483
+ }
4484
+ async function processGone(pid) {
4485
+ while (processAlive(pid)) await new Promise((r) => clock.schedule(r, PROCESS_POLL_MS));
4486
+ }
1877
4487
  const ready = browser().then(() => void 0);
1878
- ready.catch(() => void 0);
4488
+ ready.catch((e) => {
4489
+ if (e instanceof BrowserInstalledError)
4490
+ clock.schedule(() => opts.onSealed?.(), SEALED_EXIT_GRACE_MS);
4491
+ });
1879
4492
  async function handoffOp(req) {
1880
4493
  if (typeof req.callId !== "string" || req.callId === "")
1881
4494
  return fail("The handoff needs a callId.");
4495
+ const conv = req.conversationId;
1882
4496
  if (req.op === "handoff_notice") {
1883
4497
  if (typeof req.message !== "string") return fail("The handoff notice needs a message.");
1884
- state.noticeHandoff(req.callId, req.message);
4498
+ state.noticeHandoff(conv, req.rootConversationId, req.callId, req.message);
1885
4499
  } else {
1886
- state.clearHandoff(req.callId);
4500
+ state.clearHandoff(conv, req.callId);
1887
4501
  if (req.handback === true) state.handback();
1888
4502
  }
1889
4503
  let session;
@@ -1892,15 +4506,38 @@ async function startDaemon(opts) {
1892
4506
  } catch (e) {
1893
4507
  return launchFailure(e);
1894
4508
  }
1895
- return { ok: true, page: await session.pageInfo(await session.activePage()), blockedHosts: [] };
4509
+ const page = session.currentPage(conv);
4510
+ return {
4511
+ ok: true,
4512
+ ...page === void 0 ? {} : { page: await session.pageInfo(page) },
4513
+ blockedHosts: []
4514
+ };
1896
4515
  }
4516
+ const namesConversation = (raw) => {
4517
+ const r = raw;
4518
+ return typeof r.conversationId === "string" && r.conversationId !== "" && typeof r.rootConversationId === "string" && r.rootConversationId !== "";
4519
+ };
1897
4520
  async function handleRequest(raw) {
1898
4521
  if (typeof raw !== "object" || raw === null || !REQUEST_OPS.has(String(raw.op))) {
1899
4522
  return fail("Unknown browser request.");
1900
4523
  }
4524
+ if (!namesConversation(raw)) return fail(NO_CONVERSATION_MESSAGE);
1901
4525
  const req = raw;
4526
+ const conv = req.conversationId;
4527
+ state.requestArrived(conv, req.rootConversationId);
4528
+ let reply;
4529
+ try {
4530
+ reply = await conversationRequest(req);
4531
+ } catch (e) {
4532
+ reply = fail(e instanceof ActionError ? e.message : String(e));
4533
+ } finally {
4534
+ state.requestFinished(conv);
4535
+ }
4536
+ return { ...reply, tabs: { open: live?.countOf(conv) ?? 0, max: MAX_TABS_PER_CONVERSATION } };
4537
+ }
4538
+ async function conversationRequest(req) {
1902
4539
  if (req.op === "handoff_notice" || req.op === "handoff_clear") return handoffOp(req);
1903
- state.dropHandoff();
4540
+ state.dropHandoff(req.conversationId);
1904
4541
  if (state.control === "user" && req.op !== "wait") {
1905
4542
  return { ok: false, error: "taken_over", message: TAKEN_OVER_MESSAGE, blockedHosts: [] };
1906
4543
  }
@@ -1912,7 +4549,7 @@ async function startDaemon(opts) {
1912
4549
  }
1913
4550
  const reply = await session.run(req, { takenOver: () => state.control === "user" });
1914
4551
  if (reply.ok) {
1915
- const since = state.takeHandbackNote();
4552
+ const since = state.takeHandbackNote(req.conversationId);
1916
4553
  if (since !== void 0) reply.userControlledSince = since;
1917
4554
  }
1918
4555
  return reply;
@@ -1922,6 +4559,7 @@ async function startDaemon(opts) {
1922
4559
  sockets.add(sock);
1923
4560
  const decoder = new ServiceMessageDecoder();
1924
4561
  let kind;
4562
+ let context;
1925
4563
  let handled = false;
1926
4564
  let viewer;
1927
4565
  let opened = false;
@@ -1944,42 +4582,68 @@ async function startDaemon(opts) {
1944
4582
  if (kind === void 0) {
1945
4583
  const first = parse(raw);
1946
4584
  if (first?.kind === "request") kind = "request";
1947
- else if (first?.kind === "stream") {
1948
- kind = "stream";
1949
- opened = true;
1950
- state.viewerOpened();
1951
- browser().then(
1952
- (session) => {
1953
- if (sock.destroyed) return;
1954
- viewer = new ViewerSession({
1955
- browser: session,
1956
- state,
1957
- clock,
1958
- frameMaxBytes: frameCap,
1959
- transport: {
1960
- send: (m) => {
1961
- let dropped = false;
1962
- const ok = write(sock, m, () => {
1963
- dropped = true;
1964
- });
1965
- return ok || dropped || sock.destroyed;
1966
- },
1967
- whenDrained: () => new Promise((r) => sock.once("drain", () => r()))
1968
- }
1969
- });
1970
- },
1971
- () => sock.destroy()
1972
- );
1973
- } else sock.destroy();
4585
+ else if (first?.kind === "stream") kind = "stream";
4586
+ else sock.destroy();
4587
+ return;
4588
+ }
4589
+ if (kind === "stream" && context === void 0) {
4590
+ const ctx = parseViewerContext(raw);
4591
+ if (ctx === null) {
4592
+ sock.destroy();
4593
+ return;
4594
+ }
4595
+ context = {
4596
+ conversationId: ctx.conversationId,
4597
+ rootConversationId: ctx.rootConversationId
4598
+ };
4599
+ const viewerContext = context;
4600
+ opened = true;
4601
+ state.viewerOpened();
4602
+ browser().then(
4603
+ (session) => {
4604
+ if (sock.destroyed) return;
4605
+ viewer = new ViewerSession({
4606
+ browser: session,
4607
+ state,
4608
+ conversationId: viewerContext.conversationId,
4609
+ rootConversationId: viewerContext.rootConversationId,
4610
+ clock,
4611
+ frameMaxBytes: frameCap,
4612
+ transport: {
4613
+ send: (m) => {
4614
+ let dropped = false;
4615
+ const ok = write(sock, m, () => {
4616
+ dropped = true;
4617
+ });
4618
+ return ok || dropped || sock.destroyed;
4619
+ },
4620
+ sendFrame: (frame) => {
4621
+ if (sock.destroyed) return true;
4622
+ return sock.write(encodeServiceMessage(frame));
4623
+ },
4624
+ whenDrained: () => new Promise((r) => sock.once("drain", () => r()))
4625
+ }
4626
+ });
4627
+ },
4628
+ () => sock.destroy()
4629
+ );
1974
4630
  return;
1975
4631
  }
1976
4632
  if (kind === "request") {
1977
4633
  if (handled) return;
1978
4634
  handled = true;
4635
+ const body = parse(raw);
4636
+ if (isRollCheck(body)) {
4637
+ const reason = state.control === "user" ? "the person holds control of the browser" : state.handoffs().some((h) => clock.now() - h.since < HANDOFF_HOLDS_ROLL_MS) ? "a handoff to the person is pending" : void 0;
4638
+ write(sock, reason === void 0 ? { busy: false } : { busy: true, reason });
4639
+ sock.end();
4640
+ return;
4641
+ }
1979
4642
  state.requestStarted();
1980
- handleRequest(parse(raw)).catch((e) => fail(e instanceof ActionError ? e.message : String(e))).then((reply) => {
4643
+ handleRequest(body).catch((e) => fail(e instanceof ActionError ? e.message : String(e))).then((reply) => {
1981
4644
  write(sock, reply, () => write(sock, fail(REPLY_TOO_LARGE_MESSAGE), () => void 0));
1982
4645
  sock.end();
4646
+ if (!reply.ok && reply.error === "restart") sock.once("close", () => opts.onSealed?.());
1983
4647
  }).catch(() => sock.destroy()).finally(() => state.requestEnded());
1984
4648
  return;
1985
4649
  }
@@ -1998,7 +4662,7 @@ async function startDaemon(opts) {
1998
4662
  for (const m of msgs) onMessage(m);
1999
4663
  });
2000
4664
  }
2001
- if (existsSync2(opts.socketPath)) unlinkSync(opts.socketPath);
4665
+ if (existsSync2(opts.socketPath)) unlinkSync2(opts.socketPath);
2002
4666
  const server = createServer(onConnection);
2003
4667
  await new Promise((resolve, reject) => {
2004
4668
  server.once("error", reject);
@@ -2019,11 +4683,10 @@ async function startDaemon(opts) {
2019
4683
  server.close(() => r());
2020
4684
  for (const s of sockets) s.destroy();
2021
4685
  });
2022
- const session = await current?.catch(() => void 0);
2023
- await session?.close();
4686
+ await stopBrowser();
2024
4687
  if (existsSync2(opts.socketPath)) {
2025
4688
  try {
2026
- unlinkSync(opts.socketPath);
4689
+ unlinkSync2(opts.socketPath);
2027
4690
  } catch {
2028
4691
  }
2029
4692
  }
@@ -2059,7 +4722,9 @@ async function main() {
2059
4722
  stateDir,
2060
4723
  env: process.env,
2061
4724
  onIdle: () => stop(0, "idle"),
2062
- onBrowserGone: () => stop(1, "Chromium exited")
4725
+ onBrowserGone: () => stop(1, "Chromium exited"),
4726
+ // installed and sealed: the next start runs the browser read only
4727
+ onSealed: () => stop(0, "browser installed and sealed; restart to run it")
2063
4728
  });
2064
4729
  process.stderr.write(`browser daemon: listening on ${socketPath}
2065
4730
  `);