dsh-plugin-mesh 0.4.0 → 0.5.0

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
@@ -612,6 +612,33 @@ window.__ModuleLoader__.load({
612
612
  );
613
613
  }
614
614
 
615
+ /**
616
+ * 端点标签的显示顺序(只影响展示,不影响发送时的通道选择):
617
+ * 1. 局域网「在用」
618
+ * 2. 互联网「在用」
619
+ * 3. 其余按上次可见时间倒序(最近见过的在前)
620
+ * 恢复自重启前快照的机器没有「在用」,全部按第 3 条排。
621
+ */
622
+ function orderEndpointsForDisplay(peer) {
623
+ const restored = peer.restored === true;
624
+ const rank = (ep) => {
625
+ const active = !restored && ep.transport === peer.transport;
626
+ if (active && ep.transport === "lan") return 0;
627
+ if (active) return 1;
628
+ return 2;
629
+ };
630
+ const transportRank = (ep) => (ep.transport === "tsnet" ? 1 : 0);
631
+ return (peer.endpoints || []).slice().sort((a, b) => {
632
+ const d = rank(a) - rank(b);
633
+ if (d !== 0) return d;
634
+ const byTime = (Number(b.lastSeen) || 0) - (Number(a.lastSeen) || 0);
635
+ if (byTime !== 0) return byTime;
636
+ // 时间完全相同时(同一轮心跳写下的两条)按通道偏好定序,
637
+ // 否则顺序取决于数组原始顺序,看起来就是随机的 —— 真机上就被这么质疑过。
638
+ return transportRank(a) - transportRank(b);
639
+ });
640
+ }
641
+
615
642
  function PeerRow({ peer, onSend, onProbe, probe }) {
616
643
  const target = peer.machine;
617
644
  return h(
@@ -626,6 +653,9 @@ window.__ModuleLoader__.load({
626
653
  { style: { display: "flex", gap: 8, alignItems: "center", flexWrap: "wrap" } },
627
654
  h("strong", null, peer.machine),
628
655
  peer.online ? null : h("span", { style: S.tag }, "离线"),
656
+ // 「离线」和「这次启动还没见过」是两件事:后者来自重启前的快照,
657
+ // 地址是上次的,可能只是还没来得及重新发现。分开标注,避免误判成对端挂了。
658
+ peer.online || !peer.restored ? null : h("span", { style: S.tag }, "上次见到"),
629
659
  // 一台设备可能同时有局域网与互联网两条通道,任意一条通就算可达。
630
660
  peer.endpoints
631
661
  ? h(
@@ -644,13 +674,17 @@ window.__ModuleLoader__.load({
644
674
  ? h(
645
675
  "div",
646
676
  { style: { display: "flex", gap: 6, flexWrap: "wrap", marginTop: 5 } },
647
- (peer.endpoints || []).map((ep) => {
677
+ orderEndpointsForDisplay(peer).map((ep) => {
648
678
  const cooling = !!(ep.downUntil && Date.now() < ep.downUntil);
649
679
  const unverified = ep.verified === false;
650
- const active = ep.transport === peer.transport;
651
- const color = active ? "#2ea043" : cooling ? "#c0392b" : unverified ? "#9aa0a6" : "#666";
680
+ // 从重启前快照恢复的机器:一条通道都没验过,也没有"在用"这回事。
681
+ // 以前这里会按 peer.transport 选一条标成「在用」,实测对方明明离线,
682
+ // 界面上却写着「互联网 在用」——与事实相反。
683
+ const restored = peer.restored === true;
684
+ const active = !restored && ep.transport === peer.transport;
685
+ const color = restored ? "#9aa0a6" : active ? "#2ea043" : cooling ? "#c0392b" : unverified ? "#9aa0a6" : "#666";
652
686
  const cname = ep.transport === "tsnet" ? "互联网" : "局域网";
653
- const cstate = active ? "在用" : cooling ? "冷却中" : unverified ? "未探测" : "备用";
687
+ const cstate = restored ? "上次见到" : active ? "在用" : cooling ? "冷却中" : unverified ? "未探测" : "备用";
654
688
  return h(
655
689
  "span",
656
690
  {
@@ -658,6 +692,7 @@ window.__ModuleLoader__.load({
658
692
  style: { ...S.tag, color, borderColor: color, ...(active ? { fontWeight: 600 } : null) },
659
693
  title:
660
694
  `${cname} ${ep.host}:${ep.port} · ${cstate}` +
695
+ (restored && ep.lastSeen ? ` · 上次心跳 ${new Date(ep.lastSeen).toLocaleString()}` : "") +
661
696
  (ep.rttMs ? ` · ${ep.rttMs}ms` : "") +
662
697
  ` · 成功 ${ep.okCount} 次 / 失败 ${ep.failCount} 次`,
663
698
  },
@@ -245,6 +245,58 @@ test("PeerRow 渲染出的文案里包含对端的能力", () => {
245
245
  assert.ok(txt.includes("go 1.25"), `机器卡片里应显示能力:${txt}`);
246
246
  });
247
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
+
248
300
  console.log("\n── TsnetCard:用户不该自己去后台找授权码地址 ──");
249
301
 
250
302
  const noop = () => {};
@@ -0,0 +1,195 @@
1
+ /**
2
+ * 持久化自测:任务记录与机器列表在重启后能不能恢复,以及恢复出来的语义对不对。
3
+ *
4
+ * 重点不是"文件能读回来",而是**恢复出来的机器必须是离线状态**:
5
+ * 如果恢复时把 lastSeen 刷成 now,页面会先把一堆关机机器显示成在线,
6
+ * 然后逐个变灰 —— 那是比"看不到机器"更糟的错觉。
7
+ */
8
+ import assert from "node:assert/strict";
9
+ import { mkdtempSync, rmSync, existsSync, readFileSync, writeFileSync } from "node:fs";
10
+ import { tmpdir } from "node:os";
11
+ import { join } from "node:path";
12
+ import {
13
+ loadTaskHistory,
14
+ saveTaskHistory,
15
+ trimTaskRecord,
16
+ loadPeerSnapshot,
17
+ savePeerSnapshot,
18
+ toPeerSnapshot,
19
+ MAX_RECORDS,
20
+ TASK_TEXT_LIMIT,
21
+ } from "./persist.js";
22
+ import { MeshDiscovery, APP_TAG } from "./discovery.js";
23
+
24
+ const root = mkdtempSync(join(tmpdir(), "mesh-persist-test-"));
25
+ const cleanups = [];
26
+
27
+ function freshDir() {
28
+ const d = mkdtempSync(join(root, "d-"));
29
+ cleanups.push(d);
30
+ return d;
31
+ }
32
+
33
+ try {
34
+ // ── 任务记录:往返 ──
35
+ {
36
+ const dir = freshDir();
37
+ const inbound = [{ id: "t-1", from: "B/u", task: "hello", status: "dispatched" }];
38
+ const outbound = [{ id: "t-2", toMachine: "B", task: "hi", ok: true, status: 200 }];
39
+ assert.equal(saveTaskHistory(dir, inbound, outbound), true, "应当写成功");
40
+ const back = loadTaskHistory(dir);
41
+ assert.equal(back.inbound.length, 1);
42
+ assert.equal(back.outbound.length, 1);
43
+ assert.equal(back.inbound[0].id, "t-1");
44
+ assert.equal(back.outbound[0].status, 200);
45
+ assert.ok(back.savedAt > 0);
46
+ console.log("✓ 任务记录写入后能原样读回");
47
+ }
48
+
49
+ // ── 任务记录:上限与截断 ──
50
+ {
51
+ const dir = freshDir();
52
+ const many = Array.from({ length: MAX_RECORDS + 37 }, (_, i) => ({ id: `t-${i}`, task: "x" }));
53
+ saveTaskHistory(dir, many, []);
54
+ const back = loadTaskHistory(dir);
55
+ assert.equal(back.inbound.length, MAX_RECORDS, `只保留最后 ${MAX_RECORDS} 条`);
56
+ assert.equal(back.inbound.at(-1).id, `t-${MAX_RECORDS + 36}`, "保留的是最新的那批");
57
+
58
+ const long = { id: "t-long", task: "啊".repeat(TASK_TEXT_LIMIT + 500) };
59
+ const trimmed = trimTaskRecord(long);
60
+ assert.ok(trimmed.task.length < long.task.length, "超长正文必须被截断");
61
+ assert.equal(trimmed.taskTruncated, true, "截断要留标记,不能假装完整");
62
+ assert.ok(trimmed.task.includes("已截断"), "要说明被截断了");
63
+ console.log("✓ 超量滚动、超长正文截断且留标记");
64
+ }
65
+
66
+ // ── 坏文件不能把启动搞挂 ──
67
+ {
68
+ const dir = freshDir();
69
+ saveTaskHistory(dir, [{ id: "a" }], []);
70
+ // 模拟写到一半被杀
71
+ const p = join(dir, "tasks.json");
72
+ const raw = readFileSync(p, "utf8");
73
+ writeFileSync(p, raw.slice(0, Math.floor(raw.length / 2)));
74
+ const back = loadTaskHistory(dir);
75
+ assert.deepEqual(back.inbound, [], "半截 JSON 应当当成没有历史");
76
+ console.log("✓ 半截文件按「没有历史」处理,不抛错");
77
+ }
78
+
79
+ // ── 机器列表:快照往返 ──
80
+ {
81
+ const dir = freshDir();
82
+ const now = Date.now();
83
+ const peers = [{
84
+ id: "peer-1", machine: "hos", hostname: "localhost", mac: "", os: "android",
85
+ user: "u0", profile: "web", version: "0.3.36", host: "192.168.1.9", port: 45917,
86
+ ts: now - 5000, capabilities: null,
87
+ endpoints: [{ transport: "lan", host: "192.168.1.9", port: 45917, lastSeen: now - 5000, lastOkAt: now - 5000, verified: true }],
88
+ }];
89
+ assert.equal(savePeerSnapshot(dir, peers), true);
90
+ const snap = loadPeerSnapshot(dir);
91
+ assert.equal(snap.peers.length, 1);
92
+ assert.equal(snap.peers[0].record.id, "peer-1");
93
+ assert.equal(snap.peers[0].record.app, APP_TAG);
94
+ assert.equal(snap.peers[0].endpoints[0].lastSeen, now - 5000, "必须保留原始 lastSeen");
95
+ console.log("✓ 机器列表快照往返,lastSeen 原样保留");
96
+ }
97
+
98
+ // ── 恢复语义:离线、带标记、不覆盖现网 ──
99
+ {
100
+ const dir = freshDir();
101
+ const d = new MeshDiscovery({ id: "me", port: 0, meta: { machine: "me" } });
102
+ const stale = Date.now() - 3600_000; // 一小时前见过
103
+ const peer = {
104
+ id: "old-peer", machine: "old", host: "10.0.0.9", port: 45917, ts: stale,
105
+ endpoints: [{ transport: "lan", host: "10.0.0.9", port: 45917, lastSeen: stale, lastOkAt: stale, verified: true }],
106
+ };
107
+ savePeerSnapshot(dir, [peer]);
108
+
109
+ const n = d.restore(loadPeerSnapshot(dir).peers);
110
+ assert.equal(n, 1, "应当恢复 1 台");
111
+ const after = d.peers().find((p) => p.id === "old-peer");
112
+ assert.ok(after, "恢复的机器要出现在列表里");
113
+ assert.equal(after.restored, true, "要能区分「上次见到」与「这次见到」");
114
+ assert.equal(after.online, false, "一小时前的记录不能算在线");
115
+ assert.equal(after.host, "10.0.0.9", "地址要能显示出来");
116
+ // 恢复的机器没有任何通道在用:以前这里填了"最近一条端点",界面就标成「在用」,
117
+ // 而对方其实已经离线 —— 真机一眼看出来的那个错。
118
+ assert.equal(after.transport, null, "不能让界面以为某条通道在用");
119
+ assert.equal(d.isRestoredOnly("old-peer"), true, "应当被标成「只在缓存里」");
120
+
121
+ // 再次恢复同一份快照:不能重复插入
122
+ assert.equal(d.peers().filter((p) => p.id === "old-peer").length, 1, "不能出现两条");
123
+
124
+ // 现网重新发现 → 只剩活记录,且不再是"恢复的"
125
+ d.note({
126
+ app: APP_TAG, id: "old-peer", machine: "old", host: "10.0.0.9", port: 45917,
127
+ hostname: "old.local", ts: Date.now(),
128
+ }, "10.0.0.9");
129
+ const hits = d.peers().filter((p) => p.id === "old-peer");
130
+ assert.equal(hits.length, 1, "缓存与活记录不能同时存在");
131
+ assert.equal(hits[0].restored, false, "重新发现后要去掉「上次见到」标记");
132
+ assert.equal(hits[0].online, true, "刚收到心跳就是在线");
133
+ assert.equal(d.isRestoredOnly("old-peer"), false);
134
+
135
+ // 自己的 id 不能被"恢复"成一台对端
136
+ assert.equal(d.restore([{ record: { app: APP_TAG, id: "me", machine: "me" }, endpoints: [{ transport: "lan", host: "1.1.1.1", port: 1 }] }]), 0);
137
+ console.log("✓ 恢复语义正确:离线、带标记、不重复、不冒充自己、重新发现后转在线");
138
+ }
139
+
140
+ // ── 回归:恢复出来的机器不能被清扫删掉 ──
141
+ //
142
+ // 第一版实现把缓存塞进活跃注册表,而 #sweep() 会摘掉 keepMs 之外的端点、
143
+ // 端点全没了就删设备。缓存条目的 lastSeen 天然是旧的,于是恢复出来的离线机器
144
+ // 活不过一个清扫周期(实测 5 秒内消失)—— 而离线机器正是恢复功能唯一的价值。
145
+ // 这里用很小的 ttlMs 逼出清扫,直接验证它活着。
146
+ {
147
+ const d = new MeshDiscovery({ id: "me2", port: 0, meta: { machine: "me2" }, ttlMs: 1200 });
148
+ const veryOld = Date.now() - 10 * 3600_000; // 十小时前
149
+ d.restore([{
150
+ record: { app: APP_TAG, id: "offline-peer", machine: "offline", host: "10.0.0.7", port: 45917, ts: veryOld },
151
+ endpoints: [{ transport: "lan", host: "10.0.0.7", port: 45917, lastSeen: veryOld, lastOkAt: veryOld, verified: true }],
152
+ }]);
153
+ d.start({ multicast: false }); // 只为了让清扫定时器跑起来
154
+ await new Promise((r) => setTimeout(r, 2200)); // 至少跨过一个清扫周期
155
+ const kept = d.peers().find((p) => p.id === "offline-peer");
156
+ assert.ok(kept, "恢复出来的离线机器必须扛得住清扫(第一版就是在这里丢的)");
157
+ assert.equal(kept.online, false);
158
+ d.stop?.();
159
+ console.log("✓ 恢复的机器跨过清扫周期仍在(回归已钉住)");
160
+ }
161
+
162
+ // ── 列表排序:在线的排前面 ──
163
+ //
164
+ // 真机反馈:离线的 hos 排在了在线的 myserver 前面(原来只按机器名排)。
165
+ {
166
+ const d = new MeshDiscovery({ id: "me3", port: 0, meta: { machine: "me3" }, ttlMs: 60000 });
167
+ const old = Date.now() - 3600_000;
168
+ // 缓存里放一台机器名靠前的离线机器(hos),活的放一台机器名靠后的(myserver)
169
+ d.restore([{
170
+ record: { app: APP_TAG, id: "p-hos", machine: "hos", host: "10.0.0.5", port: 45917, ts: old },
171
+ endpoints: [{ transport: "lan", host: "10.0.0.5", port: 45917, lastSeen: old, verified: true }],
172
+ }]);
173
+ d.note({
174
+ app: APP_TAG, id: "p-myserver", machine: "myserver", host: "10.0.0.6", port: 45917, ts: Date.now(),
175
+ }, "10.0.0.6");
176
+ const order = d.peers().map((p) => p.machine);
177
+ assert.deepEqual(order, ["myserver", "hos"], `在线应排在离线前,实际:${order.join(",")}`);
178
+ assert.equal(d.peers()[0].online, true);
179
+ console.log("✓ 列表排序:在线优先,离线的「上次见到」排最后");
180
+ }
181
+
182
+ // ── 缺文件 / 空目录 ──
183
+ {
184
+ const dir = freshDir();
185
+ assert.deepEqual(loadTaskHistory(dir), { inbound: [], outbound: [], savedAt: 0 });
186
+ assert.deepEqual(loadPeerSnapshot(dir), { peers: [], savedAt: 0 });
187
+ assert.equal(existsSync(join(dir, "tasks.json")), false);
188
+ console.log("✓ 没有历史文件时安静返回空,不抛错");
189
+ }
190
+
191
+ console.log("\n全部通过");
192
+ } finally {
193
+ for (const d of cleanups) rmSync(d, { recursive: true, force: true });
194
+ rmSync(root, { recursive: true, force: true });
195
+ }
package/lib/discovery.js CHANGED
@@ -22,6 +22,15 @@ export const MESH_GROUP = "239.255.42.99";
22
22
  export const MESH_PORT = 45892;
23
23
  export const APP_TAG = "dsh-mesh";
24
24
 
25
+ /** 「上次见过」缓存的保留期与条数上限:地址用不了那么久,也不该无限长。 */
26
+ const KNOWN_TTL_MS = 30 * 24 * 3600 * 1000;
27
+ const KNOWN_MAX = 200;
28
+
29
+ /** 一个缓存条目里最新的一条证据时间。 */
30
+ function newestOf(known) {
31
+ return Object.values(known?.endpoints ?? {}).reduce((m, e) => Math.max(m, Number(e.lastSeen) || 0), 0);
32
+ }
33
+
25
34
  /**
26
35
  * 名片协议版本。
27
36
  *
@@ -170,6 +179,15 @@ export class MeshDiscovery extends EventEmitter {
170
179
  #ttlMs;
171
180
  #keepMs;
172
181
  #peers = new Map();
182
+ /**
183
+ * 「上次见过的机器」缓存:id → {record, endpoints, restoredAt}。
184
+ *
185
+ * **刻意与 #peers 分开**:活跃注册表的所有规则(TTL、keepMs、清扫、在线判定)
186
+ * 都是为"现在活着"服务的。把缓存塞进 #peers 会被 #sweep() 立刻删掉 —— 因为
187
+ * 缓存的 lastSeen 天然是旧的(这正是它诚实的地方)。第一版实现就是这么错的:
188
+ * 恢复出来的离线机器活不过一个清扫周期。
189
+ */
190
+ #known = new Map();
173
191
  #socket = null;
174
192
  #announceTimer = null;
175
193
  #sweepTimer = null;
@@ -383,9 +401,55 @@ export class MeshDiscovery extends EventEmitter {
383
401
  /** 当前对端快照,按 machine 名排序。 */
384
402
  peers() {
385
403
  const now = Date.now();
386
- return [...this.#peers.values()]
387
- .map((p) => this.#project(p, now))
388
- .sort((a, b) => String(a.machine).localeCompare(String(b.machine)) || String(a.id).localeCompare(String(b.id)));
404
+ const live = [...this.#peers.values()].map((p) => this.#project(p, now));
405
+ const liveIds = new Set(live.map((p) => p.id));
406
+ // 缓存里、但这次启动还没重新发现的机器:作为「上次见到」补进列表。
407
+ // 它们不受 TTL / 清扫影响 —— 这正是与活跃注册表分开的意义。
408
+ const known = [...this.#known.entries()]
409
+ .filter(([id]) => !liveIds.has(id))
410
+ .map(([, k]) => this.#projectKnown(k));
411
+ // 排序规则(真机上被指出来的问题:离线的 hos 排在了在线的 myserver 前面,
412
+ // 因为原来只按机器名排)。用户首先关心"谁能用":
413
+ // 1. 在线
414
+ // 2. 离线但这次启动见过(刚掉线,地址可信)
415
+ // 3. 只在缓存里(上次见到,地址可能已失效)
416
+ // 同级按最后活跃时间倒序,最后用机器名兜底保证稳定。
417
+ const rank = (p) => (p.online ? 0 : p.restored === true ? 2 : 1);
418
+ return [...live, ...known].sort(
419
+ (a, b) =>
420
+ rank(a) - rank(b) ||
421
+ (Number(b.lastSeen) || 0) - (Number(a.lastSeen) || 0) ||
422
+ String(a.machine).localeCompare(String(b.machine)) ||
423
+ String(a.id).localeCompare(String(b.id)),
424
+ );
425
+ }
426
+
427
+ /**
428
+ * 把「上次见过的机器」投影成与活机器同形的记录:
429
+ * online 恒为 false,restored 恒为 true,地址取最近有一个端点。
430
+ */
431
+ #projectKnown(k) {
432
+ const eps = Object.values(k.endpoints ?? {});
433
+ const last = eps.slice().sort((a, b) => Number(b.lastSeen) - Number(a.lastSeen))[0] ?? null;
434
+ return {
435
+ ...k.record,
436
+ endpoints: eps.map((e) => ({ ...e })),
437
+ online: false,
438
+ restored: true,
439
+ restoredAt: k.restoredAt,
440
+ lastSeen: newestOf(k) || k.record.ts || k.restoredAt,
441
+ // **没有通道在用**:这些端点是历史地址,一条都没验过。
442
+ // 以前这里填「最近一条端点的 transport」,界面就把它标成「在用」——
443
+ // 与实际相反(对方已经离线),这是真机上被一眼看出来的那个错。
444
+ transport: null,
445
+ host: last?.host ?? "",
446
+ port: last?.port ?? 0,
447
+ sourceAddress: last?.host ?? "",
448
+ knownAddresses: eps.filter((e) => e.host).map((e) => `${e.transport}:${e.host}:${e.port}`),
449
+ // 缓存里的能力名片可能已经过期;交给 UI 按 restored 处理,别谎称新鲜
450
+ capabilitiesStale: true,
451
+ capabilitySummary: summarizeCapabilities(k.record.capabilities),
452
+ };
389
453
  }
390
454
 
391
455
  /**
@@ -405,6 +469,8 @@ export class MeshDiscovery extends EventEmitter {
405
469
  ...p,
406
470
  endpoints,
407
471
  online: peerOnline(p, now, this.#ttlMs),
472
+ // 活记录恒为 false(缓存投影那边是 true)。显式给值,别让调用方靠 undefined 猜。
473
+ restored: false,
408
474
  // 设备级 lastSeen = 最新一条端点的证据时间。
409
475
  // 内部记录已经改成**端点级** lastSeen,这里是补一个设备级的给 UI/工具用 ——
410
476
  // 漏了它客户端会渲染出「最后心跳 Invalid Date」(new Date(undefined))。
@@ -428,7 +494,14 @@ export class MeshDiscovery extends EventEmitter {
428
494
 
429
495
  get(id) {
430
496
  const p = this.#peers.get(id);
431
- return p ? this.#project(p) : undefined;
497
+ if (p) return this.#project(p);
498
+ const k = this.#known.get(id);
499
+ return k ? this.#projectKnown(k) : undefined;
500
+ }
501
+
502
+ /** 这个 id 是不是只存在于「上次见过」缓存里(不算活机器)。 */
503
+ isRestoredOnly(id) {
504
+ return !this.#peers.has(id) && this.#known.has(id);
432
505
  }
433
506
 
434
507
  /**
@@ -444,6 +517,75 @@ export class MeshDiscovery extends EventEmitter {
444
517
  return this.#upsert(record, { address: sourceAddress ?? record.host ?? "?", ...meta });
445
518
  }
446
519
 
520
+ /**
521
+ * 用磁盘快照把「上次见过的机器」放回来。
522
+ *
523
+ * 与 note() 的关键区别:**保留快照里的 lastSeen / lastOkAt,不刷新成 now**,
524
+ * 端点一律标记为未验证。因此恢复出来的机器通常显示为**离线**——它表达的是
525
+ * "我们上次知道它在这个地址",而不是"它现在在线"。这条区别很重要:如果恢复
526
+ * 时把 lastSeen 改成 now,页面会先把一堆离线机器显示成在线,然后逐个变灰。
527
+ *
528
+ * 已经被现网重新发现的(#peers 里已有同 id)直接跳过,以现网为准。
529
+ * @param {{record: object, endpoints: object[]}[]} snapshot
530
+ * @returns {number} 实际恢复的台数
531
+ */
532
+ restore(snapshot) {
533
+ const now = Date.now();
534
+ let changed = 0;
535
+ const cutoff = now - KNOWN_TTL_MS;
536
+ for (const item of snapshot ?? []) {
537
+ const msg = item?.record;
538
+ if (!msg || msg.app !== APP_TAG || !msg.id || msg.id === this.#id) continue;
539
+ const peerId = String(msg.id);
540
+ // 现网已经发现的,以现网为准,不写缓存
541
+ if (this.#peers.has(peerId)) continue;
542
+
543
+ const endpoints = {};
544
+ for (const ep of item.endpoints ?? []) {
545
+ if (!ep?.transport) continue;
546
+ endpoints[ep.transport] = {
547
+ transport: String(ep.transport),
548
+ host: String(ep.host ?? ""),
549
+ port: Number(ep.port) || 0,
550
+ lastSeen: Number(ep.lastSeen) || 0,
551
+ lastOkAt: Number(ep.lastOkAt) || 0,
552
+ verified: ep.verified === true,
553
+ };
554
+ }
555
+ if (Object.keys(endpoints).length === 0) continue;
556
+ // 太旧的快照没有恢复价值(地址大概率早已失效)
557
+ const newest = Object.values(endpoints).reduce((m, e) => Math.max(m, e.lastSeen), 0);
558
+ if (newest && newest < cutoff) continue;
559
+
560
+ this.#known.set(peerId, {
561
+ record: {
562
+ id: peerId,
563
+ machine: String(msg.machine ?? "unknown"),
564
+ hostname: String(msg.hostname ?? ""),
565
+ mac: String(msg.mac ?? ""),
566
+ os: String(msg.os ?? ""),
567
+ user: String(msg.user ?? ""),
568
+ profile: String(msg.profile ?? ""),
569
+ version: String(msg.version ?? ""),
570
+ capabilities: sanitizeCapabilities(msg.capabilities) ?? null,
571
+ ts: Number(msg.ts) || 0,
572
+ },
573
+ endpoints,
574
+ restoredAt: now,
575
+ });
576
+ changed += 1;
577
+ }
578
+ // 缓存只留最近的一批,避免年久失修地无限增长
579
+ if (this.#known.size > KNOWN_MAX) {
580
+ const drop = [...this.#known.entries()]
581
+ .sort((a, b) => newestOf(a[1]) - newestOf(b[1]))
582
+ .slice(0, this.#known.size - KNOWN_MAX);
583
+ for (const [id] of drop) this.#known.delete(id);
584
+ }
585
+ if (changed > 0) this.emit("change", this.peers());
586
+ return changed;
587
+ }
588
+
447
589
  /**
448
590
  * 登记一个"知道地址但还没探过"的 tailnet 候选端点。
449
591
  *
@@ -567,6 +709,9 @@ export class MeshDiscovery extends EventEmitter {
567
709
  peer.version = String(msg.version ?? peer.version ?? "");
568
710
  peer.ts = Number(msg.ts) || now;
569
711
 
712
+ // 现网又见到它了 → 缓存条目作废,以活记录为准(避免同一台机器出现两次)。
713
+ this.#known.delete(id);
714
+
570
715
  // ── 能力名片(Placement 步骤 ①)──
571
716
  //
572
717
  // 净化后再存:这块数据来自网络,之后会进 UI、也会喂给 Placement 做决策,
package/lib/index.js CHANGED
@@ -39,13 +39,19 @@ import {
39
39
  import { conversationKey, replyTarget } from "./conversation.js";
40
40
  import { buildPrompt } from "./prompt.js";
41
41
  import { resolvePairing } from "./pairing.js";
42
+ import {
43
+ loadTaskHistory,
44
+ saveTaskHistory,
45
+ loadPeerSnapshot,
46
+ savePeerSnapshot,
47
+ } from "./persist.js";
42
48
  import { TsnetNode } from "./tsnet/manager.js";
43
49
  import { tailnetFetch, tailnetOrigin } from "./tsnet/bridge.js";
44
50
 
45
51
  export const name = "dsh-plugin-mesh";
46
52
  export const inject = ["tools", "webServer"];
47
53
 
48
- const VERSION = "0.4.0";
54
+ const VERSION = "0.5.0";
49
55
  const RULE_ID = "mesh-inbound";
50
56
  const RULE_KIND = "mesh";
51
57
  const MAX_BODY = 256 * 1024;
@@ -461,6 +467,30 @@ function applyUnsafe(ctx, config) {
461
467
 
462
468
  const inbound = [];
463
469
  const outbound = [];
470
+
471
+ // ── 任务记录的持久化 ──
472
+ //
473
+ // 这两个数组原来是纯内存态(上限各 200 条),重启即清空 —— 排查"刚才到底
474
+ // 派发了什么"只能去翻会话记录。启动时捞回上次的记录,之后每次增删延时落盘。
475
+ const restoredHistory = loadTaskHistory(stateDir());
476
+ if (restoredHistory.inbound.length > 0) inbound.push(...restoredHistory.inbound);
477
+ if (restoredHistory.outbound.length > 0) outbound.push(...restoredHistory.outbound);
478
+ if (inbound.length > 0 || outbound.length > 0) {
479
+ log(
480
+ `已恢复重启前的任务记录:收件 ${inbound.length} 条 / 发件 ${outbound.length} 条` +
481
+ (restoredHistory.savedAt ? `(快照 ${new Date(restoredHistory.savedAt).toISOString()})` : ""),
482
+ );
483
+ }
484
+ let historyTimer = null;
485
+ /** 延时落盘:一次密集来包可能连推好几条,没必要每条都写一次磁盘。 */
486
+ const scheduleHistorySave = () => {
487
+ if (historyTimer) return;
488
+ historyTimer = setTimeout(() => {
489
+ historyTimer = null;
490
+ saveTaskHistory(stateDir(), inbound, outbound);
491
+ }, 500);
492
+ historyTimer.unref?.();
493
+ };
464
494
  /**
465
495
  * 每个 thread 的唤醒账本:{ wakesAt: number[], sessionId }。
466
496
  * wakesAt 只保留滑动窗口内的时间戳,既给限速/冷却用,也让后续消息
@@ -513,6 +543,34 @@ function applyUnsafe(ctx, config) {
513
543
  }
514
544
  });
515
545
 
546
+ // ── 机器列表的持久化 ──
547
+ //
548
+ // 重启后不必干等组播/扫描重新发现:先把上次见过的机器按「离线但已知地址」
549
+ // 放回来(restore 保留原 lastSeen,不会假装在线)。离线机器尤其需要它 ——
550
+ // 对端关机时永远等不到重新发现,页面就会一直是空的。
551
+ {
552
+ const snap = loadPeerSnapshot(stateDir());
553
+ if (snap.peers.length > 0) {
554
+ const restored = discovery.restore(snap.peers);
555
+ if (restored > 0) {
556
+ log(
557
+ `已恢复 ${restored} 台上次见过的机器(离线,重新发现后转为在线)` +
558
+ (snap.savedAt ? `,快照时间 ${new Date(snap.savedAt).toISOString()}` : ""),
559
+ );
560
+ }
561
+ }
562
+ }
563
+ let peerSnapshotTimer = null;
564
+ const schedulePeerSnapshot = () => {
565
+ if (peerSnapshotTimer) return;
566
+ peerSnapshotTimer = setTimeout(() => {
567
+ peerSnapshotTimer = null;
568
+ savePeerSnapshot(stateDir(), discovery.peers());
569
+ }, 2000);
570
+ peerSnapshotTimer.unref?.();
571
+ };
572
+ discovery.on("change", schedulePeerSnapshot);
573
+
516
574
  // ── 能力采集(Placement 步骤 ①)──
517
575
  //
518
576
  // 尽早启动:采集是异步的、绝不阻塞启动(首轮可能要等 GPU 探测 ~3.5s)。
@@ -544,7 +602,7 @@ function applyUnsafe(ctx, config) {
544
602
  const waker = { ready: false, ctx: undefined };
545
603
 
546
604
  // 1) 先起对端 HTTP(拿到真实端口),再开始发现
547
- startPeerServer(ctx, { config, discovery, inbound, log, warn, waker, threadState, capFor, capOverrides, throttled })
605
+ startPeerServer(ctx, { config, discovery, inbound, log, warn, waker, threadState, capFor, capOverrides, throttled, onHistoryChange: scheduleHistorySave })
548
606
  .then(async (port) => {
549
607
  discovery.setPort(port);
550
608
 
@@ -649,10 +707,10 @@ function applyUnsafe(ctx, config) {
649
707
  setupInbound(ctx, config, log, warn, waker);
650
708
 
651
709
  // 3) agent 工具
652
- registerTools(ctx, { discovery, config, inbound, outbound, log, warn, threadState });
710
+ registerTools(ctx, { discovery, config, inbound, outbound, log, warn, threadState, onHistoryChange: scheduleHistorySave });
653
711
 
654
712
  // 4) UI 接口
655
- registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound, log, warn, threadState, capFor, capOverrides, throttled, waker });
713
+ registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound, log, warn, threadState, capFor, capOverrides, throttled, waker, onHistoryChange: scheduleHistorySave });
656
714
 
657
715
  ctx.effect(() => () => {
658
716
  discovery.stop();
@@ -995,7 +1053,7 @@ function classifyInbound(task, threadState, config, now, capFor, { canInject = f
995
1053
  * 收到对端任务:会话键命中且会话仍活跃就复用,否则新建,
996
1054
  * 最后才新建会话。复用是为了避免"每条消息都从零重新探索上下文"。
997
1055
  */
998
- function handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadState, capFor, throttled) {
1056
+ function handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadState, capFor, throttled, onHistoryChange) {
999
1057
  const rec = inbound.find((t) => t.id === task.id);
1000
1058
  // 记下"回信地址",与"本机用哪个会话处理"是两件事。对端可以 GET
1001
1059
  // /mesh/v1/tasks 读到它,调试时能看清结果该送回哪里。
@@ -1028,6 +1086,7 @@ function handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadS
1028
1086
  if (!verdict.wake) {
1029
1087
  if (rec) {
1030
1088
  rec.status = verdict.kind === "cap" ? "throttled" : "noted-only";
1089
+ onHistoryChange?.();
1031
1090
  // 原因必须写出来。之前这里什么都不记,于是 status='noted-only' 时
1032
1091
  // routeDecision 是 None —— 看不出为什么没处理,又回到"只能靠猜"的老路
1033
1092
  rec.routeDecision = `未唤醒:${verdict.reason}`;
@@ -1092,6 +1151,7 @@ function handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadS
1092
1151
  );
1093
1152
  if (targetRec) {
1094
1153
  targetRec.status = status;
1154
+ onHistoryChange?.();
1095
1155
  // 决策留痕:对端可以 GET /mesh/v1/tasks 读到"为什么这么路由"。
1096
1156
  // 没有这个,出问题时只能靠猜(dispatchError 那次就是这么加的)。
1097
1157
  targetRec.routeDecision = `${label} ${sessionId}(会话键 ${conversationKey(targetTask) || "无"})`;
@@ -1128,6 +1188,7 @@ function handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadS
1128
1188
  if (!waker?.ready) {
1129
1189
  if (rec) {
1130
1190
  rec.status = "stored-only";
1191
+ onHistoryChange?.();
1131
1192
  rec.routeDecision = key ? `无法新建会话(会话键 ${key})` : "无法新建会话(无会话键)";
1132
1193
  // 记下原因,让对端能远程读到(GET /mesh/v1/tasks)。一台没有界面或
1133
1194
  // 日志访问权的机器(比如 Android/Termux)出问题,否则只能靠猜。
@@ -1148,6 +1209,7 @@ function handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadS
1148
1209
  // 背压:明确回"忙",而不是无脑排队让对方以为已受理
1149
1210
  if (rec) {
1150
1211
  rec.status = "busy";
1212
+ onHistoryChange?.();
1151
1213
  rec.routeDecision = `会话 ${key} 积压 ${pending.length} 条(上限 ${MAX_PENDING_PER_CONV}),已背压`;
1152
1214
  }
1153
1215
  warn(`任务 ${task.id} 被背压:会话 ${key} 积压已达上限 ${MAX_PENDING_PER_CONV}`);
@@ -1156,6 +1218,7 @@ function handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadS
1156
1218
  pending.push({ task, rec });
1157
1219
  if (rec) {
1158
1220
  rec.status = "queued-for-session";
1221
+ onHistoryChange?.();
1159
1222
  rec.routeDecision = `会话 ${key} 正在建会话,已排队(队内第 ${pending.length} 条)`;
1160
1223
  }
1161
1224
  log(`任务 ${task.id} 排队等待会话 ${key} 建立`);
@@ -1172,6 +1235,7 @@ function handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadS
1172
1235
  .then((sessionId) => {
1173
1236
  if (rec) {
1174
1237
  rec.status = "dispatched";
1238
+ onHistoryChange?.();
1175
1239
  // 三分支文案要互斥:恢复成功时不能再挂「首次出现,或原会话已结束」——
1176
1240
  // 那句话正好与事实相反(实测时读出来自相矛盾)。
1177
1241
  const resumed = sessionId === knownSessionId;
@@ -1205,6 +1269,7 @@ function handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadS
1205
1269
  for (const item of queued.slice(drained)) {
1206
1270
  if (item.rec) {
1207
1271
  item.rec.status = "queued-lost";
1272
+ onHistoryChange?.();
1208
1273
  item.rec.routeDecision = `会话 ${key} 建好后已不可注入(会话可能已结束)`;
1209
1274
  }
1210
1275
  }
@@ -1214,6 +1279,7 @@ function handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadS
1214
1279
  if (key) pendingByConv.delete(key);
1215
1280
  if (rec) {
1216
1281
  rec.status = "dispatch-failed";
1282
+ onHistoryChange?.();
1217
1283
  // 同上:原因必须随任务记录一起能被远端读到
1218
1284
  rec.dispatchError = String(err?.message ?? err);
1219
1285
  rec.routeDecision = `${key ? `新建会话(会话键 ${key})` : "新建会话(无会话键,一次性任务)"} → 失败`;
@@ -1489,7 +1555,7 @@ async function peerFetchEndpoint(ep, url, opts = {}) {
1489
1555
 
1490
1556
  // ───────────────────────── 对端 HTTP 服务 ─────────────────────────
1491
1557
 
1492
- function startPeerServer(ctx, { config, discovery, inbound, log, warn, waker, threadState, capFor, capOverrides, throttled }) {
1558
+ function startPeerServer(ctx, { config, discovery, inbound, log, warn, waker, threadState, capFor, capOverrides, throttled, onHistoryChange }) {
1493
1559
  const send = (res, code, payload) => {
1494
1560
  const body = Buffer.from(JSON.stringify(payload), "utf8");
1495
1561
  res.writeHead(code, { "Content-Type": "application/json; charset=utf-8", "Content-Length": body.length });
@@ -1554,12 +1620,13 @@ function startPeerServer(ctx, { config, discovery, inbound, log, warn, waker, th
1554
1620
  const duplicate = inbound.some((t) => t.id === task.id);
1555
1621
  if (!duplicate) {
1556
1622
  inbound.push(task);
1623
+ onHistoryChange?.();
1557
1624
  if (inbound.length > MAX_HISTORY) inbound.shift();
1558
1625
  }
1559
1626
  log(`收到任务 ${task.id} 来自 ${task.from}${duplicate ? "(重复,忽略)" : ""}`);
1560
1627
  if (!duplicate) {
1561
1628
  try {
1562
- handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadState, capFor, throttled);
1629
+ handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadState, capFor, throttled, onHistoryChange);
1563
1630
  } catch (err) {
1564
1631
  warn(`处理入站任务异常: ${err?.message ?? err}`);
1565
1632
  }
@@ -1618,7 +1685,7 @@ function readJson(req) {
1618
1685
 
1619
1686
  // ───────────────────────── agent 工具 ─────────────────────────
1620
1687
 
1621
- function registerTools(ctx, { discovery, config, inbound, outbound, log, warn, threadState }) {
1688
+ function registerTools(ctx, { discovery, config, inbound, outbound, log, warn, threadState, onHistoryChange }) {
1622
1689
  const text = (v) => [{ type: "text", text: v }];
1623
1690
 
1624
1691
  ctx.tools.register(
@@ -1763,6 +1830,7 @@ function registerTools(ctx, { discovery, config, inbound, outbound, log, warn, t
1763
1830
  });
1764
1831
  const body = await res.json().catch(() => ({}));
1765
1832
  outbound.push({ ...payload, toMachine: target.machine, at: new Date().toISOString(), ok: res.ok, status: res.status });
1833
+ onHistoryChange?.();
1766
1834
  if (outbound.length > MAX_HISTORY) outbound.shift();
1767
1835
 
1768
1836
  if (!res.ok) {
@@ -1777,6 +1845,7 @@ function registerTools(ctx, { discovery, config, inbound, outbound, log, warn, t
1777
1845
  );
1778
1846
  } catch (err) {
1779
1847
  outbound.push({ ...payload, toMachine: target.machine, at: new Date().toISOString(), ok: false, error: String(err?.message ?? err) });
1848
+ onHistoryChange?.();
1780
1849
  return `派发失败:${err?.name === "TimeoutError" ? "超时" : err?.message ?? err}`;
1781
1850
  }
1782
1851
  },
@@ -1803,7 +1872,7 @@ function registerTools(ctx, { discovery, config, inbound, outbound, log, warn, t
1803
1872
 
1804
1873
  // ───────────────────────── UI 接口(本地回环) ─────────────────────────
1805
1874
 
1806
- function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound, log, warn, threadState, capFor, capOverrides, throttled, waker }) {
1875
+ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound, log, warn, threadState, capFor, capOverrides, throttled, waker, onHistoryChange }) {
1807
1876
  const send = (res, code, payload) => {
1808
1877
  const body = Buffer.from(JSON.stringify(payload), "utf8");
1809
1878
  res.writeHead(code, { "Content-Type": "application/json; charset=utf-8", "Content-Length": body.length });
@@ -1979,7 +2048,7 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
1979
2048
  throttled.delete(thread);
1980
2049
  if (task) {
1981
2050
  log(`用户将 thread "${thread}" 上限提高到 ${next},放行最新任务 ${lastId}`);
1982
- handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadState, capFor, throttled);
2051
+ handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadState, capFor, throttled, onHistoryChange);
1983
2052
  } else {
1984
2053
  log(`用户将 thread "${thread}" 上限提高到 ${next}(未找到可重放的任务)`);
1985
2054
  }
@@ -2218,6 +2287,7 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
2218
2287
  });
2219
2288
  const rb = await r.json().catch(() => ({}));
2220
2289
  outbound.push({ ...payload, toMachine: target.machine, at: new Date().toISOString(), ok: r.ok, status: r.status });
2290
+ onHistoryChange?.();
2221
2291
  if (outbound.length > MAX_HISTORY) outbound.shift();
2222
2292
  return send(res, r.ok ? 200 : 502, { ok: r.ok, id, error: rb?.error });
2223
2293
  } catch (err) {
package/lib/persist.js ADDED
@@ -0,0 +1,149 @@
1
+ /**
2
+ * 把「内存态」的两样东西落到磁盘,重启后还能看见:
3
+ *
4
+ * 1. 任务记录(收件箱 / 发件箱)—— 原来只是两个数组,重启即清空,
5
+ * 排查"刚才到底派了什么"时只能去翻会话记录。
6
+ * 2. 机器列表 —— 靠组播/扫描重新发现,重启后的头几十秒里页面是空的,
7
+ * 离线机器更是要等下一次扫到才回来。
8
+ *
9
+ * 设计取舍:
10
+ * · **只存展示与恢复所需的最小集**,不存整条内部记录(避免把内部字段固化)。
11
+ * · 任务正文有上限(TASK_TEXT_LIMIT):单个任务最大 256KB,200 条不设限会写出
12
+ * 几十 MB 的文件,而且是每次派发都写。超限截断并留标记,不假装完整。
13
+ * · 写入用「临时文件 + rename」,避免进程在写一半时被杀导致 JSON 半截、
14
+ * 下次启动整个文件读不出来。
15
+ * · 读失败一律当成"没有历史",绝不让恢复流程把插件启动搞挂。
16
+ */
17
+ import { readFileSync, writeFileSync, mkdirSync, existsSync, renameSync } from "node:fs";
18
+ import { join } from "node:path";
19
+ import { APP_TAG } from "./discovery.js";
20
+
21
+ /** 与 index.js 的 MAX_HISTORY 对齐(两边都 200;这里独立常量避免循环依赖)。 */
22
+ export const MAX_RECORDS = 200;
23
+
24
+ /** 单条任务正文的持久化上限。超出截断并打标记。 */
25
+ export const TASK_TEXT_LIMIT = 4000;
26
+
27
+ const tasksFile = (dir) => join(dir, "tasks.json");
28
+ const peersFile = (dir) => join(dir, "peers.json");
29
+
30
+ function atomicWrite(path, text) {
31
+ const tmp = `${path}.tmp`;
32
+ writeFileSync(tmp, text, { mode: 0o600 });
33
+ renameSync(tmp, path); // 同一目录内 rename 是原子的
34
+ }
35
+
36
+ function ensureDir(dir) {
37
+ if (!existsSync(dir)) mkdirSync(dir, { recursive: true, mode: 0o700 });
38
+ }
39
+
40
+ /** 截断过长的任务正文;保持其它字段原样。 */
41
+ export function trimTaskRecord(rec) {
42
+ if (!rec || typeof rec !== "object") return null;
43
+ const out = { ...rec };
44
+ const text = typeof out.task === "string" ? out.task : "";
45
+ if (text.length > TASK_TEXT_LIMIT) {
46
+ out.task = `${text.slice(0, TASK_TEXT_LIMIT)}…(已截断,原文 ${text.length} 字)`;
47
+ out.taskTruncated = true;
48
+ }
49
+ return out;
50
+ }
51
+
52
+ /**
53
+ * 读任务历史。
54
+ * @returns {{inbound: object[], outbound: object[], savedAt: number}}
55
+ */
56
+ export function loadTaskHistory(dir) {
57
+ try {
58
+ const raw = JSON.parse(readFileSync(tasksFile(dir), "utf8"));
59
+ const pick = (v) => (Array.isArray(v) ? v.filter((x) => x && typeof x === "object") : []).slice(-MAX_RECORDS);
60
+ return {
61
+ inbound: pick(raw?.inbound),
62
+ outbound: pick(raw?.outbound),
63
+ savedAt: Number(raw?.savedAt) || 0,
64
+ };
65
+ } catch {
66
+ return { inbound: [], outbound: [], savedAt: 0 };
67
+ }
68
+ }
69
+
70
+ /**
71
+ * 写任务历史(只保留最后 MAX_RECORDS 条)。
72
+ * @returns {boolean} 是否写成功(失败不影响派发)
73
+ */
74
+ export function saveTaskHistory(dir, inbound, outbound) {
75
+ try {
76
+ ensureDir(dir);
77
+ const body = {
78
+ version: 1,
79
+ savedAt: Date.now(),
80
+ inbound: (inbound ?? []).slice(-MAX_RECORDS).map(trimTaskRecord).filter(Boolean),
81
+ outbound: (outbound ?? []).slice(-MAX_RECORDS).map(trimTaskRecord).filter(Boolean),
82
+ };
83
+ atomicWrite(tasksFile(dir), JSON.stringify(body, null, 2));
84
+ return true;
85
+ } catch {
86
+ return false;
87
+ }
88
+ }
89
+
90
+ /**
91
+ * 把 discover.peers() 的投影列表压成可恢复的快照。
92
+ * 只留自述字段 + 端点,能力名片原样带上(它已经被净化过)。
93
+ */
94
+ export function toPeerSnapshot(peers) {
95
+ return (peers ?? [])
96
+ .filter((p) => p && p.id)
97
+ .map((p) => ({
98
+ record: {
99
+ app: APP_TAG,
100
+ id: String(p.id),
101
+ machine: String(p.machine ?? ""),
102
+ hostname: String(p.hostname ?? ""),
103
+ mac: String(p.mac ?? ""),
104
+ os: String(p.os ?? ""),
105
+ user: String(p.user ?? ""),
106
+ profile: String(p.profile ?? ""),
107
+ version: String(p.version ?? ""),
108
+ // 设备级 lastSeen 不在 health 记录里,用端点时间还原;这里给 ts 兜底
109
+ ts: Number(p.ts) || 0,
110
+ port: Number(p.port) || 0,
111
+ host: String(p.host ?? ""),
112
+ capabilities: p.capabilities ?? null,
113
+ },
114
+ endpoints: (Array.isArray(p.endpoints) ? p.endpoints : [])
115
+ .filter((e) => e && e.transport)
116
+ .map((e) => ({
117
+ transport: String(e.transport),
118
+ host: String(e.host ?? ""),
119
+ port: Number(e.port) || 0,
120
+ lastSeen: Number(e.lastSeen) || 0,
121
+ lastOkAt: Number(e.lastOkAt) || 0,
122
+ verified: e.verified === true,
123
+ })),
124
+ }));
125
+ }
126
+
127
+ export function loadPeerSnapshot(dir) {
128
+ try {
129
+ const raw = JSON.parse(readFileSync(peersFile(dir), "utf8"));
130
+ const list = Array.isArray(raw?.peers) ? raw.peers : [];
131
+ return {
132
+ peers: list.filter((p) => p && p.record && typeof p.record.id === "string"),
133
+ savedAt: Number(raw?.savedAt) || 0,
134
+ };
135
+ } catch {
136
+ return { peers: [], savedAt: 0 };
137
+ }
138
+ }
139
+
140
+ export function savePeerSnapshot(dir, peers) {
141
+ try {
142
+ ensureDir(dir);
143
+ const body = { version: 1, savedAt: Date.now(), peers: toPeerSnapshot(peers) };
144
+ atomicWrite(peersFile(dir), JSON.stringify(body, null, 2));
145
+ return true;
146
+ } catch {
147
+ return false;
148
+ }
149
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-plugin-mesh",
3
- "version": "0.4.0",
3
+ "version": "0.5.0",
4
4
  "type": "module",
5
5
  "description": "DSH Mesh:局域网自动发现同网段的 DSH 实例、显示每台机器上报的能力,并双向派发任务;可用内置的用户态 Tailscale 节点跨互联网组网。Discovers other DSH instances on the LAN, shows the capabilities each one reports, and dispatches tasks between machines in both directions, with an optional userspace Tailscale node for links across networks.",
6
6
  "license": "MIT",
@@ -61,8 +61,9 @@
61
61
  "selftest:release": "node scripts/_selftest-release-plan.mjs",
62
62
  "selftest:reply": "node --experimental-vm-modules lib/_selftest-reply-route.mjs",
63
63
  "selftest:resume": "node --experimental-vm-modules lib/_selftest-resume.mjs",
64
+ "selftest:persist": "node lib/_selftest-persist.mjs",
64
65
  "selftest:reasoning": "node lib/_selftest-reasoning.mjs",
65
- "test": "npm run check && npm run selftest && npm run selftest:prompt && npm run selftest:pairing && npm run selftest:client && npm run selftest:caps && npm run selftest:release && npm run selftest:reply && npm run selftest:reasoning && npm run selftest:resume",
66
+ "test": "npm run check && npm run selftest && npm run selftest:prompt && npm run selftest:pairing && 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",
66
67
  "check": "node scripts/check-version.mjs && node scripts/check-tdz.mjs && node --check lib/index.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/pairing.js && node --check lib/scan.js && node --check lib/tsnet/download.js && node --check lib/tsnet/manager.js && node --check lib/tsnet/bridge.js && node --check client/client.js && node --check scripts/release-plan.mjs && npm run check:loadable && npm run check:docs",
67
68
  "build:sidecar": "bash scripts/build-sidecar.sh",
68
69
  "verify:mirror": "node scripts/verify-lan-mirror.mjs",