dsh-plugin-mesh 0.5.2 → 0.5.4

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.
@@ -16,7 +16,8 @@ import { tmpdir } from "node:os";
16
16
  import { dirname, join } from "node:path";
17
17
  import { detectTarget, assetName, candidateUrls, binDir, binaryPath, binaryInfo, cacheIsCurrent, downloadToBuffer, SIDECAR_PROTOCOL } from "./tsnet/download.js";
18
18
  import { PINNED_CHECKSUMS } from "./tsnet/checksums.js";
19
- import { toHostname, TsnetNode } from "./tsnet/manager.js";
19
+ import { toHostname, TsnetNode, channelKey, channelDir, channelStateDir } from "./tsnet/manager.js";
20
+ import { resolveTailnetChannels } from "./tsnet/channels.js";
20
21
  import { tailnetOrigin, isTailnetAddress } from "./tsnet/bridge.js";
21
22
  import { MeshDiscovery, orderedEndpoints, endpointAlive } from "./discovery.js";
22
23
  import { conversationKey, replyTarget } from "./conversation.js";
@@ -294,6 +295,177 @@ check("一条通道过期不会删掉设备(另一条还活着)", () => {
294
295
  assert.ok(d.peers()[0].endpoints.length === 2);
295
296
  });
296
297
 
