@capybara-hq/plugin-browser 0.1.0-rc.7 → 0.1.0-rc.9

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.
@@ -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);
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
+ }
313
461
  this.armIdle();
314
462
  }
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();
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();
485
+ }
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,8 @@ 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 NO_TAB_TO_WAIT_ON = "This conversation has no browser tab to wait on; call browser_navigate to open a page first.";
773
+ var ERROR_PAGE_INTERRUPT_RE = /is interrupted by another navigation to "chrome-error:/;
551
774
  var ERROR_PAGE_WAIT_MS = 2e3;
552
775
  var isTimeout = (e) => e instanceof Error && e.name === "TimeoutError";
553
776
  var NET_ERROR_MEANINGS = {
@@ -777,6 +1000,41 @@ function normalizeUrl(raw) {
777
1000
  return url.href;
778
1001
  }
779
1002
  var firstLine = (e) => (e instanceof Error ? e.message : String(e)).split("\n")[0]?.replace(/^[a-zA-Z.]+: /, "") ?? "";
1003
+ var NO_USAGE = {
1004
+ busy: () => false,
1005
+ pinned: () => false,
1006
+ idleFor: () => Number.POSITIVE_INFINITY,
1007
+ lastActiveAt: () => Number.NEGATIVE_INFINITY,
1008
+ tabParked: () => false,
1009
+ tabClosed: () => void 0,
1010
+ seen: () => void 0,
1011
+ known: () => true
1012
+ };
1013
+ function isStartBlank(tab) {
1014
+ return tab.owner === void 0 && tab.url === "about:blank";
1015
+ }
1016
+ var OTHER_TITLE_CHARS = 120;
1017
+ 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.`;
1018
+ var tabInUse = (id) => `Tab ${id} is in use by another conversation right now; retry shortly or open your own tab.`;
1019
+ var tabMoved = (id, title) => `Tab ${id} (${title}) was moved to another conversation.`;
1020
+ var tabEvicted = (id, title) => `Tab ${id} (${title}) was closed to make room for another conversation.`;
1021
+ var CONVERSATION_CAP_MESSAGE = `This conversation has ${MAX_TABS_PER_CONVERSATION} tabs open, the most one conversation keeps; close one first.`;
1022
+ 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.`;
1023
+ function bareUrl(raw) {
1024
+ try {
1025
+ const u = new URL(raw);
1026
+ u.search = "";
1027
+ u.hash = "";
1028
+ return u.href;
1029
+ } catch {
1030
+ return raw.replace(/[?#].*$/s, "");
1031
+ }
1032
+ }
1033
+ function isActing(req) {
1034
+ if (req.op === "handoff_notice" || req.op === "handoff_clear") return false;
1035
+ if (req.op === "tabs") return req.action !== "list" && req.action !== "adopt";
1036
+ return true;
1037
+ }
780
1038
  var BrowserSession = class {
781
1039
  ctx;
782
1040
  proxy;
@@ -814,14 +1072,39 @@ var BrowserSession = class {
814
1072
  collectors = /* @__PURE__ */ new Set();
815
1073
  probes = /* @__PURE__ */ new Map();
816
1074
  reservedDownloads = /* @__PURE__ */ new Set();
817
- unreported = [];
1075
+ /** Notes of a conversation's pages that arrived with none of its requests in flight. */
1076
+ unreported = /* @__PURE__ */ new Map();
1077
+ /** Device notes (no page: the browser build) for the next reply of any conversation. */
1078
+ unreportedAll = [];
818
1079
  nextId = 1;
819
- active;
820
- queue = Promise.resolve();
821
- /** The blank tab {@link activePage} is opening because none was left. */
822
- opening;
823
- /** The agent's latest click; `seq` grows with every click (viewers flash only new ones). */
824
- lastClick;
1080
+ /** Each owned tab's owner (an unowned tab has no entry). */
1081
+ owners = /* @__PURE__ */ new Map();
1082
+ /** Each conversation's active tab. */
1083
+ activeOf = /* @__PURE__ */ new Map();
1084
+ /** The action queues, by {@link queueKey}. */
1085
+ queues = /* @__PURE__ */ new Map();
1086
+ /** A conversation's first tab being claimed or opened (shared by its callers meanwhile). */
1087
+ claiming = /* @__PURE__ */ new Map();
1088
+ /** Tab allocations (claim, open, eviction) one at a time across conversations. */
1089
+ allocChain = Promise.resolve();
1090
+ /** Tabs being opened by the session (not yet tracked): they count toward the device cap. */
1091
+ reserved = 0;
1092
+ /**
1093
+ * Tabs whose close is under way (an idle-closed conversation's, an evicted one): no
1094
+ * conversation owns, claims, adopts or lists them any more, and the device cap leaves them out.
1095
+ */
1096
+ closing = /* @__PURE__ */ new Set();
1097
+ /** When an agent request last acted on each tab (the eviction's least recently used tab). */
1098
+ tabUsedAt = /* @__PURE__ */ new Map();
1099
+ /** When each tab went to its owner (the next active tab after a loss is the newest). */
1100
+ gainedAt = /* @__PURE__ */ new Map();
1101
+ gainSeq = 0;
1102
+ /** Order of the conversations' last acting requests (a viewer's default shown tab). */
1103
+ actedSeq = /* @__PURE__ */ new Map();
1104
+ actSeq = 0;
1105
+ usage;
1106
+ /** Each tab's latest agent click; `seq` grows with every click (viewers flash only new ones). */
1107
+ clicks = /* @__PURE__ */ new Map();
825
1108
  clickSeq = 0;
826
1109
  constructor(ctx, opts) {
827
1110
  this.ctx = ctx;
@@ -832,20 +1115,20 @@ var BrowserSession = class {
832
1115
  this.downloadWaitMs = opts.downloadWaitMs ?? DOWNLOAD_WAIT_MS;
833
1116
  this.clock = opts.clock ?? systemClock;
834
1117
  this.navigationTimeoutMs = opts.navigationTimeoutMs ?? NAVIGATION_TIMEOUT_MS;
1118
+ this.usage = opts.usage ?? NO_USAGE;
835
1119
  ctx.setDefaultTimeout(ACTION_TIMEOUT_MS);
836
1120
  ctx.setDefaultNavigationTimeout(this.navigationTimeoutMs);
837
1121
  ctx.on("page", (p) => {
838
- if (!this.ids.has(p) && this.pages.size >= MAX_TABS) {
839
- p.close().catch(() => void 0);
840
- this.note(
841
- `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.`
842
- );
843
- return;
844
- }
1122
+ if (this.ids.has(p)) return;
845
1123
  this.track(p);
846
- this.active = this.ids.get(p);
847
- this.emit({ type: "active" });
848
1124
  this.emit({ type: "state" });
1125
+ queueMicrotask(() => {
1126
+ void this.allocate(async () => {
1127
+ const id = this.ids.get(p);
1128
+ if (id === void 0 || this.owners.has(id) || p.isClosed()) return;
1129
+ if (this.live().length > MAX_TABS) await p.close().catch(() => void 0);
1130
+ });
1131
+ });
849
1132
  });
850
1133
  for (const p of ctx.pages()) this.track(p);
851
1134
  }
@@ -856,55 +1139,312 @@ var BrowserSession = class {
856
1139
  this.listeners.add(fn);
857
1140
  return () => this.listeners.delete(fn);
858
1141
  }
859
- /**
860
- * The active tab, opening a blank one when none is left. Callers that find no tab at the same
861
- * time (two quick closes of the last tabs, a viewer's frame and a request) share that one
862
- * opening, so the last close leaves exactly one blank tab.
863
- */
864
- async activePage() {
865
- const cur = this.active === void 0 ? void 0 : this.pages.get(this.active);
866
- if (cur !== void 0 && !cur.isClosed()) return cur;
867
- const first = [...this.pages.values()].find((p) => !p.isClosed());
868
- if (first !== void 0) {
869
- this.active = this.ids.get(first);
870
- return first;
871
- }
872
- this.opening ??= this.ctx.newPage().then(
873
- (p) => {
874
- this.opening = void 0;
875
- this.track(p);
876
- this.active = this.ids.get(p);
877
- this.emit({ type: "active" });
878
- this.emit({ type: "state" });
879
- return p;
880
- },
881
- (e) => {
882
- this.opening = void 0;
883
- throw e;
884
- }
885
- );
886
- return this.opening;
887
- }
888
1142
  tabIdOf(page) {
889
1143
  return this.ids.get(page) ?? "";
890
1144
  }
1145
+ /** The live page of a tab, if it is open (and not closing). */
1146
+ pageById(tabId) {
1147
+ const page = tabId === void 0 ? void 0 : this.pages.get(tabId);
1148
+ return page === void 0 || page.isClosed() || this.closing.has(tabId) ? void 0 : page;
1149
+ }
1150
+ /** The open tabs that are not closing, in tab order. */
1151
+ live() {
1152
+ return [...this.pages.entries()].filter(([id, p]) => !p.isClosed() && !this.closing.has(id));
1153
+ }
1154
+ /** A tab's owner, if it has one. */
1155
+ ownerOf(tabId) {
1156
+ return this.owners.get(tabId);
1157
+ }
1158
+ /** The conversations owning a tab now. */
1159
+ owningConversations() {
1160
+ return [...new Set([...this.owners.values()].map((o) => o.owner))];
1161
+ }
1162
+ /** The conversation's tabs in tab order. */
1163
+ tabsOf(conversationId) {
1164
+ return this.live().map(([id]) => id).filter((id) => this.owners.get(id)?.owner === conversationId);
1165
+ }
1166
+ /** How many tabs the conversation owns. */
1167
+ countOf(conversationId) {
1168
+ return this.tabsOf(conversationId).length;
1169
+ }
1170
+ /** The conversation's active tab id, if it has a live one. */
1171
+ activeTabOf(conversationId) {
1172
+ const id = this.activeOf.get(conversationId);
1173
+ return this.pageById(id) === void 0 ? void 0 : id;
1174
+ }
1175
+ /** The conversation's active page, if it has one (never opens a tab). */
1176
+ currentPage(conversationId) {
1177
+ return this.pageById(this.activeOf.get(conversationId));
1178
+ }
1179
+ /** The order of the conversation's last acting request (higher: later; 0: never). */
1180
+ actedOrder(conversationId) {
1181
+ return this.actedSeq.get(conversationId) ?? 0;
1182
+ }
1183
+ /** The tab's latest agent click, if any. */
1184
+ lastClickOf(tabId) {
1185
+ return tabId === void 0 ? void 0 : this.clicks.get(tabId);
1186
+ }
1187
+ /** Whether the tab is loading a document. */
1188
+ isLoading(tabId) {
1189
+ return tabId !== void 0 && this.loadingTabs.has(tabId);
1190
+ }
891
1191
  tabs() {
892
- return [...this.pages.entries()].map(([id, p]) => {
1192
+ return this.live().map(([id, p]) => {
893
1193
  const blocker = this.blockers.get(id);
894
1194
  const icon = this.favicons.get(id)?.data;
1195
+ const o = this.owners.get(id);
895
1196
  return {
896
1197
  id,
897
1198
  title: clip(this.titles.get(id) ?? "", MAX_TITLE_CHARS),
898
1199
  url: clip(p.url(), MAX_URL_CHARS),
899
- active: id === this.active,
1200
+ active: o !== void 0 && this.activeOf.get(o.owner) === id,
1201
+ ...o === void 0 ? {} : { owner: o.owner, root: o.root },
900
1202
  ...blocker === void 0 ? {} : { blocker },
901
1203
  ...icon === void 0 || icon === null ? {} : { favicon: icon }
902
1204
  };
903
1205
  });
904
1206
  }
905
- /** Whether the active tab is loading a document. */
906
- get loading() {
907
- return this.active !== void 0 && this.loadingTabs.has(this.active);
1207
+ /** Makes a tab the conversation's active tab (it must own it). */
1208
+ setActive(conversationId, tabId) {
1209
+ if (this.owners.get(tabId)?.owner !== conversationId) return;
1210
+ if (this.activeOf.get(conversationId) === tabId) return;
1211
+ this.activeOf.set(conversationId, tabId);
1212
+ this.emit({ type: "active", conversationId });
1213
+ this.emit({ type: "state" });
1214
+ }
1215
+ /** Gives a tab to a conversation (owner and root); the previous owner's active moves on. */
1216
+ assign(tabId, to) {
1217
+ const before = this.owners.get(tabId);
1218
+ this.owners.set(tabId, to);
1219
+ this.gainedAt.set(tabId, ++this.gainSeq);
1220
+ if (before !== void 0 && before.owner !== to.owner) this.activeMovedOff(before.owner, tabId);
1221
+ return before;
1222
+ }
1223
+ /**
1224
+ * A conversation lost its tab `tabId` (closed or moved): when it was its active tab, the active
1225
+ * tab becomes its most recently opened remaining tab, or none.
1226
+ */
1227
+ activeMovedOff(conversationId, tabId) {
1228
+ if (this.activeOf.get(conversationId) !== tabId) return;
1229
+ const next = this.newestTabOf(conversationId, tabId);
1230
+ if (next === void 0) this.activeOf.delete(conversationId);
1231
+ else this.activeOf.set(conversationId, next);
1232
+ this.emit({ type: "active", conversationId });
1233
+ }
1234
+ /**
1235
+ * The conversation's tab it gained last (opened, claimed, adopted or restored), besides
1236
+ * `except`.
1237
+ */
1238
+ newestTabOf(conversationId, except) {
1239
+ let best;
1240
+ for (const id of this.tabsOf(conversationId)) {
1241
+ if (id === except) continue;
1242
+ if (best === void 0 || (this.gainedAt.get(id) ?? 0) > (this.gainedAt.get(best) ?? 0))
1243
+ best = id;
1244
+ }
1245
+ return best;
1246
+ }
1247
+ /** Runs a tab allocation (claim, open, eviction) one at a time across conversations. */
1248
+ allocate(fn) {
1249
+ const run = this.allocChain.then(fn, fn);
1250
+ this.allocChain = run.catch(() => void 0);
1251
+ return run;
1252
+ }
1253
+ /**
1254
+ * The page an acting request of the conversation acts on: its active tab; with no live tab, an
1255
+ * unowned tab it claims, else a new tab (subject to the caps). Callers that find no tab at the
1256
+ * same time share one claim, so the conversation gets exactly one tab.
1257
+ */
1258
+ async pageFor(conversationId, root) {
1259
+ const cur = this.currentPage(conversationId);
1260
+ if (cur !== void 0) return cur;
1261
+ const own = this.newestTabOf(conversationId);
1262
+ if (own !== void 0) {
1263
+ this.setActive(conversationId, own);
1264
+ const page = this.pageById(own);
1265
+ if (page !== void 0) return page;
1266
+ }
1267
+ let claim = this.claiming.get(conversationId);
1268
+ if (claim === void 0) {
1269
+ claim = this.allocate(async () => {
1270
+ const now = this.currentPage(conversationId) ?? this.pageById(this.newestTabOf(conversationId));
1271
+ if (now !== void 0) {
1272
+ this.setActive(conversationId, this.tabIdOf(now));
1273
+ return now;
1274
+ }
1275
+ const unowned = this.live().find(
1276
+ ([id, p]) => isStartBlank({ owner: this.owners.get(id)?.owner, url: p.url() }) && !this.usage.tabParked(id)
1277
+ );
1278
+ if (unowned !== void 0) {
1279
+ const [id, page] = unowned;
1280
+ this.assign(id, { owner: conversationId, root });
1281
+ this.activeOf.set(conversationId, id);
1282
+ this.emit({ type: "active", conversationId });
1283
+ this.emit({ type: "state" });
1284
+ return page;
1285
+ }
1286
+ return this.openLocked(conversationId, root);
1287
+ }).finally(() => {
1288
+ this.claiming.delete(conversationId);
1289
+ });
1290
+ this.claiming.set(conversationId, claim);
1291
+ }
1292
+ return claim;
1293
+ }
1294
+ /** Opens a new tab for the conversation (the caps apply) and makes it its active tab. */
1295
+ openTab(conversationId, root) {
1296
+ return this.allocate(() => this.openLocked(conversationId, root));
1297
+ }
1298
+ /** {@link openTab} inside the allocation chain. */
1299
+ async openLocked(conversationId, root) {
1300
+ const own = this.countOf(conversationId);
1301
+ if (own >= MAX_TABS_PER_CONVERSATION) throw new ActionError("failed", CONVERSATION_CAP_MESSAGE);
1302
+ if (this.live().length + this.reserved >= MAX_TABS && !await this.evict(conversationId))
1303
+ throw new ActionError("failed", deviceCapMessage(own));
1304
+ this.reserved++;
1305
+ let page;
1306
+ try {
1307
+ page = await this.ctx.newPage();
1308
+ } finally {
1309
+ this.reserved--;
1310
+ }
1311
+ this.track(page);
1312
+ const id = this.tabIdOf(page);
1313
+ this.assign(id, { owner: conversationId, root });
1314
+ this.activeOf.set(conversationId, id);
1315
+ this.emit({ type: "active", conversationId });
1316
+ this.emit({ type: "state" });
1317
+ return page;
1318
+ }
1319
+ /**
1320
+ * Closes one tab to make room at the device cap: an unowned tab first, else a tab of the least
1321
+ * recently active conversation that is evictable (not in use, not pinned by a viewer, idle for
1322
+ * at least EVICT_MIN_IDLE_MS), its least recently used non-active tab before its active one; tabs
1323
+ * a park pins are skipped. Its owner is told. False when no tab qualifies.
1324
+ */
1325
+ async evict(forConversation) {
1326
+ const live = this.live().filter(([id]) => !this.usage.tabParked(id));
1327
+ const unowned = live.find(([id]) => !this.owners.has(id));
1328
+ if (unowned !== void 0) {
1329
+ await this.closeEvicted(unowned[0], unowned[1]);
1330
+ return true;
1331
+ }
1332
+ const owners = /* @__PURE__ */ new Set();
1333
+ for (const [id] of live) {
1334
+ const o = this.owners.get(id)?.owner;
1335
+ if (o !== void 0 && o !== forConversation && !this.usage.busy(o) && !this.usage.pinned(o) && this.usage.idleFor(o) >= EVICT_MIN_IDLE_MS)
1336
+ owners.add(o);
1337
+ }
1338
+ const victim = [...owners].sort(
1339
+ (a, b) => this.usage.lastActiveAt(a) - this.usage.lastActiveAt(b)
1340
+ )[0];
1341
+ if (victim === void 0) return false;
1342
+ const active = this.activeOf.get(victim);
1343
+ const used = (id) => this.tabUsedAt.get(id) ?? 0;
1344
+ const [tabId, page] = live.filter(([id]) => this.owners.get(id)?.owner === victim).sort(
1345
+ ([a], [b]) => (a === active ? 1 : 0) - (b === active ? 1 : 0) || used(a) - used(b)
1346
+ )[0] ?? [];
1347
+ if (tabId === void 0 || page === void 0) return false;
1348
+ const title = clip(this.titles.get(tabId) ?? "", OTHER_TITLE_CHARS) || "no title";
1349
+ await this.closeEvicted(tabId, page);
1350
+ this.noteTo(victim, tabEvicted(tabId, title));
1351
+ return true;
1352
+ }
1353
+ /**
1354
+ * Closes an evicted tab, closing from the start: no request or adopt reaches it while its close
1355
+ * runs (the close handler forgets it; a tab that would not close is kept as it was).
1356
+ */
1357
+ async closeEvicted(tabId, page) {
1358
+ this.closing.add(tabId);
1359
+ await page.close().catch(() => {
1360
+ this.closing.delete(tabId);
1361
+ });
1362
+ }
1363
+ /**
1364
+ * Moves a tab to the conversation and makes it its active tab (the tool's and a viewer's adopt).
1365
+ * `in_use`: its owner has a request in flight or a park (or a park pins the tab); `cap`: the
1366
+ * conversation already owns MAX_TABS_PER_CONVERSATION tabs. The previous owner is told.
1367
+ */
1368
+ adopt(conversationId, root, tabId) {
1369
+ this.tabById(tabId);
1370
+ const before = this.owners.get(tabId);
1371
+ if (before?.owner === conversationId) {
1372
+ this.setActive(conversationId, tabId);
1373
+ return "ok";
1374
+ }
1375
+ if (before !== void 0 && this.usage.busy(before.owner) || this.usage.tabParked(tabId))
1376
+ return "in_use";
1377
+ if (this.countOf(conversationId) >= MAX_TABS_PER_CONVERSATION) return "cap";
1378
+ this.assign(tabId, { owner: conversationId, root });
1379
+ this.activeOf.set(conversationId, tabId);
1380
+ this.usage.seen(conversationId, root);
1381
+ if (before !== void 0) {
1382
+ const title = clip(this.titles.get(tabId) ?? "", OTHER_TITLE_CHARS) || "no title";
1383
+ this.noteTo(before.owner, tabMoved(tabId, title));
1384
+ }
1385
+ this.emit({ type: "active", conversationId });
1386
+ this.emit({ type: "state" });
1387
+ return "ok";
1388
+ }
1389
+ /**
1390
+ * Opens a restored tab for its owner (the first claims the start's blank tab) and starts its
1391
+ * navigation without waiting for it.
1392
+ */
1393
+ async restoreTab(owner, url) {
1394
+ const page = await this.allocate(async () => {
1395
+ const blank = this.live().find(
1396
+ ([id2, p]) => isStartBlank({ owner: this.owners.get(id2)?.owner, url: p.url() })
1397
+ );
1398
+ if (blank !== void 0) {
1399
+ this.assign(blank[0], owner);
1400
+ return blank[1];
1401
+ }
1402
+ this.reserved++;
1403
+ try {
1404
+ const p = await this.ctx.newPage();
1405
+ this.track(p);
1406
+ this.assign(this.tabIdOf(p), owner);
1407
+ return p;
1408
+ } finally {
1409
+ this.reserved--;
1410
+ }
1411
+ });
1412
+ const id = this.tabIdOf(page);
1413
+ if (!this.activeOf.has(owner.owner)) this.activeOf.set(owner.owner, id);
1414
+ this.usage.seen(owner.owner, owner.root);
1415
+ this.emit({ type: "active", conversationId: owner.owner });
1416
+ this.emit({ type: "state" });
1417
+ let target;
1418
+ try {
1419
+ target = normalizeUrl(url);
1420
+ } catch {
1421
+ }
1422
+ if (target !== void 0) void this.viewerNav(page, { url: target });
1423
+ return id;
1424
+ }
1425
+ /**
1426
+ * Closes an idle conversation's tabs (except those a park pins) and forgets what the session
1427
+ * keeps for it.
1428
+ */
1429
+ async closeConversation(conversationId) {
1430
+ const ids = this.tabsOf(conversationId).filter((id) => !this.usage.tabParked(id));
1431
+ for (const id of ids) {
1432
+ this.closing.add(id);
1433
+ this.owners.delete(id);
1434
+ }
1435
+ this.activeOf.delete(conversationId);
1436
+ this.queues.delete(this.queueKey(conversationId));
1437
+ this.unreported.delete(conversationId);
1438
+ this.claiming.delete(conversationId);
1439
+ this.actedSeq.delete(conversationId);
1440
+ await Promise.all(
1441
+ ids.map(
1442
+ (id) => this.pages.get(id)?.close().catch(() => {
1443
+ this.closing.delete(id);
1444
+ })
1445
+ )
1446
+ );
1447
+ this.emit({ type: "state" });
908
1448
  }
909
1449
  emit(e) {
910
1450
  for (const fn of [...this.listeners]) {
@@ -963,38 +1503,76 @@ var BrowserSession = class {
963
1503
  this.emit({ type: "state" });
964
1504
  }
965
1505
  if (this.proxy !== void 0 && PROXY_FAILURE_RE.test(err))
966
- this.checkBlocked(r.url(), this.pageToOpen(page, r));
1506
+ this.checkBlocked(page, r.url(), this.pageToOpen(page, r));
967
1507
  });
968
1508
  page.on("response", (r) => {
969
1509
  if (r.request().isNavigationRequest() && r.frame() === page.mainFrame())
970
1510
  this.docStatus.set(id, r.status());
971
1511
  if (this.proxy !== void 0 && r.status() === 403 && r.url().startsWith("http:")) {
972
- this.checkBlocked(r.url(), this.pageToOpen(page, r.request()));
1512
+ this.checkBlocked(page, r.url(), this.pageToOpen(page, r.request()));
973
1513
  }
974
1514
  });
975
- page.on("dialog", (d) => this.onDialog(d));
976
- page.on("download", (d) => this.onDownload(d));
1515
+ page.on("dialog", (d) => this.onDialog(page, d));
1516
+ page.on("download", (d) => this.onDownload(page, d));
977
1517
  page.on("filechooser", () => {
978
- this.note("The page opened a file chooser; use the upload tool with the file input's ref.");
979
- this.emit({ type: "dialog", kind: "file", message: "" });
1518
+ const o = this.owners.get(id);
1519
+ this.noteTo(
1520
+ o?.owner,
1521
+ "The page opened a file chooser; use the upload tool with the file input's ref."
1522
+ );
1523
+ if (o !== void 0) this.emit({ type: "dialog", kind: "file", message: "", root: o.root });
980
1524
  });
1525
+ page.on("popup", (p) => this.onPopup(page, p));
981
1526
  page.on("close", () => {
982
1527
  this.pendingNavs.delete(page);
983
1528
  this.pages.delete(id);
1529
+ this.closing.delete(id);
984
1530
  this.titles.delete(id);
985
1531
  this.loadingTabs.delete(id);
986
1532
  this.blockers.delete(id);
987
1533
  this.favicons.delete(id);
988
1534
  this.docStatus.delete(id);
989
- if (this.active === id) {
990
- const next = [...this.pages.keys()].at(-1);
991
- this.active = next;
992
- this.emit({ type: "active" });
993
- }
1535
+ this.tabUsedAt.delete(id);
1536
+ this.gainedAt.delete(id);
1537
+ this.clicks.delete(id);
1538
+ const o = this.owners.get(id);
1539
+ this.owners.delete(id);
1540
+ if (o !== void 0) this.activeMovedOff(o.owner, id);
1541
+ this.usage.tabClosed(id);
994
1542
  this.emit({ type: "state" });
995
1543
  });
996
1544
  }
997
- onDialog(d) {
1545
+ /**
1546
+ * A page opened a popup: it belongs to the opener's owner and becomes its active tab, as in a
1547
+ * desktop browser (an unowned opener leaves it unowned). Past the conversation's cap it is closed
1548
+ * at once; past the device cap a tab is evicted for it, else it is closed; the owner is told.
1549
+ */
1550
+ onPopup(opener, popup) {
1551
+ this.track(popup);
1552
+ const id = this.tabIdOf(popup);
1553
+ const o = this.owners.get(this.tabIdOf(opener));
1554
+ if (o === void 0 || this.owners.has(id) || popup.isClosed()) return;
1555
+ const closeIt = (why) => {
1556
+ popup.close().catch(() => void 0);
1557
+ this.noteTo(
1558
+ o.owner,
1559
+ `The page opened a popup, but ${why}, so the popup was closed; close a tab and retry if it was needed.`
1560
+ );
1561
+ };
1562
+ if (this.countOf(o.owner) >= MAX_TABS_PER_CONVERSATION) {
1563
+ closeIt(`this conversation keeps at most ${MAX_TABS_PER_CONVERSATION} tabs`);
1564
+ return;
1565
+ }
1566
+ this.assign(id, o);
1567
+ this.activeOf.set(o.owner, id);
1568
+ this.emit({ type: "active", conversationId: o.owner });
1569
+ this.emit({ type: "state" });
1570
+ void this.allocate(async () => {
1571
+ if (popup.isClosed() || this.live().length <= MAX_TABS) return;
1572
+ if (!await this.evict(o.owner)) closeIt(`the browser keeps at most ${MAX_TABS} tabs`);
1573
+ });
1574
+ }
1575
+ onDialog(page, d) {
998
1576
  const type = d.type();
999
1577
  if (type === "beforeunload") {
1000
1578
  d.accept().catch(() => void 0);
@@ -1004,24 +1582,50 @@ var BrowserSession = class {
1004
1582
  const message = clip(d.message(), MAX_DIALOG_CHARS);
1005
1583
  const settle = kind === "alert" ? d.accept() : d.dismiss();
1006
1584
  settle.catch(() => void 0);
1007
- this.note(
1585
+ const o = this.owners.get(this.tabIdOf(page));
1586
+ this.noteTo(
1587
+ o?.owner,
1008
1588
  `The page showed ${kind === "alert" ? "an alert" : `a ${kind}`} dialog: ${JSON.stringify(message)} (${kind === "alert" ? "closed" : "dismissed"}).`
1009
1589
  );
1010
- this.emit({ type: "dialog", kind, message });
1590
+ if (o !== void 0) this.emit({ type: "dialog", kind, message, root: o.root });
1011
1591
  }
1012
1592
  /**
1013
- * Adds a note to the replies of the requests in flight; with none in flight (a download that
1014
- * finished after its click replied, a dialog the person caused) the next reply carries it.
1593
+ * A device note (not about a page: the browser build that runs): the replies of the requests in
1594
+ * flight carry it, else the next reply of any conversation.
1015
1595
  */
1016
1596
  note(text) {
1017
1597
  const n = clip(text, MAX_DIALOG_CHARS + 200);
1018
1598
  if (this.collectors.size === 0) {
1019
- this.unreported.push(n);
1020
- if (this.unreported.length > MAX_UNREPORTED) this.unreported.shift();
1599
+ this.unreportedAll.push(n);
1600
+ if (this.unreportedAll.length > MAX_UNREPORTED) this.unreportedAll.shift();
1021
1601
  return;
1022
1602
  }
1023
1603
  for (const c of this.collectors) c.notes.push(n);
1024
1604
  }
1605
+ /**
1606
+ * A note for a conversation (about one of its pages): its requests in flight carry it, else its
1607
+ * next reply. A note of an unowned page (`undefined`) reaches nobody.
1608
+ */
1609
+ noteTo(conversationId, text) {
1610
+ if (conversationId === void 0) return;
1611
+ if (this.countOf(conversationId) === 0 && !this.usage.known(conversationId)) return;
1612
+ const n = clip(text, MAX_DIALOG_CHARS + 200);
1613
+ let delivered = false;
1614
+ for (const c of this.collectors) {
1615
+ if (c.conv !== conversationId) continue;
1616
+ c.notes.push(n);
1617
+ delivered = true;
1618
+ }
1619
+ if (delivered) return;
1620
+ const list = this.unreported.get(conversationId) ?? [];
1621
+ list.push(n);
1622
+ if (list.length > MAX_UNREPORTED) list.shift();
1623
+ this.unreported.set(conversationId, list);
1624
+ }
1625
+ /** The owner of a page, if it has one. */
1626
+ ownerOfPage(page) {
1627
+ return page === null || page === void 0 ? void 0 : this.owners.get(this.tabIdOf(page));
1628
+ }
1025
1629
  /**
1026
1630
  * Saves a download into `<workspace>/downloads` under its suggested name (sanitized, numbered
1027
1631
  * when taken). A request in flight waits for it at most `downloadWaitMs`, then says it is still
@@ -1029,12 +1633,14 @@ var BrowserSession = class {
1029
1633
  * cancelled when together they pass `downloadMaxBytes`, so a page cannot fill the disk.
1030
1634
  * Without a workspace the download is cancelled.
1031
1635
  */
1032
- onDownload(d) {
1636
+ onDownload(page, d) {
1033
1637
  const shown = JSON.stringify(clip(d.suggestedFilename(), 300));
1034
1638
  const workspace = this.workspace;
1639
+ const owner = this.ownerOfPage(page)?.owner;
1640
+ const note = (text) => this.noteTo(owner, text);
1035
1641
  if (workspace === void 0) {
1036
1642
  d.cancel().catch(() => void 0);
1037
- this.note(
1643
+ note(
1038
1644
  `The page started a download (${shown}), which was cancelled: the device has no workspace.`
1039
1645
  );
1040
1646
  return;
@@ -1047,20 +1653,20 @@ var BrowserSession = class {
1047
1653
  try {
1048
1654
  const failure = await d.failure();
1049
1655
  if (failure !== null) {
1050
- if (failure !== "canceled") this.note(`The download of ${shown} failed: ${failure}.`);
1656
+ if (failure !== "canceled") note(`The download of ${shown} failed: ${failure}.`);
1051
1657
  return;
1052
1658
  }
1053
1659
  const tmp = await d.path();
1054
1660
  if (statSync(tmp).size > this.downloadMaxBytes) {
1055
- this.note(
1661
+ note(
1056
1662
  `The download of ${shown} was not saved: it is larger than ${this.downloadMaxBytes} bytes.`
1057
1663
  );
1058
1664
  return;
1059
1665
  }
1060
1666
  target = this.saveDownload(workspace, safeFileName(d.suggestedFilename()), tmp);
1061
- this.note(`Downloaded ${shown} to ${target}.`);
1667
+ note(`Downloaded ${shown} to ${target}.`);
1062
1668
  } catch (e) {
1063
- this.note(
1669
+ note(
1064
1670
  `The download of ${shown} was not saved: ${e instanceof ActionError ? e.message : firstLine(e)}`
1065
1671
  );
1066
1672
  } finally {
@@ -1070,7 +1676,7 @@ var BrowserSession = class {
1070
1676
  entry.finished = true;
1071
1677
  }
1072
1678
  })();
1073
- for (const c of this.collectors) c.downloads.push(entry);
1679
+ for (const c of this.collectors) if (c.conv === owner) c.downloads.push(entry);
1074
1680
  }
1075
1681
  /**
1076
1682
  * Copies a finished download from Playwright's private file into `<workspace>/downloads` and
@@ -1169,7 +1775,8 @@ var BrowserSession = class {
1169
1775
  if (bytes > this.downloadMaxBytes) {
1170
1776
  for (const f of names) this.cancelledTmp.add(f);
1171
1777
  for (const d of this.activeDownloads) {
1172
- this.note(
1778
+ this.noteTo(
1779
+ this.ownerOfPage(d.page())?.owner,
1173
1780
  `The download of ${JSON.stringify(clip(d.suggestedFilename(), 300))} was cancelled: downloads in progress passed ${this.downloadMaxBytes} bytes.`
1174
1781
  );
1175
1782
  d.cancel().catch(() => void 0);
@@ -1255,8 +1862,9 @@ var BrowserSession = class {
1255
1862
  * Probes the proxy for the URL's host and reports it when refused; the viewers' `blocked`
1256
1863
  * message carries `pageUrl` (default: the URL itself), the page to open once allowed.
1257
1864
  */
1258
- checkBlocked(rawUrl, pageUrl) {
1865
+ checkBlocked(page, rawUrl, pageUrl) {
1259
1866
  const proxy = this.proxy;
1867
+ const owner = this.ownerOfPage(page);
1260
1868
  if (proxy === void 0) return Promise.resolve(false);
1261
1869
  let url;
1262
1870
  try {
@@ -1266,19 +1874,20 @@ var BrowserSession = class {
1266
1874
  }
1267
1875
  const host = url.hostname;
1268
1876
  const port = Number(url.port || (url.protocol === "https:" ? 443 : 80));
1269
- let probe = this.probes.get(host);
1877
+ const key2 = `${owner?.owner ?? ""}\0${host}`;
1878
+ let probe = this.probes.get(key2);
1270
1879
  if (probe === void 0) {
1271
1880
  probe = proxyRefuses(proxy, host, port).then((refused) => {
1272
- this.probes.delete(host);
1273
- if (refused) {
1274
- for (const c of this.collectors) c.blocked.add(host);
1275
- this.emit({ type: "blocked", host, url: pageUrl ?? url.href });
1881
+ this.probes.delete(key2);
1882
+ if (refused && owner !== void 0) {
1883
+ for (const c of this.collectors) if (c.conv === owner.owner) c.blocked.add(host);
1884
+ this.emit({ type: "blocked", host, url: pageUrl ?? url.href, root: owner.root });
1276
1885
  }
1277
1886
  return refused;
1278
1887
  });
1279
- this.probes.set(host, probe);
1888
+ this.probes.set(key2, probe);
1280
1889
  }
1281
- for (const c of this.collectors) c.pending.push(probe);
1890
+ for (const c of this.collectors) if (c.conv === owner?.owner) c.pending.push(probe);
1282
1891
  return probe;
1283
1892
  }
1284
1893
  /** `value`, or `fallback` when it takes longer than {@link PAGE_QUERY_MS} (never rejects). */
@@ -1295,24 +1904,50 @@ var BrowserSession = class {
1295
1904
  this.clock.cancel(timer);
1296
1905
  }
1297
1906
  }
1298
- /** Runs `fn` one at a time with the other actions (`wait` and the tab list run beside them). */
1299
- serial(fn) {
1300
- const run = this.queue.then(fn, fn);
1301
- this.queue = run.catch(() => void 0);
1907
+ /**
1908
+ * The action queue a conversation's requests run in: one per conversation, so one
1909
+ * conversation's slow navigation does not stall another (ruling 7). Falling back to one
1910
+ * device-wide queue is returning a constant here.
1911
+ */
1912
+ queueKey(conversationId) {
1913
+ return conversationId;
1914
+ }
1915
+ /**
1916
+ * Runs `fn` one at a time with the conversation's other actions (`wait`, the tab list and adopt
1917
+ * run beside them).
1918
+ */
1919
+ serial(conversationId, fn) {
1920
+ const key2 = this.queueKey(conversationId);
1921
+ const run = (this.queues.get(key2) ?? Promise.resolve()).then(fn, fn);
1922
+ const tail = run.catch(() => void 0);
1923
+ this.queues.set(key2, tail);
1924
+ void tail.then(() => {
1925
+ if (this.queues.get(key2) === tail) this.queues.delete(key2);
1926
+ });
1302
1927
  return run;
1303
1928
  }
1304
1929
  /**
1305
- * Runs a tool request; never throws. `takenOver` is checked when a queued request leaves the
1306
- * queue: a takeover that began while it waited refuses it. An action already running is left to
1307
- * finish (stopping it halfway would leave the page in an unknown state).
1930
+ * Runs a tool request of its conversation; never throws. `takenOver` is checked when a queued
1931
+ * request leaves the queue: a takeover that began while it waited refuses it. An action already
1932
+ * running is left to finish (stopping it halfway would leave the page in an unknown state).
1308
1933
  */
1309
1934
  async run(req, opts = {}) {
1310
- const late = this.unreported.splice(0);
1311
- const c = { blocked: /* @__PURE__ */ new Set(), notes: [...late], pending: [], downloads: [] };
1935
+ const conv = req.conversationId;
1936
+ const lateOwn = this.unreported.get(conv) ?? [];
1937
+ this.unreported.delete(conv);
1938
+ const lateAll = this.unreportedAll.splice(0);
1939
+ const c = {
1940
+ conv,
1941
+ blocked: /* @__PURE__ */ new Set(),
1942
+ notes: [...lateAll, ...lateOwn],
1943
+ pending: [],
1944
+ downloads: []
1945
+ };
1312
1946
  this.collectors.add(c);
1313
1947
  let reply;
1314
1948
  try {
1315
- const out = await (req.op === "wait" || req.op === "tabs" && req.action === "list" ? this.exec(req) : this.serial(() => {
1949
+ const beside = req.op === "wait" || req.op === "tabs" && (req.action === "list" || req.action === "adopt");
1950
+ const out = await (beside ? this.exec(req) : this.serial(conv, () => {
1316
1951
  if (opts.takenOver?.() === true)
1317
1952
  throw new ActionError("taken_over", TAKEN_OVER_MESSAGE);
1318
1953
  return this.exec(req);
@@ -1320,8 +1955,12 @@ var BrowserSession = class {
1320
1955
  await this.settleProbes(c);
1321
1956
  await this.settleDownloads(c);
1322
1957
  this.collectors.delete(c);
1323
- const page = await this.activePage();
1324
- const verifying = await this.checkVerification(page, this.tabIdOf(page));
1958
+ const page = this.currentPage(conv);
1959
+ if (page !== void 0 && isActing(req)) {
1960
+ this.tabUsedAt.set(this.tabIdOf(page), this.clock.now());
1961
+ this.actedSeq.set(conv, ++this.actSeq);
1962
+ }
1963
+ const verifying = page === void 0 ? false : await this.checkVerification(page, this.tabIdOf(page));
1325
1964
  const text = [
1326
1965
  ...verifying ? [VERIFICATION_NOTE] : [],
1327
1966
  ...c.notes,
@@ -1329,7 +1968,7 @@ var BrowserSession = class {
1329
1968
  ].join("\n");
1330
1969
  reply = {
1331
1970
  ok: true,
1332
- page: await this.pageInfo(page),
1971
+ ...page === void 0 ? {} : { page: await this.pageInfo(page) },
1333
1972
  blockedHosts: [...c.blocked],
1334
1973
  ...text === "" ? {} : { text },
1335
1974
  ...out.image === void 0 ? {} : { image: out.image }
@@ -1346,7 +1985,9 @@ var BrowserSession = class {
1346
1985
  message = `The device's network settings block ${[...c.blocked].join(", ")}.`;
1347
1986
  }
1348
1987
  reply = { ok: false, error: code, message, blockedHosts: [...c.blocked] };
1349
- this.unreported.unshift(...late);
1988
+ if (lateOwn.length > 0)
1989
+ this.unreported.set(conv, [...lateOwn, ...this.unreported.get(conv) ?? []]);
1990
+ this.unreportedAll.unshift(...lateAll);
1350
1991
  } finally {
1351
1992
  this.collectors.delete(c);
1352
1993
  }
@@ -1502,8 +2143,8 @@ var BrowserSession = class {
1502
2143
  );
1503
2144
  }
1504
2145
  }
1505
- markClick(x, y) {
1506
- this.lastClick = { x, y, seq: ++this.clickSeq };
2146
+ markClick(page, x, y) {
2147
+ this.clicks.set(this.tabIdOf(page), { x, y, seq: ++this.clickSeq });
1507
2148
  }
1508
2149
  async goto(page, url) {
1509
2150
  let res;
@@ -1512,7 +2153,7 @@ var BrowserSession = class {
1512
2153
  const deadline = Date.now() + this.navigationTimeoutMs;
1513
2154
  const watch = new NavWatch(page, url, () => this.pendingNavs.get(page));
1514
2155
  try {
1515
- res = await page.goto(url, { waitUntil: "domcontentloaded" });
2156
+ res = await this.gotoPastLateErrorPage(page, url, watch, deadline);
1516
2157
  } catch (e) {
1517
2158
  const msg = firstLine(e);
1518
2159
  if (msg.includes("Download is starting")) {
@@ -1543,7 +2184,7 @@ var BrowserSession = class {
1543
2184
  } finally {
1544
2185
  watch.dispose();
1545
2186
  }
1546
- if (res?.status() === 403 && await this.checkBlocked(res.url())) {
2187
+ if (res?.status() === 403 && await this.checkBlocked(page, res.url())) {
1547
2188
  throw new ActionError(
1548
2189
  "blocked",
1549
2190
  `The device's network settings block ${new URL(res.url()).hostname}.`
@@ -1551,6 +2192,28 @@ var BrowserSession = class {
1551
2192
  }
1552
2193
  await page.waitForLoadState("load", { timeout: LOAD_GRACE_MS }).catch(() => void 0);
1553
2194
  }
2195
+ /**
2196
+ * `page.goto`, past the late error page of the tab's previous failed or stopped navigation:
2197
+ * Chromium can commit that page after Playwright reported the failure (the Linux full build),
2198
+ * and its commit interrupts a navigation started meanwhile. Then this navigation is followed
2199
+ * when it went on in Chromium, and otherwise started once more (the error page is in now),
2200
+ * within the navigation's own deadline.
2201
+ */
2202
+ async gotoPastLateErrorPage(page, url, watch, deadline) {
2203
+ try {
2204
+ return await page.goto(url, { waitUntil: "domcontentloaded" });
2205
+ } catch (e) {
2206
+ if (!ERROR_PAGE_INTERRUPT_RE.test(firstLine(e))) throw e;
2207
+ const out = await watch.follow(deadline);
2208
+ if (out.kind === "loaded") return out.response;
2209
+ if (out.kind === "failed" && !out.error.includes("net::ERR_ABORTED"))
2210
+ throw new Error(`${out.error} at ${out.url}`);
2211
+ return page.goto(url, {
2212
+ waitUntil: "domcontentloaded",
2213
+ timeout: Math.max(1, deadline - Date.now())
2214
+ });
2215
+ }
2216
+ }
1554
2217
  /**
1555
2218
  * The error of a navigation that failed with Chromium's net error `error`: a host the proxy
1556
2219
  * refuses is reported as blocked (`run` turns `original` into the blocked reply); any other net
@@ -1561,7 +2224,7 @@ var BrowserSession = class {
1561
2224
  if (net === void 0 || net === "ERR_ABORTED") return original;
1562
2225
  await this.errorPageCommitted(page);
1563
2226
  if (PROXY_FAILURE_RE.test(error)) {
1564
- if (await this.checkBlocked(url)) return original;
2227
+ if (await this.checkBlocked(page, url)) return original;
1565
2228
  const detail = await this.networkDetail(url);
1566
2229
  return new ActionError(
1567
2230
  "unreachable",
@@ -1647,9 +2310,12 @@ var BrowserSession = class {
1647
2310
  }
1648
2311
  }
1649
2312
  async exec(req) {
2313
+ const conv = req.conversationId;
2314
+ const root = req.rootConversationId;
2315
+ const activePage = () => this.pageFor(conv, root);
1650
2316
  switch (req.op) {
1651
2317
  case "navigate": {
1652
- const page = await this.activePage();
2318
+ const page = await activePage();
1653
2319
  if (req.url !== void 0) {
1654
2320
  await this.goto(page, normalizeUrl(req.url));
1655
2321
  } else if (req.action === "back" || req.action === "forward") {
@@ -1678,40 +2344,40 @@ var BrowserSession = class {
1678
2344
  case "tabs":
1679
2345
  return this.tabsOp(req);
1680
2346
  case "snapshot":
1681
- return { text: await takeSnapshot(await this.activePage()) };
2347
+ return { text: await takeSnapshot(await activePage()) };
1682
2348
  case "click":
1683
2349
  case "hover": {
1684
- const page = await this.activePage();
2350
+ const page = await activePage();
1685
2351
  const loc = await this.locate(page, req.ref);
1686
2352
  if (req.op === "hover") {
1687
2353
  await loc.hover();
1688
2354
  return {};
1689
2355
  }
1690
2356
  const at = await this.centerOf(loc);
1691
- if (at !== void 0) this.markClick(at.x, at.y);
2357
+ if (at !== void 0) this.markClick(page, at.x, at.y);
1692
2358
  await this.settled(page, () => loc.click());
1693
2359
  return {};
1694
2360
  }
1695
2361
  case "type": {
1696
- const page = await this.activePage();
2362
+ const page = await activePage();
1697
2363
  const loc = await this.locate(page, req.ref);
1698
2364
  await loc.fill(req.text);
1699
2365
  if (req.submit === true) await this.settled(page, () => loc.press("Enter"));
1700
2366
  return {};
1701
2367
  }
1702
2368
  case "select": {
1703
- const page = await this.activePage();
2369
+ const page = await activePage();
1704
2370
  const loc = await this.locate(page, req.ref);
1705
2371
  const chosen = await this.settled(page, () => loc.selectOption(req.values));
1706
2372
  return { text: `Selected ${JSON.stringify(chosen)}.` };
1707
2373
  }
1708
2374
  case "press": {
1709
- const page = await this.activePage();
2375
+ const page = await activePage();
1710
2376
  await this.settled(page, () => page.keyboard.press(req.key));
1711
2377
  return {};
1712
2378
  }
1713
2379
  case "scroll": {
1714
- const page = await this.activePage();
2380
+ const page = await activePage();
1715
2381
  if (req.ref !== void 0) {
1716
2382
  const loc = await this.locate(page, req.ref);
1717
2383
  await loc.scrollIntoViewIfNeeded();
@@ -1725,7 +2391,7 @@ var BrowserSession = class {
1725
2391
  return {};
1726
2392
  }
1727
2393
  case "upload": {
1728
- const page = await this.activePage();
2394
+ const page = await activePage();
1729
2395
  const file = this.readUpload(req.path);
1730
2396
  const loc = await this.locate(page, req.ref);
1731
2397
  await loc.setInputFiles(file);
@@ -1733,17 +2399,17 @@ var BrowserSession = class {
1733
2399
  }
1734
2400
  case "click_at":
1735
2401
  case "type_at": {
1736
- const page = await this.activePage();
2402
+ const page = await activePage();
1737
2403
  this.checkPoint(req.x, req.y);
1738
- this.markClick(Math.round(req.x), Math.round(req.y));
2404
+ this.markClick(page, Math.round(req.x), Math.round(req.y));
1739
2405
  await this.settled(page, () => page.mouse.click(req.x, req.y));
1740
2406
  if (req.op === "type_at") await page.keyboard.type(req.text);
1741
2407
  return {};
1742
2408
  }
1743
2409
  case "wait":
1744
- return this.waitOp(req);
2410
+ return this.waitOp(req, this.currentPage(conv));
1745
2411
  case "screenshot": {
1746
- const page = await this.activePage();
2412
+ const page = await activePage();
1747
2413
  const maxBytes = Math.min(MAX_SCREENSHOT_BYTES, Math.floor(req.maxBytes));
1748
2414
  if (!(maxBytes > 0))
1749
2415
  throw new ActionError("failed", "screenshot needs a positive maxBytes.");
@@ -1774,56 +2440,79 @@ var BrowserSession = class {
1774
2440
  );
1775
2441
  }
1776
2442
  async tabsOp(req) {
2443
+ const conv = req.conversationId;
2444
+ const root = req.rootConversationId;
1777
2445
  switch (req.action) {
1778
- case "list": {
1779
- if (this.pages.size === 0) await this.activePage();
1780
- const lines = await Promise.all(
1781
- [...this.pages.entries()].map(async ([id, p]) => {
1782
- const info = await this.pageInfo(p);
1783
- return `${id}${id === this.active ? " (active)" : ""}: ${info.title || "(no title)"} ${info.url}`;
1784
- })
1785
- );
1786
- return { text: lines.join("\n") };
1787
- }
2446
+ case "list":
2447
+ return { text: await this.listText(conv, root) };
1788
2448
  case "open": {
1789
- const page = await this.openTab();
2449
+ const page = this.countOf(conv) === 0 ? await this.pageFor(conv, root) : await this.openTab(conv, root);
1790
2450
  if (req.url !== void 0) await this.goto(page, normalizeUrl(req.url));
1791
2451
  return {};
1792
2452
  }
1793
2453
  case "switch": {
1794
- const page = this.tabById(req.tabId);
1795
- this.active = req.tabId;
1796
- await page.bringToFront().catch(() => void 0);
1797
- this.emit({ type: "active" });
2454
+ this.ownTab(conv, req.tabId);
2455
+ this.setActive(conv, req.tabId);
1798
2456
  return {};
1799
2457
  }
1800
2458
  case "close": {
1801
- const page = this.tabById(req.tabId);
2459
+ const page = this.ownTab(conv, req.tabId);
1802
2460
  await page.close();
1803
- await this.activePage();
2461
+ return {};
2462
+ }
2463
+ case "adopt": {
2464
+ const id = req.tabId;
2465
+ const result = this.adopt(conv, root, this.tabIdOf(this.tabById(id)));
2466
+ if (result === "in_use") throw new ActionError("failed", tabInUse(id ?? ""));
2467
+ if (result === "cap") throw new ActionError("failed", CONVERSATION_CAP_MESSAGE);
1804
2468
  return {};
1805
2469
  }
1806
2470
  }
1807
- throw new ActionError("failed", "tabs needs an action: list, open, switch or close.");
2471
+ throw new ActionError("failed", "tabs needs an action: list, open, switch, close or adopt.");
1808
2472
  }
1809
- /** Opens a blank tab and makes it active. */
1810
- async openTab() {
1811
- if (this.pages.size >= MAX_TABS) {
1812
- throw new ActionError(
1813
- "failed",
1814
- `The browser has ${MAX_TABS} tabs open, the most it keeps; close one first.`
1815
- );
1816
- }
1817
- const page = await this.ctx.newPage();
1818
- this.track(page);
1819
- this.active = this.ids.get(page);
1820
- this.emit({ type: "active" });
1821
- this.emit({ type: "state" });
2473
+ /** The conversation's own tab `tabId`; another conversation's is refused with what to do. */
2474
+ ownTab(conversationId, tabId) {
2475
+ const page = this.tabById(tabId);
2476
+ if (this.owners.get(tabId)?.owner !== conversationId)
2477
+ throw new ActionError("failed", notYourTab(tabId));
1822
2478
  return page;
1823
2479
  }
2480
+ /**
2481
+ * The tab list of a conversation: its own tabs, then its tree's other tabs, then other trees'
2482
+ * tabs (unowned ones too, but not a blank start tab), with ids, titles clipped to
2483
+ * OTHER_TITLE_CHARS and URLs without query or fragment outside its own; no conversation ids.
2484
+ */
2485
+ async listText(conversationId, root) {
2486
+ const own = [];
2487
+ const tree = [];
2488
+ const device = [];
2489
+ for (const [id, p] of this.live()) {
2490
+ const o = this.owners.get(id);
2491
+ if (o?.owner === conversationId) {
2492
+ const info = await this.pageInfo(p);
2493
+ const active = this.activeOf.get(conversationId) === id ? " (active)" : "";
2494
+ own.push(`${id}${active}: ${info.title || "(no title)"} ${info.url}`);
2495
+ continue;
2496
+ }
2497
+ if (isStartBlank({ owner: o?.owner, url: p.url() })) continue;
2498
+ const title = clip(this.titles.get(id) ?? "", OTHER_TITLE_CHARS) || "(no title)";
2499
+ const line = `${id}: ${title} ${bareUrl(clip(p.url(), MAX_URL_CHARS))}`;
2500
+ if (o !== void 0 && o.root === root) tree.push(line);
2501
+ else device.push(line);
2502
+ }
2503
+ const lines = [...own];
2504
+ if (tree.length > 0) lines.push("Tabs of other conversations in this task:", ...tree);
2505
+ if (device.length > 0) lines.push("Tabs of other conversations on this device:", ...device);
2506
+ if (tree.length + device.length > 0)
2507
+ lines.push(
2508
+ "To use another conversation's tab, call browser_tabs with action adopt and its tabId."
2509
+ );
2510
+ if (lines.length === 0) return "No browser tabs are open.";
2511
+ return lines.join("\n");
2512
+ }
1824
2513
  tabById(tabId) {
1825
- const page = tabId === void 0 ? void 0 : this.pages.get(tabId);
1826
- if (page === void 0 || page.isClosed()) {
2514
+ const page = this.pageById(tabId);
2515
+ if (page === void 0) {
1827
2516
  throw new ActionError(
1828
2517
  "failed",
1829
2518
  `No tab ${JSON.stringify(tabId ?? "")}; list the tabs to see their ids.`
@@ -1831,18 +2520,13 @@ var BrowserSession = class {
1831
2520
  }
1832
2521
  return page;
1833
2522
  }
1834
- /** Makes a tab active (a viewer's tab switch). */
1835
- async switchTo(tabId) {
1836
- const page = this.tabById(tabId);
1837
- this.active = tabId;
1838
- await page.bringToFront().catch(() => void 0);
1839
- this.emit({ type: "active" });
1840
- this.emit({ type: "state" });
2523
+ /** Brings a tab to the front of the window (only a viewer in control decides what is front). */
2524
+ async bringToFront(tabId) {
2525
+ await this.pageById(tabId)?.bringToFront().catch(() => void 0);
1841
2526
  }
1842
- /** Navigates the active tab for a viewer (address bar, back, forward, reload); never throws. */
1843
- async viewerNav(nav) {
2527
+ /** Navigates a tab for a viewer (address bar, back, forward, reload); never throws. */
2528
+ async viewerNav(page, nav) {
1844
2529
  try {
1845
- const page = await this.activePage();
1846
2530
  if (nav.url !== void 0) await this.goto(page, normalizeUrl(nav.url));
1847
2531
  else if (nav.action === "back") await page.goBack();
1848
2532
  else if (nav.action === "forward") await page.goForward();
@@ -1850,10 +2534,15 @@ var BrowserSession = class {
1850
2534
  } catch {
1851
2535
  }
1852
2536
  }
1853
- async waitOp(req) {
2537
+ async waitOp(req, page) {
1854
2538
  const asked = Number(req.timeoutMs);
1855
2539
  const timeout = Number.isFinite(asked) ? Math.max(0, Math.min(MAX_WAIT_MS, Math.floor(asked))) : DEFAULT_WAIT_MS;
1856
- const page = await this.activePage();
2540
+ if (page === void 0) {
2541
+ if (req.text !== void 0 || req.ref !== void 0 || req.navigation === true)
2542
+ throw new ActionError("failed", NO_TAB_TO_WAIT_ON);
2543
+ await new Promise((r) => this.clock.schedule(r, timeout));
2544
+ return {};
2545
+ }
1857
2546
  if (req.text !== void 0) {
1858
2547
  await page.getByText(req.text).first().waitFor({ state: "visible", timeout }).catch((e) => {
1859
2548
  throw e instanceof Error && e.name === "TimeoutError" ? new ActionError(
@@ -2245,6 +2934,8 @@ async function restoreCookies(ctx, stateDir) {
2245
2934
  import { readFileSync as readFileSync3, renameSync as renameSync2, rmSync as rmSync2, writeFileSync as writeFileSync3 } from "node:fs";
2246
2935
  import { join as join4 } from "node:path";
2247
2936
  var RESTORE_MAX_AGE_MS = 10 * 6e4;
2937
+ var SESSION_FILE_VERSION = 2;
2938
+ var isId = (v) => typeof v === "string" && v !== "";
2248
2939
  var SessionFile = class {
2249
2940
  file;
2250
2941
  clock;
@@ -2254,7 +2945,7 @@ var SessionFile = class {
2254
2945
  this.file = join4(stateDir, "session.json");
2255
2946
  this.clock = clock;
2256
2947
  }
2257
- /** The saved session when it is recent and well formed; undefined otherwise. */
2948
+ /** The saved session when it is recent, of this format and well formed; undefined otherwise. */
2258
2949
  read() {
2259
2950
  let raw;
2260
2951
  try {
@@ -2263,42 +2954,67 @@ var SessionFile = class {
2263
2954
  return void 0;
2264
2955
  }
2265
2956
  const s = raw;
2266
- if (typeof s !== "object" || s === null || typeof s.savedAt !== "number" || this.clock.now() - s.savedAt > RESTORE_MAX_AGE_MS || !Array.isArray(s.tabs))
2957
+ 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))
2267
2958
  return void 0;
2268
2959
  const tabs = s.tabs.filter(
2269
- (u) => typeof u === "string" && /^https?:\/\//i.test(u)
2270
- );
2271
- const h = s.handoff;
2272
- 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;
2273
- return {
2274
- savedAt: s.savedAt,
2275
- tabs: tabs.slice(0, MAX_TABS),
2276
- active: typeof s.active === "number" ? s.active : 0,
2277
- ...handoff === void 0 ? {} : { handoff }
2278
- };
2960
+ (t) => typeof t === "object" && t !== null && typeof t.url === "string" && /^https?:\/\//i.test(t.url) && isId(t.owner) && isId(t.root)
2961
+ ).slice(0, MAX_TABS).map((t) => ({ url: t.url, owner: t.owner, root: t.root }));
2962
+ const conversations = [];
2963
+ for (const c of s.conversations) {
2964
+ if (typeof c !== "object" || c === null) continue;
2965
+ const x = c;
2966
+ if (!isId(x.id) || !isId(x.root)) continue;
2967
+ const h = x.handoff;
2968
+ 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;
2969
+ const parks = Array.isArray(x.parks) ? x.parks.filter(
2970
+ (p) => typeof p === "object" && p !== null && isId(p.kind) && typeof p.key === "string"
2971
+ ).map((p) => ({ kind: p.kind, key: p.key })) : [];
2972
+ conversations.push({
2973
+ id: x.id,
2974
+ root: x.root,
2975
+ ...typeof x.active === "number" ? { active: x.active } : {},
2976
+ ...handoff === void 0 ? {} : { handoff },
2977
+ ...parks.length === 0 ? {} : { parks }
2978
+ });
2979
+ }
2980
+ return { version: SESSION_FILE_VERSION, savedAt: s.savedAt, tabs, conversations };
2279
2981
  }
2280
2982
  /**
2281
- * Writes the session soon (coalesced): the tabs' URLs and the pending handoff, both read when
2282
- * the write runs.
2983
+ * Writes the session soon (coalesced): the tabs with their owners, and per conversation its
2984
+ * active tab, pending handoff and persistent parks, all read when the write runs.
2283
2985
  */
2284
- save(session, handoffNow) {
2986
+ save(session, state) {
2285
2987
  if (this.queued || this.forgotten) return;
2286
2988
  this.queued = true;
2287
2989
  queueMicrotask(() => {
2288
2990
  this.queued = false;
2289
2991
  if (this.forgotten) return;
2290
- const handoff = handoffNow();
2291
- const all = session.tabs();
2292
- const kept = all.filter((t) => /^https?:\/\//i.test(t.url));
2293
- const active = Math.max(
2294
- 0,
2295
- kept.findIndex((t) => t.active)
2992
+ const kept = session.tabs().filter(
2993
+ (t) => t.owner !== void 0 && t.root !== void 0 && /^https?:\/\//i.test(t.url)
2296
2994
  );
2995
+ const tabs = kept.map((t) => ({ url: t.url, owner: t.owner, root: t.root }));
2996
+ const ids = /* @__PURE__ */ new Set([...kept.map((t) => t.owner), ...state.conversationIds]);
2997
+ const conversations = [];
2998
+ for (const id of ids) {
2999
+ const root = kept.find((t) => t.owner === id)?.root ?? state.rootOf(id);
3000
+ if (root === void 0) continue;
3001
+ const active = kept.findIndex((t) => t.owner === id && t.active);
3002
+ const handoff = state.handoffOf(id);
3003
+ 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 }));
3004
+ if (active < 0 && handoff === void 0 && parks.length === 0) continue;
3005
+ conversations.push({
3006
+ id,
3007
+ root,
3008
+ ...active < 0 ? {} : { active },
3009
+ ...handoff === void 0 ? {} : { handoff },
3010
+ ...parks.length === 0 ? {} : { parks }
3011
+ });
3012
+ }
2297
3013
  const body = {
3014
+ version: SESSION_FILE_VERSION,
2298
3015
  savedAt: this.clock.now(),
2299
- tabs: kept.map((t) => t.url),
2300
- active,
2301
- ...handoff === void 0 ? {} : { handoff }
3016
+ tabs,
3017
+ conversations
2302
3018
  };
2303
3019
  try {
2304
3020
  writeFileSync3(`${this.file}.tmp`, JSON.stringify(body), { mode: 384 });
@@ -2312,23 +3028,32 @@ var SessionFile = class {
2312
3028
  this.forgotten = true;
2313
3029
  rmSync2(this.file, { force: true });
2314
3030
  }
3031
+ /** Gives the conversations their pending handoffs and persistent parks back. */
3032
+ restoreState(state, saved) {
3033
+ for (const c of saved.conversations) {
3034
+ if (c.handoff !== void 0)
3035
+ state.noticeHandoff(c.id, c.root, c.handoff.callId, c.handoff.message);
3036
+ for (const p of c.parks ?? []) state.park(c.id, c.root, { ...p, persist: true });
3037
+ }
3038
+ }
2315
3039
  /**
2316
- * Opens the saved tabs in a browser that has only its first blank tab. The navigations are
2317
- * started, not awaited: the first request after a restart does not wait for every page to load.
3040
+ * Opens the saved tabs, each for its owner, in a browser that has only its first blank tab, and
3041
+ * gives each conversation its active tab back. The navigations are started, not awaited: the
3042
+ * first request after a restart does not wait for every page to load.
2318
3043
  */
2319
3044
  async restoreTabs(session, saved) {
2320
- if (saved.tabs.length === 0) return;
2321
3045
  const ids = [];
2322
- for (const [i, url] of saved.tabs.entries()) {
3046
+ for (const t of saved.tabs) {
2323
3047
  try {
2324
- const page = i === 0 ? await session.activePage() : await session.openTab();
2325
- ids.push(session.tabIdOf(page));
2326
- void session.viewerNav({ url: normalizeUrl(url) });
3048
+ ids.push(await session.restoreTab({ owner: t.owner, root: t.root }, t.url));
2327
3049
  } catch {
3050
+ ids.push(void 0);
2328
3051
  }
2329
3052
  }
2330
- const active = ids[saved.active];
2331
- if (active !== void 0) await session.switchTo(active).catch(() => void 0);
3053
+ for (const c of saved.conversations) {
3054
+ const id = c.active === void 0 ? void 0 : ids[c.active];
3055
+ if (id !== void 0) session.setActive(c.id, id);
3056
+ }
2332
3057
  }
2333
3058
  };
2334
3059
 
@@ -2630,6 +3355,19 @@ var clampDim = (n, max) => typeof n === "number" && Number.isFinite(n) ? Math.ma
2630
3355
  var ViewerSession = class {
2631
3356
  browser;
2632
3357
  state;
3358
+ /** The viewer's conversation and the root of its tree (from the kernel's viewer context). */
3359
+ conv;
3360
+ root;
3361
+ /** The tab the person (or a new handoff) chose to show; cleared when it leaves the tree. */
3362
+ choice;
3363
+ /** The tab shown now (computed with every state). */
3364
+ shown;
3365
+ /** The other conversation the viewer pins because it shows one of its tabs. */
3366
+ pinnedOwner;
3367
+ /** Group keys of the tree's other conversations, in order of first appearance. */
3368
+ groups = /* @__PURE__ */ new Map();
3369
+ /** The tree's handoffs seen so far (a new one moves the shown tab to its conversation). */
3370
+ seenHandoffs = /* @__PURE__ */ new Set();
2633
3371
  out;
2634
3372
  clock;
2635
3373
  frameMaxBytes;
@@ -2691,6 +3429,9 @@ var ViewerSession = class {
2691
3429
  constructor(opts) {
2692
3430
  this.browser = opts.browser;
2693
3431
  this.state = opts.state;
3432
+ this.conv = opts.conversationId;
3433
+ this.root = opts.rootConversationId;
3434
+ this.state.pin(this.conv, this.root);
2694
3435
  this.out = opts.transport;
2695
3436
  this.clock = opts.clock;
2696
3437
  this.frameMaxBytes = opts.frameMaxBytes;
@@ -2711,8 +3452,11 @@ var ViewerSession = class {
2711
3452
  this.browser.on((e) => this.onSession(e)),
2712
3453
  this.state.onChange(() => this.onControl())
2713
3454
  );
3455
+ const pending = this.state.handoffs(this.root);
3456
+ this.seenHandoffs = new Set(pending.map(handoffKey));
3457
+ const newest = pending.at(-1);
3458
+ if (newest !== void 0) this.choice = this.browser.activeTabOf(newest.conversationId);
2714
3459
  this.sendState();
2715
- void this.serial(() => this.attach());
2716
3460
  this.ping();
2717
3461
  return;
2718
3462
  }
@@ -2738,7 +3482,7 @@ var ViewerSession = class {
2738
3482
  return;
2739
3483
  }
2740
3484
  case "takeover":
2741
- this.state.takeover();
3485
+ this.state.takeover(this.browser.owningConversations());
2742
3486
  return;
2743
3487
  case "handback":
2744
3488
  this.inputGen++;
@@ -2752,22 +3496,38 @@ var ViewerSession = class {
2752
3496
  this.input(() => this.key(m));
2753
3497
  return;
2754
3498
  case "nav":
2755
- this.input(
2756
- () => this.browser.viewerNav({
3499
+ this.input(async () => {
3500
+ let page = this.shownPage();
3501
+ if (page === void 0) {
3502
+ if (typeof m.url !== "string") return;
3503
+ page = await this.openOwnTab();
3504
+ if (page === void 0) return;
3505
+ }
3506
+ this.concern(this.browser.tabIdOf(page));
3507
+ await this.browser.viewerNav(page, {
2757
3508
  ...typeof m.url === "string" ? { url: m.url } : {},
2758
3509
  ...m.action === void 0 ? {} : { action: m.action }
2759
- })
2760
- );
3510
+ });
3511
+ });
3512
+ return;
3513
+ case "show":
3514
+ if (typeof m.tabId === "string" && this.inTree(m.tabId)) {
3515
+ this.choice = m.tabId;
3516
+ this.queueState();
3517
+ }
2761
3518
  return;
2762
3519
  case "tab":
3520
+ if (m.action === "adopt") {
3521
+ this.adopt(m.tabId);
3522
+ return;
3523
+ }
2763
3524
  this.input(async () => {
2764
3525
  try {
2765
- if (m.action === "open") await this.browser.openTab();
2766
- else if (m.action === "switch" && m.tabId !== void 0)
2767
- await this.browser.switchTo(m.tabId);
2768
- else if (m.action === "close" && m.tabId !== void 0) {
3526
+ if (m.action === "open") await this.openOwnTab();
3527
+ else if (m.action === "switch" && m.tabId !== void 0) this.switchTo(m.tabId);
3528
+ else if (m.action === "close" && m.tabId !== void 0 && this.inTree(m.tabId)) {
3529
+ this.concern(m.tabId);
2769
3530
  await this.browser.tabById(m.tabId).close();
2770
- await this.browser.activePage();
2771
3531
  }
2772
3532
  } catch {
2773
3533
  }
@@ -2775,6 +3535,69 @@ var ViewerSession = class {
2775
3535
  return;
2776
3536
  }
2777
3537
  }
3538
+ /** Whether a tab belongs to the viewer's tree. */
3539
+ inTree(tabId) {
3540
+ return this.browser.ownerOf(tabId)?.root === this.root && this.browser.pageById(tabId) !== void 0;
3541
+ }
3542
+ /** The shown tab's page, if the tree has one. */
3543
+ shownPage() {
3544
+ return this.browser.pageById(this.shown);
3545
+ }
3546
+ /** The person used a tab during the takeover: its owner gets the hand back note. */
3547
+ concern(tabId) {
3548
+ if (tabId === void 0) return;
3549
+ this.state.concern(this.browser.ownerOf(tabId)?.owner);
3550
+ }
3551
+ /**
3552
+ * A tab the person opens: owned by the viewer's conversation, made its active tab and shown
3553
+ * (the caps apply; a refusal opens nothing).
3554
+ */
3555
+ async openOwnTab() {
3556
+ try {
3557
+ const page = this.browser.countOf(this.conv) === 0 ? await this.browser.pageFor(this.conv, this.root) : await this.browser.openTab(this.conv, this.root);
3558
+ this.state.concern(this.conv);
3559
+ this.choice = void 0;
3560
+ this.queueState();
3561
+ return page;
3562
+ } catch {
3563
+ return void 0;
3564
+ }
3565
+ }
3566
+ /**
3567
+ * Shows a tab of the tree and brings it to the front (a viewer in control decides what is
3568
+ * front). A tab of the viewer's own conversation also becomes its active tab (the person chose
3569
+ * it); another conversation's tab changes only the shown tab, never that agent's active tab.
3570
+ */
3571
+ switchTo(tabId) {
3572
+ if (!this.inTree(tabId)) return;
3573
+ if (this.browser.ownerOf(tabId)?.owner === this.conv) {
3574
+ this.browser.setActive(this.conv, tabId);
3575
+ this.choice = void 0;
3576
+ } else this.choice = tabId;
3577
+ void this.browser.bringToFront(tabId);
3578
+ this.queueState();
3579
+ }
3580
+ /**
3581
+ * Moves another tree's tab (or an unowned one) to the viewer's conversation, as the tool's adopt;
3582
+ * a tab of the viewer's own tree is ignored (inside the tree the person drives tabs without
3583
+ * moving them). A tab whose owner is in use answers the `tab_in_use` notice.
3584
+ */
3585
+ adopt(tabId) {
3586
+ if (typeof tabId !== "string" || this.browser.pageById(tabId) === void 0) return;
3587
+ if (this.browser.ownerOf(tabId)?.root === this.root) return;
3588
+ let result;
3589
+ try {
3590
+ result = this.browser.adopt(this.conv, this.root, tabId);
3591
+ } catch {
3592
+ return;
3593
+ }
3594
+ if (result === "in_use") this.send({ t: "notice", code: "tab_in_use" });
3595
+ else if (result === "cap") this.send({ t: "notice", code: "tab_cap" });
3596
+ else if (result === "ok") {
3597
+ this.choice = void 0;
3598
+ this.queueState();
3599
+ }
3600
+ }
2778
3601
  /**
2779
3602
  * Runs viewer input in arrival order, apart from the screencast chain, and only while the person
2780
3603
  * holds control: input from a viewer in the watch state (the agent drives) is dropped, both when
@@ -2801,7 +3624,8 @@ var ViewerSession = class {
2801
3624
  const slot = { ...p };
2802
3625
  this.input(async () => {
2803
3626
  if (this.moveSlot === slot) this.moveSlot = void 0;
2804
- const page = await this.browser.activePage();
3627
+ const page = this.shownPage();
3628
+ if (page === void 0) return;
2805
3629
  try {
2806
3630
  await page.mouse.move(slot.x, slot.y);
2807
3631
  } catch {
@@ -2860,11 +3684,14 @@ var ViewerSession = class {
2860
3684
  get driving() {
2861
3685
  return !this.closed && this.state.control === "user";
2862
3686
  }
2863
- /** Ends the viewer: stops its screencast and its subscriptions. */
3687
+ /** Ends the viewer: stops its screencast and its subscriptions, and lets go of its pins. */
2864
3688
  async close() {
2865
3689
  if (this.closed) return;
2866
3690
  this.closed = true;
2867
3691
  this.inputGen++;
3692
+ this.state.unpin(this.conv);
3693
+ if (this.pinnedOwner !== void 0) this.state.unpin(this.pinnedOwner);
3694
+ this.pinnedOwner = void 0;
2868
3695
  await this.releaseHeld();
2869
3696
  for (const u of this.unsubscribe.splice(0)) u();
2870
3697
  for (const t of [this.pumpTimer, this.pingTimer, this.encodeTimer])
@@ -2884,8 +3711,18 @@ var ViewerSession = class {
2884
3711
  this.send({ t: "ping", id });
2885
3712
  this.pingTimer = this.clock.schedule(() => this.ping(), VIEWER_PING_MS);
2886
3713
  }
2887
- /** Control changed (takeover, hand back): a new state, and input of the old control dropped. */
3714
+ /**
3715
+ * Control or handoffs changed: a new state; input of the old control dropped; a new handoff of
3716
+ * the tree shows its conversation's active tab.
3717
+ */
2888
3718
  onControl() {
3719
+ const pending = this.state.handoffs(this.root);
3720
+ const fresh = pending.filter((h) => !this.seenHandoffs.has(handoffKey(h))).at(-1);
3721
+ this.seenHandoffs = new Set(pending.map(handoffKey));
3722
+ if (fresh !== void 0) {
3723
+ const tab = this.browser.activeTabOf(fresh.conversationId);
3724
+ if (tab !== void 0) this.choice = tab;
3725
+ }
2889
3726
  const control = this.state.control;
2890
3727
  if (control !== this.lastControl) {
2891
3728
  this.lastControl = control;
@@ -2917,7 +3754,6 @@ var ViewerSession = class {
2917
3754
  const plain = { ...m, tabs: m.tabs.map(({ favicon: _icon, ...t }) => t) };
2918
3755
  if (fits(plain)) return plain;
2919
3756
  m = plain;
2920
- const handoff = m.handoff === void 0 ? {} : { handoff: { ...m.handoff, message: clip(m.handoff.message, 200) } };
2921
3757
  small = {
2922
3758
  ...m,
2923
3759
  tabs: m.tabs.map((t) => ({
@@ -2926,7 +3762,12 @@ var ViewerSession = class {
2926
3762
  url: clip(t.url, 200),
2927
3763
  ...t.blocker === void 0 ? {} : { blocker: { ...t.blocker, url: clip(t.blocker.url, 200) } }
2928
3764
  })),
2929
- ...handoff
3765
+ otherTabs: m.otherTabs.map((t) => ({
3766
+ ...t,
3767
+ title: clip(t.title, 200),
3768
+ url: clip(t.url, 200)
3769
+ })),
3770
+ handoffs: m.handoffs.map((h) => ({ ...h, message: clip(h.message, 200) }))
2930
3771
  };
2931
3772
  } else if (m.t === "dialog") {
2932
3773
  small = { ...m, message: clip(m.message, 200) };
@@ -2953,14 +3794,12 @@ var ViewerSession = class {
2953
3794
  onSession(e) {
2954
3795
  if (e.type === "state") this.queueState();
2955
3796
  else if (e.type === "active") {
3797
+ if (e.conversationId === this.conv) this.choice = void 0;
3798
+ else if (this.shown !== void 0 && this.browser.ownerOf(this.shown)?.owner === e.conversationId)
3799
+ this.choice = this.browser.activeTabOf(e.conversationId);
2956
3800
  this.queueState();
2957
- void this.serial(async () => {
2958
- const page = await this.browser.activePage();
2959
- if (page === this.page) return;
2960
- await this.detach();
2961
- await this.attach();
2962
- });
2963
- } else if (e.type === "blocked") this.send({ t: "blocked", host: e.host, url: e.url });
3801
+ } else if (e.root !== this.root) return;
3802
+ else if (e.type === "blocked") this.send({ t: "blocked", host: e.host, url: e.url });
2964
3803
  else this.send({ t: "dialog", kind: e.kind, message: e.message });
2965
3804
  }
2966
3805
  /** Coalesces bursts of changes into one state message. */
@@ -2972,18 +3811,88 @@ var ViewerSession = class {
2972
3811
  this.sendState();
2973
3812
  });
2974
3813
  }
3814
+ /**
3815
+ * The tab to show: the chosen one while it is in the tree; else the viewer's conversation's
3816
+ * active tab; else the active tab of the tree's conversation that acted last; else the tree's
3817
+ * first tab; none when the tree owns no tab.
3818
+ */
3819
+ computeShown(tree) {
3820
+ if (this.choice !== void 0 && tree.some((t) => t.id === this.choice)) return this.choice;
3821
+ this.choice = void 0;
3822
+ const own = this.browser.activeTabOf(this.conv);
3823
+ if (own !== void 0) return own;
3824
+ let best;
3825
+ for (const owner of new Set(tree.map((t) => t.owner))) {
3826
+ if (owner === void 0) continue;
3827
+ const tab = this.browser.activeTabOf(owner);
3828
+ const order = this.browser.actedOrder(owner);
3829
+ if (tab !== void 0 && (best === void 0 || order > best.order)) best = { tab, order };
3830
+ }
3831
+ return best?.tab ?? tree[0]?.id;
3832
+ }
3833
+ /** Pins the owner of the shown tab (besides the viewer's own conversation). */
3834
+ pinShownOwner() {
3835
+ const owner = this.shown === void 0 ? void 0 : this.browser.ownerOf(this.shown);
3836
+ const next = owner === void 0 || owner.owner === this.conv ? void 0 : owner.owner;
3837
+ if (next === this.pinnedOwner) return;
3838
+ if (next !== void 0 && owner !== void 0) this.state.pin(next, owner.root);
3839
+ if (this.pinnedOwner !== void 0) this.state.unpin(this.pinnedOwner);
3840
+ this.pinnedOwner = next;
3841
+ }
3842
+ groupOf(owner) {
3843
+ if (owner === this.conv || owner === void 0) return "own";
3844
+ let g = this.groups.get(owner);
3845
+ if (g === void 0) {
3846
+ g = `sub${this.groups.size + 1}`;
3847
+ this.groups.set(owner, g);
3848
+ }
3849
+ return g;
3850
+ }
2975
3851
  sendState() {
2976
- const tabs = this.browser.tabs();
2977
- const active = tabs.find((t) => t.active);
2978
- const last = this.browser.lastClick;
3852
+ if (this.closed) return;
3853
+ const all = this.browser.tabs();
3854
+ const tree = all.filter((t) => t.root === this.root);
3855
+ this.shown = this.computeShown(tree);
3856
+ this.pinShownOwner();
3857
+ if (this.browser.pageById(this.shown) !== this.page) {
3858
+ void this.serial(async () => {
3859
+ if (this.browser.pageById(this.shown) === this.page) return;
3860
+ await this.detach();
3861
+ await this.attach();
3862
+ });
3863
+ }
3864
+ const order = /* @__PURE__ */ new Map([["own", 0]]);
3865
+ const tabs = tree.map((t) => {
3866
+ const group = this.groupOf(t.owner);
3867
+ if (!order.has(group)) order.set(group, order.size);
3868
+ return {
3869
+ id: t.id,
3870
+ title: t.title,
3871
+ url: t.url,
3872
+ active: t.id === this.shown,
3873
+ group,
3874
+ ...t.blocker === void 0 ? {} : { blocker: t.blocker },
3875
+ ...t.favicon === void 0 ? {} : { favicon: t.favicon }
3876
+ };
3877
+ });
3878
+ tabs.sort((a, b) => (order.get(a.group) ?? 0) - (order.get(b.group) ?? 0));
3879
+ const shownTab = tree.find((t) => t.id === this.shown);
3880
+ const last = this.browser.lastClickOf(this.shown);
2979
3881
  this.send({
2980
3882
  t: "state",
2981
3883
  tabs,
2982
- loading: this.browser.loading,
2983
- secure: active?.url.startsWith("https:") ?? false,
3884
+ ...this.shown === void 0 ? {} : { shown: this.shown },
3885
+ otherTabs: all.filter((t) => t.root !== this.root && !isStartBlank(t)).map((t) => ({ id: t.id, title: t.title, url: t.url })),
3886
+ loading: this.browser.isLoading(this.shown),
3887
+ secure: shownTab?.url.startsWith("https:") ?? false,
2984
3888
  control: this.state.control,
2985
3889
  ...last === void 0 ? {} : { lastClick: last },
2986
- ...this.state.handoff === void 0 ? {} : { handoff: this.state.handoff }
3890
+ handoffs: this.state.handoffs(this.root).map((h) => ({
3891
+ callId: h.callId,
3892
+ conversationId: h.conversationId,
3893
+ message: h.message,
3894
+ tabIds: this.browser.tabsOf(h.conversationId)
3895
+ }))
2987
3896
  });
2988
3897
  }
2989
3898
  get scale() {
@@ -2995,7 +3904,8 @@ var ViewerSession = class {
2995
3904
  }
2996
3905
  async attach() {
2997
3906
  if (this.closed) return;
2998
- const page = await this.browser.activePage();
3907
+ const page = this.shownPage();
3908
+ if (page === void 0) return;
2999
3909
  const cdp = await this.browser.context.newCDPSession(page);
3000
3910
  this.page = page;
3001
3911
  this.cdp = cdp;
@@ -3125,9 +4035,10 @@ var ViewerSession = class {
3125
4035
  this.scheduleEncodeAck();
3126
4036
  }
3127
4037
  async mouse(m) {
3128
- const page = await this.browser.activePage();
4038
+ const page = this.shownPage();
3129
4039
  const p = point(m);
3130
- if (p === null) return;
4040
+ if (p === null || page === void 0) return;
4041
+ this.concern(this.browser.tabIdOf(page));
3131
4042
  const { x, y } = p;
3132
4043
  const button = m.button === "right" ? "right" : "left";
3133
4044
  try {
@@ -3150,7 +4061,9 @@ var ViewerSession = class {
3150
4061
  if (m.kind !== "down") this.wantCursor(x, y);
3151
4062
  }
3152
4063
  async key(m) {
3153
- const page = await this.browser.activePage();
4064
+ const page = this.shownPage();
4065
+ if (page === void 0) return;
4066
+ this.concern(this.browser.tabIdOf(page));
3154
4067
  try {
3155
4068
  if (m.kind === "char") {
3156
4069
  const text = m.text ?? m.key;
@@ -3168,6 +4081,7 @@ var ViewerSession = class {
3168
4081
  }
3169
4082
  }
3170
4083
  };
4084
+ var handoffKey = (h) => `${h.conversationId}\0${h.callId}`;
3171
4085
  function point(m) {
3172
4086
  const x = Number(m.x);
3173
4087
  const y = Number(m.y);
@@ -3252,16 +4166,20 @@ async function startDaemon(opts) {
3252
4166
  let closing = false;
3253
4167
  const sessionFile = new SessionFile(opts.stateDir, clock);
3254
4168
  const saved = sessionFile.read();
4169
+ let live;
3255
4170
  const state = new DaemonState({
3256
4171
  clock,
3257
4172
  ...opts.idleMs === void 0 ? {} : { idleMs: opts.idleMs },
4173
+ ...opts.conversationIdleMs === void 0 ? {} : { conversationIdleMs: opts.conversationIdleMs },
3258
4174
  onIdle: () => {
3259
4175
  sessionFile.forget();
3260
4176
  opts.onIdle?.();
4177
+ },
4178
+ onConversationIdle: (conversationId) => {
4179
+ void live?.closeConversation(conversationId);
3261
4180
  }
3262
4181
  });
3263
- if (saved?.handoff !== void 0)
3264
- state.noticeHandoff(saved.handoff.callId, saved.handoff.message);
4182
+ if (saved !== void 0) sessionFile.restoreState(state, saved);
3265
4183
  const launch = opts.launch ?? launchChromium;
3266
4184
  const closeGraceMs = opts.browserCloseGraceMs ?? BROWSER_CLOSE_GRACE_MS;
3267
4185
  let current;
@@ -3299,6 +4217,7 @@ async function startDaemon(opts) {
3299
4217
  current = starting;
3300
4218
  starting.catch(() => {
3301
4219
  if (current === starting) current = void 0;
4220
+ live = void 0;
3302
4221
  if (running?.launch === starting) running = void 0;
3303
4222
  });
3304
4223
  return starting;
@@ -3316,6 +4235,7 @@ async function startDaemon(opts) {
3316
4235
  const session = new BrowserSession(ctx, {
3317
4236
  proxy: plan.proxy,
3318
4237
  clock,
4238
+ usage: state,
3319
4239
  workspace: workspace === void 0 || workspace === "" ? void 0 : workspace,
3320
4240
  downloadsTmp: plan.downloadsTmp,
3321
4241
  downloadMaxBytes: downloadMaxBytes(opts.env),
@@ -3332,10 +4252,11 @@ async function startDaemon(opts) {
3332
4252
  if (saved !== void 0) await sessionFile.restoreTabs(session, saved);
3333
4253
  }
3334
4254
  if (!closing) {
3335
- const save = () => sessionFile.save(session, () => state.handoff);
4255
+ const save = () => sessionFile.save(session, state);
3336
4256
  session.on(save);
3337
4257
  state.onChange(save);
3338
4258
  }
4259
+ if (!failed()) live = session;
3339
4260
  return session;
3340
4261
  }
3341
4262
  }
@@ -3400,11 +4321,12 @@ async function startDaemon(opts) {
3400
4321
  async function handoffOp(req) {
3401
4322
  if (typeof req.callId !== "string" || req.callId === "")
3402
4323
  return fail("The handoff needs a callId.");
4324
+ const conv = req.conversationId;
3403
4325
  if (req.op === "handoff_notice") {
3404
4326
  if (typeof req.message !== "string") return fail("The handoff notice needs a message.");
3405
- state.noticeHandoff(req.callId, req.message);
4327
+ state.noticeHandoff(conv, req.rootConversationId, req.callId, req.message);
3406
4328
  } else {
3407
- state.clearHandoff(req.callId);
4329
+ state.clearHandoff(conv, req.callId);
3408
4330
  if (req.handback === true) state.handback();
3409
4331
  }
3410
4332
  let session;
@@ -3413,15 +4335,38 @@ async function startDaemon(opts) {
3413
4335
  } catch (e) {
3414
4336
  return launchFailure(e);
3415
4337
  }
3416
- return { ok: true, page: await session.pageInfo(await session.activePage()), blockedHosts: [] };
4338
+ const page = session.currentPage(conv);
4339
+ return {
4340
+ ok: true,
4341
+ ...page === void 0 ? {} : { page: await session.pageInfo(page) },
4342
+ blockedHosts: []
4343
+ };
3417
4344
  }
4345
+ const namesConversation = (raw) => {
4346
+ const r = raw;
4347
+ return typeof r.conversationId === "string" && r.conversationId !== "" && typeof r.rootConversationId === "string" && r.rootConversationId !== "";
4348
+ };
3418
4349
  async function handleRequest(raw) {
3419
4350
  if (typeof raw !== "object" || raw === null || !REQUEST_OPS.has(String(raw.op))) {
3420
4351
  return fail("Unknown browser request.");
3421
4352
  }
4353
+ if (!namesConversation(raw)) return fail(NO_CONVERSATION_MESSAGE);
3422
4354
  const req = raw;
4355
+ const conv = req.conversationId;
4356
+ state.requestArrived(conv, req.rootConversationId);
4357
+ let reply;
4358
+ try {
4359
+ reply = await conversationRequest(req);
4360
+ } catch (e) {
4361
+ reply = fail(e instanceof ActionError ? e.message : String(e));
4362
+ } finally {
4363
+ state.requestFinished(conv);
4364
+ }
4365
+ return { ...reply, tabs: { open: live?.countOf(conv) ?? 0, max: MAX_TABS_PER_CONVERSATION } };
4366
+ }
4367
+ async function conversationRequest(req) {
3423
4368
  if (req.op === "handoff_notice" || req.op === "handoff_clear") return handoffOp(req);
3424
- state.dropHandoff();
4369
+ state.dropHandoff(req.conversationId);
3425
4370
  if (state.control === "user" && req.op !== "wait") {
3426
4371
  return { ok: false, error: "taken_over", message: TAKEN_OVER_MESSAGE, blockedHosts: [] };
3427
4372
  }
@@ -3433,7 +4378,7 @@ async function startDaemon(opts) {
3433
4378
  }
3434
4379
  const reply = await session.run(req, { takenOver: () => state.control === "user" });
3435
4380
  if (reply.ok) {
3436
- const since = state.takeHandbackNote();
4381
+ const since = state.takeHandbackNote(req.conversationId);
3437
4382
  if (since !== void 0) reply.userControlledSince = since;
3438
4383
  }
3439
4384
  return reply;
@@ -3443,6 +4388,7 @@ async function startDaemon(opts) {
3443
4388
  sockets.add(sock);
3444
4389
  const decoder = new ServiceMessageDecoder();
3445
4390
  let kind;
4391
+ let context;
3446
4392
  let handled = false;
3447
4393
  let viewer;
3448
4394
  let opened = false;
@@ -3465,37 +4411,51 @@ async function startDaemon(opts) {
3465
4411
  if (kind === void 0) {
3466
4412
  const first = parse(raw);
3467
4413
  if (first?.kind === "request") kind = "request";
3468
- else if (first?.kind === "stream") {
3469
- kind = "stream";
3470
- opened = true;
3471
- state.viewerOpened();
3472
- browser().then(
3473
- (session) => {
3474
- if (sock.destroyed) return;
3475
- viewer = new ViewerSession({
3476
- browser: session,
3477
- state,
3478
- clock,
3479
- frameMaxBytes: frameCap,
3480
- transport: {
3481
- send: (m) => {
3482
- let dropped = false;
3483
- const ok = write(sock, m, () => {
3484
- dropped = true;
3485
- });
3486
- return ok || dropped || sock.destroyed;
3487
- },
3488
- sendFrame: (frame) => {
3489
- if (sock.destroyed) return true;
3490
- return sock.write(encodeServiceMessage(frame));
3491
- },
3492
- whenDrained: () => new Promise((r) => sock.once("drain", () => r()))
3493
- }
3494
- });
3495
- },
3496
- () => sock.destroy()
3497
- );
3498
- } else sock.destroy();
4414
+ else if (first?.kind === "stream") kind = "stream";
4415
+ else sock.destroy();
4416
+ return;
4417
+ }
4418
+ if (kind === "stream" && context === void 0) {
4419
+ const ctx = parseViewerContext(raw);
4420
+ if (ctx === null) {
4421
+ sock.destroy();
4422
+ return;
4423
+ }
4424
+ context = {
4425
+ conversationId: ctx.conversationId,
4426
+ rootConversationId: ctx.rootConversationId
4427
+ };
4428
+ const viewerContext = context;
4429
+ opened = true;
4430
+ state.viewerOpened();
4431
+ browser().then(
4432
+ (session) => {
4433
+ if (sock.destroyed) return;
4434
+ viewer = new ViewerSession({
4435
+ browser: session,
4436
+ state,
4437
+ conversationId: viewerContext.conversationId,
4438
+ rootConversationId: viewerContext.rootConversationId,
4439
+ clock,
4440
+ frameMaxBytes: frameCap,
4441
+ transport: {
4442
+ send: (m) => {
4443
+ let dropped = false;
4444
+ const ok = write(sock, m, () => {
4445
+ dropped = true;
4446
+ });
4447
+ return ok || dropped || sock.destroyed;
4448
+ },
4449
+ sendFrame: (frame) => {
4450
+ if (sock.destroyed) return true;
4451
+ return sock.write(encodeServiceMessage(frame));
4452
+ },
4453
+ whenDrained: () => new Promise((r) => sock.once("drain", () => r()))
4454
+ }
4455
+ });
4456
+ },
4457
+ () => sock.destroy()
4458
+ );
3499
4459
  return;
3500
4460
  }
3501
4461
  if (kind === "request") {