@capybara-hq/plugin-browser 0.1.0-rc.2 → 0.1.0-rc.4

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.2",
4
+ "version": "0.1.0-rc.4",
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.2",
20
+ "version": "0.1.0-rc.4",
21
21
  "sdk": "^0.1.0-rc.69",
22
22
  "provides": [],
23
23
  "requires": [],
package/README.md CHANGED
@@ -46,7 +46,8 @@ A real browser in the person's device for agents (browser use spec,
46
46
  - Chromium starts on the daemon's first start. A launch that fails (no download, a refused
47
47
  network) does not stop the daemon: every request answers the cause and launches again. When the
48
48
  device's proxy refuses Playwright's download hosts (`cdn.playwright.dev`,
49
- `playwright.download.prss.microsoft.com`, or `PLAYWRIGHT_DOWNLOAD_HOST`), the reply lists them
49
+ `playwright.download.prss.microsoft.com`, `storage.googleapis.com` where the CDN redirects the
50
+ headless shell, or `PLAYWRIGHT_DOWNLOAD_HOST`), the reply lists them
50
51
  as blocked hosts, so the person is asked to allow them. A `PLAYWRIGHT_BROWSERS_PATH` in the
51
52
  device's environment that already holds this build's headless shell revision is used as is
52
53
  (a read-only image cache); otherwise the browser is installed into `<state>/browsers`.
@@ -70,9 +71,16 @@ A real browser in the person's device for agents (browser use spec,
70
71
  state. Take over is offered only in the live view; handing back with a pending handoff answers
71
72
  it Done.
72
73
  - 允许 allows the blocked host, then opens the blocked page (the blocked navigation, or the page
73
- whose resource was refused), again on the next connection if the browser restarted. A 4404 is
74
- retried twice (1 s, 3 s) before "not running", which looks for the browser every 10 s while
75
- visible, for 30 minutes at most (a ticket never starts the service). A refused allow or answer
76
- shows the kernel's reason.
74
+ whose resource was refused), again on the next connection if the browser restarted. A 4404
75
+ after a live view (a restart) is retried twice (1 s, 3 s) before "not running"; one before any
76
+ live view is "not running" at once. "Not running" looks for the browser quietly (it stays up
77
+ until the browser answers) every 10 s while visible, for 30 minutes at most (a ticket never
78
+ starts the service). A refused allow or answer shows the kernel's reason.
79
+ - Size: in the side panel the page posts the embed `resize` (120–4000) for the 16:10 frame at the
80
+ available width plus its bars, again whenever its box changes; in full mode (asked for with
81
+ `panel-mode` on take over) the host fills the panel and the frame is letterboxed in it, with
82
+ the viewer's frame size following the shown size. The host sends no mode back, so full mode
83
+ ends with the person's control by any path (hand back here or elsewhere, the agent resuming),
84
+ and the side size is asked for again.
77
85
  - A dialog strip hides after 10 s or when the page changes; agent clicks flash once each; a lock
78
86
  shows a secure page. The panel listens only to messages from its host page.
package/dist/index.mjs CHANGED
@@ -84,7 +84,7 @@ function daemonToolError(code, message) {
84
84
  `${message} Ask the user to allow these hosts so the browser can be installed, then retry.`
85
85
  );
86
86
  return new ToolError(
87
- `${message} The user is asked to allow the host; if they decline, use another site.`
87
+ `${message} The network note says whether the host can be allowed from this conversation; if it is not allowed, use another site.`
88
88
  );
89
89
  default:
90
90
  return new ToolError(`${message} Check the page with browser_snapshot before retrying.`);
