dsh-plugin-mesh 0.5.6 → 0.5.7

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 CHANGED
@@ -689,6 +689,31 @@ TCP/UDP,只放行 HTTP 客户端的代理设置对它无效(实测诊断里
689
689
 
690
690
  ---
691
691
 
692
+ ### 问题反馈与检查更新(主页页头)
693
+
694
+ 两个入口在主页页头右侧,和「专注」「自定义」同一行,**只有一行小字,不占卡片**:
695
+
696
+ **检查更新**
697
+
698
+ - 进主页时静默查一次最新版本;宿主机侧缓存 30 分钟(失败只缓存 1 分钟),
699
+ 点一下「检查更新」立即强查。
700
+ - 有新版本时旁边多出一个「**新版本 vX**」,点它直接复制升级命令(插件目录已按
701
+ 本机实际安装路径填好,与 Release 资产命名一致),装好后**重启 DSH** 才生效。
702
+ - **查不到就说查不到。** 超时 / HTTP 错误 / registry 返回了无法比较的版本号时,
703
+ 旁边会多出一个「检查失败」(悬停可看逐条原因),点一下重试 —— 不会显示成
704
+ 「已是最新」,否则用户会永远升不了级还看不出来。
705
+ - 版本源是 npm registry:`registry.npmjs.org` 优先,`registry.npmmirror.com`
706
+ 兜底,每源 5 秒超时。接口是 `GET /mesh/api/update`(`?force=1` 跳过缓存)。
707
+
708
+ **问题反馈**
709
+
710
+ - 点「问题反馈」在 GitHub 打开新建 Issue 页,标题与正文已预填:正文含版本、系统、
711
+ 发现方式、对端数量与本机名 / 地址 / MAC,**不含**配对码与 tsnet 授权码
712
+ (`buildDiagnostics()` 只挑安全字段)。提交前可以自己删改。
713
+ - GitHub 打不开时,把鼠标停在「问题反馈」上能看到邮件地址
714
+ `geekstartup@163.com`,直接把现场贴过去即可。
715
+
716
+ ---
692
717
 
693
718
  ### 远程面板与 SSH 终端
694
719
 
package/client/client.js CHANGED
@@ -37,6 +37,11 @@ window.__ModuleLoader__.load({
37
37
  const TS_KEYS_URL = "https://console.tailscale.com/admin/settings/keys";
38
38
  const TRANSFER_KEY = "mesh.transfers.v1";
39
39
  const TRANSFER_LIMIT = 50;
40
+ // 更新与反馈都指向同一个 GitHub 仓库;邮件是 GitHub 不通时的退路
41
+ //(作者机器上 git-over-https 到 github.com 常被重置,见 AGENTS.md)。
42
+ const RELEASE_REPO = "peng456/dsh-plugin-mesh";
43
+ const NEW_ISSUE_URL = `https://github.com/${RELEASE_REPO}/issues/new`;
44
+ const FEEDBACK_MAIL = "geekstartup@163.com";
40
45
  let pluginCtx = null;
41
46
 
42
47
  const HOME_PREF_KEY = "mesh.home.v1";
@@ -310,12 +315,7 @@ window.__ModuleLoader__.load({
310
315
  return (r && (r.error || r.message)) || "未知错误";
311
316
  }
312
317
 
313
- async function api(path, body) {
314
- const r = await fetch(API + path, {
315
- method: "POST",
316
- headers: { "content-type": "application/json" },
317
- body: JSON.stringify(body || {}),
318
- });
318
+ async function parseApiResponse(r) {
319
319
  let j = {};
320
320
  try {
321
321
  j = await r.json();
@@ -326,6 +326,24 @@ window.__ModuleLoader__.load({
326
326
  return j;
327
327
  }
328
328
 
329
+ async function api(path, body) {
330
+ const r = await fetch(API + path, {
331
+ method: "POST",
332
+ headers: { "content-type": "application/json" },
333
+ body: JSON.stringify(body || {}),
334
+ });
335
+ return parseApiResponse(r);
336
+ }
337
+
338
+ /** 只读接口走 GET(/mesh/api/update 就是这一类:查一次版本,不改任何状态)。 */
339
+ async function apiGet(path) {
340
+ const r = await fetch(API + path, {
341
+ headers: { accept: "application/json" },
342
+ cache: "no-store",
343
+ });
344
+ return parseApiResponse(r);
345
+ }
346
+
329
347
  async function copyText(text) {
330
348
  try {
331
349
  if (navigator.clipboard && navigator.clipboard.writeText) {
@@ -1692,6 +1710,21 @@ window.__ModuleLoader__.load({
1692
1710
  .mesh-editor-error { margin: 8px 0; font-size: 11.5px; color: var(--mesh-err); }
1693
1711
  .mesh-editor-foot { display: flex; align-items: center; gap: 8px; justify-content: flex-end; margin-top: 18px; flex-wrap: wrap; }
1694
1712
  .mesh-card-text.is-pre { white-space: pre-wrap; }
1713
+ /* 主页页头的轻入口:只有文字,没有边框/底色,和「专注」「自定义」同一行 */
1714
+ .mesh-home-meta { display: inline-flex; align-items: center; gap: 12px; flex-wrap: wrap; }
1715
+ .mesh-meta-link {
1716
+ appearance: none; -webkit-appearance: none;
1717
+ border: 0; background: none; padding: 2px 0; margin: 0;
1718
+ font: inherit; font-size: 11px; line-height: 1.5;
1719
+ color: var(--mesh-muted); cursor: pointer;
1720
+ text-decoration: none; white-space: nowrap;
1721
+ transition: color var(--mesh-dur-fast) ease;
1722
+ }
1723
+ .mesh-meta-link:hover { color: var(--mesh-accent); text-decoration: underline; text-underline-offset: 2px; }
1724
+ .mesh-meta-link:focus-visible { outline: 2px solid var(--mesh-accent); outline-offset: 2px; border-radius: 4px; }
1725
+ .mesh-meta-link:disabled { cursor: default; opacity: .6; }
1726
+ .mesh-meta-link.is-update { color: var(--mesh-accent); font-weight: 600; }
1727
+ .mesh-meta-link.is-warn { color: var(--mesh-warn); }
1695
1728
  .mesh-card-link { color: var(--mesh-accent); text-decoration: none; }
1696
1729
  .mesh-card-link:hover { text-decoration: underline; }
1697
1730
  .mesh-focus .mesh-dot.is-ok::after,
@@ -6298,6 +6331,185 @@ window.__ModuleLoader__.load({
6298
6331
  );
6299
6332
  }
6300
6333
 
6334
+ // ─────────────────────── 主页 · 问题反馈 / 检查更新(轻入口) ───────────────────────
6335
+
6336
+ /**
6337
+ * 主页页头的两个轻入口:只占一行文字,不占卡片。
6338
+ *
6339
+ * 它们最初是两张卡片,真机上看太占首屏 —— 主页要回答的是"谁在线、能不能
6340
+ * 派活",更新和反馈是偶尔用一次的事。于是收成和「专注」「自定义」同一行的
6341
+ * 两个小字,功能一个不少:
6342
+ * · 问题反馈 → GitHub 新建 Issue(标题/正文预填,带诊断、不含 secret);
6343
+ * · 检查更新 → 查一次 registry;有更新时旁边多出「新版本 vX」,点它复制
6344
+ * 升级命令;失败时多出「检查失败」,点它重试。
6345
+ * 失败**不会**显示成"已是最新":徽标、tooltip、toast 说的都是"没查到"。
6346
+ */
6347
+
6348
+ /** 反馈正文:与「诊断」同一份数据,Issue 链接里预填。 */
6349
+ function feedbackBody(state) {
6350
+ return [
6351
+ "### 发生了什么",
6352
+ "",
6353
+ "<!-- 一句话描述:做了什么、期望什么、实际发生了什么 -->",
6354
+ "",
6355
+ "### 复现步骤",
6356
+ "",
6357
+ "1. ",
6358
+ "",
6359
+ "### 诊断信息(可删掉不想公开的行)",
6360
+ "",
6361
+ "```",
6362
+ buildDiagnostics(state),
6363
+ "```",
6364
+ ].join("\n");
6365
+ }
6366
+
6367
+ function feedbackIssueUrl(state) {
6368
+ const self = (state && state.self) || {};
6369
+ const title = `[反馈] Mesh ${self.version || ""}${self.machine ? ` · ${self.machine}` : ""}`.trim();
6370
+ const params = new URLSearchParams({ title, body: feedbackBody(state) });
6371
+ return `${NEW_ISSUE_URL}?${params.toString()}`;
6372
+ }
6373
+
6374
+ /** 问题反馈:一个链接,直接打开预填好的新建 Issue 页。 */
6375
+ function FeedbackLink({ state }) {
6376
+ return h(
6377
+ "a",
6378
+ {
6379
+ className: "mesh-meta-link",
6380
+ href: feedbackIssueUrl(state),
6381
+ target: "_blank",
6382
+ rel: "noreferrer",
6383
+ title: `在 GitHub 提 Issue(打不开可以邮件 ${FEEDBACK_MAIL})`,
6384
+ },
6385
+ "问题反馈",
6386
+ );
6387
+ }
6388
+
6389
+ /** 检查更新的展示层(纯 props):自测可以直接给三种现场,不用联网。 */
6390
+ function UpdateLinkView({ phase, report, onCheck, onCopy }) {
6391
+ const checking = phase === "checking";
6392
+ const failed = !!report && report.ok !== true;
6393
+ const hasUpdate = !!report && report.ok === true && report.hasUpdate === true;
6394
+ const incomparable = !!report && report.ok === true && report.comparable === false;
6395
+ const label = checking ? "检查中…" : "检查更新";
6396
+ const title = failed
6397
+ ? `上次检查失败:${String(report.error || "未知原因")}(点一下重试)`
6398
+ : incomparable
6399
+ ? `当前 v${report.current} 与 registry 返回的 v${report.latest} 无法比较,点一下重新检查`
6400
+ : hasUpdate
6401
+ ? `当前 v${report.current} → 最新 v${report.latest};点一下重新检查`
6402
+ : "查一下有没有新版本";
6403
+ return h(
6404
+ react.Fragment,
6405
+ null,
6406
+ h(
6407
+ "button",
6408
+ {
6409
+ type: "button",
6410
+ className: cls("mesh-meta-link", checking && "is-busy"),
6411
+ onClick: onCheck,
6412
+ disabled: checking,
6413
+ title,
6414
+ "aria-label": "检查更新",
6415
+ "aria-busy": checking || undefined,
6416
+ },
6417
+ label,
6418
+ ),
6419
+ hasUpdate
6420
+ ? h(
6421
+ "button",
6422
+ {
6423
+ type: "button",
6424
+ className: "mesh-meta-link is-update",
6425
+ onClick: () => onCopy(report.upgradeCommand),
6426
+ title: `复制升级命令(v${report.current} → v${report.latest},装好后重启 DSH)`,
6427
+ "aria-label": `复制升级命令到 v${report.latest}`,
6428
+ },
6429
+ `新版本 v${report.latest}`,
6430
+ )
6431
+ : null,
6432
+ failed
6433
+ ? h(
6434
+ "button",
6435
+ { type: "button", className: "mesh-meta-link is-warn", onClick: onCheck, title: report.error },
6436
+ "检查失败",
6437
+ )
6438
+ : null,
6439
+ incomparable
6440
+ ? h(
6441
+ "button",
6442
+ { type: "button", className: "mesh-meta-link is-warn", onClick: onCheck, title },
6443
+ "无法比较",
6444
+ )
6445
+ : null,
6446
+ );
6447
+ }
6448
+
6449
+ /**
6450
+ * 检查更新的容器:进主页**静默**查一次(宿主机缓存 30 分钟),点一下强查。
6451
+ * 静默失败也会在页头留下「检查失败」—— 不点也看得见"没问到",而不是假装无事。
6452
+ */
6453
+ function UpdateLink({ push }) {
6454
+ const [phase, setPhase] = react.useState("idle");
6455
+ const [report, setReport] = react.useState(null);
6456
+ const alive = react.useRef(true);
6457
+ const copyCommand = react.useCallback(
6458
+ async (text) => {
6459
+ if (!text) {
6460
+ push("error", "这次结果里没有升级命令,请先重新检查");
6461
+ return;
6462
+ }
6463
+ const ok = await copyText(text);
6464
+ push(ok ? "success" : "error", ok ? "升级命令已复制:装好后重启 DSH 生效" : "复制失败,请手动选择");
6465
+ },
6466
+ [push],
6467
+ );
6468
+ const run = react.useCallback(
6469
+ async (force, announce) => {
6470
+ setPhase("checking");
6471
+ try {
6472
+ const r = await apiGet(`/update${force ? "?force=1" : ""}`);
6473
+ if (!alive.current) return;
6474
+ const next = r && typeof r === "object" ? r : { ok: false, error: "主机没有返回结果" };
6475
+ setReport(next);
6476
+ setPhase("done");
6477
+ if (!announce) return;
6478
+ if (next.ok !== true) {
6479
+ push("error", `没查到最新版本:${String(next.error || "未知原因")}`);
6480
+ } else if (next.comparable === false) {
6481
+ push("error", `版本号无法比较:v${next.current} vs v${next.latest},请到 Release 页面确认`);
6482
+ } else if (next.hasUpdate) {
6483
+ push("success", `有新版本 v${next.latest}(当前 v${next.current})`, {
6484
+ label: "复制升级命令",
6485
+ onClick: () => copyCommand(next.upgradeCommand),
6486
+ });
6487
+ } else {
6488
+ push("success", `已是最新(v${next.current})`);
6489
+ }
6490
+ } catch (e) {
6491
+ if (!alive.current) return;
6492
+ setReport({ ok: false, error: String((e && e.message) || e) });
6493
+ setPhase("done");
6494
+ if (announce) push("error", `没查到最新版本:${String((e && e.message) || e)}`);
6495
+ }
6496
+ },
6497
+ [push, copyCommand],
6498
+ );
6499
+ react.useEffect(() => {
6500
+ alive.current = true;
6501
+ run(false, false);
6502
+ return () => {
6503
+ alive.current = false;
6504
+ };
6505
+ }, [run]);
6506
+ return h(UpdateLinkView, { phase, report, onCheck: () => run(true, true), onCopy: copyCommand });
6507
+ }
6508
+
6509
+ function HomeMetaLinks({ state, push }) {
6510
+ return h("div", { className: "mesh-home-meta" }, h(FeedbackLink, { state }), h(UpdateLink, { push }));
6511
+ }
6512
+
6301
6513
  // ─────────────────────── 主页 · 派发任务 ───────────────────────
6302
6514
 
6303
6515
  /**
@@ -6913,6 +7125,7 @@ window.__ModuleLoader__.load({
6913
7125
  ? h(Button, { variant: "primary", size: "sm", icon: "check", onClick: () => setEditing(false) }, "完成")
6914
7126
  : h(Button, { variant: "secondary", size: "sm", icon: "edit", onClick: () => setEditing(true) }, "自定义"),
6915
7127
  editing ? h(Button, { variant: "ghost", size: "sm", onClick: onReset }, "恢复默认") : null,
7128
+ h(HomeMetaLinks, { state, push }),
6916
7129
  ),
6917
7130
  ),
6918
7131
  h(
@@ -7960,6 +8173,12 @@ window.__ModuleLoader__.load({
7960
8173
  SwitchBody,
7961
8174
  SwitchRow,
7962
8175
  HomeSwitchBar,
8176
+ HomeMetaLinks,
8177
+ UpdateLink,
8178
+ UpdateLinkView,
8179
+ FeedbackLink,
8180
+ feedbackBody,
8181
+ feedbackIssueUrl,
7963
8182
  };
7964
8183
  return module.exports;
7965
8184
  },
@@ -0,0 +1,267 @@
1
+ /**
2
+ * 「检查更新」的自测:版本比较 + registry 查询失败时的语义。
3
+ *
4
+ * 这一块的**核心断言不是"能查出新版本",而是"查不到时必须说查不到"**。
5
+ * 本项目最贵的教训(AGENTS.md 硬约束 1):探测失败被当成否定事实 ——
6
+ * 这里如果写成「没问到 → 当作已是最新」,用户会永远升不了级,而且看不出来。
7
+ *
8
+ * 全部无网络:fetch 是注入的假实现。
9
+ *
10
+ * node lib/_selftest-update.mjs
11
+ */
12
+ import { strict as assert } from "node:assert";
13
+ import {
14
+ buildUpdateReport,
15
+ buildUpgradeCommand,
16
+ compareVersions,
17
+ fetchLatestVersion,
18
+ parseVersion,
19
+ pluginDirFromUrl,
20
+ updateKind,
21
+ DEFAULT_REGISTRIES,
22
+ } from "./update.js";
23
+
24
+ let passed = 0;
25
+ let failed = 0;
26
+ function test(name, fn) {
27
+ try {
28
+ fn();
29
+ passed += 1;
30
+ console.log(` ✓ ${name}`);
31
+ } catch (err) {
32
+ failed += 1;
33
+ console.log(` ✗ ${name}`);
34
+ console.log(` ${err?.message ?? err}`);
35
+ }
36
+ }
37
+
38
+ async function testAsync(name, fn) {
39
+ try {
40
+ await fn();
41
+ passed += 1;
42
+ console.log(` ✓ ${name}`);
43
+ } catch (err) {
44
+ failed += 1;
45
+ console.log(` ✗ ${name}`);
46
+ console.log(` ${err?.message ?? err}`);
47
+ }
48
+ }
49
+
50
+ const jsonResponse = (body, status = 200) => ({
51
+ ok: status >= 200 && status < 300,
52
+ status,
53
+ json: async () => body,
54
+ });
55
+
56
+ console.log("\n── 版本解析与比较 ──");
57
+
58
+ test("解析 x.y.z / v 前缀 / 预发布 / build 元数据", () => {
59
+ assert.deepEqual(parseVersion("0.5.6"), { major: 0, minor: 5, patch: 6, pre: [] });
60
+ assert.deepEqual(parseVersion("v1.2.3"), { major: 1, minor: 2, patch: 3, pre: [] });
61
+ assert.deepEqual(parseVersion(" 1.2.3-beta.2 "), { major: 1, minor: 2, patch: 3, pre: ["beta", "2"] });
62
+ assert.deepEqual(parseVersion("1.2.3+build.9"), { major: 1, minor: 2, patch: 3, pre: [] });
63
+ });
64
+
65
+ test("不是语义化版本 → null(不能假装能比)", () => {
66
+ for (const bad of ["", "latest", "1.2", "1.2.3.4", "x.y.z", null, undefined, "1.2.x"]) {
67
+ assert.equal(parseVersion(bad), null, JSON.stringify(bad));
68
+ }
69
+ });
70
+
71
+ test("主/次/修订逐段比较", () => {
72
+ assert.equal(compareVersions("0.5.6", "0.5.7"), -1);
73
+ assert.equal(compareVersions("0.6.0", "0.5.9"), 1);
74
+ assert.equal(compareVersions("1.0.0", "1.0.0"), 0);
75
+ assert.equal(compareVersions("v1.0.0", "1.0.0"), 0, "v 前缀不影响比较");
76
+ });
77
+
78
+ test("预发布小于同号正式版;预发布之间按 semver 规则", () => {
79
+ assert.equal(compareVersions("1.0.0-beta", "1.0.0"), -1);
80
+ assert.equal(compareVersions("1.0.0", "1.0.0-rc.1"), 1);
81
+ assert.equal(compareVersions("1.0.0-alpha", "1.0.0-beta"), -1);
82
+ assert.equal(compareVersions("1.0.0-beta.2", "1.0.0-beta.10"), -1, "数字段按数值比");
83
+ assert.equal(compareVersions("1.0.0-beta", "1.0.0-beta.1"), -1, "少的段更小");
84
+ });
85
+
86
+ test("任一侧无法解析 → null,不是 0", () => {
87
+ assert.equal(compareVersions("0.5.6", "latest"), null);
88
+ assert.equal(compareVersions("", "0.5.6"), null);
89
+ });
90
+
91
+ test("更新量级:major / minor / patch / prerelease / none", () => {
92
+ assert.equal(updateKind("0.5.6", "1.0.0"), "major");
93
+ assert.equal(updateKind("0.5.6", "0.6.0"), "minor");
94
+ assert.equal(updateKind("0.5.6", "0.5.7"), "patch");
95
+ assert.equal(updateKind("0.6.0-beta.1", "0.6.0"), "prerelease");
96
+ assert.equal(updateKind("0.5.6", "0.5.6-rc.1"), "none", "预发布比正式版旧");
97
+ assert.equal(updateKind("0.5.6", "0.5.6"), "none");
98
+ assert.equal(updateKind("0.5.7", "0.5.6"), "none", "更旧不叫更新");
99
+ assert.equal(updateKind("0.5.6", "latest"), "unknown");
100
+ });
101
+
102
+ console.log("\n── 升级命令 / 安装目录 ──");
103
+
104
+ test("插件安装目录从 import.meta.url 推出(lib/ 的上一级,带结尾斜杠)", () => {
105
+ const dir = pluginDirFromUrl("file:///Users/peng/.dsh/profiles/desktop/node_modules/dsh-plugin-mesh/lib/index.js");
106
+ assert.equal(dir, "/Users/peng/.dsh/profiles/desktop/node_modules/dsh-plugin-mesh/");
107
+ });
108
+
109
+ test("升级命令用的是 release 真实资产名与 tag(与 scripts/release-plugin.sh 一致)", () => {
110
+ const cmd = buildUpgradeCommand({ version: "0.6.0", pluginDir: "/tmp/plugin/" });
111
+ assert.ok(cmd.includes("plugin-v0.6.0"), cmd);
112
+ assert.ok(cmd.includes("dsh-plugin-mesh-0.6.0.tar.gz"), cmd);
113
+ assert.ok(cmd.includes('tar xz -C "/tmp/plugin/"'), cmd);
114
+ assert.ok(cmd.startsWith("curl -L https://ghfast.top/https://github.com/peng456/dsh-plugin-mesh/releases/download/"), cmd);
115
+ });
116
+
117
+ test("没有版本就不编一条假命令", () => {
118
+ assert.equal(buildUpgradeCommand({ version: "", pluginDir: "/x/" }), "");
119
+ });
120
+
121
+ console.log("\n── 报告组装:失败绝不能说成「已是最新」──");
122
+
123
+ const okLatest = { ok: true, version: "0.6.0", registry: DEFAULT_REGISTRIES[0] };
124
+
125
+ test("有新版本 → hasUpdate / kind / 链接 / 可复制命令都在", () => {
126
+ const r = buildUpdateReport({
127
+ current: "0.5.6",
128
+ diskVersion: "0.5.6",
129
+ latest: okLatest,
130
+ pluginDir: "/p/",
131
+ now: Date.parse("2026-10-29T00:00:00Z"),
132
+ });
133
+ assert.equal(r.ok, true);
134
+ assert.equal(r.current, "0.5.6");
135
+ assert.equal(r.latest, "0.6.0");
136
+ assert.equal(r.comparable, true);
137
+ assert.equal(r.hasUpdate, true);
138
+ assert.equal(r.kind, "minor");
139
+ assert.equal(r.versionDrift, false);
140
+ assert.equal(r.checkedAt, "2026-10-29T00:00:00.000Z");
141
+ assert.ok(r.releaseUrl.endsWith("/releases/tag/plugin-v0.6.0"), r.releaseUrl);
142
+ assert.ok(r.npmUrl.endsWith("/v/0.6.0"), r.npmUrl);
143
+ assert.ok(r.upgradeCommand.includes("0.6.0"));
144
+ assert.ok(r.upgradeCommand.includes('"/p/"'));
145
+ });
146
+
147
+ test("同版本 → 已是最新(hasUpdate=false, kind=none)", () => {
148
+ const r = buildUpdateReport({ current: "0.6.0", latest: okLatest, pluginDir: "/p/" });
149
+ assert.equal(r.ok, true);
150
+ assert.equal(r.hasUpdate, false);
151
+ assert.equal(r.kind, "none");
152
+ assert.equal(r.comparable, true);
153
+ });
154
+
155
+ test("版本号无法比较 → comparable=false,且 hasUpdate 不能是 true", () => {
156
+ const r = buildUpdateReport({
157
+ current: "0.5.6",
158
+ latest: { ok: true, version: "2026.1", registry: "x" },
159
+ });
160
+ assert.equal(r.ok, true);
161
+ assert.equal(r.comparable, false);
162
+ assert.equal(r.hasUpdate, false);
163
+ assert.equal(r.kind, "unknown");
164
+ });
165
+
166
+ test("registry 查询失败 → ok:false 且带原因;不能有 latest,也不能说没有更新", () => {
167
+ const r = buildUpdateReport({
168
+ current: "0.5.6",
169
+ latest: { ok: false, error: "检查更新失败:registry.npmjs.org 超时(5000ms)", failures: ["a 超时", "b HTTP 502"] },
170
+ });
171
+ assert.equal(r.ok, false);
172
+ assert.ok(r.error.includes("超时"), r.error);
173
+ assert.deepEqual(r.failures, ["a 超时", "b HTTP 502"]);
174
+ assert.equal("latest" in r, false, "没问到最新版本就不能回报 latest");
175
+ assert.equal("hasUpdate" in r, false, "没问到就不能声称有/没有更新");
176
+ });
177
+
178
+ test("磁盘版本与进程版本不一致 → versionDrift=true(升级了没重启)", () => {
179
+ const r = buildUpdateReport({ current: "0.5.6", diskVersion: "0.6.0", latest: okLatest });
180
+ assert.equal(r.versionDrift, true);
181
+ const same = buildUpdateReport({ current: "0.6.0", diskVersion: "0.6.0", latest: okLatest });
182
+ assert.equal(same.versionDrift, false);
183
+ });
184
+
185
+ console.log("\n── registry 查询:逐源尝试,失败原因全留 ──");
186
+
187
+ await testAsync("官方源成功 → 直接用,不再问镜像", async () => {
188
+ const calls = [];
189
+ const r = await fetchLatestVersion({
190
+ registries: ["https://a.test/latest", "https://b.test/latest"],
191
+ fetchImpl: async (url) => {
192
+ calls.push(url);
193
+ return jsonResponse({ version: "0.6.0" });
194
+ },
195
+ });
196
+ assert.equal(r.ok, true);
197
+ assert.equal(r.version, "0.6.0");
198
+ assert.equal(r.registry, "https://a.test/latest");
199
+ assert.deepEqual(calls, ["https://a.test/latest"]);
200
+ });
201
+
202
+ await testAsync("官方源 HTTP 500 → 回退镜像成功", async () => {
203
+ const r = await fetchLatestVersion({
204
+ registries: ["https://a.test/latest", "https://b.test/latest"],
205
+ fetchImpl: async (url) =>
206
+ url.startsWith("https://a.test") ? jsonResponse({ error: "boom" }, 500) : jsonResponse({ version: "0.7.0" }),
207
+ });
208
+ assert.equal(r.ok, true);
209
+ assert.equal(r.version, "0.7.0");
210
+ assert.equal(r.registry, "https://b.test/latest");
211
+ });
212
+
213
+ await testAsync("两个源都挂 → ok:false,且每个原因都保留(能看出是谁挂了)", async () => {
214
+ const r = await fetchLatestVersion({
215
+ registries: ["https://a.test/latest", "https://b.test/latest"],
216
+ fetchImpl: async (url) => {
217
+ if (url.startsWith("https://a.test")) throw new Error("ENOTFOUND a.test");
218
+ return jsonResponse({}, 502);
219
+ },
220
+ });
221
+ assert.equal(r.ok, false);
222
+ assert.equal(r.failures.length, 2, JSON.stringify(r.failures));
223
+ assert.ok(r.failures[0].includes("ENOTFOUND"), r.failures[0]);
224
+ assert.ok(r.failures[1].includes("HTTP 502"), r.failures[1]);
225
+ assert.ok(r.error.includes("检查更新失败"), r.error);
226
+ });
227
+
228
+ await testAsync("超时要写成「超时」,不能和 HTTP 错误混为一谈", async () => {
229
+ const timeout = Object.assign(new Error("The operation was aborted due to timeout"), { name: "TimeoutError" });
230
+ const r = await fetchLatestVersion({
231
+ registries: ["https://a.test/latest"],
232
+ timeoutMs: 1234,
233
+ fetchImpl: async () => {
234
+ throw timeout;
235
+ },
236
+ });
237
+ assert.equal(r.ok, false);
238
+ assert.ok(r.failures[0].includes("超时(1234ms)"), r.failures[0]);
239
+ });
240
+
241
+ await testAsync("响应里没有 version → 该源不算成功,继续下一个", async () => {
242
+ const r = await fetchLatestVersion({
243
+ registries: ["https://a.test/latest", "https://b.test/latest"],
244
+ fetchImpl: async (url) =>
245
+ url.startsWith("https://a.test") ? jsonResponse({ name: "dsh-plugin-mesh" }) : jsonResponse({ version: "0.6.0" }),
246
+ });
247
+ assert.equal(r.ok, true);
248
+ assert.equal(r.version, "0.6.0");
249
+ });
250
+
251
+ await testAsync("registry 返回无法比较的版本 → 该源不算成功,最终报失败", async () => {
252
+ const r = await fetchLatestVersion({
253
+ registries: ["https://a.test/latest"],
254
+ fetchImpl: async () => jsonResponse({ version: "2026.1" }),
255
+ });
256
+ assert.equal(r.ok, false);
257
+ assert.ok(r.failures[0].includes("2026.1"), r.failures[0]);
258
+ });
259
+
260
+ await testAsync("没有 fetch 的运行环境 → 说清楚无法检查,而不是静默", async () => {
261
+ const r = await fetchLatestVersion({ fetchImpl: null, registries: [] });
262
+ assert.equal(r.ok, false);
263
+ assert.ok(r.error.includes("fetch"), r.error);
264
+ });
265
+
266
+ console.log(`\n${failed === 0 ? "全部通过" : "有失败"}:${passed} 通过 / ${failed} 失败`);
267
+ process.exit(failed === 0 ? 0 : 1);
@@ -143,6 +143,9 @@ const {
143
143
  SwitchBody,
144
144
  SwitchRow,
145
145
  HomeSwitchBar,
146
+ UpdateLink,
147
+ UpdateLinkView,
148
+ FeedbackLink,
146
149
  } = mod.__test;
147
150
 
148
151
  const noop = () => {};
@@ -1066,5 +1069,143 @@ test("一键关闭里的互联网行也标出受阻(避免只说「未连接
1066
1069
  assert.ok(txt.includes("启动受阻"), txt);
1067
1070
  });
1068
1071
 
1072
+ console.log("\n── 主页头部:问题反馈 / 检查更新(轻入口,不占卡片) ──");
1073
+
1074
+ const updateReport = {
1075
+ ok: true,
1076
+ current: "0.5.6",
1077
+ diskVersion: "0.5.6",
1078
+ versionDrift: false,
1079
+ latest: "0.6.0",
1080
+ comparable: true,
1081
+ hasUpdate: true,
1082
+ kind: "minor",
1083
+ checkedAt: new Date(now).toISOString(),
1084
+ releaseUrl: "https://github.com/peng456/dsh-plugin-mesh/releases/tag/plugin-v0.6.0",
1085
+ pluginDir: "/p/node_modules/dsh-plugin-mesh/",
1086
+ upgradeCommand: 'curl -L https://example.test/v0.6.0.tar.gz | tar xz -C "/p/node_modules/dsh-plugin-mesh/"',
1087
+ };
1088
+
1089
+ test("主页头部把两个入口收成一行小字,不再挂卡片", () => {
1090
+ const el = HomeBoard({
1091
+ state,
1092
+ self: state.self,
1093
+ peers: [peer],
1094
+ tasks: [],
1095
+ now,
1096
+ lastOk: now,
1097
+ focus: false,
1098
+ layout: [],
1099
+ sizes: {},
1100
+ customCards: [],
1101
+ density: "comfortable",
1102
+ onLayoutChange: noop,
1103
+ onFocusChange: noop,
1104
+ onSizesChange: noop,
1105
+ onCustomCardsChange: noop,
1106
+ onDensityChange: noop,
1107
+ onReset: noop,
1108
+ onDevices: noop,
1109
+ onTasks: noop,
1110
+ onConnect: noop,
1111
+ onScan: noop,
1112
+ scanning: false,
1113
+ hostDown: false,
1114
+ onDispatched: noop,
1115
+ push: noop,
1116
+ reload: async () => {},
1117
+ firstRun: null,
1118
+ });
1119
+ const txt = textOf(el).join(" ");
1120
+ assert.ok(txt.includes("问题反馈"), txt.slice(0, 300));
1121
+ assert.ok(txt.includes("检查更新"), txt);
1122
+ const cardIds = [];
1123
+ walk(el, (n) => {
1124
+ if (n.type === "article" && n.props && n.props["data-mesh-card"]) cardIds.push(n.props["data-mesh-card"]);
1125
+ });
1126
+ assert.deepEqual(cardIds, [], "布局为空时不该再有 update / feedback 卡片");
1127
+ });
1128
+
1129
+ test("反馈入口是预填好的 GitHub Issue:带版本与诊断,不带 secret / 授权码", () => {
1130
+ const link = FeedbackLink({ state });
1131
+ assert.equal(link.type, "a");
1132
+ const href = String(link.props.href);
1133
+ assert.ok(href.startsWith("https://github.com/peng456/dsh-plugin-mesh/issues/new?"), href.slice(0, 120));
1134
+ const u = new URL(href);
1135
+ assert.ok(String(u.searchParams.get("title")).includes("0.3.33"), String(u.searchParams.get("title")));
1136
+ assert.ok(String(u.searchParams.get("body")).includes("诊断信息"));
1137
+ assert.ok(!href.includes(state.self.secret), "配对码/secret 不能进 URL");
1138
+ assert.ok(!decodeURIComponent(href).includes("tsnetAuthKey"), "授权码字段不能出现");
1139
+ assert.ok(String(link.props.title).includes("geekstartup@163.com"), "GitHub 不通时邮件仍是退路");
1140
+ });
1141
+
1142
+ test("检查更新:没点之前就是一个小字,点了先说「检查中…」", () => {
1143
+ const idle = textOf(UpdateLink({ push: noop })).join(" ");
1144
+ assert.ok(idle.includes("检查更新"), idle);
1145
+ assert.ok(!idle.includes("已是最新"), "没查过就不能有任何结论");
1146
+ const checking = textOf(UpdateLinkView({ phase: "checking", report: null, onCheck: noop, onCopy: noop })).join(" ");
1147
+ assert.ok(checking.includes("检查中"), checking);
1148
+ });
1149
+
1150
+ test("有更新:旁边多一个字「新版本 v0.6.0」,命令不铺在页面上", () => {
1151
+ const txt = textOf(UpdateLinkView({ phase: "done", report: updateReport, onCheck: noop, onCopy: noop })).join(" ");
1152
+ assert.ok(txt.includes("新版本 v0.6.0"), txt);
1153
+ assert.ok(!txt.includes("curl"), "升级命令点一下才复制,不占版面");
1154
+ });
1155
+
1156
+ test("检查失败 / 无法比较:各多一个字说明,绝不说「已是最新」", () => {
1157
+ const failed = textOf(
1158
+ UpdateLinkView({
1159
+ phase: "done",
1160
+ report: { ok: false, current: "0.5.6", error: "检查更新失败:registry.npmjs.org 超时(5000ms)" },
1161
+ onCheck: noop,
1162
+ onCopy: noop,
1163
+ }),
1164
+ ).join(" ");
1165
+ assert.ok(failed.includes("检查失败"), failed);
1166
+ assert.ok(!failed.includes("已是最新"), "失败绝不能说成已是最新");
1167
+ assert.ok(!failed.includes("新版本"), "失败时不能暗示有更新");
1168
+
1169
+ const incomparable = textOf(
1170
+ UpdateLinkView({
1171
+ phase: "done",
1172
+ report: { ...updateReport, latest: "2026.1", comparable: false, hasUpdate: false },
1173
+ onCheck: noop,
1174
+ onCopy: noop,
1175
+ }),
1176
+ ).join(" ");
1177
+ assert.ok(incomparable.includes("无法比较"), incomparable);
1178
+ assert.ok(!incomparable.includes("已是最新"));
1179
+ });
1180
+
1181
+ test("点「新版本 v0.6.0」复制升级命令;点「检查更新」重查(不是跳页)", () => {
1182
+ let copied = "";
1183
+ let checked = 0;
1184
+ const el = UpdateLinkView({
1185
+ phase: "done",
1186
+ report: updateReport,
1187
+ onCheck: () => {
1188
+ checked += 1;
1189
+ },
1190
+ onCopy: (text) => {
1191
+ copied = text;
1192
+ },
1193
+ });
1194
+ let updateBtn = null;
1195
+ let checkBtn = null;
1196
+ walk(el, (n) => {
1197
+ if (n.type !== "button") return;
1198
+ const label = textOf(n).join("");
1199
+ if (label.includes("新版本")) updateBtn = n;
1200
+ if (label === "检查更新") checkBtn = n;
1201
+ });
1202
+ assert.ok(updateBtn, "要有一个「新版本」按钮");
1203
+ assert.ok(checkBtn, "要有一个「检查更新」按钮");
1204
+ updateBtn.props.onClick();
1205
+ checkBtn.props.onClick();
1206
+ assert.equal(copied, updateReport.upgradeCommand);
1207
+ assert.equal(checked, 1);
1208
+ });
1209
+
1069
1210
  console.log(`\n${failed === 0 ? "全部通过" : "有失败"}:${passed} 通过 / ${failed} 失败\n`);
1070
1211
  process.exit(failed ? 1 : 0);
package/lib/index.js CHANGED
@@ -46,6 +46,7 @@ import {
46
46
  } from "./capabilities.js";
47
47
  import { conversationKey, replyTarget } from "./conversation.js";
48
48
  import { buildDiagnostics, entryInfo, readPackageVersion } from "./diagnostics.js";
49
+ import { buildUpdateReport, fetchLatestVersion, pluginDirFromUrl } from "./update.js";
49
50
  import { buildPrompt } from "./prompt.js";
50
51
  import { resolvePairing } from "./pairing.js";
51
52
  import {
@@ -78,13 +79,15 @@ import {
78
79
  export const name = "dsh-plugin-mesh";
79
80
  export const inject = ["tools", "webServer"];
80
81
 
81
- const VERSION = "0.5.6";
82
+ const VERSION = "0.5.7";
82
83
  // 诊断用:进程启动时间、入口真实路径、**磁盘上** package.json 的版本。
83
84
  // 这三样放一起才能回答"现在跑的到底是哪份代码" —— 只看 state.json 或重启日志
84
85
  // 都答不了(真踩过:磁盘升到 0.5.1,进程还在 0.5.0,界面显示 0.5.0)。
85
86
  const PROCESS_STARTED_AT = Date.now() - Math.round(process.uptime() * 1000);
86
87
  const ENTRY_INFO = entryInfo(import.meta.url);
87
88
  const DISK_VERSION = readPackageVersion(import.meta.url);
89
+ /** 本插件的安装目录:界面生成「升级命令」时直接用它,不让人再猜 <PLUGIN> 是什么。 */
90
+ const PLUGIN_DIR = pluginDirFromUrl(import.meta.url);
88
91
  /** 一次性取文件用的 nonce:进程每次启动都换,写进日志给运维/agent 取。 */
89
92
  const FILE_TRANSFER_NONCE = randomBytes(9).toString("base64url");
90
93
  const RULE_ID = "mesh-inbound";
@@ -2983,6 +2986,43 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
2983
2986
  // 只读诊断:UI 的「诊断」卡片用它;与 /mesh/v1/diagnostics 同一份数据。
2984
2987
  route("/mesh/api/diagnostics", (_req, res) => send(res, 200, diagnostics()));
2985
2988
 
2989
+ /**
2990
+ * 检查更新:向 npm registry 问一次最新版本。
2991
+ *
2992
+ * 只读(GET),但要带缓存:
2993
+ * · 成功缓存 30 分钟 —— 主页每次进入都会问一次,不能让面板变成 registry 的
2994
+ * 高频客户端;
2995
+ * · 失败只缓存 1 分钟 —— 网络刚恢复时用户点「重新检查」应该马上能成功,
2996
+ * 但也不能让离线状态下的反复点按变成打点风暴。
2997
+ * 失败一律返回 200 + `{ok:false,error}`:这是「没问到」,不是 HTTP 故障,
2998
+ * 界面要把它和「已是最新」分开显示。
2999
+ */
3000
+ const UPDATE_OK_TTL_MS = 30 * 60 * 1000;
3001
+ const UPDATE_FAIL_TTL_MS = 60 * 1000;
3002
+ let updateCache = null;
3003
+ route("/mesh/api/update", async (req, res) => {
3004
+ const force = /[?&]force=1(?:&|$)/.test(String(req.url || ""));
3005
+ const now = Date.now();
3006
+ if (!force && updateCache) {
3007
+ const ttl = updateCache.report.ok ? UPDATE_OK_TTL_MS : UPDATE_FAIL_TTL_MS;
3008
+ if (now - updateCache.at < ttl) {
3009
+ return send(res, 200, { ...updateCache.report, cached: true });
3010
+ }
3011
+ }
3012
+ // 5 秒:主页是首屏,等不起更久;两源合计最坏也就 10 秒。
3013
+ const latest = await fetchLatestVersion({ timeoutMs: 5000 });
3014
+ const report = buildUpdateReport({
3015
+ current: VERSION,
3016
+ diskVersion: DISK_VERSION,
3017
+ latest,
3018
+ pluginDir: PLUGIN_DIR,
3019
+ now: Date.now(),
3020
+ });
3021
+ updateCache = { at: Date.now(), report };
3022
+ if (!report.ok) log(`检查更新失败(不是「已是最新」): ${report.error}`);
3023
+ send(res, 200, report);
3024
+ });
3025
+
2986
3026
  /**
2987
3027
  * 用户决定提高某个 thread 的限速上限。
2988
3028
  *
@@ -3900,5 +3940,5 @@ function registerUiRoutes(ctx, { discovery, config, identity, inbound, outbound,
3900
3940
  };
3901
3941
  ctx.effect(() => ctx.webServer.registerUpgrade({ path: "/mesh/api/ssh/ws", handler: sshUpgrade }));
3902
3942
 
3903
- log("UI 接口已挂载: /mesh/api/state|refresh|secret|send|probe|web-url|web-panel|ssh");
3943
+ log("UI 接口已挂载: /mesh/api/state|diagnostics|update|refresh|secret|send|probe|web-url|web-panel|ssh");
3904
3944
  }
package/lib/update.js ADDED
@@ -0,0 +1,232 @@
1
+ /**
2
+ * 「检查更新」:版本比较 + 向 npm registry 问一次最新版本。
3
+ *
4
+ * 为什么放在主机侧、而不是让浏览器直接 fetch registry:
5
+ * · 渲染层在 DSH Desktop 里有 CSP / 请求门禁,外网请求不一定发得出去;
6
+ * · 主机侧可以**带超时、带镜像回退、带缓存**,一次失败不会让整页变慢;
7
+ * · 失败必须能和「已是最新」区分开 —— 这是本项目最贵的一条教训
8
+ * (见 AGENTS.md 硬约束 1:探测失败不能被说成否定事实)。
9
+ *
10
+ * 所以这里只有两类结果:
11
+ * { ok: true, latest: "0.6.0", ... } —— 真的问到了
12
+ * { ok: false, error: "…超时…", failures: [...] } —— 没问到,原因逐条列出
13
+ * 绝不存在「问不到 → 当作没有更新」这种降级。
14
+ *
15
+ * 本文件是纯函数 + 一个可注入 fetch 的查询,便于无网络单测。
16
+ */
17
+ import { fileURLToPath } from "node:url";
18
+
19
+ export const RELEASE_REPO = "peng456/dsh-plugin-mesh";
20
+ export const NPM_PACKAGE = "dsh-plugin-mesh";
21
+
22
+ /**
23
+ * 版本源:官方 registry 优先,国内镜像兜底(作者的机器上官方源时常很慢)。
24
+ * 不按「谁快」做并发竞速:先问到的那个就够了,而且同时打两个源没有必要。
25
+ */
26
+ export const DEFAULT_REGISTRIES = [
27
+ `https://registry.npmjs.org/${NPM_PACKAGE}/latest`,
28
+ `https://registry.npmmirror.com/${NPM_PACKAGE}/latest`,
29
+ ];
30
+
31
+ /** 从 `import.meta.url` 推出插件安装目录(带结尾斜杠,可直接放进 tar -C)。 */
32
+ export function pluginDirFromUrl(metaUrl) {
33
+ try {
34
+ return fileURLToPath(new URL("../", metaUrl));
35
+ } catch {
36
+ return "";
37
+ }
38
+ }
39
+
40
+ /**
41
+ * 解析语义化版本;不是 `x.y.z[-pre][+build]` 就返回 null。
42
+ * 返回 null 意味着「无法比较」,调用方必须把它和「相等」区分开。
43
+ */
44
+ export function parseVersion(raw) {
45
+ const m = /^[vV]?(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/.exec(String(raw ?? "").trim());
46
+ if (!m) return null;
47
+ return {
48
+ major: Number(m[1]),
49
+ minor: Number(m[2]),
50
+ patch: Number(m[3]),
51
+ pre: m[4] ? m[4].split(".").filter(Boolean) : [],
52
+ };
53
+ }
54
+
55
+ /** semver 的预发布段比较:1.0.0-beta < 1.0.0;数字段按数值、字母段按字典序。 */
56
+ function comparePrerelease(a, b) {
57
+ if (a.length === 0 && b.length === 0) return 0;
58
+ // 有预发布段的版本**小于**同号正式版
59
+ if (a.length === 0) return 1;
60
+ if (b.length === 0) return -1;
61
+ const len = Math.max(a.length, b.length);
62
+ for (let i = 0; i < len; i += 1) {
63
+ const x = a[i];
64
+ const y = b[i];
65
+ if (x === undefined) return -1;
66
+ if (y === undefined) return 1;
67
+ const nx = /^\d+$/.test(x);
68
+ const ny = /^\d+$/.test(y);
69
+ if (nx && ny) {
70
+ const d = Number(x) - Number(y);
71
+ if (d !== 0) return d < 0 ? -1 : 1;
72
+ continue;
73
+ }
74
+ if (nx !== ny) return nx ? -1 : 1;
75
+ if (x !== y) return x < y ? -1 : 1;
76
+ }
77
+ return 0;
78
+ }
79
+
80
+ /**
81
+ * 比较两个版本:a > b → 1,a < b → -1,相等 → 0。
82
+ * 任一版本无法解析时返回 **null**(不是 0)—— 让调用方去说"无法比较"。
83
+ */
84
+ export function compareVersions(a, b) {
85
+ const pa = parseVersion(a);
86
+ const pb = parseVersion(b);
87
+ if (!pa || !pb) return null;
88
+ for (const key of ["major", "minor", "patch"]) {
89
+ if (pa[key] !== pb[key]) return pa[key] < pb[key] ? -1 : 1;
90
+ }
91
+ return comparePrerelease(pa.pre, pb.pre);
92
+ }
93
+
94
+ /** 更新的"量级":用于界面上说人话(大版本 / 小版本 / 修订 / 预发布)。 */
95
+ export function updateKind(current, latest) {
96
+ const c = parseVersion(current);
97
+ const l = parseVersion(latest);
98
+ if (!c || !l) return "unknown";
99
+ if (compareVersions(latest, current) !== 1) return "none";
100
+ if (l.major !== c.major) return "major";
101
+ if (l.minor !== c.minor) return "minor";
102
+ if (l.patch !== c.patch) return "patch";
103
+ return "prerelease";
104
+ }
105
+
106
+ function hostOf(url) {
107
+ try {
108
+ return new URL(url).host;
109
+ } catch {
110
+ return String(url || "版本源");
111
+ }
112
+ }
113
+
114
+ /**
115
+ * 问一次最新版本。逐源尝试,**每条失败原因都保留**(超时 / HTTP 错误 / 响应
116
+ * 里没有 version),最终失败时一起返回,界面才有话可说。
117
+ *
118
+ * @returns {Promise<{ok: true, version: string, registry: string}
119
+ * | {ok: false, error: string, failures: string[]}>}
120
+ */
121
+ export async function fetchLatestVersion({
122
+ fetchImpl = globalThis.fetch,
123
+ timeoutMs = 5000,
124
+ registries = DEFAULT_REGISTRIES,
125
+ } = {}) {
126
+ if (typeof fetchImpl !== "function") {
127
+ return { ok: false, error: "当前运行环境没有 fetch,无法检查更新", failures: [] };
128
+ }
129
+ const failures = [];
130
+ for (const url of registries) {
131
+ try {
132
+ const signal =
133
+ typeof AbortSignal !== "undefined" && typeof AbortSignal.timeout === "function"
134
+ ? AbortSignal.timeout(timeoutMs)
135
+ : undefined;
136
+ const res = await fetchImpl(url, { signal, headers: { accept: "application/json" } });
137
+ if (!res || res.ok !== true) {
138
+ failures.push(`${hostOf(url)} HTTP ${res ? res.status : "无响应"}`);
139
+ continue;
140
+ }
141
+ const doc = await res.json();
142
+ const version = String(doc?.version ?? "").trim();
143
+ if (!version) {
144
+ failures.push(`${hostOf(url)} 响应里没有 version`);
145
+ continue;
146
+ }
147
+ if (!parseVersion(version)) {
148
+ failures.push(`${hostOf(url)} 返回了无法比较的版本号 ${version}`);
149
+ continue;
150
+ }
151
+ return { ok: true, version, registry: url };
152
+ } catch (err) {
153
+ const timedOut = err?.name === "TimeoutError" || err?.name === "AbortError";
154
+ failures.push(`${hostOf(url)} ${timedOut ? `超时(${timeoutMs}ms)` : String(err?.message ?? err)}`);
155
+ }
156
+ }
157
+ return {
158
+ ok: false,
159
+ failures,
160
+ error: failures.length ? `检查更新失败:${failures.join(";")}` : "没有可用的版本源",
161
+ };
162
+ }
163
+
164
+ /**
165
+ * 升级命令(与 scripts/release-plugin.sh 打出来的那条一致:release 资产是
166
+ * 不带顶层目录的源码包,所以可以直接 tar xz -C 插件目录覆盖)。
167
+ *
168
+ * 这里只给「下载并覆盖」这一条;重启、回滚与可加载校验写在 README 的升级小节,
169
+ * 界面不要假装一键升级 —— 覆盖完不重启等于没升级(VERSION 是启动时常量)。
170
+ */
171
+ export function buildUpgradeCommand({ version, pluginDir } = {}) {
172
+ const v = String(version ?? "").trim();
173
+ if (!v) return "";
174
+ const dir = String(pluginDir ?? "").trim() || "<插件目录>";
175
+ const asset = `${NPM_PACKAGE}-${v}.tar.gz`;
176
+ const url = `https://ghfast.top/https://github.com/${RELEASE_REPO}/releases/download/plugin-v${v}/${asset}`;
177
+ return `curl -L ${url} | tar xz -C "${dir}"`;
178
+ }
179
+
180
+ /**
181
+ * 组装返回给界面的报告。**不抛异常、不联网**,所有字段显式传入便于测试。
182
+ *
183
+ * `latest.ok !== true` 时返回 ok:false 并把原因带出去;界面据此显示"检查失败",
184
+ * 而不是"已是最新"。
185
+ */
186
+ export function buildUpdateReport({
187
+ current = "",
188
+ diskVersion = "",
189
+ latest = null,
190
+ pluginDir = "",
191
+ now = Date.now(),
192
+ } = {}) {
193
+ const currentVersion = String(current ?? "").trim();
194
+ const onDisk = String(diskVersion ?? "").trim();
195
+ const report = {
196
+ current: currentVersion,
197
+ diskVersion: onDisk,
198
+ /** 磁盘上已经不是进程正在跑的版本 = 升级了没重启(界面要明说) */
199
+ versionDrift: !!onDisk && onDisk !== currentVersion,
200
+ pluginDir: String(pluginDir ?? ""),
201
+ checkedAt: new Date(now).toISOString(),
202
+ releaseUrl: `https://github.com/${RELEASE_REPO}/releases`,
203
+ npmUrl: `https://www.npmjs.com/package/${NPM_PACKAGE}`,
204
+ };
205
+
206
+ if (!latest || latest.ok !== true) {
207
+ return {
208
+ ok: false,
209
+ ...report,
210
+ error: String(latest?.error || "没有可用的版本源"),
211
+ failures: Array.isArray(latest?.failures) ? latest.failures : [],
212
+ };
213
+ }
214
+
215
+ const latestVersion = String(latest.version);
216
+ const cmp = compareVersions(latestVersion, currentVersion);
217
+ const comparable = cmp !== null;
218
+ return {
219
+ ok: true,
220
+ ...report,
221
+ latest: latestVersion,
222
+ registry: String(latest.registry || ""),
223
+ /** false = 版本号无法比较(界面必须说"无法比较",不能说"已是最新") */
224
+ comparable,
225
+ /** 只有明确比较出「更新」才是 true */
226
+ hasUpdate: comparable ? cmp === 1 : false,
227
+ kind: comparable ? updateKind(currentVersion, latestVersion) : "unknown",
228
+ releaseUrl: `https://github.com/${RELEASE_REPO}/releases/tag/plugin-v${latestVersion}`,
229
+ npmUrl: `https://www.npmjs.com/package/${NPM_PACKAGE}/v/${latestVersion}`,
230
+ upgradeCommand: buildUpgradeCommand({ version: latestVersion, pluginDir }),
231
+ };
232
+ }
package/llms.txt CHANGED
@@ -30,6 +30,8 @@ Verify after restart: `GET http://127.0.0.1:45917/mesh/v1/health` returns JSON c
30
30
  - Auto-creates an agent session on the receiving machine when a task arrives, then routes that task to a new or reused session.
31
31
  - Reports a structured `osInfo` card entry (host) and a `systems[]` array: host first, then environments such as WSL distros on Windows (`kind: "wsl"`, Linux `platform`, distro name/version). Older peers only send `os`, and the UI falls back to parsing it; purely display data, at most 4 systems.
32
32
  - On Windows, probes runtimes inside **running** WSL distros (`wsl.exe -d <name> -e sh -lc …`) and reports them as `capabilities.wsl[]`; stopped distros are never started just to probe. Host and WSL runtimes are displayed separately.
33
+ - Home-page header exposes two compact text links (no cards): **问题反馈** opens a prefilled GitHub issue, and **检查更新** calls `GET /mesh/api/update`. The update route asks the npm registry (`registry.npmjs.org`, falling back to `registry.npmmirror.com`, 5 s per source, 30 min host-side cache) and compares with the running `VERSION`. A failed check returns `{ok:false,error,failures[]}` and is shown as "检查失败" — never as "已是最新". When a newer version exists, clicking the inline "新版本 vX" copies the exact release asset command with this installation's plugin dir filled in (a restart is required for it to take effect).
34
+ - The prefilled feedback issue carries the same diagnostics text as the diagnostics section; `buildDiagnostics()` deliberately excludes secrets (pairing code, tsnet auth key). The author's email (`geekstartup@163.com`) is the fallback when GitHub is unreachable.
33
35
 
34
36
  ## Tools registered (callable by the agent)
35
37
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-plugin-mesh",
3
- "version": "0.5.6",
3
+ "version": "0.5.7",
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",
@@ -66,8 +66,9 @@
66
66
  "selftest:layout": "node lib/_selftest-layout.mjs",
67
67
  "selftest:diagnostics": "node lib/_selftest-diagnostics.mjs",
68
68
  "selftest:osinfo": "node lib/_selftest-osinfo.mjs",
69
- "test": "npm run check && npm run selftest && npm run selftest:prompt && npm run selftest:pairing && npm run selftest:switch && 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 && npm run selftest:layout && npm run selftest:diagnostics && npm run selftest:osinfo",
70
- "check": "node scripts/check-version.mjs && node scripts/check-tdz.mjs && node --check lib/index.js && node --check lib/layout.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/switch.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 lib/tsnet/channels.js && node --check client/client.js && node --check scripts/release-plan.mjs && npm run check:loadable && npm run check:docs",
69
+ "selftest:update": "node lib/_selftest-update.mjs",
70
+ "test": "npm run check && npm run selftest && npm run selftest:prompt && npm run selftest:pairing && npm run selftest:switch && 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 && npm run selftest:layout && npm run selftest:diagnostics && npm run selftest:osinfo && npm run selftest:update",
71
+ "check": "node scripts/check-version.mjs && node scripts/check-tdz.mjs && node --check lib/index.js && node --check lib/layout.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/switch.js && node --check lib/scan.js && node --check lib/update.js && node --check lib/tsnet/download.js && node --check lib/tsnet/manager.js && node --check lib/tsnet/bridge.js && node --check lib/tsnet/channels.js && node --check client/client.js && node --check scripts/release-plan.mjs && npm run check:loadable && npm run check:docs",
71
72
  "build:sidecar": "bash scripts/build-sidecar.sh",
72
73
  "verify:mirror": "node scripts/verify-lan-mirror.mjs",
73
74
  "release:plan": "node scripts/release-plan.mjs",
@@ -23,7 +23,7 @@ import { fileURLToPath } from "node:url";
23
23
  import { dirname, join } from "node:path";
24
24
 
25
25
  const root = join(dirname(fileURLToPath(import.meta.url)), "..");
26
- const files = ["lib/index.js", "lib/discovery.js", "lib/conversation.js", "lib/identity.js"];
26
+ const files = ["lib/index.js", "lib/discovery.js", "lib/conversation.js", "lib/identity.js", "lib/update.js"];
27
27
  let problems = 0;
28
28
 
29
29
  /** 逐行计算花括号深度(粗略:不解析字符串/模板串,够用) */