dsh-plugin-mesh 0.3.36 → 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/README.md +2 -0
- package/client/client.js +39 -4
- package/lib/_selftest-client.mjs +52 -0
- package/lib/_selftest-persist.mjs +195 -0
- package/lib/_selftest-reasoning.mjs +5 -1
- package/lib/_selftest-resume.mjs +199 -0
- package/lib/discovery.js +149 -4
- package/lib/index.js +176 -14
- package/lib/persist.js +149 -0
- package/package.json +4 -2
package/README.md
CHANGED
|
@@ -857,6 +857,8 @@ node lib/_selftest-discovery.mjs alpha 45900 9000 # 两个进程同时跑可
|
|
|
857
857
|
| 提交信息怎么写、PR 会被哪些门禁检查 | [`CONTRIBUTING.md`](CONTRIBUTING.md) |
|
|
858
858
|
| 流水线怎么运作、失败了怎么重跑、怎么撤回 | [`docs/RELEASE.md`](docs/RELEASE.md) |
|
|
859
859
|
| 改代码前必须知道的硬约束与坑 | [`AGENTS.md`](AGENTS.md) |
|
|
860
|
+
| 版本升级 / 新功能后的回归测试怎么跑 | [`docs/TEST-CASES.md`](docs/TEST-CASES.md) |
|
|
861
|
+
| 功能需求、架构逻辑、多版本通信协议、跨 IDE 实现契约 | [`docs/PLUGIN-SPEC.md`](docs/PLUGIN-SPEC.md) |
|
|
860
862
|
|
|
861
863
|
本地预演"如果现在合并会发生什么"(不联网、不改文件):
|
|
862
864
|
|
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
|
|
677
|
+
orderEndpointsForDisplay(peer).map((ep) => {
|
|
648
678
|
const cooling = !!(ep.downUntil && Date.now() < ep.downUntil);
|
|
649
679
|
const unverified = ep.verified === false;
|
|
650
|
-
|
|
651
|
-
|
|
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
|
},
|
package/lib/_selftest-client.mjs
CHANGED
|
@@ -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
|
+
}
|
|
@@ -5,7 +5,11 @@ import vm from "node:vm";
|
|
|
5
5
|
|
|
6
6
|
const source = readFileSync(new URL("./index.js", import.meta.url), "utf8");
|
|
7
7
|
const start = source.indexOf("async function wakeAgent(");
|
|
8
|
-
|
|
8
|
+
// 切到**下一个顶层函数**为止,而不是写死 resolveWorkspace:
|
|
9
|
+
// 之前写死它,一旦在两者之间插入新函数,切片就变成「多个函数声明套在括号里」,
|
|
10
|
+
// 直接 SyntaxError(加会话恢复时就这么炸过一次)。
|
|
11
|
+
const nextFn = /\n(?:async )?function [A-Za-z_$]/.exec(source.slice(start + 1));
|
|
12
|
+
const end = nextFn ? start + 1 + nextFn.index : -1;
|
|
9
13
|
assert.ok(start >= 0 && end > start, "wakeAgent source boundaries must exist");
|
|
10
14
|
const wake = vm.runInNewContext(`(${source.slice(start, end)})`, {
|
|
11
15
|
randomUUID: () => "test-id",
|
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
/** 会话恢复路径的单元检查:注入前能否把「已结束但记录还在」的会话接回来。
|
|
2
|
+
*
|
|
3
|
+
* 背景:`liveSession()` 查的是 DSH 内存里的 agent 注册表。重启 DSH 之后注册表是空的,
|
|
4
|
+
* 但磁盘上的对话记录完好无损。原实现直接新建会话,于是每重启一次所有跨机对话线
|
|
5
|
+
* 都静默断开。这里验证新增的 `wakeAgentOrResume` 会先尝试 `agents.resume`。
|
|
6
|
+
*
|
|
7
|
+
* 不联网、不装 DSH:index.js 用 vm 加载,import 被替换成最小 mock。
|
|
8
|
+
*/
|
|
9
|
+
import assert from "node:assert/strict";
|
|
10
|
+
import vm from "node:vm";
|
|
11
|
+
import { readFileSync, mkdtempSync, mkdirSync, writeFileSync, rmSync } from "node:fs";
|
|
12
|
+
import { tmpdir } from "node:os";
|
|
13
|
+
import { join } from "node:path";
|
|
14
|
+
import { conversationKey } from "./conversation.js";
|
|
15
|
+
|
|
16
|
+
const root = mkdtempSync(join(tmpdir(), "mesh-resume-test-"));
|
|
17
|
+
const entryUrl = new URL("./index.js", import.meta.url);
|
|
18
|
+
const cleanupPaths = [];
|
|
19
|
+
const noop = () => {};
|
|
20
|
+
|
|
21
|
+
const TASK_TEXT = "这张会话在重启前处理过的工作,现在要对端回传结果,测试请勿联网执行任何命令。";
|
|
22
|
+
|
|
23
|
+
async function loadModule() {
|
|
24
|
+
let source = readFileSync(entryUrl, "utf8");
|
|
25
|
+
// 暴露内部函数(这些不是公开 API,只给测试用)
|
|
26
|
+
source += "\nexport { handleInboundTask };";
|
|
27
|
+
const schema = new Proxy(() => schema, { get: () => schema });
|
|
28
|
+
const mocks = {
|
|
29
|
+
"@deepseek-ai/schemastery": { default: schema },
|
|
30
|
+
"@deepseek-ai/dsh-brand": { brandString: (value) => value },
|
|
31
|
+
"@deepseek-ai/dsh-tools": { defineTool: (tool) => tool },
|
|
32
|
+
"@deepseek-ai/dsh-llm": { createUserMessage: (message) => message },
|
|
33
|
+
};
|
|
34
|
+
const context = vm.createContext({ console, Buffer, URL, AbortSignal, setTimeout, clearTimeout, setInterval, clearInterval, process });
|
|
35
|
+
const module = new vm.SourceTextModule(source, {
|
|
36
|
+
context,
|
|
37
|
+
identifier: entryUrl.href,
|
|
38
|
+
initializeImportMeta: (meta) => { meta.url = entryUrl.href; },
|
|
39
|
+
});
|
|
40
|
+
await module.link(async (specifier) => {
|
|
41
|
+
const exports = mocks[specifier] ?? (await import(specifier.startsWith(".") ? new URL(specifier, entryUrl).href : specifier));
|
|
42
|
+
return new vm.SyntheticModule(Object.keys(exports), function () {
|
|
43
|
+
for (const key of Object.keys(exports)) this.setExport(key, exports[key]);
|
|
44
|
+
}, { context });
|
|
45
|
+
});
|
|
46
|
+
await module.evaluate();
|
|
47
|
+
return module.namespace;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** 跑一次入站任务,返回本次尝试的结果。 */
|
|
51
|
+
async function runInbound(ns, opts = {}) {
|
|
52
|
+
const home = mkdtempSync(join(root, "home-"));
|
|
53
|
+
mkdirSync(join(home, "mesh"), { recursive: true });
|
|
54
|
+
writeFileSync(join(home, "mesh", "state.json"), JSON.stringify({ secret: "s" }));
|
|
55
|
+
|
|
56
|
+
const messages = [];
|
|
57
|
+
const resumedIds = [];
|
|
58
|
+
const createdIds = [];
|
|
59
|
+
const warnings = [];
|
|
60
|
+
|
|
61
|
+
const makeHandle = (sessionId) => ({
|
|
62
|
+
agent: { session: { id: sessionId }, followup: (m) => messages.push(m) },
|
|
63
|
+
dispose: async () => {},
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
const agentApi = {
|
|
67
|
+
resume: opts.withResume === false ? undefined : async ({ resumeSessionId }) => {
|
|
68
|
+
resumedIds.push(resumeSessionId);
|
|
69
|
+
if (opts.resumeFails) throw new Error("session log missing");
|
|
70
|
+
return makeHandle(resumeSessionId);
|
|
71
|
+
},
|
|
72
|
+
create: async ({ sessionId }) => {
|
|
73
|
+
createdIds.push(sessionId);
|
|
74
|
+
return makeHandle(sessionId);
|
|
75
|
+
},
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
const liveAgents = new Map();
|
|
79
|
+
const ctx = {
|
|
80
|
+
get: (name) => (name === "agents" ? { get: (id) => liveAgents.get(id), ...agentApi } : undefined),
|
|
81
|
+
effect: () => () => {},
|
|
82
|
+
};
|
|
83
|
+
const services = {
|
|
84
|
+
agentPresets: { resolve: async (id) => ({ id }), standingKeyFor: async () => {}, mount: async () => {} },
|
|
85
|
+
workspaceRegistry: {
|
|
86
|
+
create: async () => ({
|
|
87
|
+
path: home,
|
|
88
|
+
attachSession: async () => {},
|
|
89
|
+
detachSession: async () => {},
|
|
90
|
+
}),
|
|
91
|
+
},
|
|
92
|
+
agentDefaultModel: { currentSelection: () => ({ provider: "p", model: "m", reasoningEffort: "low" }) },
|
|
93
|
+
permissionPresets: { set: () => {} },
|
|
94
|
+
sessionTitle: { rename: () => {} },
|
|
95
|
+
};
|
|
96
|
+
// wakeAgent 通过 waker.ctx 取服务(c.agents.create / c.agents.resume 都在这里)
|
|
97
|
+
const wakerCtx = Object.assign(Object.create(ctx), services, {
|
|
98
|
+
get: ctx.get,
|
|
99
|
+
effect: () => () => {},
|
|
100
|
+
agents: agentApi,
|
|
101
|
+
});
|
|
102
|
+
const waker = { ready: true, ctx: wakerCtx, missing: [] };
|
|
103
|
+
|
|
104
|
+
const threadState = new Map();
|
|
105
|
+
const thread = "重启前的对话";
|
|
106
|
+
const key = conversationKey({ fromMachine: "B", thread });
|
|
107
|
+
if (opts.boundSessionId) threadState.set(key, { sessionId: opts.boundSessionId, wakesAt: [] });
|
|
108
|
+
if (opts.liveSessionId) liveAgents.set(opts.liveSessionId, { followup: noop });
|
|
109
|
+
|
|
110
|
+
const task = {
|
|
111
|
+
id: "t-resume-1",
|
|
112
|
+
from: "B/u",
|
|
113
|
+
fromMachine: "B",
|
|
114
|
+
thread,
|
|
115
|
+
task: TASK_TEXT,
|
|
116
|
+
newSession: opts.newSession === true,
|
|
117
|
+
};
|
|
118
|
+
const inbound = [];
|
|
119
|
+
const config = {
|
|
120
|
+
port: 0,
|
|
121
|
+
requestTimeoutMs: 500,
|
|
122
|
+
minTaskChars: 10,
|
|
123
|
+
maxWakesPerThread: 30,
|
|
124
|
+
threadCooldownMs: 5000,
|
|
125
|
+
threadWindowMs: 3600000,
|
|
126
|
+
agentPreset: "standard",
|
|
127
|
+
permissionPreset: "danger-full-access",
|
|
128
|
+
workspaceRoot: home,
|
|
129
|
+
};
|
|
130
|
+
|
|
131
|
+
await ns.handleInboundTask(
|
|
132
|
+
ctx, task, inbound, config, noop, (m) => warnings.push(String(m)),
|
|
133
|
+
waker, threadState, () => config.maxWakesPerThread, new Map(),
|
|
134
|
+
);
|
|
135
|
+
// 等 wakeAgentOrResume 的 then/catch 落定:出现任一可见副作用即可
|
|
136
|
+
const settled = () => r().messages.length > 0 || r().createdIds.length > 0 || r().resumedIds.length > 0 || r().warnings.length > 0;
|
|
137
|
+
function r() { return { messages, createdIds, resumedIds, warnings }; }
|
|
138
|
+
for (let i = 0; i < 200 && !settled(); i += 1) {
|
|
139
|
+
await new Promise((res) => setTimeout(res, 10));
|
|
140
|
+
}
|
|
141
|
+
await new Promise((res) => setTimeout(res, 60));
|
|
142
|
+
cleanupPaths.push(home);
|
|
143
|
+
return { messages, resumedIds, createdIds, warnings, threadState, key, inbound, home };
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
const ns = await loadModule();
|
|
147
|
+
|
|
148
|
+
try {
|
|
149
|
+
// 1) 绑定的会话不在注册表里,但能恢复 → 必须恢复,且不新建
|
|
150
|
+
{
|
|
151
|
+
const r = await runInbound(ns, { boundSessionId: "dead-session" });
|
|
152
|
+
assert.deepEqual(r.resumedIds, ["dead-session"], "应当按绑定 id 恢复旧会话");
|
|
153
|
+
assert.equal(r.createdIds.length, 0, "能恢复时不该新建会话");
|
|
154
|
+
assert.equal(r.messages.length, 1, "恢复后要把任务提示注入进去");
|
|
155
|
+
assert.equal(r.threadState.get(r.key).sessionId, "dead-session", "绑定仍是那个会话");
|
|
156
|
+
console.log("✓ 已结束的会话被恢复:注入原会话,未新建");
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// 2) 恢复失败 → 退回新建,且不能丢消息
|
|
160
|
+
{
|
|
161
|
+
const r = await runInbound(ns, { boundSessionId: "gone-session", resumeFails: true });
|
|
162
|
+
assert.deepEqual(r.resumedIds, ["gone-session"], "先尝试恢复");
|
|
163
|
+
assert.equal(r.createdIds.length, 1, "恢复失败后应新建会话");
|
|
164
|
+
assert.equal(r.messages.length, 1, "任务提示仍要注入(不能丢回传)");
|
|
165
|
+
assert.ok(r.warnings.some((w) => w.includes("恢复会话")), "恢复失败要留下 warn 原因");
|
|
166
|
+
assert.equal(r.threadState.get(r.key).sessionId, r.createdIds[0], "绑定改到新会话");
|
|
167
|
+
console.log("✓ 恢复失败时退回新建:消息不丢,原因有记录");
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
// 3) 旧版 DSH 没有 agents.resume → 直接新建,不抛错
|
|
171
|
+
{
|
|
172
|
+
const r = await runInbound(ns, { boundSessionId: "old-dsh", withResume: false });
|
|
173
|
+
assert.equal(r.createdIds.length, 1, "没有 resume 时应新建");
|
|
174
|
+
assert.equal(r.messages.length, 1);
|
|
175
|
+
assert.ok(r.warnings.some((w) => w.includes("没有 resume")), "要说清是版本能力缺失");
|
|
176
|
+
console.log("✓ 没有 resume API 时优雅降级为新建");
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// 4) 发送方显式要求新会话 → 不许恢复
|
|
180
|
+
{
|
|
181
|
+
const r = await runInbound(ns, { boundSessionId: "dead-session", newSession: true });
|
|
182
|
+
assert.equal(r.resumedIds.length, 0, "newSession=true 时不该恢复");
|
|
183
|
+
assert.equal(r.createdIds.length, 1, "应新建会话");
|
|
184
|
+
console.log("✓ newSession=true 时不恢复");
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// 5) 会话仍活跃 → 走注入路径,既不恢复也不新建
|
|
188
|
+
{
|
|
189
|
+
const r = await runInbound(ns, { boundSessionId: "live-1", liveSessionId: "live-1" });
|
|
190
|
+
assert.equal(r.resumedIds.length, 0, "活着就直接注入");
|
|
191
|
+
assert.equal(r.createdIds.length, 0);
|
|
192
|
+
console.log("✓ 会话仍活跃时直接注入,不触发恢复");
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
console.log("\n全部通过");
|
|
196
|
+
} finally {
|
|
197
|
+
for (const p of cleanupPaths) rmSync(p, { recursive: true, force: true });
|
|
198
|
+
rmSync(root, { recursive: true, force: true });
|
|
199
|
+
}
|
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
|
-
|
|
387
|
-
|
|
388
|
-
|
|
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
|
-
|
|
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.
|
|
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();
|
|
@@ -826,6 +884,89 @@ async function wakeAgent(waker, config, task, warn = () => {}) {
|
|
|
826
884
|
return sessionId;
|
|
827
885
|
}
|
|
828
886
|
|
|
887
|
+
/**
|
|
888
|
+
* 把一条入站任务喂进一个**已存在但已结束**的会话,而不是新建一个。
|
|
889
|
+
*
|
|
890
|
+
* 为什么需要:`liveSession()` 看的是 DSH 内存里的 agent 注册表,重启 DSH 或
|
|
891
|
+
* 会话空闲被回收之后,注册表里就没有它了 —— 哪怕磁盘上的对话记录完好无损。
|
|
892
|
+
* 原来的做法是直接 `agents.create` 一个全新的 `mesh-<uuid>`,于是每重启一次,
|
|
893
|
+
* 所有跨机对话线都在下一次回传时静默断开(上下文还在旧会话里,新会话从零开始)。
|
|
894
|
+
*
|
|
895
|
+
* DSH 本身支持按 id 从持久化日志恢复会话:`agents.resume({ resumeSessionId })`。
|
|
896
|
+
* 这里就用它把旧会话接回来再注入。
|
|
897
|
+
*
|
|
898
|
+
* 失败(版本太旧没有 resume、会话记录被删、没配 sessionPersistence)时返回 null,
|
|
899
|
+
* 由调用方回退到新建会话 —— 恢复是**尽力而为**,不能因为它挂了就让回传丢失。
|
|
900
|
+
*/
|
|
901
|
+
async function resumeAgent(waker, config, task, sessionId, warn = () => {}) {
|
|
902
|
+
const c = waker.ctx;
|
|
903
|
+
if (typeof c.agents?.resume !== "function") {
|
|
904
|
+
warn("本机 DSH 的 agents 没有 resume,无法恢复已结束的会话;将新建会话");
|
|
905
|
+
return null;
|
|
906
|
+
}
|
|
907
|
+
const preset = await c.agentPresets.resolve(config.agentPreset);
|
|
908
|
+
if (typeof c.agentPresets.standingKeyFor === "function") {
|
|
909
|
+
await c.agentPresets.standingKeyFor(preset.id);
|
|
910
|
+
}
|
|
911
|
+
const selection = c.agentDefaultModel.currentSelection();
|
|
912
|
+
const handle = await c.agents.resume({
|
|
913
|
+
resumeSessionId: sessionId,
|
|
914
|
+
agentOptions: {
|
|
915
|
+
provider: selection.provider,
|
|
916
|
+
model: selection.model,
|
|
917
|
+
...(selection.reasoningEffort === undefined ? {} : { reasoningEffort: selection.reasoningEffort }),
|
|
918
|
+
},
|
|
919
|
+
setup: async (agentCtx) => {
|
|
920
|
+
await c.agentPresets.mount(agentCtx, preset.id);
|
|
921
|
+
},
|
|
922
|
+
});
|
|
923
|
+
try {
|
|
924
|
+
c.permissionPresets.set(handle.agent.session, permissionPresetFor(config, task));
|
|
925
|
+
// 恢复的会话**不重命名**:原标题承载着"这场对话原来是什么",改掉就丢了这段历史。
|
|
926
|
+
handle.agent.followup(
|
|
927
|
+
createUserMessage({
|
|
928
|
+
content: [{ type: "text", text: buildPrompt(task) }],
|
|
929
|
+
source: {
|
|
930
|
+
kind: "webhook",
|
|
931
|
+
provider: RULE_KIND,
|
|
932
|
+
source: task.from,
|
|
933
|
+
deliveryId: task.id,
|
|
934
|
+
ruleId: RULE_ID,
|
|
935
|
+
form: "notice",
|
|
936
|
+
summary: `mesh task from ${task.from} (resumed)`,
|
|
937
|
+
},
|
|
938
|
+
}),
|
|
939
|
+
);
|
|
940
|
+
} catch (err) {
|
|
941
|
+
try {
|
|
942
|
+
await handle.dispose();
|
|
943
|
+
} catch {
|
|
944
|
+
/* 回滚失败不覆盖原始错误 */
|
|
945
|
+
}
|
|
946
|
+
throw err;
|
|
947
|
+
}
|
|
948
|
+
return sessionId;
|
|
949
|
+
}
|
|
950
|
+
|
|
951
|
+
/**
|
|
952
|
+
* 唤醒会话:能恢复就恢复,恢复不了才新建。
|
|
953
|
+
*
|
|
954
|
+
* 优先级是「接续旧上下文」高于「开一个干净的新会话」—— 后者会让用户丢掉
|
|
955
|
+
* 整场对话的记忆,而这个 plugin 的全部价值就在于把上下文带过去。
|
|
956
|
+
*/
|
|
957
|
+
async function wakeAgentOrResume(waker, config, task, resumeSessionId, warn = () => {}) {
|
|
958
|
+
if (resumeSessionId && task?.newSession !== true) {
|
|
959
|
+
try {
|
|
960
|
+
const resumed = await resumeAgent(waker, config, task, resumeSessionId, warn);
|
|
961
|
+
if (resumed) return resumed;
|
|
962
|
+
} catch (err) {
|
|
963
|
+
// 恢复失败不该让这条回传丢掉:退回新建,并把原因记下来。
|
|
964
|
+
warn(`恢复会话 ${String(resumeSessionId).slice(0, 20)}… 失败,改为新建:${err?.message ?? err}`);
|
|
965
|
+
}
|
|
966
|
+
}
|
|
967
|
+
return wakeAgent(waker, config, task, warn);
|
|
968
|
+
}
|
|
969
|
+
|
|
829
970
|
function resolveWorkspace(config) {
|
|
830
971
|
if (config.workspaceRoot && isAbsolute(config.workspaceRoot)) return config.workspaceRoot;
|
|
831
972
|
return resolve(homedir());
|
|
@@ -912,7 +1053,7 @@ function classifyInbound(task, threadState, config, now, capFor, { canInject = f
|
|
|
912
1053
|
* 收到对端任务:会话键命中且会话仍活跃就复用,否则新建,
|
|
913
1054
|
* 最后才新建会话。复用是为了避免"每条消息都从零重新探索上下文"。
|
|
914
1055
|
*/
|
|
915
|
-
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) {
|
|
916
1057
|
const rec = inbound.find((t) => t.id === task.id);
|
|
917
1058
|
// 记下"回信地址",与"本机用哪个会话处理"是两件事。对端可以 GET
|
|
918
1059
|
// /mesh/v1/tasks 读到它,调试时能看清结果该送回哪里。
|
|
@@ -945,6 +1086,7 @@ function handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadS
|
|
|
945
1086
|
if (!verdict.wake) {
|
|
946
1087
|
if (rec) {
|
|
947
1088
|
rec.status = verdict.kind === "cap" ? "throttled" : "noted-only";
|
|
1089
|
+
onHistoryChange?.();
|
|
948
1090
|
// 原因必须写出来。之前这里什么都不记,于是 status='noted-only' 时
|
|
949
1091
|
// routeDecision 是 None —— 看不出为什么没处理,又回到"只能靠猜"的老路
|
|
950
1092
|
rec.routeDecision = `未唤醒:${verdict.reason}`;
|
|
@@ -1009,6 +1151,7 @@ function handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadS
|
|
|
1009
1151
|
);
|
|
1010
1152
|
if (targetRec) {
|
|
1011
1153
|
targetRec.status = status;
|
|
1154
|
+
onHistoryChange?.();
|
|
1012
1155
|
// 决策留痕:对端可以 GET /mesh/v1/tasks 读到"为什么这么路由"。
|
|
1013
1156
|
// 没有这个,出问题时只能靠猜(dispatchError 那次就是这么加的)。
|
|
1014
1157
|
targetRec.routeDecision = `${label} ${sessionId}(会话键 ${conversationKey(targetTask) || "无"})`;
|
|
@@ -1045,6 +1188,7 @@ function handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadS
|
|
|
1045
1188
|
if (!waker?.ready) {
|
|
1046
1189
|
if (rec) {
|
|
1047
1190
|
rec.status = "stored-only";
|
|
1191
|
+
onHistoryChange?.();
|
|
1048
1192
|
rec.routeDecision = key ? `无法新建会话(会话键 ${key})` : "无法新建会话(无会话键)";
|
|
1049
1193
|
// 记下原因,让对端能远程读到(GET /mesh/v1/tasks)。一台没有界面或
|
|
1050
1194
|
// 日志访问权的机器(比如 Android/Termux)出问题,否则只能靠猜。
|
|
@@ -1065,6 +1209,7 @@ function handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadS
|
|
|
1065
1209
|
// 背压:明确回"忙",而不是无脑排队让对方以为已受理
|
|
1066
1210
|
if (rec) {
|
|
1067
1211
|
rec.status = "busy";
|
|
1212
|
+
onHistoryChange?.();
|
|
1068
1213
|
rec.routeDecision = `会话 ${key} 积压 ${pending.length} 条(上限 ${MAX_PENDING_PER_CONV}),已背压`;
|
|
1069
1214
|
}
|
|
1070
1215
|
warn(`任务 ${task.id} 被背压:会话 ${key} 积压已达上限 ${MAX_PENDING_PER_CONV}`);
|
|
@@ -1073,6 +1218,7 @@ function handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadS
|
|
|
1073
1218
|
pending.push({ task, rec });
|
|
1074
1219
|
if (rec) {
|
|
1075
1220
|
rec.status = "queued-for-session";
|
|
1221
|
+
onHistoryChange?.();
|
|
1076
1222
|
rec.routeDecision = `会话 ${key} 正在建会话,已排队(队内第 ${pending.length} 条)`;
|
|
1077
1223
|
}
|
|
1078
1224
|
log(`任务 ${task.id} 排队等待会话 ${key} 建立`);
|
|
@@ -1082,14 +1228,24 @@ function handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadS
|
|
|
1082
1228
|
}
|
|
1083
1229
|
|
|
1084
1230
|
noteWake();
|
|
1085
|
-
|
|
1231
|
+
// 走到这里说明「能注入」不成立。若这个键绑过会话,先试着把它**恢复**回来
|
|
1232
|
+
// (重启 DSH / 会话被回收后,记录还在磁盘,注册表里却没有了),
|
|
1233
|
+
// 恢复不了再新建 —— 见 wakeAgentOrResume。
|
|
1234
|
+
wakeAgentOrResume(waker, config, task, knownSessionId, warn)
|
|
1086
1235
|
.then((sessionId) => {
|
|
1087
1236
|
if (rec) {
|
|
1088
1237
|
rec.status = "dispatched";
|
|
1238
|
+
onHistoryChange?.();
|
|
1239
|
+
// 三分支文案要互斥:恢复成功时不能再挂「首次出现,或原会话已结束」——
|
|
1240
|
+
// 那句话正好与事实相反(实测时读出来自相矛盾)。
|
|
1241
|
+
const resumed = sessionId === knownSessionId;
|
|
1242
|
+
const why = resumed
|
|
1243
|
+
? "重启或会话被回收后接回原上下文"
|
|
1244
|
+
: task.newSession === true
|
|
1245
|
+
? "发送方显式要求新会话"
|
|
1246
|
+
: "首次出现,或原会话已结束";
|
|
1089
1247
|
rec.routeDecision = key
|
|
1090
|
-
?
|
|
1091
|
-
task.newSession === true ? "发送方显式要求新会话" : "首次出现,或原会话已结束"
|
|
1092
|
-
})`
|
|
1248
|
+
? `${resumed ? "恢复了已结束的会话" : "新建会话"}并绑定会话键 ${key}(${why})`
|
|
1093
1249
|
: "新建会话(无会话键,一次性任务,用完不绑定)";
|
|
1094
1250
|
}
|
|
1095
1251
|
if (key) {
|
|
@@ -1113,6 +1269,7 @@ function handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadS
|
|
|
1113
1269
|
for (const item of queued.slice(drained)) {
|
|
1114
1270
|
if (item.rec) {
|
|
1115
1271
|
item.rec.status = "queued-lost";
|
|
1272
|
+
onHistoryChange?.();
|
|
1116
1273
|
item.rec.routeDecision = `会话 ${key} 建好后已不可注入(会话可能已结束)`;
|
|
1117
1274
|
}
|
|
1118
1275
|
}
|
|
@@ -1122,6 +1279,7 @@ function handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadS
|
|
|
1122
1279
|
if (key) pendingByConv.delete(key);
|
|
1123
1280
|
if (rec) {
|
|
1124
1281
|
rec.status = "dispatch-failed";
|
|
1282
|
+
onHistoryChange?.();
|
|
1125
1283
|
// 同上:原因必须随任务记录一起能被远端读到
|
|
1126
1284
|
rec.dispatchError = String(err?.message ?? err);
|
|
1127
1285
|
rec.routeDecision = `${key ? `新建会话(会话键 ${key})` : "新建会话(无会话键,一次性任务)"} → 失败`;
|
|
@@ -1397,7 +1555,7 @@ async function peerFetchEndpoint(ep, url, opts = {}) {
|
|
|
1397
1555
|
|
|
1398
1556
|
// ───────────────────────── 对端 HTTP 服务 ─────────────────────────
|
|
1399
1557
|
|
|
1400
|
-
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 }) {
|
|
1401
1559
|
const send = (res, code, payload) => {
|
|
1402
1560
|
const body = Buffer.from(JSON.stringify(payload), "utf8");
|
|
1403
1561
|
res.writeHead(code, { "Content-Type": "application/json; charset=utf-8", "Content-Length": body.length });
|
|
@@ -1462,12 +1620,13 @@ function startPeerServer(ctx, { config, discovery, inbound, log, warn, waker, th
|
|
|
1462
1620
|
const duplicate = inbound.some((t) => t.id === task.id);
|
|
1463
1621
|
if (!duplicate) {
|
|
1464
1622
|
inbound.push(task);
|
|
1623
|
+
onHistoryChange?.();
|
|
1465
1624
|
if (inbound.length > MAX_HISTORY) inbound.shift();
|
|
1466
1625
|
}
|
|
1467
1626
|
log(`收到任务 ${task.id} 来自 ${task.from}${duplicate ? "(重复,忽略)" : ""}`);
|
|
1468
1627
|
if (!duplicate) {
|
|
1469
1628
|
try {
|
|
1470
|
-
handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadState, capFor, throttled);
|
|
1629
|
+
handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadState, capFor, throttled, onHistoryChange);
|
|
1471
1630
|
} catch (err) {
|
|
1472
1631
|
warn(`处理入站任务异常: ${err?.message ?? err}`);
|
|
1473
1632
|
}
|
|
@@ -1526,7 +1685,7 @@ function readJson(req) {
|
|
|
1526
1685
|
|
|
1527
1686
|
// ───────────────────────── agent 工具 ─────────────────────────
|
|
1528
1687
|
|
|
1529
|
-
function registerTools(ctx, { discovery, config, inbound, outbound, log, warn, threadState }) {
|
|
1688
|
+
function registerTools(ctx, { discovery, config, inbound, outbound, log, warn, threadState, onHistoryChange }) {
|
|
1530
1689
|
const text = (v) => [{ type: "text", text: v }];
|
|
1531
1690
|
|
|
1532
1691
|
ctx.tools.register(
|
|
@@ -1671,6 +1830,7 @@ function registerTools(ctx, { discovery, config, inbound, outbound, log, warn, t
|
|
|
1671
1830
|
});
|
|
1672
1831
|
const body = await res.json().catch(() => ({}));
|
|
1673
1832
|
outbound.push({ ...payload, toMachine: target.machine, at: new Date().toISOString(), ok: res.ok, status: res.status });
|
|
1833
|
+
onHistoryChange?.();
|
|
1674
1834
|
if (outbound.length > MAX_HISTORY) outbound.shift();
|
|
1675
1835
|
|
|
1676
1836
|
if (!res.ok) {
|
|
@@ -1685,6 +1845,7 @@ function registerTools(ctx, { discovery, config, inbound, outbound, log, warn, t
|
|
|
1685
1845
|
);
|
|
1686
1846
|
} catch (err) {
|
|
1687
1847
|
outbound.push({ ...payload, toMachine: target.machine, at: new Date().toISOString(), ok: false, error: String(err?.message ?? err) });
|
|
1848
|
+
onHistoryChange?.();
|
|
1688
1849
|
return `派发失败:${err?.name === "TimeoutError" ? "超时" : err?.message ?? err}`;
|
|
1689
1850
|
}
|
|
1690
1851
|
},
|
|
@@ -1711,7 +1872,7 @@ function registerTools(ctx, { discovery, config, inbound, outbound, log, warn, t
|
|
|
1711
1872
|
|
|
1712
1873
|
// ───────────────────────── UI 接口(本地回环) ─────────────────────────
|
|
1713
1874
|
|
|
1714
|
-
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 }) {
|
|
1715
1876
|
const send = (res, code, payload) => {
|
|
1716
1877
|
const body = Buffer.from(JSON.stringify(payload), "utf8");
|
|
1717
1878
|
res.writeHead(code, { "Content-Type": "application/json; charset=utf-8", "Content-Length": body.length });
|
|
@@ -1887,7 +2048,7 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
|
|
|
1887
2048
|
throttled.delete(thread);
|
|
1888
2049
|
if (task) {
|
|
1889
2050
|
log(`用户将 thread "${thread}" 上限提高到 ${next},放行最新任务 ${lastId}`);
|
|
1890
|
-
handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadState, capFor, throttled);
|
|
2051
|
+
handleInboundTask(ctx, task, inbound, config, log, warn, waker, threadState, capFor, throttled, onHistoryChange);
|
|
1891
2052
|
} else {
|
|
1892
2053
|
log(`用户将 thread "${thread}" 上限提高到 ${next}(未找到可重放的任务)`);
|
|
1893
2054
|
}
|
|
@@ -2126,6 +2287,7 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
|
|
|
2126
2287
|
});
|
|
2127
2288
|
const rb = await r.json().catch(() => ({}));
|
|
2128
2289
|
outbound.push({ ...payload, toMachine: target.machine, at: new Date().toISOString(), ok: r.ok, status: r.status });
|
|
2290
|
+
onHistoryChange?.();
|
|
2129
2291
|
if (outbound.length > MAX_HISTORY) outbound.shift();
|
|
2130
2292
|
return send(res, r.ok ? 200 : 502, { ok: r.ok, id, error: rb?.error });
|
|
2131
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.
|
|
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",
|
|
@@ -60,8 +60,10 @@
|
|
|
60
60
|
"selftest:newsession": "node lib/_selftest-newsession.mjs",
|
|
61
61
|
"selftest:release": "node scripts/_selftest-release-plan.mjs",
|
|
62
62
|
"selftest:reply": "node --experimental-vm-modules lib/_selftest-reply-route.mjs",
|
|
63
|
+
"selftest:resume": "node --experimental-vm-modules lib/_selftest-resume.mjs",
|
|
64
|
+
"selftest:persist": "node lib/_selftest-persist.mjs",
|
|
63
65
|
"selftest:reasoning": "node lib/_selftest-reasoning.mjs",
|
|
64
|
-
"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",
|
|
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",
|
|
65
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",
|
|
66
68
|
"build:sidecar": "bash scripts/build-sidecar.sh",
|
|
67
69
|
"verify:mirror": "node scripts/verify-lan-mirror.mjs",
|