dsh-browser-cdp 1.9.16 → 1.9.51

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/CHANGELOG.de.md CHANGED
@@ -1,3 +1,7 @@
1
+ ## [1.9.17] - 2026-11-13 — Reaktive Erfassung: Status aus dem Cache, Tab-Fokus vom Capture getrennt
2
+
3
+ Kurzfassung (Details und Zwischenversionen in `CHANGELOG.md`): `bcdp_status` antwortet aus dem Attach-Cache (`refresh:true` erzwingt eine echte Prüfung), damit „Status prüfen“ keinen Prozess startet; die Attach-Prüfung ist entprellt und teilt ein laufendes Ergebnis; `tabbit-cli diagnose` läuft NICHT beim Mounten (gemessen: es startet den Browser); der Tab-Fokus hat jetzt drei getrennte Eigentümer (Operator/Agent, Panel, Frame-Capture), sodass das Panel auch bei entferntem CDP der aktuellen Registerkarte folgt (DevTools-Basis aus der WebSocket-URL abgeleitet, stille Degradation ohne `/json/*`); alle Aufrufe an ein Backend laufen über eine Warteschlange.
4
+
1
5
  ## [0.18.0] - 2026-09-29 — DSH-0.2.0-rc.1-Linie (compat/0.2.0: reine Metadaten-Anpassung, null Codeänderungen)
2
6
 
3
7
  ### Neu
package/CHANGELOG.es.md CHANGED
@@ -1,3 +1,7 @@
1
+ ## [1.9.17] - 2026-11-13 — Sondeo reactivo: estado desde caché, foco de pestaña separado de la captura
2
+
3
+ Resumen (detalle y versiones intermedias en `CHANGELOG.md`): `bcdp_status` responde desde la caché de conexión (`refresh:true` fuerza un sondeo real), para que «comprobar estado» no arranque un proceso; el sondeo de conexión tiene debounce y comparte el resultado en curso; `tabbit-cli diagnose` NO se ejecuta al montar (medido: arranca el navegador); el foco de pestaña tiene ahora tres propietarios distintos (operador/agente, panel, captura de fotogramas), así el panel sigue la pestaña actual también con CDP remoto (base DevTools derivada de la URL WebSocket, degradación silenciosa sin `/json/*`); todas las llamadas a un backend pasan por una única cola.
4
+
1
5
  ## [0.18.0] - 2026-09-29 — Línea DSH 0.2.0-rc.1 (compat/0.2.0: adaptación puramente de metadata, cero cambios de código)
2
6
 
3
7
  ### Añadidos
package/CHANGELOG.fr.md CHANGED
@@ -1,3 +1,7 @@
1
+ ## [1.9.17] - 2026-11-13 — Sondage réactif : état depuis le cache, focus d'onglet séparé de la capture
2
+
3
+ Résumé (détail et versions intermédiaires dans `CHANGELOG.md`) : `bcdp_status` répond depuis le cache de connexion (`refresh:true` force un vrai sondage), pour que « vérifier l'état » ne lance pas de processus ; le sondage de connexion est déduplicaté et partage le résultat en cours ; `tabbit-cli diagnose` n'est PAS exécuté au montage (mesuré : il démarre le navigateur) ; le focus d'onglet a désormais trois propriétaires distincts (opérateur/agent, panneau, capture d'image), le panneau suit donc l'onglet courant même en CDP distant (base DevTools dérivée de l'URL WebSocket, dégradation silencieuse sans `/json/*`) ; tous les appels vers un backend passent par une file unique.
4
+
1
5
  ## [0.18.0] - 2026-09-29 — Ligne DSH 0.2.0-rc.1 (compat/0.2.0 : adaptation purement métadonnées, zéro modification de code)
2
6
 
3
7
  ### Ajouts
