dsh-plugin-mesh 0.5.4 → 0.5.5

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.
@@ -71,8 +71,31 @@ async function makeNode(machine) {
71
71
  node.agents.set(id, { messages: [], followup(message) { this.messages.push(message); } });
72
72
  return id;
73
73
  } } };
74
- const options = { ...node, discovery, config: node.config, log: noop, warn: noop, waker, capFor: () => node.config.maxWakesPerThread, capOverrides: new Map(), throttled: new Map() };
75
- node.port = await module.namespace.startPeerServer(ctx, options);
74
+ // 一键关闭的门面:这里用可观测的替身,验证工具的参数处理与回报文案;
75
+ // 真正的停/启逻辑由 applyUnsafe 的运行时 + /mesh/api/switch 承担。
76
+ node.switchCalls = [];
77
+ node.switchStatus = () => ({
78
+ lan: { off: false, active: true, bind: "0.0.0.0", port: node.port, multicast: false, note: "" },
79
+ internet: { off: false, active: false, running: 0, configured: 0, note: "" },
80
+ all: false,
81
+ at: "",
82
+ by: "",
83
+ summary: "局域网 开启 · 互联网 开启",
84
+ });
85
+ const meshSwitch = {
86
+ status: () => node.switchStatus(),
87
+ set: async (opts) => {
88
+ node.switchCalls.push(opts);
89
+ return { changed: true, scope: opts.scope, status: node.switchStatus() };
90
+ },
91
+ };
92
+ const options = { ...node, discovery, config: node.config, log: noop, warn: noop, waker, meshSwitch, capFor: () => node.config.maxWakesPerThread, capOverrides: new Map(), throttled: new Map() };
93
+ // startPeerServer 现在返回句柄(一键关闭要重绑监听地址),端口在 handle.port 上。
94
+ const handle = await module.namespace.startPeerServer(ctx, options);
95
+ node.port = handle.port;
96
+ node.server = handle.server;
97
+ cleanups.push(() => handle.server.close());
98
+ node.gate = module.namespace.transportGate;
76
99
  module.namespace.registerTools(ctx, options);
77
100
  node.peer = { machine, id: machine, online: true, host: "127.0.0.1", port: node.port,
78
101
  endpoints: [{ transport: "lan", host: "127.0.0.1", port: node.port, lastSeen: Date.now() }] };
@@ -82,6 +105,15 @@ async function makeNode(machine) {
82
105
  return node;
83
106
  }
84
107
 