298
+ check("多 tailnet:同一台设备两条 tailnet 端点互不覆盖", () => {
299
+ const d = new MeshDiscovery({ id: "self-1", port: 45917, meta: { machine: "me" } });
300
+ d.note({ app: "dsh-mesh", id: "dev", machine: "hos", host: "192.168.1.7", port: 45917 }, "192.168.1.7");
301
+ d.note({ app: "dsh-mesh", id: "dev", machine: "hos", host: "192.168.1.7", port: 45917 }, "100.64.0.9", {
302
+ transport: "tsnet",
303
+ channel: "tsnet:personal",
304
+ });
305
+ // 第二个 tailnet 给出**同一个** 100.x 地址(不同 tailnet 的 CGNAT 网段可以重叠)
306
+ d.note({ app: "dsh-mesh", id: "dev", machine: "hos", host: "192.168.1.7", port: 45917 }, "100.64.0.9", {
307
+ transport: "tsnet",
308
+ channel: "tsnet:company",
309
+ });
310
+ const p = d.peers().find((x) => x.id === "dev");
311
+ assert.equal(p.endpoints.length, 3, `应有 lan + 两条 tailnet,实际 ${p.endpoints.length}`);
312
+ const keys = p.endpoints.map((e) => e.channel).sort();
313
+ assert.deepEqual(keys, ["lan", "tsnet:company", "tsnet:personal"]);
314
+
315
+ // 一条 tailnet 失败不该影响另一条
316
+ d.markEndpoint("dev", "tsnet:personal", { ok: false });
317
+ d.markEndpoint("dev", "tsnet:personal", { ok: false });
318
+ const after = d.peers().find((x) => x.id === "dev");
319
+ assert.equal(after.online, true, "company 通道还通,设备必须仍在线");
320
+ const company = after.endpoints.find((e) => e.channel === "tsnet:company");
321
+ assert.equal(company.downUntil, 0, "company 通道不应被 personal 的失败连坐");
322
+ });
323
+
324
+ check("多 tailnet:名片里的 tailnetIps 每个地址各记一条候选端点", () => {
325
+ const d = new MeshDiscovery({ id: "self-1", port: 45917, meta: { machine: "me" } });
326
+ d.note(
327
+ {
328
+ app: "dsh-mesh",
329
+ id: "dev",
330
+ machine: "hos",
331
+ host: "192.168.1.7",
332
+ port: 45917,
333
+ tailnetIps: ["100.64.0.9", "100.88.0.3"],
334
+ },
335
+ "192.168.1.7",
336
+ );
337
+ const p = d.peers().find((x) => x.id === "dev");
338
+ const cands = p.endpoints.filter((e) => e.candidate === true);
339
+ assert.equal(cands.length, 2, `应有两个候选地址,实际 ${cands.length}`);
340
+ assert.deepEqual(cands.map((e) => e.host).sort(), ["100.64.0.9", "100.88.0.3"]);
341
+ assert.ok(cands.every((e) => e.verified === false), "候选端点一律不算已验证");
342
+ assert.equal(p.online, true, "局域网端点仍然在线");
343
+ });
344
+
345
+ check("多 tailnet:老对端的单个 tailnetIp 仍能被识别", () => {
346
+ const d = new MeshDiscovery({ id: "self-1", port: 45917, meta: { machine: "me" } });
347
+ d.note({ app: "dsh-mesh", id: "dev", machine: "hos", host: "192.168.1.7", port: 45917, tailnetIp: "100.64.0.9" }, "192.168.1.7");
348
+ const p = d.peers().find((x) => x.id === "dev");
349
+ assert.equal(p.endpoints.filter((e) => e.transport === "tsnet").length, 1);
350
+ });
351
+
352
+ check("多 tailnet:快照恢复保留通道 key,不把两条 tailnet 合并成一条", () => {
353
+ const d = new MeshDiscovery({ id: "self-1", port: 45917, meta: { machine: "me" } });
354
+ d.restore([
355
+ {
356
+ record: { app: "dsh-mesh", id: "dev", machine: "hos", host: "192.168.1.7", port: 45917 },
357
+ endpoints: [
358
+ { channel: "lan", transport: "lan", host: "192.168.1.7", port: 45917, lastSeen: Date.now() },
359
+ { channel: "tsnet:a", transport: "tsnet", host: "100.64.0.9", port: 45917, lastSeen: Date.now() },
360
+ { channel: "tsnet:b", transport: "tsnet", host: "100.88.0.3", port: 45917, lastSeen: Date.now() },
361
+ ],
362
+ },
363
+ ]);
364
+ const p = d.peers().find((x) => x.id === "dev");
365
+ assert.equal(p.endpoints.length, 3, `恢复后应保留 3 条端点,实际 ${p.endpoints.length}`);
366
+ assert.equal(p.restored, true);
367
+ assert.ok(p.endpoints.some((e) => e.channel === "tsnet:b"));
368
+ });
369
+
370
+ check("多 tailnet:设备上的 tailnetIps 会随名片对外广播", () => {
371
+ const d = new MeshDiscovery({ id: "self-1", port: 45917, meta: { machine: "me" } });
372
+ d.setMeta({ tailnetIps: ["100.64.0.9", "100.88.0.3"] });
373
+ const rec = d.selfRecord();
374
+ assert.deepEqual(rec.tailnetIps, ["100.64.0.9", "100.88.0.3"]);
375
+ assert.equal(rec.tailnetIp, "100.64.0.9", "老字段要保留第一项,供老对端读取");
376
+ });
377
+
378
+ check("通道 id 只保留安全字符,空值落到 default", () => {
379
+ assert.equal(channelKey("Company Tailnet"), "company-tailnet");
380
+ assert.equal(channelKey("../../etc/passwd"), "etc-passwd");
381
+ assert.equal(channelKey(""), "default");
382
+ assert.equal(channelKey("!!!"), "default");
383
+ });
384
+
385
+ check("default 沿用旧目录,其它通道各自独立(身份不能共享)", () => {
386
+ const prev = process.env.DSH_HOME;
387
+ const home = mkdtempSync(join(tmpdir(), "mesh-selftest-channels-"));
388
+ process.env.DSH_HOME = home;
389
+ try {
390
+ const root = join(home, "mesh", "tsnet");
391
+ assert.equal(channelDir("default"), root, "default 必须是旧布局,升级不丢设备身份");
392
+ assert.equal(channelDir("company"), join(root, "company"));
393
+ assert.notEqual(channelStateDir("company"), channelStateDir("personal"));
394
+ assert.equal(channelStateDir("company"), join(root, "company", "state"));
395
+ } finally {
396
+ if (prev === undefined) delete process.env.DSH_HOME;
397
+ else process.env.DSH_HOME = prev;
398
+ rmSync(home, { recursive: true, force: true });
399
+ }
400
+ });
401
+
402
+ check("TsnetNode 暴露通道 id/label,且签名随授权码变化(不泄露明文)", () => {
403
+ const a = new TsnetNode({ channel: { id: "company", label: "公司", authKey: "tskey-auth-aaa", controlUrl: "", hostname: "" }, machineName: "mac" });
404
+ const b = new TsnetNode({ channel: { id: "company", label: "公司", authKey: "tskey-auth-bbb", controlUrl: "", hostname: "" }, machineName: "mac" });
405
+ assert.equal(a.channelKey, "company");
406
+ assert.equal(a.label, "公司");
407
+ assert.notEqual(a.signature, b.signature, "换授权码后必须判定为配置变更,否则会留在旧 tailnet");
408
+ assert.equal(a.signature.length, 12);
409
+ assert.ok(!a.signature.includes("tskey"), "签名里不能出现授权码明文");
410
+ // 旧调用方式(只传 config)仍然工作,并落到 default 通道
411
+ const legacy = new TsnetNode({ config: { tsnetAuthKey: "tskey-auth-ccc" }, machineName: "mac" });
412
+ assert.equal(legacy.channelKey, "default");
413
+ });
414
+
415
+ check("通道解析:配置优先于 state.json", () => {
416
+ const list = resolveTailnetChannels({
417
+ config: { tsnetChannels: [{ id: "corp", label: "公司", authKey: "k1", enabled: true }] },
418
+ state: { tsnetChannels: [{ id: "home", label: "家里", authKey: "k2", enabled: true }] },
419
+ });
420
+ assert.equal(list.length, 1);
421
+ assert.equal(list[0].id, "corp");
422
+ assert.equal(list[0].source, "config");
423
+ });
424
+
425
+ check("通道解析:没有通道列表时退回旧版单 key,并落到 default", () => {
426
+ const list = resolveTailnetChannels({ config: {}, state: { tsnetAuthKey: "tskey-auth-old", tsnetEnabled: true } });
427
+ assert.equal(list.length, 1);
428
+ assert.equal(list[0].id, "default");
429
+ assert.equal(list[0].legacy, true);
430
+ assert.equal(list[0].authKey, "tskey-auth-old");
431
+ assert.equal(list[0].enabled, true);
432
+ });
433
+
434
+ check("通道解析:没给 id 的通道按 label + 控制服务器推导稳定 id", () => {
435
+ const a = resolveTailnetChannels({ config: { tsnetChannels: [{ label: "公司", controlUrl: "https://hs.example" }] } });
436
+ const b = resolveTailnetChannels({ config: { tsnetChannels: [{ label: "公司", controlUrl: "https://hs.example" }] } });
437
+ assert.match(a[0].id, /^ch-[0-9a-f]{10}$/);
438
+ assert.equal(a[0].id, b[0].id, "同样的配置必须得到同一个 id(否则每次重启都重新注册设备)");
439
+ const renamed = resolveTailnetChannels({ config: { tsnetChannels: [{ label: "公司2", controlUrl: "https://hs.example" }] } });
440
+ assert.notEqual(renamed[0].id, a[0].id, "推导 id 依赖显示名,改名前必须显式固定 id(文档已注明)");
441
+ });
442
+
443
+ check("通道解析:重复 id 自动去重,不会共享 sidecar 状态目录", () => {
444
+ const list = resolveTailnetChannels({
445
+ config: {
446
+ tsnetChannels: [
447
+ { id: "dup", label: "A" },
448
+ { id: "dup", label: "B" },
449
+ ],
450
+ },
451
+ });
452
+ assert.equal(list.length, 2);
453
+ assert.notEqual(list[0].id, list[1].id);
454
+ });
455
+
456
+ check("通道解析:enabled 默认 true,显式 false 才停用", () => {
457
+ const list = resolveTailnetChannels({
458
+ config: {
459
+ tsnetChannels: [
460
+ { id: "a", label: "A" },
461
+ { id: "b", label: "B", enabled: false },
462
+ ],
463
+ },
464
+ });
465
+ assert.equal(list[0].enabled, true);
466
+ assert.equal(list[1].enabled, false);
467
+ });
468
+
297
469
  console.log("\n── 身份:指纹认领与冲突 ──");