package/CHANGELOG.it.md CHANGED
@@ -1,3 +1,7 @@
1
+ ## [1.9.17] - 2026-11-13 — Sondaggio reattivo: stato dalla cache, focus della scheda separato dalla cattura
2
+
3
+ Sintesi (dettagli e versioni intermedie in `CHANGELOG.md`): `bcdp_status` risponde dalla cache di connessione (`refresh:true` forza un sondaggio reale), così «controllare lo stato» non avvia un processo; il sondaggio di connessione è antirimbalzo e condivide il risultato in corso; `tabbit-cli diagnose` NON viene eseguito al mount (misurato: avvia il browser); il focus della scheda ora ha tre proprietari distinti (operatore/agente, pannello, cattura fotogrammi), quindi il pannello segue la scheda corrente anche con CDP remoto (base DevTools derivata dall'URL WebSocket, degrado silenzioso senza `/json/*`); tutte le chiamate verso un backend passano da un'unica coda.
4
+
1
5
  ## [0.18.0] - 2026-09-29 — Linea DSH 0.2.0-rc.1 (compat/0.2.0: adattamento puramente di metadata, zero modifiche al codice)
2
6
 
3
7
  ### Aggiunte
package/CHANGELOG.md CHANGED
@@ -1,3 +1,88 @@
1
+ ## 1.9.22 (2026-11-13)
2
+
3
+ **面板 ↻ 现在真的会同步「当前激活对象」——而且是零副作用。**
4
+
5
+ 排查发现:头部刷新按钮 `#dsh-ego-refresh` 早在 1.9.x 就有 DOM 和 `refreshBtn` 引用,但**从来没挂过 click 监听**——所以重启后点它什么也不会发生,面板要等一次 `bcdp_*` 才出内容。
6
+
7
+ - **新增 `POST /api/bcdp/sync`**(`EGO_SYNC_ROUTE`),宿主按通道分流(`src/runtime/refresh-sync.ts`):
8
+ - `cdp`:重跑 attach pass,worker 重新读 spaces;
9
+ - `tabbit-cli`:跑**只读** `tabs --task`(实测:该命令对任意不存在的 task 名也返回完整清单,不建 task、不认领、浏览器关着也不拉起)→ 行清单立刻上屏;有活 task 时顺带拍一帧;
10
+ - `ego-cli` / `lightpanda`:只重探就绪,仍受 `allowProbeColdStart` 门禁。
11
+ - **为什么不顺手把帧也拍了**:`nodejs --tab <id>` 确实会自动建 task 并认领那颗 tab(实测 158ms,`acquisition.tabIds` 命中),但 task 名是 `dsh-<sessionToken>`,刷新处理器拿不到 session id;用猜的名字建 task 会**割裂归属**(面板 task 占了 tab,下一个工具 task 就抢不到)。所以刷新只做只读同步,画面随首次工具调用到位。
12
+ - **客户端**:↻ 点击 → `POST /api/bcdp/sync` → 再读 spaces;`StatsSnapshot` 补上正式返回类型(不再 `Record<string, unknown>`)。
13
+
14
+ 真机实测(宿主刚重启、无 task、无工具调用):
15
+
16
+ ```
17
+ POST /api/bcdp/sync → {"ok":true,"action":"tabbit-sync","listed":3,"framed":false,"adopted":false,"reason":"list-only-needs-task"}
18
+ GET /api/bcdp/spaces → ok=true rows=1 link=tabbit-cli (305298915, active=true, https://www.baidu.com/)
19
+ ```
20
+
21
+ ## 1.9.21 (2026-11-13)
22
+
23
+ **tab 条强制换行 + × 乐观关闭 + 版本徽标(用于分辨 renderer 是否加载了新包)。**
24
+
25
+ - `renderTabs()` 逐项写 **inline style**(`flexWrap=wrap`、`overflowX=hidden`、`maxHeight=92px`,pill `flex:0 1 auto`),不再单靠样式表——宿主的样式表或旧缓存都能把它覆盖掉。
26
+ - `×` 改为**乐观移除**:先 `tab.remove()` 给反馈,再 POST `/api/bcdp/close`,700ms 后 refresh 对账(关失败行会回来)。
27
+ - 面板标题旁新增 **版本徽标** `v1.9.22`:一眼看出 renderer 加载的是哪份客户端切包。
28
+
29
+ ## 1.9.20 (2026-11-13)
30
+
31
+ **1.9.19 的窗口收窄没生效的真因:`??` 链停在 0 上;同时把「关 tab」变成面板即时可见。**
32
+
33
+ - **真因**:这个 tabbit-cli 版本里 `tabs` 的 `focusedWindowId` 返回 **null**,解析后归为 `0`;而 `0` 不是 nullish,所以 `a ?? b ?? c` 链在 `0` 处就停了 —— `_tabbitWindowId` 永远是 0,行清单压根没收窄。改用 `||` 链,并把选择逻辑抽成 `chooseTabbitWindow()` 加单测(含 `focusedWindowId=0` 这条回归用例)。
34
+ - **关 tab 后即时消失**:之前只有帧广播会带 `spaces`,而帧广播在没图时(空白页/截屏跳过)直接 return,行就会挂着。新增 `broadcastCliSpaces()`,tabbit 关闭成功后立刻推一次只含 `spaces` 的事件,并同步 `lastCliSpaces`。
35
+ - 实测:`page.close()` 在该 CLI 上真的关 tab(4 → 3,回执 `closedPages` 带具体 tab),所以 × 现在是真关,不再是只删行。
36
+
37
+ ## 1.9.19 (2026-11-13)
38
+
39
+ **面板 Tab 条:不再把两个窗口的 tab 当成重复项;tab 条自动换行;× 真的关 tab。**
40
+
41
+ 现场现象(用户截图):全模式下出现四条「新标签页 / 百度一下 / 新标签页 / 百度一下」,看起来像双份;同时面板拍的是 about:newtab 而不是当前的百度页。
42
+
43
+ - **根因:Tabbit 汇报的是「所有窗口的所有 tab」。** 用户开了两个 Tabbit 窗口,每个窗口里都是 newtab + 百度,于是 strip 里就是一对一对的。现在 `tabs` 子命令的 `focusedWindowId` 被保留,新增 `_tabbitWindowId`:优先跟**agent 自己那个 tab 所在的窗口**,否则跟浏览器焦点窗口;行清单(`tabbitSpaceRows`)按它收窄,帧轮询的 fallback 也从「全量里的 active」改成「收窄后的 active」——不再可能拿另一个窗口的 tab 去拍。
44
+ - **为什么之前会拍成 newtab:** 帧轮询在 `--tab` 目标缺失时会落回 task 的默认页(新 task 刚建就是一个 about:blank)。窗口收窄后,active 行只会在本窗口内产生,不会是另一个窗口的 newtab。
45
+ - **tab 条换行**:`#dsh-ego-tabs` 改为 `flex-wrap:wrap` + `overflow-x:hidden` + `max-height:92px`(超出才纵向滚),pill 改为 `flex:0 1 auto`、标题省略号 150px。四个 tab 不再需要横滚才能看全。
46
+ - **× 在 CLI 通道真的关 tab**:`/api/bcdp/close` 在无 worker(tabbit/ego-cli)时不再直接 400,而是走宿主注入的 `closeCliTab`;tabbit 用 `page.close()`(带 `--tab`)关闭,成功后当场从缓存里删行、清 `_tabbitLastActiveTabId`。其他 CLI 通道返回 501 并附原因,不再假装成功。
47
+
48
+ ## 1.9.18 (2026-11-13)
49
+
50
+ **观察面不再吃操作面的配额:Tabbit receipt 预算账本 + 主动回收 + 无人看时不烧。**
51
+
52
+ 实测背景(tabbit-cli 1.21.21):单个 task 只接受 **1024 条 receipt**,满了之后**每一次 `nodejs` 都返回空 stdout**,插件只能报 `tabbit-cli produced no stdout`,且 CLI 只进不出(`receipts.delete` 零命中)。而帧轮询每 3 s 一条 `frame-<ts>-<tab>`、约 **51 分钟**把单 tab 的配额烧光 —— 于是**看板把工具路径饿死了**:面板开着、agent 闲置时,下一次 `bcdp_*` 全部失败。
53
+
54
+ - **配额账本**(`src/cdp/tabbit-receipts.ts`):一次 `nodejs` 一条,按 task 本地计数;不向 CLI 查询(那会每 tick 多一个子进程)。
55
+ - **主动回收**:到 **80%(819 条)** 就 `finish`(不带 `--discard`,保留 tab)并 `reset` 账本,下一次 `nodejs` 由 tabbit 按需重建 task —— 调用方无感。
56
+ - **撞墙也能自愈**:`EMPTY_OUTPUT` 且计数越线 → 回收一次 + 重试一次;仍失败才归类 `tabbit-task-stalled`,并在错误文案里带上 `receipts n/1024` 与“用 `bcdp_space op=close` 收尾”的指引。
57
+ - **重建后清状态**:`_tabbitTabCache` / `_tabbitLastActiveTabId` / 帧轮询的 good-rows 全部作废 —— 否则会拿旧 tab id 去绑新任务的行,表现就是“闪一下又变白”。
58
+ - **无人看就不烧**:`cast-server` 导出 `panelWatcherCount()`;面板 SSE 订阅为 0 时,帧轮询与盘存轮询直接跳过(`no-watchers`),这是省得最多的一条。
59
+ - **静止降频**:连续 3 帧相同 → 10 s,6 帧相同 → 30 s;画面一变立刻回 3 s(用长度 + 首尾字节的轻量摘要判定)。
60
+ - **医生可见**:`bcdp_doctor` 新增 `tabbit receipts: n/1024 used, m left, recycles=k`。
61
+
62
+ ## 1.9.17 (2026-11-13)
63
+
64
+ **「重启后必须先调一次 status」的根因:把「连接就绪」和「工具面解锁」两件事压在同一个工具上;顺带拆开争抢「当前 tab」的三个写者。**
65
+
66
+ - **`bcdp_status` 改为读 attach 缓存 + `refresh:true` 强制探测**。真实成本决定了这是个必须先修的点:CDP 路要起一个 subprocess heredoc(典型 ~300 ms),tabbit 路要跑 `diagnose`(grace 20 s)**且在 ego 锁内持锁**——一次「先看看状态」会把整条工具链堵住。就绪判定本来就由 mount / 设置变更 / 显式刷新驱动,工具只该读结果。
67
+ 常驻面字符数反降(441 ≤ 600 预算),schema 总预算测试仍绿。
68
+ - **attach 探测:300 ms trailing 去抖 + 1 s 最小间隔 + 同 link 单飞共享 Promise**。表单逐字段 onChange 以前会真的探 N 次(inFlight 时只置 pending、随后重跑),现在一次变更风暴只探一次,并发调用者共享同一个 Promise。卸载时清掉待触发的定时器。
69
+ - **tabbit 就绪不再是假 `ready`**:原来 `refreshAttach` 的 tabbit 分支只 `patch({status:'ready'})`,CLI 根本不存在也报就绪。现在由宿主导入的 `tabbitProbe` 回答,缺失 CLI 给 `tabbit-cli-missing`。探针**只查 CLI 存在性**——`tabbit-cli diagnose` 的 spawn 注释写着它会冷启动浏览器,挂载期不能碰(待真机确认后再议)。
70
+ - **tabbit 盘存定时器补闸 + 修正 owner**:10 s grace / 3 s 周期的组合原本可叠 3–4 个 `tabs` 进程,且用的是虚构 task `dsh-<token('poll')>` ——按 task 隔离的 tab 归属下,它看到的是「别人」的清单,tabId 与出帧用的 `_tabbitLastTaskName` 对不上。现在串行化、查 `egoLockBusy`、无 owner 直接跳过并计数。
71
+ - **修 gateway 的冷启动旁路**:`gateway.ts` 的 `cdp-refresh` 没传 `cliProbeColdStart`,undefined 被当成「允许冷启动」——面板点一次刷新会把浏览器弹出来,而改设置不会。两条路径现在读同一个开关。
72
+ - **「当前 tab」三个写者拆成三个焦点**(本版结构改动):`TargetFocus`(host 内存,`src/runtime/focus.ts`,唯一写者是工具分派与 switch-tab)/ `ViewFocus`(面板自己的 `selectedTabId`)/ `captureTargetId`(worker 的 watch 租约)。worker 新增 `POST /api/focus`(脏 id 回 `focus-stale`,关 tab 自动清),`spaces` 增补 `activeSource` 与 `capturing`。
73
+ - **远程 CDP 面板永久空态的死锁解开**:`activeTargetId()` 原来在无本地 DevTools 端口时直接返回 `currentStatus.targetId`(watch 前恒 null → 全行 active:false),而面板只渲染 active 行、空态又不发起 watch。现在顺序是「显式焦点 → 前景观测 → 无」;前景观测本地走 `127.0.0.1:<port>/json/list`,远程由 WebSocket URL 推导 `/json/list` 基址(`src/cdp/proxy-base.ts`),代理不提供该路径时**静默降级并记住 30s**,不会每秒重打。客户端空态也退到首行而不是终态。上游 PR #12 的 `lastActivatedTargetId` 由 FocusStore 取代,#13 的 base 推导被吸收为「只观测、不决定焦点」。
74
+ - **工程闸门**:CI 加 `git diff --exit-code -- lib bin`(运行时不读 src,过期产物以前能绿);`.map` 出 git;修 `docs/ARCH.md` 的「lib 是唯一权威源」与 `cliFramePollEnabled` 的 5s→3s 文档漂移。
75
+ - **新增** `src/runtime/stats.ts` + `GET /api/bcdp/stats`:probe/tick/frame/queue 计数与 `scheduled == ran + dropped` 不变量,回答「自动机制还在干活吗」。
76
+
77
+ ### 端点对象化(结构)
78
+
79
+ - **一 link 一 runtime**:`src/runtime/backend-runtime.ts` 提供 `BackendRuntime`(`probe` / 可选 `exec` / 能力位 `localOnly`、`ownsUserBrowser`、`usesCdpWorker`、`injectsEndpoint`、`channel`)与 `runtimeOf/runtimeOfLink` 注册表;cdp / ego-cli / lightpanda / tabbit 四份实现各自一个文件。原先散布在 `refreshAttach`、`decideAttach`、工具分派、`isCliCaptureChannel`、各定时器里的 kind 梯子全部收成一个查表。
80
+ - **`decideAttach` 不再比 kind**:改读 `ownsBrowser` + `injectsEndpoint`。lightpanda 的「自己拥有 serve 但仍注入 wsUrl」这种边缘差异现在是能力位的事实,不再是特例分支。
81
+ - **操作面也归 runtime**:新增可选 `exec`,tabbit 通道通过 `setTabbitExecutor` 注入宿主实现,三处分派点改问「谁拥有这条 link」,不再问「是不是 tabbit」。
82
+ - **单一串行域**:`withEgoLock` 改为建在 `src/cast/run-queue.ts` 上(`must-run` FIFO),两个 tabbit 定时器改为 `opportunistic`(繁忙时直接丢,不排队)。原先定时器只“看”锁不“取”锁,一次 2.6s 截屏与一次工具调用会并发打同一个浏览器;现在同一条 lane 上不存在并发,也不存在丢工具调用。
83
+ - **顺手修**:`bcdp_navigate` 命中同 URL tab 时不再无条件 `switchTab`(Windows 有头会白抬一次窗口);`bridge.onChange` 的退订句柄与 `triggerCdpRef` 在卸载时清掉,热重挂载不再带着上一次 mount 的闭包去探测;`setTabbitExecutor(null)` 同批清掉。
84
+ - **测试**:新增 `runtime-registry`(四实现 × 能力位 × 错 kind 拒绝)、`run-queue`(FIFO / latest-wins / 截止中止 / 深度)、`focus-store`(单写者与 stale),`cdp-targets` 补 tabbit 探针三例。
85
+
1
86
  ## 1.9.16 (2026-11-12)
2
87
 
3
88
  **修复 `bcdp_snapshot` 的死开关:`maxChars` 补进工具 schema 声明。**
package/CHANGELOG.ru.md CHANGED
@@ -1,3 +1,7 @@
1
+ ## [1.9.17] - 2026-11-13 — Адаптивный опрос: состояние из кэша, фокус вкладки отделён от захвата
2
+
3
+ Кратко (подробности и промежуточные версии — в `CHANGELOG.md`): `bcdp_status` отвечает из кэша подключения (принудительный опрос — `refresh:true`), чтобы «проверить состояние» не стоило запуска процесса; опрос подключения получил задержку/склейку; `tabbit-cli diagnose` НЕ вызывается при монтировании (измерено: он запускает браузер); фокус вкладки разделён на три владельца (оператор/агент, панель, захват кадра), панель следует за текущей вкладкой и на удалённом CDP (база DevTools выводится из WebSocket-URL, при отсутствии `/json/*` тихо деградирует); все вызовы к одному бэкенду сериализуются одной очередью.
4
+
1
5
  ## [0.18.0] - 2026-09-29 — Линия DSH 0.2.0-rc.1 (compat/0.2.0: чисто метаданная адаптация, ноль изменений кода)
2
6
 
3
7
  ### Добавлено
package/README.md CHANGED
@@ -13,9 +13,9 @@
13
13
  [![dshfind](https://dshfind.com/api/badge/drscrewdriver/dsh-browser-cdp?lang=zh)](https://dshfind.com/zh/plugins/drscrewdriver/dsh-browser-cdp?ref=badge)
14
14
  [![dsh.so risk](https://cdn.dsh.so/badge/dsh-browser-cdp.svg)](https://www.dsh.so/artifact/dsh-browser-cdp/?ref=badge)
15
15
  [![dsh.so install · dsh 0.2.1-rc.2](https://cdn.dsh.so/badge/install/dsh-browser-cdp@0.2.1-rc.2.svg)](https://www.dsh.so/artifact/dsh-browser-cdp/?ref=badge-install)
16
- > 看得见的 Agent 浏览器(CDP 接入),同时驱动 egolite / Tabbit / Chrome / Edge / Brave / Lightpanda。常驻只有 `bcdp_status`(401 字符),其余 34 个 `bcdp_*` 工具按活动批次解锁——不碰浏览器的会话不缴 schema token 税(实测 −91.9%)。实时观察窗支持直接点击/滚动/中文输入,点选元素以 `@"picks/*.json"` 引用投进输入框,人机验证提醒;非 CDP 通道(ego CLI / Tabbit CLI)以 3s 轮询同步画面。宿主 `>=0.1.7-rc.1 <0.3.0-0`(窗口 era)。
16
+ > 看得见的 Agent 浏览器(CDP 接入),同时驱动 egolite / Tabbit / Chrome / Edge / Brave / Lightpanda。常驻只有 `bcdp_status`(401 字符),其余 34 个 `bcdp_*` 工具按活动批次解锁——不碰浏览器的会话不缴 schema token 税(实测 −91.9%)。实时观察窗支持直接点击/滚动/中文输入,点选元素以 `@"picks/*.json"` 引用投进输入框,人机验证提醒;非 CDP 通道(ego CLI / Tabbit CLI)以 3s 轮询同步画面。宿主 `>=0.1.7-rc.1 <0.3.0-0`(窗口 era,production);下行 `0.1.0-rc.2 ~ 0.1.5-rc.3` 走命令式 installSection / 模块级注册 + describe/mutate 桥与 gen-1 齿轮(experimental,待逐线 farm 实测)。
17
17
  >
18
- > Visible agent browser for DSH over CDP, also driving egolite / Tabbit / Chrome / Edge / Brave / Lightpanda. Only `bcdp_status` stays resident (401 chars); the other 34 context-optimized `bcdp_*` tools unlock per activity batch, so non-browser sessions pay no schema tax (−91.9% measured). Realtime watch panel with direct click/scroll/IME, element picks quoted into the composer as `@"picks/*.json"`, human-verification notices; non-CDP channels (ego CLI / Tabbit CLI) sync frames by 3s polling. Host `>=0.1.7-rc.1 <0.3.0-0` (window era).
18
+ > Visible agent browser for DSH over CDP, also driving egolite / Tabbit / Chrome / Edge / Brave / Lightpanda. Only `bcdp_status` stays resident (401 chars); the other 34 context-optimized `bcdp_*` tools unlock per activity batch, so non-browser sessions pay no schema tax (−91.9% measured). Realtime watch panel with direct click/scroll/IME, element picks quoted into the composer as `@"picks/*.json"`, human-verification notices; non-CDP channels (ego CLI / Tabbit CLI) sync frames by 3s polling. Host `>=0.1.7-rc.1 <0.3.0-0` (window era, production); the down-line `0.1.0-rc.2 ~ 0.1.5-rc.3` uses imperative installSection / module-level registration + describe/mutate bridge and a Gen-1 gear (experimental, pending per-line farm).
19
19
 
20
20
  [简体中文](README.md) | [Français](README.fr.md) | [Deutsch](README.de.md) | [Italiano](README.it.md) | [Русский](README.ru.md) | [Español](README.es.md)
21
21
 
@@ -34,6 +34,49 @@ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__ge
34
34
  }) : target, mod));
35
35
  var __require = /* @__PURE__ */ createRequire(import.meta.url);
36
36
 
37
+ //#endregion
38
+ //#region src/cdp/proxy-base.ts
39
+ /**
40
+ * src/cdp/proxy-base.ts — the HTTP face of a CDP PROXY.
41
+ *
42
+ * A remote attach hands over only a WebSocket URL. Proxies (CloakBrowser and
43
+ * friends) serve `/json/*` under the SAME path the socket lives on, so the
44
+ * DevTools HTTP base is derivable without asking anybody:
45
+ *
46
+ * wss://host/api/profiles/<id>/cdp → https://host/api/profiles/<id>/cdp
47
+ * ws://host:9222/devtools/browser/x → http://host:9222/devtools/browser/x
48
+ *
49
+ * Two rules matter: swap the scheme (ws→http, wss→https) and keep the path that
50
+ * the PROXY was mounted under — but DROP a plain DevTools socket path, because
51
+ * for those the HTTP face is the origin itself:
52
+ *
53
+ * wss://host/api/profiles/x/cdp → https://host/api/profiles/x/cdp + /json/list
54
+ * ws://127.0.0.1:9337/devtools/browser/<uuid>
55
+ * → http://127.0.0.1:9337 + /json/list
56
+ *
57
+ * That second case is not hypothetical: appending `/json/list` to the DevTools
58
+ * socket path yields 404, the observation silently degrades, and the panel looks
59
+ * like it has no foreground at all. Unparseable input returns null; this never
60
+ * throws, because it runs inside a 1 s snapshot tick.
61
+ *
62
+ * Lives here (not in the worker) so it can be unit-tested: importing the worker
63
+ * module starts the worker.
64
+ */
65
+ function proxyBase(wsUrl) {
66
+ const raw = String(wsUrl ?? "").trim();
67
+ if (raw === "") return null;
68
+ try {
69
+ const url = new URL(raw);
70
+ if (url.protocol !== "ws:" && url.protocol !== "wss:") return null;
71
+ const scheme = url.protocol === "wss:" ? "https:" : "http:";
72
+ const devtoolsAt = url.pathname.indexOf("/devtools/");
73
+ const path = devtoolsAt >= 0 ? url.pathname.slice(0, devtoolsAt) : url.pathname;
74
+ return `${scheme}//${url.host}${path.replace(/\/+$/, "")}`;
75
+ } catch {
76
+ return null;
77
+ }
78
+ }
79
+
37
80
  //#endregion
38
81
  //#region node_modules/ws/lib/constants.js
39
82
  var require_constants = /* @__PURE__ */ __commonJS({ "node_modules/ws/lib/constants.js": ((exports, module) => {
@@ -6501,6 +6544,14 @@ let currentStatus = {
6501
6544
  generation: 0,
6502
6545
  watchers: 0
6503
6546
  };
6547
+ /**
6548
+ * The tab the OPERATION side owns (`POST /api/focus`), or null when nobody owns
6549
+ * one yet. Deliberately NOT the capture lease: `currentStatus.targetId` answers
6550
+ * "what is being screencast", which is a consequence of a watch, not a choice
6551
+ * the user made. Keeping them apart is what stops the panel highlight from
6552
+ * snapping back after a tab click (see src/runtime/focus.ts).
6553
+ */
6554
+ let focusTargetId = null;
6504
6555
  let videoInit = null;
6505
6556
  function normalizeConfig(input) {
6506
6557
  const next = { ...castConfig };
@@ -6719,24 +6770,131 @@ async function listTargets() {
6719
6770
  if (!active) return [];
6720
6771
  return ((await active.cdp.call("Target.getTargets")).targetInfos || []).filter((target) => target.type === "page");
6721
6772
  }
6722
- async function activeTargetId() {
6723
- if (!active?.port) return currentStatus.targetId || null;
6773
+ /**
6774
+ * Where to ask "which page is in front". One code path serves both launches:
6775
+ * a local launcher gives a loopback DevTools port, a remote attach gives only a
6776
+ * WebSocket URL (and possibly a proxy that speaks `/json/*`).
6777
+ */
6778
+ async function devtoolsBase(browser) {
6779
+ if (browser === null) return null;
6780
+ if (browser.port !== null) return {
6781
+ base: `http://127.0.0.1:${browser.port}`,
6782
+ remote: false
6783
+ };
6784
+ const base = proxyBase(browser.wsUrl);
6785
+ return base === null ? null : {
6786
+ base,
6787
+ remote: true
6788
+ };
6789
+ }
6790
+ /**
6791
+ * Remote foreground observation, cached.
6792
+ *
6793
+ * Two things must be cheap here because this runs on the 1s spaces tick: the
6794
+ * success answer is reused for a second, and a proxy that does NOT serve
6795
+ * `/json/*` is remembered for a while instead of being re-asked every tick
6796
+ * (a 404 every second would be noise in the logs for the whole session).
6797
+ */
6798
+ const proxyObserveCache = {
6799
+ at: 0,
6800
+ id: null,
6801
+ failedUntil: 0,
6802
+ base: ""
6803
+ };
6804
+ /**
6805
+ * Which tab is "current", and WHY.
6806
+ *
6807
+ * This used to be one expression with three competing sources, which is how the
6808
+ * panel ended up disagreeing with itself:
6809
+ * - `currentStatus.targetId` — the tab being CAPTURED (a watch lease). Using
6810
+ * it as "active" left every row `active:false` until a watch started, and
6811
+ * the panel (which renders active rows only) then never started one: a
6812
+ * deadlock, not a glitch.
6813
+ * - `/json/list` first page — the FOREGROUND tab. Correct for a local launch
6814
+ * (the user really is switching tabs in that window) and, through the proxy
6815
+ * path, for a remote one too; a proxy that cannot answer is "no
6816
+ * observation", never an error.
6817
+ * - the panel's own selection — belongs to the view focus, not here.
6818
+ *
6819
+ * Order: explicit host focus (validated against the live list) → foreground
6820
+ * observation (local port, else remote proxy) → none. `known` lets the caller
6821
+ * pass the target list it already fetched, so a closed tab cannot keep the
6822
+ * highlight.
6823
+ */
6824
+ async function activeTargetInfo(known) {
6825
+ const inKnown = (id) => known === void 0 || known.includes(id);
6826
+ if (focusTargetId !== null && inKnown(focusTargetId)) return {
6827
+ id: focusTargetId,
6828
+ source: "focus"
6829
+ };
6830
+ const target = await devtoolsBase(active);
6831
+ if (target === null) return {
6832
+ id: null,
6833
+ source: "none"
6834
+ };
6835
+ const now = Date.now();
6836
+ if (target.remote && now < proxyObserveCache.failedUntil) return {
6837
+ id: null,
6838
+ source: "none"
6839
+ };
6840
+ if (target.remote && proxyObserveCache.base === target.base && now - proxyObserveCache.at < 1e3) return proxyObserveCache.id === null ? {
6841
+ id: null,
6842
+ source: "none"
6843
+ } : {
6844
+ id: proxyObserveCache.id,
6845
+ source: "foreground-remote"
6846
+ };
6724
6847
  try {
6725
- const response = await fetch(`http://127.0.0.1:${active.port}/json/list`, { signal: AbortSignal.timeout(1500) });
6726
- return (response.ok ? await response.json() : []).find((entry) => entry.type === "page")?.id || currentStatus.targetId || null;
6848
+ const response = await fetch(`${target.base}/json/list`, { signal: AbortSignal.timeout(1500) });
6849
+ if (!response.ok) {
6850
+ if (target.remote) {
6851
+ proxyObserveCache.failedUntil = now + 3e4;
6852
+ proxyObserveCache.base = target.base;
6853
+ }
6854
+ return {
6855
+ id: null,
6856
+ source: "none"
6857
+ };
6858
+ }
6859
+ const id = (await response.json()).find((entry) => entry.type === "page")?.id ?? null;
6860
+ if (target.remote) {
6861
+ proxyObserveCache.at = now;
6862
+ proxyObserveCache.id = id;
6863
+ proxyObserveCache.base = target.base;
6864
+ proxyObserveCache.failedUntil = 0;
6865
+ }
6866
+ if (id !== null && inKnown(id)) return {
6867
+ id,
6868
+ source: target.remote ? "foreground-remote" : "foreground"
6869
+ };
6727
6870
  } catch {
6728
- return currentStatus.targetId || null;
6871
+ if (target.remote) {
6872
+ proxyObserveCache.failedUntil = now + 3e4;
6873
+ proxyObserveCache.base = target.base;
6874
+ }
6729
6875
  }
6876
+ return {
6877
+ id: null,
6878
+ source: "none"
6879
+ };
6880
+ }
6881
+ /** String-only view of `activeTargetInfo` for the single-target routes. */
6882
+ async function activeTargetId() {
6883
+ return (await activeTargetInfo()).id;
6730
6884
  }
6731
6885
  async function snapshotSpaces() {
6886
+ const browser = active;
6887
+ if (browser === null) return [];
6732
6888
  const targets = await listTargets();
6733
- const activeId = await activeTargetId();
6889
+ const activeInfo = await activeTargetInfo(targets.map((target) => target.targetId));
6890
+ const activeId = activeInfo.id;
6891
+ const capturingId = currentStatus.targetId;
6734
6892
  const spaces = [];
6735
6893
  for (const target of targets.slice(0, 30)) {
6736
6894
  const frame = frameCache.get(target.targetId);
6737
- const session = active.sessions.get(target.targetId);
6895
+ const session = browser.sessions.get(target.targetId);
6738
6896
  const cached = probeCache.get(target.targetId);
6739
- if (!cached || Date.now() - cached.at > 5e3) active.sessions.call(target.targetId, "Runtime.evaluate", {
6897
+ if (!cached || Date.now() - cached.at > 5e3) browser.sessions.call(target.targetId, "Runtime.evaluate", {
6740
6898
  expression: HUMAN_PROBE_JS,
6741
6899
  returnByValue: true,
6742
6900
  awaitPromise: false
@@ -6752,6 +6910,8 @@ async function snapshotSpaces() {
6752
6910
  url: target.url,
6753
6911
  title: target.title,
6754
6912
  active: target.targetId === activeId,
6913
+ activeSource: target.targetId === activeId ? activeInfo.source : "",
6914
+ capturing: target.targetId === capturingId,
6755
6915
  lastActive: frame?.lastActive || 0,
6756
6916
  viewportW: frame?.viewportW || session?.viewportW,
6757
6917
  viewportH: frame?.viewportH || session?.viewportH,
@@ -7067,13 +7227,41 @@ async function main() {
7067
7227
  });
7068
7228
  }
7069
7229
  }
7230
+ if (req.method === "POST" && url.pathname === "/api/focus") {
7231
+ if (!active) return sendJson(res, 409, {
7232
+ ok: false,
7233
+ error: "no live browser"
7234
+ });
7235
+ const body = await readJson(req);
7236
+ const targetId = typeof body?.targetId === "string" ? body.targetId.trim() : "";
7237
+ if (targetId === "") {
7238
+ focusTargetId = null;
7239
+ return sendJson(res, 200, {
7240
+ ok: true,
7241
+ cleared: true
7242
+ });
7243
+ }
7244
+ if (!(await listTargets()).map((target) => target.targetId).includes(targetId)) return sendJson(res, 409, {
7245
+ ok: false,
7246
+ code: "focus-stale",
7247
+ error: "that target is gone",
7248
+ targetId
7249
+ });
7250
+ focusTargetId = targetId;
7251
+ return sendJson(res, 200, {
7252
+ ok: true,
7253
+ targetId
7254
+ });
7255
+ }
7070
7256
  if (req.method === "POST" && url.pathname === "/api/close") {
7071
- const { targetId } = await readJson(req);
7257
+ const body = await readJson(req);
7258
+ const targetId = typeof body?.targetId === "string" ? body.targetId : "";
7072
7259
  if (!active || !targetId) return sendJson(res, 400, {
7073
7260
  ok: false,
7074
7261
  error: "targetId required"
7075
7262
  });
7076
7263
  await active.cdp.call("Target.closeTarget", { targetId });
7264
+ if (focusTargetId === targetId) focusTargetId = null;
7077
7265
  return sendJson(res, 200, { ok: true });
7078
7266
  }
7079
7267
  if (req.method === "POST" && url.pathname === "/api/switch-tab") {
@@ -7085,6 +7273,7 @@ async function main() {
7085
7273
  });
7086
7274
  try {
7087
7275
  await active.cdp.call("Target.activateTarget", { targetId });
7276
+ focusTargetId = targetId;
7088
7277
  return sendJson(res, 200, {
7089
7278
  ok: true,
7090
7279
  targetId
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.9.16",
5
+ "version": "1.9.51",
6
6
  "manifestVersion": "0.15",
7
7
  "facets": {
8
8
  "host": {