@linxin666/dsh-client-ui-browser-view 0.4.12 → 0.4.14

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.
package/lib/index.js CHANGED
@@ -653,11 +653,14 @@ var TabManager = class {
653
653
  viewport;
654
654
  ringSize;
655
655
  now;
656
+ discoversTargets;
657
+ pinViewports;
656
658
  onFrame;
657
659
  onTabsChanged;
658
660
  tabs = /* @__PURE__ */ new Map();
659
661
  bySession = /* @__PURE__ */ new Map();
660
662
  unsubscribers = [];
663
+ attaching = /* @__PURE__ */ new Map();
661
664
  active = null;
662
665
  disposed = false;
663
666
  /**
@@ -672,6 +675,8 @@ var TabManager = class {
672
675
  };
673
676
  this.ringSize = options.ringSize ?? 500;
674
677
  this.now = options.now ?? Date.now;
678
+ this.discoversTargets = options.discoverTargets ?? false;
679
+ this.pinViewports = options.pinViewport ?? true;
675
680
  this.onFrame = options.onFrame;
676
681
  this.onTabsChanged = options.onTabsChanged;
677
682
  this.subscribe();
@@ -720,19 +725,77 @@ var TabManager = class {
720
725
  async createTab(options = {}) {
721
726
  const targetId = (await this.transport.send("Target.createTarget", { url: "about:blank" })).targetId;
722
727
  if (typeof targetId !== "string" || targetId === "") throw new Error("the browser did not return a target id for the new tab");
728
+ const record = await this.attachTarget({
729
+ targetId,
730
+ type: "page",
731
+ url: "about:blank",
732
+ title: ""
733
+ }, "created");
734
+ record.ownerSessionId = options.sessionId;
735
+ this.active = targetId;
736
+ if (this.pinViewports) await this.pinViewport(record);
737
+ if (options.url !== void 0 && options.url !== "") await this.navigate(targetId, options.url);
738
+ this.onTabsChanged?.();
739
+ return this.view(record);
740
+ }
741
+ /** Discover every existing page and keep following pages created later. */
742
+ async discoverExistingTabs() {
743
+ if (!this.discoversTargets || this.disposed) return;
744
+ await this.transport.send("Target.setDiscoverTargets", { discover: true });
745
+ const result = await this.transport.send("Target.getTargets");
746
+ for (const info of result.targetInfos ?? []) {
747
+ if (info.type !== "page") continue;
748
+ await this.attachTarget(info, "adopted").catch(() => void 0);
749
+ }
750
+ this.onTabsChanged?.();
751
+ }
752
+ /** Adopt one target-created event without racing an explicit create/attach. */
753
+ async adoptTarget(info) {
754
+ if (this.disposed || info.type !== "page") return;
755
+ await this.attachTarget(info, "adopted");
756
+ this.onTabsChanged?.();
757
+ }
758
+ /** Attach a page exactly once, coalescing discovery and Target.createTarget. */
759
+ async attachTarget(info, origin) {
760
+ const targetId = info.targetId;
761
+ if (typeof targetId !== "string" || targetId === "") throw new Error("the browser did not return a target id");
762
+ const existing = this.tabs.get(targetId);
763
+ if (existing !== void 0) {
764
+ if (origin === "created") existing.origin = "created";
765
+ return existing;
766
+ }
767
+ const inFlight = this.attaching.get(targetId);
768
+ if (inFlight !== void 0) {
769
+ const record = await inFlight;
770
+ if (origin === "created") record.origin = "created";
771
+ return record;
772
+ }
773
+ const task = this.attachNewTarget(targetId, info, origin);
774
+ this.attaching.set(targetId, task);
775
+ try {
776
+ return await task;
777
+ } finally {
778
+ this.attaching.delete(targetId);
779
+ }
780
+ }
781
+ /** Build and instrument one previously unseen page record. */
782
+ async attachNewTarget(targetId, info, origin) {
783
+ if (this.disposed) throw new Error("the tab manager is disposed");
723
784
  const sessionId = (await this.transport.send("Target.attachToTarget", {
724
785
  targetId,
725
786
  flatten: true
726
787
  })).sessionId;
727
788
  if (typeof sessionId !== "string" || sessionId === "") throw new Error(`the browser did not return a session for tab ${targetId}`);
789
+ if (this.disposed) throw new Error("the tab manager is disposed");
728
790
  const record = {
729
791
  id: targetId,
730
792
  sessionId,
731
- url: "about:blank",
732
- title: "",
793
+ url: typeof info.url === "string" ? info.url : "about:blank",
794
+ title: typeof info.title === "string" ? info.title : "",
733
795
  loading: false,
734
796
  loaderId: void 0,
735
- ownerSessionId: options.sessionId,
797
+ ownerSessionId: void 0,
798
+ origin,
736
799
  console: [],
737
800
  network: [],
738
801
  pendingRequests: /* @__PURE__ */ new Map(),
@@ -742,12 +805,27 @@ var TabManager = class {
742
805
  };
743
806
  this.tabs.set(targetId, record);
744
807
  this.bySession.set(sessionId, record);
745
- this.active = targetId;
746
- await this.enableDomains(record);
747
- await this.pinViewport(record);
748
- if (options.url !== void 0 && options.url !== "") await this.navigate(targetId, options.url);
808
+ if (this.active === null) this.active = targetId;
809
+ try {
810
+ await this.enableDomains(record);
811
+ await this.refreshDocumentInfo(record);
812
+ return record;
813
+ } catch (error) {
814
+ this.tabs.delete(targetId);
815
+ this.bySession.delete(sessionId);
816
+ if (this.active === targetId) this.active = [...this.tabs.keys()].at(-1) ?? null;
817
+ await this.transport.send("Target.detachFromTarget", { sessionId }).catch(() => void 0);
818
+ throw error;
819
+ }
820
+ }
821
+ /** Forget a target the real browser closed. */
822
+ removeTarget(targetId) {
823
+ const record = this.tabs.get(targetId);
824
+ if (record === void 0) return;
825
+ this.tabs.delete(targetId);
826
+ this.bySession.delete(record.sessionId);
827
+ if (this.active === targetId) this.active = [...this.tabs.keys()].at(-1) ?? null;
749
828
  this.onTabsChanged?.();
750
- return this.view(record);
751
829
  }
752
830
  /**
753
831
  * Pin CSS-pixel viewport metrics so frames, boxes, and clicks share one
@@ -808,7 +886,7 @@ var TabManager = class {
808
886
  async closeTab(tabId) {
809
887
  const record = this.requireRecord(tabId);
810
888
  await this.stopScreencast(tabId).catch(() => void 0);
811
- await this.transport.send("Target.closeTarget", { targetId: record.id }).catch(() => void 0);
889
+ if ((await this.transport.send("Target.closeTarget", { targetId: record.id })).success === false) throw new Error(`the browser refused to close tab "${record.id}"`);
812
890
  this.tabs.delete(record.id);
813
891
  this.bySession.delete(record.sessionId);
814
892
  if (this.active === record.id) this.active = [...this.tabs.keys()].at(-1) ?? null;
@@ -841,17 +919,25 @@ var TabManager = class {
841
919
  await this.transport.send("Page.stopScreencast", {}, record.sessionId);
842
920
  }
843
921
  /**
844
- * Capture one JPEG frame on demand.
922
+ * Capture one screenshot on demand.
923
+ *
924
+ * Without explicit parameters this is exactly the frame the screencast path
925
+ * has always asked for: a JPEG at the configured quality, bounded to the
926
+ * viewport. A caller that wants a clip or a scale plans it with
927
+ * `planScreenshot` and passes those parameters, so this method stays the
928
+ * single send point without deciding any of it.
845
929
  * @param tabId - target tab.
846
- * @returns base64 JPEG without the `data:` prefix.
930
+ * @param params - CDP parameters from `planScreenshot`; omitted keeps the plain JPEG capture.
931
+ * @returns base64 payload without the `data:` prefix.
847
932
  */
848
- async captureScreenshot(tabId) {
933
+ async captureScreenshot(tabId, params) {
849
934
  const record = this.requireRecord(tabId);
850
- const result = await this.transport.send("Page.captureScreenshot", {
935
+ const request = params ?? {
851
936
  format: "jpeg",
852
937
  quality: this.jpegQuality,
853
938
  captureBeyondViewport: false
854
- }, record.sessionId);
939
+ };
940
+ const result = await this.transport.send("Page.captureScreenshot", { ...request }, record.sessionId);
855
941
  if (typeof result.data !== "string" || result.data === "") throw new Error("the browser returned an empty screenshot");
856
942
  return result.data;
857
943
  }
@@ -867,17 +953,47 @@ var TabManager = class {
867
953
  const data = await this.captureScreenshot(tabId);
868
954
  const record = this.requireRecord(tabId);
869
955
  record.frameSeq += 1;
956
+ const viewport = await this.frameViewport(record);
870
957
  const frame = {
871
958
  tabId: record.id,
872
959
  seq: record.frameSeq,
873
- width: this.viewport.width,
874
- height: this.viewport.height,
960
+ width: viewport.width,
961
+ height: viewport.height,
875
962
  data
876
963
  };
877
964
  this.onFrame?.(frame);
878
965
  return frame;
879
966
  }
880
967
  /**
968
+ * Report the CSS viewport a capture of this tab renders.
969
+ *
970
+ * A pinned tab answers from configuration, so this costs no protocol
971
+ * round-trip. A tab this host adopted from a real browser is never pinned —
972
+ * the page keeps whatever size its window has — so the real CSS layout
973
+ * viewport is read from the page instead. Screenshot planning needs exactly
974
+ * this number: clip bounds and the output budget are both expressed in the
975
+ * viewport the pixels are measured against.
976
+ * @param tabId - target tab.
977
+ * @returns the CSS viewport size in pixels.
978
+ */
979
+ async viewportOf(tabId) {
980
+ const record = this.requireRecord(tabId);
981
+ return await this.frameViewport(record);
982
+ }
983
+ /** Read the real CSS viewport without changing it in external-browser mode. */
984
+ async frameViewport(record) {
985
+ if (this.pinViewports) return this.viewport;
986
+ try {
987
+ const metrics = await this.transport.send("Page.getLayoutMetrics", {}, record.sessionId);
988
+ const viewport = metrics.cssLayoutViewport ?? metrics.layoutViewport;
989
+ if (typeof viewport?.clientWidth === "number" && typeof viewport.clientHeight === "number" && viewport.clientWidth > 0 && viewport.clientHeight > 0) return {
990
+ width: Math.round(viewport.clientWidth),
991
+ height: Math.round(viewport.clientHeight)
992
+ };
993
+ } catch {}
994
+ return this.viewport;
995
+ }
996
+ /**
881
997
  * Console entries captured so far, oldest first.
882
998
  * @param tabId - target tab.
883
999
  * @returns a copy; the ring keeps mutating.
@@ -934,7 +1050,8 @@ var TabManager = class {
934
1050
  id: record.id,
935
1051
  url: record.url,
936
1052
  title: record.title,
937
- loading: record.loading
1053
+ loading: record.loading,
1054
+ origin: record.origin
938
1055
  };
939
1056
  if (record.ownerSessionId !== void 0) view.sessionId = record.ownerSessionId;
940
1057
  return view;
@@ -978,6 +1095,28 @@ var TabManager = class {
978
1095
  const bySession = (sessionId) => {
979
1096
  return sessionId === void 0 ? void 0 : this.bySession.get(sessionId);
980
1097
  };
1098
+ if (this.discoversTargets) {
1099
+ this.unsubscribers.push(this.transport.on("Target.targetCreated", (params) => {
1100
+ const info = params.targetInfo;
1101
+ if (info !== void 0) this.adoptTarget(info).catch(() => void 0);
1102
+ }));
1103
+ this.unsubscribers.push(this.transport.on("Target.targetInfoChanged", (params) => {
1104
+ const info = params.targetInfo;
1105
+ if (info === void 0 || typeof info.targetId !== "string") return;
1106
+ const record = this.tabs.get(info.targetId);
1107
+ if (record === void 0) {
1108
+ this.adoptTarget(info).catch(() => void 0);
1109
+ return;
1110
+ }
1111
+ if (typeof info.url === "string") record.url = info.url;
1112
+ if (typeof info.title === "string") record.title = info.title;
1113
+ this.onTabsChanged?.();
1114
+ }));
1115
+ this.unsubscribers.push(this.transport.on("Target.targetDestroyed", (params) => {
1116
+ const targetId = params.targetId;
1117
+ if (typeof targetId === "string") this.removeTarget(targetId);
1118
+ }));
1119
+ }
981
1120
  this.unsubscribers.push(this.transport.on("Page.frameNavigated", (params, sessionId) => {
982
1121
  const frame = params.frame;
983
1122
  if (frame === void 0) return;
@@ -1270,6 +1409,136 @@ async function buildSnapshot(transport, tabId, sessionId, options = {}) {
1270
1409
  return assembled;
1271
1410
  }
1272
1411
  //#endregion
1412
+ //#region src/core/screenshot.ts
1413
+ /** Matches the attachment service's `normalizedImageMaxPixels`: 2048*2048. */
1414
+ const SCREENSHOT_MAX_OUTPUT_PIXELS = 2048 * 2048;
1415
+ /** Longest encoded side CDP renders in one capture. */
1416
+ const SCREENSHOT_MAX_SIDE = 8192;
1417
+ /** Scale a clip-only request renders at: a crop is a detail view. */
1418
+ const DEFAULT_CLIP_SCALE = 2;
1419
+ /**
1420
+ * Describe one requested rectangle for an error message.
1421
+ * @param clip - the rectangle as the caller asked for it.
1422
+ * @returns a compact `width x height at x,y` reading.
1423
+ */
1424
+ function describeClip(clip) {
1425
+ return `${clip.width}x${clip.height} at (${clip.x}, ${clip.y})`;
1426
+ }
1427
+ /**
1428
+ * Reject a format outside png/jpeg.
1429
+ *
1430
+ * The tool schema already constrains this; a second guard here is what keeps a
1431
+ * caller that reaches the core directly from asking CDP for an unknown encoder
1432
+ * and receiving an opaque protocol error.
1433
+ * @param format - the requested format.
1434
+ * @throws when the format is neither `png` nor `jpeg`.
1435
+ */
1436
+ function assertFormat(format) {
1437
+ if (format !== "png" && format !== "jpeg") throw new Error(`screenshot format must be "png" or "jpeg"; received ${String(format)}`);
1438
+ }
1439
+ /**
1440
+ * Reject a scale outside the allowed range.
1441
+ * @param scale - the requested scale.
1442
+ * @throws when the scale is not a whole number from 1 to {@link SCREENSHOT_MAX_SCALE}.
1443
+ */
1444
+ function assertScale(scale) {
1445
+ if (!Number.isInteger(scale) || scale < 1 || scale > 3) throw new Error(`screenshot scale must be an integer from 1 to 3; received ${scale}`);
1446
+ }
1447
+ /**
1448
+ * Reject a clip CDP could not honour.
1449
+ *
1450
+ * Fractional edges make the encoded size disagree with the reported size, a
1451
+ * zero or negative extent has no pixels, and a negative origin addresses
1452
+ * something outside the page.
1453
+ * @param clip - the requested rectangle.
1454
+ * @throws when any edge is fractional, the origin is negative, or an extent is below one pixel.
1455
+ */
1456
+ function assertClip(clip) {
1457
+ if (![
1458
+ clip.x,
1459
+ clip.y,
1460
+ clip.width,
1461
+ clip.height
1462
+ ].every((edge) => Number.isInteger(edge))) throw new Error(`screenshot clip must use whole pixels; received ${describeClip(clip)}`);
1463
+ if (clip.x < 0 || clip.y < 0) throw new Error(`screenshot clip must not start outside the viewport; received ${describeClip(clip)}`);
1464
+ if (clip.width < 1 || clip.height < 1) throw new Error(`screenshot clip must be at least 1x1 pixel; received ${describeClip(clip)}`);
1465
+ }
1466
+ /**
1467
+ * Reject a clip that reaches past the viewport.
1468
+ *
1469
+ * Reporting the real viewport is what lets the caller correct the rectangle
1470
+ * without a second round-trip to find out how large the page actually is.
1471
+ * @param clip - the requested rectangle.
1472
+ * @param viewport - the viewport the capture renders.
1473
+ * @throws when the clip crosses the right or bottom edge.
1474
+ */
1475
+ function assertInside(clip, viewport) {
1476
+ if (clip.x + clip.width > viewport.width || clip.y + clip.height > viewport.height) throw new Error(`screenshot clip must stay inside the ${viewport.width}x${viewport.height} viewport; received ${describeClip(clip)}`);
1477
+ }
1478
+ /**
1479
+ * Reject a capture whose encoded size would be unusable.
1480
+ * @param width - base width in CSS pixels, before scaling.
1481
+ * @param height - base height in CSS pixels, before scaling.
1482
+ * @param scale - scale the capture renders at.
1483
+ * @throws when a side exceeds {@link SCREENSHOT_MAX_SIDE} or the total exceeds {@link SCREENSHOT_MAX_OUTPUT_PIXELS}.
1484
+ */
1485
+ function assertOutputSize(width, height, scale) {
1486
+ const encodedWidth = width * scale;
1487
+ const encodedHeight = height * scale;
1488
+ if (encodedWidth > SCREENSHOT_MAX_SIDE || encodedHeight > SCREENSHOT_MAX_SIDE) throw new Error(`a ${width}x${height} screenshot at scale ${scale} would be ${encodedWidth}x${encodedHeight} pixels, over the ${SCREENSHOT_MAX_SIDE}-pixel side limit; lower the scale or shrink the clip`);
1489
+ const pixels = encodedWidth * encodedHeight;
1490
+ if (pixels > 4194304) throw new Error(`a ${width}x${height} screenshot at scale ${scale} would be ${pixels} pixels, over the ${SCREENSHOT_MAX_OUTPUT_PIXELS}-pixel output limit; lower the scale or shrink the clip`);
1491
+ }
1492
+ /**
1493
+ * Plan one screenshot capture.
1494
+ *
1495
+ * Pure: the same three arguments always produce the same plan, and nothing here
1496
+ * reads configuration, the clock, or the environment.
1497
+ * @param viewport - the CSS-pixel viewport the page is pinned to.
1498
+ * @param request - what the caller asked for; every field is optional.
1499
+ * @param jpegQuality - quality to request for a JPEG capture, 0-100.
1500
+ * @returns the CDP parameters, the media type, and the encoded pixel size.
1501
+ * @throws when the format, scale, clip, or resulting size cannot be honoured.
1502
+ */
1503
+ function planScreenshot(viewport, request, jpegQuality) {
1504
+ const format = request.format ?? "png";
1505
+ assertFormat(format);
1506
+ const clip = request.clip;
1507
+ if (clip !== void 0) assertClip(clip);
1508
+ if (request.scale !== void 0) assertScale(request.scale);
1509
+ const scale = request.scale ?? (clip === void 0 ? 1 : DEFAULT_CLIP_SCALE);
1510
+ const width = clip === void 0 ? viewport.width : clip.width;
1511
+ const height = clip === void 0 ? viewport.height : clip.height;
1512
+ if (clip !== void 0) assertInside(clip, viewport);
1513
+ assertOutputSize(width, height, scale);
1514
+ const params = {
1515
+ format,
1516
+ captureBeyondViewport: false
1517
+ };
1518
+ if (format === "jpeg") params.quality = jpegQuality;
1519
+ if (clip !== void 0) params.clip = {
1520
+ x: clip.x,
1521
+ y: clip.y,
1522
+ width: clip.width,
1523
+ height: clip.height,
1524
+ scale
1525
+ };
1526
+ else if (scale > 1) params.clip = {
1527
+ x: 0,
1528
+ y: 0,
1529
+ width: viewport.width,
1530
+ height: viewport.height,
1531
+ scale
1532
+ };
1533
+ return {
1534
+ params,
1535
+ mediaType: format === "jpeg" ? "image/jpeg" : "image/png",
1536
+ width: width * scale,
1537
+ height: height * scale,
1538
+ scale
1539
+ };
1540
+ }
1541
+ //#endregion
1273
1542
  //#region src/host/loopback.ts
1274
1543
  /** IPv4 127/8 predicate (four decimal octets, first == 127). */
1275
1544
  function isIPv4Loopback(v4) {
@@ -1387,6 +1656,74 @@ function isLoopbackTarget(url) {
1387
1656
  return isLoopbackHostname(parsed.hostname);
1388
1657
  }
1389
1658
  //#endregion
1659
+ //#region src/host/cdp-endpoint.ts
1660
+ /**
1661
+ * Loopback-only discovery of an external Chrome DevTools endpoint.
1662
+ * @module @linxin666/dsh-client-ui-browser-view/host/cdp-endpoint
1663
+ */
1664
+ function assertLoopbackUrl(url, protocols, label) {
1665
+ if (!protocols.includes(url.protocol)) throw new Error(`${label} must use ${protocols.join(" or ")}`);
1666
+ if (!isLoopbackHostname(url.hostname)) throw new Error(`${label} must name a loopback host (localhost, 127/8, or [::1])`);
1667
+ if (url.username !== "" || url.password !== "") throw new Error(`${label} must not contain credentials`);
1668
+ }
1669
+ /** Parse and normalize the configured HTTP endpoint, failing closed. */
1670
+ function parseCdpEndpoint(raw) {
1671
+ let url;
1672
+ try {
1673
+ url = new URL(raw);
1674
+ } catch {
1675
+ throw new Error("cdpEndpoint must be an absolute HTTP URL such as http://127.0.0.1:9222");
1676
+ }
1677
+ assertLoopbackUrl(url, ["http:"], "cdpEndpoint");
1678
+ if (url.port === "") throw new Error("cdpEndpoint must include an explicit port");
1679
+ if (url.pathname !== "" && url.pathname !== "/" || url.search !== "" || url.hash !== "") throw new Error("cdpEndpoint must be an origin without a path, query, or fragment");
1680
+ return {
1681
+ baseUrl: url.origin,
1682
+ versionUrl: new URL("/json/version", url.origin).toString()
1683
+ };
1684
+ }
1685
+ /** Validate the WebSocket published by the local discovery document. */
1686
+ function parseCdpWebSocketUrl(raw) {
1687
+ let url;
1688
+ try {
1689
+ url = new URL(raw);
1690
+ } catch {
1691
+ throw new Error("the CDP discovery document returned an invalid webSocketDebuggerUrl");
1692
+ }
1693
+ assertLoopbackUrl(url, ["ws:", "wss:"], "webSocketDebuggerUrl");
1694
+ if (url.port === "") throw new Error("webSocketDebuggerUrl must include an explicit port");
1695
+ return url.toString();
1696
+ }
1697
+ /** Fetch and validate the external browser's discovery document. */
1698
+ async function fetchCdpVersion(endpoint, options = {}) {
1699
+ const fetchImpl = options.fetchImpl ?? fetch;
1700
+ const controller = new AbortController();
1701
+ const timer = setTimeout(() => {
1702
+ controller.abort();
1703
+ }, options.timeoutMs ?? 5e3);
1704
+ try {
1705
+ const response = await fetchImpl(endpoint.versionUrl, {
1706
+ signal: controller.signal,
1707
+ redirect: "error"
1708
+ });
1709
+ if (!response.ok) throw new Error(`discovery returned HTTP ${response.status}`);
1710
+ const value = await response.json();
1711
+ if (typeof value.webSocketDebuggerUrl !== "string" || value.webSocketDebuggerUrl === "") throw new Error("discovery did not return webSocketDebuggerUrl");
1712
+ const browser = value.Browser ?? value.browser;
1713
+ return {
1714
+ webSocketDebuggerUrl: parseCdpWebSocketUrl(value.webSocketDebuggerUrl),
1715
+ ...typeof browser === "string" && browser !== "" ? { browser } : {}
1716
+ };
1717
+ } finally {
1718
+ clearTimeout(timer);
1719
+ }
1720
+ }
1721
+ /** Add the real-browser startup constraints to any external connection error. */
1722
+ function realBrowserConnectionError(endpoint, error) {
1723
+ const reason = error instanceof Error ? error.message : String(error);
1724
+ return /* @__PURE__ */ new Error(`Could not connect to the real browser at ${endpoint.baseUrl}: ${reason}. Start Chrome/Edge with --remote-debugging-port and a non-default --user-data-dir. Chrome 136+ ignores remote debugging switches on its default data directory. No isolated-browser fallback was attempted.`);
1725
+ }
1726
+ //#endregion
1390
1727
  //#region src/core/actions.ts
1391
1728
  /** Dispatch one expression in the page and return its plain-JSON value. */
1392
1729
  async function evaluateJson(transport, sessionId, expression) {
@@ -1730,8 +2067,8 @@ async function scrollBy(scope, tabId, delta) {
1730
2067
  *
1731
2068
  * @module @linxin666/dsh-client-ui-browser-view/host/service
1732
2069
  */
1733
- /** Start Chrome, connect CDP, and wrap both in a session. */
1734
- async function openDefaultSession(options) {
2070
+ /** Start the default isolated Chrome and wrap it in a session. */
2071
+ async function openIsolatedSession(options) {
1735
2072
  const chrome = await ChromeProcess.launch({ viewport: options.viewport });
1736
2073
  let cdp;
1737
2074
  try {
@@ -1748,6 +2085,7 @@ async function openDefaultSession(options) {
1748
2085
  onTabsChanged: options.onTabsChanged
1749
2086
  });
1750
2087
  return {
2088
+ mode: "isolated",
1751
2089
  transport: cdp,
1752
2090
  tabs,
1753
2091
  chrome,
@@ -1758,6 +2096,44 @@ async function openDefaultSession(options) {
1758
2096
  }
1759
2097
  };
1760
2098
  }
2099
+ /** Connect to an existing real browser without owning its process or tabs. */
2100
+ async function openExternalSession(options) {
2101
+ const endpoint = parseCdpEndpoint(options.cdpEndpoint ?? "");
2102
+ let cdp;
2103
+ let tabs;
2104
+ try {
2105
+ const version = await fetchCdpVersion(endpoint);
2106
+ cdp = await CdpClient.connect(version.webSocketDebuggerUrl, { timeoutMs: 5e3 });
2107
+ tabs = new TabManager({
2108
+ transport: cdp,
2109
+ jpegQuality: options.jpegQuality,
2110
+ viewport: options.viewport,
2111
+ pinViewport: false,
2112
+ discoverTargets: true,
2113
+ onFrame: options.onFrame,
2114
+ onTabsChanged: options.onTabsChanged
2115
+ });
2116
+ await tabs.discoverExistingTabs();
2117
+ const attachedTabs = tabs;
2118
+ return {
2119
+ mode: "cdp",
2120
+ transport: cdp,
2121
+ tabs: attachedTabs,
2122
+ async dispose() {
2123
+ await attachedTabs.dispose();
2124
+ cdp?.close();
2125
+ }
2126
+ };
2127
+ } catch (error) {
2128
+ if (tabs !== void 0) await tabs.dispose().catch(() => void 0);
2129
+ cdp?.close();
2130
+ throw realBrowserConnectionError(endpoint, error);
2131
+ }
2132
+ }
2133
+ /** Resolve a factory that honors the selected mode without fallback. */
2134
+ function openConfiguredSession(options) {
2135
+ return options.mode === "cdp" ? openExternalSession(options) : openIsolatedSession(options);
2136
+ }
1761
2137
  /**
1762
2138
  * The plugin's single browser service.
1763
2139
  */
@@ -1766,6 +2142,7 @@ var BrowserViewService = class {
1766
2142
  viewport;
1767
2143
  now;
1768
2144
  openSession;
2145
+ resolveConfig;
1769
2146
  authenticatedUrl;
1770
2147
  sinks = /* @__PURE__ */ new Set();
1771
2148
  bindings = /* @__PURE__ */ new Map();
@@ -1792,6 +2169,7 @@ var BrowserViewService = class {
1792
2169
  opening;
1793
2170
  openingTab;
1794
2171
  lastError;
2172
+ generation = 0;
1795
2173
  disposed = false;
1796
2174
  /**
1797
2175
  * @param options - quality, viewport, clock, and the browser factory seam.
@@ -1803,7 +2181,8 @@ var BrowserViewService = class {
1803
2181
  height: DEFAULT_VIEWPORT.height
1804
2182
  };
1805
2183
  this.now = options.now ?? Date.now;
1806
- this.openSession = options.openSession ?? openDefaultSession;
2184
+ this.openSession = options.openSession ?? openConfiguredSession;
2185
+ this.resolveConfig = options.resolveConfig ?? (() => ({ mode: "isolated" }));
1807
2186
  this.authenticatedUrl = options.authenticatedUrl;
1808
2187
  }
1809
2188
  /** Whether a browser is currently running. */
@@ -1812,11 +2191,18 @@ var BrowserViewService = class {
1812
2191
  }
1813
2192
  /** The current panel-facing state; safe to call before anything started. */
1814
2193
  state() {
2194
+ const config = this.resolveConfig();
1815
2195
  const state = {
1816
2196
  tabs: this.session?.tabs.list() ?? [],
1817
2197
  activeTabId: this.session === void 0 ? null : this.displayedOrDefault(),
1818
- running: this.session !== void 0
2198
+ running: this.session !== void 0,
2199
+ mode: config.mode
1819
2200
  };
2201
+ if (config.mode === "cdp" && config.cdpEndpoint !== void 0) try {
2202
+ state.cdpEndpoint = parseCdpEndpoint(config.cdpEndpoint).baseUrl;
2203
+ } catch {
2204
+ state.cdpEndpoint = config.cdpEndpoint;
2205
+ }
1820
2206
  if (this.lastError !== void 0) state.message = this.lastError;
1821
2207
  return state;
1822
2208
  }
@@ -1832,7 +2218,7 @@ var BrowserViewService = class {
1832
2218
  kind: "hello",
1833
2219
  state: this.state()
1834
2220
  });
1835
- this.startStreaming();
2221
+ this.startStreaming().catch(() => void 0);
1836
2222
  return () => {
1837
2223
  this.sinks.delete(sink);
1838
2224
  if (this.sinks.size === 0) this.stopStreaming();
@@ -1871,6 +2257,7 @@ var BrowserViewService = class {
1871
2257
  return;
1872
2258
  }
1873
2259
  case "close-tab":
2260
+ if ((await this.requireTabs()).tab(command.tabId).origin === "adopted") throw new Error("an adopted real-browser tab can only be closed in the browser or by browser_close with an explicit tab_id");
1874
2261
  await this.closeTab(command.tabId);
1875
2262
  return;
1876
2263
  default:
@@ -1921,12 +2308,17 @@ var BrowserViewService = class {
1921
2308
  */
1922
2309
  async closeOwnTabs(sessionId, tabId) {
1923
2310
  if (sessionId === void 0) throw new Error("browser_close needs the calling session: with no session there is no tab this call may close");
1924
- if (this.session === void 0) return [];
1925
- const tabs = this.session.tabs;
2311
+ if (this.session === void 0) {
2312
+ if (tabId === void 0 || tabId === "" || this.resolveConfig().mode !== "cdp") return [];
2313
+ await this.requireSession();
2314
+ }
2315
+ const session = this.session;
2316
+ if (session === void 0) return [];
2317
+ const tabs = session.tabs;
1926
2318
  if (tabId !== void 0 && tabId !== "") {
1927
2319
  const found = tabs.list().find((tab) => tab.id === tabId);
1928
2320
  if (found === void 0) throw new Error(`unknown tab "${tabId}"; call browser_tabs to see the open tabs`);
1929
- if (found.sessionId !== sessionId) throw new Error(`tab "${tabId}" was not opened by this session, so it is not this session's to close`);
2321
+ if (session.mode !== "cdp" && found.sessionId !== sessionId) throw new Error(`tab "${tabId}" was not opened by this session, so it is not this session's to close`);
1930
2322
  await this.closeTab(found.id);
1931
2323
  return [found.id];
1932
2324
  }
@@ -2197,21 +2589,36 @@ var BrowserViewService = class {
2197
2589
  return result.snapshot;
2198
2590
  }
2199
2591
  /**
2200
- * Capture one JPEG of the tab.
2592
+ * Capture one image of the tab.
2593
+ *
2594
+ * The plan decides everything the caller is told about the bytes: the format
2595
+ * becomes the media type the attachment service stores, and the scale turns
2596
+ * one capture into a cropped render whose encoded size has to be reported
2597
+ * rather than guessed from the viewport. Planning before the capture is what
2598
+ * makes an impossible request fail here, with the numbers, instead of
2599
+ * producing a truncated or silently downscaled image. The viewport it plans
2600
+ * against is the tab's own: a pinned tab answers from configuration, and an
2601
+ * adopted real-browser tab reports the page's real layout viewport.
2201
2602
  * @param sessionId - calling agent session.
2202
2603
  * @param tabId - explicit tab.
2203
- * @returns the tab and the base64 JPEG.
2604
+ * @param request - format, clip, and scale; every field is optional.
2605
+ * @returns the tab, the base64 payload, and the media type and encoded size the plan produced.
2606
+ * @throws when the request cannot be honoured by this viewport or the size limits.
2204
2607
  */
2205
- async screenshot(sessionId, tabId) {
2608
+ async screenshot(sessionId, tabId, request = {}) {
2206
2609
  const tab = await this.tabFor(sessionId, tabId);
2207
2610
  const tabs = await this.requireTabs();
2208
- const data = await tabs.captureScreenshot(tab.id);
2611
+ const plan = planScreenshot(await tabs.viewportOf(tab.id), request, this.jpegQuality);
2612
+ const data = await tabs.captureScreenshot(tab.id, plan.params);
2209
2613
  const current = tabs.list().find((candidate) => candidate.id === tab.id) ?? tab;
2210
2614
  return {
2211
2615
  tabId: current.id,
2212
2616
  url: current.url,
2213
2617
  title: current.title,
2214
- data
2618
+ data,
2619
+ mediaType: plan.mediaType,
2620
+ width: plan.width,
2621
+ height: plan.height
2215
2622
  };
2216
2623
  }
2217
2624
  /**
@@ -2246,12 +2653,20 @@ var BrowserViewService = class {
2246
2653
  }
2247
2654
  /** Open tabs, for `browser_tabs`. */
2248
2655
  async listTabs() {
2249
- if (this.session === void 0) return {
2656
+ if (this.session === void 0) {
2657
+ if (this.resolveConfig().mode !== "cdp") return {
2658
+ tabs: [],
2659
+ activeTabId: null
2660
+ };
2661
+ await this.requireSession();
2662
+ }
2663
+ const session = this.session;
2664
+ if (session === void 0) return {
2250
2665
  tabs: [],
2251
2666
  activeTabId: null
2252
2667
  };
2253
2668
  return {
2254
- tabs: this.session.tabs.list(),
2669
+ tabs: session.tabs.list(),
2255
2670
  activeTabId: this.displayedOrDefault()
2256
2671
  };
2257
2672
  }
@@ -2263,6 +2678,26 @@ var BrowserViewService = class {
2263
2678
  this.sinks.delete(sink);
2264
2679
  }
2265
2680
  }
2681
+ /** Apply a settings edit: detach the old source and restart an attached panel's stream. */
2682
+ async reconfigure() {
2683
+ if (this.disposed) return;
2684
+ this.generation += 1;
2685
+ const session = this.session;
2686
+ this.session = void 0;
2687
+ this.opening = void 0;
2688
+ this.bindings.clear();
2689
+ this.authTopUpSpent.clear();
2690
+ this.displayedTabId = null;
2691
+ this.selectionPinned = false;
2692
+ this.lastError = void 0;
2693
+ if (session !== void 0) await session.dispose();
2694
+ this.broadcast({
2695
+ v: 1,
2696
+ kind: "state",
2697
+ state: this.state()
2698
+ });
2699
+ if (this.sinks.size > 0) await this.startStreaming().catch(() => void 0);
2700
+ }
2266
2701
  /**
2267
2702
  * Tear everything down: stop pushing, stop streaming, close the socket, kill
2268
2703
  * the browser.
@@ -2271,6 +2706,8 @@ var BrowserViewService = class {
2271
2706
  async dispose() {
2272
2707
  if (this.disposed) return;
2273
2708
  this.disposed = true;
2709
+ this.generation += 1;
2710
+ this.opening = void 0;
2274
2711
  const sinks = [...this.sinks];
2275
2712
  this.sinks.clear();
2276
2713
  for (const sink of sinks) try {
@@ -2304,15 +2741,21 @@ var BrowserViewService = class {
2304
2741
  async requireSession() {
2305
2742
  if (this.disposed) throw new Error("the browser view service is disposed");
2306
2743
  if (this.session !== void 0) return this.session;
2307
- this.opening ??= this.startSession().finally(() => {
2308
- this.opening = void 0;
2309
- });
2310
- return await this.opening;
2744
+ if (this.opening === void 0) this.opening = this.startSession();
2745
+ const opening = this.opening;
2746
+ try {
2747
+ return await opening;
2748
+ } finally {
2749
+ if (this.opening === opening) this.opening = void 0;
2750
+ }
2311
2751
  }
2312
2752
  /** Start the browser once, recording failures for the panel. */
2313
2753
  async startSession() {
2754
+ const generation = this.generation;
2755
+ const config = this.resolveConfig();
2314
2756
  try {
2315
2757
  const session = await this.openSession({
2758
+ ...config,
2316
2759
  jpegQuality: this.jpegQuality,
2317
2760
  viewport: this.viewport,
2318
2761
  onFrame: (frame) => {
@@ -2330,6 +2773,10 @@ var BrowserViewService = class {
2330
2773
  });
2331
2774
  }
2332
2775
  });
2776
+ if (generation !== this.generation || this.disposed) {
2777
+ await session.dispose();
2778
+ throw new Error("the browser configuration changed while the session was opening");
2779
+ }
2333
2780
  this.session = session;
2334
2781
  this.lastError = void 0;
2335
2782
  this.broadcast({
@@ -2339,19 +2786,21 @@ var BrowserViewService = class {
2339
2786
  });
2340
2787
  return session;
2341
2788
  } catch (error) {
2342
- this.lastError = error instanceof Error ? error.message : String(error);
2343
- this.broadcast({
2344
- v: 1,
2345
- kind: "error",
2346
- code: "browser-launch-failed",
2347
- message: this.lastError
2348
- });
2789
+ if (generation === this.generation && !this.disposed) {
2790
+ this.lastError = error instanceof Error ? error.message : String(error);
2791
+ this.broadcast({
2792
+ v: 1,
2793
+ kind: "error",
2794
+ code: config.mode === "cdp" ? "browser-connect-failed" : "browser-launch-failed",
2795
+ message: this.lastError
2796
+ });
2797
+ }
2349
2798
  throw error;
2350
2799
  }
2351
2800
  }
2352
2801
  /** Start the screencast for the tab the panel watches. */
2353
2802
  async startStreaming() {
2354
- const session = this.session;
2803
+ const session = this.session ?? (this.resolveConfig().mode === "cdp" && this.sinks.size > 0 ? await this.requireSession() : void 0);
2355
2804
  if (session === void 0 || this.sinks.size === 0) return;
2356
2805
  const tabId = this.displayedOrDefault();
2357
2806
  if (tabId === null) return;
@@ -9865,8 +10314,8 @@ function toolAbortedBeforeDispatchResult(prior) {
9865
10314
  * JSON, rendered as one pretty-printed text block: the model reads fields, not
9866
10315
  * prose, and the GUI can present the same value later. `browser_screenshot`
9867
10316
  * returns a real image part — an `ImageBlock` carrying a durable attachment
9868
- * reference — because a JPEG smuggled in as base64 text is not an image to any
9869
- * model that can see one.
10317
+ * reference — because a screenshot smuggled in as base64 text is not an image to
10318
+ * any model that can see one.
9870
10319
  *
9871
10320
  * The screenshot path therefore needs the host's attachment service: the bytes
9872
10321
  * are committed through it, and the block only carries the reference. The
@@ -9880,6 +10329,10 @@ function toolAbortedBeforeDispatchResult(prior) {
9880
10329
  *
9881
10330
  * @module @linxin666/dsh-client-ui-browser-view/host/tools
9882
10331
  */
10332
+ /** File extension matching one screenshot media type. */
10333
+ function extensionOf(mediaType) {
10334
+ return mediaType === "image/png" ? "png" : "jpg";
10335
+ }
9883
10336
  /** One text block. */
9884
10337
  function text(value) {
9885
10338
  return [{
@@ -10003,7 +10456,11 @@ const TAB_VIEW_SCHEMA = {
10003
10456
  type: "boolean",
10004
10457
  required: true
10005
10458
  },
10006
- sessionId: { type: "string" }
10459
+ sessionId: { type: "string" },
10460
+ origin: {
10461
+ type: "string",
10462
+ description: "created when DSH opened the target; adopted when it already existed in the real browser."
10463
+ }
10007
10464
  }
10008
10465
  };
10009
10466
  /**
@@ -10016,7 +10473,7 @@ function createBrowserTools(deps) {
10016
10473
  return [
10017
10474
  defineTool({
10018
10475
  name: "browser_navigate",
10019
- description: "Navigate the plugin's own browser tab to a URL and report the resulting page (url, title). This browser is a real Chromium the host launched, so the page renders, runs scripts, and makes network requests exactly as it would for a user. Use it to inspect a local page or site, to verify rendered markup, or to set up a page before a snapshot, click, or screenshot. After navigating, call browser_snapshot before clicking anything: refs from before the navigation no longer exist. Without new_tab the call reuses this session's current tab, so the console and network buffers start over with the new document. Set new_tab to true to keep the current page and open the URL in an additional tab (browser_tabs then lists both). 中文触发词:打开网页、浏览器里看一下、访问这个地址、渲染页面、新标签页。",
10476
+ description: "Navigate the selected browser tab to a URL and report the resulting page (url, title). This is a real Chromium either launched by the host or attached over CDP, so the page renders, runs scripts, and makes network requests exactly as it would for a user. Use it to inspect a local page or site, to verify rendered markup, or to set up a page before a snapshot, click, or screenshot. After navigating, call browser_snapshot before clicking anything: refs from before the navigation no longer exist. Without new_tab the call reuses this session's current tab, so the console and network buffers start over with the new document. Set new_tab to true to keep the current page and open the URL in an additional tab (browser_tabs then lists both). 中文触发词:打开网页、浏览器里看一下、访问这个地址、渲染页面、新标签页。",
10020
10477
  parameters: {
10021
10478
  url: {
10022
10479
  type: "string",
@@ -10255,8 +10712,51 @@ function createBrowserTools(deps) {
10255
10712
  }),
10256
10713
  defineTool({
10257
10714
  name: "browser_screenshot",
10258
- description: "Capture the current tab as a JPEG and return the image itself, not a description of it. Use it when the user should see the page, when layout or styling matters more than the DOM, or to check that something rendered correctly. The image is the whole visible viewport; scroll first if the region you need is off-screen. 中文触发词:截图、看一下现在的页面、画面。",
10259
- parameters: { tab_id: TAB_ID_PARAM },
10715
+ description: "Capture the current tab as an image and return the image itself, not a description of it. Use it when the user should see the page, when layout or styling matters more than the DOM, or to check that something rendered correctly. The default is a lossless PNG of the whole visible viewport; scroll first if the region you need is off-screen. The full viewport is coarse to read: one visual token cell on the model side covers roughly 42x42 px of the image. To read detail, call browser_snapshot first, take the box of the node you care about, and capture just that region with clip (rendered at 2x unless scale says otherwise). 中文触发词:截图、看一下现在的页面、画面、放大看细节。",
10716
+ parameters: {
10717
+ clip: {
10718
+ type: "object",
10719
+ additionalProperties: false,
10720
+ description: "Region to capture, in CSS pixels inside the fixed viewport: the same coordinate space as a browser_snapshot box and the x/y of browser_click. Omit to capture the whole visible viewport.",
10721
+ properties: {
10722
+ x: {
10723
+ type: "number",
10724
+ required: true,
10725
+ description: "Left edge in CSS pixels."
10726
+ },
10727
+ y: {
10728
+ type: "number",
10729
+ required: true,
10730
+ description: "Top edge in CSS pixels."
10731
+ },
10732
+ width: {
10733
+ type: "number",
10734
+ required: true,
10735
+ description: "Region width in CSS pixels."
10736
+ },
10737
+ height: {
10738
+ type: "number",
10739
+ required: true,
10740
+ description: "Region height in CSS pixels."
10741
+ }
10742
+ }
10743
+ },
10744
+ scale: {
10745
+ type: "integer",
10746
+ enum: [
10747
+ 1,
10748
+ 2,
10749
+ 3
10750
+ ],
10751
+ description: "Render multiplier. Defaults to 2 when clip is given and 1 otherwise."
10752
+ },
10753
+ format: {
10754
+ type: "string",
10755
+ enum: ["png", "jpeg"],
10756
+ description: "Encoded image format; 'png' is lossless and the default."
10757
+ },
10758
+ tab_id: TAB_ID_PARAM
10759
+ },
10260
10760
  output: {
10261
10761
  schema: {
10262
10762
  type: "object",
@@ -10302,7 +10802,7 @@ function createBrowserTools(deps) {
10302
10802
  }
10303
10803
  },
10304
10804
  render: (_args, value) => {
10305
- const envelope = `<path>browser-view:screenshot/${value.tabId}.jpg</path>
10805
+ const envelope = `<path>browser-view:screenshot/${value.tabId}.${extensionOf(value.image.mediaType)}</path>
10306
10806
  <type>image</type>
10307
10807
  <content>
10308
10808
  ${value.image.mediaType} screenshot, ${value.image.width}x${value.image.height} px, ${value.image.bytes} bytes
@@ -10319,11 +10819,15 @@ title: ${value.title}
10319
10819
  execute: async (args, exec) => {
10320
10820
  const saveImage = deps.saveImage;
10321
10821
  if (saveImage === void 0) throw new Error("browser_screenshot needs the host attachment service to store the image; this host mounts none");
10322
- const shot = await service.screenshot(sessionIdOf(exec), args.tab_id);
10822
+ const request = {};
10823
+ if (args.format !== void 0) request.format = args.format;
10824
+ if (args.clip !== void 0) request.clip = args.clip;
10825
+ if (args.scale !== void 0) request.scale = args.scale;
10826
+ const shot = await service.screenshot(sessionIdOf(exec), args.tab_id, request);
10323
10827
  const ref = await saveImage({
10324
10828
  data: Buffer.from(shot.data, "base64"),
10325
- mediaType: "image/jpeg",
10326
- name: `browser-view-${shot.tabId}.jpg`
10829
+ mediaType: shot.mediaType,
10830
+ name: `browser-view-${shot.tabId}.${extensionOf(shot.mediaType)}`
10327
10831
  });
10328
10832
  return {
10329
10833
  tabId: shot.tabId,
@@ -10448,7 +10952,7 @@ title: ${value.title}
10448
10952
  }),
10449
10953
  defineTool({
10450
10954
  name: "browser_tabs",
10451
- description: "List the browser tabs this plugin currently has open, with their ids, urls, titles, and loading state. Call it when you need a tab id, when you are unsure whether a browser is running at all, or after the user closed a tab in the panel. It never starts a browser: an empty list means nothing has been opened yet, so navigate first. 中文触发词:有多少标签页、当前浏览器状态、打开着哪些页面。",
10955
+ description: "List the browser tabs this plugin currently has open, with their ids, urls, titles, and loading state. Call it when you need a tab id, when you are unsure whether a browser is running at all, or after the user closed a tab in the panel. In isolated mode it never starts a browser; in real-browser mode it connects to the configured CDP endpoint and discovers existing page tabs. 中文触发词:有多少标签页、当前浏览器状态、打开着哪些页面。",
10452
10956
  parameters: {},
10453
10957
  output: {
10454
10958
  schema: {
@@ -10479,7 +10983,7 @@ title: ${value.title}
10479
10983
  }),
10480
10984
  defineTool({
10481
10985
  name: "browser_close",
10482
- description: "Close the browser tab this session opened, and nothing else. Call it when the work in the browser is finished: a tab left open is a page still running on the host and a chip still sitting in the panel, and the next thing anyone sees is somebody else's leftover. It refuses a tab another session opened, because those pages belong to the sessions driving them; a session that owns no tab closes nothing and still succeeds, so the call is safe to make unconditionally. Without tab_id it closes every tab this session opened; with tab_id it closes exactly that one. 中文触发词:关掉网页、关闭标签页、收尾清理。",
10986
+ description: "Close browser tabs within the ownership rules of the selected mode. Call it when the work in the browser is finished: a tab left open is a page still running on the host and a chip still sitting in the panel, and the next thing anyone sees is somebody else's leftover. Without tab_id it closes only tabs this session opened. In isolated mode an explicit tab_id must also belong to this session; in real-browser mode an explicit tab_id may close any listed page, including an adopted one. A session that owns no tab and omits tab_id closes nothing and still succeeds, so cleanup is safe to make unconditionally. 中文触发词:关掉网页、关闭标签页、收尾清理。",
10483
10987
  parameters: { tab_id: {
10484
10988
  type: "string",
10485
10989
  description: "Tab id from browser_tabs or a previous result. Omit to close every tab this session opened."
@@ -10504,6 +11008,20 @@ title: ${value.title}
10504
11008
  ];
10505
11009
  }
10506
11010
  //#endregion
11011
+ //#region src/host/config.ts
11012
+ /** Settings schema exported through the host loader entry. */
11013
+ const Config = Schema.object({
11014
+ realBrowserEnabled: Schema.boolean().default(false).volatile().description("Connect the browser tools to a real Chrome/Edge over CDP instead of launching an isolated temporary browser. Off by default."),
11015
+ cdpEndpoint: Schema.string().default("http://127.0.0.1:9222").volatile().description("Loopback CDP endpoint only. Chrome 136+ ignores remote debugging on its default data directory; use a browser profile explicitly started with remote debugging and a non-default --user-data-dir.")
11016
+ });
11017
+ /** Read the current values, including edits committed without a plugin remount. */
11018
+ function effectiveConfig(config) {
11019
+ return {
11020
+ realBrowserEnabled: config?.realBrowserEnabled?.get() ?? false,
11021
+ cdpEndpoint: config?.cdpEndpoint?.get() ?? "http://127.0.0.1:9222"
11022
+ };
11023
+ }
11024
+ //#endregion
10507
11025
  //#region src/index.ts
10508
11026
  /** Stable cordis plugin name. */
10509
11027
  const name = "browser-view";
@@ -10513,16 +11031,25 @@ const inject = ["webServer", "tools"];
10513
11031
  * Mount the routes, the tools, and the browser lifetime.
10514
11032
  * @param ctx - host plugin context carrying webServer and tools.
10515
11033
  */
10516
- function apply(ctx) {
10517
- const service = new BrowserViewService({ authenticatedUrl: (url) => {
10518
- const connection = ctx.get("connection");
10519
- if (connection === void 0 || typeof connection.authenticatedUrl !== "function") return void 0;
10520
- try {
10521
- return connection.authenticatedUrl(url);
10522
- } catch {
10523
- return;
11034
+ function apply(ctx, config) {
11035
+ const service = new BrowserViewService({
11036
+ resolveConfig: () => {
11037
+ const value = effectiveConfig(config);
11038
+ return value.realBrowserEnabled ? {
11039
+ mode: "cdp",
11040
+ cdpEndpoint: value.cdpEndpoint
11041
+ } : { mode: "isolated" };
11042
+ },
11043
+ authenticatedUrl: (url) => {
11044
+ const connection = ctx.get("connection");
11045
+ if (connection === void 0 || typeof connection.authenticatedUrl !== "function") return void 0;
11046
+ try {
11047
+ return connection.authenticatedUrl(url);
11048
+ } catch {
11049
+ return;
11050
+ }
10524
11051
  }
10525
- } });
11052
+ });
10526
11053
  const saveImage = async (input) => {
10527
11054
  const attachments = ctx.get("attachments");
10528
11055
  if (attachments === void 0 || typeof attachments.saveImage !== "function") throw new Error("browser_screenshot needs the host attachment service to store the image; this host mounts none");
@@ -10547,9 +11074,17 @@ function apply(ctx) {
10547
11074
  for (const dispose of disposers) dispose();
10548
11075
  };
10549
11076
  }, "browser-view: tools");
11077
+ ctx.effect(() => {
11078
+ const dispose = ctx.on("loader/volatile-update", (paths) => {
11079
+ if (paths.some((path) => path[0] === "realBrowserEnabled" || path[0] === "cdpEndpoint")) service.reconfigure().catch(() => void 0);
11080
+ });
11081
+ return () => {
11082
+ dispose();
11083
+ };
11084
+ }, "browser-view: settings");
10550
11085
  ctx.effect(() => () => {
10551
11086
  service.dispose();
10552
11087
  }, "browser-view: browser");
10553
11088
  }
10554
11089
  //#endregion
10555
- export { apply, inject, name };
11090
+ export { Config, apply, inject, name };