298
470
 
299
471
  check("同指纹不同 instanceId → 认领为同一台(旧记录立刻淘汰)", () => {
@@ -123,6 +123,7 @@ const {
123
123
  TaskRow,
124
124
  TaskDetail,
125
125
  SettingsView,
126
+ Diagnostics,
126
127
  Composer,
127
128
  DispatchPanel,
128
129
  DeviceList,
@@ -384,6 +385,59 @@ test("主页把派发任务面板放在最底下(卡片之后)", () => {
384
385
  assert.ok(cardTail >= 0 && dispatch > cardTail, "派发面板应在卡片区之后");
385
386
  });
386
387
 
388
+ test("多 tailnet:两条通道各自显示状态与操作,页头汇总为 1/2 条", () => {
389
+ const channels = [
390
+ {
391
+ id: "ch-aaa",
392
+ label: "个人",
393
+ enabled: true,
394
+ authKeySaved: true,
395
+ controlUrl: "",
396
+ node: { phase: "running", hostname: "dsh-mac", selfIpv4: "100.64.0.9", selfDnsName: "dsh-mac.tailnet.ts.net", forwards: [], diagnostics: [] },
397
+ recentEvents: [],
398
+ },
399
+ {
400
+ id: "ch-bbb",
401
+ label: "公司",
402
+ enabled: true,
403
+ authKeySaved: true,
404
+ controlUrl: "https://hs.example",
405
+ node: { phase: "idle", hostname: "dsh-mac" },
406
+ recentEvents: [],
407
+ },
408
+ ];
409
+ const tsnet = { enabled: true, channels, node: channels[0].node, recentEvents: [] };
410
+ const body = textOf(TsnetBody({ tsnet, push: noop, reload: async () => {} })).join(" ");
411
+ assert.ok(body.includes("个人"), body.slice(0, 300));
412
+ assert.ok(body.includes("公司"), body.slice(0, 300));
413
+ assert.ok(body.includes("100.64.0.9"), "要显示每条通道自己的 tailnet 地址");
414
+ assert.ok(body.includes("断开"), "已连接的通道要能单独断开");
415
+ assert.ok(body.includes("连接"), "未连接的通道要能单独连接");
416
+ assert.ok(body.includes("ch-aaa"), "显示通道 id,便于区分同名/多条 tailnet");
417
+ assert.ok(body.includes("添加通道"), "要能继续添加通道");
418
+
419
+ const view = textOf(
420
+ SettingsView({ ...{ state: { ...state, tsnet } }, open: null, onOpen: noop, onSaveName: async () => true, nameBusy: false, push: noop, reload: async () => {} }),
421
+ ).join(" ");
422
+ assert.ok(view.includes("已连接 1/2 条"), view.slice(0, 400));
423
+ });
424
+
425
+ test("多 tailnet:全部断开时不再显示“已连接”,但仍列出通道", () => {
426
+ const tsnet = {
427
+ enabled: true,
428
+ channels: [
429
+ { id: "ch-aaa", label: "个人", enabled: true, authKeySaved: true, node: { phase: "exited" }, recentEvents: [] },
430
+ { id: "ch-bbb", label: "公司", enabled: false, authKeySaved: false, node: null, recentEvents: [] },
431
+ ],
432
+ };
433
+ const view = textOf(
434
+ SettingsView({ state: { ...state, tsnet }, open: "tsnet", onOpen: noop, onSaveName: async () => true, nameBusy: false, push: noop, reload: async () => {} }),
435
+ ).join(" ");
436
+ assert.ok(!view.includes("已连接 1/2"), view.slice(0, 400));
437
+ assert.ok(view.includes("个人"));
438
+ assert.ok(view.includes("公司"));
439
+ });
440
+
387
441
  console.log("\n── 视图里不再重复 tab 名 ──");
388
442
 
389
443
  /** 收集某个 class 上的可见文字,用来钉住「标题写了什么」。 */
@@ -419,6 +473,22 @@ test("任务页左栏只写条数,不重复「任务」", () => {
419
473
  assert.notEqual(titles[0], "任务");
420
474
  });
421
475
 
476
+ test("诊断卡显示「进程版本 / 磁盘版本」,漂移时说清要重启", () => {
477
+ const drift = {
478
+ self: { version: "0.5.2", diskVersion: "0.5.3", versionDrift: true, port: 45917 },
479
+ config: {},
480
+ peers: [],
481
+ };
482
+ const txt = textOf(Diagnostics({ state: drift, push: noop })).join(" ");
483
+ assert.ok(txt.includes("版本(进程)"), txt);
484
+ assert.ok(txt.includes("版本(磁盘)"), txt);
485
+ assert.ok(txt.includes("重启 DSH 后新版本才生效"), txt);
486
+
487
+ // 没漂移时不该吓人
488
+ const same = { self: { version: "0.5.2", diskVersion: "0.5.2", versionDrift: false }, config: {}, peers: [] };
489
+ assert.ok(!textOf(Diagnostics({ state: same, push: noop })).join(" ").includes("重启 DSH"));
490
+ });
491
+
422
492
  test("连接页不再重复写「连接」大标题", () => {
423
493
  const el = SettingsView({ state, open: null, onOpen: noop, onSaveName: async () => true, nameBusy: false, push: noop, reload: async () => {} });
424
494
  let h1 = 0;
@@ -428,6 +498,42 @@ test("连接页不再重复写「连接」大标题", () => {
428
498
  assert.equal(h1, 0, "tab 已经叫「连接」,正文不必再来一个 h1");
429
499
  });
430
500
 
501
+ console.log("\n── 系统身份(osInfo / systems / WSL)──");
502
+
503
+ const winPeer = {
504
+ ...peer,
505
+ os: "win32 10.0.22631",
506
+ osInfo: { platform: "win32", name: "Windows 11 Home China", version: "10.0.22631", distro: "", kernel: "10.0.22631", desktop: "", arch: "x64" },
507
+ systems: [
508
+ { kind: "host", platform: "win32", name: "Windows 11 Home China", version: "10.0.22631" },
509
+ { kind: "wsl", platform: "linux", name: "Ubuntu", version: "22.04", distro: "ubuntu" },
510
+ ],
511
+ capabilities: { ...peer.capabilities, wsl: [{ name: "Ubuntu", runtimes: { node: "22.1", python: "3.12" }, error: "" }] },
512
+ };
513
+
514
+ test("设备详情用结构化 osInfo(不再是 win32 10.0.xxx 这种机器串)", () => {
515
+ const txt = textOf(DeviceDetail({ peer: winPeer, now, onCompose: noop, onProbe: noop, onBack: noop })).join(" ");
516
+ assert.ok(txt.includes("Windows 11 Home China"), txt);
517
+ });
518
+
519
+ test("同一台机器上的 WSL 单独标出来,不混进宿主机", () => {
520
+ const txt = textOf(DeviceDetail({ peer: winPeer, now, onCompose: noop, onProbe: noop, onBack: noop })).join(" ");
521
+ assert.ok(txt.includes("WSL Ubuntu 22.04"), `应显示 WSL 发行版:${txt}`);
522
+ });
523
+
524
+ test("老对端(只有 os 字符串)不能崩,回退到 osLabel", () => {
525
+ const legacy = { ...peer, os: "linux 6.1", osInfo: null, systems: null, capabilities: { runtimes: {} } };
526
+ const txt = textOf(DeviceDetail({ peer: legacy, now, onCompose: noop, onProbe: noop, onBack: noop })).join(" ");
527
+ assert.ok(txt.includes("Linux"), txt);
528
+ });
529
+
530
+ test("能力 chip 里 WSL 运行时单独一行(Windows 的 Python ≠ WSL 的 Python)", () => {
531
+ const txt = textOf(CapabilityChips({ caps: winPeer.capabilities, peer: winPeer })).join(" ");
532
+ assert.ok(txt.includes("WSL"), txt);
533
+ assert.ok(txt.includes("Ubuntu"), txt);
534
+ assert.ok(txt.includes("node 22.1"), txt);
535
+ });
536
+
431
537
  console.log("\n── 图标:网段探测 vs 单机探测 ──");
432
538
 
433
539
  /** 收集组件树里所有按钮/图标按钮的 icon 名(含函数组件展开)。 */
@@ -23,9 +23,13 @@
23
23
  * 失败更糟,因为它看起来像正常的空数据。
24
24
  */
25
25
  import { execFile } from "node:child_process";
26
+ import { promisify } from "node:util";
26
27
  import { existsSync } from "node:fs";
27
28
  import { homedir, release, totalmem, cpus, platform, arch } from "node:os";
28
29
  import { join, delimiter } from "node:path";
30
+ import { wslTargets } from "./osinfo.js";
31
+
32
+ const execFileAsync = promisify(execFile);
29
33
 
30
34
  /** 重新采集的间隔。设计上低频:装了新运行时最迟 10 分钟后上名片。 */
31
35
  export const CAPABILITY_REFRESH_MS = 10 * 60 * 1000;
@@ -332,6 +336,85 @@ export async function collectRuntimes(specs = RUNTIMES) {
332
336
  return { runtimes, errors };
333
337
  }
334
338
 
339
+ /**
340
+ * 在 WSL 里探测运行时的 shell 片段。
341
+ *
342
+ * 命令是常量(来自 RUNTIMES),不拼接用户输入。每行输出 `名字<TAB>版本输出`;
343
+ * 没装的运行时不会出现在输出里。python 的 fallback 用 if/elif,避免 python3 与
344
+ * python 各打一行。
345
+ */
346
+ function wslProbeScript() {
347
+ return RUNTIMES.map((spec) => {
348
+ const cmds = [spec, spec.fallback].filter(Boolean);
349
+ const branches = cmds
350
+ .map(
351
+ (c, i) =>
352
+ `${i === 0 ? "if" : "elif"} command -v ${c.cmd} >/dev/null 2>&1; then ` +
353
+ `v=$(${c.cmd} ${c.args.join(" ")} 2>&1 | head -n 1); printf '%s\\t%s\\n' ${spec.name} "$v";`,
354
+ )
355
+ .join(" ");
356
+ return `${branches} fi`;
357
+ }).join("\n");
358
+ }
359
+
360
+ /**
361
+ * 探测运行中的 WSL 发行版里的运行时。
362
+ *
363
+ * 只探 `running` 的发行版:`wsl -d <name>` 对停着的发行版会把它启动起来,
364
+ * 为了看一眼版本付几十秒启动代价不值得。最多两个发行版,每个 8s 超时;
365
+ * 失败只记录短错误码,绝不抛(能力采集不能拖垮启动)。
366
+ *
367
+ * @returns [{ name, runtimes, error }]
368
+ */
369
+ export async function collectWslRuntimes({ platform: p = platform(), targets, run, timeoutMs = 8000 } = {}) {
370
+ if (p !== "win32") return [];
371
+ let list = targets;
372
+ if (!list) {
373
+ try {
374
+ list = wslTargets();
375
+ } catch {
376
+ return [];
377
+ }
378
+ }
379
+ const running = (list ?? []).filter((t) => t && t.running).slice(0, 2);
380
+ if (running.length === 0) return [];
381
+
382
+ const exec = run ?? ((cmd, args, opts) => execFileAsync(cmd, args, opts));
383
+ const script = wslProbeScript();
384
+
385
+ return Promise.all(
386
+ running.map(async (target) => {
387
+ try {
388
+ const { stdout } = await exec(
389
+ "wsl.exe",
390
+ ["-d", target.name, "-e", "sh", "-lc", script],
391
+ { timeout: timeoutMs, windowsHide: true, maxBuffer: 1 << 20 },
392
+ );
393
+ const runtimes = {};
394
+ for (const line of String(stdout ?? "").split("\n")) {
395
+ const tab = line.indexOf("\t");
396
+ if (tab <= 0) continue;
397
+ const name = line.slice(0, tab).trim().toLowerCase();
398
+ const version = parseVersion(line.slice(tab + 1));
399
+ if (name && version) runtimes[name] = version;
400
+ }
401
+ return {
402
+ name: target.name,
403
+ runtimes,
404
+ error: Object.keys(runtimes).length > 0 ? "" : "empty-output",
405
+ };
406
+ } catch (err) {
407
+ return {
408
+ name: target.name,
409
+ runtimes: {},
410
+ error: String(err?.code ?? err?.message ?? err).slice(0, 80),
411
+ };
412
+ }
413
+ }),
414
+ );
415
+ }
416
+
417
+
335
418
  /**
336
419
  * 探测失败的项里有没有"不确定"的(超时 / spawn 失败)。
337
420
  *
@@ -431,6 +514,8 @@ export const __normPathForCompare = normPathForCompare;
431
514
  /** 只为自测导出:原始 GPU 探测输出 —— 用来区分"这台机器没有显卡"和"解析器坏了"。 */
432
515
  export const __probeGpu = probeGpu;
433
516
  export const __isUncertain = isUncertain;
517
+ /** 只为自测导出:GPU 探测的候选链 —— 靠它钉住「Windows 先问 nvidia-smi」这个顺序。 */
518
+ export const __gpuProbeSpecs = gpuProbeSpecs;
434
519
  /** 只为自测导出:Store 别名目录的排除规则(Mac 上没有该目录,无法端到端复现)。 */
435
520
  export const __storeAliasDir = STORE_ALIAS_DIR;
436
521
  /** 只为自测导出:让自测能按判据反推 runtimesIncomplete 的期望值,而不是写死。 */
@@ -498,15 +583,30 @@ export function parseNvidiaGpu(text) {
498
583
  }
499
584
 
500
585
  /**
501
- * 从 powershell `Get-CimInstance Win32_VideoController` 的输出里取第一行型号。
586
+ * 虚拟显示驱动/远程桌面适配器的名字特征。
587
+ *
588
+ * 为什么需要它:`Get-CimInstance Win32_VideoController` 在多显卡机器上给出多行,
589
+ * 而 MuMu / GameViewer / Parsec / RDP / Hyper-V 这类虚拟适配器常常**排在真卡
590
+ * 前面**。原实现只取第一行,于是装了 3060 的机器会被名片报成
591
+ * "MuMuVMM Display Adapter" —— 真卡被藏起来,Placement 拿到的是假事实。
502
592
  *
503
- * 注意 `Name -join "\`n"` 在多显卡时给出多行;只取第一行是有意的 ——
504
- * 名片只报"有没有 GPU + 主卡型号",不报全部。
593
+ * 保守起见只匹配明确的虚拟/远程产品名;Intel/AMD 的核显是**真卡**,不排除。
594
+ */
595
+ const VIRTUAL_GPU =
596
+ /virtual|remote|parsec|gameviewer|mumu|vmware|virtualbox|hyper-?v|basic display|rdp|citrix|spacedesk|sunlogin|todesk|displaylink/i;
597
+
598
+ /**
599
+ * 从 powershell `Get-CimInstance Win32_VideoController` 的多行输出里挑真卡。
600
+ *
601
+ * 规则:跳过已知虚拟适配器,取第一条剩下的;全都像虚拟适配器时退回第一行
602
+ * (**不要**因此返回 null —— "只有虚拟显卡"是一台真机器的真实状态,退回第一行
603
+ * 至少让调用方看到它是什么)。
505
604
  */
506
605
  export function parseWindowsGpu(text) {
507
606
  const s = gpuText(text);
508
607
  if (s === null) return null;
509
- const name = s.split("\n").map((l) => l.trim()).filter(Boolean)[0] ?? "";
608
+ const names = s.split("\n").map((l) => l.trim()).filter(Boolean);
609
+ const name = names.find((n) => !VIRTUAL_GPU.test(n)) ?? names[0] ?? "";
510
610
  return name ? { present: true, name, vramMb: 0 } : null;
511
611
  }
512
612
 
@@ -520,26 +620,37 @@ export function parseWindowsGpu(text) {
520
620
  * ⚠️ 每个分支都必须读 `r.output`(runProbe 返回的是 `{output,error}`)。
521
621
  * 直接把 `r` 交给解析函数就是上面说的那个 bug。
522
622
  */
523
- /** 每个平台"怎么问 + 用哪个解析器"集中一张表:自测与生产共用同一条命令。 */
524
- function gpuProbeSpec(p = platform()) {
623
+ /**
624
+ * 每个平台"按什么顺序问 + 用哪个解析器"集中一张表:自测与生产共用同一张表。
625
+ *
626
+ * 返回的是**候选列表**而不是单个命令,因为 Windows 上要"先问准的、再问全的":
627
+ * · `nvidia-smi` 只报真 N 卡,还带显存,是最可信的一手;
628
+ * · `Win32_VideoController` 更全(核显/AMD 也有),但会把虚拟适配器排前面。
629
+ * 先跑前者、解析不出来再跑后者,就不会被虚拟适配器骗到。
630
+ */
631
+ function gpuProbeSpecs(p = platform()) {
632
+ const NV = {
633
+ cmd: "nvidia-smi",
634
+ args: ["--query-gpu=name,memory.total", "--format=csv,noheader,nounits"],
635
+ parse: parseNvidiaGpu,
636
+ };
525
637
  switch (p) {
526
638
  case "darwin":
527
- return { cmd: "system_profiler", args: ["SPDisplaysDataType"], parse: parseMacGpu };
639
+ return [{ cmd: "system_profiler", args: ["SPDisplaysDataType"], parse: parseMacGpu }];
528
640
  case "linux":
529
641
  case "android":
530
- return {
531
- cmd: "nvidia-smi",
532
- args: ["--query-gpu=name,memory.total", "--format=csv,noheader,nounits"],
533
- parse: parseNvidiaGpu,
534
- };
642
+ return [NV];
535
643
  case "win32":
536
- return {
537
- cmd: "powershell",
538
- args: ["-NoProfile", "-Command", "(Get-CimInstance Win32_VideoController).Name -join \"`n\""],
539
- parse: parseWindowsGpu,
540
- };
644
+ return [
645
+ NV,
646
+ {
647
+ cmd: "powershell",
648
+ args: ["-NoProfile", "-Command", "(Get-CimInstance Win32_VideoController).Name -join \"`n\""],
649
+ parse: parseWindowsGpu,
650
+ },
651
+ ];
541
652
  default:
542
- return null;
653
+ return [];
543
654
  }
544
655
  }
545
656
 
@@ -552,12 +663,19 @@ function gpuProbeSpec(p = platform()) {
552
663
  * 否则在有显卡的机器上永远绿、在 VM 上永远红(GitHub runner 上就是这么红的)。
553
664
  */
554
665
  async function probeGpu() {
555
- const spec = gpuProbeSpec();
556
- if (!spec) return { output: "", gpu: null };
557
- const r = await runProbe(spec.cmd, spec.args, GPU_TIMEOUT_MS);
558
- const output = r.output ?? "";
559
- if (!output) return { output: "", gpu: null };
560
- return { output, gpu: spec.parse(output) };
666
+ const specs = gpuProbeSpecs();
667
+ let output = "";
668
+ for (const spec of specs) {
669
+ const r = await runProbe(spec.cmd, spec.args, GPU_TIMEOUT_MS);
670
+ const out = r.output ?? "";
671
+ // 命令没装/超时 → 空输出,换下一条;不要因为"没装 nvidia-smi"就报"没有 GPU"。
672
+ if (!out) continue;
673
+ output = out;
674
+ const gpu = spec.parse(out);
675
+ // 解析出真卡就停;解析不出来继续问下一条更全的命令。
676
+ if (gpu) return { output, gpu };
677
+ }
678
+ return { output, gpu: null };
561
679
  }
562
680
 
563
681
  async function collectGpu() {
@@ -635,9 +753,10 @@ export function setCapabilitiesForTest(value) {
635
753
  * @param options.hints 额外的"常用目录"(插件传 config.workspaceRoot)
636
754
  */
637
755
  export async function collectCapabilities({ now = Date.now(), hints = [] } = {}) {
638
- const [rt, gpu] = await Promise.all([
756
+ const [rt, gpu, wsl] = await Promise.all([
639
757
  collectRuntimes().catch(() => ({ runtimes: {}, errors: { _: "collect-threw" } })),
640
758
  collectGpu().catch(() => null),
759
+ collectWslRuntimes().catch(() => []),
641
760
  ]);
642
761
  // 三种触发(对端 hos 逼出来的完整版):
643
762
  // ① 探测本身没给出结论(超时 / spawn 失败 / 抛异常)
@@ -667,6 +786,9 @@ export async function collectCapabilities({ now = Date.now(), hints = [] } = {})
667
786
  // 只看 `runtimes` 的投影时,"3 项没探到"和"8 项全没探到"长得一样。
668
787
  probeFailCount: probeFailCount(rt),
669
788
  gpu,
789
+ // WSL 发行版里的运行时(只探运行中的);一台 Windows 机器上"装了 Python"
790
+ // 可能指宿主机,也可能指 WSL 里 —— 分开报才不会被当成同一件事。
791
+ ...(wsl.length > 0 ? { wsl } : {}),
670
792
  workspaceHints: collectWorkspaceHints(hints),
671
793
  capabilitiesAt: now,
672
794
  };
@@ -781,6 +903,32 @@ export function sanitizeCapabilities(raw) {
781
903
  if (name) gpu = { present: raw.gpu.present !== false, name, vramMb: safeNum(raw.gpu.vramMb, 1 << 20) };
782
904
  }
783
905
 
906
+ const wsl = [];
907
+ if (Array.isArray(raw.wsl)) {
908
+ for (const item of raw.wsl.slice(0, 8)) {
909
+ if (!item || typeof item !== "object" || Array.isArray(item)) continue;
910
+ const name = safeStr(item.name, 32);
911
+ if (!name) continue;
912
+ const wslRuntimes = {};
913
+ let wslCount = 0;
914
+ const rawWslRuntimes =
915
+ item.runtimes && typeof item.runtimes === "object" && !Array.isArray(item.runtimes)
916
+ ? item.runtimes
917
+ : {};
918
+ for (const [k, v] of Object.entries(rawWslRuntimes)) {
919
+ if (wslCount >= 12) break;
920
+ const rtName = safeStr(k, 24).toLowerCase();
921
+ const rtVersion = safeStr(v, 16).replace(/[^0-9.]/g, "");
922
+ if (rtName && rtVersion) {
923
+ wslRuntimes[rtName] = rtVersion;
924
+ wslCount += 1;
925
+ }
926
+ }
927
+ wsl.push({ name, runtimes: wslRuntimes, error: safeStr(item.error, 80) });
928
+ if (wsl.length >= 2) break;
929
+ }
930
+ }
931
+
784
932
  const hints = Array.isArray(raw.workspaceHints)
785
933
  ? raw.workspaceHints.slice(0, 8).map((h) => safeStr(h, 40)).filter(Boolean)
786
934
  : [];
@@ -798,6 +946,8 @@ export function sanitizeCapabilities(raw) {
798
946
  // "8 项全没探到"是两回事)。旧对端没有这个字段 → 0(当作"没失败")。
799
947
  probeFailCount: safeNum(raw.probeFailCount, 64),
800
948
  gpu,
949
+ // 对端报来的 WSL 运行时同样要清洗:名字截断、版本只留数字和点、最多两个发行版。
950
+ ...(wsl.length > 0 ? { wsl } : {}),
801
951
  workspaceHints: hints,
802
952
  // 时间戳不能用 safeNum 的"非法即 0"——0 会让 capabilityAge 变成
803
953
  // "1970 年采的",也就是永远过期。非法就置 0 并在下面按"未知"处理。
@@ -843,6 +993,12 @@ export function describePeerCapabilities(peer) {
843
993
  ` 能力${marks.length ? `(${marks.join(";")})` : ""}:${specs.join(" / ") || "规格未知"}`,
844
994
  ` 运行时:${summarizeCapabilities(caps) || "(未探到)"}`,
845
995
  ];
996
+ for (const w of caps.wsl ?? []) {
997
+ const detail = Object.entries(w.runtimes ?? {})
998
+ .map(([name, ver]) => `${name} ${ver}`)
999
+ .join("、");
1000
+ lines.push(` WSL ${w.name}:${detail || "(未探到)"}`);
1001
+ }
846
1002
  if (caps.workspaceHints?.length) lines.push(` 常用目录:${caps.workspaceHints.join(" ")}`);
847
1003
  if (caps.capabilitiesAt) {
848
1004
  lines.push(` 采集于 ${new Date(caps.capabilitiesAt).toISOString().slice(0, 16).replace("T", " ")} UTC`);