108
+ /**
109
+ * 一键关闭的入站闸门必须真有牙:gate 关掉后连 health 都要 503,
110
+ * 打开后立刻恢复。这条同时守住"别只改界面不改后端"。
111
+ */
112
+ async function probeHealth(node) {
113
+ const res = await fetch(`http://127.0.0.1:${node.port}/mesh/v1/health`);
114
+ return { status: res.status, body: await res.json().catch(() => ({})) };
115
+ }
116
+
85
117
  async function until(check) {
86
118
  const end = Date.now() + 3000;
87
119
  while (!check()) {
@@ -158,6 +190,52 @@ try {
158
190
  assert.equal(a.created, 1);
159
191
  console.log("✓ noWake, wake cap and explicit newSession still apply");
160
192
 
193
+ // 一键关闭的工具面:三个范围、默认关闭、不认识的范围要明确报错。
194
+ const switchTool = b.tools.get("mesh_switch");
195
+ assert.ok(switchTool, "必须注册 mesh_switch");
196
+ const offText = await switchTool.execute({ scope: "局域网", action: "off" });
197
+ assert.match(offText, /局域网 mesh已关闭/, offText);
198
+ assert.match(offText, /当前:局域网 开启/, offText);
199
+ // 注意:工具在 vm 里执行,跨 realm 的对象原型不同,不能 deepStrictEqual
200
+ assert.equal(b.switchCalls.at(-1).scope, "lan");
201
+ assert.equal(b.switchCalls.at(-1).off, true);
202
+ assert.equal(b.switchCalls.at(-1).by, "tool");
203
+ await switchTool.execute({ scope: "all" });
204
+ assert.equal(b.switchCalls.at(-1).off, true, "action 省略时默认关闭");
205
+ const onText = await switchTool.execute({ scope: "internet", action: "on" });
206
+ assert.equal(b.switchCalls.at(-1).off, false);
207
+ assert.match(onText, /互联网 mesh已打开/, onText);
208
+ assert.match(await switchTool.execute({ scope: "wifi" }), /scope 不合法/);
209
+ assert.match(await switchTool.execute({ scope: "lan", action: "shutdown" }), /action 不合法/);
210
+ assert.match(await b.tools.get("mesh_peers").execute({}), /开关: 局域网 开启/, "mesh_peers 要带上开关状态");
211
+
212
+ // 全部关闭时,派发与扫描都必须直接拒绝并说明原因(不是"对端离线")。
213
+ b.switchStatus = () => ({
214
+ lan: { off: true, active: false, bind: "", port: 0, multicast: false, note: "" },
215
+ internet: { off: true, active: false, running: 0, configured: 0, note: "" },
216
+ all: true,
217
+ at: "",
218
+ by: "tool",
219
+ summary: "mesh 已全部关闭(局域网 + 互联网)",
220
+ });
221
+ assert.match(await b.send("A", "closed", "mesh-B-1"), /已全部关闭/);
222
+ assert.match(await b.tools.get("mesh_scan").execute({}), /已全部关闭/);
223
+ assert.match(await b.tools.get("mesh_peers").execute({}), /已全部关闭/);
224
+ assert.doesNotMatch(await b.tools.get("mesh_peers").execute({}), /^没有发现其他 DSH 机器/, "关闭导致的空列表不能说成「没发现」");
225
+ console.log("✓ mesh_switch: scopes, default off, invalid input, and closed-state refusals");
226
+
227
+ // 一键关闭:入站闸门要对 health 也生效,打开后立刻恢复。
228
+ a.gate.lan = false;
229
+ const closed = await probeHealth(a);
230
+ assert.equal(closed.status, 503, "局域网关闭后,对端健康探测必须被拒绝");
231
+ assert.equal(closed.body.closed, true);
232
+ assert.match(String(closed.body.error || ""), /局域网 mesh 已关闭/);
233
+ a.gate.lan = true;
234
+ const reopened = await probeHealth(a);
235
+ assert.equal(reopened.status, 200, "打开后必须恢复");
236
+ assert.equal(reopened.body.ok, true);
237
+ console.log("✓ kill switch closes the inbound peer API and reopens it");
238
+
161
239
  // Missing thread or originating session must not create a reply binding.
162
240
  const bindings = a.threadState.size;
163
241
  await a.send("B", "", "original-session", { noWake: true });
@@ -0,0 +1,142 @@
1
+ /**
2
+ * 一键关闭(kill switch)判定的自测。
3
+ *
4
+ * 这段和配对码一样**安全相关**,而且判错的后果同样是静默的:界面显示
5
+ * "已关闭",端口却还开在 0.0.0.0 上。必须用断言盯着这几件事:
6
+ * · 缺省是"开着"(升级不会突然断开所有人)
7
+ * · 关"全部"必须两个范围都关(不能只关一半)
8
+ * · 只认严格布尔 true(防手工编辑/YAML 字符串坑)
9
+ * · 打开其中一个范围时,另一个范围保持原样(不能顺带把别人开了/关了)
10
+ *
11
+ * node lib/_selftest-switch.mjs
12
+ */
13
+ import { strict as assert } from "node:assert";
14
+ import {
15
+ MESH_SWITCH_SCOPES,
16
+ applyMeshSwitch,
17
+ describeMeshSwitch,
18
+ normalizeSwitchScope,
19
+ resolveMeshSwitch,
20
+ } from "./switch.js";
21
+
22
+ let passed = 0;
23
+ let failed = 0;
24
+ function test(name, fn) {
25
+ try {
26
+ fn();
27
+ passed += 1;
28
+ console.log(` ✓ ${name}`);
29
+ } catch (err) {
30
+ failed += 1;
31
+ console.log(` ✗ ${name}`);
32
+ console.log(` ${err?.message ?? err}`);
33
+ }
34
+ }
35
+
36
+ console.log("\n── 缺省:都开着(升级不会突然断开)──");
37
+
38
+ test("空 state / 空入参 → 都开着", () => {
39
+ for (const st of [{}, null, undefined, { shutdown: null }, { shutdown: {} }]) {
40
+ const r = resolveMeshSwitch(st);
41
+ assert.equal(r.lan, false);
42
+ assert.equal(r.internet, false);
43
+ assert.equal(r.all, false);
44
+ }
45
+ });
46
+
47
+ test("只写了一个范围 → 另一个范围仍是开着", () => {
48
+ const r = resolveMeshSwitch({ shutdown: { lan: true } });
49
+ assert.equal(r.lan, true);
50
+ assert.equal(r.internet, false);
51
+ assert.equal(r.all, false);
52
+ });
53
+
54
+ console.log("\n── 只认严格布尔 true ──");
55
+
56
+ test('字符串 "true" / 数字 1 都不算关闭 —— 否则会让人以为关了、实际没关', () => {
57
+ for (const v of ["true", 1, "1", "yes", {}, []]) {
58
+ const r = resolveMeshSwitch({ shutdown: { lan: v, internet: v } });
59
+ assert.equal(r.lan, false, `lan=${JSON.stringify(v)}`);
60
+ assert.equal(r.internet, false, `internet=${JSON.stringify(v)}`);
61
+ }
62
+ });
63
+
64
+ console.log("\n── 合并:关全部 = 两个都关,别只关一半 ──");
65
+
66
+ test("关 all → lan 与 internet 都为 true(已关闭)", () => {
67
+ const next = applyMeshSwitch(resolveMeshSwitch({}), { scope: "all", off: true, by: "ui", at: "T" });
68
+ assert.deepEqual(next, { lan: true, internet: true, at: "T", by: "ui" });
69
+ });
70
+
71
+ test("只关局域网 → 互联网不受影响", () => {
72
+ const next = applyMeshSwitch(resolveMeshSwitch({}), { scope: "lan", off: true, at: "T" });
73
+ assert.equal(next.lan, true);
74
+ assert.equal(next.internet, false);
75
+ });
76
+
77
+ test("只关互联网 → 局域网不受影响", () => {
78
+ const next = applyMeshSwitch(resolveMeshSwitch({}), { scope: "internet", off: true, at: "T" });
79
+ assert.equal(next.lan, false);
80
+ assert.equal(next.internet, true);
81
+ });
82
+
83
+ test("从「全部关闭」只打开局域网 → 互联网保持关闭(不能顺带全开)", () => {
84
+ const closed = resolveMeshSwitch({ shutdown: { lan: true, internet: true } });
85
+ const next = applyMeshSwitch(closed, { scope: "lan", off: false, at: "T" });
86
+ assert.equal(next.lan, false);
87
+ assert.equal(next.internet, true);
88
+ assert.equal(resolveMeshSwitch({ shutdown: next }).all, false);
89
+ });
90
+
91
+ test("从「全部关闭」打开全部 → 都开", () => {
92
+ const closed = resolveMeshSwitch({ shutdown: { lan: true, internet: true } });
93
+ const next = applyMeshSwitch(closed, { scope: "all", off: false, at: "T" });
94
+ assert.equal(next.lan, false);
95
+ assert.equal(next.internet, false);
96
+ });
97
+
98
+ test("applyMeshSwitch 不修改入参", () => {
99
+ const before = { lan: false, internet: true, at: "", by: "" };
100
+ const frozen = JSON.stringify(before);
101
+ applyMeshSwitch(before, { scope: "all", off: true });
102
+ assert.equal(JSON.stringify(before), frozen);
103
+ });
104
+
105
+ test("off 漏传时按「关闭」处理(一键关闭是主动作)", () => {
106
+ const next = applyMeshSwitch(resolveMeshSwitch({}), { scope: "lan" });
107
+ assert.equal(next.lan, true);
108
+ });
109
+
110
+ console.log("\n── 范围归一化:中英文都收,不认识的必须报错而不是乱猜 ──");
111
+
112
+ test("英文 id 与界面中文词都能识别", () => {
113
+ assert.equal(normalizeSwitchScope("all"), "all");
114
+ assert.equal(normalizeSwitchScope("LAN"), "lan");
115
+ assert.equal(normalizeSwitchScope(" 互联网 "), "internet");
116
+ assert.equal(normalizeSwitchScope("局域网 mesh"), "lan");
117
+ assert.equal(normalizeSwitchScope("全部"), "all");
118
+ });
119
+
120
+ test("不认识的 scope 直接抛错(不静默关掉全部,也不静默什么都不做)", () => {
121
+ for (const bad of ["", "everything", "wifi", null, undefined, 0]) {
122
+ assert.throws(() => applyMeshSwitch(resolveMeshSwitch({}), { scope: bad }), /未知的开关范围/);
123
+ }
124
+ });
125
+
126
+ test("MESH_SWITCH_SCOPES 与界面顺序一致", () => {
127
+ assert.deepEqual(MESH_SWITCH_SCOPES, ["all", "lan", "internet"]);
128
+ });
129
+
130
+ console.log("\n── 摘要文案:读的人要能判断现在能不能派任务 ──");
131
+
132
+ test("全部关闭时明确说「全部关闭」", () => {
133
+ assert.match(describeMeshSwitch({ lan: true, internet: true }), /全部关闭/);
134
+ });
135
+ test("只说一个范围时,另一个也要说清楚是开着的", () => {
136
+ const txt = describeMeshSwitch({ lan: true, internet: false });
137
+ assert.match(txt, /局域网 已关闭/);
138
+ assert.match(txt, /互联网 开启/);
139
+ });
140
+
141
+ console.log(`\n${failed === 0 ? "全部通过" : "有失败"}:${passed} 通过 / ${failed} 失败\n`);
142
+ process.exit(failed === 0 ? 0 : 1);
@@ -16,7 +16,17 @@ import { tmpdir } from "node:os";
16
16
  import { dirname, join } from "node:path";
17
17
  import { detectTarget, assetName, candidateUrls, binDir, binaryPath, binaryInfo, cacheIsCurrent, downloadToBuffer, SIDECAR_PROTOCOL } from "./tsnet/download.js";
18
18
  import { PINNED_CHECKSUMS } from "./tsnet/checksums.js";
19
- import { toHostname, TsnetNode, channelKey, channelDir, channelStateDir } from "./tsnet/manager.js";
19
+ import {
20
+ toHostname,
21
+ TsnetNode,
22
+ channelKey,
23
+ channelDir,
24
+ channelStateDir,
25
+ extractLoginFailure,
26
+ explainTailnetFailure,
27
+ evaluateTailnetProgress,
28
+ TSNET_STALL_MS,
29
+ } from "./tsnet/manager.js";
20
30
  import { resolveTailnetChannels } from "./tsnet/channels.js";
21
31
  import { tailnetOrigin, isTailnetAddress } from "./tsnet/bridge.js";
22
32
  import { MeshDiscovery, orderedEndpoints, endpointAlive } from "./discovery.js";
@@ -840,5 +850,80 @@ check("回信地址与会话键是两件事,不能混用", () => {
840
850
  assert.ok(!conversationKey(t).includes("sess-remote-123"));
841
851
  });
842
852
 
853
+ console.log("\n── 启动受阻:不能永远显示「正在启动」──");
854
+
855
+ check("从 sidecar 诊断里取出登录失败原因(真机 2026-10-29 原文)", () => {
856
+ const diag = [
857
+ "health(warnable=warming-up): ok",
858
+ "control: [v1] TryLogin: register request: Post \"https://controlplane.tailscale.com/machine/register\": connection attempts aborted by context: context deadline exceeded",
859
+ "health(warnable=login-state): error: You are logged out. The last login error was: register request: Post \"https://controlplane.tailscale.com/machine/register\": connection attempts aborted by context: context deadline exceeded",
860
+ "control: authRoutine: [v1] backoff: 50 msec",
861
+ ];
862
+ const text = extractLoginFailure(diag);
863
+ assert.match(text, /deadline exceeded/, text);
864
+ assert.ok(!text.startsWith("You are logged out"), "要去掉套话,只留能读的原因");
865
+ });
866
+
867
+ check("没有登录错误时返回空串(不要凭空编一个原因)", () => {
868
+ assert.equal(extractLoginFailure([]), "");
869
+ assert.equal(extractLoginFailure(["netmap: self: [x] ..."]), "");
870
+ assert.equal(extractLoginFailure(null), "");
871
+ });
872
+
873
+ check("超时类错误 → 提示检查代理(sidecar 走裸 TCP)", () => {
874
+ const hint = explainTailnetFailure("register request: ... context deadline exceeded");
875
+ assert.match(hint, /代理/);
876
+ assert.match(hint, /裸 TCP/);
877
+ });
878
+
879
+ check("授权码类错误 → 指向 Reusable auth key", () => {
880
+ assert.match(explainTailnetFailure("invalid key: empty"), /Reusable/);
881
+ assert.match(explainTailnetFailure("401 Unauthorized"), /Reusable/);
882
+ });
883
+
884
+ check("认不出的错误不给建议(宁可不猜)", () => {
885
+ assert.equal(explainTailnetFailure("something odd happened"), "");
886
+ assert.equal(explainTailnetFailure(""), "");
887
+ });
888
+
889
+ check("受阻阈值足够长:正常的十几秒握手不会被误报", () => {
890
+ assert.ok(TSNET_STALL_MS >= 60000, `TSNET_STALL_MS=${TSNET_STALL_MS}`);
891
+ });
892
+
893
+ check("卡满阈值 → 判受阻;刚启动 / 已有地址 / 等授权都不算", () => {
894
+ const now = 1_000_000;
895
+ const base = { now, stallMs: 60000, startingSince: now - 61000 };
896
+ assert.equal(evaluateTailnetProgress({ ...base, phase: "starting" }).stalled, true, "卡了 61s 应判受阻");
897
+ assert.equal(evaluateTailnetProgress({ ...base, phase: "starting", selfIpv4: "100.64.0.9" }).stalled, false, "有地址不算受阻");
898
+ assert.equal(evaluateTailnetProgress({ ...base, phase: "starting", authUrl: "https://x" }).stalled, false, "等授权不算受阻");
899
+ assert.equal(evaluateTailnetProgress({ ...base, startingSince: now - 1000, phase: "starting" }).stalled, false, "刚启动不算");
900
+ assert.equal(evaluateTailnetProgress({ ...base, phase: "running" }).stalled, false, "已连接不算");
901
+ assert.equal(evaluateTailnetProgress({ ...base, phase: "starting", startingSince: 0 }).stalled, false, "没有计时不清空前提");
902
+ });
903
+
904
+ check("needs-login 但没有授权链接 → 也算受阻(实测形状:只显示「需要授权」却没链接可点)", () => {
905
+ const now = 1_000_000;
906
+ const base = { now, stallMs: 60000, startingSince: now - 61000, selfIpv4: "" };
907
+ assert.equal(evaluateTailnetProgress({ ...base, phase: "needs-login", authUrl: "" }).stalled, true);
908
+ assert.equal(evaluateTailnetProgress({ ...base, phase: "needs-login", authUrl: "https://login" }).stalled, false);
909
+ });
910
+
911
+ check("受阻状态从 starting 变来,恢复时退回 starting(不谎报已连接)", () => {
912
+ const now = 1_000_000;
913
+ const stalled = evaluateTailnetProgress({ phase: "starting", startingSince: now - 120000, now, stallMs: 60000 });
914
+ assert.equal(stalled.phase, "stalled");
915
+ const recovering = evaluateTailnetProgress({ phase: "stalled", startingSince: now - 120000, now, stallMs: 60000, selfIpv4: "100.64.0.9" });
916
+ assert.equal(recovering.stalled, false);
917
+ assert.equal(recovering.phase, "starting");
918
+ });
919
+
920
+ check("新节点默认不显示受阻,且带 stalled 字段给界面用", () => {
921
+ const node = new TsnetNode({ channel: { id: "t1", label: "T", authKey: "", controlUrl: "", hostname: "" }, machineName: "m" });
922
+ const st = node.status();
923
+ assert.equal(st.stalled, false);
924
+ assert.equal(st.stalledReason, "");
925
+ assert.equal(st.phase, "idle");
926
+ });
927
+
843
928
  console.log(`\n结果:${passed} 通过,${failed} 失败\n`);
844
929
  process.exit(failed === 0 ? 0 : 1);
@@ -140,6 +140,9 @@ const {
140
140
  sendToAgent,
141
141
  PairingBody,
142
142
  TsnetBody,
143
+ SwitchBody,
144
+ SwitchRow,
145
+ HomeSwitchBar,
143
146
  } = mod.__test;
144
147
 
145
148
  const noop = () => {};
@@ -830,5 +833,238 @@ await testAsync("sendToAgent 写入并提交当前会话草稿", async () => {
830
833
  assert.equal(status, "sent");
831
834
  });
832
835
 
836
+ console.log("\n── 一键关闭:三个范围都要看得见、说清后果 ──");
837
+
838
+ const swOn = {
839
+ lan: { off: false, active: true, bind: "0.0.0.0", port: 45917, multicast: true, note: "" },
840
+ internet: { off: false, active: true, running: 1, configured: 2, note: "" },
841
+ all: false,
842
+ at: "",
843
+ by: "",
844
+ summary: "局域网 开启 · 互联网 开启",
845
+ };
846
+
847
+ test("三行开关都在:全部 / 局域网 / 互联网,且当前是可关闭状态", () => {
848
+ const txt = textOf(SwitchBody({ sw: swOn, push: noop, reload: async () => {} })).join(" ");
849
+ assert.ok(txt.includes("全部 Mesh"), txt);
850
+ assert.ok(txt.includes("局域网 Mesh"), txt);
851
+ assert.ok(txt.includes("互联网 Mesh"), txt);
852
+ assert.ok(txt.includes("一键关闭"), txt);
853
+ assert.ok(txt.includes("重启 DSH 后仍保持关闭"), "必须写明跨重启保持");
854
+ });
855
+
856
+ test("开着时能看见真实监听信息,而不是只说「开」", () => {
857
+ const txt = textOf(SwitchBody({ sw: swOn, push: noop, reload: async () => {} })).join(" ");
858
+ assert.ok(txt.includes("0.0.0.0:45917"), txt);
859
+ assert.ok(txt.includes("组播 开"), txt);
860
+ assert.ok(txt.includes("运行中 1 / 已启用 2 条通道"), txt);
861
+ });
862
+
863
+ test("全部关闭时:三行都显示已关闭,按钮变成「打开」", () => {
864
+ const off = {
865
+ ...swOn,
866
+ lan: { ...swOn.lan, off: true, active: false, bind: "127.0.0.1" },
867
+ internet: { ...swOn.internet, off: true, active: false, running: 0 },
868
+ all: true,
869
+ by: "ui",
870
+ at: "2026-01-01T00:00:00.000Z",
871
+ summary: "mesh 已全部关闭(局域网 + 互联网)",
872
+ };
873
+ const txt = textOf(SwitchBody({ sw: off, push: noop, reload: async () => {} })).join(" ");
874
+ assert.ok((txt.match(/已关闭/g) || []).length >= 3, txt);
875
+ assert.ok(txt.includes("打开"), txt);
876
+ assert.ok(txt.includes("界面"), "要说明这次是界面操作的");
877
+ });
878
+
879
+ test("只关局域网:互联网行仍报运行中的通道(不能一起静音)", () => {
880
+ const half = {
881
+ ...swOn,
882
+ lan: { ...swOn.lan, off: true, active: false, bind: "127.0.0.1" },
883
+ all: false,
884
+ summary: "局域网 已关闭 · 互联网 开启",
885
+ };
886
+ const txt = textOf(SwitchBody({ sw: half, push: noop, reload: async () => {} })).join(" ");
887
+ assert.ok(txt.includes("运行中 1 / 已启用 2 条通道"), txt);
888
+ assert.ok(txt.includes("组播已停"), txt);
889
+ assert.ok(txt.includes("部分关闭"), "只关了一条时,「全部」那行必须显示部分关闭");
890
+ });
891
+
892
+ test("老宿主没有 switch 字段时不渲染这个区块(避免出现一个点了没用的开关)", () => {
893
+ const view = textOf(
894
+ SettingsView({ state, open: null, onOpen: noop, onSaveName: async () => true, nameBusy: false, push: noop, reload: async () => {} }),
895
+ ).join(" ");
896
+ assert.ok(!view.includes("一键关闭"), view.slice(0, 400));
897
+ });
898
+
899
+ test("重绑失败这类偏差必须显示出来(不能显示「已关闭」就完事)", () => {
900
+ const bad = {
901
+ ...swOn,
902
+ lan: { ...swOn.lan, off: true, active: false, bind: "0.0.0.0", note: "端口仍对局域网开放(未能收回回环,检查端口占用)" },
903
+ all: false,
904
+ };
905
+ const txt = textOf(SwitchBody({ sw: bad, push: noop, reload: async () => {} })).join(" ");
906
+ assert.ok(txt.includes("端口仍对局域网开放"), txt);
907
+ });
908
+
909
+ test("坏数据不崩(老版本宿主没有 switch 字段)", () => {
910
+ for (const sw of [null, undefined, {}, { lan: null }, { lan: {}, internet: {} }, { all: true }]) {
911
+ const el = SwitchBody({ sw, push: noop, reload: async () => {} });
912
+ assert.ok(el, JSON.stringify(sw));
913
+ textOf(el);
914
+ }
915
+ });
916
+
917
+ test("连接页出现「一键关闭」区块,且包含三条范围", () => {
918
+ const view = textOf(
919
+ SettingsView({
920
+ state: { ...state, switch: swOn },
921
+ open: "switch",
922
+ onOpen: noop,
923
+ onSaveName: async () => true,
924
+ nameBusy: false,
925
+ push: noop,
926
+ reload: async () => {},
927
+ }),
928
+ ).join(" ");
929
+ assert.ok(view.includes("一键关闭"), view.slice(0, 400));
930
+ assert.ok(view.includes("全部 Mesh"), view);
931
+ assert.ok(view.includes("局域网 Mesh"), view);
932
+ assert.ok(view.includes("互联网 Mesh"), view);
933
+ });
934
+
935
+ test("连接页区块标题按状态说话:全部关闭时不是「全部开启」", () => {
936
+ const off = { ...swOn, all: true, lan: { ...swOn.lan, off: true }, internet: { ...swOn.internet, off: true } };
937
+ const view = textOf(
938
+ SettingsView({
939
+ state: { ...state, switch: off },
940
+ open: null,
941
+ onOpen: noop,
942
+ onSaveName: async () => true,
943
+ nameBusy: false,
944
+ push: noop,
945
+ reload: async () => {},
946
+ }),
947
+ ).join(" ");
948
+ assert.ok(view.includes("全部已关闭"), view.slice(0, 500));
949
+ assert.ok(!view.includes("全部开启"), "关闭时不能还写全部开启");
950
+ });
951
+
952
+ console.log("\n── 主页概览:一键关闭要能直接点 ──");
953
+
954
+ test("概览卡上的三个胶囊都在,状态直接的可读", () => {
955
+ const txt = textOf(HomeSwitchBar({ sw: swOn, push: noop, reload: async () => {} })).join(" ");
956
+ assert.ok(txt.includes("一键关闭"), txt);
957
+ assert.ok(txt.includes("全部"), txt);
958
+ assert.ok(txt.includes("局域网"), txt);
959
+ assert.ok(txt.includes("互联网"), txt);
960
+ assert.ok(txt.includes("开"), txt);
961
+ });
962
+
963
+ test("概览胶囊把关闭/受阻状态写在脸上(不用展开设置页)", () => {
964
+ const half = {
965
+ ...swOn,
966
+ lan: { ...swOn.lan, off: true, active: false },
967
+ internet: { ...swOn.internet, off: false, active: false, stalled: 2, note: "控制面连不上" },
968
+ all: false,
969
+ };
970
+ const txt = textOf(HomeSwitchBar({ sw: half, push: noop, reload: async () => {} })).join(" ");
971
+ assert.ok(txt.includes("已关"), txt);
972
+ assert.ok(txt.includes("受阻"), txt);
973
+ });
974
+
975
+ test("老宿主没有 switch 字段时,概览不显示这块(不占位)", () => {
976
+ for (const sw of [null, undefined]) {
977
+ assert.equal(HomeSwitchBar({ sw, push: noop, reload: async () => {} }), null);
978
+ }
979
+ });
980
+
981
+ test("概览卡真的把一键关闭放进去了(不只是定义了组件)", () => {
982
+ const el = HomeBoard({
983
+ state: { ...state, switch: swOn },
984
+ self: state.self,
985
+ peers: [peer],
986
+ tasks: [],
987
+ now,
988
+ lastOk: now,
989
+ focus: false,
990
+ layout: ["overview"],
991
+ sizes: {},
992
+ customCards: [],
993
+ density: "comfortable",
994
+ onLayoutChange: noop,
995
+ onFocusChange: noop,
996
+ onSizesChange: noop,
997
+ onCustomCardsChange: noop,
998
+ onDensityChange: noop,
999
+ onReset: noop,
1000
+ onDevices: noop,
1001
+ onTasks: noop,
1002
+ onConnect: noop,
1003
+ onScan: noop,
1004
+ scanning: false,
1005
+ hostDown: false,
1006
+ onDispatched: noop,
1007
+ push: noop,
1008
+ reload: async () => {},
1009
+ firstRun: null,
1010
+ });
1011
+ const txt = textOf(el).join(" ");
1012
+ assert.ok(txt.includes("一键关闭"), txt.slice(0, 400));
1013
+ assert.ok(txt.includes("局域网"), txt);
1014
+ });
1015
+
1016
+ console.log("\n── 互联网:卡在控制面时必须说出来 ──");
1017
+
1018
+ test("通道卡住 → 显示「启动受阻」、原因与可执行提示,按钮变「重试连接」", () => {
1019
+ const tsnet = {
1020
+ enabled: true,
1021
+ channels: [
1022
+ {
1023
+ id: "ch-1",
1024
+ label: "Tailscale",
1025
+ enabled: true,
1026
+ authKeySaved: true,
1027
+ controlUrl: "",
1028
+ node: {
1029
+ phase: "stalled",
1030
+ stalled: true,
1031
+ stalledReason: "register request: ... deadline exceeded",
1032
+ stalledHint: "控制面连不上:检查本机网络或代理。sidecar 走的是裸 TCP/UDP,只放行 HTTP 客户端的代理设置对它无效。",
1033
+ diagnostics: [],
1034
+ },
1035
+ recentEvents: [],
1036
+ },
1037
+ ],
1038
+ };
1039
+ const txt = textOf(TsnetBody({ tsnet, push: noop, reload: async () => {} })).join(" ");
1040
+ assert.ok(txt.includes("启动受阻"), txt);
1041
+ assert.ok(txt.includes("deadline exceeded"), txt);
1042
+ assert.ok(txt.includes("裸 TCP"), txt);
1043
+ assert.ok(txt.includes("重试连接"), txt);
1044
+ });
1045
+
1046
+ test("汇总状态也跟着变:不再显示「正在启动」", () => {
1047
+ const tsnet = {
1048
+ enabled: true,
1049
+ channels: [
1050
+ { id: "a", label: "A", enabled: true, authKeySaved: true, node: { phase: "starting", stalled: true, stalledReason: "x" }, recentEvents: [] },
1051
+ ],
1052
+ };
1053
+ const view = textOf(
1054
+ SettingsView({ state: { ...state, tsnet }, open: "tsnet", onOpen: noop, onSaveName: async () => true, nameBusy: false, push: noop, reload: async () => {} }),
1055
+ ).join(" ");
1056
+ assert.ok(view.includes("启动受阻"), view.slice(0, 500));
1057
+ assert.ok(!view.includes("正在启动"), "卡住时不该继续说正在启动");
1058
+ });
1059
+
1060
+ test("一键关闭里的互联网行也标出受阻(避免只说「未连接」)", () => {
1061
+ const sw = {
1062
+ ...swOn,
1063
+ internet: { ...swOn.internet, active: false, stalled: 1, note: "有 1 条通道启动受阻:deadline exceeded" },
1064
+ };
1065
+ const txt = textOf(SwitchBody({ sw, push: noop, reload: async () => {} })).join(" ");
1066
+ assert.ok(txt.includes("启动受阻"), txt);
1067
+ });
1068
+
833
1069
  console.log(`\n${failed === 0 ? "全部通过" : "有失败"}:${passed} 通过 / ${failed} 失败\n`);
834
1070
  process.exit(failed ? 1 : 0);