dsh-browser-cdp 1.14.12 → 1.14.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/CHANGELOG.md CHANGED
@@ -1,3 +1,38 @@
1
+ # Changelog
2
+
3
+ ## 1.14.14 (2026-11-25)
4
+
5
+ **修复 #20:观察窗焊死在旧实例 / 「不关浏览器也卡 New Tab」——两处独立缺陷,分开修。**
6
+
7
+ 报告人(MOYU126)的现象由两个不同源的成因拼成,本版逐一处理:
8
+
9
+ ### 一、端点权威(R1:端口漂移后面板不跟随)
10
+
11
+ - `resolveBrowser()` 不再把 `EGO_LINUX_CDP_URL`(spawn 时刻的快照)当真理:改为 **browser.json / launcher.json 状态文件候选 + 逐个 `/json/version` 活体探测(1s 超时),env 仅在候选全灭后兜底**。idle 关闭重开、端口 40025→33253 漂移时观察窗自动跟随新实例,无需重启引擎。
12
+ - **实例身份 + 强制换代**:`connectLoop` 过去只在 ws 断开后重解析——旧端口上若另有一只活浏览器,连接永不断、永不换。现在每条连接携带 `instanceKey = pid:port`,独立 5s watcher 比对权威实例,不同才 `ws.close()` 换代(日志 `endpoint replaced: old -> new`);无新候选时绝不动现有连接。
13
+ - 回环候选一律回传**数值 port**,`devtoolsBase()` 从此走 local 分支,绕开 `proxyObserveCache` 的 30s 失败毒化(一次本地抖动不再让前台观测哑 30 秒)。
14
+ - **远端 CDP 不回归(#12)**:env host 非回环(含代理前缀)时 env 仍是唯一权威,不做回环探测、不被状态文件覆盖;watcher 整体停用。Lightpanda 后端(`launcher.json.engine === 'lightpanda'`)走同一端口探测路径。
15
+ - 实现下沉到新模块 `src/worker/endpoint-authority.ts`(fs/net/clock 全注入,零新依赖);探测预算:状态文件 mtime+port 未变则 0 网络,稳态反查节流至 ~15s 一次。
16
+
17
+ ### 二、前景选择(R2:不关浏览器也卡 New Tab)
18
+
19
+ - 该症状与端口漂移无关:`activeTargetInfo()` 的前台兜底取的是 `/json/list` 的首个 page,而列表顺序≠前台顺序,新标签页常排第一(旧注释「first page — the FOREGROUND tab」的假设不成立)。focus 通道未命中时面板就挂到 New Tab 上。
20
+ - 现在 `HUMAN_PROBE_JS` 同一次 `Runtime.evaluate` 多带回 `visibilityState`(零额外调用,与 1.14.11 加 `readyState`/`dpr` 同模式),本地前景选择改为:**per-session focus(#15,不动)→ global focus → `visibilityState === 'visible'` 页 → 非 newtab/about:blank/startpage 首个页 → none**;`spaces` 行另透 `visibility` 字段,SSE 形状不变,客户端零改动。远端代理路径无逐页探针条件,维持首个 page 语义。
21
+
22
+ ### 三、前提更正与致谢
23
+
24
+ - 报告人推测「1.14.10 改成 env 优先 / 丢掉 launcher.json 多候选」经 tarball 逐版核对不成立:env 优先至少自 1.5.0 就在,worker 从未读过 launcher.json;升级即坏的感觉来自上述两个既有缺陷在新构建中显形。但其端口漂移序列、四轮 workaround 验证与「状态文件候选→探测→env 兜底」的期望顺序全部可信,本版的候选顺序即采纳其方案(仅对远端 env 保留例外)。
25
+ - 新增 `tests/worker-endpoint-authority.test.ts`(19 例:候选收集/活体探测/远端例外/指纹零网络/换代契约)与 `active-space.test.ts` H 组(5 例:可见性链/全 hidden 退化/单页原样/远端首 page 保留)。Android/proot 环境本地无法复现报告人宿主,落地实测以 Windows 本机 + 单测为准,Android 侧待报告人复验。
26
+
27
+ 门禁:typecheck 双 project 干净;`npm test` 1422 passed / 13 skipped;build 后 `bin/cdp-cast-worker.mjs` 含 `instanceKey`×13 / `visibilityState`×12 / `endpoint replaced`。
28
+
29
+ ## 1.14.13 (2026-11-25)
30
+
31
+ **「重新查看引导」按钮改为圆角描边胶囊(对齐统一引导件新样式)。**
32
+
33
+ - 上一版发出去的仍是旧的下划线文字链接:统一引导真源 `_tools/guide-kit/guide.tsx` 已把 `.sgGuideRestart` 换成 `border-radius:999px` + 1px 描边 + 微底 + hover 主色强调(参照 dsh-prime-memory `8a530f0` 的按钮调整),但本仓 `lib/client.js` 没跟着重建,于是 1.14.12 在分节顶部把这个链接挤成一个小方框。
34
+ - 本版只重建产物并补一个补丁版:`src/client/guide.tsx` 与真源逐字一致(`guide-kit sync --check` 通过),引导步骤、跳过标记、入口位置均与 1.14.12 一致,无行为变更。
35
+
1
36
  ## 1.14.12 (2026-11-25)
2
37
 
3
38
  **引导重开入口从分节底部移到上方。**
@@ -413,14 +413,14 @@ var require_permessage_deflate = /* @__PURE__ */ __commonJS({ "node_modules/ws/l
413
413
  value = value[0];
414
414
  if (key === "client_max_window_bits") {
415
415
  if (value !== true) {
416
- const num = +value;
417
- if (!Number.isInteger(num) || num < 8 || num > 15) throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
418
- value = num;
416
+ const num$1 = +value;
417
+ if (!Number.isInteger(num$1) || num$1 < 8 || num$1 > 15) throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
418
+ value = num$1;
419
419
  } else if (!this._isServer) throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
420
420
  } else if (key === "server_max_window_bits") {
421
- const num = +value;
422
- if (!Number.isInteger(num) || num < 8 || num > 15) throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
423
- value = num;
421
+ const num$1 = +value;
422
+ if (!Number.isInteger(num$1) || num$1 < 8 || num$1 > 15) throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
423
+ value = num$1;
424
424
  } else if (key === "client_no_context_takeover" || key === "server_no_context_takeover") {
425
425
  if (value !== true) throw new TypeError(`Invalid value for parameter "${key}": ${value}`);
426
426
  } else throw new Error(`Unknown parameter "${key}"`);
@@ -1032,12 +1032,12 @@ var require_receiver = /* @__PURE__ */ __commonJS({ "node_modules/ws/lib/receive
1032
1032
  return;
1033
1033
  }
1034
1034
  const buf = this.consume(8);
1035
- const num = buf.readUInt32BE(0);
1036
- if (num > Math.pow(2, 21) - 1) {
1035
+ const num$1 = buf.readUInt32BE(0);
1036
+ if (num$1 > Math.pow(2, 21) - 1) {
1037
1037
  cb(this.createError(RangeError, "Unsupported WebSocket frame: payload length > 2^53 - 1", false, 1009, "WS_ERR_UNSUPPORTED_DATA_PAYLOAD_LENGTH"));
1038
1038
  return;
1039
1039
  }
1040
- this._payloadLength = num * Math.pow(2, 32) + buf.readUInt32BE(4);
1040
+ this._payloadLength = num$1 * Math.pow(2, 32) + buf.readUInt32BE(4);
1041
1041
  this.haveLength(cb);
1042
1042
  }
1043
1043
  /**
@@ -6624,6 +6624,215 @@ function aspectHeight(width, aspect, fallbackHeight) {
6624
6624
  return Math.round(width * ratio);
6625
6625
  }
6626
6626
 
6627
+ //#endregion
6628
+ //#region src/worker/endpoint-authority.ts
6629
+ /** pid:port identity of one browser instance; stable across ws reconnects. */
6630
+ function instanceKey(pid, port) {
6631
+ return `${pid ?? "nopid"}:${port ?? "noport"}`;
6632
+ }
6633
+ const LOOPBACK_HOSTS = new Set([
6634
+ "127.0.0.1",
6635
+ "localhost",
6636
+ "0.0.0.0",
6637
+ "::1",
6638
+ "[::1]"
6639
+ ]);
6640
+ /**
6641
+ * Is this host (or ws/http URL host segment) loopback? A proxy-prefixed host
6642
+ * segment like "gateway.corp:8443/127.0.0.1" is NOT loopback — that is a remote
6643
+ * path and keeps env authority (#12 regression guard).
6644
+ */
6645
+ function isLoopbackHost(host) {
6646
+ return LOOPBACK_HOSTS.has(host.toLowerCase());
6647
+ }
6648
+ function num(v) {
6649
+ return typeof v === "number" && Number.isFinite(v) && v > 0 ? v : null;
6650
+ }
6651
+ function str(v) {
6652
+ return typeof v === "string" && v !== "" ? v : null;
6653
+ }
6654
+ /** browser.json / launcher.json share one shape interest: port + optional ws endpoint + pid. */
6655
+ function stateRecord(raw, source, fresh) {
6656
+ if (raw === null) return null;
6657
+ const port = num(raw.port);
6658
+ if (port === null) return null;
6659
+ return {
6660
+ port,
6661
+ wsUrl: str(raw.wsUrl) ?? (str(raw.endpoint)?.startsWith("ws") ? str(raw.endpoint) : null),
6662
+ pid: num(raw.pid),
6663
+ source,
6664
+ fresh
6665
+ };
6666
+ }
6667
+ /** Parse EGO_LINUX_CDP_URL into a candidate; unparseable (proxy-prefixed) URLs keep env-source with wsUrl only. */
6668
+ function envCandidate(env) {
6669
+ const raw = env.EGO_LINUX_CDP_URL;
6670
+ if (!raw) return null;
6671
+ let parsed = null;
6672
+ try {
6673
+ parsed = new URL(raw);
6674
+ } catch {
6675
+ parsed = null;
6676
+ }
6677
+ if (parsed === null || !isLoopbackHost(parsed.hostname)) return {
6678
+ port: null,
6679
+ wsUrl: raw,
6680
+ pid: null,
6681
+ source: "env",
6682
+ fresh: 0,
6683
+ trustWsUrl: true
6684
+ };
6685
+ return {
6686
+ port: num(Number(parsed.port)),
6687
+ wsUrl: raw,
6688
+ pid: null,
6689
+ source: "env",
6690
+ fresh: 0
6691
+ };
6692
+ }
6693
+ /**
6694
+ * Build the resolver bound to one set of state paths. `fingerprint()` lets the
6695
+ * 5s watcher skip ALL probing (zero network) while neither mtime nor the
6696
+ * recorded port changed; `remoteAuthoritative()` gates the whole watcher off
6697
+ * for remote env.
6698
+ */
6699
+ function createEndpointResolver(io, paths) {
6700
+ const envRemote = () => {
6701
+ const c = envCandidate(io.env);
6702
+ return c !== null && c.source === "env" && c.port === null;
6703
+ };
6704
+ async function collectCandidates() {
6705
+ const [stateMtime, launcherMtime, stateRaw, launcherRaw] = await Promise.all([
6706
+ io.statMtime(paths.browserStatePath),
6707
+ io.statMtime(paths.launcherStatePath),
6708
+ io.readJson(paths.browserStatePath),
6709
+ io.readJson(paths.launcherStatePath)
6710
+ ]);
6711
+ const out = [];
6712
+ const state = stateRecord(stateRaw, "state", stateMtime);
6713
+ if (state) out.push({
6714
+ ...state,
6715
+ fresh: Math.max(stateMtime, state.fresh)
6716
+ });
6717
+ const launcher = stateRecord(launcherRaw, "launcher", launcherMtime);
6718
+ if (launcher) out.push({
6719
+ ...launcher,
6720
+ fresh: Math.max(launcherMtime, launcher.fresh)
6721
+ });
6722
+ const candidates = out.map((r) => ({
6723
+ port: r.port,
6724
+ wsUrl: r.wsUrl,
6725
+ pid: r.pid,
6726
+ source: r.source,
6727
+ fresh: r.fresh
6728
+ }));
6729
+ candidates.sort((a, b) => Number(io.isAlive(b.pid ?? -1)) - Number(io.isAlive(a.pid ?? -1)) || b.fresh - a.fresh);
6730
+ return candidates;
6731
+ }
6732
+ async function probeCandidate(c) {
6733
+ if (c.trustWsUrl === true && c.wsUrl !== null) return {
6734
+ wsUrl: c.wsUrl,
6735
+ port: c.port,
6736
+ pid: c.pid,
6737
+ instanceKey: instanceKey(c.pid, c.port)
6738
+ };
6739
+ if (c.port === null) return null;
6740
+ const version = await io.fetchVersion(`http://127.0.0.1:${c.port}/json/version`);
6741
+ if (version === null) return null;
6742
+ const wsUrl = c.wsUrl ?? str(version.wsUrl);
6743
+ if (wsUrl === null) return null;
6744
+ return {
6745
+ wsUrl,
6746
+ port: c.port,
6747
+ pid: c.pid,
6748
+ instanceKey: instanceKey(c.pid, c.port)
6749
+ };
6750
+ }
6751
+ async function resolve() {
6752
+ const env = envCandidate(io.env);
6753
+ if (env !== null && env.trustWsUrl === true) return {
6754
+ wsUrl: env.wsUrl,
6755
+ port: null,
6756
+ pid: null,
6757
+ instanceKey: instanceKey(null, null)
6758
+ };
6759
+ const candidates = await collectCandidates();
6760
+ for (const c of candidates) {
6761
+ const hit = await probeCandidate(c);
6762
+ if (hit !== null) return hit;
6763
+ }
6764
+ if (env !== null && env.source === "env") {
6765
+ const hit = await probeCandidate(env);
6766
+ if (hit !== null) return hit;
6767
+ if (env.wsUrl !== null && env.port === null) return {
6768
+ wsUrl: env.wsUrl,
6769
+ port: null,
6770
+ pid: null,
6771
+ instanceKey: instanceKey(null, null)
6772
+ };
6773
+ }
6774
+ return null;
6775
+ }
6776
+ async function fingerprint() {
6777
+ const [a, b, stateRaw, launcherRaw] = await Promise.all([
6778
+ io.statMtime(paths.browserStatePath),
6779
+ io.statMtime(paths.launcherStatePath),
6780
+ io.readJson(paths.browserStatePath),
6781
+ io.readJson(paths.launcherStatePath)
6782
+ ]);
6783
+ const state = stateRecord(stateRaw, "state", a);
6784
+ const launcher = stateRecord(launcherRaw, "launcher", b);
6785
+ return `${a}:${state?.port ?? "-"}|${b}:${launcher?.port ?? "-"}`;
6786
+ }
6787
+ return {
6788
+ resolve,
6789
+ fingerprint,
6790
+ remoteAuthoritative: envRemote
6791
+ };
6792
+ }
6793
+ /** Pages that mean "nothing is being looked at"; ordering around them is what the New Tab bug is. */
6794
+ const BLANK_PAGE_URLS = [
6795
+ "chrome://newtab",
6796
+ "about:blank",
6797
+ "chrome://startpage",
6798
+ "edge://newtab",
6799
+ "data:,"
6800
+ ];
6801
+ function isBlankPageUrl(url) {
6802
+ if (!url) return true;
6803
+ const u = url.trim().toLowerCase();
6804
+ return BLANK_PAGE_URLS.includes(u);
6805
+ }
6806
+ /**
6807
+ * Pick the foreground page from a `/json/list` page set.
6808
+ *
6809
+ * The old code took the FIRST `type === 'page'` entry and commented it as
6810
+ * "the FOREGROUND tab" — the assumption never held: a freshly opened New Tab
6811
+ * usually sorts first, so the panel snapped to it (findings F3). Order:
6812
+ * 1. the page whose visibilityState === 'visible' (local only — a remote
6813
+ * proxy cannot answer per-page probes, so callers keep first-page there)
6814
+ * 2. the first non-blank page
6815
+ * 3. the first page (last resort; a single-tab browser lands here)
6816
+ *
6817
+ * The getter may be sync (tests, warm cache) or async (one per-target CDP
6818
+ * evaluate); every answer is requested up front, so async probes run in
6819
+ * parallel and the hot path pays one round-trip, not N.
6820
+ */
6821
+ async function pickForegroundId(pages, visibility) {
6822
+ if (pages.length === 0) return null;
6823
+ const seen = await Promise.all(pages.map((p) => Promise.resolve(visibility(p.id)).catch(() => void 0)));
6824
+ const hit = pages.findIndex((_, i) => seen[i] === "visible");
6825
+ if (hit >= 0) return pages[hit].id;
6826
+ const real = pages.findIndex((p) => !isBlankPageUrl(p.url));
6827
+ return real >= 0 ? pages[real].id : pages[0].id;
6828
+ }
6829
+
6830
+ //#endregion
6831
+ //#region src/cdp/launcher.ts
6832
+ function defaultLauncherStatePath() {
6833
+ return join(homedir(), ".dsh", "cache", "dsh-browser-cdp", "launcher.json");
6834
+ }
6835
+
6627
6836
  //#endregion
6628
6837
  //#region src/worker/cdp-cast-worker.ts
6629
6838
  const SENTINEL = "@@DSH_RESULT@@";
@@ -6661,17 +6870,19 @@ try {
6661
6870
  };
6662
6871
  } catch {}
6663
6872
  /**
6664
- * One Runtime.evaluate answers three questions the panel used to guess at:
6873
+ * One Runtime.evaluate answers four questions the panel used to guess at:
6665
6874
  * `humanCheck` (unchanged), `readyState` (a page still loading looks dead in a
6666
- * screenshot) and `dpr` (a 1.25 phone-preview layout explains "why is the text
6667
- * smaller"). All three ride the SAME 5s-throttled probe — no extra CDP call.
6875
+ * screenshot), `dpr` (a 1.25 phone-preview layout explains "why is the text
6876
+ * smaller") and — #20 — `visibilityState` (a background tab reports 'hidden',
6877
+ * which is the only reliable "which tab is the user actually looking at").
6878
+ * All four ride the SAME 5s-throttled probe — no extra CDP call.
6668
6879
  */
6669
6880
  const HUMAN_PROBE_JS = `(() => {
6670
- const readyState=document.readyState,dpr=(window.devicePixelRatio||1);
6881
+ const readyState=document.readyState,dpr=(window.devicePixelRatio||1),visibilityState=document.visibilityState;
6671
6882
  const el=document.querySelector('iframe[src*="recaptcha"],.g-recaptcha,.h-captcha,iframe[src*="hcaptcha"],.cf-turnstile,iframe[src*="turnstile"],iframe[src*="cloudflare"],#challenge-form,.challenge-form,#captcha,.captcha');
6672
- if(el)return{detected:true,kind:/recaptcha/i.test(el.outerHTML)?'recaptcha':/hcaptcha/i.test(el.outerHTML)?'hcaptcha':/turnstile/i.test(el.outerHTML)?'turnstile':'captcha',readyState:readyState,dpr:dpr};
6883
+ if(el)return{detected:true,kind:/recaptcha/i.test(el.outerHTML)?'recaptcha':/hcaptcha/i.test(el.outerHTML)?'hcaptcha':/turnstile/i.test(el.outerHTML)?'turnstile':'captcha',readyState:readyState,dpr:dpr,visibilityState:visibilityState};
6673
6884
  const t=((document.body&&document.body.innerText)||'').slice(0,120000).toLowerCase();
6674
- return /verify you are human|your activity looks unusual|captcha|i.?m not a robot|人机验证|安全验证|我是人类|验证码|滑块验证/.test(t)?{detected:true,kind:'captcha',readyState:readyState,dpr:dpr}:{detected:false,kind:null,readyState:readyState,dpr:dpr};
6885
+ return /verify you are human|your activity looks unusual|captcha|i.?m not a robot|人机验证|安全验证|我是人类|验证码|滑块验证/.test(t)?{detected:true,kind:'captcha',readyState:readyState,dpr:dpr,visibilityState:visibilityState}:{detected:false,kind:null,readyState:readyState,dpr:dpr,visibilityState:visibilityState};
6675
6886
  })()`;
6676
6887
  const sseClients = /* @__PURE__ */ new Set();
6677
6888
  const videoClients = /* @__PURE__ */ new Set();
@@ -6920,30 +7131,53 @@ const manager = new CaptureManager({
6920
7131
  }
6921
7132
  }
6922
7133
  });
6923
- async function readBrowserState() {
6924
- try {
6925
- return JSON.parse(await import("node:fs/promises").then((fs) => fs.readFile(BROWSER_STATE_FILE, "utf8")));
6926
- } catch {
6927
- return null;
6928
- }
6929
- }
7134
+ /**
7135
+ * #20 — the endpoint resolver. io.fs/net are the only place this worker touches
7136
+ * state files or /json/version for AUTHORITY purposes; every function falls
7137
+ * back silently (a missing/bad file is "no candidate", never an error).
7138
+ */
7139
+ const fsp = await import("node:fs/promises");
7140
+ const endpointIO = {
7141
+ statMtime: async (p) => {
7142
+ try {
7143
+ return (await fsp.stat(p)).mtimeMs;
7144
+ } catch {
7145
+ return -1;
7146
+ }
7147
+ },
7148
+ readJson: async (p) => {
7149
+ try {
7150
+ return JSON.parse(await fsp.readFile(p, "utf8"));
7151
+ } catch {
7152
+ return null;
7153
+ }
7154
+ },
7155
+ fetchVersion: async (u) => {
7156
+ try {
7157
+ const r = await fetch(u, { signal: AbortSignal.timeout(1e3) });
7158
+ if (!r.ok) return null;
7159
+ const j = await r.json();
7160
+ return { wsUrl: typeof j.webSocketDebuggerUrl === "string" ? j.webSocketDebuggerUrl : void 0 };
7161
+ } catch {
7162
+ return null;
7163
+ }
7164
+ },
7165
+ isAlive: (pid) => {
7166
+ try {
7167
+ process.kill(pid, 0);
7168
+ return true;
7169
+ } catch {
7170
+ return false;
7171
+ }
7172
+ },
7173
+ env: process.env
7174
+ };
7175
+ const endpointResolver = createEndpointResolver(endpointIO, {
7176
+ browserStatePath: BROWSER_STATE_FILE,
7177
+ launcherStatePath: defaultLauncherStatePath()
7178
+ });
6930
7179
  async function resolveBrowser() {
6931
- if (process.env.EGO_LINUX_CDP_URL) return {
6932
- wsUrl: process.env.EGO_LINUX_CDP_URL,
6933
- port: null
6934
- };
6935
- const state = await readBrowserState();
6936
- if (!state?.port) return null;
6937
- try {
6938
- const response = await fetch(`http://127.0.0.1:${state.port}/json/version`, { signal: AbortSignal.timeout(1500) });
6939
- const wsUrl = response.ok ? (await response.json()).webSocketDebuggerUrl : null;
6940
- return wsUrl ? {
6941
- port: state.port ?? null,
6942
- wsUrl
6943
- } : null;
6944
- } catch {
6945
- return null;
6946
- }
7180
+ return endpointResolver.resolve();
6947
7181
  }
6948
7182
  async function listTargets() {
6949
7183
  if (!active) return [];
@@ -6989,16 +7223,18 @@ const proxyObserveCache = {
6989
7223
  * it as "active" left every row `active:false` until a watch started, and
6990
7224
  * the panel (which renders active rows only) then never started one: a
6991
7225
  * deadlock, not a glitch.
6992
- * - `/json/list` first page — the FOREGROUND tab. Correct for a local launch
6993
- * (the user really is switching tabs in that window) and, through the proxy
6994
- * path, for a remote one too; a proxy that cannot answer is "no
6995
- * observation", never an error.
7226
+ * - `/json/list` foreground pick — the tab the USER is looking at. The old
7227
+ * "first page" rule was a wrong assumption (#20 / findings F3): a freshly
7228
+ * opened New Tab usually sorts first, so the panel snapped to it. Locally
7229
+ * the pick now goes visibility → first non-blank → first; through the
7230
+ * remote proxy path (`/json/*` over the proxy) a per-page CDP probe is not
7231
+ * possible, so there the first page stays — #12 semantics unchanged.
6996
7232
  * - the panel's own selection — belongs to the view focus, not here.
6997
7233
  *
6998
7234
  * Order: per-session focus (validated against the live list) → explicit host
6999
- * focus → foreground observation (local port, else remote proxy) → none.
7000
- * `known` lets the caller pass the target list it already fetched, so a closed
7001
- * tab cannot keep the highlight.
7235
+ * focus → foreground observation (local: visibility-ranked list; remote: proxy
7236
+ * list) → none. `known` lets the caller pass the target list it already
7237
+ * fetched, so a closed tab cannot keep the highlight.
7002
7238
  */
7003
7239
  async function activeTargetInfo(known, sessionId) {
7004
7240
  const inKnown = (id) => known === void 0 || known.includes(id);
@@ -7042,7 +7278,12 @@ async function activeTargetInfo(known, sessionId) {
7042
7278
  source: "none"
7043
7279
  };
7044
7280
  }
7045
- const id = (await response.json()).find((entry) => entry.type === "page")?.id ?? null;
7281
+ const pages = (await response.json()).filter((entry) => entry.type === "page" && typeof entry.id === "string");
7282
+ const visibilityOf = (id$1) => {
7283
+ const cached = probeCache.get(id$1);
7284
+ return cached?.visibility !== void 0 && now - cached.at <= 5e3 ? cached.visibility : void 0;
7285
+ };
7286
+ const id = target.remote ? pages.find((p) => p.id !== void 0)?.id ?? null : await pickForegroundId(pages.slice(0, 30), visibilityOf);
7046
7287
  if (target.remote) {
7047
7288
  proxyObserveCache.at = now;
7048
7289
  proxyObserveCache.id = id;
@@ -7116,10 +7357,13 @@ async function snapshotSpaces(sessionId) {
7116
7357
  returnByValue: true,
7117
7358
  awaitPromise: false
7118
7359
  }, 3e3).then((result) => {
7119
- const r = result;
7360
+ const r = result.result?.value || null;
7120
7361
  probeCache.set(target.targetId, {
7121
7362
  at: Date.now(),
7122
- human: r.result?.value || null
7363
+ human: r,
7364
+ visibility: r?.visibilityState,
7365
+ readyState: r?.readyState,
7366
+ dpr: r?.dpr
7123
7367
  });
7124
7368
  }).catch(() => {});
7125
7369
  if (target.targetId === activeId) probeZoom(browser, target.targetId, now);
@@ -7140,6 +7384,7 @@ async function snapshotSpaces(sessionId) {
7140
7384
  },
7141
7385
  readyState: probe?.readyState,
7142
7386
  dpr: probe?.dpr,
7387
+ visibility: probe?.visibilityState,
7143
7388
  zoom: zoomCache.get(target.targetId)?.zoom ?? null
7144
7389
  });
7145
7390
  }
@@ -7169,6 +7414,7 @@ async function connectLoop() {
7169
7414
  cdp,
7170
7415
  sessions
7171
7416
  };
7417
+ verifySkips = 0;
7172
7418
  publishStatus({ browserConnected: true });
7173
7419
  await manager.browserConnected();
7174
7420
  await new Promise((resolve) => {
@@ -7190,6 +7436,40 @@ async function connectLoop() {
7190
7436
  }
7191
7437
  }
7192
7438
  }
7439
+ /**
7440
+ * #20 (F2) — endpoint authority while the socket is ALIVE.
7441
+ *
7442
+ * `connectLoop` only re-resolves on ws close/error, so a stale snapshot that
7443
+ * still reaches a living wrong browser would never be replaced. Every 5s the
7444
+ * watcher asks the resolver again; a different `instanceKey` (new browser on a
7445
+ * new port, or the state file taking authority over the env snapshot) closes
7446
+ * the current socket so the loop swaps to the winner. Hard guards, all from the
7447
+ * issue thread's regression list:
7448
+ * - remote env (`#12`) → the watcher never runs, env stays the only authority;
7449
+ * - no live candidate → nothing happens, the connection is never broken on a
7450
+ * probe miss (维持 3s 重试语义);
7451
+ * - unchanged fingerprint AND an answering active port → zero network.
7452
+ */
7453
+ let lastFingerprint = "";
7454
+ let verifySkips = 0;
7455
+ async function maybeReplaceEndpoint() {
7456
+ if (endpointResolver.remoteAuthoritative()) return;
7457
+ const fp = await endpointResolver.fingerprint();
7458
+ const browser = active;
7459
+ if (browser === null) return;
7460
+ const current = browser.instanceKey ?? "";
7461
+ if (fp === lastFingerprint) {
7462
+ if (verifySkips++ % 3 !== 0 || browser.port === null) return;
7463
+ if (await endpointIO.fetchVersion(`http://127.0.0.1:${browser.port}/json/version`) !== null) return;
7464
+ } else lastFingerprint = fp;
7465
+ const next = await resolveBrowser();
7466
+ if (!next) return;
7467
+ if (next.instanceKey === current) return;
7468
+ process.stderr.write(`[cdp-cast-worker] endpoint replaced: ${current} -> ${next.instanceKey}\n`);
7469
+ try {
7470
+ browser.ws.close();
7471
+ } catch {}
7472
+ }
7193
7473
  function sleep(ms) {
7194
7474
  return new Promise((resolve) => setTimeout(resolve, ms));
7195
7475
  }
@@ -7754,8 +8034,12 @@ async function main() {
7754
8034
  if (!active || sseClients.size === 0) return;
7755
8035
  snapshotSpaces().then((spaces) => broadcast("spaces", spaces)).catch(() => {});
7756
8036
  }, 1e3);
8037
+ const endpointTimer = setInterval(() => {
8038
+ maybeReplaceEndpoint().catch(() => {});
8039
+ }, 5e3);
7757
8040
  const shutdown = async () => {
7758
8041
  clearInterval(metadataTimer);
8042
+ clearInterval(endpointTimer);
7759
8043
  await manager.dispose().catch(() => {});
7760
8044
  try {
7761
8045
  active?.ws?.close();
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.14.12",
5
+ "version": "1.14.14",
6
6
  "manifestVersion": "0.15",
7
7
  "facets": {
8
8
  "host": {
package/lib/client.js CHANGED
@@ -538,7 +538,8 @@ const GUIDE_CSS = `
538
538
  .sgGuideBtn{appearance:none;font:inherit;font-size:12px;padding:5px 12px;border-radius:8px;border:1px solid var(--dsw-alias-border-l2, rgba(127,127,127,.3));background:transparent;color:var(--dsw-alias-label-primary, currentColor);cursor:pointer}
539
539
  .sgGuideBtn-primary{background:var(--dsw-alias-button-primary-fill, #4d6bfe);border-color:transparent;color:#fff}
540
540
  .sgGuideBtn-skip{margin-right:auto;color:var(--dsw-alias-label-tertiary, rgba(127,127,127,.9));border-color:transparent;text-decoration:underline}
541
- .sgGuideRestart{appearance:none;font:inherit;font-size:12px;padding:0;border:0;background:transparent;color:var(--dsw-alias-link-primary, #4d6bfe);cursor:pointer;text-decoration:underline}
541
+ .sgGuideRestart{appearance:none;font:inherit;font-size:12px;line-height:1.4;padding:4px 12px;border-radius:999px;border:1px solid var(--dsw-alias-border-l2, rgba(127,127,127,.35));background:var(--dsw-alias-bg-layer-2, rgba(127,127,127,.06));color:var(--dsw-alias-label-primary, currentColor);cursor:pointer;text-decoration:none}
542
+ .sgGuideRestart:hover{border-color:var(--dsw-alias-button-primary-fill, #4d6bfe);color:var(--dsw-alias-button-primary-fill, #4d6bfe)}
542
543
  `;
543
544
  function injectGuideCss() {
544
545
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-browser-cdp",
3
- "version": "1.14.12",
3
+ "version": "1.14.14",
4
4
  "description": "dsh-browser-cdp: visible agent browser for DSH — drives the vendored ego-compatible Chromium over CDP, and can also attach to a running Chrome/Edge/Brave or route through egolite, Tabbit and Lightpanda backends. 35 structured bcdp_* tools; only bcdp_status stays resident by default (lazy injection, −91.9% schema per turn for non-browser sessions). Realtime watch panel with direct click/scroll/IME input, element picks quoted into the composer, human-verification notices; non-CDP channels sync frames by 3s polling. Web shell: floating watch ball without dsh-better-sidebar, sidebar tab with it. Headless/TUI hosts: tools-only. [DSH 0.1.0-rc.2 ~ 0.2.2-rc.1: declarative settings via Config .volatile() fields on 0.1.7+; imperative installSection / module-level registration + describe/mutate bridge on 0.1.0 ~ 0.1.5 (experimental, pending farm). Client peers stay optional so gen-1 hosts without dsh-client-store still load; for a production install on the current line use the 0.17.x line]",
5
5
  "type": "module",
6
6
  "main": "./lib/index.js",