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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  // @capybara-hq/plugin-browser daemon (generated by daemon/build.ts)
2
2
 
3
- // ../../node_modules/.pnpm/@capybara-hq+plugin-sdk@0.1.0-rc.74/node_modules/@capybara-hq/plugin-sdk/dist/device-service.js
3
+ // ../../node_modules/.pnpm/@capybara-hq+plugin-sdk@0.1.0-rc.75/node_modules/@capybara-hq/plugin-sdk/dist/device-service.js
4
4
  var DEVICE_SERVICE_SOCKET_ENV = "CAPYBARA_SERVICE_SOCKET";
5
5
  var DEVICE_SERVICE_STATE_ENV = "CAPYBARA_SERVICE_STATE";
6
6
  var DEVICE_SERVICE_MACH_ENV = "CAPYBARA_SERVICE_MACH";
@@ -69,6 +69,25 @@ var ServiceMessageDecoder = class {
69
69
  return out;
70
70
  }
71
71
  };
72
+ function parseViewerContext(body) {
73
+ let msg;
74
+ try {
75
+ const text = typeof body === "string" ? body : new TextDecoder("utf-8", { fatal: true }).decode(body);
76
+ msg = JSON.parse(text);
77
+ } catch {
78
+ return null;
79
+ }
80
+ if (typeof msg !== "object" || msg === null || Array.isArray(msg))
81
+ return null;
82
+ const { kind, conversationId, rootConversationId } = msg;
83
+ if (kind !== "viewer")
84
+ return null;
85
+ if (typeof conversationId !== "string" || conversationId === "")
86
+ return null;
87
+ if (typeof rootConversationId !== "string" || rootConversationId === "")
88
+ return null;
89
+ return { kind: "viewer", conversationId, rootConversationId };
90
+ }
72
91
 
73
92
  // daemon/main.ts
74
93
  import { chmodSync, existsSync as existsSync2, mkdirSync as mkdirSync2, unlinkSync as unlinkSync2 } from "node:fs";
