dsh-plugin-mesh 0.0.0-stage → 0.3.30

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.
Files changed (48) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +1199 -2
  3. package/client/client.js +958 -0
  4. package/cordis.patch.yml +80 -0
  5. package/install.sh +142 -0
  6. package/lib/_rehearsal-peer.mjs +229 -0
  7. package/lib/_selftest-capabilities.mjs +631 -0
  8. package/lib/_selftest-client.mjs +249 -0
  9. package/lib/_selftest-discovery.mjs +51 -0
  10. package/lib/_selftest-newsession.mjs +124 -0
  11. package/lib/_selftest-prompt.mjs +97 -0
  12. package/lib/_selftest-tsnet-live.mjs +169 -0
  13. package/lib/_selftest-tsnet-tailnet.mjs +418 -0
  14. package/lib/_selftest-tsnet.mjs +647 -0
  15. package/lib/capabilities.js +786 -0
  16. package/lib/conversation.js +59 -0
  17. package/lib/discovery.js +744 -0
  18. package/lib/identity.js +136 -0
  19. package/lib/index.js +2079 -0
  20. package/lib/prompt.js +50 -0
  21. package/lib/scan.js +118 -0
  22. package/lib/tsnet/bridge.js +71 -0
  23. package/lib/tsnet/checksums.js +19 -0
  24. package/lib/tsnet/download.js +384 -0
  25. package/lib/tsnet/manager.js +655 -0
  26. package/package.json +118 -4
  27. package/scripts/__pycache__/mesh-tsnet-merge.cpython-312.pyc +0 -0
  28. package/scripts/_selftest-tsnet-merge.py +168 -0
  29. package/scripts/build-sidecar.sh +372 -0
  30. package/scripts/check-loadable.mjs +154 -0
  31. package/scripts/check-tarball.mjs +106 -0
  32. package/scripts/check-tdz.mjs +78 -0
  33. package/scripts/check-version.mjs +32 -0
  34. package/scripts/fix-android-tls-align.py +87 -0
  35. package/scripts/mesh-tsnet-merge.py +345 -0
  36. package/scripts/mesh-tsnet-onboarding.md +98 -0
  37. package/scripts/publish-assets.py +213 -0
  38. package/scripts/push-via-api.py +262 -0
  39. package/scripts/release-plugin.sh +129 -0
  40. package/scripts/restart-dsh.sh +308 -0
  41. package/scripts/submit-to-awesome.py +212 -0
  42. package/scripts/verify-lan-mirror.mjs +57 -0
  43. package/sidecar/androidbin_linux.go +39 -0
  44. package/sidecar/androidnet_linux.go +414 -0
  45. package/sidecar/androidnet_other.go +15 -0
  46. package/sidecar/go.mod +51 -0
  47. package/sidecar/go.sum +239 -0
  48. package/sidecar/main.go +850 -0