@@ -859,7 +859,7 @@ function registerBrowserTools(ctx, deps) {
859
859
  // src/index.ts
860
860
  var index_default = defineExtension({
861
861
  name: "browser",
862
- version: "0.1.0-rc.2",
862
+ version: "0.1.0-rc.4",
863
863
  sdk: "^0.1.0-rc.69",
864
864
  provides: [],
865
865
  ui: [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@capybara-hq/plugin-browser",
3
- "version": "0.1.0-rc.2",
3
+ "version": "0.1.0-rc.4",
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
@@ -85,6 +85,8 @@
85
85
  var PROTOCOL = "capybara-embed/1";
86
86
  var ASPECT = VIEWPORT.width / VIEWPORT.height;
87
87
  var SIDE_MAX_WIDTH = 640;
88
+ var MIN_HEIGHT = 120;
89
+ var MAX_HEIGHT = 4e3;
88
90
  var HIDDEN_CLOSE_MS = 6e4;
89
91
  var COMPACT_BELOW = 600;
90
92
  var MOVE_INTERVAL_MS = 50;
@@ -132,6 +134,10 @@
132
134
  let retried401 = false;
133
135
  let attempts = 0;
134
136
  let restartRetries = 0;
137
+ let wasLive = false;
138
+ let quiet = false;
139
+ let full = false;
140
+ let postedHeight = 0;
135
141
  let retryTimer;
136
142
  let emptyTimer;
137
143
  let emptySince;
@@ -155,7 +161,14 @@
155
161
  if (sock === null) return;
156
162
  sock.send(new TextEncoder().encode(JSON.stringify(msg)));
157
163
  }
158
- const bridge = (full) => post({ protocol: PROTOCOL, type: "panel-mode", full });
164
+ function bridge(next) {
165
+ full = next;
166
+ post({ protocol: PROTOCOL, type: "panel-mode", full: next });
167
+ if (!next) {
168
+ postedHeight = 0;
169
+ fitHeight();
170
+ }
171
+ }
159
172
  function setLabels() {
160
173
  const set = (id, key) => {
161
174
  $(id).textContent = text(key);
@@ -189,6 +202,10 @@
189
202
  const el = $("status");
190
203
  el.setAttribute("data-control", control);
191
204
  let key;
205
+ if (mode === "empty" || mode === "offline" || mode === "error") {
206
+ el.textContent = "";
207
+ return;
208
+ }
192
209
  if (mode === "connecting") key = "statusConnecting";
193
210
  else if (control === "user") key = compact() ? "statusUserElsewhere" : "takeoverHint";
194
211
  else if (lastState?.loading === true) key = "statusLoading";
@@ -263,7 +280,9 @@
263
280
  $("handoff").hidden = pendingHandoff === null;
264
281
  $("handoff-message").textContent = pendingHandoff?.message ?? "";
265
282
  tabs = s.tabs;
283
+ const was = control;
266
284
  control = s.control;
285
+ if (full && was === "user" && control === "agent") bridge(false);
267
286
  const active = tabs.find((x) => x.active);
268
287
  if (doc.activeElement !== url) url.value = active?.url ?? "";
269
288
  renderTabs();
@@ -336,10 +355,28 @@
336
355
  view.style.width = `${box.w}px`;
337
356
  view.style.height = `${box.h}px`;
338
357
  const dpr = win.devicePixelRatio || 1;
339
- const cap = control === "user" ? VIEWPORT.width : SIDE_MAX_WIDTH;
358
+ const cap = control === "user" || full ? VIEWPORT.width : SIDE_MAX_WIDTH;
340
359
  const w = Math.max(1, Math.min(cap, Math.round(box.w * dpr)));
341
360
  return { w, h: Math.max(1, Math.round(w / ASPECT)) };
342
361
  }
362
+ function fitHeight() {
363
+ if (full) return;
364
+ const st = stage.getBoundingClientRect();
365
+ const width = Math.max(0, Math.floor(st.width));
366
+ if (width === 0) return;
367
+ const chrome = Math.max(0, win.innerHeight - Math.max(0, st.height));
368
+ const height = Math.max(MIN_HEIGHT, Math.min(MAX_HEIGHT, Math.ceil(chrome + width / ASPECT)));
369
+ if (height === postedHeight) return;
370
+ postedHeight = height;
371
+ post({ protocol: PROTOCOL, type: "resize", height });
372
+ }
373
+ function onBoxChange() {
374
+ fitHeight();
375
+ if (sock === null || mode !== "live") return;
376
+ const { w, h } = layout();
377
+ if (sentSize !== `${w}x${h}`) sizeMessage("resize");
378
+ draw();
379
+ }
343
380
  function sizeMessage(kind) {
344
381
  const { w, h } = layout();
345
382
  sentSize = `${w}x${h}`;
@@ -368,7 +405,10 @@
368
405
  }
369
406
  function show(next) {
370
407
  mode = next;
371
- if (next === "empty") armEmptyPoll();
408
+ if (next === "empty") {
409
+ wasLive = false;
410
+ armEmptyPoll();
411
+ }
372
412
  renderChrome();
373
413
  }
374
414
  function armEmptyPoll() {
@@ -379,7 +419,7 @@
379
419
  if (mode !== "empty" || emptySince === void 0) return;
380
420
  if (Date.now() - emptySince >= EMPTY_POLL_FOR_MS) return;
381
421
  if (doc.visibilityState === "hidden") armEmptyPoll();
382
- else void connect();
422
+ else void connect(true);
383
423
  }, EMPTY_POLL_MS);
384
424
  }
385
425
  function stop() {
@@ -395,10 +435,12 @@
395
435
  s.close();
396
436
  }
397
437
  }
398
- async function connect() {
438
+ async function connect(lookOnly = false) {
399
439
  stop();
400
440
  const mine = gen;
401
- show("connecting");
441
+ quiet = lookOnly && mode === "empty";
442
+ if (quiet) armEmptyPoll();
443
+ else show("connecting");
402
444
  let ticketUrl;
403
445
  try {
404
446
  const res = await doFetch("stream-ticket", {
@@ -411,10 +453,10 @@
411
453
  if (mine !== gen) return;
412
454
  const code = body.code ?? body.error?.code;
413
455
  if (code === "service_not_running") return show("empty");
414
- if (!res.ok || typeof body.url !== "string") return show("offline");
456
+ if (!res.ok || typeof body.url !== "string") return show(quiet ? "empty" : "offline");
415
457
  ticketUrl = body.url;
416
458
  } catch {
417
- if (mine === gen) show("offline");
459
+ if (mine === gen) show(quiet ? "empty" : "offline");
418
460
  return;
419
461
  }
420
462
  const ws = new SocketCtor(ticketUrl);
@@ -449,6 +491,8 @@
449
491
  switch (msg.t) {
450
492
  case "state":
451
493
  mode = "live";
494
+ wasLive = true;
495
+ quiet = false;
452
496
  emptySince = void 0;
453
497
  applyState(msg);
454
498
  break;
@@ -468,11 +512,15 @@
468
512
  function onClose(code) {
469
513
  sock = null;
470
514
  lastState = null;
515
+ if (quiet && code !== 4401 && code !== 4409 && code !== 1009) {
516
+ show("empty");
517
+ return;
518
+ }
471
519
  if (code === 4401 && !retried401) {
472
520
  retried401 = true;
473
- void connect();
521
+ void connect(quiet);
474
522
  } else if (code === 4404) {
475
- const wait = RESTART_RETRY_MS[restartRetries];
523
+ const wait = wasLive ? RESTART_RETRY_MS[restartRetries] : void 0;
476
524
  if (wait === void 0) show("empty");
477
525
  else {
478
526
  restartRetries++;
@@ -638,13 +686,13 @@
638
686
  if (e.key === "Escape" && interactive()) handback();
639
687
  });
640
688
  win.addEventListener("resize", () => {
689
+ onBoxChange();
641
690
  if (sock === null || mode !== "live") return;
642
- const { w, h } = layout();
643
- if (sentSize !== `${w}x${h}`) sizeMessage("resize");
644
691
  renderChrome();
645
692
  renderTabs();
646
- draw();
647
693
  });
694
+ const Ro = win.ResizeObserver;
695
+ if (Ro !== void 0) new Ro(onBoxChange).observe(stage);
648
696
  doc.addEventListener("visibilitychange", () => {
649
697
  if (doc.visibilityState === "hidden") {
650
698
  if (hiddenTimer === void 0) {
@@ -661,7 +709,7 @@
661
709
  hiddenTimer = void 0;
662
710
  if (pausedForHidden) {
663
711
  pausedForHidden = false;
664
- void connect();
712
+ void connect(true);
665
713
  }
666
714
  }
667
715
  });
@@ -677,6 +725,7 @@
677
725
  }
678
726
  setLabels();
679
727
  renderChrome();
728
+ fitHeight();
680
729
  win.addEventListener("message", (ev) => {
681
730
  if (ev.source !== win.parent) return;
682
731
  const m = ev.data;
@@ -687,6 +736,8 @@
687
736
  applyTheme(m.tokens, m.theme);
688
737
  setLabels();
689
738
  renderChrome();
739
+ postedHeight = 0;
740
+ fitHeight();
690
741
  if (!started) {
691
742
  started = true;
692
743
  void connect();
@@ -334,6 +334,113 @@ function absent(path) {
334
334
  var PROXY_PROBE_TIMEOUT_MS = 5e3;
335
335
  var REF_RE = /^(f\d+)?e\d+$/;
336
336
  var PROXY_FAILURE_RE = /ERR_TUNNEL_CONNECTION_FAILED|ERR_PROXY_CONNECTION_FAILED/;
337
+ function docUrl(raw) {
338
+ try {
339
+ const u = new URL(raw);
340
+ u.hash = "";
341
+ return u.href;
342
+ } catch {
343
+ return raw;
344
+ }
345
+ }
346
+ var NavWatch = class {
347
+ constructor(page, url, pending) {
348
+ this.page = page;
349
+ this.pending = pending;
350
+ this.target = docUrl(url);
351
+ const before = pending();
352
+ if (before !== void 0 && this.isOurs(before)) this.lastOurs = before;
353
+ page.on("request", this.onRequest);
354
+ page.on("framenavigated", this.onNavigated);
355
+ page.on("requestfailed", this.onFailed);
356
+ page.on("requestfinished", this.onFinished);
357
+ }
358
+ page;
359
+ pending;
360
+ target;
361
+ /** The newest main-frame navigation request to the target address (redirects included). */
362
+ lastOurs;
363
+ /** The request of `lastOurs`'s chain whose document the main frame committed. */
364
+ committedOurs;
365
+ /** The request of `lastOurs`'s chain that failed. */
366
+ failedOurs;
367
+ wake;
368
+ onRequest = (r) => {
369
+ if (!r.isNavigationRequest() || r.frame() !== this.page.mainFrame()) return;
370
+ this.lastOurs = this.isOurs(r) ? r : void 0;
371
+ this.wake?.();
372
+ };
373
+ onNavigated = (f) => {
374
+ if (f !== this.page.mainFrame()) return;
375
+ const ours = this.lastOurs;
376
+ if (ours !== void 0 && docUrl(this.page.mainFrame().url()) === docUrl(ours.url()))
377
+ this.committedOurs = ours;
378
+ this.wake?.();
379
+ };
380
+ onFailed = (r) => {
381
+ if (r === this.lastOurs) this.failedOurs = r;
382
+ this.wake?.();
383
+ };
384
+ /** After the session's own `requestfinished` handler (registered first) settled the request. */
385
+ onFinished = (r) => {
386
+ if (!r.isNavigationRequest() || r.frame() !== this.page.mainFrame()) return;
387
+ const wake = () => this.wake?.();
388
+ void r.response().then(wake, wake);
389
+ };
390
+ isOurs(r) {
391
+ let root = r;
392
+ for (let from = r.redirectedFrom(); from !== null; from = from.redirectedFrom()) root = from;
393
+ return docUrl(root.url()) === this.target;
394
+ }
395
+ /** Resolves on the next navigation event or after `ms`. */
396
+ next(ms) {
397
+ return new Promise((resolve) => {
398
+ const timer = setTimeout(done, ms);
399
+ function done() {
400
+ clearTimeout(timer);
401
+ resolve();
402
+ }
403
+ this.wake = () => {
404
+ this.wake = void 0;
405
+ done();
406
+ };
407
+ });
408
+ }
409
+ /**
410
+ * After an abort: waits (until `deadline`, the navigation's own) while a navigation to the
411
+ * target address is in flight, then tells whether it loaded (its document committed; a script
412
+ * may have moved the page on since), failed, or none of ours took over.
413
+ */
414
+ async follow(deadline) {
415
+ for (let r = this.pending(); r !== void 0; r = this.pending()) {
416
+ if (!this.isOurs(r)) return { kind: "none" };
417
+ const left2 = deadline - Date.now();
418
+ if (left2 <= 0) return { kind: "none" };
419
+ await this.next(left2);
420
+ }
421
+ const final = this.lastOurs;
422
+ if (final === void 0) return { kind: "none" };
423
+ if (this.failedOurs === final) {
424
+ return { kind: "failed", url: final.url(), error: final.failure()?.errorText ?? "" };
425
+ }
426
+ if (this.committedOurs !== final) return { kind: "none" };
427
+ const left = deadline - Date.now();
428
+ if (left <= 0) return { kind: "none" };
429
+ try {
430
+ await this.page.waitForLoadState("domcontentloaded", { timeout: left });
431
+ } catch {
432
+ return { kind: "none" };
433
+ }
434
+ return { kind: "loaded", response: await final.response().catch(() => null) };
435
+ }
436
+ dispose() {
437
+ this.page.off("request", this.onRequest);
438
+ this.page.off("framenavigated", this.onNavigated);
439
+ this.page.off("requestfailed", this.onFailed);
440
+ this.page.off("requestfinished", this.onFinished);
441
+ this.wake?.();
442
+ }
443
+ };
337
444
  function jpegSize(jpeg) {
338
445
  let i = 2;
339
446
  while (i + 9 < jpeg.length) {
@@ -443,6 +550,8 @@ var BrowserSession = class {
443
550
  ids = /* @__PURE__ */ new WeakMap();
444
551
  titles = /* @__PURE__ */ new Map();
445
552
  loadingTabs = /* @__PURE__ */ new Set();
553
+ /** Each page's main-frame navigation request in flight (until it commits, fails or finishes). */
554
+ pendingNavs = /* @__PURE__ */ new WeakMap();
446
555
  listeners = /* @__PURE__ */ new Set();
447
556
  collectors = /* @__PURE__ */ new Set();
448
557
  probes = /* @__PURE__ */ new Map();
@@ -531,14 +640,31 @@ var BrowserSession = class {
531
640
  const refresh = () => {
532
641
  page.title().then((t) => this.titles.set(id, t)).catch(() => void 0).finally(() => this.emit({ type: "state" }));
533
642
  };
643
+ const settle = (r) => {
644
+ if (this.pendingNavs.get(page) === r) this.pendingNavs.delete(page);
645
+ };
646
+ page.on("requestfinished", (r) => {
647
+ if (this.pendingNavs.get(page) !== r) return;
648
+ void r.response().then(
649
+ (res) => {
650
+ const status = res?.status() ?? 0;
651
+ const redirects = status >= 300 && status < 400 && res?.headers().location;
652
+ if (!redirects) settle(r);
653
+ },
654
+ () => settle(r)
655
+ );
656
+ });
534
657
  page.on("request", (r) => {
535
658
  if (r.isNavigationRequest() && r.frame() === page.mainFrame()) {
659
+ this.pendingNavs.set(page, r);
536
660
  this.loadingTabs.add(id);
537
661
  this.emit({ type: "state" });
538
662
  }
539
663
  });
540
664
  page.on("framenavigated", (f) => {
541
- if (f === page.mainFrame()) refresh();
665
+ if (f !== page.mainFrame()) return;
666
+ this.pendingNavs.delete(page);
667
+ refresh();
542
668
  });
543
669
  page.on("domcontentloaded", refresh);
544
670
  page.on("load", () => {
@@ -546,6 +672,7 @@ var BrowserSession = class {
546
672
  refresh();
547
673
  });
548
674
  page.on("requestfailed", (r) => {
675
+ settle(r);
549
676
  const err = r.failure()?.errorText ?? "";
550
677
  if (r.isNavigationRequest() && r.frame() === page.mainFrame()) {
551
678
  this.loadingTabs.delete(id);
@@ -566,6 +693,7 @@ var BrowserSession = class {
566
693
  this.emit({ type: "dialog", kind: "file", message: "" });
567
694
  });
568
695
  page.on("close", () => {
696
+ this.pendingNavs.delete(page);
569
697
  this.pages.delete(id);
570
698
  this.titles.delete(id);
571
699
  this.loadingTabs.delete(id);
@@ -939,6 +1067,8 @@ var BrowserSession = class {
939
1067
  let res;
940
1068
  const download = page.waitForEvent("download", { timeout: ACTION_TIMEOUT_MS });
941
1069
  download.catch(() => void 0);
1070
+ const deadline = Date.now() + NAVIGATION_TIMEOUT_MS;
1071
+ const watch = new NavWatch(page, url, () => this.pendingNavs.get(page));
942
1072
  try {
943
1073
  res = await page.goto(url, { waitUntil: "domcontentloaded" });
944
1074
  } catch (e) {
@@ -948,7 +1078,16 @@ var BrowserSession = class {
948
1078
  return;
949
1079
  }
950
1080
  if (PROXY_FAILURE_RE.test(msg)) await this.checkBlocked(url);
951
- throw e;
1081
+ if (!msg.includes("net::ERR_ABORTED")) throw e;
1082
+ const out = await watch.follow(deadline);
1083
+ if (out.kind === "none") throw e;
1084
+ if (out.kind === "failed") {
1085
+ if (PROXY_FAILURE_RE.test(out.error)) await this.checkBlocked(out.url);
1086
+ throw new Error(`${out.error} at ${out.url}`);
1087
+ }
1088
+ res = out.response;
1089
+ } finally {
1090
+ watch.dispose();
952
1091
  }
953
1092
  if (res?.status() === 403 && await this.checkBlocked(res.url())) {
954
1093
  throw new ActionError(
@@ -1232,7 +1371,7 @@ function playwrightDownloadHosts(env) {
1232
1371
  return [];
1233
1372
  }
1234
1373
  }
1235
- return ["cdn.playwright.dev", "playwright.download.prss.microsoft.com"];
1374
+ return ["cdn.playwright.dev", "playwright.download.prss.microsoft.com", "storage.googleapis.com"];
1236
1375
  }
1237
1376
  function browsersPathFor(stateDir, env, revision) {
1238
1377
  const cache = envValue(env, "PLAYWRIGHT_BROWSERS_PATH");