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

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.5",
4
+ "version": "0.1.0-rc.7",
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.5",
20
+ "version": "0.1.0-rc.7",
21
21
  "sdk": "^0.1.0-rc.69",
22
22
  "provides": [],
23
23
  "requires": [],
package/README.md CHANGED
@@ -28,8 +28,10 @@ A real browser in the person's device for agents (browser use spec,
28
28
  `reportBlockedHosts` (the kernel raises the network ask and reruns the call once allowed).
29
29
  - `browser_handoff` sends the daemon a handoff notice (the panels show a banner with 完成 / 取消),
30
30
  then raises an `InputRequired` question `{ done: boolean }` in the conversation, with `open`
31
- naming the `browser` panel so the person's conversation page opens it (a boolean, not
32
- a 完成 / 取消 enum: the kernel's `answerHandoff`, which the banner uses, answers `{ done }`); on
31
+ naming the `browser` panel so the person's conversation page opens it. The question's title is
32
+ 请在浏览器中完成:<the reason's first sentence> / Finish in the browser: …, the body is the full
33
+ reason, and `choices` draw 完成 (true, primary) and 取消 (false) as buttons. It stays a boolean
34
+ because the kernel's `answerHandoff`, which the banner uses, answers `{ done }`. On
33
35
  resume it clears the notice (with Done also handing the browser back, so a takeover the person
34
36
  still holds ends) and returns the page snapshot, or fails with "The user cancelled the handoff;
35
37
  ask the user how to continue, or try another approach.".
@@ -48,14 +50,18 @@ A real browser in the person's device for agents (browser use spec,
48
50
  the full Chromium build in its new headless mode, so the browser presents as an ordinary Chrome:
49
51
  Chrome's own reduced user agent for the platform (`--user-agent`, never "HeadlessChrome"), the
50
52
  browser's own client hints, a window the size of the viewport, the device's locale and time zone.