@@ -0,0 +1,249 @@
1
+ /**
2
+ * 客户端 bundle 的自测(无浏览器)。
3
+ *
4
+ * 这是个**手写 bundle、没有构建步骤**,而这个安装里也没有 react-dom,所以
5
+ * 常规手段(跑一次页面看)在我这里做不到。但组件都是纯函数,`createElement`
6
+ * 的返回值就是一棵可遍历的普通对象树 —— 于是可以:
7
+ *
8
+ * 1. 造一个假的 `window.__ModuleLoader__` 把 factory 抓出来
9
+ * 2. 用最小 react stub(只需要 createElement)执行 factory
10
+ * 3. 直接调用组件函数,遍历返回树,断言文案与标记
11
+ *
12
+ * 覆盖的是最容易出错、也最该被盯住的东西:**三种「不知道」有没有被分开渲染**。
13
+ * 把"对端没报能力"渲染成"什么都没装",会让用户把任务派到跑不了的机器上。
14
+ *
15
+ * node lib/_selftest-client.mjs
16
+ */
17
+ import { strict as assert } from "node:assert";
18
+ import { readFileSync } from "node:fs";
19
+ import { fileURLToPath } from "node:url";
20
+ import { dirname, join } from "node:path";
21
+
22
+ const HERE = dirname(fileURLToPath(import.meta.url));
23
+ const BUNDLE = join(HERE, "..", "client", "client.js");
24
+
25
+ let passed = 0;
26
+ let failed = 0;
27
+ function test(name, fn) {
28
+ try {
29
+ fn();
30
+ passed += 1;
31
+ console.log(` ✓ ${name}`);
32
+ } catch (err) {
33
+ failed += 1;
34
+ console.log(` ✗ ${name}`);
35
+ console.log(` ${err?.message ?? err}`);
36
+ }
37
+ }
38
+
39
+ // ── 最小 react stub:只需要 createElement 的形状与 hook 的存在 ──
40
+ const react = {
41
+ createElement: (type, props, ...children) => ({ type, props: props ?? {}, children: children.flat(Infinity) }),
42
+ useState: (v) => [typeof v === "function" ? v() : v, () => {}],
43
+ useEffect: () => {},
44
+ useMemo: (f) => f(),
45
+ useCallback: (f) => f(),
46
+ useRef: (v) => ({ current: v }),
47
+ Fragment: Symbol("Fragment"),
48
+ };
49
+
50
+ /** 把一个元素树里所有文本收集起来,便于断言"文案里有没有这句话"。 */
51
+ function textOf(node, out = []) {
52
+ if (node === null || node === undefined || node === false || node === true) return out;
53
+ if (typeof node === "string" || typeof node === "number") {
54
+ out.push(String(node));
55
+ return out;
56
+ }
57
+ if (Array.isArray(node)) {
58
+ for (const c of node) textOf(c, out);
59
+ return out;
60
+ }
61
+ if (typeof node === "object") {
62
+ // 函数组件:直接调用(这些组件都是纯函数、不依赖 hook 顺序)
63
+ if (typeof node.type === "function") {
64
+ textOf(node.type(node.props), out);
65
+ return out;
66
+ }
67
+ textOf(node.children, out);
68
+ const kids = node.props && node.props.children;
69
+ if (kids !== undefined) textOf(kids, out);
70
+ return out;
71
+ }
72
+ return out;
73
+ }
74
+
75
+ /** 收集树里所有 title 属性(提示文案也是要验证的内容)。 */
76
+ function titlesOf(node, out = []) {
77
+ if (!node || typeof node !== "object") return out;
78
+ if (Array.isArray(node)) {
79
+ for (const c of node) titlesOf(c, out);
80
+ return out;
81
+ }
82
+ if (typeof node.type === "function") {
83
+ titlesOf(node.type(node.props), out);
84
+ return out;
85
+ }
86
+ if (node.props && typeof node.props.title === "string") out.push(node.props.title);
87
+ titlesOf(node.children, out);
88
+ if (node.props && node.props.children !== undefined) titlesOf(node.props.children, out);
89
+ return out;
90
+ }
91
+
92
+ // ── 用假的 module loader 把 bundle 抓出来 ──
93
+ let captured = null;
94
+ globalThis.window = {
95
+ __ModuleLoader__: {
96
+ load: (entry) => {
97
+ captured = entry;
98
+ },
99
+ },
100
+ };
101
+
102
+ const source = readFileSync(BUNDLE, "utf8");
103
+ // 直接在全局作用域里执行:bundle 末尾的语句就是调用 __ModuleLoader__.load
104
+ // eslint-disable-next-line no-new-func
105
+ new Function("window", `${source}\n`)(globalThis.window);
106
+
107
+ console.log("\n── bundle 能被加载 ──");
108
+
109
+ test("__ModuleLoader__.load 被调用,且 id 等于包名(槽位注册依赖它)", () => {
110
+ assert.ok(captured, "bundle 没有调用 __ModuleLoader__.load");
111
+ assert.equal(captured.id, "dsh-plugin-mesh");
112
+ });
113
+
114
+ const mod = captured.factory((name) => {
115
+ if (name === "react") return react;
116
+ throw new Error(`未预期的依赖:${name}`);
117
+ });
118
+
119
+ test("只依赖 react(不该 require 别的东西)", () => {
120
+ assert.ok(mod && typeof mod.apply === "function", "应导出 apply");
121
+ assert.deepEqual(mod.inject, ["slots"]);
122
+ });
123
+
124
+ test("apply() 注册两个槽位:侧栏图标 + 主面板", () => {
125
+ const regs = [];
126
+ const fakeCtx = {
127
+ slots: {
128
+ inject: (name, cb) => {
129
+ // 槽位已声明时 cb 会立刻执行;这里模拟"已声明",直接调用
130
+ cb();
131
+ regs.push(name);
132
+ },
133
+ register: (spec) => regs.push(spec),
134
+ },
135
+ };
136
+ mod.apply(fakeCtx);
137
+ assert.ok(regs.includes("sidebar.panellist"), `侧栏槽未注册:${JSON.stringify(regs)}`);
138
+ assert.ok(regs.includes("main"), `主面板槽未注册:${JSON.stringify(regs)}`);
139
+ });
140
+
141
+ const { CapabilityLine, PeerRow } = mod.__test;
142
+
143
+ console.log("\n── CapabilityLine:三种「不知道」必须分开渲染 ──");
144
+
145
+ test("对端没报能力 → 说「未知」,绝不能说成「什么都没装」", () => {
146
+ const txt = textOf(CapabilityLine({ peer: { capabilities: null } })).join(" ");
147
+ assert.ok(txt.includes("未知"), txt);
148
+ assert.ok(!txt.includes("未探到运行时"), "把未知说成没有是最危险的错误");
149
+ });
150
+
151
+ test("对端报了运行时 → 每个都渲染成徽章(名字 + 版本)", () => {
152
+ const txt = textOf(
153
+ CapabilityLine({
154
+ peer: {
155
+ capabilities: { runtimes: { python: "3.12", node: "20.19" }, cpuCores: 8, memMb: 16384, arch: "arm64" },
156
+ },
157
+ }),
158
+ ).join(" ");
159
+ assert.ok(txt.includes("python 3.12"), txt);
160
+ assert.ok(txt.includes("node 20.19"), txt);
161
+ assert.ok(txt.includes("8 核"), txt);
162
+ assert.ok(txt.includes("16 GB 内存"), txt);
163
+ });
164
+
165
+ test("对端确实什么运行时都没有 → 说「未探到运行时」(和「未知」不同)", () => {
166
+ const txt = textOf(CapabilityLine({ peer: { capabilities: { runtimes: {} } } })).join(" ");
167
+ assert.ok(txt.includes("未探到运行时"), txt);
168
+ assert.ok(!txt.includes("未知"), "「报过了确实没有」不该说成未知");
169
+ });
170
+
171
+ test("能力已过期 → 标出来", () => {
172
+ const txt = textOf(
173
+ CapabilityLine({ peer: { capabilities: { runtimes: {} }, capabilitiesStale: true } }),
174
+ ).join(" ");
175
+ assert.ok(txt.includes("能力已过期"), txt);
176
+ });
177
+
178
+ test("探测未探准 → 标出来,并在悬停里说明「缺失不能当结论」", () => {
179
+ const el = CapabilityLine({
180
+ peer: { capabilities: { runtimes: {}, runtimesIncomplete: true } },
181
+ });
182
+ const txt = textOf(el).join(" ");
183
+ assert.ok(txt.includes("探测未探准"), txt);
184
+ const tips = titlesOf(el).join("\n");
185
+ assert.ok(tips.includes("不能当结论"), `悬停解释缺失:${tips}`);
186
+ });
187
+
188
+ test("GPU 会显示成独立徽章,并带上显存", () => {
189
+ const el = CapabilityLine({
190
+ peer: { capabilities: { runtimes: {}, gpu: { present: true, name: "Intel Iris", vramMb: 1536 } } },
191
+ });
192
+ assert.ok(textOf(el).join(" ").includes("GPU Intel Iris"), textOf(el).join(" "));
193
+ assert.ok(titlesOf(el).join("\n").includes("1536MB"), "悬停里应带显存");
194
+ });
195
+
196
+ test("悬停里给出完整信息(系统 / 常用目录 / 采集时间)", () => {
197
+ const el = CapabilityLine({
198
+ peer: {
199
+ capabilities: {
200
+ runtimes: {},
201
+ os: "darwin 21.6.0",
202
+ workspaceHints: ["~/projects"],
203
+ capabilitiesAt: 1792000000000,
204
+ },
205
+ },
206
+ });
207
+ const tips = titlesOf(el).join("\n");
208
+ assert.ok(tips.includes("darwin 21.6.0"), tips);
209
+ assert.ok(tips.includes("~/projects"), tips);
210
+ assert.ok(tips.includes("采集于"), tips);
211
+ });
212
+
213
+ test("坏数据不崩(capabilities 是字符串/数字/数组时)", () => {
214
+ for (const junk of ["python", 42, [], undefined]) {
215
+ const el = CapabilityLine({ peer: { capabilities: junk } });
216
+ assert.ok(el, `capabilities=${JSON.stringify(junk)} 时应仍能渲染`);
217
+ }
218
+ // capabilities 是对象但 runtimes 形状不对
219
+ const el = CapabilityLine({ peer: { capabilities: { runtimes: "nope" } } });
220
+ assert.ok(textOf(el).join(" ").includes("未探到运行时"));
221
+ });
222
+
223
+ console.log("\n── PeerRow 把能力行接进去了 ──");
224
+
225
+ test("PeerRow 渲染出的文案里包含对端的能力", () => {
226
+ const el = PeerRow({
227
+ peer: {
228
+ id: "p1",
229
+ machine: "winbox",
230
+ online: true,
231
+ host: "192.168.1.9",
232
+ port: 45917,
233
+ os: "win32 10.0",
234
+ user: "u",
235
+ lastSeen: Date.now(),
236
+ endpoints: [],
237
+ capabilities: { runtimes: { go: "1.25" } },
238
+ capabilitiesStale: false,
239
+ },
240
+ onSend: () => {},
241
+ onProbe: () => {},
242
+ });
243
+ const txt = textOf(el).join(" ");
244
+ assert.ok(txt.includes("winbox"), txt);
245
+ assert.ok(txt.includes("go 1.25"), `机器卡片里应显示能力:${txt}`);
246
+ });
247
+
248
+ console.log(`\n${failed === 0 ? "全部通过" : "有失败"}:${passed} 通过 / ${failed} 失败\n`);
249
+ process.exit(failed === 0 ? 0 : 1);
@@ -0,0 +1,51 @@
1
+ /**
2
+ * 局域网发现的双进程手动测试:起两个实例,互相发现。
3
+ *
4
+ * node lib/_selftest-discovery.mjs mac-a 45900 &
5
+ * node lib/_selftest-discovery.mjs mac-b 45901
6
+ *
7
+ * ⚠ 用**私有组播组和端口**,不要改回生产的 239.255.42.99:45892 ——
8
+ * 这个脚本会向组播组宣告自己,跑在生产组上会被同一网段的真实 DSH 登记成
9
+ * 一台假机器。实测踩过:`npm run selftest` 每跑一次,就在真实网络里多出
10
+ * 一条名为 test 的重名记录(身份带 pid,所以每次还都不一样)。
11
+ *
12
+ * 日常回归测试请用 `npm run selftest`(纯逻辑、不碰网络)。
13
+ */
14
+ import { MeshDiscovery, preferredAddress } from "./discovery.js";
15
+
16
+ /** 测试专用组播组/端口:与生产值刻意不同,避免污染真实网络。 */
17
+ export const TEST_GROUP = "239.255.42.98";
18
+ export const TEST_MULTICAST_PORT = 45893;
19
+
20
+ const machine = process.argv[2] ?? "selftest-probe";
21
+ const port = Number(process.argv[3] ?? 45900);
22
+ const id = `selftest-${machine}-${process.pid}`;
23
+
24
+ const d = new MeshDiscovery({
25
+ id,
26
+ port,
27
+ meta: { machine, user: "tester", profile: "selftest", version: "0.1.0" },
28
+ intervalMs: 2000,
29
+ ttlMs: 6000,
30
+ group: TEST_GROUP,
31
+ multicastPort: TEST_MULTICAST_PORT,
32
+ });
33
+
34
+ d.on("change", (peers) => {
35
+ console.log(`[${machine}] 对端变化 (${peers.length}):`);
36
+ for (const p of peers) {
37
+ console.log(` ${p.online ? "●" : "○"} ${p.machine} ${p.host}:${p.port} id=${p.id} lastSeen=${new Date(p.lastSeen).toISOString()}`);
38
+ }
39
+ });
40
+ d.on("diagnostic", (m) => console.log(`[${machine}] 诊断: ${m}`));
41
+
42
+ console.log(`[${machine}] 本机地址 ${preferredAddress()} 实例 id=${id}`);
43
+ d.start();
44
+ d.announceNow();
45
+
46
+ setTimeout(() => {
47
+ const peers = d.peers();
48
+ console.log(`[${machine}] === 最终结果: 发现 ${peers.length} 个对端 ===`);
49
+ d.stop();
50
+ process.exit(peers.length > 0 ? 0 : 3);
51
+ }, Number(process.argv[4] ?? 9000));
@@ -0,0 +1,124 @@
1
+ /**
2
+ * newSession 端到端验证脚本。
3
+ *
4
+ * 思路:本机(生产 DSH,profile=desktop)与被测的隔离实例(dev,profile=meshtest)
5
+ * 通过多播互相发现。dev 的 web server 没有被 Desktop 的 permits 闸门保护,所以
6
+ * 可以用 curl/node 直接驱动;生产实例作为接收方,把路由结果写进
7
+ * ~/.dsh/mesh/threads.json —— 读这个文件就能看到"复用还是新建"。
8
+ *
9
+ * 断言:同一 thread 的第 2 条带 newSession:true 时,必须绑定到**不同的** sessionId。
10
+ *
11
+ * 跑之前要先起一个隔离实例(它的 web 端口固定用 8877):
12
+ *
13
+ * MACHINE=meshdev PORT=45918 ./dev-setup.sh meshtest /tmp/dsh-mesh-dev
14
+ * DSH_HOME=/tmp/dsh-mesh-dev ELECTRON_RUN_AS_NODE=1 \
15
+ * "/Applications/DSH Desktop.app/Contents/MacOS/DSH Desktop" \
16
+ * dev-boot.mjs --profile meshtest --port 8877 --no-open &
17
+ *
18
+ * 然后:
19
+ *
20
+ * node lib/_selftest-newsession.mjs <对端机器名> [间隔ms]
21
+ * CONTROL=1 node lib/_selftest-newsession.mjs <对端机器名> [间隔ms] # 对照组
22
+ *
23
+ * 间隔必须大于 threadCooldownMs(默认 5000),否则第二条会被冷却拦下 ——
24
+ * 这正是第一次验证时卡住的原因。
25
+ *
26
+ * ⚠ 这个脚本会**真的让对端建两个 agent 会话**(会花 token),所以它不在
27
+ * `npm run selftest` 里,只手动跑。
28
+ */
29
+ import { readFileSync } from "node:fs";
30
+ import { homedir } from "node:os";
31
+ import { join } from "node:path";
32
+
33
+ const DEV = "http://127.0.0.1:8877";
34
+ const PEER = process.argv[2] ?? "lipeng-mac";
35
+ const GAP_MS = Number(process.argv[3] ?? 8000);
36
+ const THREAD = `nsverify-${Date.now()}`;
37
+
38
+ const threadsPath = join(homedir(), ".dsh", "mesh", "threads.json");
39
+
40
+ function snapshot() {
41
+ try {
42
+ const t = JSON.parse(readFileSync(threadsPath, "utf8"));
43
+ const out = {};
44
+ for (const [k, v] of Object.entries(t.threads ?? {})) out[k] = v.sessionId;
45
+ return out;
46
+ } catch {
47
+ return {};
48
+ }
49
+ }
50
+
51
+ async function send(task, newSession) {
52
+ const res = await fetch(`${DEV}/mesh/api/send`, {
53
+ method: "POST",
54
+ headers: { "content-type": "application/json" },
55
+ body: JSON.stringify({ peer: PEER, thread: THREAD, newSession, task }),
56
+ });
57
+ return { status: res.status, body: await res.json().catch(() => ({})) };
58
+ }
59
+
60
+ /** 找到本 thread 对应的会话键 —— 键里带发送方机器名,所以按后缀匹配。 */
61
+ function findKey(snap) {
62
+ const hits = Object.keys(snap).filter((k) => k.startsWith("meshdev#"));
63
+ return hits.length === 1 ? hits[0] : hits[hits.length - 1];
64
+ }
65
+
66
+ const before = snapshot();
67
+ console.log(`thread=${THREAD} peer=${PEER} gap=${GAP_MS}ms`);
68
+
69
+ console.log("\n[1] newSession=false →");
70
+ const r1 = await send("【自动测试】newSession 功能验证的第 1 条消息。请只回复 ok 两个字,不要调用任何工具,也不要做别的事情。", false);
71
+ console.log(" ", r1.status, JSON.stringify(r1.body));
72
+
73
+ console.log(`\n 等 ${GAP_MS}ms(必须大于 threadCooldownMs=5000,否则会被冷却拦下)…`);
74
+ await new Promise((r) => setTimeout(r, GAP_MS));
75
+
76
+ const mid = snapshot();
77
+ const key = findKey(mid);
78
+ const s1 = key ? mid[key] : undefined;
79
+ console.log(` 第 1 条绑定:${key} -> ${s1}`);
80
+
81
+ if (!s1) {
82
+ console.log("\n[FAIL] 第 1 条没有绑定任何会话 —— 检查对端是否真的开跑了。");
83
+ console.log(" 生产实例 inbound 记录:");
84
+ const r = await fetch(`${DEV}/mesh/api/state`);
85
+ const st = await r.json();
86
+ console.log(JSON.stringify(st.outbound?.slice(-3), null, 2));
87
+ process.exit(1);
88
+ }
89
+
90
+ // CONTROL=1:第 2 条也不带 newSession。此时应当**复用**第 1 条建的会话 ——
91
+ // 这是对照实验:同样的间隔、同样的 thread,唯一变量就是 newSession。
92
+ // 没有这个对照,"两个 session 不同"可能来自别的原因(比如注入失败回退新建)。
93
+ const CONTROL = process.env.CONTROL === "1";
94
+ console.log(`\n[2] newSession=${CONTROL ? "false(对照组,应复用)" : "true(应新建)"} →`);
95
+ const r2 = await send("【自动测试】newSession 功能验证的第 2 条消息。请只回复 ok 两个字,不要调用任何工具,也不要做别的事情。", !CONTROL);
96
+ console.log(" ", r2.status, JSON.stringify(r2.body));
97
+
98
+ await new Promise((r) => setTimeout(r, 8000));
99
+ const after = snapshot();
100
+ const s2 = after[key];
101
+ console.log(` 第 2 条绑定:${key} -> ${s2}`);
102
+
103
+ console.log("");
104
+ if (CONTROL) {
105
+ if (s2 && s1 && s2 === s1) {
106
+ console.log(`[PASS] 对照组符合预期:不带 newSession 时复用了同一会话 ${s1}`);
107
+ console.log(` → 说明上一轮的"两个不同会话"确实是 newSession 造成的`);
108
+ process.exit(0);
109
+ }
110
+ console.log(`[FAIL] 对照组异常:期望复用 ${s1},实际 ${s2}`);
111
+ process.exit(1);
112
+ }
113
+ if (s2 && s1 && s2 !== s1) {
114
+ console.log(`[PASS] newSession 生效:同一会话键绑到了两个不同会话`);
115
+ console.log(` ${s1}`);
116
+ console.log(` ${s2}`);
117
+ process.exit(0);
118
+ }
119
+ if (s2 === s1) {
120
+ console.log(`[FAIL] newSession 没生效:第 2 条仍复用 ${s1}`);
121
+ process.exit(1);
122
+ }
123
+ console.log(`[FAIL] 第 2 条没有绑定会话(s2=${s2})`);
124
+ process.exit(1);
@@ -0,0 +1,97 @@
1
+ /**
2
+ * 任务提示词的自测。
3
+ *
4
+ * node lib/_selftest-prompt.mjs
5
+ *
6
+ * 这组测试的存在理由是**一个真发出去的 bug**:提示词里让对端把结果"回派给
7
+ * `lipeng-mac/peng`",而 `mesh_run` 的 peer 参数要的是机器名 —— 对端 agent
8
+ * 拿着它去派发会被 findPeer 拒绝,白费一轮。hos 实测撞上并按自己的判断改成
9
+ * 机器名才成功。**agent 能自救,不代表指令是对的。**
10
+ */
11
+ import { strict as assert } from "node:assert";
12
+ import { buildPrompt } from "./prompt.js";
13
+
14
+ let passed = 0;
15
+ let failed = 0;
16
+ function test(name, fn) {
17
+ try {
18
+ fn();
19
+ passed += 1;
20
+ console.log(` ✓ ${name}`);
21
+ } catch (err) {
22
+ failed += 1;
23
+ console.log(` ✗ ${name}`);
24
+ console.log(` ${err?.message ?? err}`);
25
+ }
26
+ }
27
+
28
+ /** 取出"回派给 X"里的 X。 */
29
+ function replyPeerOf(text) {
30
+ const m = text.match(/把结果回派给 ([^\s((]+)/);
31
+ return m ? m[1] : "";
32
+ }
33
+
34
+ console.log("\n── 回派目标必须是机器名,不能是「机器名/用户」──");
35
+
36
+ test("fromMachine 存在时用它(这是最可靠的来源)", () => {
37
+ const t = buildPrompt({ id: "t1", from: "lipeng-mac/peng", fromMachine: "lipeng-mac", task: "x", thread: "th" });
38
+ assert.equal(replyPeerOf(t), "lipeng-mac", t);
39
+ });
40
+
41
+ test("from 里的 /用户 后缀绝不能进回派目标(就是踩过的那个 bug)", () => {
42
+ const t = buildPrompt({ id: "t1", from: "hos/u0_a267", fromMachine: "hos", task: "x", thread: "th" });
43
+ assert.equal(replyPeerOf(t), "hos");
44
+ assert.ok(!replyPeerOf(t).includes("/"), "回派目标里不该有斜杠");
45
+ });
46
+
47
+ test("老版本对端没有 fromMachine 时,切掉 /user 兜底", () => {
48
+ const t = buildPrompt({ id: "t1", from: "文超-win/86189", task: "x", thread: "th" });
49
+ assert.equal(replyPeerOf(t), "文超-win", t);
50
+ });
51
+
52
+ test("fromMachine 是空串时也走兜底(不能因为空串就退化成空目标)", () => {
53
+ const t = buildPrompt({ id: "t1", from: "winbox/86189", fromMachine: " ", task: "x" });
54
+ assert.equal(replyPeerOf(t), "winbox", t);
55
+ });
56
+
57
+ test("指令里额外用一句话点明「填机器名」", () => {
58
+ const t = buildPrompt({ id: "t1", from: "hos/u0_a267", fromMachine: "hos", task: "x" });
59
+ assert.ok(t.includes("不要填 \"机器名/用户\""), t);
60
+ });
61
+
62
+ console.log("\n── 归一化:webhook 与 mesh 两种形状都要认 ──");
63
+
64
+ test("mesh 形状(id/from)", () => {
65
+ const t = buildPrompt({ id: "t-abc", from: "hos/u0_a267", fromMachine: "hos", task: "干活", thread: "th-1" });
66
+ assert.ok(t.includes("[DSH Mesh 任务 t-abc]"), t);
67
+ assert.ok(t.includes("线程: th-1"), t);
68
+ assert.ok(t.includes("干活"), t);
69
+ });
70
+
71
+ test("webhook 形状(deliveryId/source)也能归一化", () => {
72
+ const t = buildPrompt({ deliveryId: "d-1", source: "somewhere", task: "干活" });
73
+ assert.ok(t.includes("[DSH Mesh 任务 d-1]"), t);
74
+ assert.ok(t.includes("来自: somewhere"), t);
75
+ assert.ok(!t.includes("undefined"), `不该出现 undefined:${t}`);
76
+ });
77
+
78
+ test("没有 thread 时用 id 兜底", () => {
79
+ const t = buildPrompt({ id: "t-9", from: "a/u", fromMachine: "a", task: "x" });
80
+ assert.ok(t.includes("thread 填 t-9"), t);
81
+ });
82
+
83
+ test("全空入参不崩,也不产出 undefined", () => {
84
+ const t = buildPrompt({});
85
+ assert.ok(t.includes("[DSH Mesh 任务 unknown]"), t);
86
+ assert.ok(!t.includes("undefined"), t);
87
+ assert.equal(replyPeerOf(t), "unknown");
88
+ });
89
+
90
+ test("task 正文原样保留(不被指令淹没)", () => {
91
+ const body = "第一行\n第二行\n 缩进行";
92
+ const t = buildPrompt({ id: "t1", from: "a/u", fromMachine: "a", task: body });
93
+ assert.ok(t.includes(body), "正文必须逐字保留");
94
+ });
95
+
96
+ console.log(`\n${failed === 0 ? "全部通过" : "有失败"}:${passed} 通过 / ${failed} 失败\n`);
97
+ process.exit(failed === 0 ? 0 : 1);
@@ -0,0 +1,169 @@
1
+ /**
2
+ * P1 实机验证:真实下载 sidecar、真实拉起进程、验证整机单实例复用与清理。
3
+ *
4
+ * 跑法:node lib/_selftest-tsnet-live.mjs
5
+ *
6
+ * 不需要 Tailscale 授权码 —— 没有授权码时 sidecar 会停在 NeedsLogin 并给出
7
+ * 授权链接,这已经足够验证 P1 的全部机制:
8
+ * · 按平台从镜像下载 .gz,按内置 sha256 校验通过,解压后可执行
9
+ * · 进程起来、控制 API 可用、能读到 backendState / authUrl
10
+ * · rendezvous 生效:第二个实例**复用**而不是再起一个节点
11
+ * · 非 owner 退出不牵连共享 sidecar;owner 退出时 sidecar 随之消失(不留孤儿)
12
+ *
13
+ * 注意:会真的联网下载(约 8.5MB)并写入 ~/.dsh/mesh/。这是有意的 ——
14
+ * P1 要验的就是这条路,用假的就失去意义了。
15
+ */
16
+ import assert from "node:assert/strict";
17
+ import { existsSync, statSync } from "node:fs";
18
+ import { homedir } from "node:os";
19
+ import { join } from "node:path";
20
+ import { ensureBinary, binaryInfo, binaryPath, looksExecutable, clearBinary } from "./tsnet/download.js";
21
+ import { TsnetNode } from "./tsnet/manager.js";
22
+
23
+ let passed = 0;
24
+ let failed = 0;
25
+ const step = (label) => console.log(`\n── ${label} ──`);
26
+ function check(label, fn) {
27
+ try {
28
+ fn();
29
+ console.log(` ✓ ${label}`);
30
+ passed += 1;
31
+ } catch (err) {
32
+ console.log(` ✗ ${label}\n ${err.message}`);
33
+ failed += 1;
34
+ }
35
+ }
36
+ const log = (m) => console.log(` · ${m}`);
37
+ const warn = (m) => console.log(` ! ${m}`);
38
+
39
+ function pidAlive(pid) {
40
+ // pid 0 会被 process.kill 当成"整个进程组",永远返回成功 —— 必须挡掉,
41
+ // 否则"没拿到 pid"会伪装成"进程还活着"。
42
+ if (!Number.isInteger(pid) || pid <= 0) return false;
43
+ try {
44
+ process.kill(pid, 0);
45
+ return true;
46
+ } catch (err) {
47
+ return err.code === "EPERM";
48
+ }
49
+ }
50
+
51
+ const config = {
52
+ tsnetHostname: "selftest-node",
53
+ tsnetAuthKey: "",
54
+ tsnetControlUrl: "",
55
+ tsnetDownloadSources: [],
56
+ };
57
+
58
+ let node1 = null;
59
+ let node2 = null;
60
+ let sidecarPid = 0;
61
+
62
+ try {
63
+ step("1. 下载与完整性校验");
64
+ const info = binaryInfo();
65
+ log(`缓存路径:${info.path}(当前 ${info.installed ? `${(info.size / 1048576).toFixed(1)}MB` : "不存在"})`);
66
+
67
+ const res = await ensureBinary({ log, force: true });
68
+ check("下载成功", () => {
69
+ assert.ok(existsSync(res.path), `文件不存在:${res.path}`);
70
+ assert.ok(res.downloaded, "应该是新下载的");
71
+ });
72
+ check("sha256 校验通过(内置白名单)", () => {
73
+ // ensureBinary 内部做校验,能走到这里就说明匹配;这里再确认来源不是兜底直连
74
+ assert.ok(!res.source.includes("github.com") || res.source === "github.com", `来源异常:${res.source}`);
75
+ log(`下载来源:${res.source}`);
76
+ });
77
+ check("解压后是可执行文件且体积合理", () => {
78
+ assert.ok(looksExecutable(), `文件头不像可执行文件:${binaryPath()}`);
79
+ const size = statSync(binaryPath()).size;
80
+ assert.ok(size > 10 * 1048576, `体积异常:${size} 字节`);
81
+ log(`二进制体积:${(size / 1048576).toFixed(1)}MB`);
82
+ });
83
+
84
+ step("2. 拉起 sidecar(无授权码 → 应停在待登录)");
85
+ node1 = new TsnetNode({ config, log, warn });
86
+ await node1.start();
87
+ const st1 = node1.status();
88
+ sidecarPid = st1.pid;
89
+ log(`phase=${st1.phase} port=${st1.port} pid=${sidecarPid}`);
90
+
91
+ check("sidecar 进程在运行", () => {
92
+ assert.ok(sidecarPid > 0, "没有拿到 pid");
93
+ assert.ok(pidAlive(sidecarPid), `pid ${sidecarPid} 不存活`);
94
+ });
95
+ check("注册了 tailnet 入站转发", () => {
96
+ assert.ok(Array.isArray(st1.forwards), "forwards 不是数组");
97
+ });
98
+
99
+ // sidecar 要先连控制面、再发起交互登录,授权链接不会在 start() 返回时就有。
100
+ let authUrl = st1.authUrl;
101
+ for (let i = 0; i < 60 && !authUrl; i += 1) {
102
+ await new Promise((r) => setTimeout(r, 500));
103
+ authUrl = node1.status().authUrl;
104
+ }
105
+ check("状态为待登录,且给出了授权链接", () => {
106
+ // 没有授权码时这是唯一正确的状态
107
+ assert.equal(node1.status().backendState, "NeedsLogin", `backendState=${node1.status().backendState}`);
108
+ assert.ok(authUrl?.startsWith("https://"), `authUrl 异常:${authUrl}`);
109
+ log(`授权链接:${authUrl}`);
110
+ });
111
+
112
+ step("3. 整机单实例:第二个实例必须复用,不能再起一个节点");
113
+ node2 = new TsnetNode({ config, log, warn });
114
+ const started = await node2.start();
115
+ check("复用而非新建", () => {
116
+ assert.equal(started.reused, true, "第二个实例没有复用已有 sidecar");
117
+ });
118
+ check("两个实例指向同一个 sidecar", () => {
119
+ assert.equal(node2.status().port, st1.port, "控制端口不一致,说明起了两个节点");
120
+ assert.equal(node2.status().pid, sidecarPid, "pid 不一致,说明起了两个节点");
121
+ });
122
+ check("第二个实例不是 owner", () => {
123
+ assert.equal(node2.ownsProcess, false, "第二个实例不该拥有进程");
124
+ });
125
+
126
+ step("4. 非 owner 退出不应牵连共享的 sidecar");
127
+ await node2.stop({ keepRemote: true });
128
+ node2 = null;
129
+ check("共享 sidecar 仍然存活", () => {
130
+ assert.ok(pidAlive(sidecarPid), `复用的 sidecar 被误杀了(pid ${sidecarPid})`);
131
+ });
132
+ const stAfter = await node1.statusRemote();
133
+ check("控制 API 仍然可用", () => {
134
+ assert.equal(stAfter.ok, true);
135
+ assert.equal(stAfter.backendState, "NeedsLogin");
136
+ });
137
+
138
+ step("5. owner 退出后 sidecar 必须消失(不留孤儿进程)");
139
+ await node1.stop();
140
+ node1 = null;
141
+ // 给它一点时间退出
142
+ await new Promise((r) => setTimeout(r, 1200));
143
+ check("sidecar 已退出", () => {
144
+ assert.equal(pidAlive(sidecarPid), false, `sidecar(pid ${sidecarPid})还在跑,会变成孤儿`);
145
+ });
146
+ check("rendezvous 已清理", () => {
147
+ // rendezvous.json 应被删除,下次启动才会重新选举 owner
148
+ const base = process.env.DSH_HOME || join(homedir(), ".dsh");
149
+ const p = join(base, "mesh", "tsnet", "rendezvous.json");
150
+ assert.equal(existsSync(p), false, `残留:${p}`);
151
+ });
152
+
153
+ step("6. 缓存可被清理(界面上的「重新下载」)");
154
+ clearBinary();
155
+ check("二进制已删除", () => {
156
+ assert.equal(existsSync(binaryPath()), false, "缓存没删掉");
157
+ });
158
+ } catch (err) {
159
+ console.log(`\n✗ 验证中断:${err?.stack ?? err}`);
160
+ failed += 1;
161
+ } finally {
162
+ // 无论成败都收干净,别给用户留野进程
163
+ for (const n of [node2, node1]) {
164
+ if (n) await n.stop().catch(() => {});
165
+ }
166
+ }
167
+
168
+ console.log(`\n结果:${passed} 通过,${failed} 失败\n`);
169
+ process.exit(failed === 0 ? 0 : 1);