dsh-plugin-mesh 0.5.0 → 0.5.2

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/cordis.patch.yml CHANGED
@@ -76,5 +76,6 @@
76
76
  threadWindowMs: 3600000
77
77
  # 两次自动唤醒之间的最小间隔(毫秒),管突发;0 = 不限制
78
78
  threadCooldownMs: 5000
79
- # 单条任务正文短于此长度就只入箱不唤醒(挡 ping/ack 这类寒暄)
80
- minTaskChars: 24
79
+ # 单条任务正文短于此长度就只入箱不唤醒(挡 ping/ack 这类寒暄)。
80
+ # 8 = 只当地板值;中文 24 字太苛刻,真实短任务会被吞(真机反馈)。
81
+ minTaskChars: 8
@@ -104,7 +104,8 @@ const meshServer = createServer((req, res) => {
104
104
  const body = Buffer.from(
105
105
  JSON.stringify({
106
106
  ok: true,
107
- v: 1,
107
+ // 必须与 PROTOCOL_VERSION 一致:准入(looksLikeDshPeer)会拒收 v 存在但非 2 的记录
108
+ v: 2,
108
109
  app: "dsh-mesh",
109
110
  id: `rehearsal-${MACHINE}`,
110
111
  machine: MACHINE,
@@ -7,7 +7,8 @@
7
7
  * node lib/_selftest-capabilities.mjs
8
8
  */
9
9
  import { strict as assert } from "node:assert";
10
- import { homedir } from "node:os";
10
+ import { homedir, tmpdir } from "node:os";
11
+ import { mkdirSync, mkdtempSync, rmSync } from "node:fs";
11
12
  import { join } from "node:path";
12
13
  import {
13
14
  augmentedPath,
@@ -35,6 +36,7 @@ import {
35
36
  __storeAliasDir,
36
37
  __hasUncertainProbe,
37
38
  __probeFailCount,
39
+ __isUncertain,
38
40
  } from "./capabilities.js";
39
41
  import { MeshDiscovery, APP_TAG } from "./discovery.js";
40
42
 
@@ -413,6 +415,28 @@ test("Store 别名目录(WindowsApps)不算「补全真的生效」的证据
413
415
  assert.ok(!__storeAliasDir.test(String.raw`C:\tools\WindowsApps\extra`), "只排除该目录本身,不误伤子目录");
414
416
  });
415
417
 
418
+ test("探测 PATH 不再前置 WindowsApps(0 字节 Store 存根不能遮住真实运行时)", () => {
419
+ // 构造一个只存在 WindowsApps 的 LOCALAPPDATA。修复前 extraPathDirs() 会把它
420
+ // 加进候选;修复后必须为空 —— 否则它会排在真实 python/node 前面。
421
+ const tmp = mkdtempSync(join(tmpdir(), "mesh-path-"));
422
+ try {
423
+ mkdirSync(join(tmp, "Microsoft", "WindowsApps"), { recursive: true });
424
+ const dirs = __extraPathDirs("win32", { LOCALAPPDATA: tmp });
425
+ assert.ok(
426
+ !dirs.some((d) => __storeAliasDir.test(d)),
427
+ `不该把 WindowsApps 补进探测 PATH:${dirs.join(", ")}`,
428
+ );
429
+ } finally {
430
+ rmSync(tmp, { recursive: true, force: true });
431
+ }
432
+ });
433
+
434
+ test("exit-9009(Store 存根)算「不确定」,不能当「没装」", () => {
435
+ assert.equal(__isUncertain("exit-9009"), true);
436
+ assert.equal(__isUncertain("ENOENT"), false);
437
+ assert.equal(__isUncertain("timeout"), true);
438
+ });
439
+
416
440
  test("对端 Android:6 项 ENOENT 确实都没装(它自查 command -v 确认)", () => {
417
441
  // 对端跑过 command -v:go/docker/rustc/java/ffmpeg/adb **全部 absent**,
418
442
  // 所以它那台**没有缺陷**。这条用例记的是"它曾经被误判成活反例"这件事:
@@ -488,7 +512,9 @@ test("能力刷新后名片立刻跟着变(无需重启、无需重新 start
488
512
 
489
513
  test("旧版本对端(名片里没有 capabilities)不报错,且被标成「未知」而不是「什么都没装」", () => {
490
514
  const d = makeDiscovery();
491
- d.note({ v: 1, app: APP_TAG, id: "old-peer", machine: "old", host: "10.0.0.9", port: 45917, ts: Date.now() }, "10.0.0.9");
515
+ // 注意:不要再用 v: 1 —— 新的准入(looksLikeDshPeer)要求 v 存在时必须是 2,
516
+ // 否则直接拒收。模拟"旧对端"应该用**没有 v/proto** 的记录(快照里就是这样)。
517
+ d.note({ app: APP_TAG, id: "old-peer", machine: "old", host: "10.0.0.9", port: 45917, ts: Date.now() }, "10.0.0.9");
492
518
  const p = d.get("old-peer");
493
519
  assert.ok(p, "对端应被登记");
494
520
  assert.equal(p.capabilities, null, "旧对端的能力应是 null(未知)");
@@ -1,392 +1,9 @@
1
1
  /**
2
- * 客户端 bundle 的自测(无浏览器)。
2
+ * 兼容入口:工作台改版后,旧的“卡片组件”自测不再适用。
3
+ * 新的渲染自测在 _selftest-workbench.mjs,保留这个文件名是为了让
4
+ * package.json 里的 selftest:client 继续工作。
3
5
  *
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
6
+ * 旧版断言(CapabilityLine / PeerRow / TsnetCard / SecretBox)已归档到
7
+ * _selftest-client.cards.mjs,仅作历史参考,不参与 npm test。
16
8
  */
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, TsnetCard, SecretBox } = 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── 端点标签的显示顺序 ──");
249
-
250
- function peerWith(endpoints, extra = {}) {
251
- return {
252
- id: "p2", machine: "hos", online: true, host: "192.168.1.9", port: 45917,
253
- lastSeen: Date.now(), endpoints, capabilities: null, capabilitiesStale: false, ...extra,
254
- };
255
- }
256
- const EP_LAN = { transport: "lan", host: "192.168.1.9", port: 45917, lastSeen: Date.now() - 60_000, verified: true, okCount: 3, failCount: 0 };
257
- const EP_TS = { transport: "tsnet", host: "100.81.214.118", port: 45917, lastSeen: Date.now(), verified: true, okCount: 3, failCount: 0 };
258
-
259
- test("局域网在用 → 局域网排第一", () => {
260
- const txt = textOf(PeerRow({ peer: peerWith([EP_TS, EP_LAN], { transport: "lan" }), onSend: () => {}, onProbe: () => {} })).join(" ");
261
- assert.ok(txt.indexOf("局域网") < txt.indexOf("互联网"), `顺序不对:${txt.slice(0, 120)}`);
262
- assert.ok(txt.includes("局域网 在用"));
263
- });
264
-
265
- test("互联网在用 → 互联网排第一", () => {
266
- const txt = textOf(PeerRow({ peer: peerWith([EP_LAN, EP_TS], { transport: "tsnet" }), onSend: () => {}, onProbe: () => {} })).join(" ");
267
- assert.ok(txt.indexOf("互联网") < txt.indexOf("局域网"), `顺序不对:${txt.slice(0, 120)}`);
268
- assert.ok(txt.includes("互联网 在用"));
269
- });
270
-
271
- test("都非在用 → 按上次可见时间倒序(近的在前)", () => {
272
- const lan = { ...EP_LAN, lastSeen: Date.now() - 3600_000 };
273
- const ts = { ...EP_TS, lastSeen: Date.now() - 60_000 };
274
- const txt = textOf(PeerRow({ peer: peerWith([lan, ts], { transport: null }), onSend: () => {}, onProbe: () => {} })).join(" ");
275
- assert.ok(txt.indexOf("互联网") < txt.indexOf("局域网"), `较近的应在前面:${txt.slice(0, 120)}`);
276
- });
277
-
278
- test("两条时间完全相同时,局域网排前面(不靠数组顺序)", () => {
279
- const t = Date.now() - 60_000;
280
- const lan = { ...EP_LAN, lastSeen: t };
281
- const ts = { ...EP_TS, lastSeen: t };
282
- // 故意把互联网放在数组前面,验证排序不依赖原始顺序
283
- const txt = textOf(PeerRow({ peer: peerWith([ts, lan], { transport: null }), onSend: () => {}, onProbe: () => {} })).join(" ");
284
- assert.ok(txt.indexOf("局域网") < txt.indexOf("互联网"), `平手时应局域网优先:${txt.slice(0, 120)}`);
285
- });
286
-
287
- test("恢复的机器:全部标「上次见到」,且按上次可见时间倒序", () => {
288
- const lan = { ...EP_LAN, lastSeen: Date.now() - 7200_000, verified: true };
289
- const ts = { ...EP_TS, lastSeen: Date.now() - 600_000, verified: true };
290
- const txt = textOf(PeerRow({
291
- peer: peerWith([lan, ts], { transport: null, restored: true, online: false }),
292
- onSend: () => {}, onProbe: () => {},
293
- })).join(" ");
294
- assert.ok(txt.includes("互联网 上次见到"), `应标上次见到:${txt.slice(0, 140)}`);
295
- assert.ok(txt.includes("局域网 上次见到"), `应标上次见到:${txt.slice(0, 140)}`);
296
- assert.ok(!txt.includes("在用"), `离线机器不能出现「在用」:${txt.slice(0, 140)}`);
297
- assert.ok(txt.indexOf("互联网") < txt.indexOf("局域网"), `较近的应在前面:${txt.slice(0, 140)}`);
298
- });
299
-
300
- console.log("\n── TsnetCard:用户不该自己去后台找授权码地址 ──");
301
-
302
- const noop = () => {};
303
- const tsnetOff = { enabled: false, authKeySaved: false, controlUrl: "", node: null, hostname: "", permissionPresetEffective: "" };
304
-
305
- test("未配置时,卡片当场说明「需要授权码」而不是只留一个输入框", () => {
306
- const txt = textOf(TsnetCard({ tsnet: tsnetOff, onChanged: noop })).join(" ");
307
- assert.ok(txt.includes("授权码"), txt.slice(0, 200));
308
- assert.ok(txt.includes("免费"), "应说明可以免费注册");
309
- });
310
-
311
- test("给出可直接点开的授权码页面地址", () => {
312
- const el = TsnetCard({ tsnet: tsnetOff, onChanged: noop });
313
- const txt = textOf(el).join(" ");
314
- assert.ok(txt.includes("https://console.tailscale.com/admin/settings/keys"), "地址必须出现在可见文本里(Electron 里点不动也能复制)");
315
- });
316
-
317
- test("地址是可点链接且新窗口打开", () => {
318
- const el = TsnetCard({ tsnet: tsnetOff, onChanged: noop });
319
- const links = [];
320
- (function walk(n) {
321
- if (!n || typeof n !== "object") return;
322
- if (Array.isArray(n)) return n.forEach(walk);
323
- if (typeof n.type === "function") return walk(n.type(n.props));
324
- if (n.props && n.props.href) links.push(n.props);
325
- walk(n.children);
326
- if (n.props && n.props.children !== undefined) walk(n.props.children);
327
- })(el);
328
- const hit = links.find((a) => a.href === "https://console.tailscale.com/admin/settings/keys");
329
- assert.ok(hit, "应有指向授权码页面的 <a>");
330
- assert.equal(hit.target, "_blank");
331
- });
332
-
333
- test("点明「必须勾选 Reusable」这个真实坑(一次性码重启就失效)", () => {
334
- const txt = textOf(TsnetCard({ tsnet: tsnetOff, onChanged: noop })).join(" ");
335
- assert.ok(txt.includes("Reusable"), txt.slice(0, 300));
336
- assert.ok(txt.includes("一次性"), "应解释为什么必须 Reusable");
337
- });
338
-
339
- test("已经存过授权码时不再重复推销取码步骤,只提示已保存", () => {
340
- // 注意要用 enabled:false —— 那才是"面板会展开"的状态(open 初值 = !enabled)。
341
- // 用 enabled:true 测这条是假绿:面板默认收起,什么都断言得到。
342
- const txt = textOf(
343
- TsnetCard({ tsnet: { ...tsnetOff, enabled: false, authKeySaved: true }, onChanged: noop }),
344
- ).join(" ");
345
- assert.ok(txt.includes("已保存"), txt.slice(0, 300));
346
- assert.ok(!txt.includes("console.tailscale.com"), "已配置后不该再占版面显示取码地址");
347
- });
348
-
349
- test("enabled 状态下设置面板默认收起(不占版面)", () => {
350
- const txt = textOf(
351
- TsnetCard({ tsnet: { ...tsnetOff, enabled: true, authKeySaved: true }, onChanged: noop }),
352
- ).join(" ");
353
- assert.ok(txt.includes("设置"), "应有「设置」按钮可以展开");
354
- assert.ok(!txt.includes("console.tailscale.com"), "收起时不该显示取码步骤");
355
- });
356
-
357
- console.log("\n── SecretBox:配对码要有开关,不能只显示状态 ──");
358
-
359
- test("未启用时给出「启用配对码」按钮(而不是叫人去改 YAML)", () => {
360
- const txt = textOf(SecretBox({ self: { secret: "x".repeat(32) }, config: { requirePairing: false }, onSaved: noop })).join(" ");
361
- assert.ok(txt.includes("启用配对码"), txt.slice(0, 200));
362
- assert.ok(!txt.includes("在插件配置里把 requirePairing 设为 true"), "不能只让人去翻配置文件");
363
- });
364
-
365
- test("已启用时按钮变成「停用配对码」", () => {
366
- const txt = textOf(SecretBox({ self: { secret: "x".repeat(32) }, config: { requirePairing: true }, onSaved: noop })).join(" ");
367
- assert.ok(txt.includes("停用配对码"), txt.slice(0, 200));
368
- });
369
-
370
- test("说明改动立即生效、不用重启", () => {
371
- const txt = textOf(SecretBox({ self: { secret: "x".repeat(32) }, config: { requirePairing: false }, onSaved: noop })).join(" ");
372
- assert.ok(txt.includes("立即生效"), txt.slice(0, 300));
373
- });
374
-
375
- test("配置钉死时按钮禁用并说明原因(不能让人以为点了有用)", () => {
376
- const el = SecretBox({ self: { secret: "x".repeat(32) }, config: { requirePairing: true, requirePairingPinned: true }, onSaved: noop });
377
- const txt = textOf(el).join(" ");
378
- assert.ok(txt.includes("固定开启"), txt.slice(0, 300));
379
- let disabled = false;
380
- (function walk(n) {
381
- if (!n || typeof n !== "object") return;
382
- if (Array.isArray(n)) return n.forEach(walk);
383
- if (typeof n.type === "function") return walk(n.type(n.props));
384
- if (n.props && n.props.disabled === true) disabled = true;
385
- walk(n.children);
386
- if (n.props && n.props.children !== undefined) walk(n.props.children);
387
- })(el);
388
- assert.ok(disabled, "钉死时开关应被禁用");
389
- });
390
-
391
- console.log(`\n${failed === 0 ? "全部通过" : "有失败"}:${passed} 通过 / ${failed} 失败\n`);
392
- process.exit(failed === 0 ? 0 : 1);
9
+ import "./_selftest-workbench.mjs";
@@ -0,0 +1,112 @@
1
+ /**
2
+ * 目录布局自测:profile 识别、mesh 根选择、session 工作区、路径逃逸。
3
+ *
4
+ * 不碰网络、不启动 DSH;用临时目录模拟一个 profile。
5
+ */
6
+ import assert from "node:assert/strict";
7
+ import { mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
8
+ import { tmpdir } from "node:os";
9
+ import { join } from "node:path";
10
+ import { pathToFileURL } from "node:url";
11
+ import {
12
+ chooseMeshRoot,
13
+ copyLegacyFiles,
14
+ isProfileDir,
15
+ profileDirFromModuleUrl,
16
+ safeSegment,
17
+ sessionDirFor,
18
+ receiveWorkspaceDir,
19
+ } from "./layout.js";
20
+
21
+ let pass = 0;
22
+ let fail = 0;
23
+
24
+ function ok(name, fn) {
25
+ try {
26
+ fn();
27
+ console.log(` ✓ ${name}`);
28
+ pass += 1;
29
+ } catch (err) {
30
+ console.error(` ✗ ${name}: ${err?.message ?? err}`);
31
+ fail += 1;
32
+ }
33
+ }
34
+
35
+ const tmp = mkdtempSync(join(tmpdir(), "dsh-mesh-layout-"));
36
+ try {
37
+ const profile = join(tmp, "profiles", "demo");
38
+ const entry = join(profile, "node_modules", "dsh-plugin-mesh", "lib", "index.js");
39
+ mkdirSync(join(profile, "node_modules", "dsh-plugin-mesh", "lib"), { recursive: true });
40
+ writeFileSync(join(profile, "package.json"), JSON.stringify({ dsh: { profile: { bundles: [] } } }));
41
+
42
+ ok("从入口 URL 推导 profile 根目录", () => {
43
+ assert.equal(profileDirFromModuleUrl(pathToFileURL(entry).href), profile);
44
+ });
45
+
46
+ ok("只有 dsh.profile 的目录才算 profile", () => {
47
+ assert.equal(isProfileDir(profile), true);
48
+ const repo = join(tmp, "repo");
49
+ mkdirSync(repo, { recursive: true });
50
+ writeFileSync(join(repo, "package.json"), JSON.stringify({ name: "repo" }));
51
+ assert.equal(isProfileDir(repo), false);
52
+ });
53
+
54
+ ok("带 BOM 的 profile package.json 仍能识别", () => {
55
+ const bom = join(tmp, "profiles", "bom");
56
+ mkdirSync(bom, { recursive: true });
57
+ writeFileSync(join(bom, "package.json"), "\uFEFF" + JSON.stringify({ dsh: { profile: {} } }));
58
+ assert.equal(isProfileDir(bom), true);
59
+ });
60
+
61
+ ok("优先 <profile>/mesh", () => {
62
+ assert.equal(
63
+ chooseMeshRoot({ profileDir: profile, dshHome: join(tmp, "dsh-home"), homeDir: tmp }),
64
+ join(profile, "mesh"),
65
+ );
66
+ });
67
+
68
+ ok("无 profile 时回退 DSH_HOME/mesh", () => {
69
+ assert.equal(chooseMeshRoot({ dshHome: join(tmp, "dsh-home") }), join(tmp, "dsh-home", "mesh"));
70
+ });
71
+
72
+ ok("无 profile、无 DSH_HOME 时回退 ~/.dsh/mesh", () => {
73
+ assert.equal(chooseMeshRoot({ homeDir: tmp }), join(tmp, ".dsh", "mesh"));
74
+ });
75
+
76
+ ok("会话工作区在 mesh/sessions/<id> 下", () => {
77
+ assert.equal(
78
+ sessionDirFor(join(profile, "mesh"), "mesh-abc"),
79
+ join(profile, "mesh", "sessions", "mesh-abc"),
80
+ );
81
+ });
82
+
83
+ ok("mesh 会话共用 mesh-receive-task 工作区(不再按 session 分散)", () => {
84
+ const profile = "/p";
85
+ assert.equal(receiveWorkspaceDir(join(profile, "mesh")), join(profile, "mesh", "mesh-receive-task"));
86
+ });
87
+
88
+ ok("sessionId 不能逃出 sessions/", () => {
89
+ const p = sessionDirFor(join(profile, "mesh"), "../evil");
90
+ assert.equal(p, join(profile, "mesh", "sessions", ".._evil"));
91
+ assert.equal(safeSegment("../../etc/passwd").includes("/"), false);
92
+ });
93
+
94
+ ok("旧状态首次迁移,且不覆盖已有状态", () => {
95
+ const legacy = join(tmp, "legacy");
96
+ mkdirSync(legacy, { recursive: true });
97
+ writeFileSync(join(legacy, "state.json"), '{"secret":"old"}');
98
+ writeFileSync(join(legacy, "threads.json"), '{"threads":{}}');
99
+ const root = join(tmp, "newroot");
100
+ mkdirSync(root, { recursive: true });
101
+ assert.deepEqual(copyLegacyFiles(root, legacy), ["state.json", "threads.json"]);
102
+ assert.equal(readFileSync(join(root, "state.json"), "utf8"), '{"secret":"old"}');
103
+ writeFileSync(join(root, "state.json"), '{"secret":"new"}');
104
+ assert.deepEqual(copyLegacyFiles(root, legacy), []);
105
+ assert.equal(readFileSync(join(root, "state.json"), "utf8"), '{"secret":"new"}');
106
+ });
107
+ } finally {
108
+ rmSync(tmp, { recursive: true, force: true });
109
+ }
110
+
111
+ console.log(`\n${fail === 0 ? "全部通过" : "存在失败"}:${pass} 通过 / ${fail} 失败`);
112
+ if (fail > 0) process.exit(1);
@@ -9,6 +9,7 @@
9
9
  * 机器名才成功。**agent 能自救,不代表指令是对的。**
10
10
  */
11
11
  import { strict as assert } from "node:assert";
12
+ import { readFileSync } from "node:fs";
12
13
  import { buildPrompt } from "./prompt.js";
13
14
 
14
15
  let passed = 0;
@@ -77,7 +78,7 @@ test("webhook 形状(deliveryId/source)也能归一化", () => {
77
78
 
78
79
  test("没有 thread 时用 id 兜底", () => {
79
80
  const t = buildPrompt({ id: "t-9", from: "a/u", fromMachine: "a", task: "x" });
80
- assert.ok(t.includes("thread 填 t-9"), t);
81
+ assert.match(t, /thread (填 )?t-9/, t); // 文案精简后可能是「thread t-9」
81
82
  });
82
83
 
83
84
  test("全空入参不崩,也不产出 undefined", () => {
@@ -93,5 +94,70 @@ test("task 正文原样保留(不被指令淹没)", () => {
93
94
  assert.ok(t.includes(body), "正文必须逐字保留");
94
95
  });
95
96
 
97
+ // ── 回执:必须明确禁止再回派 ──
98
+ //
99
+ // 2026-10-21 真机事故:手动派发后,对端回执被注入会话,提示词仍写着
100
+ // 「做完后用 mesh_run 回派」→ agent 照做 → 两边互相回执,一轮几十条。
101
+ console.log("\n── 回执 vs 新任务:指令必须相反 ──");
102
+
103
+ test("回执:明确禁止再回派,并说明会形成循环", () => {
104
+ const p = buildPrompt({
105
+ id: "t-1", from: "hos/u0", fromMachine: "hos", thread: "T", task: "结果如下", isReply: true,
106
+ });
107
+ assert.ok(p.includes("回执"), p.slice(0, 200));
108
+ assert.ok(!/做完后用 mesh_run 工具把结果回派/.test(p), "回执不该再给「做完后回派」的指令");
109
+ assert.ok(p.includes("不要再用 mesh_run 回派"), p.slice(0, 300));
110
+ assert.ok(p.includes("循环"), "要说清后果,agent 才会真的停下");
111
+ });
112
+
113
+ test("新任务:仍然要求回派(否则对端永远收不到结果)", () => {
114
+ const p = buildPrompt({
115
+ id: "t-2", from: "hos/u0", fromMachine: "hos", thread: "T", task: "做点事",
116
+ });
117
+ assert.ok(/做完后用 mesh_run 把结果回派给 hos/.test(p), p.slice(0, 300));
118
+ assert.ok(!p.includes("不要再用 mesh_run 回派"));
119
+ });
120
+
121
+ // ── 手动派发:用户气泡里只能是用户自己那句话 ──
122
+ //
123
+ // 真机事故(2026-10-21 splitmsg → lipeng-mac,t-d5176adbec0a):预建会话里先注入
124
+ // 一条给 agent 的说明、再注入用户原文,结果第二条被当成「下一轮排队消息」插进
125
+ // inbox,随本轮结束被清掉 —— 用户点进去看到的是那条说明,自己发的那句话一个字
126
+ // 都没有。所以这里断言的不是措辞,是**只注入一条、内容就是原文、且必须
127
+ // kind:"user"**(kind 不是 user 会被渲染成折叠的「上下文注入」,气泡就没了)。
128
+ console.log("\n── 手动派发:气泡只放原文 ──");
129
+
130
+ function announceBlock() {
131
+ const src = readFileSync(new URL("./index.js", import.meta.url), "utf8");
132
+ const start = src.indexOf("if (announce?.text)");
133
+ assert.ok(start > 0, "找不到预建会话注入 announce 的分支");
134
+ return { src, block: src.slice(start, src.indexOf("} catch (err)", start)) };
135
+ }
136
+
137
+ test("预建会话只注入一条消息(多条时后面的会被吞掉)", () => {
138
+ const { block } = announceBlock();
139
+ const followups = block.match(/handle\.agent\.followup\(/g) ?? [];
140
+ assert.equal(
141
+ followups.length,
142
+ 1,
143
+ "连续两次 followup 时第二条会被当排队消息吞掉(实测:说明留下、原文被吞,正好反了)",
144
+ );
145
+ });
146
+
147
+ test("注入的内容就是原文,不加任何说明文字", () => {
148
+ const { block } = announceBlock();
149
+ assert.ok(
150
+ /text:\s*announce\.text\s*\}/.test(block),
151
+ "必须是 announce.text 原样注入,不能拼前缀/后缀",
152
+ );
153
+ assert.ok(!/announce\.note/.test(announceBlock().src), "说明不能再作为第二条消息注入");
154
+ });
155
+
156
+ test("必须是 kind:\"user\",否则被折叠成上下文注入、不成为气泡", () => {
157
+ const { block } = announceBlock();
158
+ assert.ok(/source:\s*\{\s*kind:\s*"user"/.test(block), "原文必须 kind:\"user\" 才渲染成正常气泡");
159
+ assert.ok(!/kind:\s*"webhook"/.test(block), "气泡里不能掺进 webhook/notice");
160
+ });
161
+
96
162
  console.log(`\n${failed === 0 ? "全部通过" : "有失败"}:${passed} 通过 / ${failed} 失败\n`);
97
163
  process.exit(failed === 0 ? 0 : 1);