51
- On macOS (device-local) it is the headless shell in one process: the local device sandbox refuses
52
- the full build's Mach service registrations. Nothing spoofs a fingerprint, solves a CAPTCHA or
53
+ On macOS (device-local) too where the machine's capybara-device says its sandbox allows it
54
+ (`CAPYBARA_SERVICE_MACH=chromium`, capybara-hq/core#843); the browser gets `MAC_CHROMIUM_TMPDIR`
55
+ and crash reporting off. An older capybara-device keeps the headless shell in one process (and
56
+ nothing larger is downloaded). First start there: one download into the install directory (about 377 MB, 16 s on a fast
57
+ link), one restart, then about 2 s to launch. Nothing spoofs a fingerprint, solves a CAPTCHA or
53
58
  hides automation beyond Playwright's own flags (`navigator.webdriver` stays true).
54
59
  - Where the browser comes from (plugins#209: never from a place the service or an agent command
55
60
  could write once it runs): the provider's install directory `CAPYBARA_SERVICE_INSTALL`
56
61
  (device-local) is filled on the first start, sealed with `.sealed`, and the daemon answers
57
62
  `restart` and exits, so every later start runs it read only (the plugin starts the service again
58
- within the same tool call; an unsealed directory is always installed afresh, never trusted as
63
+ within the same tool call, waiting while `ensureService` still reports the exiting process's
64
+ start time, for at most 30 s; an unsealed directory is always installed afresh, never trusted as
59
65
  found); else a `PLAYWRIGHT_BROWSERS_PATH` the daemon cannot write, outside the workspace
60
66
  (device-docker / device-e2b ship it in `/opt/capybara-browsers`, pinned to this package's
61
67
  playwright-core): this build's revision, else the newest revision of the build there. Nothing
@@ -68,6 +74,22 @@ A real browser in the person's device for agents (browser use spec,
68
74
  created file in `<workspace>/downloads`, checked to be that directory's own before any byte is
69
75
  written. So a link the agent plants in the workspace never makes the service read or write its
70
76
  own profile.
77
+ - The network: Chromium sends everything, loopback included, through the device's proxy
78
+ (`HTTPS_PROXY` / `HTTP_PROXY` of the service, the same proxy and rules as the device's commands:
79
+ the proxy resolves the name, with the fake-IP DNS fallback, and judges the address). A proxy URL
80
+ with credentials goes to Playwright's `proxy` option, which answers the challenge by
81
+ intercepting requests; under that interception Chromium loses a request it restarts for an
82
+ ACCEPT_CH frame (www.google.com sends one), so the daemon disables `AcceptCHFrame` (its
83
+ `--disable-features` repeats Playwright's own list: Chromium takes only the last flag), and
84
+ `--disable-auto-reload` keeps a network error page from reloading itself (that reload aborted
85
+ the agent's next navigation in the tab).
86
+ - A navigation that fails says why (`unreachable`): Chromium's net error with its meaning, and
87
+ for a failed tunnel what the device's proxy answers for the host (refused by the network
88
+ settings: `blocked`; could not connect: the name did not resolve, or the host refused or did not
89
+ answer). A navigation with no page within 30 s is stopped (CDP `Page.stopLoading`: one left in
90
+ flight keeps the page's queries waiting), so the tab shows its previous page and the next
91
+ request works on it. A 204 / 205 answer says so. The tab list runs beside the actions, and a
92
+ reply's title and verification check are bounded (2 s), so neither waits on a hanging page.
71
93
  - A launch that fails (no download, a refused network) does not stop the daemon: every request
72
94
  answers the cause and launches again. When the device's proxy refuses Playwright's download
73
95
  hosts (`cdn.playwright.dev`, `playwright.download.prss.microsoft.com`, `storage.googleapis.com`
@@ -155,7 +177,9 @@ A real browser in the person's device for agents (browser use spec,
155
177
  status line and picture are separated by space and ground, not borders. Colours come from the
156
178
  host's `--cb-*` tokens (light and dark). Until the browser's state and its first frame are there,
157
179
  the whole panel is one skeleton and nothing else; then it switches once to the live panel. "Not
158
- running", offline and error show at once. The picture is contained and centred on a neutral ground
180
+ running", offline and error show at once as the centred idle state alone (no tabs, toolbar or
181
+ status line: nothing to navigate); a browser that comes up switches once to the live panel on
182
+ its first frame. The picture is contained and centred on a neutral ground
159
183
  (soft shadow; a 2 px accent ring while the person is in control). The status line has a fixed
160
184
  height. Take over is there at every width: below 440 px the tabs and the address merge into one
161
185
  button with a tab count, and forward and reload move into a "more" menu. On a phone (a screen
package/dist/index.mjs CHANGED
@@ -21,6 +21,7 @@ var HANDOFF_MAX_CHARS = 4096;
21
21
  var HANDOFF_KEEPALIVE_MS = 24 * 60 * 6e4;
22
22
  var DOWNLOAD_BLOCKED_PREFIX = "The browser could not be downloaded into the device: its network settings block ";
23
23
  var REPLY_TOO_LARGE_MESSAGE = "The reply was too large to send; ask for less (a smaller maxBytes).";
24
+ var FAVICON_MAX_BYTES = 8 * 1024;
24
25
 
25
26
  // src/browser.ts
26
27
  import {
@@ -36,6 +37,20 @@ var START_FAILED_MESSAGE = "The browser could not start in the device; retry, an
36
37
  var SERVICE = "browser";
37
38
  var RESTARTING_MESSAGE = "The browser was just installed in the device and its service is restarting; call the tool again.";
38
39
  var RESTART_ATTEMPTS = 3;
40
+ var RESTART_WAIT_MS = 3e4;
41
+ var RESTART_PAUSE_FIRST_MS = 100;
42
+ var RESTART_PAUSE_MAX_MS = 1e3;
43
+ var pause = (ms, signal) => new Promise((resolve) => {
44
+ if (signal.aborted) return resolve();
45
+ const timer = AbortSignal.timeout(ms);
46
+ const done = () => {
47
+ signal.removeEventListener("abort", done);
48
+ timer.removeEventListener("abort", done);
49
+ resolve();
50
+ };
51
+ signal.addEventListener("abort", done, { once: true });
52
+ timer.addEventListener("abort", done, { once: true });
53
+ });
39
54
  var REQUEST_TIMEOUT_MS = 9e4;
40
55
  var TOOL_TIMEOUT_MS = 3e5;
41
56
  function assertOwner(call) {
@@ -81,6 +96,8 @@ function daemonToolError(code, message) {
81
96
  return new ToolError(
82
97
  `${message} Check the page with browser_snapshot, then retry or call browser_wait.`
83
98
  );
99
+ case "unreachable":
100
+ return new ToolError(`${message} Check the address before retrying.`);
84
101
  case "blocked":
85
102
  if (message.startsWith(DOWNLOAD_BLOCKED_PREFIX))
86
103
  return new ToolError(
@@ -123,28 +140,45 @@ function failure(deps, call, e, starting) {
123
140
  async function runRequest(deps, call, req, timeoutMs = REQUEST_TIMEOUT_MS) {
124
141
  assertOwner(call);
125
142
  let reply;
126
- let restarting = false;
127
- for (let restarts = 0; ; restarts++) {
143
+ let exiting;
144
+ let waitUntil = 0;
145
+ let pauseMs = RESTART_PAUSE_FIRST_MS;
146
+ const waitMore = async () => {
147
+ if (call.signal.aborted || Date.now() + pauseMs > waitUntil) return false;
148
+ await pause(pauseMs, call.signal);
149
+ pauseMs = Math.min(pauseMs * 2, RESTART_PAUSE_MAX_MS);
150
+ return !call.signal.aborted;
151
+ };
152
+ for (let restarts = 0; ; ) {
153
+ let startedAt;
128
154
  try {
129
- await deps.deviceAccess.ensureService(call, await deps.serviceSpec());
155
+ ({ startedAt } = await deps.deviceAccess.ensureService(call, await deps.serviceSpec()));
130
156
  } catch (e) {
131
157
  throw failure(deps, call, e, true);
132
158
  }
159
+ if (exiting !== void 0 && startedAt !== null && startedAt === exiting.startedAt) {
160
+ if (await waitMore()) continue;
161
+ if (call.signal.aborted) throw failure(deps, call, call.signal.reason, true);
162
+ throw new ToolError(RESTARTING_MESSAGE);
163
+ }
133
164
  try {
134
165
  const body = new TextEncoder().encode(JSON.stringify(req));
135
166
  reply = parseReply(
136
167
  await deps.deviceAccess.request(call, { service: SERVICE, body, timeoutMs })
137
168
  );
138
169
  } catch (e) {
139
- if (restarting && !call.signal.aborted) {
140
- if (restarts < RESTART_ATTEMPTS) continue;
141
- throw new ToolError(RESTARTING_MESSAGE);
170
+ if (exiting !== void 0 && !call.signal.aborted) {
171
+ if (await waitMore()) continue;
172
+ if (!call.signal.aborted) throw new ToolError(RESTARTING_MESSAGE);
142
173
  }
143
174
  throw failure(deps, call, e, false);
144
175
  }
145
176
  if (reply.ok || reply.error !== "restart") break;
146
177
  if (restarts >= RESTART_ATTEMPTS) throw new ToolError(RESTARTING_MESSAGE);
147
- restarting = true;
178
+ restarts++;
179
+ exiting = { startedAt };
180
+ waitUntil = Date.now() + RESTART_WAIT_MS;
181
+ pauseMs = RESTART_PAUSE_FIRST_MS;
148
182
  }
149
183
  const hosts = Array.isArray(reply.blockedHosts) ? reply.blockedHosts.filter((h) => typeof h === "string" && h !== "") : [];
150
184
  if (hosts.length > 0)
@@ -173,16 +207,22 @@ function toResult(reply) {
173
207
 
174
208
  // src/i18n.ts
175
209
  var HANDOFF_FORM = {
210
+ titlePrefix: { zh: "请在浏览器中完成:", en: "Finish in the browser: " },
176
211
  label: { zh: "完成", en: "Done" },
177
- description: {
178
- zh: "完成后打开开关并提交,浏览器交还智能体;关闭开关提交或关闭此问题即为取消。",
179
- en: "Turn on and submit when you are done to hand the browser back; submit with it off, or dismiss the question, to cancel."
180
- }
212
+ done: { zh: "完成", en: "Done" },
213
+ cancel: { zh: "取消", en: "Cancel" }
181
214
  };
182
215
 
183
216
  // src/handoff.ts
184
217
  var PANEL = "browser";
185
218
  var MESSAGE_MAX = Math.min(2e3, HANDOFF_MAX_CHARS);
219
+ var SHORT_MAX = 40;
220
+ function shortReason(message) {
221
+ const first = message.trim().split(/(?<=[。!?.!?])\s*|\n/u)[0]?.trim() ?? "";
222
+ const chars = Array.from(first);
223
+ if (chars.length <= SHORT_MAX) return first.replace(/[。.]$/u, "");
224
+ return `${chars.slice(0, SHORT_MAX - 1).join("")}…`;
225
+ }
186
226
  var HANDOFF = {
187
227
  name: "browser_handoff",
188
228
  title: "Hand the browser to the user",
@@ -214,14 +254,22 @@ function handoffHandler(deps) {
214
254
  const asked = {
215
255
  kind: "input_required",
216
256
  form: {
217
- title: message,
257
+ title: {
258
+ zh: `${HANDOFF_FORM.titlePrefix.zh}${shortReason(message)}`,
259
+ en: `${HANDOFF_FORM.titlePrefix.en}${shortReason(message)}`
260
+ },
261
+ body: message,
218
262
  fields: [
219
263
  {
220
264
  key: "done",
221
265
  label: HANDOFF_FORM.label,
222
- description: HANDOFF_FORM.description,
223
266
  schema: { type: "boolean" },
224
- required: true
267
+ required: true,
268
+ // two buttons (完成 primary, 取消), the same answer the panel's banner sends
269
+ choices: [
270
+ { value: true, label: HANDOFF_FORM.done },
271
+ { value: false, label: HANDOFF_FORM.cancel }
272
+ ]
225
273
  }
226
274
  ]
227
275
  },
@@ -313,7 +361,8 @@ var PANEL_HTML = `<!doctype html>
313
361
  .outline { padding: 0 12px; color: var(--cb-accent, #CC4609); box-shadow: inset 0 0 0 1px var(--cb-accent, #CC4609); }
314
362
 
315
363
  .layer { position: absolute; inset: 0; display: flex; flex-direction: column; }
316
- #app[data-loading] { visibility: hidden; }
364
+ /* laid out underneath while the skeleton or the idle state shows, so the switch never reflows */
365
+ #app[data-loading], #app[data-idle] { visibility: hidden; }
317
366
  .row { flex: none; display: flex; align-items: center; padding: 0 12px; }
318
367
 
319
368
  /* tab strip */
@@ -321,7 +370,8 @@ var PANEL_HTML = `<!doctype html>
321
370
  .tab { display: flex; align-items: center; gap: 6px; flex: 0 1 auto; min-width: 64px; max-width: 200px; padding: 0 10px; color: var(--cb-muted, #5E5E5A); }
322
371
  .tab[data-active="true"] { color: var(--cb-ink, #1A1A18); font-weight: 500; box-shadow: inset 0 -2px 0 var(--cb-accent, #CC4609); padding-right: 6px; }
323
372
  .fav { width: 14px; height: 14px; border-radius: 3px; flex: none; background: var(--cb-line-soft, #E8E7E2); }
324
- .tab[data-active="true"] .fav { background: var(--cb-line, #D9D8D2); }
373
+ img.fav { background: none; object-fit: contain; }
374
+ .tab[data-active="true"] span.fav { background: var(--cb-line, #D9D8D2); }
325
375
  .tab .label { flex: 1; min-width: 0; display: block; height: auto; text-align: left; overflow: hidden; text-overflow: ellipsis; font-weight: inherit; }
326
376
  .tab .label:hover:not(:disabled) { background: transparent; }
327
377
  .tab .label:disabled { color: inherit; }
@@ -378,7 +428,7 @@ var PANEL_HTML = `<!doctype html>
378
428
  #stage[data-control="user"] #view { box-shadow: 0 0 0 2px var(--cb-accent, #CC4609), 0 4px 16px rgba(26,26,24,.08); }
379
429
  #view:focus-visible { box-shadow: 0 0 0 2px var(--cb-focus-ring, Highlight), var(--frame-shadow); }
380
430
  #flash { position: absolute; width: 24px; height: 24px; margin: -12px 0 0 -12px; border: 2px solid var(--cb-accent, #CC4609); border-radius: 50%; pointer-events: none; }
381
- .center { position: absolute; inset: 0; display: flex; flex-direction: column; gap: 6px; align-items: center; justify-content: center; padding: 16px; text-align: center; background: var(--cb-panel-2, Canvas); }
431
+ .center { position: absolute; inset: 0; display: flex; flex-direction: column; gap: 6px; align-items: center; justify-content: center; padding: 16px; text-align: center; background: var(--ground); }
382
432
  .center h2 { margin: 0; font-size: inherit; font-weight: 600; }
383
433
  .center p { margin: 0; font-family: var(--cb-font-prose, system-ui, sans-serif); color: var(--cb-muted, #5E5E5A); }
384
434
  .center button { margin-top: 6px; }
@@ -434,11 +484,6 @@ var PANEL_HTML = `<!doctype html>
434
484
  <div id="stage">
435
485
  <canvas id="view" tabindex="0"></canvas>
436
486
  <div id="flash" hidden></div>
437
- <div id="empty" class="center" hidden>
438
- <h2 id="empty-title"></h2>
439
- <p id="empty-body"></p>
440
- <button type="button" id="reconnect" class="secondary"></button>
441
- </div>
442
487
  <div id="strips">
443
488
  <div id="blocked" class="strip" hidden><p><span id="blocked-label" class="label"></span> <span id="blocked-host"></span></p><button type="button" id="allow" class="primary"></button></div>
444
489
  <div id="dialog" class="strip" hidden><p><span id="dialog-label" class="label"></span> <span id="dialog-text"></span></p></div>
@@ -446,6 +491,11 @@ var PANEL_HTML = `<!doctype html>
446
491
  </div>
447
492
  </div>
448
493
  </div>
494
+ <div id="empty" class="layer center" hidden>
495
+ <h2 id="empty-title"></h2>
496
+ <p id="empty-body"></p>
497
+ <button type="button" id="reconnect" class="secondary"></button>
498
+ </div>
449
499
  <div id="menu" class="menu" role="menu" hidden></div>
450
500
  <script src="panel.js"></script>
451
501
  </body>
@@ -544,9 +594,19 @@ function registerRoutes(ctx, deps) {
544
594
  const body = await readJson(req);
545
595
  const callId = body?.callId;
546
596
  const done = body?.done;
547
- if (typeof callId !== "string" || callId === "" || callId.length > CALL_ID_MAX || typeof done !== "boolean")
548
- return error(400, "invalid_body", "the body must be { callId: string, done: boolean }");
549
- await deps.deviceAccess.answerHandoff({ ...scope, callId, done });
597
+ const raised = body?.handoffConversationId;
598
+ if (typeof callId !== "string" || callId === "" || callId.length > CALL_ID_MAX || typeof done !== "boolean" || raised !== void 0 && (typeof raised !== "string" || raised === "" || raised.length > CALL_ID_MAX))
599
+ return error(
600
+ 400,
601
+ "invalid_body",
602
+ "the body must be { callId: string, done: boolean, handoffConversationId?: string }"
603
+ );
604
+ await deps.deviceAccess.answerHandoff({
605
+ ...scope,
606
+ callId,
607
+ handoffConversationId: typeof raised === "string" ? raised : scope.conversationId,
608
+ done
609
+ });
550
610
  return json(200, { ok: true });
551
611
  })
552
612
  );
@@ -1029,7 +1089,7 @@ function registerBrowserTools(ctx, deps) {
1029
1089
  // src/index.ts
1030
1090
  var index_default = defineExtension({
1031
1091
  name: "browser",
1032
- version: "0.1.0-rc.5",
1092
+ version: "0.1.0-rc.7",
1033
1093
  sdk: "^0.1.0-rc.69",
1034
1094
  provides: [],
1035
1095
  ui: [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/plugin-browser",
3
- "version": "0.1.0-rc.5",
3
+ "version": "0.1.0-rc.7",
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",
package/ui/panel.js CHANGED
@@ -62,6 +62,8 @@
62
62
  }
63
63
  var DEFAULT_FRAME_MAX_BYTES = 256 * 1024;
64
64
  var HANDOFF_KEEPALIVE_MS = 24 * 60 * 6e4;
65
+ var FAVICON_MAX_BYTES = 8 * 1024;
66
+ var isIconDataUrl = (s) => typeof s === "string" && s.length <= 64 + Math.ceil(FAVICON_MAX_BYTES * 4 / 3) && /^data:image\/(png|x-icon|gif|jpeg|webp|svg\+xml);base64,[A-Za-z0-9+/=]+$/.test(s);
65
67
 
66
68
  // ui-src/panel/i18n.ts
67
69
  var STRINGS = {
@@ -439,7 +441,8 @@
439
441
  .outline { padding: 0 12px; color: var(--cb-accent, #CC4609); box-shadow: inset 0 0 0 1px var(--cb-accent, #CC4609); }
440
442
 
441
443
  .layer { position: absolute; inset: 0; display: flex; flex-direction: column; }
442
- #app[data-loading] { visibility: hidden; }
444
+ /* laid out underneath while the skeleton or the idle state shows, so the switch never reflows */
445
+ #app[data-loading], #app[data-idle] { visibility: hidden; }
443
446
  .row { flex: none; display: flex; align-items: center; padding: 0 12px; }
444
447
 
445
448
  /* tab strip */
@@ -447,7 +450,8 @@
447
450
  .tab { display: flex; align-items: center; gap: 6px; flex: 0 1 auto; min-width: 64px; max-width: 200px; padding: 0 10px; color: var(--cb-muted, #5E5E5A); }
448
451
  .tab[data-active="true"] { color: var(--cb-ink, #1A1A18); font-weight: 500; box-shadow: inset 0 -2px 0 var(--cb-accent, #CC4609); padding-right: 6px; }
449
452
  .fav { width: 14px; height: 14px; border-radius: 3px; flex: none; background: var(--cb-line-soft, #E8E7E2); }
450
- .tab[data-active="true"] .fav { background: var(--cb-line, #D9D8D2); }
453
+ img.fav { background: none; object-fit: contain; }
454
+ .tab[data-active="true"] span.fav { background: var(--cb-line, #D9D8D2); }
451
455
  .tab .label { flex: 1; min-width: 0; display: block; height: auto; text-align: left; overflow: hidden; text-overflow: ellipsis; font-weight: inherit; }
452
456
  .tab .label:hover:not(:disabled) { background: transparent; }
453
457
  .tab .label:disabled { color: inherit; }
@@ -504,7 +508,7 @@
504
508
  #stage[data-control="user"] #view { box-shadow: 0 0 0 2px var(--cb-accent, #CC4609), 0 4px 16px rgba(26,26,24,.08); }
505
509
  #view:focus-visible { box-shadow: 0 0 0 2px var(--cb-focus-ring, Highlight), var(--frame-shadow); }
506
510
  #flash { position: absolute; width: 24px; height: 24px; margin: -12px 0 0 -12px; border: 2px solid var(--cb-accent, #CC4609); border-radius: 50%; pointer-events: none; }
507
- .center { position: absolute; inset: 0; display: flex; flex-direction: column; gap: 6px; align-items: center; justify-content: center; padding: 16px; text-align: center; background: var(--cb-panel-2, Canvas); }
511
+ .center { position: absolute; inset: 0; display: flex; flex-direction: column; gap: 6px; align-items: center; justify-content: center; padding: 16px; text-align: center; background: var(--ground); }
508
512
  .center h2 { margin: 0; font-size: inherit; font-weight: 600; }
509
513
  .center p { margin: 0; font-family: var(--cb-font-prose, system-ui, sans-serif); color: var(--cb-muted, #5E5E5A); }
510
514
  .center button { margin-top: 6px; }
@@ -560,11 +564,6 @@
560
564
  <div id="stage">
561
565
  <canvas id="view" tabindex="0"></canvas>
562
566
  <div id="flash" hidden></div>
563
- <div id="empty" class="center" hidden>
564
- <h2 id="empty-title"></h2>
565
- <p id="empty-body"></p>
566
- <button type="button" id="reconnect" class="secondary"></button>
567
- </div>
568
567
  <div id="strips">
569
568
  <div id="blocked" class="strip" hidden><p><span id="blocked-label" class="label"></span> <span id="blocked-host"></span></p><button type="button" id="allow" class="primary"></button></div>
570
569
  <div id="dialog" class="strip" hidden><p><span id="dialog-label" class="label"></span> <span id="dialog-text"></span></p></div>
@@ -572,6 +571,11 @@
572
571
  </div>
573
572
  </div>
574
573
  </div>
574
+ <div id="empty" class="layer center" hidden>
575
+ <h2 id="empty-title"></h2>
576
+ <p id="empty-body"></p>
577
+ <button type="button" id="reconnect" class="secondary"></button>
578
+ </div>
575
579
  <div id="menu" class="menu" role="menu" hidden></div>
576
580
  <script src="panel.js"><\/script>
577
581
  </body>
@@ -648,6 +652,7 @@
648
652
  let pendingHandoff = null;
649
653
  let sentSize = "";
650
654
  let image = null;
655
+ let shown = "skeleton";
651
656
  const compact = () => {
652
657
  const sw = win.screen?.width ?? 0;
653
658
  return sw > 0 && sw < COMPACT_BELOW;
@@ -761,7 +766,6 @@
761
766
  input.sync();
762
767
  $("lock").hidden = !isLive || lastState?.secure !== true;
763
768
  const showEmpty = mode === "empty" || mode === "offline" || mode === "error";
764
- $("empty").hidden = !showEmpty;
765
769
  $("reconnect").hidden = !showEmpty;
766
770
  const keys = {
767
771
  empty: ["emptyTitle", "emptyBody"],
@@ -779,10 +783,18 @@
779
783
  renderLoading();
780
784
  }
781
785
  function renderLoading() {
782
- const loading = mode === "connecting" || mode === "live" && image === null;
783
- $("app").toggleAttribute("data-loading", loading);
784
- $("skeleton").hidden = !loading;
785
- if (!loading) onBoxChange();
786
+ const idleMode = mode === "empty" || mode === "offline" || mode === "error";
787
+ let next;
788
+ if (idleMode) next = "idle";
789
+ else if (mode === "live" && image !== null) next = "app";
790
+ else if (mode === "live" && shown === "idle") next = "idle";
791
+ else next = "skeleton";
792
+ shown = next;
793
+ $("app").toggleAttribute("data-loading", next === "skeleton");
794
+ $("app").toggleAttribute("data-idle", next === "idle");
795
+ $("skeleton").hidden = next !== "skeleton";
796
+ $("empty").hidden = next !== "idle";
797
+ if (next === "app") onBoxChange();
786
798
  }
787
799
  function renderTabs() {
788
800
  const box = $("tabs");
@@ -794,9 +806,7 @@
794
806
  el.setAttribute("role", "tab");
795
807
  el.setAttribute("data-active", String(tab.active));
796
808
  el.setAttribute("aria-selected", String(tab.active));
797
- const fav = doc.createElement("span");
798
- fav.className = "fav";
799
- el.appendChild(fav);
809
+ el.appendChild(favOf(tab));
800
810
  const label = doc.createElement("button");
801
811
  label.type = "button";
802
812
  label.className = "label";
@@ -826,11 +836,25 @@
826
836
  box.appendChild(add);
827
837
  }
828
838
  const active = tabs.find((x) => x.active);
839
+ $("tabsbtn").querySelector(".fav")?.replaceWith(favOf(active));
829
840
  $("tabsbtn-name").textContent = active === void 0 ? "" : hostOf(active.url) || tabName(active);
830
841
  $("tabsbtn-count").textContent = String(tabs.length);
831
842
  $("tabsbtn").setAttribute("aria-label", `${text("tabs")}: ${tabs.length}`);
832
843
  }
833
- const tabName = (tab) => tab.title === "" ? tab.url : tab.title;
844
+ const tabName = (tab) => tab.title !== "" ? tab.title : tab.url === "about:blank" ? text("newTab") : tab.url;
845
+ function favOf(tab) {
846
+ if (tab !== void 0 && isIconDataUrl(tab.favicon)) {
847
+ const img = doc.createElement("img");
848
+ img.className = "fav";
849
+ img.alt = "";
850
+ img.src = tab.favicon;
851
+ img.addEventListener("error", () => img.replaceWith(favOf(void 0)), { once: true });
852
+ return img;
853
+ }
854
+ const fav = doc.createElement("span");
855
+ fav.className = "fav";
856
+ return fav;
857
+ }
834
858
  function hostOf(u) {
835
859
  try {
836
860
  return new URL(u).host;
@@ -1004,6 +1028,7 @@
1004
1028
  }
1005
1029
  function show(next) {
1006
1030
  mode = next;
1031
+ if (next === "empty" || next === "offline" || next === "error") image = null;
1007
1032
  if (next === "empty") {
1008
1033
  wasLive = false;
1009
1034
  armEmptyPoll();
@@ -1,8 +1,10 @@
1
1
  // @capybara-hq/plugin-browser daemon (generated by daemon/build.ts)
2
2
 
3
- // ../../node_modules/.pnpm/@capybara-hq+plugin-sdk@0.1.0-rc.72/node_modules/@capybara-hq/plugin-sdk/dist/device-service.js
3
+ // ../../node_modules/.pnpm/@capybara-hq+plugin-sdk@0.1.0-rc.75/node_modules/@capybara-hq/plugin-sdk/dist/device-service.js
4
4
  var DEVICE_SERVICE_SOCKET_ENV = "CAPYBARA_SERVICE_SOCKET";
5
5
  var DEVICE_SERVICE_STATE_ENV = "CAPYBARA_SERVICE_STATE";
6
+ var DEVICE_SERVICE_MACH_ENV = "CAPYBARA_SERVICE_MACH";
7
+ var DEVICE_SERVICE_MACH_CHROMIUM = "chromium";
6
8
  var DEVICE_SERVICE_MAX_MESSAGE = 8 * 1024 * 1024;
7
9
  var HEADER = 4;
8
10
  function encodeServiceMessage(body) {
@@ -160,6 +162,73 @@ var MAX_TABS = 10;
160
162
  var HANDOFF_KEEPALIVE_MS = 24 * 60 * 6e4;
161
163
  var DOWNLOAD_BLOCKED_PREFIX = "The browser could not be downloaded into the device: its network settings block ";
162
164
  var REPLY_TOO_LARGE_MESSAGE = "The reply was too large to send; ask for less (a smaller maxBytes).";
165
+ var FAVICON_MAX_BYTES = 8 * 1024;
166
+
167
+ // daemon/favicon.ts
168
+ var READ_MAX_BYTES = 64 * 1024;
169
+ function sniffIcon(b) {
170
+ const at = (i, ...xs) => xs.every((x, j) => b[i + j] === x);
171
+ if (at(0, 137, 80, 78, 71)) return "image/png";
172
+ if (at(0, 0, 0, 1, 0)) return "image/x-icon";
173
+ if (at(0, 71, 73, 70, 56)) return "image/gif";
174
+ if (at(0, 255, 216, 255)) return "image/jpeg";
175
+ if (at(0, 82, 73, 70, 70) && at(8, 87, 69, 66, 80)) return "image/webp";
176
+ const head = new TextDecoder().decode(b.subarray(0, 512)).trimStart().toLowerCase();
177
+ if (head.startsWith("<svg") || head.startsWith("<?xml") && head.includes("<svg"))
178
+ return "image/svg+xml";
179
+ return null;
180
+ }
181
+ function iconDataUrl(b) {
182
+ if (b.byteLength === 0 || b.byteLength > FAVICON_MAX_BYTES) return null;
183
+ const mime = sniffIcon(b);
184
+ if (mime === null) return null;
185
+ return `data:${mime};base64,${Buffer.from(b).toString("base64")}`;
186
+ }
187
+ async function iconUrlOf(page) {
188
+ let base;
189
+ try {
190
+ base = new URL(page.url());
191
+ } catch {
192
+ return null;
193
+ }
194
+ if (base.protocol !== "http:" && base.protocol !== "https:") return null;
195
+ const declared = await page.evaluate(
196
+ `(() => { const l = Array.from(document.querySelectorAll("link[rel][href]")).find((x) => /(^|\\s)icon(\\s|$)/i.test(x.rel)); return l ? l.href : null; })()`
197
+ ).catch(() => null);
198
+ if (typeof declared === "string") {
199
+ try {
200
+ const u = new URL(declared, base);
201
+ if (u.protocol === "http:" || u.protocol === "https:") return u.href;
202
+ } catch {
203
+ }
204
+ }
205
+ return new URL("/favicon.ico", base).href;
206
+ }
207
+ async function fetchIcon(cdp, url) {
208
+ const tree = await cdp.send("Page.getFrameTree");
209
+ const res = await cdp.send("Network.loadNetworkResource", {
210
+ frameId: tree.frameTree.frame.id,
211
+ url,
212
+ options: { disableCache: false, includeCredentials: false }
213
+ });
214
+ const r = res.resource;
215
+ if (!r.success || r.httpStatusCode !== 200 || r.stream === void 0) return null;
216
+ const chunks = [];
217
+ let size = 0;
218
+ try {
219
+ for (; ; ) {
220
+ const part = await cdp.send("IO.read", { handle: r.stream, size: 16 * 1024 });
221
+ const buf = Buffer.from(part.data, part.base64Encoded ? "base64" : "utf8");
222
+ size += buf.byteLength;
223
+ if (size > READ_MAX_BYTES) return null;
224
+ chunks.push(buf);
225
+ if (part.eof) break;
226
+ }
227
+ } finally {
228
+ await cdp.send("IO.close", { handle: r.stream }).catch(() => void 0);
229
+ }
230
+ return new Uint8Array(Buffer.concat(chunks));
231
+ }
163
232
 
164
233
  // daemon/snapshot.ts
165
234
  var isNode = (line) => line.trimStart().startsWith("- ");
@@ -402,6 +471,7 @@ var MAX_NAME_BYTES = 200;
402
471
  var ACTION_TIMEOUT_MS = 1e4;
403
472
  var NAVIGATION_TIMEOUT_MS = 3e4;
404
473
  var LOAD_GRACE_MS = 5e3;
474
+ var PAGE_QUERY_MS = 2e3;
405
475
  var MAX_WAIT_MS = 6e4;
406
476
  var MAX_SCREENSHOT_BYTES = Math.floor((8 * 1024 * 1024 - 64 * 1024) * 3 / 4);
407
477
  var MAX_TITLE_CHARS = 2048;
@@ -478,6 +548,23 @@ function within(real, root) {
478
548
  var sameFile = (a, b) => a.dev === b.dev && a.ino === b.ino;
479
549
  var REF_RE = /^(f\d+)?e\d+$/;
480
550
  var PROXY_FAILURE_RE = /ERR_TUNNEL_CONNECTION_FAILED|ERR_PROXY_CONNECTION_FAILED/;
551
+ var ERROR_PAGE_WAIT_MS = 2e3;
552
+ var isTimeout = (e) => e instanceof Error && e.name === "TimeoutError";
553
+ var NET_ERROR_MEANINGS = {
554
+ ERR_NAME_NOT_RESOLVED: "the host name does not resolve",
555
+ ERR_CONNECTION_REFUSED: "the host refused the connection",
556
+ ERR_CONNECTION_RESET: "the connection was reset",
557
+ ERR_CONNECTION_CLOSED: "the host closed the connection without an answer",
558
+ ERR_CONNECTION_TIMED_OUT: "the host did not answer the connection",
559
+ ERR_ADDRESS_UNREACHABLE: "the host's address is unreachable",
560
+ ERR_INTERNET_DISCONNECTED: "the device has no network connection",
561
+ ERR_EMPTY_RESPONSE: "the server sent an empty answer",
562
+ ERR_SSL_PROTOCOL_ERROR: "the secure connection failed",
563
+ ERR_CERT_AUTHORITY_INVALID: "the site's certificate is not trusted",
564
+ ERR_CERT_COMMON_NAME_INVALID: "the site's certificate is for another name",
565
+ ERR_CERT_DATE_INVALID: "the site's certificate has expired or is not yet valid",
566
+ ERR_TOO_MANY_REDIRECTS: "the page redirects in a loop"
567
+ };
481
568
  function docUrl(raw) {
482
569
  try {
483
570
  const u = new URL(raw);
@@ -577,6 +664,16 @@ var NavWatch = class {
577
664
  }
578
665
  return { kind: "loaded", response: await final.response().catch(() => null) };
579
666
  }
667
+ /**
668
+ * The status the newest navigation to the target address was answered with, when it finished
669
+ * without a document (a 204 or 205: Chromium keeps the page and aborts the navigation).
670
+ */
671
+ async emptyAnswer() {
672
+ const r = this.lastOurs;
673
+ if (r === void 0 || r === this.committedOurs) return void 0;
674
+ const status = (await r.response().catch(() => null))?.status();
675
+ return status === 204 || status === 205 ? status : void 0;
676
+ }
580
677
  dispose() {
581
678
  this.page.off("request", this.onRequest);
582
679
  this.page.off("framenavigated", this.onNavigated);
@@ -622,13 +719,16 @@ async function captureFitting(cdp, opts) {
622
719
  }
623
720
  return null;
624
721
  }
625
- function proxyRefuses(proxy, host, port) {
722
+ async function proxyRefuses(proxy, host, port) {
723
+ return await probeProxy(proxy, host, port) === "refused";
724
+ }
725
+ function probeProxy(proxy, host, port) {
626
726
  return new Promise((resolve) => {
627
727
  let url;
628
728
  try {
629
729
  url = new URL(proxy.includes("://") ? proxy : `http://${proxy}`);
630
730
  } catch {
631
- resolve(false);
731
+ resolve("unknown");
632
732
  return;
633
733
  }
634
734
  const headers = { host: `${host}:${port}` };
@@ -644,16 +744,20 @@ function proxyRefuses(proxy, host, port) {
644
744
  headers,
645
745
  timeout: PROXY_PROBE_TIMEOUT_MS
646
746
  });
747
+ const verdict = (status) => status === 403 ? "refused" : status === 200 ? "connected" : "unreachable";
647
748
  req.on("connect", (res, socket) => {
648
749
  socket.destroy();
649
- resolve(res.statusCode === 403);
750
+ resolve(verdict(res.statusCode));
650
751
  });
651
752
  req.on("response", (res) => {
652
753
  res.resume();
653
- resolve(res.statusCode === 403);
754
+ resolve(verdict(res.statusCode));
755
+ });
756
+ req.on("timeout", () => {
757
+ resolve("no_answer");
758
+ req.destroy();
654
759
  });
655
- req.on("timeout", () => req.destroy());
656
- req.on("error", () => resolve(false));
760
+ req.on("error", () => resolve("unknown"));
657
761
  req.end();
658
762
  });
659
763
  }
@@ -677,6 +781,7 @@ var BrowserSession = class {
677
781
  ctx;
678
782
  proxy;
679
783
  clock;
784
+ navigationTimeoutMs;
680
785
  /** The device's workspace root (CAPYBARA_SERVICE_WORKSPACE): uploads and downloads stay in it. */
681
786
  workspace;
682
787
  downloadsTmp;
@@ -694,6 +799,11 @@ var BrowserSession = class {
694
799
  ids = /* @__PURE__ */ new WeakMap();
695
800
  titles = /* @__PURE__ */ new Map();
696
801
  loadingTabs = /* @__PURE__ */ new Set();
802
+ /**
803
+ * Each tab's icon: the address it came from and its data URL (null: none or not usable). Kept
804
+ * across navigations until the new page's icon is known, so the strip does not flicker.
805
+ */
806
+ favicons = /* @__PURE__ */ new Map();
697
807
  /** Tabs showing a verification page, by tab id (cleared on every main-frame navigation). */
698
808
  blockers = /* @__PURE__ */ new Map();
699
809
  /** The status of each tab's current document (main-frame response), by tab id. */
@@ -708,6 +818,8 @@ var BrowserSession = class {
708
818
  nextId = 1;
709
819
  active;
710
820
  queue = Promise.resolve();
821
+ /** The blank tab {@link activePage} is opening because none was left. */
822
+ opening;
711
823
  /** The agent's latest click; `seq` grows with every click (viewers flash only new ones). */
712
824
  lastClick;
713
825
  clickSeq = 0;
@@ -719,8 +831,9 @@ var BrowserSession = class {
719
831
  this.downloadMaxBytes = opts.downloadMaxBytes ?? DEFAULT_DOWNLOAD_MAX_BYTES;
720
832
  this.downloadWaitMs = opts.downloadWaitMs ?? DOWNLOAD_WAIT_MS;
721
833
  this.clock = opts.clock ?? systemClock;
834
+ this.navigationTimeoutMs = opts.navigationTimeoutMs ?? NAVIGATION_TIMEOUT_MS;
722
835
  ctx.setDefaultTimeout(ACTION_TIMEOUT_MS);
723
- ctx.setDefaultNavigationTimeout(NAVIGATION_TIMEOUT_MS);
836
+ ctx.setDefaultNavigationTimeout(this.navigationTimeoutMs);
724
837
  ctx.on("page", (p) => {
725
838
  if (!this.ids.has(p) && this.pages.size >= MAX_TABS) {
726
839
  p.close().catch(() => void 0);
@@ -743,19 +856,34 @@ var BrowserSession = class {
743
856
  this.listeners.add(fn);
744
857
  return () => this.listeners.delete(fn);
745
858
  }
746
- /** The active tab, opening a blank one when none is left. */
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
+ */
747
864
  async activePage() {
748
865
  const cur = this.active === void 0 ? void 0 : this.pages.get(this.active);
749
866
  if (cur !== void 0 && !cur.isClosed()) return cur;
750
- const first = [...this.pages.values()].find((p2) => !p2.isClosed());
867
+ const first = [...this.pages.values()].find((p) => !p.isClosed());
751
868
  if (first !== void 0) {
752
869
  this.active = this.ids.get(first);
753
870
  return first;
754
871
  }
755
- const p = await this.ctx.newPage();
756
- this.track(p);
757
- this.active = this.ids.get(p);
758
- return p;
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;
759
887
  }
760
888
  tabIdOf(page) {
761
889
  return this.ids.get(page) ?? "";
@@ -763,12 +891,14 @@ var BrowserSession = class {
763
891
  tabs() {
764
892
  return [...this.pages.entries()].map(([id, p]) => {
765
893
  const blocker = this.blockers.get(id);
894
+ const icon = this.favicons.get(id)?.data;
766
895
  return {
767
896
  id,
768
897
  title: clip(this.titles.get(id) ?? "", MAX_TITLE_CHARS),
769
898
  url: clip(p.url(), MAX_URL_CHARS),
770
899
  active: id === this.active,
771
- ...blocker === void 0 ? {} : { blocker }
900
+ ...blocker === void 0 ? {} : { blocker },
901
+ ...icon === void 0 || icon === null ? {} : { favicon: icon }
772
902
  };
773
903
  });
774
904
  }
@@ -823,6 +953,7 @@ var BrowserSession = class {
823
953
  page.on("load", () => {
824
954
  this.loadingTabs.delete(id);
825
955
  refresh();
956
+ void this.resolveFavicon(page, id);
826
957
  });
827
958
  page.on("requestfailed", (r) => {
828
959
  settle(r);
@@ -853,6 +984,7 @@ var BrowserSession = class {
853
984
  this.titles.delete(id);
854
985
  this.loadingTabs.delete(id);
855
986
  this.blockers.delete(id);
987
+ this.favicons.delete(id);
856
988
  this.docStatus.delete(id);
857
989
  if (this.active === id) {
858
990
  const next = [...this.pages.keys()].at(-1);
@@ -1149,7 +1281,21 @@ var BrowserSession = class {
1149
1281
  for (const c of this.collectors) c.pending.push(probe);
1150
1282
  return probe;
1151
1283
  }
1152
- /** Runs `fn` one at a time with the other actions (`wait` runs beside them). */
1284
+ /** `value`, or `fallback` when it takes longer than {@link PAGE_QUERY_MS} (never rejects). */
1285
+ async bounded(value, fallback) {
1286
+ let timer;
1287
+ try {
1288
+ return await Promise.race([
1289
+ value.catch(() => fallback),
1290
+ new Promise((r) => {
1291
+ timer = this.clock.schedule(() => r(fallback), PAGE_QUERY_MS);
1292
+ })
1293
+ ]);
1294
+ } finally {
1295
+ this.clock.cancel(timer);
1296
+ }
1297
+ }
1298
+ /** Runs `fn` one at a time with the other actions (`wait` and the tab list run beside them). */
1153
1299
  serial(fn) {
1154
1300
  const run = this.queue.then(fn, fn);
1155
1301
  this.queue = run.catch(() => void 0);
@@ -1166,7 +1312,7 @@ var BrowserSession = class {
1166
1312
  this.collectors.add(c);
1167
1313
  let reply;
1168
1314
  try {
1169
- const out = await (req.op === "wait" ? this.exec(req) : this.serial(() => {
1315
+ const out = await (req.op === "wait" || req.op === "tabs" && req.action === "list" ? this.exec(req) : this.serial(() => {
1170
1316
  if (opts.takenOver?.() === true)
1171
1317
  throw new ActionError("taken_over", TAKEN_OVER_MESSAGE);
1172
1318
  return this.exec(req);
@@ -1234,13 +1380,41 @@ var BrowserSession = class {
1234
1380
  await Promise.allSettled(all);
1235
1381
  }
1236
1382
  }
1383
+ /**
1384
+ * Finds the loaded page's icon and fetches it through the browser (the device's network rules
1385
+ * apply); a new address replaces the tab's icon, the same one is not fetched again. Any failure
1386
+ * leaves no icon (the panel's placeholder) and never affects the page.
1387
+ */
1388
+ async resolveFavicon(page, id) {
1389
+ try {
1390
+ const url = await iconUrlOf(page);
1391
+ if (this.pages.get(id) !== page) return;
1392
+ if (url === null) {
1393
+ if (this.favicons.delete(id)) this.emit({ type: "state" });
1394
+ return;
1395
+ }
1396
+ if (this.favicons.get(id)?.url === url) return;
1397
+ const cdp = await this.ctx.newCDPSession(page);
1398
+ let data = null;
1399
+ try {
1400
+ const bytes = await fetchIcon(cdp, url);
1401
+ data = bytes === null ? null : iconDataUrl(bytes);
1402
+ } finally {
1403
+ await cdp.detach().catch(() => void 0);
1404
+ }
1405
+ if (this.pages.get(id) !== page) return;
1406
+ this.favicons.set(id, { url, data });
1407
+ this.emit({ type: "state" });
1408
+ } catch {
1409
+ }
1410
+ }
1237
1411
  /**
1238
1412
  * Looks at the tab's page now and records or clears its verification blocker; true when it
1239
1413
  * shows a verification page.
1240
1414
  */
1241
1415
  async checkVerification(page, id) {
1242
1416
  if (id === "") return false;
1243
- const blocked = await isVerificationPage(page, this.docStatus.get(id));
1417
+ const blocked = await this.bounded(isVerificationPage(page, this.docStatus.get(id)), false);
1244
1418
  if (this.pages.get(id) !== page) return false;
1245
1419
  const before = this.blockers.get(id);
1246
1420
  if (blocked) {
@@ -1256,12 +1430,11 @@ var BrowserSession = class {
1256
1430
  return blocked;
1257
1431
  }
1258
1432
  async pageInfo(page) {
1259
- let title = "";
1260
- try {
1261
- title = await page.title();
1262
- } catch {
1263
- title = this.titles.get(this.tabIdOf(page)) ?? "";
1264
- }
1433
+ const known = this.titles.get(this.tabIdOf(page)) ?? "";
1434
+ const title = await this.bounded(
1435
+ page.title().catch(() => known),
1436
+ known
1437
+ );
1265
1438
  return {
1266
1439
  url: clip(page.url(), MAX_URL_CHARS),
1267
1440
  title: clip(title, MAX_TITLE_CHARS),
@@ -1308,7 +1481,7 @@ var BrowserSession = class {
1308
1481
  try {
1309
1482
  const out = await fn();
1310
1483
  if (navigating && !loaded2) {
1311
- await page.waitForEvent("domcontentloaded", { timeout: NAVIGATION_TIMEOUT_MS }).catch(() => void 0);
1484
+ await page.waitForEvent("domcontentloaded", { timeout: this.navigationTimeoutMs }).catch(() => void 0);
1312
1485
  }
1313
1486
  return out;
1314
1487
  } finally {
@@ -1336,7 +1509,7 @@ var BrowserSession = class {
1336
1509
  let res;
1337
1510
  const download = page.waitForEvent("download", { timeout: ACTION_TIMEOUT_MS });
1338
1511
  download.catch(() => void 0);
1339
- const deadline = Date.now() + NAVIGATION_TIMEOUT_MS;
1512
+ const deadline = Date.now() + this.navigationTimeoutMs;
1340
1513
  const watch = new NavWatch(page, url, () => this.pendingNavs.get(page));
1341
1514
  try {
1342
1515
  res = await page.goto(url, { waitUntil: "domcontentloaded" });
@@ -1346,13 +1519,25 @@ var BrowserSession = class {
1346
1519
  await download.catch(() => void 0);
1347
1520
  return;
1348
1521
  }
1349
- if (PROXY_FAILURE_RE.test(msg)) await this.checkBlocked(url);
1350
- if (!msg.includes("net::ERR_ABORTED")) throw e;
1522
+ if (isTimeout(e)) throw await this.navigationTimedOut(page, url);
1523
+ if (!msg.includes("net::ERR_ABORTED")) throw await this.navigationFailed(page, e, url, msg);
1351
1524
  const out = await watch.follow(deadline);
1525
+ if (out.kind !== "loaded") {
1526
+ const status = await watch.emptyAnswer();
1527
+ if (status !== void 0)
1528
+ throw new ActionError(
1529
+ "failed",
1530
+ `${url} answered ${status} with no page to show; the tab shows ${page.url()}.`
1531
+ );
1532
+ }
1352
1533
  if (out.kind === "none") throw e;
1353
1534
  if (out.kind === "failed") {
1354
- if (PROXY_FAILURE_RE.test(out.error)) await this.checkBlocked(out.url);
1355
- throw new Error(`${out.error} at ${out.url}`);
1535
+ throw await this.navigationFailed(
1536
+ page,
1537
+ new Error(`${out.error} at ${out.url}`),
1538
+ out.url,
1539
+ out.error
1540
+ );
1356
1541
  }
1357
1542
  res = out.response;
1358
1543
  } finally {
@@ -1366,6 +1551,101 @@ var BrowserSession = class {
1366
1551
  }
1367
1552
  await page.waitForLoadState("load", { timeout: LOAD_GRACE_MS }).catch(() => void 0);
1368
1553
  }
1554
+ /**
1555
+ * The error of a navigation that failed with Chromium's net error `error`: a host the proxy
1556
+ * refuses is reported as blocked (`run` turns `original` into the blocked reply); any other net
1557
+ * error is `unreachable`, saying what the device's network answered when it went through it.
1558
+ */
1559
+ async navigationFailed(page, original, url, error) {
1560
+ const net = /net::(ERR_[A-Z_]+)/.exec(error)?.[1];
1561
+ if (net === void 0 || net === "ERR_ABORTED") return original;
1562
+ await this.errorPageCommitted(page);
1563
+ if (PROXY_FAILURE_RE.test(error)) {
1564
+ if (await this.checkBlocked(url)) return original;
1565
+ const detail = await this.networkDetail(url);
1566
+ return new ActionError(
1567
+ "unreachable",
1568
+ `${url} could not be loaded (net::${net})${detail === "" ? "." : `: ${detail}`}`
1569
+ );
1570
+ }
1571
+ const meaning = NET_ERROR_MEANINGS[net];
1572
+ return new ActionError(
1573
+ "unreachable",
1574
+ `${url} could not be loaded (net::${net})${meaning === void 0 ? "." : `: ${meaning}.`}`
1575
+ );
1576
+ }
1577
+ /**
1578
+ * Waits (at most {@link ERROR_PAGE_WAIT_MS}) for the error page of the main frame's failed
1579
+ * navigation: Chromium commits it after Playwright reported the failure (the Linux full build
1580
+ * shows it), and a navigation started before that commit is interrupted by it.
1581
+ */
1582
+ async errorPageCommitted(page) {
1583
+ if (page.isClosed() || page.mainFrame().url().startsWith("chrome-error:")) return;
1584
+ await page.waitForEvent("framenavigated", {
1585
+ predicate: (f) => f === page.mainFrame() && f.url().startsWith("chrome-error:"),
1586
+ timeout: ERROR_PAGE_WAIT_MS
1587
+ }).catch(() => void 0);
1588
+ }
1589
+ /**
1590
+ * The error of a navigation that took longer than its time limit. The navigation is stopped
1591
+ * first (a navigation left in flight keeps the page's scripts and snapshots waiting for a
1592
+ * document that never comes), so the tab goes back to the page it showed and the next request
1593
+ * works on it; the message says what the device's network answered for the host.
1594
+ */
1595
+ async navigationTimedOut(page, url) {
1596
+ await this.stopNavigation(page);
1597
+ const seconds = Math.round(this.navigationTimeoutMs / 1e3);
1598
+ let detail = await this.networkDetail(url, true);
1599
+ if (detail === "") detail = "no page came in that time.";
1600
+ const now = page.isClosed() ? "" : ` The navigation was stopped; the tab shows ${page.url()}.`;
1601
+ return new ActionError(
1602
+ "unreachable",
1603
+ `${url} did not load within ${seconds} s: ${detail}${now}`
1604
+ );
1605
+ }
1606
+ /** Stops the page's navigation in flight (Chromium's stop button); never throws. */
1607
+ async stopNavigation(page) {
1608
+ if (page.isClosed()) return;
1609
+ try {
1610
+ const cdp = await this.ctx.newCDPSession(page);
1611
+ try {
1612
+ await cdp.send("Page.stopLoading");
1613
+ } finally {
1614
+ await cdp.detach().catch(() => void 0);
1615
+ }
1616
+ } catch {
1617
+ }
1618
+ this.pendingNavs.delete(page);
1619
+ const id = this.ids.get(page);
1620
+ if (id !== void 0 && this.loadingTabs.delete(id)) this.emit({ type: "state" });
1621
+ }
1622
+ /**
1623
+ * What the device's proxy answers for the URL's host, as a sentence ("" without a proxy, or when
1624
+ * the proxy failed itself). `timedOut`: the navigation got no page in time.
1625
+ */
1626
+ async networkDetail(rawUrl, timedOut = false) {
1627
+ if (this.proxy === void 0) return "";
1628
+ let url;
1629
+ try {
1630
+ url = new URL(rawUrl);
1631
+ } catch {
1632
+ return "";
1633
+ }
1634
+ const host = url.hostname;
1635
+ const port = Number(url.port || (url.protocol === "https:" ? 443 : 80));
1636
+ switch (await probeProxy(this.proxy, host, port)) {
1637
+ case "unreachable":
1638
+ return `the device's network could not connect to ${host}:${port} (the name did not resolve, or the host refused or did not answer the connection).`;
1639
+ case "no_answer":
1640
+ return `the device's network got no answer from ${host}:${port}.`;
1641
+ case "connected":
1642
+ return timedOut ? `${host} accepted the connection through the device's network but sent no page in that time.` : `the device's network connects to ${host}:${port}, but the connection failed.`;
1643
+ case "refused":
1644
+ return `the device's network settings block ${host}.`;
1645
+ default:
1646
+ return "";
1647
+ }
1648
+ }
1369
1649
  async exec(req) {
1370
1650
  switch (req.op) {
1371
1651
  case "navigate": {
@@ -1373,12 +1653,20 @@ var BrowserSession = class {
1373
1653
  if (req.url !== void 0) {
1374
1654
  await this.goto(page, normalizeUrl(req.url));
1375
1655
  } else if (req.action === "back" || req.action === "forward") {
1376
- const r = await (req.action === "back" ? page.goBack() : page.goForward());
1656
+ const r = await (req.action === "back" ? page.goBack() : page.goForward()).catch(
1657
+ async (e) => {
1658
+ if (isTimeout(e)) throw await this.navigationTimedOut(page, page.url());
1659
+ throw e;
1660
+ }
1661
+ );
1377
1662
  if (r === null && page.url() === "about:blank") {
1378
1663
  return { text: `No ${req.action === "back" ? "earlier" : "later"} page in this tab.` };
1379
1664
  }
1380
1665
  } else if (req.action === "reload") {
1381
- await page.reload({ waitUntil: "domcontentloaded" });
1666
+ await page.reload({ waitUntil: "domcontentloaded" }).catch(async (e) => {
1667
+ if (isTimeout(e)) throw await this.navigationTimedOut(page, page.url());
1668
+ throw e;
1669
+ });
1382
1670
  } else {
1383
1671
  throw new ActionError(
1384
1672
  "failed",
@@ -1488,7 +1776,7 @@ var BrowserSession = class {
1488
1776
  async tabsOp(req) {
1489
1777
  switch (req.action) {
1490
1778
  case "list": {
1491
- await this.activePage();
1779
+ if (this.pages.size === 0) await this.activePage();
1492
1780
  const lines = await Promise.all(
1493
1781
  [...this.pages.entries()].map(async ([id, p]) => {
1494
1782
  const info = await this.pageInfo(p);
@@ -1618,8 +1906,11 @@ import {
1618
1906
  import { createRequire } from "node:module";
1619
1907
  import { dirname, isAbsolute, join as join2, relative } from "node:path";
1620
1908
  import { fileURLToPath } from "node:url";
1621
- function chromiumBuild(platform) {
1622
- return platform === "darwin" ? "chromium-headless-shell" : "chromium";
1909
+ var SERVICE_MACH_ENV = DEVICE_SERVICE_MACH_ENV;
1910
+ var HEADLESS_SHELL_NOTE = "The browser runs as a headless shell, which sites flag as a bot more often: the machine's capybara-device predates the full browser; ask the user to update capybara-device on that machine.";
1911
+ function chromiumBuild(platform, env = process.env) {
1912
+ if (platform !== "darwin") return "chromium";
1913
+ return env[SERVICE_MACH_ENV] === DEVICE_SERVICE_MACH_CHROMIUM ? "chromium" : "chromium-headless-shell";
1623
1914
  }
1624
1915
  var BUILD_DIR = {
1625
1916
  chromium: "chromium",
@@ -1728,17 +2019,46 @@ function shippedRevisions(cache, build) {
1728
2019
  }
1729
2020
  return names.map((n) => ({ n, rev: Number(re.exec(n)?.[1] ?? Number.NaN) })).filter((x) => Number.isFinite(x.rev)).sort((a, b) => a.rev - b.rev).map((x) => x.n);
1730
2021
  }
2022
+ var PLAYWRIGHT_DISABLED_FEATURES = [
2023
+ "AvoidUnnecessaryBeforeUnloadCheckSync",
2024
+ "DestroyProfileOnBrowserClose",
2025
+ "HttpsUpgrades",
2026
+ "HttpsFirstBalancedModeAutoEnable",
2027
+ "LensOverlay",
2028
+ "MediaRouter",
2029
+ "PaintHolding",
2030
+ "ThirdPartyStoragePartitioning",
2031
+ "AvoidCorsURLLoaderRestartOnRedirect",
2032
+ "TcpPortRandomizationWin",
2033
+ "OptimizationHints",
2034
+ "NetworkTimeServiceQuerying",
2035
+ "AimEnabled",
2036
+ "PreconnectToSearch",
2037
+ "msForceBrowserSignIn",
2038
+ "msEdgeUpdateLaunchServicesPreferredVersion"
2039
+ ];
2040
+ var DISABLED_FEATURES = [...PLAYWRIGHT_DISABLED_FEATURES, "AcceptCHFrame"];
1731
2041
  function chromiumLaunchPlan(opts, release = browserRelease(
1732
- chromiumBuild(opts.platform)
2042
+ chromiumBuild(opts.platform, opts.env)
1733
2043
  )) {
1734
- const build = chromiumBuild(opts.platform);
2044
+ const build = chromiumBuild(opts.platform, opts.env);
1735
2045
  const args = [
1736
2046
  "--headless",
1737
2047
  "--use-mock-keychain",
1738
2048
  `--window-size=${VIEWPORT.width},${VIEWPORT.height}`,
1739
- `--user-agent=${chromeUserAgent(opts.platform, release?.version ?? "")}`
2049
+ `--user-agent=${chromeUserAgent(opts.platform, release?.version ?? "")}`,
2050
+ `--disable-features=${DISABLED_FEATURES.join(",")}`,
2051
+ // Chrome reloads a network error page by itself (after 1 s, then backing off): that reload
2052
+ // aborts the agent's next navigation in the tab and asks the proxy for the failed host again
2053
+ "--disable-auto-reload"
1740
2054
  ];
1741
2055
  if (build === "chromium-headless-shell") args.push("--single-process");
2056
+ let env;
2057
+ if (opts.platform === "darwin") {
2058
+ args.push("--disable-crash-reporter", "--disable-breakpad");
2059
+ const tmp = envValue(opts.env, "TMPDIR");
2060
+ if (tmp !== void 0) env = { MAC_CHROMIUM_TMPDIR: tmp };
2061
+ }
1742
2062
  const proxy = envValue(opts.env, "HTTPS_PROXY") ?? envValue(opts.env, "HTTP_PROXY");
1743
2063
  let proxyAuth;
1744
2064
  if (proxy !== void 0) {
@@ -1765,6 +2085,7 @@ function chromiumLaunchPlan(opts, release = browserRelease(
1765
2085
  return {
1766
2086
  ...opts.browsersPath === void 0 ? browsersPathFor(opts.stateDir, opts.env, release?.revision, build) : { browsersPath: opts.browsersPath },
1767
2087
  build,
2088
+ ...env === void 0 ? {} : { env },
1768
2089
  profileDir: join2(opts.stateDir, "profile"),
1769
2090
  downloadsTmp: join2(opts.stateDir, "downloads-tmp"),
1770
2091
  args,
@@ -1834,7 +2155,8 @@ async function launchChromium(plan) {
1834
2155
  // downloads are saved into the workspace by the session (actions.ts)
1835
2156
  acceptDownloads: true,
1836
2157
  downloadsPath: plan.downloadsTmp,
1837
- ...plan.proxyAuth === void 0 ? {} : { proxy: plan.proxyAuth }
2158
+ ...plan.proxyAuth === void 0 ? {} : { proxy: plan.proxyAuth },
2159
+ ...plan.env === void 0 ? {} : { env: { ...process.env, ...plan.env } }
1838
2160
  });
1839
2161
  }
1840
2162
  async function shippedExecutable(cache, dir, build) {
@@ -2592,6 +2914,9 @@ var ViewerSession = class {
2592
2914
  if (fits(m)) return m;
2593
2915
  let small;
2594
2916
  if (m.t === "state") {
2917
+ const plain = { ...m, tabs: m.tabs.map(({ favicon: _icon, ...t }) => t) };
2918
+ if (fits(plain)) return plain;
2919
+ m = plain;
2595
2920
  const handoff = m.handoff === void 0 ? {} : { handoff: { ...m.handoff, message: clip(m.handoff.message, 200) } };
2596
2921
  small = {
2597
2922
  ...m,
@@ -2994,10 +3319,13 @@ async function startDaemon(opts) {
2994
3319
  workspace: workspace === void 0 || workspace === "" ? void 0 : workspace,
2995
3320
  downloadsTmp: plan.downloadsTmp,
2996
3321
  downloadMaxBytes: downloadMaxBytes(opts.env),
2997
- ...opts.downloadWaitMs === void 0 ? {} : { downloadWaitMs: opts.downloadWaitMs }
3322
+ ...opts.downloadWaitMs === void 0 ? {} : { downloadWaitMs: opts.downloadWaitMs },
3323
+ ...opts.navigationTimeoutMs === void 0 ? {} : { navigationTimeoutMs: opts.navigationTimeoutMs }
2998
3324
  });
2999
3325
  if (plan.shippedDir !== void 0)
3000
3326
  session.note(shippedRevisionNote(plan.shippedDir, browserRevision(plan.build)));
3327
+ if (plan.build === "chromium-headless-shell" && opts.browsersPath === void 0)
3328
+ session.note(HEADLESS_SHELL_NOTE);
3001
3329
  if (!closing) await restoreCookies(ctx, opts.stateDir);
3002
3330
  if (!restored && !closing) {
3003
3331
  restored = true;