dsh-plugin-mesh 0.5.19 → 0.5.20

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/client/client.js CHANGED
@@ -728,7 +728,7 @@ window.__ModuleLoader__.load({
728
728
  // ─────────────────────── 样式 ───────────────────────
729
729
 
730
730
  const CSS = `
731
- .mesh-root {
731
+ .mesh-root, .mesh-web-hosted {
732
732
  --mesh-bg: var(--dsw-alias-bg-base);
733
733
  --mesh-surface: var(--dsw-alias-bg-layer-1);
734
734
  --mesh-surface-2: var(--dsw-alias-bg-layer-2);
@@ -775,6 +775,11 @@ window.__ModuleLoader__.load({
775
775
  border-radius: 999px;
776
776
  }
777
777
  .mesh-root ::-webkit-scrollbar-track { background: transparent; }
778
+ /* body 级常驻宿主:只借 .mesh-root 的变量与排版,不要它的布局(它是主面板外壳)。 */
779
+ .mesh-web-hosted {
780
+ position: static; display: block; flex: none;
781
+ min-height: 0; overflow: visible; background: none;
782
+ }
778
783
 
779
784
  /* ── 顶栏 ── */
780
785
  .mesh-topbar {
@@ -810,6 +815,8 @@ window.__ModuleLoader__.load({
810
815
  display: flex; flex-direction: column;
811
816
  background: var(--mesh-bg);
812
817
  }
818
+ /* 搬出 MeshApp 之后由 body 级宿主接管定位:盖住整屏,但仍低于应用自己的弹层(1000+)。 */
819
+ .mesh-web-hosted .mesh-web-layer { position: fixed; inset: 0; z-index: 900; }
813
820
  .mesh-web-bar {
814
821
  flex: 0 0 auto;
815
822
  display: flex; align-items: center; gap: 8px;
@@ -4441,6 +4448,333 @@ window.__ModuleLoader__.load({
4441
4448
  );
4442
4449
  }
4443
4450
 
4451
+ // ─────────────────────── 常驻 Web 面板层 ───────────────────────
4452
+
4453
+ /** 空闲多久拆掉面板(毫秒);localStorage 写 mesh.webPanelIdleMs = 0 表示「收起即拆」。 */
4454
+ const WEB_PANEL_IDLE_KEY = "mesh.webPanelIdleMs";
4455
+ const WEB_PANEL_IDLE_DEFAULT = 10 * 60 * 1000;
4456
+ /** 可见期间的心跳上限:面板开着就定期把宿主的宽限期续上(见 startBeat)。 */
4457
+ const WEB_PANEL_HEARTBEAT_MAX = 4 * 60 * 1000;
4458
+
4459
+ function readWebPanelIdleMs() {
4460
+ try {
4461
+ const raw = window.localStorage.getItem(WEB_PANEL_IDLE_KEY);
4462
+ // 注意:没设置时 getItem 返回 null,而 Number(null) === 0 —— 直接 Number()
4463
+ // 会把「没配置」读成「收起即拆」,于是每次 hide() 立刻销毁 iframe,秒切失效。
4464
+ if (raw !== null && String(raw).trim() !== "") {
4465
+ const ms = Number(raw);
4466
+ if (Number.isFinite(ms) && ms >= 0) return ms;
4467
+ }
4468
+ } catch {
4469
+ /* 没有 localStorage(隐私模式 / 非浏览器宿主):用默认值 */
4470
+ }
4471
+ return WEB_PANEL_IDLE_DEFAULT;
4472
+ }
4473
+
4474
+ /** 让宿主回收这块面板的回环反代与 tailnet 出站流(keepalive:页面正在关也发得出去)。 */
4475
+ function closePeerPanel(peer, force) {
4476
+ if (!peer || typeof fetch !== "function") return;
4477
+ try {
4478
+ fetch(`${API}/web-panel/close`, {
4479
+ method: "POST",
4480
+ headers: { "content-type": "application/json" },
4481
+ body: JSON.stringify(force ? { peer, force: true } : { peer }),
4482
+ keepalive: true,
4483
+ }).catch(() => {});
4484
+ } catch {
4485
+ /* 尽力而为:宿主自己的空闲 sweep 会兜底回收 */
4486
+ }
4487
+ }
4488
+
4489
+ /**
4490
+ * 常驻 Web 面板层:对端 DSH Web 的 iframe 挂在 document.body 上,
4491
+ * **不随 MeshApp 卸载**。
4492
+ *
4493
+ * 为什么必须搬出来:main 这个 slot 是 keyed 渲染(dsh-client-ui-layout),
4494
+ * activePanelId 一旦离开 mesh(点侧栏任何一个会话、切别的面板、换 workspace),
4495
+ * MeshApp 就整棵卸载,组件里的 iframe 跟着销毁、对端页面从头重载 —— 而宿主
4496
+ * 那边的回环反代明明还在 10 分钟宽限期里。iframe 的寿命不能挂在一个会被卸载
4497
+ * 的组件上。
4498
+ *
4499
+ * 时效销毁(三层,缺一不可):
4500
+ * 1. 收起(面板「返回」或 MeshApp 被卸载)→ 只 display:none,iframe、对端
4501
+ * 会话、滚动位置全留着;IDLE_MS 内再打开就是原样显示(不请求宿主、不重建
4502
+ * iframe)—— 这才是「秒切」;
4503
+ * 2. 空闲超过 IDLE_MS(默认 10 分钟,与宿主 WEB_PANEL_IDLE_MS 对齐)→ 卸载
4504
+ * iframe + force-close 宿主反代,不留孤儿端口和 tailnet 出站流;
4505
+ * 3. 页面 pagehide → 尽力 force-close(keepalive),双保险。
4506
+ */
4507
+ function createWebPanelLayer() {
4508
+ let hostEl = null; // body 级容器
4509
+ let root = null; // 独立 React root:与 MeshApp 的生命周期无关
4510
+ let timer = null; // 空闲销毁计时器
4511
+ let beat = null; // 可见期间的心跳计时器
4512
+ let beatMiss = 0; // 连续失败次数(对端短暂掉出发现列表时别一击必杀)
4513
+ let beatOverride = 0; // 仅自测用:覆盖心跳间隔
4514
+ let panel = null; // 当前面板;null = 没有 iframe
4515
+ let hooks = null; // { push, fallback }:MeshApp 挂载时注册,卸载即清空
4516
+ let pagehideBound = false;
4517
+
4518
+ const keyOf = (peer) => (peer && (peer.machine || peer.id)) || "";
4519
+ const nameOf = (peer) => (peer && (peer.machine || peer.id)) || "对端";
4520
+
4521
+ function ensureHost() {
4522
+ if (hostEl !== null) return true;
4523
+ if (typeof document === "undefined" || !document.body) return false;
4524
+ hostEl = document.createElement("div");
4525
+ hostEl.className = "mesh-web-hosted";
4526
+ document.body.appendChild(hostEl);
4527
+ root = require("react-dom/client").createRoot(hostEl);
4528
+ if (!pagehideBound) {
4529
+ pagehideBound = true;
4530
+ window.addEventListener("pagehide", () => {
4531
+ // 页面要走了:先把 iframe 的引用扔掉,再尽力让宿主立刻回收。
4532
+ const key = panel ? panel.key : "";
4533
+ panel = null;
4534
+ if (key) closePeerPanel(key, true);
4535
+ });
4536
+ }
4537
+ return true;
4538
+ }
4539
+
4540
+ function paint() {
4541
+ if (root === null) return;
4542
+ root.render(h(WebPanel, { panel, onClose: hide, onReload: reload }));
4543
+ }
4544
+
4545
+ function clearTimer() {
4546
+ if (timer === null) return;
4547
+ clearTimeout(timer);
4548
+ timer = null;
4549
+ }
4550
+
4551
+ function startIdleTimer() {
4552
+ clearTimer();
4553
+ // 现读而不是插件加载时读一次:改 mesh.webPanelIdleMs 不用重载界面。
4554
+ const idleMs = readWebPanelIdleMs();
4555
+ if (!(idleMs > 0)) {
4556
+ destroy();
4557
+ return;
4558
+ }
4559
+ timer = setTimeout(() => {
4560
+ timer = null;
4561
+ destroy();
4562
+ }, idleMs);
4563
+ }
4564
+
4565
+ /** 心跳间隔:取宽限期的一半,夹在 15s–4min 之间(后台标签页的定时器会被节流)。 */
4566
+ function beatInterval() {
4567
+ if (beatOverride > 0) return beatOverride;
4568
+ const idleMs = readWebPanelIdleMs();
4569
+ const half = idleMs > 0 ? idleMs / 2 : WEB_PANEL_HEARTBEAT_MAX;
4570
+ return Math.max(15 * 1000, Math.min(WEB_PANEL_HEARTBEAT_MAX, half));
4571
+ }
4572
+
4573
+ function clearBeat() {
4574
+ if (beat === null) return;
4575
+ clearInterval(beat);
4576
+ beat = null;
4577
+ }
4578
+
4579
+ function startBeat() {
4580
+ clearBeat();
4581
+ beatMiss = 0;
4582
+ beat = setInterval(() => {
4583
+ void ensureAlive();
4584
+ }, beatInterval());
4585
+ }
4586
+
4587
+ /**
4588
+ * 续命 + 自愈。
4589
+ *
4590
+ * 宿主的回收按 lastUsedAt 的「空闲 10 分钟」算,它不知道面板是不是正开在
4591
+ * 屏幕上 —— 只在打开那一刻刷新的话,一直开着的面板会在第 10 分钟被
4592
+ * sweep 掉反代(画面还在,后续请求开始失败)。所以可见期间定期打一次
4593
+ * /web-panel:命中复用分支只刷新 lastUsedAt,不重建、不换端口。
4594
+ *
4595
+ * 顺便自愈:如果反代真被回收后重建过,返回的地址会变,这里把 iframe
4596
+ * 指过去(页面重载一次),而不是让用户对着一个死地址。
4597
+ */
4598
+ async function ensureAlive() {
4599
+ if (panel === null || panel.state !== "ready") return;
4600
+ const key = panel.key;
4601
+ const url = panel.url;
4602
+ let r = null;
4603
+ try {
4604
+ r = await api("/web-panel", { peer: key });
4605
+ } catch {
4606
+ return; // 网络抖动不算失效,下一次心跳再试
4607
+ }
4608
+ if (panel === null || panel.key !== key || panel.state !== "ready") return;
4609
+ if (r && r.ok === true && typeof r.url === "string") {
4610
+ beatMiss = 0;
4611
+ if (r.url === url) return;
4612
+ panel = { ...panel, url: r.url, remote: r.remote || panel.remote, reloadKey: (panel.reloadKey || 0) + 1 };
4613
+ paint();
4614
+ notify("info", "宿主那边的反代被回收过,已重新建连并重载页面。");
4615
+ return;
4616
+ }
4617
+ // 对端可能只是短暂掉出发现列表(peers 有 TTL):连续两次问不到才判死。
4618
+ beatMiss += 1;
4619
+ if (beatMiss < 2) return;
4620
+ destroy();
4621
+ notify("warn", "这块面板的反代已被宿主收回,请重新打开。");
4622
+ }
4623
+
4624
+ function notify(kind, text) {
4625
+ try {
4626
+ if (hooks && typeof hooks.push === "function") hooks.push(kind, text);
4627
+ } catch {
4628
+ /* toast 只是提示,失败不影响面板 */
4629
+ }
4630
+ }
4631
+
4632
+ /** 拆掉 iframe 并让宿主回收反代:空闲到期、插件卸载、换设备都走这里。 */
4633
+ function destroy() {
4634
+ clearTimer();
4635
+ clearBeat();
4636
+ const key = panel ? panel.key : "";
4637
+ panel = null;
4638
+ if (root !== null) {
4639
+ try {
4640
+ root.unmount();
4641
+ } catch {
4642
+ /* 已经不在渲染树里也无所谓 */
4643
+ }
4644
+ root = null;
4645
+ }
4646
+ if (hostEl !== null && hostEl.parentNode) hostEl.parentNode.removeChild(hostEl);
4647
+ hostEl = null;
4648
+ if (key) closePeerPanel(key, true);
4649
+ }
4650
+
4651
+ /** 收起:只隐藏。iframe 与对端会话留着,等 IDLE_MS 到期才真拆。 */
4652
+ function hide() {
4653
+ if (panel === null || panel.hidden) return;
4654
+ clearBeat();
4655
+ panel = { ...panel, hidden: true, hiddenAt: Date.now() };
4656
+ paint();
4657
+ startIdleTimer();
4658
+ }
4659
+
4660
+ /** 重载同一个地址(对端重启过、iframe 白屏时用),不动宿主反代。 */
4661
+ function reload() {
4662
+ if (panel === null || !panel.url) return;
4663
+ clearTimer();
4664
+ panel = { ...panel, state: "ready", hidden: false, hiddenAt: 0, reloadKey: (panel.reloadKey || 0) + 1 };
4665
+ paint();
4666
+ startBeat();
4667
+ }
4668
+
4669
+ async function open(peer, opts) {
4670
+ const force = !!(opts && opts.force);
4671
+ const key = keyOf(peer);
4672
+ if (!key) return;
4673
+ if (!ensureHost()) {
4674
+ notify("error", "当前宿主没有可用的 document.body,打不开应用内面板。");
4675
+ return;
4676
+ }
4677
+ // 快路:同一台设备、iframe 还活着(IDLE_MS 内)→ 直接显示,不请求宿主、
4678
+ // 不重建 iframe。页面状态、滚动位置、对端会话原样都在。
4679
+ if (panel !== null && panel.key === key && panel.state === "ready") {
4680
+ clearTimer();
4681
+ if (force) {
4682
+ reload();
4683
+ return;
4684
+ }
4685
+ panel = { ...panel, peer, name: nameOf(peer), hidden: false, hiddenAt: 0 };
4686
+ paint();
4687
+ startBeat();
4688
+ // 收起过一段时间的(接近宽限期)从这一刻起续命,别刚打开就被宿主 sweep。
4689
+ void ensureAlive();
4690
+ return;
4691
+ }
4692
+ // 换设备:旧面板的反代先还给宿主,别留一个孤儿端口。
4693
+ if (panel !== null && panel.key !== key) closePeerPanel(panel.key, true);
4694
+ clearTimer();
4695
+ panel = {
4696
+ key,
4697
+ peer,
4698
+ name: nameOf(peer),
4699
+ state: "loading",
4700
+ url: "",
4701
+ remote: "",
4702
+ hasSession: true,
4703
+ note: "",
4704
+ hidden: false,
4705
+ hiddenAt: 0,
4706
+ reloadKey: 0,
4707
+ };
4708
+ paint();
4709
+ let r = null;
4710
+ try {
4711
+ r = await api("/web-panel", { peer: key });
4712
+ } catch (error) {
4713
+ r = { ok: false, error: String((error && error.message) || error) };
4714
+ }
4715
+ // 期间被收起并到期拆掉、或又换了设备:这次响应作废。
4716
+ if (panel === null || panel.key !== key || panel.state !== "loading") return;
4717
+ if (r && r.ok === true && typeof r.url === "string") {
4718
+ panel = {
4719
+ ...panel,
4720
+ state: "ready",
4721
+ url: r.url,
4722
+ remote: r.remote || "",
4723
+ hasSession: r.hasSession !== false,
4724
+ note: r.note || "",
4725
+ hidden: false,
4726
+ reloadKey: 0,
4727
+ };
4728
+ paint();
4729
+ startBeat();
4730
+ if (panel.hasSession === false) {
4731
+ notify("warn", `${panel.name} 那边没给出可用 token,面板可能停在登录页。`);
4732
+ }
4733
+ return;
4734
+ }
4735
+ const detail = (r && r.error) || "未知原因";
4736
+ panel = null;
4737
+ paint();
4738
+ notify("warn", `应用内面板起不来(${detail}),改用外部方式打开。`);
4739
+ try {
4740
+ if (hooks && typeof hooks.fallback === "function") await hooks.fallback(peer);
4741
+ } catch (error) {
4742
+ notify("error", `外部方式也打不开:${String((error && error.message) || error)}`);
4743
+ }
4744
+ }
4745
+
4746
+ return {
4747
+ open,
4748
+ hide,
4749
+ reload,
4750
+ /** 当前面板的只读快照(不把 live 引用交给外部)。 */
4751
+ current: () =>
4752
+ panel === null
4753
+ ? null
4754
+ : { key: panel.key, name: panel.name, hidden: !!panel.hidden, hasSession: panel.hasSession !== false },
4755
+ /** MeshApp 挂载时注册 toast / 兜底打开;卸载时清空。 */
4756
+ setHooks: (next) => {
4757
+ hooks = next || null;
4758
+ },
4759
+ clearHooks: () => {
4760
+ hooks = null;
4761
+ },
4762
+ /** 插件被卸载/热更:拆干净,别在 body 上留一个 iframe。 */
4763
+ dispose: () => {
4764
+ hooks = null;
4765
+ destroy();
4766
+ },
4767
+ /** 仅供自测:面板是否处于「iframe 活着」的状态。 */
4768
+ __alive: () => panel !== null && panel.state === "ready",
4769
+ /** 仅供自测:覆盖心跳间隔(0 = 恢复自动)。 */
4770
+ __setHeartbeatMs: (ms) => {
4771
+ beatOverride = Number(ms) > 0 ? Number(ms) : 0;
4772
+ if (panel !== null && !panel.hidden) startBeat();
4773
+ },
4774
+ };
4775
+ }
4776
+
4777
+ const webPanelLayer = createWebPanelLayer();
4444
4778
 
4445
4779
  /** 去掉终端控制序列:没有 xterm 时,把 ANSI 转义剥掉才不会满屏乱码。 */
4446
4780
  function stripAnsi(text) {
@@ -8127,8 +8461,8 @@ window.__ModuleLoader__.load({
8127
8461
  const [taskFilter, setTaskFilter] = react.useState("all");
8128
8462
  const [composer, setComposer] = react.useState(null);
8129
8463
  const [probe, setProbe] = react.useState(null);
8130
- // 对端 DSH Web 的应用内面板:{ peer, name, state: loading|ready, url, note, hasSession, reloadKey }
8131
- const [webPanel, setWebPanel] = react.useState(null);
8464
+ // 对端 DSH Web 的面板不在这里:它由 webPanelLayer 挂在 document.body 上,
8465
+ // 这样 Mesh 面板被卸载(点侧栏任何会话)时 iframe 不会被销毁。
8132
8466
  // SSH 终端面板:null 或某个 peer
8133
8467
  const [sshPeer, setSshPeer] = react.useState(null);
8134
8468
  const [scanning, setScanning] = react.useState(false);
@@ -8353,59 +8687,15 @@ window.__ModuleLoader__.load({
8353
8687
  /**
8354
8688
  * 打开对端的 DSH Web。
8355
8689
  *
8356
- * 主路是**应用内面板**:宿主起一个回环反代(认证在服务端做),这里只
8357
- * 把它的地址塞进同源 iframe —— 不依赖壳的浏览器 WebView(本机没有),
8358
- * 也不受对端 cookie 的 SameSite=Strict 影响。
8359
- * 反代起不来时才退回老的"浏览器页签 / 外部浏览器"那条链。
8690
+ * 面板本身由 webPanelLayer(body 级常驻层)持有:这里只做转交。之所以
8691
+ * 不在组件里管,是因为主面板 slot 是 keyed 渲染,MeshApp 一卸载 iframe
8692
+ * 就会跟着销毁 —— 而宿主那边的回环反代还在宽限期里,本来可以秒切。
8360
8693
  */
8361
- const openWeb = async (peer, opts) => {
8362
- const force = !!(opts && opts.force);
8363
- const name = (peer && peer.machine) || "对端";
8364
- const key = (peer && (peer.machine || peer.id)) || "";
8365
- const cachedKey =
8366
- webPanel && webPanel.peer ? webPanel.peer.machine || webPanel.peer.id || "" : "";
8367
- // 之前收起来的同一台设备:直接显示,不请求宿主、不重建 iframe。
8368
- // 页面状态、滚动位置、对端会话原样还在(宿主那边代理也在宽限期内)。
8369
- // 超过宽限期就不再走快路——那时宿主可能已经把代理回收了,直接显示
8370
- // 只会看到一个连不上的 iframe。
8371
- const hiddenFor = webPanel && webPanel.hiddenAt ? Date.now() - webPanel.hiddenAt : Infinity;
8372
- if (!force && webPanel && webPanel.url && cachedKey && cachedKey === key && hiddenFor < 8 * 60 * 1000) {
8373
- setWebPanel((prev) => ({ ...(prev || { peer, name }), peer, name, hidden: false, hiddenAt: 0, state: "ready" }));
8374
- return;
8375
- }
8376
- // force = 用户点「重新加载面板」:保留同一个代理地址,只让 iframe 重载
8377
- setWebPanel((prev) => ({
8378
- peer,
8379
- name,
8380
- state: "loading",
8381
- hidden: false,
8382
- reloadKey: force && prev && prev.url ? (prev.reloadKey || 0) + 1 : 0,
8383
- }));
8384
- try {
8385
- const r = await api("/web-panel", { peer: (peer && (peer.machine || peer.id)) || "" });
8386
- if (r && r.ok === true && typeof r.url === "string") {
8387
- setWebPanel((prev) => ({
8388
- ...(prev || { peer, name }),
8389
- state: "ready",
8390
- url: r.url,
8391
- remote: r.remote || "",
8392
- hasSession: r.hasSession !== false,
8393
- note: r.note || "",
8394
- hidden: false,
8395
- reloadKey: (prev && prev.reloadKey) || 0,
8396
- }));
8397
- if (r.hasSession === false) {
8398
- push("warn", `${name} 那边没给出可用 token,面板可能停在登录页。`);
8399
- }
8400
- return;
8401
- }
8402
- setWebPanel(null);
8403
- push("warn", `应用内面板起不来(${(r && r.error) || "未知原因"}),改用外部方式打开。`);
8404
- } catch (error) {
8405
- setWebPanel(null);
8406
- push("warn", `应用内面板起不来(${String((error && error.message) || error)}),改用外部方式打开。`);
8407
- }
8694
+ const openWeb = (peer, opts) => webPanelLayer.open(peer, opts);
8408
8695
 
8696
+ /** 应用内面板起不来时,退回旧的"浏览器页签 / 外部浏览器"那条链。 */
8697
+ const openWebFallback = async (peer) => {
8698
+ const name = (peer && peer.machine) || "对端";
8409
8699
  let result;
8410
8700
  try {
8411
8701
  result = await openDshWebPage(peer);
@@ -8455,27 +8745,15 @@ window.__ModuleLoader__.load({
8455
8745
  push("warn", "当前宿主没有 layout 服务,无法自动回到会话;用侧边栏切回对话即可。");
8456
8746
  };
8457
8747
 
8458
- /**
8459
- * 关掉对端 Web 面板:先卸载前端这一层,再尽力让宿主把反代也停掉
8460
- * (停不掉只是多一个回环端口,不影响正确性)。
8461
- */
8462
- const closeWebPanel = () => {
8463
- const machine = webPanel && webPanel.peer ? webPanel.peer.machine || webPanel.peer.id || "" : "";
8464
- // 只收起、不卸载:iframe 留着,对端页面的会话状态和滚动位置都还在;
8465
- // 宿主收到 close 只把它标记成空闲,宽限期内不拆代理和出站流。
8466
- setWebPanel((prev) => (prev ? { ...prev, hidden: true, hiddenAt: Date.now() } : null));
8467
- if (!machine) return;
8468
- api("/web-panel/close", { peer: machine }).catch(() => {
8469
- /* 关闭是尽力而为 */
8470
- });
8471
- };
8748
+ // 面板层用的 toast 与兜底:push 是 useCallback 稳定的,这里只挂一次。
8749
+ react.useEffect(() => {
8750
+ webPanelLayer.setHooks({ push, fallback: openWebFallback });
8751
+ return () => webPanelLayer.clearHooks();
8752
+ }, [push]);
8472
8753
 
8473
- /** 重新拉起面板(对端重启过、或 iframe 白屏时用)。 */
8474
- const reloadWebPanel = () => {
8475
- const peer = webPanel && webPanel.peer;
8476
- if (!peer) return;
8477
- void openWeb(peer, { force: true });
8478
- };
8754
+ // Mesh 面板被卸载(点侧栏任何会话、切别的面板、换 workspace)→ 只收起,
8755
+ // 不拆 iframe:宽限期内再打开就是原样秒切。
8756
+ react.useEffect(() => () => webPanelLayer.hide(), []);
8479
8757
 
8480
8758
  /** 派发成功的统一收尾:toast + 让轮询立刻刷新。
8481
8759
  * 设备页弹层和主页的派发面板共用它,免得两处提示文案慢慢走散。
@@ -8861,7 +9139,6 @@ window.__ModuleLoader__.load({
8861
9139
  onCopy: copyTransfer,
8862
9140
  })
8863
9141
  : null,
8864
- h(WebPanel, { panel: webPanel, onClose: closeWebPanel, onReload: reloadWebPanel }),
8865
9142
  sshPeer ? h(SshPanel, { peer: sshPeer, onClose: () => setSshPeer(null) }) : null,
8866
9143
  h(Toasts, { items: toasts, onClose: close }),
8867
9144
  h(DemoOverlay, { open: demoOpen, onClose: () => setDemoOpen(false) }),
@@ -8904,6 +9181,10 @@ window.__ModuleLoader__.load({
8904
9181
  ctx.slots.register({ name: "main", key: PANEL_ID }, MeshApp),
8905
9182
  );
8906
9183
  registerAtPeerSource(ctx);
9184
+ // 常驻层不走 slot 的生命周期:插件停用/热更时要自己把 body 上的 iframe 收掉。
9185
+ if (typeof ctx.effect === "function") {
9186
+ ctx.effect(() => () => webPanelLayer.dispose(), "mesh: 常驻 Web 面板层");
9187
+ }
8907
9188
  ctx.logger?.info?.("mesh client: 已注册 Mesh 工作台");
8908
9189
  }
8909
9190
 
@@ -8924,6 +9205,10 @@ window.__ModuleLoader__.load({
8924
9205
  resolveWebUrl,
8925
9206
  openDshWebPage,
8926
9207
  WebPanel,
9208
+ webPanelLayer,
9209
+ createWebPanelLayer,
9210
+ readWebPanelIdleMs,
9211
+ WEB_PANEL_IDLE_DEFAULT,
8927
9212
  CapabilityChips,
8928
9213
  TaskRow,
8929
9214
  TaskDetail,
@@ -0,0 +1,273 @@
1
+ /**
2
+ * 常驻 Web 面板层(client.js 的 webPanelLayer)自测。
3
+ *
4
+ * 面板层是唯一直接碰 document.body 的部分,用假 DOM + 假 fetch 就能把生命周期
5
+ * 从头到尾走一遍,不需要浏览器:
6
+ *
7
+ * 打开 → 收起(只隐藏)→ 宽限期内复开(不请求、不重建 = 秒切)
8
+ * → 空闲到期(unmount + 摘宿主 + force-close 宿主反代)
9
+ * → 换设备(旧面板先还给宿主)→ dispose(插件卸载不留孤儿)
10
+ *
11
+ * node lib/_selftest-webhost.mjs
12
+ */
13
+ import { strict as assert } from "node:assert";
14
+ import { readFileSync } from "node:fs";
15
+ import { fileURLToPath } from "node:url";
16
+ import { dirname, join } from "node:path";
17
+
18
+ const HERE = dirname(fileURLToPath(import.meta.url));
19
+ const BUNDLE = join(HERE, "..", "client", "client.js");
20
+
21
+ // ── 假 DOM ──
22
+ const created = [];
23
+ function fakeEl(tag) {
24
+ return {
25
+ tagName: tag,
26
+ className: "",
27
+ id: "",
28
+ style: {},
29
+ children: [],
30
+ parentNode: null,
31
+ appendChild(child) {
32
+ this.children.push(child);
33
+ child.parentNode = this;
34
+ return child;
35
+ },
36
+ removeChild(child) {
37
+ this.children = this.children.filter((item) => item !== child);
38
+ child.parentNode = null;
39
+ },
40
+ textContent: "",
41
+ };
42
+ }
43
+ const body = fakeEl("body");
44
+ globalThis.document = {
45
+ body,
46
+ head: null, // installStyle() 直接早退:样式不在本自测的范围内
47
+ createElement: (tag) => {
48
+ const el = fakeEl(tag);
49
+ created.push(el);
50
+ return el;
51
+ },
52
+ getElementById: () => null,
53
+ };
54
+
55
+ // ── 假 localStorage / window ──
56
+ const store = new Map([["mesh.webPanelIdleMs", "25"]]);
57
+ const listeners = new Map();
58
+ let captured = null;
59
+ globalThis.window = {
60
+ __ModuleLoader__: {
61
+ load: (entry) => {
62
+ captured = entry;
63
+ },
64
+ },
65
+ localStorage: {
66
+ getItem: (key) => (store.has(key) ? store.get(key) : null),
67
+ setItem: (key, value) => store.set(key, String(value)),
68
+ },
69
+ addEventListener: (name, fn) => listeners.set(name, fn),
70
+ };
71
+
72
+ // ── 假 fetch(地址与失败都可由用例控制)──
73
+ const calls = [];
74
+ let hostUrl = "http://127.0.0.1:4321/?k=x";
75
+ let hostFail = false;
76
+ globalThis.fetch = async (url, init) => {
77
+ const payload = init && init.body ? JSON.parse(init.body) : {};
78
+ calls.push({ url: String(url), body: payload, keepalive: !!(init && init.keepalive) });
79
+ if (String(url).endsWith("/mesh/api/web-panel")) {
80
+ if (hostFail) {
81
+ return { ok: true, status: 200, json: async () => ({ ok: false, error: "宿主说保不住了" }) };
82
+ }
83
+ return { ok: true, status: 200, json: async () => ({ ok: true, url: hostUrl, hasSession: true }) };
84
+ }
85
+ return { ok: true, status: 200, json: async () => ({ ok: true }) };
86
+ };
87
+
88
+ // ── 假 react / react-dom/client ──
89
+ const reactStub = {
90
+ createElement: (type, props, ...children) => ({ type, props: props ?? {}, children: children.flat(Infinity) }),
91
+ useState: (value) => [typeof value === "function" ? value() : value, () => {}],
92
+ useEffect: () => {},
93
+ useMemo: (fn) => fn(),
94
+ useCallback: (fn) => fn,
95
+ useRef: (value) => ({ current: value }),
96
+ Fragment: Symbol("Fragment"),
97
+ };
98
+ const rendered = [];
99
+ let unmounted = 0;
100
+ const reactDomStub = {
101
+ createRoot: () => ({
102
+ render: (node) => rendered.push(node),
103
+ unmount: () => {
104
+ unmounted += 1;
105
+ },
106
+ }),
107
+ };
108
+
109
+ const source = readFileSync(BUNDLE, "utf8");
110
+ new Function("window", `${source}\n`)(globalThis.window);
111
+ const mod = captured.factory((name) => {
112
+ if (name === "react") return reactStub;
113
+ if (name === "react-dom/client") return reactDomStub;
114
+ throw new Error(`未预期的依赖:${name}`);
115
+ });
116
+
117
+ const layer = mod.__test.webPanelLayer;
118
+ const peer = { machine: "hos", id: "x1" };
119
+ const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
120
+
121
+ let passed = 0;
122
+ function ok(name, fn) {
123
+ fn();
124
+ passed += 1;
125
+ console.log(` ✓ ${name}`);
126
+ }
127
+ async function okAsync(name, fn) {
128
+ await fn();
129
+ passed += 1;
130
+ console.log(` ✓ ${name}`);
131
+ }
132
+
133
+ await okAsync("打开:一次 /web-panel,宿主挂到 body 上", async () => {
134
+ await layer.open(peer);
135
+ assert.equal(layer.__alive(), true);
136
+ assert.equal(layer.current().hidden, false);
137
+ assert.equal(calls.length, 1);
138
+ const host = created.find((el) => el.className === "mesh-web-hosted");
139
+ assert.ok(host, "应创建 body 级宿主");
140
+ assert.ok(body.children.includes(host), "宿主必须挂在 body 上");
141
+ });
142
+
143
+ ok("收起:只隐藏,不卸载 iframe", () => {
144
+ layer.hide();
145
+ assert.equal(layer.current().hidden, true);
146
+ assert.equal(layer.__alive(), true);
147
+ assert.equal(unmounted, 0);
148
+ });
149
+
150
+ await okAsync("宽限期内复开:不重建 iframe(秒切),只顺手续一次命", async () => {
151
+ const before = rendered.length;
152
+ const opens = calls.filter((call) => call.url.endsWith("/mesh/api/web-panel")).length;
153
+ await layer.open(peer);
154
+ assert.equal(layer.current().hidden, false);
155
+ assert.equal(rendered.length, before + 1, "只重绘一次");
156
+ assert.equal(unmounted, 0, "复开不该重建 root");
157
+ await sleep(10);
158
+ const after = calls.filter((call) => call.url.endsWith("/mesh/api/web-panel")).length;
159
+ assert.equal(after, opens + 1, "复开应顺带打一次 /web-panel 续命(只刷新 lastUsedAt)");
160
+ });
161
+
162
+ await okAsync("空闲到期:unmount + 摘宿主 + force-close 宿主反代", async () => {
163
+ layer.hide();
164
+ await sleep(80);
165
+ assert.equal(layer.__alive(), false);
166
+ assert.equal(unmounted, 1);
167
+ assert.equal(body.children.length, 0, "宿主应从 body 摘掉");
168
+ const close = calls.find((call) => call.url.endsWith("/web-panel/close"));
169
+ assert.ok(close, "到期应通知宿主 close");
170
+ assert.equal(close.body.force, true, "到期必须 force-close");
171
+ assert.equal(close.body.peer, "hos");
172
+ });
173
+
174
+ await okAsync("换设备:旧面板先还给宿主,不留孤儿端口", async () => {
175
+ calls.length = 0;
176
+ await layer.open(peer);
177
+ await layer.open({ machine: "myserver-wb", id: "y2" });
178
+ const closed = calls.filter((call) => call.url.endsWith("/web-panel/close"));
179
+ assert.equal(closed.length, 1);
180
+ assert.equal(closed[0].body.peer, "hos");
181
+ assert.equal(closed[0].body.force, true);
182
+ });
183
+
184
+ ok("dispose:插件卸载后 body 上不留宿主", () => {
185
+ layer.dispose();
186
+ assert.equal(layer.__alive(), false);
187
+ assert.equal(body.children.length, 0);
188
+ });
189
+
190
+ // ── 回归:没配置 mesh.webPanelIdleMs 时必须落到默认 10 分钟 ──
191
+ // getItem 未命中返回 null,而 Number(null) 是 0 —— 曾经因此把「没配置」读成
192
+ // 「收起即拆」,每次 hide() 立刻销毁 iframe,秒切整个失效。
193
+ const emptyStore = new Map();
194
+ let captured2 = null;
195
+ globalThis.window = {
196
+ __ModuleLoader__: {
197
+ load: (entry) => {
198
+ captured2 = entry;
199
+ },
200
+ },
201
+ localStorage: {
202
+ getItem: (key) => (emptyStore.has(key) ? emptyStore.get(key) : null),
203
+ setItem: (key, value) => emptyStore.set(key, String(value)),
204
+ },
205
+ addEventListener: () => {},
206
+ };
207
+ new Function("window", `${readFileSync(BUNDLE, "utf8")}\n`)(globalThis.window);
208
+ const mod2 = captured2.factory((name) => {
209
+ if (name === "react") return reactStub;
210
+ if (name === "react-dom/client") return reactDomStub;
211
+ throw new Error(`未预期的依赖:${name}`);
212
+ });
213
+
214
+ ok("未配置空闲时长 → 默认 10 分钟(不是 0)", () => {
215
+ assert.equal(mod2.__test.WEB_PANEL_IDLE_DEFAULT, 10 * 60 * 1000);
216
+ assert.equal(mod2.__test.readWebPanelIdleMs(), mod2.__test.WEB_PANEL_IDLE_DEFAULT);
217
+ });
218
+
219
+ await okAsync("默认配置下收起:宽限期内 iframe 必须还活着", async () => {
220
+ const layer2 = mod2.__test.webPanelLayer;
221
+ await layer2.open({ machine: "hos", id: "x1" });
222
+ layer2.hide();
223
+ await sleep(40);
224
+ assert.equal(layer2.__alive(), true, "收起后立刻销毁 = 秒切失效");
225
+ layer2.dispose();
226
+ assert.equal(layer2.__alive(), false);
227
+ });
228
+
229
+ await okAsync("可见期间心跳:按时续命,地址不变就不重载", async () => {
230
+ const layer2 = mod2.__test.webPanelLayer;
231
+ hostUrl = "http://127.0.0.1:5555/?k=keep";
232
+ await layer2.open({ machine: "hos", id: "x1" });
233
+ const base = calls.filter((call) => call.url.endsWith("/mesh/api/web-panel")).length;
234
+ const before = rendered.length;
235
+ layer2.__setHeartbeatMs(20);
236
+ await sleep(70);
237
+ const after = calls.filter((call) => call.url.endsWith("/mesh/api/web-panel")).length;
238
+ assert.ok(after > base, "心跳应持续打 /web-panel");
239
+ assert.equal(rendered.length, before, "地址没变就不该重绘/重载");
240
+ assert.equal(layer2.__alive(), true);
241
+ layer2.dispose();
242
+ });
243
+
244
+ await okAsync("心跳自愈:宿主回收后重建过(地址变了)→ iframe 换到新地址重载", async () => {
245
+ const layer3 = mod2.__test.webPanelLayer;
246
+ hostUrl = "http://127.0.0.1:6666/?k=old";
247
+ await layer3.open({ machine: "hos", id: "x1" });
248
+ const before = rendered.length;
249
+ hostUrl = "http://127.0.0.1:7777/?k=new";
250
+ layer3.__setHeartbeatMs(20);
251
+ await sleep(70);
252
+ const last = rendered[rendered.length - 1];
253
+ assert.equal(rendered.length, before + 1, "地址变了应重绘一次");
254
+ assert.ok(last && last.props && last.props.panel, "最后一次渲染应带 panel");
255
+ assert.equal(last.props.panel.url, "http://127.0.0.1:7777/?k=new");
256
+ assert.equal(last.props.panel.reloadKey, 1, "重载计数应 +1");
257
+ layer3.dispose();
258
+ });
259
+
260
+ await okAsync("心跳失败:宿主说保不住 → 拆面板并提示重开", async () => {
261
+ const layer4 = mod2.__test.webPanelLayer;
262
+ hostUrl = "http://127.0.0.1:8888/?k=x";
263
+ hostFail = false;
264
+ await layer4.open({ machine: "hos", id: "x1" });
265
+ hostFail = true;
266
+ layer4.__setHeartbeatMs(20);
267
+ await sleep(70);
268
+ assert.equal(layer4.__alive(), false, "保不住时应销毁面板");
269
+ layer4.dispose();
270
+ hostFail = false;
271
+ });
272
+
273
+ console.log(`\n全部通过:${passed} 通过 / 0 失败`);
package/lib/index.js CHANGED
@@ -130,7 +130,7 @@ import {
130
130
  export const name = "dsh-plugin-mesh";
131
131
  export const inject = ["tools", "webServer"];
132
132
 
133
- const VERSION = "0.5.19";
133
+ const VERSION = "0.5.20";
134
134
  // 诊断用:进程启动时间 + 入口真实路径。磁盘上的版本**不在这里缓存** ——
135
135
  // 升级之后进程还跑旧代码,版本号必须现读磁盘才能立刻反映出来(真踩过:
136
136
  // 磁盘升到 0.5.1,进程还在 0.5.0,界面显示 0.5.0)。
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-plugin-mesh",
3
- "version": "0.5.19",
3
+ "version": "0.5.20",
4
4
  "type": "module",
5
5
  "description": "把跑不完的活交给另一台电脑;跑完,结果回到你面前。两台装了 DSH 的电脑各装一次,自动互相发现,任务派过去由对端的 agent 执行,结果派回来。Hand a long task to another machine: your DSH instances find each other, the peer runs it, and the result comes back. No pairing codes, no IPs, no Tailscale client.",
6
6
  "license": "MIT",
@@ -69,7 +69,7 @@
69
69
  "selftest:update": "node lib/_selftest-update.mjs",
70
70
  "selftest:upgrade": "node lib/_selftest-upgrade.mjs",
71
71
  "selftest:approval": "node lib/_selftest-approval.mjs",
72
- "test": "npm run check && npm run selftest && npm run selftest:prompt && npm run selftest:at && npm run selftest:at:host && npm run selftest:pairing && npm run selftest:approval && npm run selftest:switch && npm run selftest:client && npm run selftest:caps && npm run selftest:release && npm run selftest:reply && npm run selftest:reasoning && npm run selftest:resume && npm run selftest:persist && npm run selftest:layout && npm run selftest:diagnostics && npm run selftest:osinfo && npm run selftest:peerweb && npm run selftest:webtarget && npm run selftest:webfence && npm run selftest:sshtarget && npm run selftest:update && npm run selftest:upgrade",
72
+ "test": "npm run check && npm run selftest && npm run selftest:prompt && npm run selftest:at && npm run selftest:at:host && npm run selftest:pairing && npm run selftest:approval && npm run selftest:switch && npm run selftest:client && npm run selftest:caps && npm run selftest:release && npm run selftest:reply && npm run selftest:reasoning && npm run selftest:resume && npm run selftest:persist && npm run selftest:layout && npm run selftest:diagnostics && npm run selftest:osinfo && npm run selftest:peerweb && npm run selftest:webtarget && npm run selftest:webfence && npm run selftest:webhost && npm run selftest:sshtarget && npm run selftest:update && npm run selftest:upgrade",
73
73
  "check": "node scripts/check-version.mjs && node scripts/check-tdz.mjs && node --check lib/index.js && node --check lib/layout.js && node --check lib/discovery.js && node --check lib/conversation.js && node --check lib/identity.js && node --check lib/capabilities.js && node --check lib/prompt.js && node --check lib/at-mention.js && node --check lib/pairing.js && node --check lib/switch.js && node --check lib/scan.js && node --check lib/update.js && node --check lib/upgrade.js && node --check lib/peer-web.js && node --check lib/web-target.js && node --check lib/web-fence.js && node --check lib/ssh-target.js && node --check lib/tsnet/download.js && node --check lib/tsnet/manager.js && node --check lib/tsnet/bridge.js && node --check lib/tsnet/channels.js && node --check client/client.js && node --check scripts/release-plan.mjs && npm run check:loadable && npm run check:docs",
74
74
  "build:sidecar": "bash scripts/build-sidecar.sh",
75
75
  "verify:mirror": "node scripts/verify-lan-mirror.mjs",
@@ -87,6 +87,7 @@
87
87
  "selftest:peerweb": "node lib/_selftest-peer-web.mjs",
88
88
  "selftest:webtarget": "node lib/_selftest-web-target.mjs",
89
89
  "selftest:webfence": "node lib/_selftest-web-fence.mjs",
90
+ "selftest:webhost": "node lib/_selftest-webhost.mjs",
90
91
  "selftest:sshtarget": "node lib/_selftest-ssh-target.mjs"
91
92
  },
92
93
  "publishConfig": {