@capybara-hq/plugin-browser 0.1.0-rc.13 → 0.1.0-rc.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "schemaVersion": 1,
3
3
  "name": "browser",
4
- "version": "0.1.0-rc.13",
4
+ "version": "0.1.0-rc.15",
5
5
  "publisher": "Capybara",
6
6
  "description": {
7
7
  "en": "A real browser in the conversation owner's device for agents: navigate, read and act on pages through tools, with a live view in the conversation panel and takeover by the person",
@@ -17,7 +17,7 @@
17
17
  "entry": "./dist/index.mjs",
18
18
  "manifest": {
19
19
  "name": "browser",
20
- "version": "0.1.0-rc.13",
20
+ "version": "0.1.0-rc.15",
21
21
  "sdk": "^0.1.0-rc.83",
22
22
  "provides": [],
23
23
  "requires": [],
package/dist/index.mjs CHANGED
@@ -1514,7 +1514,7 @@ function registerBrowserTools(ctx, deps) {
1514
1514
  // src/index.ts
1515
1515
  var index_default = defineExtension({
1516
1516
  name: "browser",
1517
- version: "0.1.0-rc.13",
1517
+ version: "0.1.0-rc.15",
1518
1518
  sdk: "^0.1.0-rc.83",
1519
1519
  provides: [],
1520
1520
  ui: [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/plugin-browser",
3
- "version": "0.1.0-rc.13",
3
+ "version": "0.1.0-rc.15",
4
4
  "type": "module",
5
5
  "license": "Apache-2.0",
6
6
  "description": "A real browser in the person's device for agents: navigate, read and act on pages through tools, with a live view in the conversation and takeover by the person",
@@ -175,6 +175,8 @@ import { basename, extname, join, sep } from "node:path";
175
175
 
176
176
  // daemon/protocol.ts
177
177
  var ROLL_CHECK_REQUEST = '{"capybara":"roll-check"}';
178
+ var BROWSER_CRASHED_MESSAGE = "The browser in the device stopped unexpectedly while this ran (it crashed). It starts again on the next browser call, with this conversation's tabs reopened; call browser_snapshot to see the page, and retry if the action did not happen.";
179
+ var BROWSER_RESTARTED_NOTE = "The browser in the device stopped unexpectedly (it crashed) and was started again: this conversation's tabs were reopened at their last addresses, and anything typed into them but not submitted is gone.";
178
180
  var CONVERSATION_DELETED_MESSAGE = "This conversation was deleted; its browser tabs are closed.";
179
181
  var VIEWPORT = { width: 1280, height: 800 };
180
182
  var VIEWPORT_PROFILES = {
@@ -1259,6 +1261,8 @@ var MAX_URL_CHARS = 2048;
1259
1261
  var MAX_DIALOG_CHARS = 4096;
1260
1262
  var DEFAULT_WAIT_MS = 1e4;
1261
1263
  var MAX_UNREPORTED = 20;
1264
+ var RESTORE_NAV_WAIT_MS = 1e4;
1265
+ var LOST_TAB_WINDOW_MS = 5e3;
1262
1266
  var TAKEN_OVER_MESSAGE = "The user is controlling the browser; call wait or handoff.";
1263
1267
  function clip(s, max) {
1264
1268
  return s.length <= max ? s : `${s.slice(0, Math.max(0, max - 1))}\u2026`;
@@ -1524,6 +1528,7 @@ async function captureFitting(cdp, opts) {
1524
1528
  const area = opts.fullPage ? { x: 0, y: 0, width: content.width, height: Math.min(content.height, 16384) } : { x: vv.pageX, y: vv.pageY, width: vv.clientWidth, height: vv.clientHeight };
1525
1529
  const maxScale = Math.min(1, opts.maxScale ?? 1);
1526
1530
  const zoom = opts.fullPage === true ? 1 : vv.scale > 0 && vv.scale < 1 ? vv.scale : 1;
1531
+ const device = opts.deviceScale !== void 0 && opts.deviceScale > 0 ? opts.deviceScale : 1;
1527
1532
  for (const s of SCALES) {
1528
1533
  const scale = s * maxScale * zoom;
1529
1534
  if (scale * area.width < 16) break;
@@ -1531,7 +1536,7 @@ async function captureFitting(cdp, opts) {
1531
1536
  const shot = await cdp.send("Page.captureScreenshot", {
1532
1537
  format: "jpeg",
1533
1538
  quality,
1534
- clip: { ...area, scale },
1539
+ clip: { ...area, scale: scale / device },
1535
1540
  captureBeyondViewport: opts.fullPage === true
1536
1541
  });
1537
1542
  const bytes = Buffer.from(shot.data, "base64");
@@ -1777,6 +1782,12 @@ var BrowserSession = class {
1777
1782
  watches;
1778
1783
  /** Short download waits: resolved with the saved path when a download of `conv` is saved. */
1779
1784
  downloadWaiters = /* @__PURE__ */ new Set();
1785
+ /** The restore navigation of each restored tab, until it settles (see restoredTabsOf). */
1786
+ restoring = /* @__PURE__ */ new Map();
1787
+ /** Pages the session closes itself (a tab close, a popup past a cap): never "lost". */
1788
+ closedOnPurpose = /* @__PURE__ */ new WeakSet();
1789
+ /** Owned tabs that closed without the session closing them, newest last (see lostTabs). */
1790
+ lost = [];
1780
1791
  /** The dialog each tab holds until answered (one per tab: JS dialogs are modal per page). */
1781
1792
  held = /* @__PURE__ */ new Map();
1782
1793
  dialogSeq = 0;
@@ -1809,6 +1820,12 @@ var BrowserSession = class {
1809
1820
  profileSessions = /* @__PURE__ */ new Map();
1810
1821
  /** Every agent request waits for this (a restore to desktop after hand back). */
1811
1822
  viewportGate = Promise.resolve();
1823
+ /** The clipped captures queued or running (a profile change waits for them: see `capture`). */
1824
+ captures = /* @__PURE__ */ new Set();
1825
+ /** The profile sessions that sent device metrics (a capture through one puts them back). */
1826
+ withMetrics = /* @__PURE__ */ new WeakSet();
1827
+ /** The newest clipped capture (they run one at a time). */
1828
+ captureTail = Promise.resolve();
1812
1829
  mobileUa;
1813
1830
  /** The pages' own user agent (given back when the phone profile ends). */
1814
1831
  desktopUa;
@@ -1953,6 +1970,31 @@ var BrowserSession = class {
1953
1970
  };
1954
1971
  });
1955
1972
  }
1973
+ recordLost(o, id, page) {
1974
+ const url = page.url();
1975
+ if (!/^https?:\/\//i.test(url)) return;
1976
+ this.lost.push({
1977
+ url,
1978
+ owner: o.owner,
1979
+ root: o.root,
1980
+ active: this.activeOf.get(o.owner) === id,
1981
+ at: this.clock.now()
1982
+ });
1983
+ if (this.lost.length > MAX_TABS) this.lost.shift();
1984
+ }
1985
+ /**
1986
+ * The owned http(s) tabs that closed without the session closing them in the last
1987
+ * {@link LOST_TAB_WINDOW_MS}, in the order they closed: after a crash, the tabs the browser had.
1988
+ */
1989
+ lostTabs() {
1990
+ const since = this.clock.now() - LOST_TAB_WINDOW_MS;
1991
+ return this.lost.filter((t) => t.at >= since).map((t) => ({ ...t }));
1992
+ }
1993
+ /** Closes a tab on purpose (the agent's or a viewer's close). */
1994
+ async closeTab(page) {
1995
+ this.closedOnPurpose.add(page);
1996
+ await page.close();
1997
+ }
1956
1998
  /** Makes a tab the conversation's active tab (it must own it). */
1957
1999
  setActive(conversationId, tabId) {
1958
2000
  if (this.owners.get(tabId)?.owner !== conversationId) return;
@@ -2168,9 +2210,37 @@ var BrowserSession = class {
2168
2210
  target = normalizeUrl(url);
2169
2211
  } catch {
2170
2212
  }
2171
- if (target !== void 0) void this.viewerNav(page, { url: target });
2213
+ if (target !== void 0) {
2214
+ const nav = this.viewerNav(page, { url: target }).finally(() => {
2215
+ if (this.restoring.get(id) === nav) this.restoring.delete(id);
2216
+ });
2217
+ this.restoring.set(id, nav);
2218
+ }
2172
2219
  return id;
2173
2220
  }
2221
+ /**
2222
+ * Waits, at most {@link RESTORE_NAV_WAIT_MS}, for the restore navigations of the conversation's
2223
+ * tabs: its first request after a restart (or a crash) must not race them (a navigation of its
2224
+ * own would be interrupted by the restore's). Other conversations' tabs are not waited for.
2225
+ */
2226
+ async restoredTabsOf(conv) {
2227
+ const navs = this.tabsOf(conv).map((id) => this.restoring.get(id)).filter((n) => n !== void 0);
2228
+ if (navs.length === 0) return;
2229
+ await this.boundedWait(Promise.all(navs), RESTORE_NAV_WAIT_MS);
2230
+ }
2231
+ async boundedWait(p, ms) {
2232
+ let timer;
2233
+ await Promise.race([
2234
+ p.then(
2235
+ () => void 0,
2236
+ () => void 0
2237
+ ),
2238
+ new Promise((r) => {
2239
+ timer = this.clock.schedule(r, ms);
2240
+ })
2241
+ ]);
2242
+ this.clock.cancel(timer);
2243
+ }
2174
2244
  /**
2175
2245
  * Closes an idle conversation's tabs (except those a park pins) and forgets what the session
2176
2246
  * keeps for it.
@@ -2232,7 +2302,7 @@ var BrowserSession = class {
2232
2302
  const id = `t${this.nextId++}`;
2233
2303
  this.ids.set(page, id);
2234
2304
  this.pages.set(id, page);
2235
- if (this.profile === "phone") void this.applyPhone(page);
2305
+ if (this.profile === "phone") this.queueProfileChange(() => this.applyPhone(page));
2236
2306
  const refresh = () => {
2237
2307
  page.title().then((t) => this.titles.set(id, t)).catch(() => void 0).then(() => this.checkVerification(page, id)).finally(() => this.emit({ type: "state" }));
2238
2308
  };
@@ -2305,6 +2375,9 @@ var BrowserSession = class {
2305
2375
  });
2306
2376
  page.on("popup", (p) => this.onPopup(page, p));
2307
2377
  page.on("close", () => {
2378
+ const lostOwner = this.owners.get(id);
2379
+ if (lostOwner !== void 0 && !this.closing.has(id) && !this.closedOnPurpose.has(page))
2380
+ this.recordLost(lostOwner, id, page);
2308
2381
  this.pendingNavs.delete(page);
2309
2382
  this.pages.delete(id);
2310
2383
  this.closing.delete(id);
@@ -2338,6 +2411,7 @@ var BrowserSession = class {
2338
2411
  const o = this.owners.get(this.tabIdOf(opener));
2339
2412
  if (o === void 0 || this.owners.has(id) || popup.isClosed()) return;
2340
2413
  const closeIt = (why) => {
2414
+ this.closedOnPurpose.add(popup);
2341
2415
  popup.close().catch(() => void 0);
2342
2416
  this.noteTo(
2343
2417
  o.owner,
@@ -2517,10 +2591,56 @@ var BrowserSession = class {
2517
2591
  this.signIn(origin, m.username, m.password);
2518
2592
  for (const [id, x] of [...this.held])
2519
2593
  if (x.view.kind === "auth" && x.view.origin === origin) this.clearHeld(id);
2520
- this.noteTo(h.owner.owner, `The user signed in to ${origin} (HTTP auth).`);
2521
- const page = this.pageById(h.view.tabId);
2522
- if (page !== void 0)
2523
- await this.viewerNav(page, h.atUrl === void 0 ? { action: "reload" } : { url: h.atUrl });
2594
+ const tabId = h.view.tabId;
2595
+ const page = this.pageById(tabId);
2596
+ if (page === void 0) {
2597
+ this.authNote(
2598
+ h.owner.owner,
2599
+ origin,
2600
+ "the user entered credentials, but the tab closed before the site answered."
2601
+ );
2602
+ return;
2603
+ }
2604
+ await this.viewerNav(page, h.atUrl === void 0 ? { action: "reload" } : { url: h.atUrl });
2605
+ this.authNote(h.owner.owner, origin, this.authOutcome(page, tabId, origin));
2606
+ }
2607
+ /**
2608
+ * What the site answered the credentials the person entered, after the tab loaded again with
2609
+ * them: rejected when the tab holds a new auth dialog for the origin, its document answered
2610
+ * 401 / 407 or the 401 to a signed request dropped them; accepted when the tab shows a document
2611
+ * of the origin with another status; unknown otherwise (the load failed or went elsewhere).
2612
+ */
2613
+ authOutcome(page, tabId, origin) {
2614
+ const again = this.held.get(tabId);
2615
+ if (again?.view.kind === "auth" && again.view.origin === origin)
2616
+ return `the site rejected the credentials the user entered and asks to sign in again (dialog ${again.view.id}); ask the user to sign in again with browser_handoff, or dismiss the dialog.`;
2617
+ const status = this.docStatus.get(tabId);
2618
+ if (status === 401 || status === 407 || !this.credentials.has(origin))
2619
+ return `the site rejected the credentials the user entered${status === void 0 ? "" : ` (status ${status})`}; ask the user to sign in again with browser_handoff.`;
2620
+ if (status !== void 0 && !page.isClosed() && originOf(page.url()) === origin)
2621
+ return `the site accepted the credentials the user entered (status ${status}).`;
2622
+ return "the user entered credentials, but the page did not load, so whether the site accepted them is unknown; call browser_snapshot to check.";
2623
+ }
2624
+ /**
2625
+ * The outcome note of a sign-in to `origin` for a conversation: it replaces the outcome of an
2626
+ * earlier attempt for the same origin that no reply carried yet (each attempt says only what
2627
+ * the site answered last). Never carries the credentials.
2628
+ */
2629
+ authNote(conversationId, origin, outcome) {
2630
+ const prefix = `HTTP sign-in to ${origin}: `;
2631
+ const stale = (n) => n.startsWith(prefix);
2632
+ const waiting = this.unreported.get(conversationId);
2633
+ if (waiting !== void 0) {
2634
+ const kept = waiting.filter((n) => !stale(n));
2635
+ if (kept.length === 0) this.unreported.delete(conversationId);
2636
+ else this.unreported.set(conversationId, kept);
2637
+ }
2638
+ for (const c of this.collectors) {
2639
+ if (c.conv !== conversationId) continue;
2640
+ const kept = c.notes.filter((n) => !stale(n));
2641
+ c.notes.splice(0, c.notes.length, ...kept);
2642
+ }
2643
+ this.noteTo(conversationId, `${prefix}${outcome}`);
2524
2644
  }
2525
2645
  // ---- HTTP Basic auth (dialogs spec §4)
2526
2646
  /**
@@ -2698,13 +2818,11 @@ var BrowserSession = class {
2698
2818
  this.profile = profile;
2699
2819
  this.touchTranslator.reset();
2700
2820
  const pages = this.live().map(([, p]) => p);
2701
- const run = async () => {
2821
+ this.queueProfileChange(async () => {
2702
2822
  if (profile === "phone") await Promise.all(pages.map((p) => this.applyPhone(p)));
2703
2823
  else await this.restoreAll();
2704
2824
  if (this.profile === profile) this.applied = profile;
2705
- };
2706
- const next = this.viewportGate.then(run, run);
2707
- this.viewportGate = next.catch(() => void 0);
2825
+ });
2708
2826
  this.emit({ type: "state" });
2709
2827
  void this.viewportGate.then(() => this.emit({ type: "state" }));
2710
2828
  return this.viewportGate;
@@ -2765,6 +2883,7 @@ var BrowserSession = class {
2765
2883
  screenWidth: p.width,
2766
2884
  screenHeight: p.height
2767
2885
  });
2886
+ this.withMetrics.add(cdp);
2768
2887
  await cdp.send("Emulation.setTouchEmulationEnabled", { enabled: true, maxTouchPoints: 5 });
2769
2888
  await cdp.send("Emulation.setUserAgentOverride", {
2770
2889
  userAgent: this.mobileUa ?? mobileUserAgent("")
@@ -2794,7 +2913,7 @@ var BrowserSession = class {
2794
2913
  mobile: false,
2795
2914
  screenWidth: VIEWPORT.width,
2796
2915
  screenHeight: VIEWPORT.height
2797
- }).catch(() => void 0);
2916
+ }).then(() => this.withMetrics.add(cdp)).catch(() => void 0);
2798
2917
  await cdp.send("Emulation.setTouchEmulationEnabled", { enabled: false }).catch(() => void 0);
2799
2918
  if (this.desktopUa !== void 0)
2800
2919
  await cdp.send("Emulation.setUserAgentOverride", { userAgent: this.desktopUa }).catch(() => void 0);
@@ -2808,9 +2927,75 @@ var BrowserSession = class {
2808
2927
  */
2809
2928
  reapplyPhone(page) {
2810
2929
  if (this.profile !== "phone") return;
2811
- const run = () => this.applyPhone(page, true).then(() => void 0);
2930
+ this.queueProfileChange(() => this.applyPhone(page, true));
2931
+ }
2932
+ /**
2933
+ * Queues a change of the pages' device metrics in the profile chain (the viewport gate): it runs
2934
+ * after the changes before it and once the clipped captures in flight are done (bounded: a
2935
+ * capture of a page a JS dialog holds never answers).
2936
+ */
2937
+ queueProfileChange(change) {
2938
+ const run = async () => {
2939
+ await this.bounded(Promise.allSettled([...this.captures]), []);
2940
+ await change();
2941
+ };
2812
2942
  const next = this.viewportGate.then(run, run);
2813
- this.viewportGate = next.catch(() => void 0);
2943
+ this.viewportGate = next.then(
2944
+ () => void 0,
2945
+ () => void 0
2946
+ );
2947
+ }
2948
+ /**
2949
+ * A clipped capture of a page (`captureFitting`, plugins#298). Chromium captures a clip by
2950
+ * replacing the page's device emulation with a temporary one built from the capturing session's
2951
+ * own metrics and, when done, puts back that session's metrics as they were at the start: from
2952
+ * a session without metrics the page is left with none (at the view size of the start, the
2953
+ * window's on macOS), a profile change in between is lost, and a second capture meanwhile reads
2954
+ * the temporary metrics. So a capture goes through the page's metrics session, runs alone (each
2955
+ * waits for the one before, bounded: a capture of a page a JS dialog holds never answers),
2956
+ * starts once no profile change is queued, and a change waits for the captures queued before it.
2957
+ */
2958
+ async capture(page, opts) {
2959
+ for (; ; ) {
2960
+ const gate = this.viewportGate;
2961
+ await gate;
2962
+ if (gate === this.viewportGate) break;
2963
+ }
2964
+ const before = this.captureTail;
2965
+ const shot = (async () => {
2966
+ await this.bounded(before, void 0);
2967
+ const cdp = await this.metricsSession(page);
2968
+ if (cdp === void 0) throw new ActionError("failed", "The tab is gone.");
2969
+ const scale = VIEWPORT_PROFILES[this.applied].scale;
2970
+ return captureFitting(cdp, { ...opts, deviceScale: scale });
2971
+ })();
2972
+ this.captureTail = shot.catch(() => void 0);
2973
+ this.captures.add(shot);
2974
+ try {
2975
+ return await shot;
2976
+ } finally {
2977
+ this.captures.delete(shot);
2978
+ }
2979
+ }
2980
+ /**
2981
+ * The session a page's captures go through: its profile session, holding the metrics of the
2982
+ * profile applied (sent now if it never sent any). A capture puts back the metrics of its own
2983
+ * session when done, so on this one it puts back the page's real metrics.
2984
+ */
2985
+ async metricsSession(page) {
2986
+ const cdp = await this.profileSession(page);
2987
+ if (cdp === void 0 || this.withMetrics.has(cdp)) return cdp;
2988
+ const p = VIEWPORT_PROFILES[this.applied];
2989
+ await cdp.send("Emulation.setDeviceMetricsOverride", {
2990
+ width: p.width,
2991
+ height: p.height,
2992
+ deviceScaleFactor: p.scale,
2993
+ mobile: p.mobile,
2994
+ screenWidth: p.width,
2995
+ screenHeight: p.height
2996
+ });
2997
+ this.withMetrics.add(cdp);
2998
+ return cdp;
2814
2999
  }
2815
3000
  /** Every page that got the phone profile back on desktop. */
2816
3001
  async restoreAll() {
@@ -3206,6 +3391,7 @@ var BrowserSession = class {
3206
3391
  let reply;
3207
3392
  try {
3208
3393
  await this.viewportGate;
3394
+ await this.restoredTabsOf(conv);
3209
3395
  const beside = req.op === "wait" || req.op === "watch_end" || req.op === "dialog" || req.op === "tabs" && (req.action === "list" || req.action === "adopt");
3210
3396
  this.refuseIfBlocked(req);
3211
3397
  const out = await (beside ? req.op === "wait" ? this.raceDialog(conv, req.op, () => this.exec(req)) : this.exec(req) : this.serial(conv, () => {
@@ -3732,25 +3918,20 @@ var BrowserSession = class {
3732
3918
  const maxBytes = Math.min(MAX_SCREENSHOT_BYTES, Math.floor(req.maxBytes));
3733
3919
  if (!(maxBytes > 0))
3734
3920
  throw new ActionError("failed", "screenshot needs a positive maxBytes.");
3735
- const cdp = await this.ctx.newCDPSession(page);
3736
- try {
3737
- const shot = await captureFitting(cdp, {
3738
- maxBytes,
3739
- ...req.fullPage === true ? { fullPage: true } : {}
3740
- });
3741
- if (shot === null) {
3742
- throw new ActionError(
3743
- "failed",
3744
- `The page does not fit in a ${maxBytes}-byte screenshot even at the smallest size; use snapshot instead.`
3745
- );
3746
- }
3747
- return {
3748
- image: shot.data,
3749
- text: `Screenshot ${shot.width}x${shot.height} (viewport ${VIEWPORT.width}x${VIEWPORT.height}).`
3750
- };
3751
- } finally {
3752
- await cdp.detach().catch(() => void 0);
3921
+ const shot = await this.capture(page, {
3922
+ maxBytes,
3923
+ ...req.fullPage === true ? { fullPage: true } : {}
3924
+ });
3925
+ if (shot === null) {
3926
+ throw new ActionError(
3927
+ "failed",
3928
+ `The page does not fit in a ${maxBytes}-byte screenshot even at the smallest size; use snapshot instead.`
3929
+ );
3753
3930
  }
3931
+ return {
3932
+ image: shot.data,
3933
+ text: `Screenshot ${shot.width}x${shot.height} (viewport ${VIEWPORT.width}x${VIEWPORT.height}).`
3934
+ };
3754
3935
  }
3755
3936
  }
3756
3937
  throw new ActionError(
@@ -3776,7 +3957,7 @@ var BrowserSession = class {
3776
3957
  }
3777
3958
  case "close": {
3778
3959
  const page = this.ownTab(conv, req.tabId);
3779
- await page.close();
3960
+ await this.closeTab(page);
3780
3961
  return {};
3781
3962
  }
3782
3963
  case "adopt": {
@@ -4993,7 +5174,7 @@ var ViewerSession = class {
4993
5174
  else if (m.action === "switch" && m.tabId !== void 0) this.switchTo(m.tabId);
4994
5175
  else if (m.action === "close" && m.tabId !== void 0 && this.inTree(m.tabId)) {
4995
5176
  this.concern(m.tabId);
4996
- await this.browser.tabById(m.tabId).close();
5177
+ await this.browser.closeTab(this.browser.tabById(m.tabId));
4997
5178
  }
4998
5179
  } catch {
4999
5180
  }
@@ -5402,7 +5583,7 @@ var ViewerSession = class {
5402
5583
  this.cursorResolver = new CursorResolver(this.browser.context, page, cdp);
5403
5584
  let timer;
5404
5585
  const first = await Promise.race([
5405
- captureFitting(cdp, { maxBytes: this.jpegBudget, maxScale: this.scale }).catch(() => null),
5586
+ this.browser.capture(page, { maxBytes: this.jpegBudget, maxScale: this.scale }).catch(() => null),
5406
5587
  new Promise((r) => {
5407
5588
  timer = this.clock.schedule(() => r(null), FIRST_FRAME_MS);
5408
5589
  })
@@ -5687,6 +5868,9 @@ async function startDaemon(opts) {
5687
5868
  let current;
5688
5869
  let running;
5689
5870
  let restored = false;
5871
+ let crashNotes = /* @__PURE__ */ new Set();
5872
+ const crashed = /* @__PURE__ */ new WeakSet();
5873
+ const streams = /* @__PURE__ */ new Set();
5690
5874
  function within2(value, ms) {
5691
5875
  let timer;
5692
5876
  return Promise.race([
@@ -5696,6 +5880,23 @@ async function startDaemon(opts) {
5696
5880
  })
5697
5881
  ]).finally(() => clock.cancel(timer));
5698
5882
  }
5883
+ function reopenAfterCrash(lost) {
5884
+ if (lost.length === 0) return;
5885
+ const conversations = [];
5886
+ for (const t of lost) {
5887
+ if (conversations.some((c) => c.id === t.owner)) continue;
5888
+ const active = lost.findLastIndex((x) => x.owner === t.owner && x.active);
5889
+ conversations.push({ id: t.owner, root: t.root, ...active < 0 ? {} : { active } });
5890
+ }
5891
+ saved = {
5892
+ version: SESSION_FILE_VERSION,
5893
+ savedAt: clock.now(),
5894
+ tabs: lost.map((t) => ({ url: t.url, owner: t.owner, root: t.root })),
5895
+ conversations
5896
+ };
5897
+ restored = false;
5898
+ crashNotes = new Set(lost.map((t) => t.owner));
5899
+ }
5699
5900
  function browser() {
5700
5901
  if (current !== void 0) return current;
5701
5902
  if (closing) return Promise.reject(new Error("The browser daemon is stopping."));
@@ -5725,16 +5926,29 @@ async function startDaemon(opts) {
5725
5926
  return starting;
5726
5927
  async function sessionOn(ctx, setPid, failed) {
5727
5928
  let gone = false;
5929
+ let pid;
5930
+ let session;
5931
+ const unlisten = [];
5728
5932
  ctx.on("close", () => {
5729
5933
  gone = true;
5730
5934
  if (running?.launch === starting) running = void 0;
5731
- if (!closing && !failed()) opts.onBrowserGone?.();
5935
+ if (closing || failed()) return;
5936
+ if (current === starting) current = void 0;
5937
+ for (const off of unlisten.splice(0)) off();
5938
+ if (session !== void 0) {
5939
+ crashed.add(session);
5940
+ if (live === session) live = void 0;
5941
+ reopenAfterCrash(session.lostTabs());
5942
+ }
5943
+ if (pid !== void 0) killChromium(pid);
5944
+ for (const s2 of streams) s2.destroy();
5945
+ opts.onBrowserGone?.();
5732
5946
  });
5733
- const pid = await within2(browserProcessId(ctx), BROWSER_CLOSE_GRACE_MS);
5947
+ pid = await within2(browserProcessId(ctx), BROWSER_CLOSE_GRACE_MS);
5734
5948
  setPid(pid);
5735
5949
  if (!gone) running = { launch: starting, pid, ctx };
5736
5950
  const workspace = opts.env[SERVICE_WORKSPACE_ENV];
5737
- const session = new BrowserSession(ctx, {
5951
+ session = new BrowserSession(ctx, {
5738
5952
  proxy: plan.proxy,
5739
5953
  clock,
5740
5954
  usage: state,
@@ -5748,24 +5962,31 @@ async function startDaemon(opts) {
5748
5962
  ...opts.navigationTimeoutMs === void 0 ? {} : { navigationTimeoutMs: opts.navigationTimeoutMs }
5749
5963
  });
5750
5964
  await session.ready;
5751
- state.onChange(() => {
5752
- if (state.control === "agent") void session.restoreDesktop();
5753
- });
5965
+ const s = session;
5966
+ unlisten.push(
5967
+ state.onChange(() => {
5968
+ if (state.control === "agent") void s.restoreDesktop();
5969
+ })
5970
+ );
5754
5971
  if (plan.shippedDir !== void 0)
5755
5972
  session.note(shippedRevisionNote(plan.shippedDir, browserRevision(plan.build)));
5756
5973
  if (plan.build === "chromium-headless-shell" && opts.browsersPath === void 0)
5757
5974
  session.note(HEADLESS_SHELL_NOTE);
5758
5975
  if (!closing) await restoreCookies(ctx, opts.stateDir);
5976
+ let reopened = false;
5759
5977
  if (!restored && !closing) {
5760
5978
  restored = true;
5761
5979
  if (saved !== void 0) await sessionFile.restoreTabs(session, saved);
5980
+ reopened = crashNotes.size > 0;
5981
+ for (const conv of crashNotes) session.noteTo(conv, BROWSER_RESTARTED_NOTE);
5982
+ crashNotes = /* @__PURE__ */ new Set();
5762
5983
  }
5763
- if (!closing) {
5764
- const save = () => sessionFile.save(session, state);
5765
- session.on(save);
5766
- state.onChange(save);
5984
+ if (!closing && !gone) {
5985
+ const save = () => sessionFile.save(s, state);
5986
+ unlisten.push(session.on(save), state.onChange(save));
5987
+ if (reopened) save();
5767
5988
  }
5768
- if (!failed()) live = session;
5989
+ if (!failed() && !gone) live = session;
5769
5990
  return session;
5770
5991
  }
5771
5992
  }
@@ -5933,7 +6154,9 @@ async function startDaemon(opts) {
5933
6154
  } catch (e) {
5934
6155
  return launchFailure(e);
5935
6156
  }
5936
- const reply = await session.run(req, { takenOver: () => state.control === "user" });
6157
+ let reply = await session.run(req, { takenOver: () => state.control === "user" });
6158
+ if (!reply.ok && crashed.has(session))
6159
+ reply = { ...fail(BROWSER_CRASHED_MESSAGE), blockedHosts: reply.blockedHosts };
5937
6160
  if (reply.ok) {
5938
6161
  const since = state.takeHandbackNote(req.conversationId);
5939
6162
  if (since !== void 0) reply.userControlledSince = since;
@@ -5952,6 +6175,7 @@ async function startDaemon(opts) {
5952
6175
  let viewerChain = Promise.resolve();
5953
6176
  const end = () => {
5954
6177
  sockets.delete(sock);
6178
+ streams.delete(sock);
5955
6179
  if (viewer !== void 0) {
5956
6180
  const v = viewer;
5957
6181
  viewer = void 0;
@@ -5983,6 +6207,7 @@ async function startDaemon(opts) {
5983
6207
  rootConversationId: ctx.rootConversationId
5984
6208
  };
5985
6209
  const viewerContext = context;
6210
+ streams.add(sock);
5986
6211
  opened = true;
5987
6212
  state.viewerOpened();
5988
6213
  browser().then(
@@ -6128,7 +6353,10 @@ async function main() {
6128
6353
  stateDir,
6129
6354
  env: process.env,
6130
6355
  onIdle: () => stop(0, "idle"),
6131
- onBrowserGone: () => stop(1, "Chromium exited"),
6356
+ // the daemon stays: the next request or viewer launches Chromium again
6357
+ onBrowserGone: () => process.stderr.write(
6358
+ "browser daemon: Chromium exited unexpectedly; relaunched on next use\n"
6359
+ ),
6132
6360
  // installed and sealed: the next start runs the browser read only
6133
6361
  onSealed: () => stop(0, "browser installed and sealed; restart to run it")
6134
6362
  });