dsh-browser-cdp 1.7.5 → 1.7.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dsh-plugin.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "$schema": "https://dsh.community/schemas/dsh-plugin-0.15.json",
3
3
  "id": "dsh-browser-cdp",
4
4
  "name": "dsh-browser-cdp",
5
- "version": "1.7.5",
5
+ "version": "1.7.9",
6
6
  "manifestVersion": "0.15",
7
7
  "facets": {
8
8
  "host": {
package/lib/client.js CHANGED
@@ -259,10 +259,16 @@ function FamilyHostSection(props) {
259
259
  if (props.useTabs !== void 0 || raw === void 0) return;
260
260
  return raw.subscribe(() => setPolled(raw.getSnapshot()));
261
261
  });
262
+ const tabs = props.useTabs !== void 0 ? props.useTabs((value) => value, eqRows) : polled;
263
+ const ownId = props.ownId ?? "__own__";
262
264
  return (0, react.createElement)("div", { style: {
263
265
  display: "grid",
264
266
  gap: "12px"
265
- } }, (props.useTabs !== void 0 ? props.useTabs((value) => value, eqRows) : polled).map((row) => (0, react.createElement)("div", { key: row.id }, props.renderSlot ? props.renderSlot(FAMILY_CHILD_KEY, {}, {
267
+ } }, (props.renderOwn ? [{
268
+ id: ownId,
269
+ order: Number.NEGATIVE_INFINITY,
270
+ label: ownId
271
+ }, ...tabs.filter((tab) => tab.id !== ownId)] : tabs).map((row) => (0, react.createElement)("div", { key: row.id }, props.renderOwn && row.id === ownId ? props.renderOwn() : props.renderSlot ? props.renderSlot(FAMILY_CHILD_KEY, {}, {
266
272
  only: row.id,
267
273
  fallback: null
268
274
  }) : props.renderContributor?.(row.id) ?? null)));
@@ -305,7 +311,7 @@ function projectLedger(slots) {
305
311
  * @param log - console 前缀(带插件名)。
306
312
  * @returns 取消定时器与撤销接管注册的 disposer。
307
313
  */
308
- function claimFamilyHostIfOrphaned(slots, isHeld, label, log) {
314
+ function claimFamilyHostIfOrphaned(slots, isHeld, label, log, ownTab) {
309
315
  let disposeClaim;
310
316
  let claimed = false;
311
317
  const timer = setTimeout(() => {
@@ -344,7 +350,9 @@ function claimFamilyHostIfOrphaned(slots, isHeld, label, log) {
344
350
  label,
345
351
  inject: () => ({
346
352
  hooks: { tabs: ledger },
347
- renderContributor
353
+ renderContributor,
354
+ ownId: ownTab?.id,
355
+ renderOwn: ownTab === void 0 ? void 0 : () => (0, react.createElement)(ownTab.component, ownTab.inject ? ownTab.inject() : {})
348
356
  }),
349
357
  children: { [FAMILY_CHILD_KEY]: {
350
358
  kind: "list",
@@ -714,6 +722,8 @@ const WATCH_SWITCH_ROUTE = "/api/bcdp/watch/switch";
714
722
  const WATCH_STOP_ROUTE = "/api/bcdp/watch/stop";
715
723
  const WATCH_STATUS_ROUTE = "/api/bcdp/watch/status";
716
724
  const VIDEO_ROUTE = "/api/bcdp/video";
725
+ const CLI_FRAME_ROUTE = "/api/bcdp/cli-frame";
726
+ const CLI_FRAME_TARGET_ID = "__cli_frame__";
717
727
  function postJson(path, body) {
718
728
  return fetch(path, {
719
729
  method: "POST",
@@ -1363,9 +1373,7 @@ function mountFamilySettingsCard(ctx) {
1363
1373
  var forms = typeof ctx.get === "function" ? ctx.get("configForms") : void 0;
1364
1374
  var scope = forms && typeof forms.get === "function" ? forms.get("dsh-browser-cdp") : void 0;
1365
1375
  if (!scope) scope = makeBridgeScope();
1366
- var familyTabHeld = false;
1367
1376
  ctx.slots.inject("dsh-family.tab", function() {
1368
- familyTabHeld = true;
1369
1377
  return ctx.slots.register({
1370
1378
  name: "dsh-family.tab",
1371
1379
  id: "dsh-browser-cdp",
@@ -1379,10 +1387,22 @@ function mountFamilySettingsCard(ctx) {
1379
1387
  }, FamilySettingsCard);
1380
1388
  }, "dsh-browser-cdp: family settings tab");
1381
1389
  var claim = claimFamilyHostIfOrphaned(ctx.slots, function() {
1382
- return familyTabHeld;
1390
+ try {
1391
+ return ctx.slots.entries("settings.section").some(function(e) {
1392
+ return String(e && e.options && e.options.id || "") === "dsh-family";
1393
+ });
1394
+ } catch {
1395
+ return false;
1396
+ }
1383
1397
  }, function() {
1384
1398
  return "起子插件设置";
1385
- }, "[dsh-browser-cdp]");
1399
+ }, "[dsh-browser-cdp]", {
1400
+ id: "dsh-browser-cdp",
1401
+ component: FamilySettingsCard,
1402
+ inject: function() {
1403
+ return { scope };
1404
+ }
1405
+ });
1386
1406
  if (typeof ctx.effect === "function") ctx.effect(function() {
1387
1407
  return claim;
1388
1408
  }, "dsh-browser-cdp: family host backstop");
@@ -1662,6 +1682,12 @@ var FAM_FIELD_GROUPS = [
1662
1682
  kind: "str",
1663
1683
  en: ["Extra Chrome args", "Appended to the Chrome launch argv; next cold start"],
1664
1684
  zh: ["Chrome 附加启动参数", "追加到 Chrome 启动 argv;下次冷启动生效"]
1685
+ },
1686
+ {
1687
+ k: "cliFramePollEnabled",
1688
+ kind: "bool",
1689
+ en: ["ego-cli fallback frames (5s)", "With no CDP screencast (local ego-cli link active), capture one screenshot every 5s through the CLI so the watch panel still fills. Off = panel shows a placeholder and no screenshot subprocess is spawned"],
1690
+ zh: ["ego-cli 降级帧(5s 一刷)", "无 CDP screencast(本机 ego-cli 激活)时,每 5s 走一次 CLI 截图填充观察窗画面区。关 = 面板显示占位提示、不拉截图子进程"]
1665
1691
  }
1666
1692
  ]
1667
1693
  },
@@ -3260,6 +3286,12 @@ function mountFloatingWatch(ctx) {
3260
3286
  return;
3261
3287
  }
3262
3288
  applyCaptureStatus(data.capture);
3289
+ if (data.cliFrameMode === true && Array.isArray(data.spaces)) {
3290
+ const cli = data.spaces.find((s) => s && s.targetId === CLI_FRAME_TARGET_ID);
3291
+ if (cli) frameCache.set(CLI_FRAME_TARGET_ID, `${CLI_FRAME_ROUTE}?t=${cli.lastActive || Date.now()}`);
3292
+ renderSpaces(data.spaces);
3293
+ return;
3294
+ }
3263
3295
  renderSpaces(data.spaces);
3264
3296
  } catch {
3265
3297
  renderEmpty();
@@ -4732,6 +4764,14 @@ LivePreviewController.prototype.refresh = function() {
4732
4764
  return;
4733
4765
  }
4734
4766
  self._applyCaptureStatus(data.capture);
4767
+ if (data.cliFrameMode === true && Array.isArray(data.spaces)) {
4768
+ var cli = data.spaces.find(function(s) {
4769
+ return s && s.targetId === CLI_FRAME_TARGET_ID;
4770
+ });
4771
+ if (cli) self.frameCache.set(CLI_FRAME_TARGET_ID, CLI_FRAME_ROUTE + "?t=" + (cli.lastActive || Date.now()));
4772
+ self._processSpaces(data.spaces);
4773
+ return;
4774
+ }
4735
4775
  self._processSpaces(data.spaces);
4736
4776
  } catch (e) {
4737
4777
  self._renderEmpty();
package/lib/index.js CHANGED
@@ -1801,6 +1801,26 @@ let attachEngine = null;
1801
1801
  /** Logger captured in initCastServer so module-level helpers can report. */
1802
1802
  let castLogger;
1803
1803
  /**
1804
+ * The active ego-cli frame poller, published by initCastServer so the tool-side
1805
+ * doctor can report the current frame source without threading the instance
1806
+ * through every registration. Null when no cast server is wired (headless host).
1807
+ */
1808
+ let activeCliPoller = null;
1809
+ /** Frame-source status for bcdp_doctor: running + the newest frame's age. */
1810
+ function getCliPollStatus() {
1811
+ if (!activeCliPoller || !activeCliPoller.isRunning()) return {
1812
+ running: false,
1813
+ lastFrameAgeMs: null,
1814
+ frameSeq: 0
1815
+ };
1816
+ const f = activeCliPoller.getFrame();
1817
+ return {
1818
+ running: true,
1819
+ lastFrameAgeMs: f ? Math.max(0, Date.now() - f.updatedAt) : null,
1820
+ frameSeq: f ? f.seq : 0
1821
+ };
1822
+ }
1823
+ /**
1804
1824
  * Publish the currently resolved endpoint for the worker. Called by the host
1805
1825
  * half whenever the ACTIVATED target changes (new target, new endpoint, or
1806
1826
  * mode switching away from remote). Returns true when the value actually
@@ -1862,6 +1882,9 @@ const EGO_WATCH_STOP_ROUTE = "/api/bcdp/watch/stop";
1862
1882
  const EGO_WATCH_STATUS_ROUTE = "/api/bcdp/watch/status";
1863
1883
  const EGO_VIDEO_ROUTE = "/api/bcdp/video";
1864
1884
  const EGO_VIDEO_STATUS_ROUTE = "/api/bcdp/video/status";
1885
+ const EGO_CLI_FRAME_ROUTE = "/api/bcdp/cli-frame";
1886
+ /** Synthetic target id the panel shows for the single CLI fallback frame. */
1887
+ const CLI_FRAME_TARGET_ID = "__cli_frame__";
1865
1888
  let toolCallCount = 0;
1866
1889
  const sseClients = /* @__PURE__ */ new Set();
1867
1890
  /** Timestamp of the last bcdp_* tool call — the idle reaper's activity signal. */
@@ -1897,6 +1920,38 @@ function markEgoToolCall(sessionId) {
1897
1920
  sseClients.delete(res);
1898
1921
  }
1899
1922
  }
1923
+ /**
1924
+ * Push one CLI-captured frame into the live watch-panel stream. In the degraded
1925
+ * ego-cli mode there is no screencast worker to emit `spaces`/`frame` events, so
1926
+ * the poller is their only source: we broadcast a synthetic single-space `spaces`
1927
+ * event (tab bar + active page) followed by a `frame` event (the PNG) to every
1928
+ * connected client. The client's existing SSE handlers render both, so the panel
1929
+ * updates the instant a frame lands — no client polling, no chicken/egg.
1930
+ */
1931
+ function broadcastCliFrame(frame) {
1932
+ if (sseClients.size === 0) return;
1933
+ const synthetic = [{
1934
+ targetId: CLI_FRAME_TARGET_ID,
1935
+ url: frame.url,
1936
+ title: frame.title,
1937
+ active: true,
1938
+ lastActive: frame.updatedAt
1939
+ }];
1940
+ const spacesFrame = `event: spaces\ndata: ${JSON.stringify(synthetic)}\n\n`;
1941
+ const framePayload = {
1942
+ targetId: CLI_FRAME_TARGET_ID,
1943
+ data: frame.png.toString("base64"),
1944
+ fmt: "png",
1945
+ ts: frame.updatedAt
1946
+ };
1947
+ const frameEvent = `event: frame\ndata: ${JSON.stringify(framePayload)}\n\n`;
1948
+ for (const res of sseClients) try {
1949
+ res.write(spacesFrame);
1950
+ res.write(frameEvent);
1951
+ } catch {
1952
+ sseClients.delete(res);
1953
+ }
1954
+ }
1900
1955
  function castStatePath() {
1901
1956
  const e = process.env;
1902
1957
  const isWin = process.platform === "win32";
@@ -2269,9 +2324,10 @@ function initCastServer(ctx, cfg, bridge, ffmpegManager, openAgentWindow$1 = asy
2269
2324
  }), loginImport = async () => ({
2270
2325
  ok: false,
2271
2326
  error: "login import not supported by this host build"
2272
- })) {
2327
+ }), cliPoller = null) {
2273
2328
  const ensureWorker = makeEnsureWorker(ctx, cfg, ffmpegManager);
2274
2329
  const pushConfig = makePushConfig(ensureWorker, ffmpegManager);
2330
+ activeCliPoller = cliPoller;
2275
2331
  const rawServer = ctx.get?.("webServer");
2276
2332
  if (!rawServer || typeof rawServer.register !== "function") return;
2277
2333
  const isTrustedRequest = (req) => /(?:^|;\s*)dsh-auth-[^=]+=/.test(String(req.headers.cookie ?? ""));
@@ -2306,12 +2362,28 @@ function initCastServer(ctx, cfg, bridge, ffmpegManager, openAgentWindow$1 = asy
2306
2362
  handler: async (_req, resRaw) => {
2307
2363
  const res = resRaw;
2308
2364
  const port = await ensureWorker();
2309
- if (port === null) return sendJson(res, 200, {
2310
- ok: false,
2311
- spaces: [],
2312
- toolCallCount,
2313
- reason: "no live agent browser"
2314
- });
2365
+ if (port === null) {
2366
+ const cliFrame = cliPoller && cliPoller.isRunning() ? cliPoller.getFrame() : null;
2367
+ if (cliFrame) return sendJson(res, 200, {
2368
+ ok: true,
2369
+ toolCallCount,
2370
+ cliFrameMode: true,
2371
+ cliFrameIntervalMs: 3e3,
2372
+ spaces: [{
2373
+ targetId: CLI_FRAME_TARGET_ID,
2374
+ url: cliFrame.url,
2375
+ title: cliFrame.title,
2376
+ active: true,
2377
+ lastActive: cliFrame.updatedAt
2378
+ }]
2379
+ });
2380
+ return sendJson(res, 200, {
2381
+ ok: false,
2382
+ spaces: [],
2383
+ toolCallCount,
2384
+ reason: "no live agent browser"
2385
+ });
2386
+ }
2315
2387
  const data = await proxyFrom(port, "/api/spaces");
2316
2388
  if (!data) return sendJson(res, 200, {
2317
2389
  ok: false,
@@ -2338,6 +2410,26 @@ function initCastServer(ctx, cfg, bridge, ffmpegManager, openAgentWindow$1 = asy
2338
2410
  proxyWorkerStream(port, res, "/api/stream");
2339
2411
  }
2340
2412
  });
2413
+ const disposeCliFrame = server.register({
2414
+ kind: "exact",
2415
+ path: EGO_CLI_FRAME_ROUTE,
2416
+ handler: async (_req, resRaw) => {
2417
+ const res = resRaw;
2418
+ const frame = cliPoller && cliPoller.isRunning() ? cliPoller.getFrame() : null;
2419
+ if (!frame) {
2420
+ res.statusCode = 204;
2421
+ res.end();
2422
+ return;
2423
+ }
2424
+ res.writeHead(200, {
2425
+ "content-type": "image/png",
2426
+ "content-length": frame.png.length,
2427
+ "cache-control": "no-store",
2428
+ "x-cli-frame-seq": String(frame.seq)
2429
+ });
2430
+ res.end(frame.png);
2431
+ }
2432
+ });
2341
2433
  const disposeInput = server.register({
2342
2434
  kind: "exact",
2343
2435
  path: EGO_INPUT_ROUTE,
@@ -2589,6 +2681,9 @@ function initCastServer(ctx, cfg, bridge, ffmpegManager, openAgentWindow$1 = asy
2589
2681
  try {
2590
2682
  disposeStream();
2591
2683
  } catch {}
2684
+ try {
2685
+ disposeCliFrame();
2686
+ } catch {}
2592
2687
  try {
2593
2688
  disposeInput();
2594
2689
  } catch {}
@@ -2631,6 +2726,135 @@ function initCastServer(ctx, cfg, bridge, ffmpegManager, openAgentWindow$1 = asy
2631
2726
  });
2632
2727
  }
2633
2728
 
2729
+ //#endregion
2730
+ //#region src/cast/cli-frame-poller.ts
2731
+ /**
2732
+ * src/cast/cli-frame-poller.ts — degraded observation frame source for the
2733
+ * `ego-cli` link kind.
2734
+ *
2735
+ * When the activated link is a local ego CLI, no CDP ws is injected, so the
2736
+ * screencast worker cannot attach and the watch panel would show nothing. This
2737
+ * poller is the fallback: every `intervalMs` it runs a short heredoc through
2738
+ * the SAME CLI channel real tools use (`ego-browser nodejs`), captures one
2739
+ * viewport PNG, and keeps the newest frame in memory for the host route to
2740
+ * serve. One frame in, one frame out — no streaming, no SSE image mirror.
2741
+ *
2742
+ * Design constraints (from the approved plan):
2743
+ * - It is a fire-and-forget short subprocess, NOT a long-lived process, so it
2744
+ * lives in the host half (cast-server), not inside cdp-cast-worker.
2745
+ * - It never contends with a real tool call: when `isBusy()` is true (a bcdp_*
2746
+ * call holds the plugin lock) the tick is skipped, and the previous frame
2747
+ * stays served. Frame freshness is subordinate to correctness of actions.
2748
+ * - Capture failures are silent by design: a wedged space / no active tab /
2749
+ * transient cold start must not blank the panel — the last good frame is the
2750
+ * honest degraded state, and the next tick retries.
2751
+ * - `capture` is injected (returns the CLI's merged stdout), so this module
2752
+ * imports nothing from index.ts and never touches ctx.subprocess directly.
2753
+ */
2754
+ /** Sentinel the frame heredoc prints; carries base64 PNG + url + title. */
2755
+ const FRAME_SENTINEL = "@@BCDP_FRAME@@";
2756
+ /**
2757
+ * Parse one capture's merged stdout for the frame sentinel line. Returns the
2758
+ * decoded frame, or null when the sentinel is absent or its payload malformed
2759
+ * (a CLI that errored before reaching the log line, a truncated base64, etc.).
2760
+ * Scans last-to-first so trailing log noise cannot displace the payload, and so
2761
+ * the behaviour matches the tool-side `parseSentinel` convention.
2762
+ * @internal exported for tests
2763
+ */
2764
+ function parseFrameSentinel(stdout, seq, at) {
2765
+ const lines = stdout.split("\n");
2766
+ for (let i = lines.length - 1; i >= 0; i--) {
2767
+ const line = lines[i];
2768
+ const idx = line.indexOf(FRAME_SENTINEL);
2769
+ if (idx === -1) continue;
2770
+ const payload = line.slice(idx + 14).trim();
2771
+ if (payload === "") continue;
2772
+ let parsed;
2773
+ try {
2774
+ parsed = JSON.parse(payload);
2775
+ } catch {
2776
+ return null;
2777
+ }
2778
+ if (typeof parsed.png !== "string" || parsed.png === "") return null;
2779
+ let png;
2780
+ try {
2781
+ png = Buffer.from(parsed.png, "base64");
2782
+ } catch {
2783
+ return null;
2784
+ }
2785
+ if (png.length === 0) return null;
2786
+ return {
2787
+ png,
2788
+ url: typeof parsed.url === "string" ? parsed.url : "",
2789
+ title: typeof parsed.title === "string" ? parsed.title : "",
2790
+ seq,
2791
+ updatedAt: at
2792
+ };
2793
+ }
2794
+ return null;
2795
+ }
2796
+ var CliFramePoller = class {
2797
+ opts;
2798
+ timer = null;
2799
+ latest = null;
2800
+ seq = 0;
2801
+ /** Guard against overlapping ticks (a capture slower than the interval). */
2802
+ inFlight = false;
2803
+ constructor(opts) {
2804
+ this.opts = opts;
2805
+ }
2806
+ /** Start polling. Idempotent: a second call while running is a no-op. */
2807
+ start() {
2808
+ if (this.timer !== null) return;
2809
+ this.timer = setInterval(() => {
2810
+ this.tick();
2811
+ }, this.opts.intervalMs);
2812
+ this.timer.unref?.();
2813
+ this.tick();
2814
+ }
2815
+ /** Stop polling and drop the cached frame (the panel reverts to its placeholder). */
2816
+ stop() {
2817
+ if (this.timer !== null) {
2818
+ clearInterval(this.timer);
2819
+ this.timer = null;
2820
+ }
2821
+ this.latest = null;
2822
+ }
2823
+ isRunning() {
2824
+ return this.timer !== null;
2825
+ }
2826
+ /** The newest captured frame, or null when there is none yet. */
2827
+ getFrame() {
2828
+ return this.latest;
2829
+ }
2830
+ async tick() {
2831
+ if (this.inFlight) return;
2832
+ if (this.opts.isBusy && this.opts.isBusy()) return;
2833
+ this.inFlight = true;
2834
+ try {
2835
+ const frame = parseFrameSentinel(await this.opts.capture(), ++this.seq, (this.opts.now ?? Date.now)());
2836
+ if (frame !== null) {
2837
+ this.latest = frame;
2838
+ if (this.opts.onFrame) try {
2839
+ this.opts.onFrame(frame);
2840
+ } catch {}
2841
+ }
2842
+ } catch {} finally {
2843
+ this.inFlight = false;
2844
+ }
2845
+ }
2846
+ };
2847
+ /**
2848
+ * The capture heredoc. Uses the runtime's own facades (taskSpaces + page) so it
2849
+ * rides the exact channel real tools use; deliberately does NOT call
2850
+ * ensureRealTab / switchTab — a passive observer must not move the active tab.
2851
+ * `page.screenshot()` in this runtime returns a saved PNG path, so we read the
2852
+ * file back into base64 and clean it up.
2853
+ */
2854
+ function buildFrameScript(spaceJson) {
2855
+ return `const task = await taskSpaces.useOrCreate(${spaceJson})\nlet __info = {}\ntry { __info = await page.info() } catch { __info = {} }\nconst __p = await page.screenshot({ fullPage: false })\nconst __fs = await import('node:fs/promises')\nconst __png = (await __fs.readFile(__p)).toString('base64')\ntry { await __fs.unlink(__p) } catch {}\nconsole.log(${JSON.stringify(FRAME_SENTINEL)} + JSON.stringify({ png: __png, url: __info.url || '', title: __info.title || '' }))\n`;
2856
+ }
2857
+
2634
2858
  //#endregion
2635
2859
  //#region src/config.ts
2636
2860
  const backend = z.union([
@@ -2765,6 +2989,7 @@ const Config$1 = z.object({
2765
2989
  localHeadless: z.boolean().description("Run the locally launched browser headless."),
2766
2990
  remoteEnabled: z.boolean().description("Master switch for REMOTE attach. Off = the configured target sequence is preserved but inert (nothing probes or connects remotely); flip back on any time. Does not affect cdpMode=local.").volatile(),
2767
2991
  allowProbeColdStart: z.boolean().description("Allow the ego-cli readiness probe to cold-start the backing browser. Off (default): the probe never launches the browser — when --status cannot prove the browser is already up, the heredoc round-trip is skipped and the browser starts on the first real bcdp_* call instead (no browser window at plugin startup). On: the probe verifies the SDK harness up front, which may launch the browser.").volatile(),
2992
+ cliFramePollEnabled: z.boolean().default(true).description("Degraded watch-panel frame source for the local ego-cli link: with no CDP screencast available, capture one viewport screenshot every 5s through the CLI channel and serve it to the panel. On (default): the poller runs while an ego-cli link owns routing. Off: the panel keeps its placeholder and no screenshot subprocess is spawned. Hot-applies without reloading the plugin.").volatile(),
2768
2993
  localUserDataDir: z.string().description("Profile dir for the locally launched browser. Empty = managed dir; never point at your daily Chrome profile."),
2769
2994
  lightpandaArgs: z.string().description("Extra args appended to a managed `lightpanda serve` argv. --host/--port are managed and cannot be overridden.").volatile(),
2770
2995
  castFpsCap: z.number().min(0).max(60).step(1),
@@ -3037,6 +3262,7 @@ function resolveConfig(config = {}) {
3037
3262
  lightpandaArgs: trimmed(config.lightpandaArgs),
3038
3263
  remoteEnabled: config.remoteEnabled === void 0 ? true : Boolean(config.remoteEnabled),
3039
3264
  allowProbeColdStart: config.allowProbeColdStart === true || config.allowProbeColdStart === "true",
3265
+ cliFramePollEnabled: config.cliFramePollEnabled !== false && config.cliFramePollEnabled !== "false",
3040
3266
  jevUrl: trimmed(config.jevUrl),
3041
3267
  jevKey: trimmed(config.jevKey),
3042
3268
  jevModel: trimmed(config.jevModel) === "" ? "jev" : trimmed(config.jevModel),
@@ -7269,6 +7495,10 @@ function createSessionSpaceTracker(defaultNameFor = () => DEFAULT_SPACE) {
7269
7495
  const slots = /* @__PURE__ */ new Map();
7270
7496
  let sessionKey = GLOBAL_SESSION_KEY;
7271
7497
  let session;
7498
+ let lastRealKey = null;
7499
+ const noteReal = () => {
7500
+ if (sessionKey !== GLOBAL_SESSION_KEY) lastRealKey = sessionKey;
7501
+ };
7272
7502
  const slotOf = (key) => {
7273
7503
  let s = slots.get(key);
7274
7504
  if (!s) {
@@ -7288,20 +7518,26 @@ function createSessionSpaceTracker(defaultNameFor = () => DEFAULT_SPACE) {
7288
7518
  setCurrentSession: (id) => {
7289
7519
  session = id;
7290
7520
  sessionKey = id ?? GLOBAL_SESSION_KEY;
7521
+ noteReal();
7291
7522
  },
7292
7523
  currentSession: () => session,
7293
7524
  current: () => slotOf(sessionKey).activeSpace,
7525
+ lastActiveSpace: () => lastRealKey === null ? null : slotOf(lastRealKey).activeSpace,
7294
7526
  opened: (args, result) => {
7527
+ noteReal();
7295
7528
  withSlot((s, def) => {
7296
7529
  s.activeName = result?.name ?? str(args?.name, def) ?? null;
7297
7530
  s.activeSpace = result?.id ?? s.activeName ?? def;
7298
7531
  });
7299
7532
  },
7300
7533
  selected: (space) => {
7301
- if (space !== void 0 && space !== "") withSlot((s) => {
7302
- s.activeSpace = space;
7303
- s.activeName = typeof space === "string" ? space : null;
7304
- });
7534
+ if (space !== void 0 && space !== "") {
7535
+ noteReal();
7536
+ withSlot((s) => {
7537
+ s.activeSpace = space;
7538
+ s.activeName = typeof space === "string" ? space : null;
7539
+ });
7540
+ }
7305
7541
  },
7306
7542
  closed: (space, done) => {
7307
7543
  withSlot((s, def) => {
@@ -7326,8 +7562,38 @@ function createSessionSpaceTracker(defaultNameFor = () => DEFAULT_SPACE) {
7326
7562
  * harness sessions sharing the same browser remain unsupported (host-level).
7327
7563
  */
7328
7564
  let egoLockChain = Promise.resolve();
7565
+ /**
7566
+ * How many bcdp_* executions are currently inside the lock body (0 = idle).
7567
+ * The CLI frame poller reads this via `egoLockBusy()` to skip a tick while a
7568
+ * real tool call owns the browser — a passive observer must never contend with
7569
+ * an action. Incremented the moment the queued `fn` starts, decremented when its
7570
+ * result settles, so a chained-but-not-yet-run call does not falsely read busy.
7571
+ */
7572
+ let egoLockDepth = 0;
7573
+ function egoLockBusy() {
7574
+ return egoLockDepth > 0;
7575
+ }
7329
7576
  function withEgoLock(fn) {
7330
- const run = egoLockChain.then(() => fn(), () => fn());
7577
+ const runBody = () => {
7578
+ egoLockDepth += 1;
7579
+ let r;
7580
+ try {
7581
+ r = fn();
7582
+ } catch (err) {
7583
+ egoLockDepth -= 1;
7584
+ throw err;
7585
+ }
7586
+ if (r && typeof r.then === "function") return r.then((v) => {
7587
+ egoLockDepth -= 1;
7588
+ return v;
7589
+ }, (e) => {
7590
+ egoLockDepth -= 1;
7591
+ throw e;
7592
+ });
7593
+ egoLockDepth -= 1;
7594
+ return r;
7595
+ };
7596
+ const run = egoLockChain.then(runBody, runBody);
7331
7597
  egoLockChain = run.then(() => void 0, () => void 0);
7332
7598
  return run;
7333
7599
  }
@@ -7868,6 +8134,47 @@ async function runEgoScript(subprocess, script, exec, cfg, graceOverrideMs) {
7868
8134
  stderr
7869
8135
  };
7870
8136
  }
8137
+ /**
8138
+ * ego-cli degraded frame source: run the poller heredoc through the SAME CLI
8139
+ * channel real tools use and resolve the merged stdout (which carries the
8140
+ * `@@BCDP_FRAME@@` payload). Kept separate from `runEgoScript` because that one
8141
+ * parses `@@DSH_RESULT@@` and needs an exec/abort context a passive poller has
8142
+ * none of. A failed or non-zero run resolves '' — the poller treats '' as "no
8143
+ * new frame" and keeps the previous one, so a transient cold start never blanks
8144
+ * the panel.
8145
+ */
8146
+ const CLI_FRAME_MAX_BYTES = 12 * 1024 * 1024;
8147
+ async function spawnCliFrameCapture(subprocess, cfg, space) {
8148
+ if (space === null || space === void 0 || space === "") return "";
8149
+ const { attach } = effectiveChannel(cfg);
8150
+ const script = buildFrameScript(j(space));
8151
+ try {
8152
+ const handle = subprocess.spawn({
8153
+ argv: buildEgoToolArgv(cfg.egoArgvPrefix, attach, cfg.runtimeArgs ?? ""),
8154
+ cwd: process.cwd(),
8155
+ env: resolveEgoEnv(cfg),
8156
+ stdio: {
8157
+ stdin: { data: script },
8158
+ stdout: {
8159
+ maxBytes: CLI_FRAME_MAX_BYTES,
8160
+ spill: { maxBytes: CLI_FRAME_MAX_BYTES }
8161
+ },
8162
+ stderr: {
8163
+ maxBytes: CLI_FRAME_MAX_BYTES,
8164
+ spill: { maxBytes: CLI_FRAME_MAX_BYTES }
8165
+ }
8166
+ },
8167
+ graceMs: cfg.graceMs
8168
+ });
8169
+ if ((await handle.done).exitCode !== 0) return "";
8170
+ return mergeCliOutput({
8171
+ stdout: readAll(handle.collected.stdout),
8172
+ stderr: readAll(handle.collected.stderr)
8173
+ });
8174
+ } catch {
8175
+ return "";
8176
+ }
8177
+ }
7871
8178
  /** How much raw stdout a tool may hand back when a script emitted no JSON. */
7872
8179
  const TOOL_RAW_STDOUT_MAX = 4e3;
7873
8180
  /**
@@ -8170,6 +8477,9 @@ function apply(ctx, config = {}) {
8170
8477
  get allowProbeColdStart() {
8171
8478
  return resolveConfig(bridge.source()).allowProbeColdStart;
8172
8479
  },
8480
+ get cliFramePollEnabled() {
8481
+ return resolveConfig(bridge.source()).cliFramePollEnabled;
8482
+ },
8173
8483
  get jevUrl() {
8174
8484
  return judgeSettingsOf(resolveConfig(bridge.source())).jevUrl;
8175
8485
  },
@@ -8341,6 +8651,13 @@ function apply(ctx, config = {}) {
8341
8651
  })})`);
8342
8652
  }
8343
8653
  bridge.onChange(() => tiers.reapply());
8654
+ const cliPoller = new CliFramePoller({
8655
+ intervalMs: 3e3,
8656
+ capture: () => spawnCliFrameCapture(ctx.subprocess, cfg, cfg.spaceTracker.lastActiveSpace()),
8657
+ isBusy: egoLockBusy,
8658
+ onFrame: (frame) => broadcastCliFrame(frame)
8659
+ });
8660
+ ctx.effect?.(() => () => cliPoller.stop());
8344
8661
  const triggerCdpRefresh = (() => {
8345
8662
  let inFlight = false;
8346
8663
  let pending = false;
@@ -8392,6 +8709,8 @@ function apply(ctx, config = {}) {
8392
8709
  changed = true;
8393
8710
  recycleWorker("cdp activation change").catch(() => null);
8394
8711
  }
8712
+ if (ws === null && attach.linkKind === EGO_CLI_KIND && attach.status === "ready" && resolved.cliFramePollEnabled === true) cliPoller.start();
8713
+ else cliPoller.stop();
8395
8714
  } catch {} finally {
8396
8715
  inFlight = false;
8397
8716
  if (pending) {
@@ -8411,7 +8730,7 @@ function apply(ctx, config = {}) {
8411
8730
  });
8412
8731
  ctx.inject?.(["webServer"], (wctx) => {
8413
8732
  try {
8414
- initCastServer(wctx, cfg, bridge, ffmpegManager, () => openAgentWindow(ctx, cfg), (opts) => importLoginCookies(opts, { subprocess: ctx.subprocess }));
8733
+ initCastServer(wctx, cfg, bridge, ffmpegManager, () => openAgentWindow(ctx, cfg), (opts) => importLoginCookies(opts, { subprocess: ctx.subprocess }), cliPoller);
8415
8734
  } catch (err) {
8416
8735
  ctx.logger?.warn?.(`dsh-browser-cdp: cast server init failed: ${err?.message ?? err}`);
8417
8736
  }
@@ -9608,6 +9927,14 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
9608
9927
  lines.push(`channel: ${channel.effective ? `${channel.effective.link.label} [${channel.effective.link.id}] (${channel.effective.reason}${channel.effective.demotedId ? `, over ${channel.effective.demotedId}` : ""})` : "(none — activate a link or enable one)"}`);
9609
9928
  lines.push(`remote CDP: ${cfg.remoteEnabled === false ? "DISABLED by switch (sequence preserved)" : "enabled"}`);
9610
9929
  lines.push(`attach: ${attachNow.status}${attachNow.endpointSource ? ` (source: ${attachNow.endpointSource})` : ""}${attachNow.endpoint ? ` @ ${attachNow.endpoint}` : ""}`);
9930
+ const cliPoll = getCliPollStatus();
9931
+ const frameSource = getAttachEndpoint() ? "screencast (CDP)" : cliPoll.running ? `cli-poll (3s interval, seq ${cliPoll.frameSeq}${cliPoll.lastFrameAgeMs !== null ? `, last frame ${cliPoll.lastFrameAgeMs}ms ago` : ", no frame yet"})` : cfg.cliFramePollEnabled === false ? "none (cliFramePollEnabled off)" : "none";
9932
+ lines.push(`frame source: ${frameSource}`);
9933
+ {
9934
+ const sid = callingSessionId(exec);
9935
+ const pollSpace = cfg.spaceTracker.lastActiveSpace();
9936
+ lines.push(`session scope: id=${sid ?? "(none → global slot)"} thisCallSpace=${cfg.activeSpace} pollerObserves=${pollSpace ?? "(null: poller will skip / no default registered)"} defaultSpace=${cfg.defaultSpace} isolateSpaces=${cfg.isolateSpaces}`);
9937
+ }
9611
9938
  if (attachNow.engine !== void 0) lines.push(`engine: ${attachNow.engine}`);
9612
9939
  if (attachNow.engine === "lightpanda") lines.push("degraded on this engine: live view (no screencast) · panel pick (no Overlay/bindingCalled) · bcdp_download (no Page download events) · screenshots are PNG text-renders · auth_flush is a no-op");
9613
9940
  if (attachNow.engine === "lightpanda" || process.platform === "win32") lines.push(process.platform === "win32" ? "lightpanda on win32: no native build �?use WSL2: `wsl --install` (admin), then inside WSL: `curl -fsSL https://pkg.lightpanda.io/install.sh | bash` + `lightpanda serve --host 127.0.0.1 --port 9222`; WSL2 maps the port to Windows localhost, then add http://127.0.0.1:9222 as a CDP endpoint. Docker alternative: `docker run -d -p 127.0.0.1:9222:9222 lightpanda/browser:nightly`." : "lightpanda (linux/macOS): `curl -fsSL https://pkg.lightpanda.io/install.sh | bash` (installs to ~/.local/bin) then `lightpanda serve --host 127.0.0.1 --port 9222`.");
@@ -10380,4 +10707,4 @@ function registerHelpAndDoctor(ctx, cfg, reg, tiers) {
10380
10707
  }
10381
10708
 
10382
10709
  //#endregion
10383
- export { ATTACH_SESSION_HINT, CDP_CONNECT_FAIL_RE, Config, GLOBAL_SESSION_KEY, STATUS_FACADE_SCRIPT, STATUS_FACADE_SENTINEL, TAB_STUCK_RE, apply, attachSessionHint, buildEgoToolArgv, cdpAttachError, createActiveSpaceTracker, createSessionSpaceTracker, decideCdpAttach, deriveSlotDefaultName, effectiveChannel, findChromeBinary, findUpstreamPluginInstall, inject, isTabStuckFailure, name, parseSentinel, parseStatusFacades, resolveEgoEnv, runWithStaleSpaceRetry, runWithTabRevive, sessionSpaceToken, shouldReapBrowser };
10710
+ export { ATTACH_SESSION_HINT, CDP_CONNECT_FAIL_RE, Config, GLOBAL_SESSION_KEY, STATUS_FACADE_SCRIPT, STATUS_FACADE_SENTINEL, TAB_STUCK_RE, apply, attachSessionHint, buildEgoToolArgv, cdpAttachError, createActiveSpaceTracker, createSessionSpaceTracker, decideCdpAttach, deriveSlotDefaultName, effectiveChannel, egoLockBusy, findChromeBinary, findUpstreamPluginInstall, inject, isTabStuckFailure, name, parseSentinel, parseStatusFacades, resolveEgoEnv, runWithStaleSpaceRetry, runWithTabRevive, sessionSpaceToken, shouldReapBrowser };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-browser-cdp",
3
- "version": "1.7.5",
3
+ "version": "1.7.9",
4
4
  "description": "dsh-browser-cdp: DSH browser plugin — attach to a running Chrome/Edge over CDP (no bundled browser needed); structured browser-automation tools (30+ bcdp_*) that drive the vendored ego runtime through ctx.subprocess, plus a realtime watch panel (live SSE screencast + direct mouse interaction + download capture + human-verification notice). Web shell: floating watch panel without dsh-better-sidebar, sidebar tab with it. Headless/TUI hosts: tools-only. [DSH 0.1.7-rc.1 ~ 0.2.1-rc.1 line (exact rc enumeration): declarative settings via Config .volatile() fields; for DSH 0.1.2-rc.1 ~ 0.1.5-rc.3 use the 0.17.x line]",
5
5
  "type": "module",
6
6
  "main": "./lib/index.js",
@@ -38,7 +38,12 @@
38
38
  "0.1.7-rc.2": "compatible",
39
39
  "0.2.0-rc.1": "compatible",
40
40
  "0.2.0-rc.2": "compatible",
41
- "0.2.1-rc.1": "compatible", "0.2.1-rc.2": "compatible", "0.2.1-rc.3": "compatible", "0.2.1-rc.4": "compatible", "0.2.1-rc.5": "compatible"}
41
+ "0.2.1-rc.1": "compatible",
42
+ "0.2.1-rc.2": "compatible",
43
+ "0.2.1-rc.3": "compatible",
44
+ "0.2.1-rc.4": "compatible",
45
+ "0.2.1-rc.5": "compatible"
46
+ }
42
47
  }
43
48
  },
44
49
  "scripts": {