@@ -159,6 +178,10 @@ function encodeFrame(f) {
159
178
  var DEFAULT_FRAME_MAX_BYTES = 256 * 1024;
160
179
  var HANDOFF_MAX_CHARS = 4096;
161
180
  var MAX_TABS = 10;
181
+ var MAX_TABS_PER_CONVERSATION = 6;
182
+ var CONVERSATION_IDLE_MS = 15 * 6e4;
183
+ var EVICT_MIN_IDLE_MS = 5 * 6e4;
184
+ var NO_CONVERSATION_MESSAGE = "the request names no conversation";
162
185
  var HANDOFF_KEEPALIVE_MS = 24 * 60 * 6e4;
163
186
  var DOWNLOAD_BLOCKED_PREFIX = "The browser could not be downloaded into the device: its network settings block ";
164
187
  var REPLY_TOO_LARGE_MESSAGE = "The reply was too large to send; ask for less (a smaller maxBytes).";
@@ -259,27 +282,35 @@ var systemClock = {
259
282
  schedule: (fn, ms) => setTimeout(fn, ms).unref(),
260
283
  cancel: (h) => clearTimeout(h)
261
284
  };
285
+ var HANDOFF_PARK = "handoff";
286
+ var HANDOFF_PARK_KEY = "";
287
+ var parkId = (kind, key2) => `${kind}\0${key2}`;
262
288
  var DaemonState = class {
263
289
  clock;
264
290
  idleMs;
265
291
  graceMs;
292
+ conversationIdleMs;
266
293
  onIdle;
294
+ onConversationIdle;
267
295
  listeners = /* @__PURE__ */ new Set();
296
+ conversations = /* @__PURE__ */ new Map();
268
297
  viewers = 0;
269
298
  inflight = 0;
270
299
  since;
271
- note;
300
+ /** Conversations the running takeover concerns (told on their next ok reply after it ends). */
301
+ concerned = /* @__PURE__ */ new Set();
302
+ /** Hand back notes not yet told: conversation id to when the takeover began. */
303
+ notes = /* @__PURE__ */ new Map();
272
304
  idleTimer;
273
305
  graceTimer;
274
306
  disposed = false;
275
- pendingHandoff;
276
- /** When the first notice of the pending handoff arrived (the keepalive counts from it). */
277
- handoffSince;
278
307
  constructor(opts) {
279
308
  this.clock = opts.clock ?? systemClock;
280
309
  this.idleMs = opts.idleMs ?? IDLE_STOP_MS;
281
310
  this.graceMs = opts.graceMs ?? TAKEOVER_GRACE_MS;
311
+ this.conversationIdleMs = opts.conversationIdleMs ?? CONVERSATION_IDLE_MS;
282
312
  this.onIdle = opts.onIdle;
313
+ this.onConversationIdle = opts.onConversationIdle ?? (() => void 0);
283
314
  this.armIdle();
284
315
  }
285
316
  get control() {
@@ -295,66 +326,218 @@ var DaemonState = class {
295
326
  get requestsInFlight() {
296
327
  return this.inflight;
297
328
  }
298
- /** Subscribes to control changes; returns the unsubscribe function. */
329
+ /** Subscribes to control, handoff and park changes; returns the unsubscribe function. */
299
330
  onChange(fn) {
300
331
  this.listeners.add(fn);
301
332
  return () => this.listeners.delete(fn);
302
333
  }
303
- /** The pending handoff question (the latest notice), if any. */
304
- get handoff() {
305
- return this.pendingHandoff;
334
+ // ---- conversations
335
+ /** The conversations the daemon keeps state for (tests, the session file). */
336
+ get conversationIds() {
337
+ return [...this.conversations.keys()];
338
+ }
339
+ /** Whether the daemon keeps state for the conversation. */
340
+ known(conversationId) {
341
+ return this.conversations.has(conversationId);
342
+ }
343
+ /** The root of a conversation's tree, when the daemon knows the conversation. */
344
+ rootOf(conversationId) {
345
+ return this.conversations.get(conversationId)?.root;
346
+ }
347
+ entry(conversationId, root) {
348
+ let e = this.conversations.get(conversationId);
349
+ if (e === void 0) {
350
+ e = {
351
+ root,
352
+ inflight: 0,
353
+ lastActiveAt: this.clock.now(),
354
+ pins: 0,
355
+ parks: /* @__PURE__ */ new Map(),
356
+ handoff: void 0,
357
+ idleTimer: void 0
358
+ };
359
+ this.conversations.set(conversationId, e);
360
+ }
361
+ return e;
306
362
  }
307
- /** Records a handoff question; it replaces any earlier one. */
308
- noticeHandoff(callId, message) {
309
- const m = message.length <= HANDOFF_MAX_CHARS ? message : `${message.slice(0, HANDOFF_MAX_CHARS - 1)}\u2026`;
310
- this.pendingHandoff = { callId, message: m };
311
- this.handoffSince ??= this.clock.now();
363
+ /**
364
+ * Records activity of a conversation that is not a request (it gained a tab: a restore, an
365
+ * adopt, a tab the person opened): its idle countdowns start again.
366
+ */
367
+ seen(conversationId, root) {
368
+ const e = this.entry(conversationId, root);
369
+ e.lastActiveAt = this.clock.now();
370
+ this.armConversation(conversationId, e);
371
+ }
372
+ /** A request of the conversation arrived (it is in use until {@link requestFinished}). */
373
+ requestArrived(conversationId, root) {
374
+ const e = this.entry(conversationId, root);
375
+ e.inflight++;
376
+ e.lastActiveAt = this.clock.now();
377
+ this.armConversation(conversationId, e);
378
+ }
379
+ /** The conversation's request got its reply. */
380
+ requestFinished(conversationId) {
381
+ const e = this.conversations.get(conversationId);
382
+ if (e === void 0) return;
383
+ e.inflight = Math.max(0, e.inflight - 1);
384
+ e.lastActiveAt = this.clock.now();
385
+ this.armConversation(conversationId, e);
386
+ }
387
+ /** A viewer pins the conversation (its own, or the owner of the tab it shows). */
388
+ pin(conversationId, root) {
389
+ const e = this.entry(conversationId, root);
390
+ e.pins++;
391
+ this.armConversation(conversationId, e);
392
+ }
393
+ unpin(conversationId) {
394
+ const e = this.conversations.get(conversationId);
395
+ if (e === void 0) return;
396
+ e.pins = Math.max(0, e.pins - 1);
397
+ e.lastActiveAt = this.clock.now();
398
+ this.armConversation(conversationId, e);
399
+ }
400
+ /**
401
+ * Whether the conversation is in use: a request in flight or a conversation park. Adopt of its
402
+ * tabs is refused meanwhile, and the cap eviction skips it.
403
+ */
404
+ busy(conversationId) {
405
+ const e = this.conversations.get(conversationId);
406
+ if (e === void 0) return false;
407
+ if (e.inflight > 0) return true;
408
+ for (const p of e.parks.values()) if (p.tabId === void 0) return true;
409
+ return false;
410
+ }
411
+ /** Whether a viewer pins the conversation. */
412
+ pinned(conversationId) {
413
+ return (this.conversations.get(conversationId)?.pins ?? 0) > 0;
414
+ }
415
+ /** How long the conversation has been without activity (unknown: forever). */
416
+ idleFor(conversationId) {
417
+ const e = this.conversations.get(conversationId);
418
+ return e === void 0 ? Number.POSITIVE_INFINITY : this.clock.now() - e.lastActiveAt;
419
+ }
420
+ /** The last activity of the conversation (unknown: never). */
421
+ lastActiveAt(conversationId) {
422
+ return this.conversations.get(conversationId)?.lastActiveAt ?? Number.NEGATIVE_INFINITY;
423
+ }
424
+ // ---- parks
425
+ /** Starts (or renews the spec of) a park; a park of the same kind and key keeps its start. */
426
+ park(conversationId, root, spec) {
427
+ const e = this.entry(conversationId, root);
428
+ const id = parkId(spec.kind, spec.key);
429
+ const since = e.parks.get(id)?.since ?? this.clock.now();
430
+ e.parks.set(id, { ...spec, since });
431
+ this.armConversation(conversationId, e);
432
+ this.armIdle();
312
433
  this.emit();
434
+ }
435
+ /** Ends a park; an unknown one changes nothing. */
436
+ unpark(conversationId, kind, key2) {
437
+ const e = this.conversations.get(conversationId);
438
+ if (e === void 0 || !e.parks.delete(parkId(kind, key2))) return;
439
+ e.lastActiveAt = this.clock.now();
440
+ this.armConversation(conversationId, e);
313
441
  this.armIdle();
442
+ this.emit();
443
+ }
444
+ /** The conversation's parks. */
445
+ parksOf(conversationId) {
446
+ return [...this.conversations.get(conversationId)?.parks.values() ?? []];
447
+ }
448
+ /** Whether a tab park pins the tab. */
449
+ tabParked(tabId) {
450
+ for (const e of this.conversations.values())
451
+ for (const p of e.parks.values()) if (p.tabId === tabId) return true;
452
+ return false;
453
+ }
454
+ /** Drops the tab parks of a tab that closed. */
455
+ tabClosed(tabId) {
456
+ for (const [conv, e] of this.conversations) {
457
+ let changed = false;
458
+ for (const [id, p] of e.parks) if (p.tabId === tabId) changed = e.parks.delete(id) || changed;
459
+ if (changed) this.armConversation(conv, e);
460
+ }
461
+ this.armIdle();
462
+ }
463
+ // ---- handoffs (a park of kind HANDOFF_PARK)
464
+ /** The tree's or every pending handoff, oldest first. */
465
+ handoffs(root) {
466
+ const out = [];
467
+ for (const [conversationId, e] of this.conversations) {
468
+ if (e.handoff === void 0 || root !== void 0 && e.root !== root) continue;
469
+ const since = e.parks.get(parkId(HANDOFF_PARK, HANDOFF_PARK_KEY))?.since ?? 0;
470
+ out.push({ conversationId, rootConversationId: e.root, ...e.handoff, since });
471
+ }
472
+ return out.sort((a, b) => a.since - b.since);
473
+ }
474
+ /** The conversation's pending handoff, if any. */
475
+ handoffOf(conversationId) {
476
+ return this.conversations.get(conversationId)?.handoff;
477
+ }
478
+ /** Records the conversation's handoff question; it replaces an earlier one of the conversation. */
479
+ noticeHandoff(conversationId, root, callId, message) {
480
+ const m = message.length <= HANDOFF_MAX_CHARS ? message : `${message.slice(0, HANDOFF_MAX_CHARS - 1)}\u2026`;
481
+ const e = this.entry(conversationId, root);
482
+ e.handoff = { callId, message: m };
483
+ this.park(conversationId, root, { kind: HANDOFF_PARK, key: HANDOFF_PARK_KEY, persist: true });
484
+ this.emit();
314
485
  }
315
- /** Clears the pending handoff when it is `callId`'s; a stale clear changes nothing. */
316
- clearHandoff(callId) {
317
- if (this.pendingHandoff?.callId !== callId) return;
318
- this.endHandoff();
486
+ /** Clears the conversation's pending handoff when it is `callId`'s; a stale clear changes nothing. */
487
+ clearHandoff(conversationId, callId) {
488
+ if (this.conversations.get(conversationId)?.handoff?.callId !== callId) return;
489
+ this.endHandoff(conversationId);
319
490
  }
320
491
  /**
321
- * Drops the pending handoff whatever its callId: the next agent tool request means its run has
322
- * moved on (an aborted run never sends handoff_clear). This is device-wide on purpose: a tool
323
- * call from any conversation of the device drops it, since they are all the owner's
324
- * conversations and the browser is one.
492
+ * Drops the conversation's pending handoff whatever its callId: the conversation's next tool
493
+ * request means its run moved on (an aborted run never sends handoff_clear). Other
494
+ * conversations' handoffs stay.
325
495
  */
326
- dropHandoff() {
327
- if (this.pendingHandoff === void 0) return;
328
- this.endHandoff();
329
- }
330
- endHandoff() {
331
- this.pendingHandoff = void 0;
332
- this.handoffSince = void 0;
496
+ dropHandoff(conversationId) {
497
+ if (this.conversations.get(conversationId)?.handoff === void 0) return;
498
+ this.endHandoff(conversationId);
499
+ }
500
+ endHandoff(conversationId) {
501
+ const e = this.conversations.get(conversationId);
502
+ if (e === void 0) return;
503
+ e.handoff = void 0;
504
+ this.unpark(conversationId, HANDOFF_PARK, HANDOFF_PARK_KEY);
333
505
  this.emit();
334
- this.armIdle();
335
506
  }
336
- takeover() {
507
+ // ---- takeover
508
+ /**
509
+ * The person takes control of the browser (every conversation's agent is refused meanwhile).
510
+ * `owners`: the conversations owning a tab now, told on hand back.
511
+ */
512
+ takeover(owners = []) {
337
513
  if (this.since !== void 0) return;
338
514
  this.since = this.clock.now();
339
- this.note = void 0;
515
+ this.concerned = new Set(owners);
340
516
  this.emit();
341
517
  }
518
+ /** The person used a tab of `conversationId` during the takeover: it is told on hand back. */
519
+ concern(conversationId) {
520
+ if (this.since === void 0 || conversationId === void 0) return;
521
+ this.concerned.add(conversationId);
522
+ }
342
523
  handback() {
343
524
  if (this.since === void 0) return;
344
- this.note = this.since;
525
+ for (const c of this.concerned) this.notes.set(c, this.since);
526
+ this.concerned = /* @__PURE__ */ new Set();
345
527
  this.since = void 0;
346
528
  this.clearGrace();
347
529
  this.emit();
348
530
  }
349
531
  /**
350
- * When the last takeover began (ISO), once: the first tool reply after a hand back carries it so
351
- * the agent learns the person drove the browser.
532
+ * When the last takeover that concerned the conversation began (ISO), once: its first ok reply
533
+ * after the hand back carries it so its agent learns the person drove the browser.
352
534
  */
353
- takeHandbackNote() {
354
- const n = this.note;
355
- this.note = void 0;
535
+ takeHandbackNote(conversationId) {
536
+ const n = this.notes.get(conversationId);
537
+ this.notes.delete(conversationId);
356
538
  return n === void 0 ? void 0 : new Date(n).toISOString();
357
539
  }
540
+ // ---- viewers and requests (the daemon's own idle stop)
358
541
  viewerOpened() {
359
542
  this.viewers++;
360
543
  this.clearGrace();
@@ -384,6 +567,10 @@ var DaemonState = class {
384
567
  this.clearGrace();
385
568
  if (this.idleTimer !== void 0) this.clock.cancel(this.idleTimer);
386
569
  this.idleTimer = void 0;
570
+ for (const e of this.conversations.values()) {
571
+ if (e.idleTimer !== void 0) this.clock.cancel(e.idleTimer);
572
+ e.idleTimer = void 0;
573
+ }
387
574
  this.listeners.clear();
388
575
  }
389
576
  emit() {
@@ -394,15 +581,49 @@ var DaemonState = class {
394
581
  this.graceTimer = void 0;
395
582
  }
396
583
  /**
397
- * (Re)starts the idle countdown when nothing is in use; stops it otherwise. A pending handoff
398
- * keeps the daemon running until {@link HANDOFF_KEEPALIVE_MS} after its notice (the person is
399
- * still to answer it); the device's idle suspension may still stop the device sooner.
584
+ * (Re)starts the conversation's idle countdown when it is not in use (no request in flight, no
585
+ * viewer pin, no conversation park); stops it otherwise.
586
+ */
587
+ armConversation(conversationId, e) {
588
+ if (e.idleTimer !== void 0) this.clock.cancel(e.idleTimer);
589
+ e.idleTimer = void 0;
590
+ if (this.disposed || e.pins > 0 || this.busy(conversationId)) return;
591
+ const wait = Math.max(0, e.lastActiveAt + this.conversationIdleMs - this.clock.now());
592
+ e.idleTimer = this.clock.schedule(() => {
593
+ e.idleTimer = void 0;
594
+ this.idleClose(conversationId, e);
595
+ }, wait);
596
+ }
597
+ /** Closes an idle conversation's tabs and deletes what the daemon keeps for it. */
598
+ idleClose(conversationId, e) {
599
+ if (this.conversations.get(conversationId) !== e) return;
600
+ try {
601
+ this.onConversationIdle(conversationId);
602
+ } finally {
603
+ this.notes.delete(conversationId);
604
+ this.concerned.delete(conversationId);
605
+ if (e.parks.size === 0) this.conversations.delete(conversationId);
606
+ }
607
+ }
608
+ /** When the oldest pending park began, if any. */
609
+ oldestPark() {
610
+ let oldest;
611
+ for (const e of this.conversations.values())
612
+ for (const p of e.parks.values())
613
+ if (oldest === void 0 || p.since < oldest) oldest = p.since;
614
+ return oldest;
615
+ }
616
+ /**
617
+ * (Re)starts the idle countdown when nothing is in use; stops it otherwise. Pending parks keep
618
+ * the daemon running until {@link HANDOFF_KEEPALIVE_MS} after the oldest one began (the person
619
+ * is still to answer a handoff); the device's idle suspension may still stop the device sooner.
400
620
  */
401
621
  armIdle() {
402
622
  if (this.idleTimer !== void 0) this.clock.cancel(this.idleTimer);
403
623
  this.idleTimer = void 0;
404
624
  if (this.disposed || this.viewers > 0 || this.inflight > 0) return;
405
- const keepalive = this.handoffSince === void 0 ? 0 : this.handoffSince + HANDOFF_KEEPALIVE_MS - this.clock.now();
625
+ const oldest = this.oldestPark();
626
+ const keepalive = oldest === void 0 ? 0 : oldest + HANDOFF_KEEPALIVE_MS - this.clock.now();
406
627
  this.idleTimer = this.clock.schedule(
407
628
  () => {
408
629
  this.idleTimer = void 0;
@@ -548,6 +769,7 @@ function within(real, root) {
548
769
  var sameFile = (a, b) => a.dev === b.dev && a.ino === b.ino;
549
770
  var REF_RE = /^(f\d+)?e\d+$/;
550
771
  var PROXY_FAILURE_RE = /ERR_TUNNEL_CONNECTION_FAILED|ERR_PROXY_CONNECTION_FAILED/;
772
+ var ERROR_PAGE_INTERRUPT_RE = /is interrupted by another navigation to "chrome-error:/;
551
773
  var ERROR_PAGE_WAIT_MS = 2e3;
552
774
  var isTimeout = (e) => e instanceof Error && e.name === "TimeoutError";
553
775
  var NET_ERROR_MEANINGS = {
@@ -777,6 +999,41 @@ function normalizeUrl(raw) {
777
999
  return url.href;
778
1000
  }
779
1001
  var firstLine = (e) => (e instanceof Error ? e.message : String(e)).split("\n")[0]?.replace(/^[a-zA-Z.]+: /, "") ?? "";
1002
+ var NO_USAGE = {
1003
+ busy: () => false,
1004
+ pinned: () => false,
1005
+ idleFor: () => Number.POSITIVE_INFINITY,
1006
+ lastActiveAt: () => Number.NEGATIVE_INFINITY,
1007
+ tabParked: () => false,
1008
+ tabClosed: () => void 0,
1009
+ seen: () => void 0,
1010
+ known: () => true
1011
+ };
1012
+ function isStartBlank(tab) {
1013
+ return tab.owner === void 0 && tab.url === "about:blank";
1014
+ }
1015
+ var OTHER_TITLE_CHARS = 120;
1016
+ 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.`;
1017
+ var tabInUse = (id) => `Tab ${id} is in use by another conversation right now; retry shortly or open your own tab.`;
1018
+ var tabMoved = (id, title) => `Tab ${id} (${title}) was moved to another conversation.`;
1019
+ var tabEvicted = (id, title) => `Tab ${id} (${title}) was closed to make room for another conversation.`;
1020
+ var CONVERSATION_CAP_MESSAGE = `This conversation has ${MAX_TABS_PER_CONVERSATION} tabs open, the most one conversation keeps; close one first.`;
1021
+ 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.`;
1022
+ function bareUrl(raw) {
1023
+ try {
1024
+ const u = new URL(raw);
1025
+ u.search = "";
1026
+ u.hash = "";
1027
+ return u.href;
1028
+ } catch {
1029
+ return raw.replace(/[?#].*$/s, "");
1030
+ }
1031
+ }
1032
+ function isActing(req) {
1033
+ if (req.op === "handoff_notice" || req.op === "handoff_clear") return false;
1034
+ if (req.op === "tabs") return req.action !== "list" && req.action !== "adopt";
1035
+ return true;
1036
+ }
780
1037
  var BrowserSession = class {
781
1038
  ctx;
782
1039
  proxy;
@@ -814,12 +1071,36 @@ var BrowserSession = class {
814
1071
  collectors = /* @__PURE__ */ new Set();
815
1072
  probes = /* @__PURE__ */ new Map();
816
1073
  reservedDownloads = /* @__PURE__ */ new Set();
817
- unreported = [];
1074
+ /** Notes of a conversation's pages that arrived with none of its requests in flight. */
1075
+ unreported = /* @__PURE__ */ new Map();
1076
+ /** Device notes (no page: the browser build) for the next reply of any conversation. */
1077
+ unreportedAll = [];
818
1078
  nextId = 1;
819
- active;
820
- queue = Promise.resolve();
821
- /** The agent's latest click; `seq` grows with every click (viewers flash only new ones). */
822
- lastClick;
1079
+ /** Each owned tab's owner (an unowned tab has no entry). */
1080
+ owners = /* @__PURE__ */ new Map();
1081
+ /** Each conversation's active tab. */
1082
+ activeOf = /* @__PURE__ */ new Map();
1083
+ /** The action queues, by {@link queueKey}. */
1084
+ queues = /* @__PURE__ */ new Map();
1085
+ /** A conversation's first tab being claimed or opened (shared by its callers meanwhile). */
1086
+ claiming = /* @__PURE__ */ new Map();
1087
+ /** Tab allocations (claim, open, eviction) one at a time across conversations. */
1088
+ allocChain = Promise.resolve();
1089
+ /** Tabs being opened by the session (not yet tracked): they count toward the device cap. */
1090
+ reserved = 0;
1091
+ /**
1092
+ * Tabs of an idle-closed conversation whose close is under way: no conversation owns, claims,
1093
+ * adopts or lists them any more.
1094
+ */
1095
+ closing = /* @__PURE__ */ new Set();
1096
+ /** When an agent request last acted on each tab (the eviction's least recently used tab). */
1097
+ tabUsedAt = /* @__PURE__ */ new Map();
1098
+ /** Order of the conversations' last acting requests (a viewer's default shown tab). */
1099
+ actedSeq = /* @__PURE__ */ new Map();
1100
+ actSeq = 0;
1101
+ usage;
1102
+ /** Each tab's latest agent click; `seq` grows with every click (viewers flash only new ones). */
1103
+ clicks = /* @__PURE__ */ new Map();
823
1104
  clickSeq = 0;
824
1105
  constructor(ctx, opts) {
825
1106
  this.ctx = ctx;
@@ -830,20 +1111,20 @@ var BrowserSession = class {
830
1111
  this.downloadWaitMs = opts.downloadWaitMs ?? DOWNLOAD_WAIT_MS;
831
1112
  this.clock = opts.clock ?? systemClock;
832
1113
  this.navigationTimeoutMs = opts.navigationTimeoutMs ?? NAVIGATION_TIMEOUT_MS;
1114
+ this.usage = opts.usage ?? NO_USAGE;
833
1115
  ctx.setDefaultTimeout(ACTION_TIMEOUT_MS);
834
1116
  ctx.setDefaultNavigationTimeout(this.navigationTimeoutMs);
835
1117
  ctx.on("page", (p) => {
836
- if (!this.ids.has(p) && this.pages.size >= MAX_TABS) {
837
- p.close().catch(() => void 0);
838
- this.note(
839
- `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.`
840
- );
841
- return;
842
- }
1118
+ if (this.ids.has(p)) return;
843
1119
  this.track(p);
844
- this.active = this.ids.get(p);
845
- this.emit({ type: "active" });
846
1120
  this.emit({ type: "state" });
1121
+ queueMicrotask(() => {
1122
+ void this.allocate(async () => {
1123
+ const id = this.ids.get(p);
1124
+ if (id === void 0 || this.owners.has(id) || p.isClosed()) return;
1125
+ if (this.pages.size > MAX_TABS) await p.close().catch(() => void 0);
1126
+ });
1127
+ });
847
1128
  });
848
1129
  for (const p of ctx.pages()) this.track(p);
849
1130
  }
@@ -854,40 +1135,288 @@ var BrowserSession = class {
854
1135
  this.listeners.add(fn);
855
1136
  return () => this.listeners.delete(fn);
856
1137
  }
857
- /** The active tab, opening a blank one when none is left. */
858
- async activePage() {
859
- const cur = this.active === void 0 ? void 0 : this.pages.get(this.active);
860
- if (cur !== void 0 && !cur.isClosed()) return cur;
861
- const first = [...this.pages.values()].find((p2) => !p2.isClosed());
862
- if (first !== void 0) {
863
- this.active = this.ids.get(first);
864
- return first;
865
- }
866
- const p = await this.ctx.newPage();
867
- this.track(p);
868
- this.active = this.ids.get(p);
869
- return p;
870
- }
871
1138
  tabIdOf(page) {
872
1139
  return this.ids.get(page) ?? "";
873
1140
  }
1141
+ /** The live page of a tab, if it is open (and not closing). */
1142
+ pageById(tabId) {
1143
+ const page = tabId === void 0 ? void 0 : this.pages.get(tabId);
1144
+ return page === void 0 || page.isClosed() || this.closing.has(tabId) ? void 0 : page;
1145
+ }
1146
+ /** The open tabs that are not closing, in tab order. */
1147
+ live() {
1148
+ return [...this.pages.entries()].filter(([id, p]) => !p.isClosed() && !this.closing.has(id));
1149
+ }
1150
+ /** A tab's owner, if it has one. */
1151
+ ownerOf(tabId) {
1152
+ return this.owners.get(tabId);
1153
+ }
1154
+ /** The conversations owning a tab now. */
1155
+ owningConversations() {
1156
+ return [...new Set([...this.owners.values()].map((o) => o.owner))];
1157
+ }
1158
+ /** The conversation's tabs in tab order. */
1159
+ tabsOf(conversationId) {
1160
+ return this.live().map(([id]) => id).filter((id) => this.owners.get(id)?.owner === conversationId);
1161
+ }
1162
+ /** How many tabs the conversation owns. */
1163
+ countOf(conversationId) {
1164
+ return this.tabsOf(conversationId).length;
1165
+ }
1166
+ /** The conversation's active tab id, if it has a live one. */
1167
+ activeTabOf(conversationId) {
1168
+ const id = this.activeOf.get(conversationId);
1169
+ return this.pageById(id) === void 0 ? void 0 : id;
1170
+ }
1171
+ /** The conversation's active page, if it has one (never opens a tab). */
1172
+ currentPage(conversationId) {
1173
+ return this.pageById(this.activeOf.get(conversationId));
1174
+ }
1175
+ /** The order of the conversation's last acting request (higher: later; 0: never). */
1176
+ actedOrder(conversationId) {
1177
+ return this.actedSeq.get(conversationId) ?? 0;
1178
+ }
1179
+ /** The tab's latest agent click, if any. */
1180
+ lastClickOf(tabId) {
1181
+ return tabId === void 0 ? void 0 : this.clicks.get(tabId);
1182
+ }
1183
+ /** Whether the tab is loading a document. */
1184
+ isLoading(tabId) {
1185
+ return tabId !== void 0 && this.loadingTabs.has(tabId);
1186
+ }
874
1187
  tabs() {
875
- return [...this.pages.entries()].map(([id, p]) => {
1188
+ return this.live().map(([id, p]) => {
876
1189
  const blocker = this.blockers.get(id);
877
1190
  const icon = this.favicons.get(id)?.data;
1191
+ const o = this.owners.get(id);
878
1192
  return {
879
1193
  id,
880
1194
  title: clip(this.titles.get(id) ?? "", MAX_TITLE_CHARS),
881
1195
  url: clip(p.url(), MAX_URL_CHARS),
882
- active: id === this.active,
1196
+ active: o !== void 0 && this.activeOf.get(o.owner) === id,
1197
+ ...o === void 0 ? {} : { owner: o.owner, root: o.root },
883
1198
  ...blocker === void 0 ? {} : { blocker },
884
1199
  ...icon === void 0 || icon === null ? {} : { favicon: icon }
885
1200
  };
886
1201
  });
887
1202
  }
888
- /** Whether the active tab is loading a document. */
889
- get loading() {
890
- return this.active !== void 0 && this.loadingTabs.has(this.active);
1203
+ /** Makes a tab the conversation's active tab (it must own it). */
1204
+ setActive(conversationId, tabId) {
1205
+ if (this.owners.get(tabId)?.owner !== conversationId) return;
1206
+ if (this.activeOf.get(conversationId) === tabId) return;
1207
+ this.activeOf.set(conversationId, tabId);
1208
+ this.emit({ type: "active", conversationId });
1209
+ this.emit({ type: "state" });
1210
+ }
1211
+ /** Gives a tab to a conversation (owner and root); the previous owner's active moves on. */
1212
+ assign(tabId, to) {
1213
+ const before = this.owners.get(tabId);
1214
+ this.owners.set(tabId, to);
1215
+ if (before !== void 0 && before.owner !== to.owner) this.activeMovedOff(before.owner, tabId);
1216
+ return before;
1217
+ }
1218
+ /**
1219
+ * A conversation lost its tab `tabId` (closed or moved): when it was its active tab, the active
1220
+ * tab becomes its most recently opened remaining tab, or none.
1221
+ */
1222
+ activeMovedOff(conversationId, tabId) {
1223
+ if (this.activeOf.get(conversationId) !== tabId) return;
1224
+ const next = this.tabsOf(conversationId).filter((id) => id !== tabId).at(-1);
1225
+ if (next === void 0) this.activeOf.delete(conversationId);
1226
+ else this.activeOf.set(conversationId, next);
1227
+ this.emit({ type: "active", conversationId });
1228
+ }
1229
+ /** Runs a tab allocation (claim, open, eviction) one at a time across conversations. */
1230
+ allocate(fn) {
1231
+ const run = this.allocChain.then(fn, fn);
1232
+ this.allocChain = run.catch(() => void 0);
1233
+ return run;
1234
+ }
1235
+ /**
1236
+ * The page an acting request of the conversation acts on: its active tab; with no live tab, an
1237
+ * unowned tab it claims, else a new tab (subject to the caps). Callers that find no tab at the
1238
+ * same time share one claim, so the conversation gets exactly one tab.
1239
+ */
1240
+ async pageFor(conversationId, root) {
1241
+ const cur = this.currentPage(conversationId);
1242
+ if (cur !== void 0) return cur;
1243
+ const own = this.tabsOf(conversationId).at(-1);
1244
+ if (own !== void 0) {
1245
+ this.setActive(conversationId, own);
1246
+ const page = this.pageById(own);
1247
+ if (page !== void 0) return page;
1248
+ }
1249
+ let claim = this.claiming.get(conversationId);
1250
+ if (claim === void 0) {
1251
+ claim = this.allocate(async () => {
1252
+ const now = this.currentPage(conversationId) ?? this.pageById(this.tabsOf(conversationId).at(-1));
1253
+ if (now !== void 0) {
1254
+ this.setActive(conversationId, this.tabIdOf(now));
1255
+ return now;
1256
+ }
1257
+ const unowned = this.live().find(
1258
+ ([id]) => !this.owners.has(id) && !this.usage.tabParked(id)
1259
+ );
1260
+ if (unowned !== void 0) {
1261
+ const [id, page] = unowned;
1262
+ this.assign(id, { owner: conversationId, root });
1263
+ this.activeOf.set(conversationId, id);
1264
+ this.emit({ type: "active", conversationId });
1265
+ this.emit({ type: "state" });
1266
+ return page;
1267
+ }
1268
+ return this.openLocked(conversationId, root);
1269
+ }).finally(() => {
1270
+ this.claiming.delete(conversationId);
1271
+ });
1272
+ this.claiming.set(conversationId, claim);
1273
+ }
1274
+ return claim;
1275
+ }
1276
+ /** Opens a new tab for the conversation (the caps apply) and makes it its active tab. */
1277
+ openTab(conversationId, root) {
1278
+ return this.allocate(() => this.openLocked(conversationId, root));
1279
+ }
1280
+ /** {@link openTab} inside the allocation chain. */
1281
+ async openLocked(conversationId, root) {
1282
+ const own = this.countOf(conversationId);
1283
+ if (own >= MAX_TABS_PER_CONVERSATION) throw new ActionError("failed", CONVERSATION_CAP_MESSAGE);
1284
+ if (this.pages.size + this.reserved >= MAX_TABS && !await this.evict(conversationId))
1285
+ throw new ActionError("failed", deviceCapMessage(own));
1286
+ this.reserved++;
1287
+ let page;
1288
+ try {
1289
+ page = await this.ctx.newPage();
1290
+ } finally {
1291
+ this.reserved--;
1292
+ }
1293
+ this.track(page);
1294
+ const id = this.tabIdOf(page);
1295
+ this.assign(id, { owner: conversationId, root });
1296
+ this.activeOf.set(conversationId, id);
1297
+ this.emit({ type: "active", conversationId });
1298
+ this.emit({ type: "state" });
1299
+ return page;
1300
+ }
1301
+ /**
1302
+ * Closes one tab to make room at the device cap: an unowned tab first, else a tab of the least
1303
+ * recently active conversation that is evictable (not in use, not pinned by a viewer, idle for
1304
+ * at least EVICT_MIN_IDLE_MS), its least recently used non-active tab before its active one; tabs
1305
+ * a park pins are skipped. Its owner is told. False when no tab qualifies.
1306
+ */
1307
+ async evict(forConversation) {
1308
+ const live = this.live().filter(([id]) => !this.usage.tabParked(id));
1309
+ const unowned = live.find(([id]) => !this.owners.has(id));
1310
+ if (unowned !== void 0) {
1311
+ await unowned[1].close().catch(() => void 0);
1312
+ return true;
1313
+ }
1314
+ const owners = /* @__PURE__ */ new Set();
1315
+ for (const [id] of live) {
1316
+ const o = this.owners.get(id)?.owner;
1317
+ if (o !== void 0 && o !== forConversation && !this.usage.busy(o) && !this.usage.pinned(o) && this.usage.idleFor(o) >= EVICT_MIN_IDLE_MS)
1318
+ owners.add(o);
1319
+ }
1320
+ const victim = [...owners].sort(
1321
+ (a, b) => this.usage.lastActiveAt(a) - this.usage.lastActiveAt(b)
1322
+ )[0];
1323
+ if (victim === void 0) return false;
1324
+ const active = this.activeOf.get(victim);
1325
+ const used = (id) => this.tabUsedAt.get(id) ?? 0;
1326
+ const [tabId, page] = live.filter(([id]) => this.owners.get(id)?.owner === victim).sort(
1327
+ ([a], [b]) => (a === active ? 1 : 0) - (b === active ? 1 : 0) || used(a) - used(b)
1328
+ )[0] ?? [];
1329
+ if (tabId === void 0 || page === void 0) return false;
1330
+ const title = clip(this.titles.get(tabId) ?? "", OTHER_TITLE_CHARS) || "no title";
1331
+ await page.close().catch(() => void 0);
1332
+ this.noteTo(victim, tabEvicted(tabId, title));
1333
+ return true;
1334
+ }
1335
+ /**
1336
+ * Moves a tab to the conversation and makes it its active tab (the tool's and a viewer's adopt).
1337
+ * `in_use`: its owner has a request in flight or a park (or a park pins the tab); `cap`: the
1338
+ * conversation already owns MAX_TABS_PER_CONVERSATION tabs. The previous owner is told.
1339
+ */
1340
+ adopt(conversationId, root, tabId) {
1341
+ this.tabById(tabId);
1342
+ const before = this.owners.get(tabId);
1343
+ if (before?.owner === conversationId) {
1344
+ this.setActive(conversationId, tabId);
1345
+ return "ok";
1346
+ }
1347
+ if (before !== void 0 && this.usage.busy(before.owner) || this.usage.tabParked(tabId))
1348
+ return "in_use";
1349
+ if (this.countOf(conversationId) >= MAX_TABS_PER_CONVERSATION) return "cap";
1350
+ this.assign(tabId, { owner: conversationId, root });
1351
+ this.activeOf.set(conversationId, tabId);
1352
+ this.usage.seen(conversationId, root);
1353
+ if (before !== void 0) {
1354
+ const title = clip(this.titles.get(tabId) ?? "", OTHER_TITLE_CHARS) || "no title";
1355
+ this.noteTo(before.owner, tabMoved(tabId, title));
1356
+ }
1357
+ this.emit({ type: "active", conversationId });
1358
+ this.emit({ type: "state" });
1359
+ return "ok";
1360
+ }
1361
+ /**
1362
+ * Opens a restored tab for its owner (the first claims the start's blank tab) and starts its
1363
+ * navigation without waiting for it.
1364
+ */
1365
+ async restoreTab(owner, url) {
1366
+ const page = await this.allocate(async () => {
1367
+ const blank = this.live().find(
1368
+ ([id2, p]) => isStartBlank({ owner: this.owners.get(id2)?.owner, url: p.url() })
1369
+ );
1370
+ if (blank !== void 0) {
1371
+ this.assign(blank[0], owner);
1372
+ return blank[1];
1373
+ }
1374
+ this.reserved++;
1375
+ try {
1376
+ const p = await this.ctx.newPage();
1377
+ this.track(p);
1378
+ this.assign(this.tabIdOf(p), owner);
1379
+ return p;
1380
+ } finally {
1381
+ this.reserved--;
1382
+ }
1383
+ });
1384
+ const id = this.tabIdOf(page);
1385
+ if (!this.activeOf.has(owner.owner)) this.activeOf.set(owner.owner, id);
1386
+ this.usage.seen(owner.owner, owner.root);
1387
+ this.emit({ type: "active", conversationId: owner.owner });
1388
+ this.emit({ type: "state" });
1389
+ let target;
1390
+ try {
1391
+ target = normalizeUrl(url);
1392
+ } catch {
1393
+ }
1394
+ if (target !== void 0) void this.viewerNav(page, { url: target });
1395
+ return id;
1396
+ }
1397
+ /**
1398
+ * Closes an idle conversation's tabs (except those a park pins) and forgets what the session
1399
+ * keeps for it.
1400
+ */
1401
+ async closeConversation(conversationId) {
1402
+ const ids = this.tabsOf(conversationId).filter((id) => !this.usage.tabParked(id));
1403
+ for (const id of ids) {
1404
+ this.closing.add(id);
1405
+ this.owners.delete(id);
1406
+ }
1407
+ this.activeOf.delete(conversationId);
1408
+ this.queues.delete(this.queueKey(conversationId));
1409
+ this.unreported.delete(conversationId);
1410
+ this.claiming.delete(conversationId);
1411
+ this.actedSeq.delete(conversationId);
1412
+ await Promise.all(
1413
+ ids.map(
1414
+ (id) => this.pages.get(id)?.close().catch(() => {
1415
+ this.closing.delete(id);
1416
+ })
1417
+ )
1418
+ );
1419
+ this.emit({ type: "state" });
891
1420
  }
892
1421
  emit(e) {
893
1422
  for (const fn of [...this.listeners]) {
@@ -946,38 +1475,75 @@ var BrowserSession = class {
946
1475
  this.emit({ type: "state" });
947
1476
  }
948
1477
  if (this.proxy !== void 0 && PROXY_FAILURE_RE.test(err))
949
- this.checkBlocked(r.url(), this.pageToOpen(page, r));
1478
+ this.checkBlocked(page, r.url(), this.pageToOpen(page, r));
950
1479
  });
951
1480
  page.on("response", (r) => {
952
1481
  if (r.request().isNavigationRequest() && r.frame() === page.mainFrame())
953
1482
  this.docStatus.set(id, r.status());
954
1483
  if (this.proxy !== void 0 && r.status() === 403 && r.url().startsWith("http:")) {
955
- this.checkBlocked(r.url(), this.pageToOpen(page, r.request()));
1484
+ this.checkBlocked(page, r.url(), this.pageToOpen(page, r.request()));
956
1485
  }
957
1486
  });
958
- page.on("dialog", (d) => this.onDialog(d));
959
- page.on("download", (d) => this.onDownload(d));
1487
+ page.on("dialog", (d) => this.onDialog(page, d));
1488
+ page.on("download", (d) => this.onDownload(page, d));
960
1489
  page.on("filechooser", () => {
961
- this.note("The page opened a file chooser; use the upload tool with the file input's ref.");
962
- this.emit({ type: "dialog", kind: "file", message: "" });
1490
+ const o = this.owners.get(id);
1491
+ this.noteTo(
1492
+ o?.owner,
1493
+ "The page opened a file chooser; use the upload tool with the file input's ref."
1494
+ );
1495
+ if (o !== void 0) this.emit({ type: "dialog", kind: "file", message: "", root: o.root });
963
1496
  });
1497
+ page.on("popup", (p) => this.onPopup(page, p));
964
1498
  page.on("close", () => {
965
1499
  this.pendingNavs.delete(page);
966
1500
  this.pages.delete(id);
1501
+ this.closing.delete(id);
967
1502
  this.titles.delete(id);
968
1503
  this.loadingTabs.delete(id);
969
1504
  this.blockers.delete(id);
970
1505
  this.favicons.delete(id);
971
1506
  this.docStatus.delete(id);
972
- if (this.active === id) {
973
- const next = [...this.pages.keys()].at(-1);
974
- this.active = next;
975
- this.emit({ type: "active" });
976
- }
1507
+ this.tabUsedAt.delete(id);
1508
+ this.clicks.delete(id);
1509
+ const o = this.owners.get(id);
1510
+ this.owners.delete(id);
1511
+ if (o !== void 0) this.activeMovedOff(o.owner, id);
1512
+ this.usage.tabClosed(id);
977
1513
  this.emit({ type: "state" });
978
1514
  });
979
1515
  }
980
- onDialog(d) {
1516
+ /**
1517
+ * A page opened a popup: it belongs to the opener's owner and becomes its active tab, as in a
1518
+ * desktop browser (an unowned opener leaves it unowned). Past the conversation's cap it is closed
1519
+ * at once; past the device cap a tab is evicted for it, else it is closed; the owner is told.
1520
+ */
1521
+ onPopup(opener, popup) {
1522
+ this.track(popup);
1523
+ const id = this.tabIdOf(popup);
1524
+ const o = this.owners.get(this.tabIdOf(opener));
1525
+ if (o === void 0 || this.owners.has(id) || popup.isClosed()) return;
1526
+ const closeIt = (why) => {
1527
+ popup.close().catch(() => void 0);
1528
+ this.noteTo(
1529
+ o.owner,
1530
+ `The page opened a popup, but ${why}, so the popup was closed; close a tab and retry if it was needed.`
1531
+ );
1532
+ };
1533
+ if (this.countOf(o.owner) >= MAX_TABS_PER_CONVERSATION) {
1534
+ closeIt(`this conversation keeps at most ${MAX_TABS_PER_CONVERSATION} tabs`);
1535
+ return;
1536
+ }
1537
+ this.assign(id, o);
1538
+ this.activeOf.set(o.owner, id);
1539
+ this.emit({ type: "active", conversationId: o.owner });
1540
+ this.emit({ type: "state" });
1541
+ void this.allocate(async () => {
1542
+ if (popup.isClosed() || this.pages.size <= MAX_TABS) return;
1543
+ if (!await this.evict(o.owner)) closeIt(`the browser keeps at most ${MAX_TABS} tabs`);
1544
+ });
1545
+ }
1546
+ onDialog(page, d) {
981
1547
  const type = d.type();
982
1548
  if (type === "beforeunload") {
983
1549
  d.accept().catch(() => void 0);
@@ -987,24 +1553,50 @@ var BrowserSession = class {
987
1553
  const message = clip(d.message(), MAX_DIALOG_CHARS);
988
1554
  const settle = kind === "alert" ? d.accept() : d.dismiss();
989
1555
  settle.catch(() => void 0);
990
- this.note(
1556
+ const o = this.owners.get(this.tabIdOf(page));
1557
+ this.noteTo(
1558
+ o?.owner,
991
1559
  `The page showed ${kind === "alert" ? "an alert" : `a ${kind}`} dialog: ${JSON.stringify(message)} (${kind === "alert" ? "closed" : "dismissed"}).`
992
1560
  );
993
- this.emit({ type: "dialog", kind, message });
1561
+ if (o !== void 0) this.emit({ type: "dialog", kind, message, root: o.root });
994
1562
  }
995
1563
  /**
996
- * Adds a note to the replies of the requests in flight; with none in flight (a download that
997
- * finished after its click replied, a dialog the person caused) the next reply carries it.
1564
+ * A device note (not about a page: the browser build that runs): the replies of the requests in
1565
+ * flight carry it, else the next reply of any conversation.
998
1566
  */
999
1567
  note(text) {
1000
1568
  const n = clip(text, MAX_DIALOG_CHARS + 200);
1001
1569
  if (this.collectors.size === 0) {
1002
- this.unreported.push(n);
1003
- if (this.unreported.length > MAX_UNREPORTED) this.unreported.shift();
1570
+ this.unreportedAll.push(n);
1571
+ if (this.unreportedAll.length > MAX_UNREPORTED) this.unreportedAll.shift();
1004
1572
  return;
1005
1573
  }
1006
1574
  for (const c of this.collectors) c.notes.push(n);
1007
1575
  }
1576
+ /**
1577
+ * A note for a conversation (about one of its pages): its requests in flight carry it, else its
1578
+ * next reply. A note of an unowned page (`undefined`) reaches nobody.
1579
+ */
1580
+ noteTo(conversationId, text) {
1581
+ if (conversationId === void 0) return;
1582
+ if (this.countOf(conversationId) === 0 && !this.usage.known(conversationId)) return;
1583
+ const n = clip(text, MAX_DIALOG_CHARS + 200);
1584
+ let delivered = false;
1585
+ for (const c of this.collectors) {
1586
+ if (c.conv !== conversationId) continue;
1587
+ c.notes.push(n);
1588
+ delivered = true;
1589
+ }
1590
+ if (delivered) return;
1591
+ const list = this.unreported.get(conversationId) ?? [];
1592
+ list.push(n);
1593
+ if (list.length > MAX_UNREPORTED) list.shift();
1594
+ this.unreported.set(conversationId, list);
1595
+ }
1596
+ /** The owner of a page, if it has one. */
1597
+ ownerOfPage(page) {
1598
+ return page === null || page === void 0 ? void 0 : this.owners.get(this.tabIdOf(page));
1599
+ }
1008
1600
  /**
1009
1601
  * Saves a download into `<workspace>/downloads` under its suggested name (sanitized, numbered
1010
1602
  * when taken). A request in flight waits for it at most `downloadWaitMs`, then says it is still
@@ -1012,12 +1604,14 @@ var BrowserSession = class {
1012
1604
  * cancelled when together they pass `downloadMaxBytes`, so a page cannot fill the disk.
1013
1605
  * Without a workspace the download is cancelled.
1014
1606
  */
1015
- onDownload(d) {
1607
+ onDownload(page, d) {
1016
1608
  const shown = JSON.stringify(clip(d.suggestedFilename(), 300));
1017
1609
  const workspace = this.workspace;
1610
+ const owner = this.ownerOfPage(page)?.owner;
1611
+ const note = (text) => this.noteTo(owner, text);
1018
1612
  if (workspace === void 0) {
1019
1613
  d.cancel().catch(() => void 0);
1020
- this.note(
1614
+ note(
1021
1615
  `The page started a download (${shown}), which was cancelled: the device has no workspace.`
1022
1616
  );
1023
1617
  return;
@@ -1030,20 +1624,20 @@ var BrowserSession = class {
1030
1624
  try {
1031
1625
  const failure = await d.failure();
1032
1626
  if (failure !== null) {
1033
- if (failure !== "canceled") this.note(`The download of ${shown} failed: ${failure}.`);
1627
+ if (failure !== "canceled") note(`The download of ${shown} failed: ${failure}.`);
1034
1628
  return;
1035
1629
  }
1036
1630
  const tmp = await d.path();
1037
1631
  if (statSync(tmp).size > this.downloadMaxBytes) {
1038
- this.note(
1632
+ note(
1039
1633
  `The download of ${shown} was not saved: it is larger than ${this.downloadMaxBytes} bytes.`
1040
1634
  );
1041
1635
  return;
1042
1636
  }
1043
1637
  target = this.saveDownload(workspace, safeFileName(d.suggestedFilename()), tmp);
1044
- this.note(`Downloaded ${shown} to ${target}.`);
1638
+ note(`Downloaded ${shown} to ${target}.`);
1045
1639
  } catch (e) {
1046
- this.note(
1640
+ note(
1047
1641
  `The download of ${shown} was not saved: ${e instanceof ActionError ? e.message : firstLine(e)}`
1048
1642
  );
1049
1643
  } finally {
@@ -1053,7 +1647,7 @@ var BrowserSession = class {
1053
1647
  entry.finished = true;
1054
1648
  }
1055
1649
  })();
1056
- for (const c of this.collectors) c.downloads.push(entry);
1650
+ for (const c of this.collectors) if (c.conv === owner) c.downloads.push(entry);
1057
1651
  }
1058
1652
  /**
1059
1653
  * Copies a finished download from Playwright's private file into `<workspace>/downloads` and
@@ -1152,7 +1746,8 @@ var BrowserSession = class {
1152
1746
  if (bytes > this.downloadMaxBytes) {
1153
1747
  for (const f of names) this.cancelledTmp.add(f);
1154
1748
  for (const d of this.activeDownloads) {
1155
- this.note(
1749
+ this.noteTo(
1750
+ this.ownerOfPage(d.page())?.owner,
1156
1751
  `The download of ${JSON.stringify(clip(d.suggestedFilename(), 300))} was cancelled: downloads in progress passed ${this.downloadMaxBytes} bytes.`
1157
1752
  );
1158
1753
  d.cancel().catch(() => void 0);
@@ -1238,8 +1833,9 @@ var BrowserSession = class {
1238
1833
  * Probes the proxy for the URL's host and reports it when refused; the viewers' `blocked`
1239
1834
  * message carries `pageUrl` (default: the URL itself), the page to open once allowed.
1240
1835
  */
1241
- checkBlocked(rawUrl, pageUrl) {
1836
+ checkBlocked(page, rawUrl, pageUrl) {
1242
1837
  const proxy = this.proxy;
1838
+ const owner = this.ownerOfPage(page);
1243
1839
  if (proxy === void 0) return Promise.resolve(false);
1244
1840
  let url;
1245
1841
  try {
@@ -1249,19 +1845,20 @@ var BrowserSession = class {
1249
1845
  }
1250
1846
  const host = url.hostname;
1251
1847
  const port = Number(url.port || (url.protocol === "https:" ? 443 : 80));
1252
- let probe = this.probes.get(host);
1848
+ const key2 = `${owner?.owner ?? ""}\0${host}`;
1849
+ let probe = this.probes.get(key2);
1253
1850
  if (probe === void 0) {
1254
1851
  probe = proxyRefuses(proxy, host, port).then((refused) => {
1255
- this.probes.delete(host);
1256
- if (refused) {
1257
- for (const c of this.collectors) c.blocked.add(host);
1258
- this.emit({ type: "blocked", host, url: pageUrl ?? url.href });
1852
+ this.probes.delete(key2);
1853
+ if (refused && owner !== void 0) {
1854
+ for (const c of this.collectors) if (c.conv === owner.owner) c.blocked.add(host);
1855
+ this.emit({ type: "blocked", host, url: pageUrl ?? url.href, root: owner.root });
1259
1856
  }
1260
1857
  return refused;
1261
1858
  });
1262
- this.probes.set(host, probe);
1859
+ this.probes.set(key2, probe);
1263
1860
  }
1264
- for (const c of this.collectors) c.pending.push(probe);
1861
+ for (const c of this.collectors) if (c.conv === owner?.owner) c.pending.push(probe);
1265
1862
  return probe;
1266
1863
  }
1267
1864
  /** `value`, or `fallback` when it takes longer than {@link PAGE_QUERY_MS} (never rejects). */
@@ -1278,24 +1875,50 @@ var BrowserSession = class {
1278
1875
  this.clock.cancel(timer);
1279
1876
  }
1280
1877
  }
1281
- /** Runs `fn` one at a time with the other actions (`wait` and the tab list run beside them). */
1282
- serial(fn) {
1283
- const run = this.queue.then(fn, fn);
1284
- this.queue = run.catch(() => void 0);
1878
+ /**
1879
+ * The action queue a conversation's requests run in: one per conversation, so one
1880
+ * conversation's slow navigation does not stall another (ruling 7). Falling back to one
1881
+ * device-wide queue is returning a constant here.
1882
+ */
1883
+ queueKey(conversationId) {
1884
+ return conversationId;
1885
+ }
1886
+ /**
1887
+ * Runs `fn` one at a time with the conversation's other actions (`wait`, the tab list and adopt
1888
+ * run beside them).
1889
+ */
1890
+ serial(conversationId, fn) {
1891
+ const key2 = this.queueKey(conversationId);
1892
+ const run = (this.queues.get(key2) ?? Promise.resolve()).then(fn, fn);
1893
+ const tail = run.catch(() => void 0);
1894
+ this.queues.set(key2, tail);
1895
+ void tail.then(() => {
1896
+ if (this.queues.get(key2) === tail) this.queues.delete(key2);
1897
+ });
1285
1898
  return run;
1286
1899
  }
1287
1900
  /**
1288
- * Runs a tool request; never throws. `takenOver` is checked when a queued request leaves the
1289
- * queue: a takeover that began while it waited refuses it. An action already running is left to
1290
- * finish (stopping it halfway would leave the page in an unknown state).
1901
+ * Runs a tool request of its conversation; never throws. `takenOver` is checked when a queued
1902
+ * request leaves the queue: a takeover that began while it waited refuses it. An action already
1903
+ * running is left to finish (stopping it halfway would leave the page in an unknown state).
1291
1904
  */
1292
1905
  async run(req, opts = {}) {
1293
- const late = this.unreported.splice(0);
1294
- const c = { blocked: /* @__PURE__ */ new Set(), notes: [...late], pending: [], downloads: [] };
1906
+ const conv = req.conversationId;
1907
+ const lateOwn = this.unreported.get(conv) ?? [];
1908
+ this.unreported.delete(conv);
1909
+ const lateAll = this.unreportedAll.splice(0);
1910
+ const c = {
1911
+ conv,
1912
+ blocked: /* @__PURE__ */ new Set(),
1913
+ notes: [...lateAll, ...lateOwn],
1914
+ pending: [],
1915
+ downloads: []
1916
+ };
1295
1917
  this.collectors.add(c);
1296
1918
  let reply;
1297
1919
  try {
1298
- const out = await (req.op === "wait" || req.op === "tabs" && req.action === "list" ? this.exec(req) : this.serial(() => {
1920
+ const beside = req.op === "wait" || req.op === "tabs" && (req.action === "list" || req.action === "adopt");
1921
+ const out = await (beside ? this.exec(req) : this.serial(conv, () => {
1299
1922
  if (opts.takenOver?.() === true)
1300
1923
  throw new ActionError("taken_over", TAKEN_OVER_MESSAGE);
1301
1924
  return this.exec(req);
@@ -1303,8 +1926,12 @@ var BrowserSession = class {
1303
1926
  await this.settleProbes(c);
1304
1927
  await this.settleDownloads(c);
1305
1928
  this.collectors.delete(c);
1306
- const page = await this.activePage();
1307
- const verifying = await this.checkVerification(page, this.tabIdOf(page));
1929
+ const page = this.currentPage(conv);
1930
+ if (page !== void 0 && isActing(req)) {
1931
+ this.tabUsedAt.set(this.tabIdOf(page), this.clock.now());
1932
+ this.actedSeq.set(conv, ++this.actSeq);
1933
+ }
1934
+ const verifying = page === void 0 ? false : await this.checkVerification(page, this.tabIdOf(page));
1308
1935
  const text = [
1309
1936
  ...verifying ? [VERIFICATION_NOTE] : [],
1310
1937
  ...c.notes,
@@ -1312,7 +1939,7 @@ var BrowserSession = class {
1312
1939
  ].join("\n");
1313
1940
  reply = {
1314
1941
  ok: true,
1315
- page: await this.pageInfo(page),
1942
+ ...page === void 0 ? {} : { page: await this.pageInfo(page) },
1316
1943
  blockedHosts: [...c.blocked],
1317
1944
  ...text === "" ? {} : { text },
1318
1945
  ...out.image === void 0 ? {} : { image: out.image }
@@ -1329,7 +1956,9 @@ var BrowserSession = class {
1329
1956
  message = `The device's network settings block ${[...c.blocked].join(", ")}.`;
1330
1957
  }
1331
1958
  reply = { ok: false, error: code, message, blockedHosts: [...c.blocked] };
1332
- this.unreported.unshift(...late);
1959
+ if (lateOwn.length > 0)
1960
+ this.unreported.set(conv, [...lateOwn, ...this.unreported.get(conv) ?? []]);
1961
+ this.unreportedAll.unshift(...lateAll);
1333
1962
  } finally {
1334
1963
  this.collectors.delete(c);
1335
1964
  }
@@ -1485,8 +2114,8 @@ var BrowserSession = class {
1485
2114
  );
1486
2115
  }
1487
2116
  }
1488
- markClick(x, y) {
1489
- this.lastClick = { x, y, seq: ++this.clickSeq };
2117
+ markClick(page, x, y) {
2118
+ this.clicks.set(this.tabIdOf(page), { x, y, seq: ++this.clickSeq });
1490
2119
  }
1491
2120
  async goto(page, url) {
1492
2121
  let res;
@@ -1495,7 +2124,7 @@ var BrowserSession = class {
1495
2124
  const deadline = Date.now() + this.navigationTimeoutMs;
1496
2125
  const watch = new NavWatch(page, url, () => this.pendingNavs.get(page));
1497
2126
  try {
1498
- res = await page.goto(url, { waitUntil: "domcontentloaded" });
2127
+ res = await this.gotoPastLateErrorPage(page, url, watch, deadline);
1499
2128
  } catch (e) {
1500
2129
  const msg = firstLine(e);
1501
2130
  if (msg.includes("Download is starting")) {
@@ -1526,7 +2155,7 @@ var BrowserSession = class {
1526
2155
  } finally {
1527
2156
  watch.dispose();
1528
2157
  }
1529
- if (res?.status() === 403 && await this.checkBlocked(res.url())) {
2158
+ if (res?.status() === 403 && await this.checkBlocked(page, res.url())) {
1530
2159
  throw new ActionError(
1531
2160
  "blocked",
1532
2161
  `The device's network settings block ${new URL(res.url()).hostname}.`
@@ -1534,6 +2163,27 @@ var BrowserSession = class {
1534
2163
  }
1535
2164
  await page.waitForLoadState("load", { timeout: LOAD_GRACE_MS }).catch(() => void 0);
1536
2165
  }
2166
+ /**
2167
+ * `page.goto`, past the late error page of the tab's previous failed or stopped navigation:
2168
+ * Chromium can commit that page after Playwright reported the failure (the Linux full build),
2169
+ * and its commit interrupts a navigation started meanwhile. Then this navigation is followed
2170
+ * when it went on in Chromium, and otherwise started once more (the error page is in now),
2171
+ * within the navigation's own deadline.
2172
+ */
2173
+ async gotoPastLateErrorPage(page, url, watch, deadline) {
2174
+ try {
2175
+ return await page.goto(url, { waitUntil: "domcontentloaded" });
2176
+ } catch (e) {
2177
+ if (!ERROR_PAGE_INTERRUPT_RE.test(firstLine(e))) throw e;
2178
+ const out = await watch.follow(deadline);
2179
+ if (out.kind === "loaded") return out.response;
2180
+ if (out.kind === "failed") throw new Error(`${out.error} at ${out.url}`);
2181
+ return page.goto(url, {
2182
+ waitUntil: "domcontentloaded",
2183
+ timeout: Math.max(1, deadline - Date.now())
2184
+ });
2185
+ }
2186
+ }
1537
2187
  /**
1538
2188
  * The error of a navigation that failed with Chromium's net error `error`: a host the proxy
1539
2189
  * refuses is reported as blocked (`run` turns `original` into the blocked reply); any other net
@@ -1544,7 +2194,7 @@ var BrowserSession = class {
1544
2194
  if (net === void 0 || net === "ERR_ABORTED") return original;
1545
2195
  await this.errorPageCommitted(page);
1546
2196
  if (PROXY_FAILURE_RE.test(error)) {
1547
- if (await this.checkBlocked(url)) return original;
2197
+ if (await this.checkBlocked(page, url)) return original;
1548
2198
  const detail = await this.networkDetail(url);
1549
2199
  return new ActionError(
1550
2200
  "unreachable",
@@ -1630,9 +2280,12 @@ var BrowserSession = class {
1630
2280
  }
1631
2281
  }
1632
2282
  async exec(req) {
2283
+ const conv = req.conversationId;
2284
+ const root = req.rootConversationId;
2285
+ const activePage = () => this.pageFor(conv, root);
1633
2286
  switch (req.op) {
1634
2287
  case "navigate": {
1635
- const page = await this.activePage();
2288
+ const page = await activePage();
1636
2289
  if (req.url !== void 0) {
1637
2290
  await this.goto(page, normalizeUrl(req.url));
1638
2291
  } else if (req.action === "back" || req.action === "forward") {
@@ -1661,40 +2314,40 @@ var BrowserSession = class {
1661
2314
  case "tabs":
1662
2315
  return this.tabsOp(req);
1663
2316
  case "snapshot":
1664
- return { text: await takeSnapshot(await this.activePage()) };
2317
+ return { text: await takeSnapshot(await activePage()) };
1665
2318
  case "click":
1666
2319
  case "hover": {
1667
- const page = await this.activePage();
2320
+ const page = await activePage();
1668
2321
  const loc = await this.locate(page, req.ref);
1669
2322
  if (req.op === "hover") {
1670
2323
  await loc.hover();
1671
2324
  return {};
1672
2325
  }
1673
2326
  const at = await this.centerOf(loc);
1674
- if (at !== void 0) this.markClick(at.x, at.y);
2327
+ if (at !== void 0) this.markClick(page, at.x, at.y);
1675
2328
  await this.settled(page, () => loc.click());
1676
2329
  return {};
1677
2330
  }
1678
2331
  case "type": {
1679
- const page = await this.activePage();
2332
+ const page = await activePage();
1680
2333
  const loc = await this.locate(page, req.ref);
1681
2334
  await loc.fill(req.text);
1682
2335
  if (req.submit === true) await this.settled(page, () => loc.press("Enter"));
1683
2336
  return {};
1684
2337
  }
1685
2338
  case "select": {
1686
- const page = await this.activePage();
2339
+ const page = await activePage();
1687
2340
  const loc = await this.locate(page, req.ref);
1688
2341
  const chosen = await this.settled(page, () => loc.selectOption(req.values));
1689
2342
  return { text: `Selected ${JSON.stringify(chosen)}.` };
1690
2343
  }
1691
2344
  case "press": {
1692
- const page = await this.activePage();
2345
+ const page = await activePage();
1693
2346
  await this.settled(page, () => page.keyboard.press(req.key));
1694
2347
  return {};
1695
2348
  }
1696
2349
  case "scroll": {
1697
- const page = await this.activePage();
2350
+ const page = await activePage();
1698
2351
  if (req.ref !== void 0) {
1699
2352
  const loc = await this.locate(page, req.ref);
1700
2353
  await loc.scrollIntoViewIfNeeded();
@@ -1708,7 +2361,7 @@ var BrowserSession = class {
1708
2361
  return {};
1709
2362
  }
1710
2363
  case "upload": {
1711
- const page = await this.activePage();
2364
+ const page = await activePage();
1712
2365
  const file = this.readUpload(req.path);
1713
2366
  const loc = await this.locate(page, req.ref);
1714
2367
  await loc.setInputFiles(file);
@@ -1716,17 +2369,17 @@ var BrowserSession = class {
1716
2369
  }
1717
2370
  case "click_at":
1718
2371
  case "type_at": {
1719
- const page = await this.activePage();
2372
+ const page = await activePage();
1720
2373
  this.checkPoint(req.x, req.y);
1721
- this.markClick(Math.round(req.x), Math.round(req.y));
2374
+ this.markClick(page, Math.round(req.x), Math.round(req.y));
1722
2375
  await this.settled(page, () => page.mouse.click(req.x, req.y));
1723
2376
  if (req.op === "type_at") await page.keyboard.type(req.text);
1724
2377
  return {};
1725
2378
  }
1726
2379
  case "wait":
1727
- return this.waitOp(req);
2380
+ return this.waitOp(req, await activePage());
1728
2381
  case "screenshot": {
1729
- const page = await this.activePage();
2382
+ const page = await activePage();
1730
2383
  const maxBytes = Math.min(MAX_SCREENSHOT_BYTES, Math.floor(req.maxBytes));
1731
2384
  if (!(maxBytes > 0))
1732
2385
  throw new ActionError("failed", "screenshot needs a positive maxBytes.");
@@ -1757,56 +2410,79 @@ var BrowserSession = class {
1757
2410
  );
1758
2411
  }
1759
2412
  async tabsOp(req) {
2413
+ const conv = req.conversationId;
2414
+ const root = req.rootConversationId;
1760
2415
  switch (req.action) {
1761
- case "list": {
1762
- if (this.pages.size === 0) await this.activePage();
1763
- const lines = await Promise.all(
1764
- [...this.pages.entries()].map(async ([id, p]) => {
1765
- const info = await this.pageInfo(p);
1766
- return `${id}${id === this.active ? " (active)" : ""}: ${info.title || "(no title)"} ${info.url}`;
1767
- })
1768
- );
1769
- return { text: lines.join("\n") };
1770
- }
2416
+ case "list":
2417
+ return { text: await this.listText(conv, root) };
1771
2418
  case "open": {
1772
- const page = await this.openTab();
2419
+ const page = this.countOf(conv) === 0 ? await this.pageFor(conv, root) : await this.openTab(conv, root);
1773
2420
  if (req.url !== void 0) await this.goto(page, normalizeUrl(req.url));
1774
2421
  return {};
1775
2422
  }
1776
2423
  case "switch": {
1777
- const page = this.tabById(req.tabId);
1778
- this.active = req.tabId;
1779
- await page.bringToFront().catch(() => void 0);
1780
- this.emit({ type: "active" });
2424
+ this.ownTab(conv, req.tabId);
2425
+ this.setActive(conv, req.tabId);
1781
2426
  return {};
1782
2427
  }
1783
2428
  case "close": {
1784
- const page = this.tabById(req.tabId);
2429
+ const page = this.ownTab(conv, req.tabId);
1785
2430
  await page.close();
1786
- await this.activePage();
2431
+ return {};
2432
+ }
2433
+ case "adopt": {
2434
+ const id = req.tabId;
2435
+ const result = this.adopt(conv, root, this.tabIdOf(this.tabById(id)));
2436
+ if (result === "in_use") throw new ActionError("failed", tabInUse(id ?? ""));
2437
+ if (result === "cap") throw new ActionError("failed", CONVERSATION_CAP_MESSAGE);
1787
2438
  return {};
1788
2439
  }
1789
2440
  }
1790
- throw new ActionError("failed", "tabs needs an action: list, open, switch or close.");
2441
+ throw new ActionError("failed", "tabs needs an action: list, open, switch, close or adopt.");
1791
2442
  }
1792
- /** Opens a blank tab and makes it active. */
1793
- async openTab() {
1794
- if (this.pages.size >= MAX_TABS) {
1795
- throw new ActionError(
1796
- "failed",
1797
- `The browser has ${MAX_TABS} tabs open, the most it keeps; close one first.`
1798
- );
1799
- }
1800
- const page = await this.ctx.newPage();
1801
- this.track(page);
1802
- this.active = this.ids.get(page);
1803
- this.emit({ type: "active" });
1804
- this.emit({ type: "state" });
2443
+ /** The conversation's own tab `tabId`; another conversation's is refused with what to do. */
2444
+ ownTab(conversationId, tabId) {
2445
+ const page = this.tabById(tabId);
2446
+ if (this.owners.get(tabId)?.owner !== conversationId)
2447
+ throw new ActionError("failed", notYourTab(tabId));
1805
2448
  return page;
1806
2449
  }
2450
+ /**
2451
+ * The tab list of a conversation: its own tabs, then its tree's other tabs, then other trees'
2452
+ * tabs (unowned ones too, but not a blank start tab), with ids, titles clipped to
2453
+ * OTHER_TITLE_CHARS and URLs without query or fragment outside its own; no conversation ids.
2454
+ */
2455
+ async listText(conversationId, root) {
2456
+ const own = [];
2457
+ const tree = [];
2458
+ const device = [];
2459
+ for (const [id, p] of this.live()) {
2460
+ const o = this.owners.get(id);
2461
+ if (o?.owner === conversationId) {
2462
+ const info = await this.pageInfo(p);
2463
+ const active = this.activeOf.get(conversationId) === id ? " (active)" : "";
2464
+ own.push(`${id}${active}: ${info.title || "(no title)"} ${info.url}`);
2465
+ continue;
2466
+ }
2467
+ if (isStartBlank({ owner: o?.owner, url: p.url() })) continue;
2468
+ const title = clip(this.titles.get(id) ?? "", OTHER_TITLE_CHARS) || "(no title)";
2469
+ const line = `${id}: ${title} ${bareUrl(clip(p.url(), MAX_URL_CHARS))}`;
2470
+ if (o !== void 0 && o.root === root) tree.push(line);
2471
+ else device.push(line);
2472
+ }
2473
+ const lines = [...own];
2474
+ if (tree.length > 0) lines.push("Tabs of other conversations in this task:", ...tree);
2475
+ if (device.length > 0) lines.push("Tabs of other conversations on this device:", ...device);
2476
+ if (tree.length + device.length > 0)
2477
+ lines.push(
2478
+ "To use another conversation's tab, call browser_tabs with action adopt and its tabId."
2479
+ );
2480
+ if (lines.length === 0) return "No browser tabs are open.";
2481
+ return lines.join("\n");
2482
+ }
1807
2483
  tabById(tabId) {
1808
- const page = tabId === void 0 ? void 0 : this.pages.get(tabId);
1809
- if (page === void 0 || page.isClosed()) {
2484
+ const page = this.pageById(tabId);
2485
+ if (page === void 0) {
1810
2486
  throw new ActionError(
1811
2487
  "failed",
1812
2488
  `No tab ${JSON.stringify(tabId ?? "")}; list the tabs to see their ids.`
@@ -1814,18 +2490,13 @@ var BrowserSession = class {
1814
2490
  }
1815
2491
  return page;
1816
2492
  }
1817
- /** Makes a tab active (a viewer's tab switch). */
1818
- async switchTo(tabId) {
1819
- const page = this.tabById(tabId);
1820
- this.active = tabId;
1821
- await page.bringToFront().catch(() => void 0);
1822
- this.emit({ type: "active" });
1823
- this.emit({ type: "state" });
2493
+ /** Brings a tab to the front of the window (only a viewer in control decides what is front). */
2494
+ async bringToFront(tabId) {
2495
+ await this.pageById(tabId)?.bringToFront().catch(() => void 0);
1824
2496
  }
1825
- /** Navigates the active tab for a viewer (address bar, back, forward, reload); never throws. */
1826
- async viewerNav(nav) {
2497
+ /** Navigates a tab for a viewer (address bar, back, forward, reload); never throws. */
2498
+ async viewerNav(page, nav) {
1827
2499
  try {
1828
- const page = await this.activePage();
1829
2500
  if (nav.url !== void 0) await this.goto(page, normalizeUrl(nav.url));
1830
2501
  else if (nav.action === "back") await page.goBack();
1831
2502
  else if (nav.action === "forward") await page.goForward();
@@ -1833,10 +2504,9 @@ var BrowserSession = class {
1833
2504
  } catch {
1834
2505
  }
1835
2506
  }
1836
- async waitOp(req) {
2507
+ async waitOp(req, page) {
1837
2508
  const asked = Number(req.timeoutMs);
1838
2509
  const timeout = Number.isFinite(asked) ? Math.max(0, Math.min(MAX_WAIT_MS, Math.floor(asked))) : DEFAULT_WAIT_MS;
1839
- const page = await this.activePage();
1840
2510
  if (req.text !== void 0) {
1841
2511
  await page.getByText(req.text).first().waitFor({ state: "visible", timeout }).catch((e) => {
1842
2512
  throw e instanceof Error && e.name === "TimeoutError" ? new ActionError(
@@ -2228,6 +2898,8 @@ async function restoreCookies(ctx, stateDir) {
2228
2898
  import { readFileSync as readFileSync3, renameSync as renameSync2, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "node:fs";
2229
2899
  import { join as join4 } from "node:path";
2230
2900
  var RESTORE_MAX_AGE_MS = 10 * 6e4;
2901
+ var SESSION_FILE_VERSION = 2;
2902
+ var isId = (v) => typeof v === "string" && v !== "";
2231
2903
  var SessionFile = class {
2232
2904
  file;
2233
2905
  clock;
@@ -2237,7 +2909,7 @@ var SessionFile = class {
2237
2909
  this.file = join4(stateDir, "session.json");
2238
2910
  this.clock = clock;
2239
2911
  }
2240
- /** The saved session when it is recent and well formed; undefined otherwise. */
2912
+ /** The saved session when it is recent, of this format and well formed; undefined otherwise. */
2241
2913
  read() {
2242
2914
  let raw;
2243
2915
  try {
@@ -2246,42 +2918,67 @@ var SessionFile = class {
2246
2918
  return void 0;
2247
2919
  }
2248
2920
  const s = raw;
2249
- if (typeof s !== "object" || s === null || typeof s.savedAt !== "number" || this.clock.now() - s.savedAt > RESTORE_MAX_AGE_MS || !Array.isArray(s.tabs))
2921
+ 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))
2250
2922
  return void 0;
2251
2923
  const tabs = s.tabs.filter(
2252
- (u) => typeof u === "string" && /^https?:\/\//i.test(u)
2253
- );
2254
- const h = s.handoff;
2255
- 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;
2256
- return {
2257
- savedAt: s.savedAt,
2258
- tabs: tabs.slice(0, MAX_TABS),
2259
- active: typeof s.active === "number" ? s.active : 0,
2260
- ...handoff === void 0 ? {} : { handoff }
2261
- };
2924
+ (t) => typeof t === "object" && t !== null && typeof t.url === "string" && /^https?:\/\//i.test(t.url) && isId(t.owner) && isId(t.root)
2925
+ ).slice(0, MAX_TABS).map((t) => ({ url: t.url, owner: t.owner, root: t.root }));
2926
+ const conversations = [];
2927
+ for (const c of s.conversations) {
2928
+ if (typeof c !== "object" || c === null) continue;
2929
+ const x = c;
2930
+ if (!isId(x.id) || !isId(x.root)) continue;
2931
+ const h = x.handoff;
2932
+ 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;
2933
+ const parks = Array.isArray(x.parks) ? x.parks.filter(
2934
+ (p) => typeof p === "object" && p !== null && isId(p.kind) && typeof p.key === "string"
2935
+ ).map((p) => ({ kind: p.kind, key: p.key })) : [];
2936
+ conversations.push({
2937
+ id: x.id,
2938
+ root: x.root,
2939
+ ...typeof x.active === "number" ? { active: x.active } : {},
2940
+ ...handoff === void 0 ? {} : { handoff },
2941
+ ...parks.length === 0 ? {} : { parks }
2942
+ });
2943
+ }
2944
+ return { version: SESSION_FILE_VERSION, savedAt: s.savedAt, tabs, conversations };
2262
2945
  }
2263
2946
  /**
2264
- * Writes the session soon (coalesced): the tabs' URLs and the pending handoff, both read when
2265
- * the write runs.
2947
+ * Writes the session soon (coalesced): the tabs with their owners, and per conversation its
2948
+ * active tab, pending handoff and persistent parks, all read when the write runs.
2266
2949
  */
2267
- save(session, handoffNow) {
2950
+ save(session, state) {
2268
2951
  if (this.queued || this.forgotten) return;
2269
2952
  this.queued = true;
2270
2953
  queueMicrotask(() => {
2271
2954
  this.queued = false;
2272
2955
  if (this.forgotten) return;
2273
- const handoff = handoffNow();
2274
- const all = session.tabs();
2275
- const kept = all.filter((t) => /^https?:\/\//i.test(t.url));
2276
- const active = Math.max(
2277
- 0,
2278
- kept.findIndex((t) => t.active)
2956
+ const kept = session.tabs().filter(
2957
+ (t) => t.owner !== void 0 && t.root !== void 0 && /^https?:\/\//i.test(t.url)
2279
2958
  );
2959
+ const tabs = kept.map((t) => ({ url: t.url, owner: t.owner, root: t.root }));
2960
+ const ids = /* @__PURE__ */ new Set([...kept.map((t) => t.owner), ...state.conversationIds]);
2961
+ const conversations = [];
2962
+ for (const id of ids) {
2963
+ const root = kept.find((t) => t.owner === id)?.root ?? state.rootOf(id);
2964
+ if (root === void 0) continue;
2965
+ const active = kept.findIndex((t) => t.owner === id && t.active);
2966
+ const handoff = state.handoffOf(id);
2967
+ 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 }));
2968
+ if (active < 0 && handoff === void 0 && parks.length === 0) continue;
2969
+ conversations.push({
2970
+ id,
2971
+ root,
2972
+ ...active < 0 ? {} : { active },
2973
+ ...handoff === void 0 ? {} : { handoff },
2974
+ ...parks.length === 0 ? {} : { parks }
2975
+ });
2976
+ }
2280
2977
  const body = {
2978
+ version: SESSION_FILE_VERSION,
2281
2979
  savedAt: this.clock.now(),
2282
- tabs: kept.map((t) => t.url),
2283
- active,
2284
- ...handoff === void 0 ? {} : { handoff }
2980
+ tabs,
2981
+ conversations
2285
2982
  };
2286
2983
  try {
2287
2984
  writeFileSync3(`${this.file}.tmp`, JSON.stringify(body), { mode: 384 });
@@ -2295,23 +2992,32 @@ var SessionFile = class {
2295
2992
  this.forgotten = true;
2296
2993
  rmSync2(this.file, { force: true });
2297
2994
  }
2995
+ /** Gives the conversations their pending handoffs and persistent parks back. */
2996
+ restoreState(state, saved) {
2997
+ for (const c of saved.conversations) {
2998
+ if (c.handoff !== void 0)
2999
+ state.noticeHandoff(c.id, c.root, c.handoff.callId, c.handoff.message);
3000
+ for (const p of c.parks ?? []) state.park(c.id, c.root, { ...p, persist: true });
3001
+ }
3002
+ }
2298
3003
  /**
2299
- * Opens the saved tabs in a browser that has only its first blank tab. The navigations are
2300
- * started, not awaited: the first request after a restart does not wait for every page to load.
3004
+ * Opens the saved tabs, each for its owner, in a browser that has only its first blank tab, and
3005
+ * gives each conversation its active tab back. The navigations are started, not awaited: the
3006
+ * first request after a restart does not wait for every page to load.
2301
3007
  */
2302
3008
  async restoreTabs(session, saved) {
2303
- if (saved.tabs.length === 0) return;
2304
3009
  const ids = [];
2305
- for (const [i, url] of saved.tabs.entries()) {
3010
+ for (const t of saved.tabs) {
2306
3011
  try {
2307
- const page = i === 0 ? await session.activePage() : await session.openTab();
2308
- ids.push(session.tabIdOf(page));
2309
- void session.viewerNav({ url: normalizeUrl(url) });
3012
+ ids.push(await session.restoreTab({ owner: t.owner, root: t.root }, t.url));
2310
3013
  } catch {
3014
+ ids.push(void 0);
2311
3015
  }
2312
3016
  }
2313
- const active = ids[saved.active];
2314
- if (active !== void 0) await session.switchTo(active).catch(() => void 0);
3017
+ for (const c of saved.conversations) {
3018
+ const id = c.active === void 0 ? void 0 : ids[c.active];
3019
+ if (id !== void 0) session.setActive(c.id, id);
3020
+ }
2315
3021
  }
2316
3022
  };
2317
3023
 
@@ -2613,6 +3319,19 @@ var clampDim = (n, max) => typeof n === "number" && Number.isFinite(n) ? Math.ma
2613
3319
  var ViewerSession = class {
2614
3320
  browser;
2615
3321
  state;
3322
+ /** The viewer's conversation and the root of its tree (from the kernel's viewer context). */
3323
+ conv;
3324
+ root;
3325
+ /** The tab the person (or a new handoff) chose to show; cleared when it leaves the tree. */
3326
+ choice;
3327
+ /** The tab shown now (computed with every state). */
3328
+ shown;
3329
+ /** The other conversation the viewer pins because it shows one of its tabs. */
3330
+ pinnedOwner;
3331
+ /** Group keys of the tree's other conversations, in order of first appearance. */
3332
+ groups = /* @__PURE__ */ new Map();
3333
+ /** The tree's handoffs seen so far (a new one moves the shown tab to its conversation). */
3334
+ seenHandoffs = /* @__PURE__ */ new Set();
2616
3335
  out;
2617
3336
  clock;
2618
3337
  frameMaxBytes;
@@ -2674,6 +3393,9 @@ var ViewerSession = class {
2674
3393
  constructor(opts) {
2675
3394
  this.browser = opts.browser;
2676
3395
  this.state = opts.state;
3396
+ this.conv = opts.conversationId;
3397
+ this.root = opts.rootConversationId;
3398
+ this.state.pin(this.conv, this.root);
2677
3399
  this.out = opts.transport;
2678
3400
  this.clock = opts.clock;
2679
3401
  this.frameMaxBytes = opts.frameMaxBytes;
@@ -2694,8 +3416,11 @@ var ViewerSession = class {
2694
3416
  this.browser.on((e) => this.onSession(e)),
2695
3417
  this.state.onChange(() => this.onControl())
2696
3418
  );
3419
+ const pending = this.state.handoffs(this.root);
3420
+ this.seenHandoffs = new Set(pending.map(handoffKey));
3421
+ const newest = pending.at(-1);
3422
+ if (newest !== void 0) this.choice = this.browser.activeTabOf(newest.conversationId);
2697
3423
  this.sendState();
2698
- void this.serial(() => this.attach());
2699
3424
  this.ping();
2700
3425
  return;
2701
3426
  }
@@ -2721,7 +3446,7 @@ var ViewerSession = class {
2721
3446
  return;
2722
3447
  }
2723
3448
  case "takeover":
2724
- this.state.takeover();
3449
+ this.state.takeover(this.browser.owningConversations());
2725
3450
  return;
2726
3451
  case "handback":
2727
3452
  this.inputGen++;
@@ -2735,22 +3460,38 @@ var ViewerSession = class {
2735
3460
  this.input(() => this.key(m));
2736
3461
  return;
2737
3462
  case "nav":
2738
- this.input(
2739
- () => this.browser.viewerNav({
3463
+ this.input(async () => {
3464
+ let page = this.shownPage();
3465
+ if (page === void 0) {
3466
+ if (typeof m.url !== "string") return;
3467
+ page = await this.openOwnTab();
3468
+ if (page === void 0) return;
3469
+ }
3470
+ this.concern(this.browser.tabIdOf(page));
3471
+ await this.browser.viewerNav(page, {
2740
3472
  ...typeof m.url === "string" ? { url: m.url } : {},
2741
3473
  ...m.action === void 0 ? {} : { action: m.action }
2742
- })
2743
- );
3474
+ });
3475
+ });
3476
+ return;
3477
+ case "show":
3478
+ if (typeof m.tabId === "string" && this.inTree(m.tabId)) {
3479
+ this.choice = m.tabId;
3480
+ this.queueState();
3481
+ }
2744
3482
  return;
2745
3483
  case "tab":
3484
+ if (m.action === "adopt") {
3485
+ this.adopt(m.tabId);
3486
+ return;
3487
+ }
2746
3488
  this.input(async () => {
2747
3489
  try {
2748
- if (m.action === "open") await this.browser.openTab();
2749
- else if (m.action === "switch" && m.tabId !== void 0)
2750
- await this.browser.switchTo(m.tabId);
2751
- else if (m.action === "close" && m.tabId !== void 0) {
3490
+ if (m.action === "open") await this.openOwnTab();
3491
+ else if (m.action === "switch" && m.tabId !== void 0) this.switchTo(m.tabId);
3492
+ else if (m.action === "close" && m.tabId !== void 0 && this.inTree(m.tabId)) {
3493
+ this.concern(m.tabId);
2752
3494
  await this.browser.tabById(m.tabId).close();
2753
- await this.browser.activePage();
2754
3495
  }
2755
3496
  } catch {
2756
3497
  }
@@ -2758,6 +3499,69 @@ var ViewerSession = class {
2758
3499
  return;
2759
3500
  }
2760
3501
  }
3502
+ /** Whether a tab belongs to the viewer's tree. */
3503
+ inTree(tabId) {
3504
+ return this.browser.ownerOf(tabId)?.root === this.root && this.browser.pageById(tabId) !== void 0;
3505
+ }
3506
+ /** The shown tab's page, if the tree has one. */
3507
+ shownPage() {
3508
+ return this.browser.pageById(this.shown);
3509
+ }
3510
+ /** The person used a tab during the takeover: its owner gets the hand back note. */
3511
+ concern(tabId) {
3512
+ if (tabId === void 0) return;
3513
+ this.state.concern(this.browser.ownerOf(tabId)?.owner);
3514
+ }
3515
+ /**
3516
+ * A tab the person opens: owned by the viewer's conversation, made its active tab and shown
3517
+ * (the caps apply; a refusal opens nothing).
3518
+ */
3519
+ async openOwnTab() {
3520
+ try {
3521
+ const page = this.browser.countOf(this.conv) === 0 ? await this.browser.pageFor(this.conv, this.root) : await this.browser.openTab(this.conv, this.root);
3522
+ this.state.concern(this.conv);
3523
+ this.choice = void 0;
3524
+ this.queueState();
3525
+ return page;
3526
+ } catch {
3527
+ return void 0;
3528
+ }
3529
+ }
3530
+ /**
3531
+ * Shows a tab of the tree and brings it to the front (a viewer in control decides what is
3532
+ * front). A tab of the viewer's own conversation also becomes its active tab (the person chose
3533
+ * it); another conversation's tab changes only the shown tab, never that agent's active tab.
3534
+ */
3535
+ switchTo(tabId) {
3536
+ if (!this.inTree(tabId)) return;
3537
+ if (this.browser.ownerOf(tabId)?.owner === this.conv) {
3538
+ this.browser.setActive(this.conv, tabId);
3539
+ this.choice = void 0;
3540
+ } else this.choice = tabId;
3541
+ void this.browser.bringToFront(tabId);
3542
+ this.queueState();
3543
+ }
3544
+ /**
3545
+ * Moves another tree's tab (or an unowned one) to the viewer's conversation, as the tool's adopt;
3546
+ * a tab of the viewer's own tree is ignored (inside the tree the person drives tabs without
3547
+ * moving them). A tab whose owner is in use answers the `tab_in_use` notice.
3548
+ */
3549
+ adopt(tabId) {
3550
+ if (typeof tabId !== "string" || this.browser.pageById(tabId) === void 0) return;
3551
+ if (this.browser.ownerOf(tabId)?.root === this.root) return;
3552
+ let result;
3553
+ try {
3554
+ result = this.browser.adopt(this.conv, this.root, tabId);
3555
+ } catch {
3556
+ return;
3557
+ }
3558
+ if (result === "in_use") this.send({ t: "notice", code: "tab_in_use" });
3559
+ else if (result === "cap") this.send({ t: "notice", code: "tab_cap" });
3560
+ else if (result === "ok") {
3561
+ this.choice = void 0;
3562
+ this.queueState();
3563
+ }
3564
+ }
2761
3565
  /**
2762
3566
  * Runs viewer input in arrival order, apart from the screencast chain, and only while the person
2763
3567
  * holds control: input from a viewer in the watch state (the agent drives) is dropped, both when
@@ -2784,7 +3588,8 @@ var ViewerSession = class {
2784
3588
  const slot = { ...p };
2785
3589
  this.input(async () => {
2786
3590
  if (this.moveSlot === slot) this.moveSlot = void 0;
2787
- const page = await this.browser.activePage();
3591
+ const page = this.shownPage();
3592
+ if (page === void 0) return;
2788
3593
  try {
2789
3594
  await page.mouse.move(slot.x, slot.y);
2790
3595
  } catch {
@@ -2843,11 +3648,14 @@ var ViewerSession = class {
2843
3648
  get driving() {
2844
3649
  return !this.closed && this.state.control === "user";
2845
3650
  }
2846
- /** Ends the viewer: stops its screencast and its subscriptions. */
3651
+ /** Ends the viewer: stops its screencast and its subscriptions, and lets go of its pins. */
2847
3652
  async close() {
2848
3653
  if (this.closed) return;
2849
3654
  this.closed = true;
2850
3655
  this.inputGen++;
3656
+ this.state.unpin(this.conv);
3657
+ if (this.pinnedOwner !== void 0) this.state.unpin(this.pinnedOwner);
3658
+ this.pinnedOwner = void 0;
2851
3659
  await this.releaseHeld();
2852
3660
  for (const u of this.unsubscribe.splice(0)) u();
2853
3661
  for (const t of [this.pumpTimer, this.pingTimer, this.encodeTimer])
@@ -2867,8 +3675,18 @@ var ViewerSession = class {
2867
3675
  this.send({ t: "ping", id });
2868
3676
  this.pingTimer = this.clock.schedule(() => this.ping(), VIEWER_PING_MS);
2869
3677
  }
2870
- /** Control changed (takeover, hand back): a new state, and input of the old control dropped. */
3678
+ /**
3679
+ * Control or handoffs changed: a new state; input of the old control dropped; a new handoff of
3680
+ * the tree shows its conversation's active tab.
3681
+ */
2871
3682
  onControl() {
3683
+ const pending = this.state.handoffs(this.root);
3684
+ const fresh = pending.filter((h) => !this.seenHandoffs.has(handoffKey(h))).at(-1);
3685
+ this.seenHandoffs = new Set(pending.map(handoffKey));
3686
+ if (fresh !== void 0) {
3687
+ const tab = this.browser.activeTabOf(fresh.conversationId);
3688
+ if (tab !== void 0) this.choice = tab;
3689
+ }
2872
3690
  const control = this.state.control;
2873
3691
  if (control !== this.lastControl) {
2874
3692
  this.lastControl = control;
@@ -2900,7 +3718,6 @@ var ViewerSession = class {
2900
3718
  const plain = { ...m, tabs: m.tabs.map(({ favicon: _icon, ...t }) => t) };
2901
3719
  if (fits(plain)) return plain;
2902
3720
  m = plain;
2903
- const handoff = m.handoff === void 0 ? {} : { handoff: { ...m.handoff, message: clip(m.handoff.message, 200) } };
2904
3721
  small = {
2905
3722
  ...m,
2906
3723
  tabs: m.tabs.map((t) => ({
@@ -2909,7 +3726,12 @@ var ViewerSession = class {
2909
3726
  url: clip(t.url, 200),
2910
3727
  ...t.blocker === void 0 ? {} : { blocker: { ...t.blocker, url: clip(t.blocker.url, 200) } }
2911
3728
  })),
2912
- ...handoff
3729
+ otherTabs: m.otherTabs.map((t) => ({
3730
+ ...t,
3731
+ title: clip(t.title, 200),
3732
+ url: clip(t.url, 200)
3733
+ })),
3734
+ handoffs: m.handoffs.map((h) => ({ ...h, message: clip(h.message, 200) }))
2913
3735
  };
2914
3736
  } else if (m.t === "dialog") {
2915
3737
  small = { ...m, message: clip(m.message, 200) };
@@ -2936,14 +3758,12 @@ var ViewerSession = class {
2936
3758
  onSession(e) {
2937
3759
  if (e.type === "state") this.queueState();
2938
3760
  else if (e.type === "active") {
3761
+ if (e.conversationId === this.conv) this.choice = void 0;
3762
+ else if (this.shown !== void 0 && this.browser.ownerOf(this.shown)?.owner === e.conversationId)
3763
+ this.choice = this.browser.activeTabOf(e.conversationId);
2939
3764
  this.queueState();
2940
- void this.serial(async () => {
2941
- const page = await this.browser.activePage();
2942
- if (page === this.page) return;
2943
- await this.detach();
2944
- await this.attach();
2945
- });
2946
- } else if (e.type === "blocked") this.send({ t: "blocked", host: e.host, url: e.url });
3765
+ } else if (e.root !== this.root) return;
3766
+ else if (e.type === "blocked") this.send({ t: "blocked", host: e.host, url: e.url });
2947
3767
  else this.send({ t: "dialog", kind: e.kind, message: e.message });
2948
3768
  }
2949
3769
  /** Coalesces bursts of changes into one state message. */
@@ -2955,18 +3775,88 @@ var ViewerSession = class {
2955
3775
  this.sendState();
2956
3776
  });
2957
3777
  }
3778
+ /**
3779
+ * The tab to show: the chosen one while it is in the tree; else the viewer's conversation's
3780
+ * active tab; else the active tab of the tree's conversation that acted last; else the tree's
3781
+ * first tab; none when the tree owns no tab.
3782
+ */
3783
+ computeShown(tree) {
3784
+ if (this.choice !== void 0 && tree.some((t) => t.id === this.choice)) return this.choice;
3785
+ this.choice = void 0;
3786
+ const own = this.browser.activeTabOf(this.conv);
3787
+ if (own !== void 0) return own;
3788
+ let best;
3789
+ for (const owner of new Set(tree.map((t) => t.owner))) {
3790
+ if (owner === void 0) continue;
3791
+ const tab = this.browser.activeTabOf(owner);
3792
+ const order = this.browser.actedOrder(owner);
3793
+ if (tab !== void 0 && (best === void 0 || order > best.order)) best = { tab, order };
3794
+ }
3795
+ return best?.tab ?? tree[0]?.id;
3796
+ }
3797
+ /** Pins the owner of the shown tab (besides the viewer's own conversation). */
3798
+ pinShownOwner() {
3799
+ const owner = this.shown === void 0 ? void 0 : this.browser.ownerOf(this.shown);
3800
+ const next = owner === void 0 || owner.owner === this.conv ? void 0 : owner.owner;
3801
+ if (next === this.pinnedOwner) return;
3802
+ if (next !== void 0 && owner !== void 0) this.state.pin(next, owner.root);
3803
+ if (this.pinnedOwner !== void 0) this.state.unpin(this.pinnedOwner);
3804
+ this.pinnedOwner = next;
3805
+ }
3806
+ groupOf(owner) {
3807
+ if (owner === this.conv || owner === void 0) return "own";
3808
+ let g = this.groups.get(owner);
3809
+ if (g === void 0) {
3810
+ g = `sub${this.groups.size + 1}`;
3811
+ this.groups.set(owner, g);
3812
+ }
3813
+ return g;
3814
+ }
2958
3815
  sendState() {
2959
- const tabs = this.browser.tabs();
2960
- const active = tabs.find((t) => t.active);
2961
- const last = this.browser.lastClick;
3816
+ if (this.closed) return;
3817
+ const all = this.browser.tabs();
3818
+ const tree = all.filter((t) => t.root === this.root);
3819
+ this.shown = this.computeShown(tree);
3820
+ this.pinShownOwner();
3821
+ if (this.browser.pageById(this.shown) !== this.page) {
3822
+ void this.serial(async () => {
3823
+ if (this.browser.pageById(this.shown) === this.page) return;
3824
+ await this.detach();
3825
+ await this.attach();
3826
+ });
3827
+ }
3828
+ const order = /* @__PURE__ */ new Map([["own", 0]]);
3829
+ const tabs = tree.map((t) => {
3830
+ const group = this.groupOf(t.owner);
3831
+ if (!order.has(group)) order.set(group, order.size);
3832
+ return {
3833
+ id: t.id,
3834
+ title: t.title,
3835
+ url: t.url,
3836
+ active: t.id === this.shown,
3837
+ group,
3838
+ ...t.blocker === void 0 ? {} : { blocker: t.blocker },
3839
+ ...t.favicon === void 0 ? {} : { favicon: t.favicon }
3840
+ };
3841
+ });
3842
+ tabs.sort((a, b) => (order.get(a.group) ?? 0) - (order.get(b.group) ?? 0));
3843
+ const shownTab = tree.find((t) => t.id === this.shown);
3844
+ const last = this.browser.lastClickOf(this.shown);
2962
3845
  this.send({
2963
3846
  t: "state",
2964
3847
  tabs,
2965
- loading: this.browser.loading,
2966
- secure: active?.url.startsWith("https:") ?? false,
3848
+ ...this.shown === void 0 ? {} : { shown: this.shown },
3849
+ otherTabs: all.filter((t) => t.root !== this.root && !isStartBlank(t)).map((t) => ({ id: t.id, title: t.title, url: t.url })),
3850
+ loading: this.browser.isLoading(this.shown),
3851
+ secure: shownTab?.url.startsWith("https:") ?? false,
2967
3852
  control: this.state.control,
2968
3853
  ...last === void 0 ? {} : { lastClick: last },
2969
- ...this.state.handoff === void 0 ? {} : { handoff: this.state.handoff }
3854
+ handoffs: this.state.handoffs(this.root).map((h) => ({
3855
+ callId: h.callId,
3856
+ conversationId: h.conversationId,
3857
+ message: h.message,
3858
+ tabIds: this.browser.tabsOf(h.conversationId)
3859
+ }))
2970
3860
  });
2971
3861
  }
2972
3862
  get scale() {
@@ -2978,7 +3868,8 @@ var ViewerSession = class {
2978
3868
  }
2979
3869
  async attach() {
2980
3870
  if (this.closed) return;
2981
- const page = await this.browser.activePage();
3871
+ const page = this.shownPage();
3872
+ if (page === void 0) return;
2982
3873
  const cdp = await this.browser.context.newCDPSession(page);
2983
3874
  this.page = page;
2984
3875
  this.cdp = cdp;
@@ -3108,9 +3999,10 @@ var ViewerSession = class {
3108
3999
  this.scheduleEncodeAck();
3109
4000
  }
3110
4001
  async mouse(m) {
3111
- const page = await this.browser.activePage();
4002
+ const page = this.shownPage();
3112
4003
  const p = point(m);
3113
- if (p === null) return;
4004
+ if (p === null || page === void 0) return;
4005
+ this.concern(this.browser.tabIdOf(page));
3114
4006
  const { x, y } = p;
3115
4007
  const button = m.button === "right" ? "right" : "left";
3116
4008
  try {
@@ -3133,7 +4025,9 @@ var ViewerSession = class {
3133
4025
  if (m.kind !== "down") this.wantCursor(x, y);
3134
4026
  }
3135
4027
  async key(m) {
3136
- const page = await this.browser.activePage();
4028
+ const page = this.shownPage();
4029
+ if (page === void 0) return;
4030
+ this.concern(this.browser.tabIdOf(page));
3137
4031
  try {
3138
4032
  if (m.kind === "char") {
3139
4033
  const text = m.text ?? m.key;
@@ -3151,6 +4045,7 @@ var ViewerSession = class {
3151
4045
  }
3152
4046
  }
3153
4047
  };
4048
+ var handoffKey = (h) => `${h.conversationId}\0${h.callId}`;
3154
4049
  function point(m) {
3155
4050
  const x = Number(m.x);
3156
4051
  const y = Number(m.y);
@@ -3235,16 +4130,20 @@ async function startDaemon(opts) {
3235
4130
  let closing = false;
3236
4131
  const sessionFile = new SessionFile(opts.stateDir, clock);
3237
4132
  const saved = sessionFile.read();
4133
+ let live;
3238
4134
  const state = new DaemonState({
3239
4135
  clock,
3240
4136
  ...opts.idleMs === void 0 ? {} : { idleMs: opts.idleMs },
4137
+ ...opts.conversationIdleMs === void 0 ? {} : { conversationIdleMs: opts.conversationIdleMs },
3241
4138
  onIdle: () => {
3242
4139
  sessionFile.forget();
3243
4140
  opts.onIdle?.();
4141
+ },
4142
+ onConversationIdle: (conversationId) => {
4143
+ void live?.closeConversation(conversationId);
3244
4144
  }
3245
4145
  });
3246
- if (saved?.handoff !== void 0)
3247
- state.noticeHandoff(saved.handoff.callId, saved.handoff.message);
4146
+ if (saved !== void 0) sessionFile.restoreState(state, saved);
3248
4147
  const launch = opts.launch ?? launchChromium;
3249
4148
  const closeGraceMs = opts.browserCloseGraceMs ?? BROWSER_CLOSE_GRACE_MS;
3250
4149
  let current;
@@ -3282,6 +4181,7 @@ async function startDaemon(opts) {
3282
4181
  current = starting;
3283
4182
  starting.catch(() => {
3284
4183
  if (current === starting) current = void 0;
4184
+ live = void 0;
3285
4185
  if (running?.launch === starting) running = void 0;
3286
4186
  });
3287
4187
  return starting;
@@ -3299,6 +4199,7 @@ async function startDaemon(opts) {
3299
4199
  const session = new BrowserSession(ctx, {
3300
4200
  proxy: plan.proxy,
3301
4201
  clock,
4202
+ usage: state,
3302
4203
  workspace: workspace === void 0 || workspace === "" ? void 0 : workspace,
3303
4204
  downloadsTmp: plan.downloadsTmp,
3304
4205
  downloadMaxBytes: downloadMaxBytes(opts.env),
@@ -3315,10 +4216,11 @@ async function startDaemon(opts) {
3315
4216
  if (saved !== void 0) await sessionFile.restoreTabs(session, saved);
3316
4217
  }
3317
4218
  if (!closing) {
3318
- const save = () => sessionFile.save(session, () => state.handoff);
4219
+ const save = () => sessionFile.save(session, state);
3319
4220
  session.on(save);
3320
4221
  state.onChange(save);
3321
4222
  }
4223
+ if (!failed()) live = session;
3322
4224
  return session;
3323
4225
  }
3324
4226
  }
@@ -3383,11 +4285,12 @@ async function startDaemon(opts) {
3383
4285
  async function handoffOp(req) {
3384
4286
  if (typeof req.callId !== "string" || req.callId === "")
3385
4287
  return fail("The handoff needs a callId.");
4288
+ const conv = req.conversationId;
3386
4289
  if (req.op === "handoff_notice") {
3387
4290
  if (typeof req.message !== "string") return fail("The handoff notice needs a message.");
3388
- state.noticeHandoff(req.callId, req.message);
4291
+ state.noticeHandoff(conv, req.rootConversationId, req.callId, req.message);
3389
4292
  } else {
3390
- state.clearHandoff(req.callId);
4293
+ state.clearHandoff(conv, req.callId);
3391
4294
  if (req.handback === true) state.handback();
3392
4295
  }
3393
4296
  let session;
@@ -3396,15 +4299,38 @@ async function startDaemon(opts) {
3396
4299
  } catch (e) {
3397
4300
  return launchFailure(e);
3398
4301
  }
3399
- return { ok: true, page: await session.pageInfo(await session.activePage()), blockedHosts: [] };
4302
+ const page = session.currentPage(conv);
4303
+ return {
4304
+ ok: true,
4305
+ ...page === void 0 ? {} : { page: await session.pageInfo(page) },
4306
+ blockedHosts: []
4307
+ };
3400
4308
  }
4309
+ const namesConversation = (raw) => {
4310
+ const r = raw;
4311
+ return typeof r.conversationId === "string" && r.conversationId !== "" && typeof r.rootConversationId === "string" && r.rootConversationId !== "";
4312
+ };
3401
4313
  async function handleRequest(raw) {
3402
4314
  if (typeof raw !== "object" || raw === null || !REQUEST_OPS.has(String(raw.op))) {
3403
4315
  return fail("Unknown browser request.");
3404
4316
  }
4317
+ if (!namesConversation(raw)) return fail(NO_CONVERSATION_MESSAGE);
3405
4318
  const req = raw;
4319
+ const conv = req.conversationId;
4320
+ state.requestArrived(conv, req.rootConversationId);
4321
+ let reply;
4322
+ try {
4323
+ reply = await conversationRequest(req);
4324
+ } catch (e) {
4325
+ reply = fail(e instanceof ActionError ? e.message : String(e));
4326
+ } finally {
4327
+ state.requestFinished(conv);
4328
+ }
4329
+ return { ...reply, tabs: { open: live?.countOf(conv) ?? 0, max: MAX_TABS_PER_CONVERSATION } };
4330
+ }
4331
+ async function conversationRequest(req) {
3406
4332
  if (req.op === "handoff_notice" || req.op === "handoff_clear") return handoffOp(req);
3407
- state.dropHandoff();
4333
+ state.dropHandoff(req.conversationId);
3408
4334
  if (state.control === "user" && req.op !== "wait") {
3409
4335
  return { ok: false, error: "taken_over", message: TAKEN_OVER_MESSAGE, blockedHosts: [] };
3410
4336
  }
@@ -3416,7 +4342,7 @@ async function startDaemon(opts) {
3416
4342
  }
3417
4343
  const reply = await session.run(req, { takenOver: () => state.control === "user" });
3418
4344
  if (reply.ok) {
3419
- const since = state.takeHandbackNote();
4345
+ const since = state.takeHandbackNote(req.conversationId);
3420
4346
  if (since !== void 0) reply.userControlledSince = since;
3421
4347
  }
3422
4348
  return reply;
@@ -3426,6 +4352,7 @@ async function startDaemon(opts) {
3426
4352
  sockets.add(sock);
3427
4353
  const decoder = new ServiceMessageDecoder();
3428
4354
  let kind;
4355
+ let context;
3429
4356
  let handled = false;
3430
4357
  let viewer;
3431
4358
  let opened = false;
@@ -3448,37 +4375,51 @@ async function startDaemon(opts) {
3448
4375
  if (kind === void 0) {
3449
4376
  const first = parse(raw);
3450
4377
  if (first?.kind === "request") kind = "request";
3451
- else if (first?.kind === "stream") {
3452
- kind = "stream";
3453
- opened = true;
3454
- state.viewerOpened();
3455
- browser().then(
3456
- (session) => {
3457
- if (sock.destroyed) return;
3458
- viewer = new ViewerSession({
3459
- browser: session,
3460
- state,
3461
- clock,
3462
- frameMaxBytes: frameCap,
3463
- transport: {
3464
- send: (m) => {
3465
- let dropped = false;
3466
- const ok = write(sock, m, () => {
3467
- dropped = true;
3468
- });
3469
- return ok || dropped || sock.destroyed;
3470
- },
3471
- sendFrame: (frame) => {
3472
- if (sock.destroyed) return true;
3473
- return sock.write(encodeServiceMessage(frame));
3474
- },
3475
- whenDrained: () => new Promise((r) => sock.once("drain", () => r()))
3476
- }
3477
- });
3478
- },
3479
- () => sock.destroy()
3480
- );
3481
- } else sock.destroy();
4378
+ else if (first?.kind === "stream") kind = "stream";
4379
+ else sock.destroy();
4380
+ return;
4381
+ }
4382
+ if (kind === "stream" && context === void 0) {
4383
+ const ctx = parseViewerContext(raw);
4384
+ if (ctx === null) {
4385
+ sock.destroy();
4386
+ return;
4387
+ }
4388
+ context = {
4389
+ conversationId: ctx.conversationId,
4390
+ rootConversationId: ctx.rootConversationId
4391
+ };
4392
+ const viewerContext = context;
4393
+ opened = true;
4394
+ state.viewerOpened();
4395
+ browser().then(
4396
+ (session) => {
4397
+ if (sock.destroyed) return;
4398
+ viewer = new ViewerSession({
4399
+ browser: session,
4400
+ state,
4401
+ conversationId: viewerContext.conversationId,
4402
+ rootConversationId: viewerContext.rootConversationId,
4403
+ clock,
4404
+ frameMaxBytes: frameCap,
4405
+ transport: {
4406
+ send: (m) => {
4407
+ let dropped = false;
4408
+ const ok = write(sock, m, () => {
4409
+ dropped = true;
4410
+ });
4411
+ return ok || dropped || sock.destroyed;
4412
+ },
4413
+ sendFrame: (frame) => {
4414
+ if (sock.destroyed) return true;
4415
+ return sock.write(encodeServiceMessage(frame));
4416
+ },
4417
+ whenDrained: () => new Promise((r) => sock.once("drain", () => r()))
4418
+ }
4419
+ });
4420
+ },
4421
+ () => sock.destroy()
4422
+ );
3482
4423
  return;
3483
4424
  }
3484
4425
  if (kind === "request") {