dsh-clash-subscription 0.11.0 → 0.13.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.
@@ -0,0 +1,156 @@
1
+ # 0.13.0 · 测速只剩两个按钮,而且测速就带可用性
2
+
3
+ > 上一版 `0.12.0` · 本版 `0.13.0`
4
+
5
+ ## 症状
6
+
7
+ 面板上一个横排四个按钮:**立即重测**、**测全部节点**、**立刻检测当前节点**、**按能力重挑节点**。
8
+
9
+ 四个里三个都叫「测」,但干的事不一样:
10
+
11
+ - 点「立即重测」,节点列表里的延迟数字变了,**可用 / 限流 / 受限 却一动不动**——想看一眼某个节点到底是慢还是坏,得再点另一个按钮。
12
+ - 「立刻检测当前节点」和「按能力重挑节点」听起来是两件事,实际都落到同一轮真实探测上,区别只在切不切节点。
13
+ - 用户得先记住「哪个按钮会写哪一列」,否则看到的是半张表。
14
+
15
+ 这四行字背后的真实问题是:**同一个「测」字被三条不同的测量代码路径实现了**,而其中只有一条会把结论写进列表。
16
+
17
+ ## 根因:`nodeDelays()` 拿不到可用性
18
+
19
+ 面板表格的两列来自两个不同的地方:
20
+
21
+ | 列 | 来源 | 谁写 |
22
+ |---|---|---|
23
+ | 延迟 | `runtime.measured` | `nodeDelays()`、`healthRound()`、`runSurveyTick()` |
24
+ | 可用 / 限流 / 受限 | `runtime.healthRows` | **只有** `healthRound()`、`switchAfterStrikes()`、`runSurveyTick()` |
25
+
26
+ 而「立即重测」走的 `nodeDelays()`,每节点调的是:
27
+
28
+ ```js
29
+ // lib/core.js · 0.12.0
30
+ async capabilities(name, probes, options) → { [probeId]: 毫秒数 | null }
31
+ ```
32
+
33
+ **纯数字**。没有 `state`、没有 `ok`、没有 `reason`——`judgeNodeHealth()` 要的东西一个都没有。所以这条路径天生只能写延迟,`healthRows` 从头到尾没被碰过:
34
+
35
+ ```js
36
+ // index.js · 0.12.0 nodeDelays()
37
+ this.measured = measured
38
+ this.lastMatrix = [...capability.values()]
39
+ this.measuredAt = Date.now()
40
+ return Object.fromEntries(measured) // 到此为止,healthRows 一行都没写
41
+ ```
42
+
43
+ 要拿到三态,必须走真实探针那套:`core.probeNodeReal()` / `core.realMatrix()` 返回的是
44
+ `{ id, state, ok, reason, ms, status, remaining, resetAt }`,再由 `judgeNodeHealth()` 汇总成
45
+ `{ usable, degraded, limited, blocked, failed }`。
46
+
47
+ ## 改法一:面板只留两个按钮
48
+
49
+ ```
50
+ 当前节点测试 → action=test { current: true } 测正在跑流量的那个节点
51
+ 全部节点测试 → action=test { all: true } 测订阅里的每一个节点
52
+ ```
53
+
54
+ 「立刻检测当前节点」与「按能力重挑节点」两个按钮一起删掉,MCP 工具的 `action=health` /
55
+ `action=reselect` 也一起下线(HTTP 路由里两个分支整段删除,现在传这两个动作会得到
56
+ `400 unknown action`)。
57
+
58
+ 删的是**入口**,不是能力:
59
+
60
+ - `healthRound()` 保留——自动测速这一轮就是它,删了定时器就没了。
61
+ - `autoReselect()` 保留——它是 `healthRound({force:true})` 的薄包装,历史测试直接断言它。
62
+ - `describeHealth()` 保留——报告渲染还在用。
63
+
64
+ ## 改法二:新增 `testNodes()`,一次测出延迟和结论
65
+
66
+ 两个按钮共用一个入口,`Runtime.testNodes(options)`:
67
+
68
+ ```js
69
+ const plan = this.probePlan() // { probes, gating, specs }
70
+ const matrix = await this.core.realMatrix({
71
+ nodes, // 当前节点 / 指定节点 / 全部
72
+ specs: plan.specs,
73
+ gating: plan.gating,
74
+ delays: this.measured, // 已知延迟的先用,快的排前面
75
+ budgetMs, // min(selectBudgetMs, 300 s)
76
+ timeoutMs: this.config.probeTimeoutMs ?? 8000,
77
+ })
78
+ for (const row of matrix.rows) {
79
+ this.healthRows.set(row.name, { results: row.results, verdict: row.verdict, at })
80
+ const fastest = Math.min(...Object.values(row.results).filter(r => r?.ok === true && typeof r?.ms === 'number').map(r => r.ms))
81
+ if (Number.isFinite(fastest)) this.measured.set(row.name, fastest)
82
+ }
83
+ const rows = this.buildRealRows(nodes) // 和 status 用的是同一个映射
84
+ return { state: 'ok', rows, tested, skipped, total, summary: summariseRows(rows) }
85
+ ```
86
+
87
+ 三个刻意的选择:
88
+
89
+ 1. **串行,不是并发。** `probeNodeReal()` 先 `selectProbe(name)` 把 `PROBE` 组指到某个节点,
90
+ 而 `PROBE` 组同一时刻只能指一个——并发测就是在互相抢指针,测出来的结论会串。所以这里
91
+ 和 `runSurveyTick()` 一样串行跑,用预算而不是并发控制时长。
92
+ 2. **延迟不再单独测一遍。** `realMatrix` 已经把 gating 探针都跑完了,每一行都带着
93
+ `ms`;再从这些结果里取最快的一次当延迟,等于省掉一次完整的 `delay()` 往返。
94
+ 3. **写的是 `buildRealRows()`。** 面板读 `status.nodeRows.rows`,那是 `buildRealRows()` 的输出;
95
+ 测完直接用它组装返回,面板看到的形状和它轮询拿到的一模一样,不会出现「测的时候有、刷新后没了」。
96
+
97
+ ## 自动测速没有改,因为它本来就是对的
98
+
99
+ 需求是「发现当前节点有问题,立即连测三次,不受间隔限制,三次都有问题就切走」。
100
+ `healthRound()` 从 0.11.0 起就是这么写的:
101
+
102
+ ```js
103
+ const attempts = Math.max(1, Number(this.config.healthAttempts ?? 3)) // 默认 3
104
+ for (let attempt = 1; attempt <= attempts; attempt += 1) {
105
+ const measured = await this.measureNode(current, plan) // 三次之间没有任何定时器
106
+ if (clean === true) return report // 一次干净就结束
107
+ }
108
+ return await this.switchAfterStrikes(report, plan, options) // 三次都不干净才找替代
109
+ ```
110
+
111
+ 这一次只补了**断言**:`test/regression-0130.mjs` 第 6 节用一个假内核记录每次调用的时间戳,
112
+ 然后断言 `attempts.length === 3` 且相邻两次间隔 `< 200 ms`(实测 0,0 ms)——把
113
+ 「不受间隔限制」这句话变成可复跑的判据,而不是继续写在注释里。
114
+
115
+ ### 预算:真机上 50 多个节点测不完怎么办
116
+
117
+ 「全部节点测试」是**串行真探针**,一个节点要跑 gstatic / GitHub / git 三条真实请求,
118
+ 失败还要退避重试。真机实测:订阅 55 个节点、其中大部分是死节点,45 秒预算只测完 4 个。
119
+ 所以 `testNodes()` 的返回里既有 `rows`(整张表,没测到的显示「未测」),也有 `skipped`
120
+ (这一轮预算没轮到的节点名)。**没测到不等于坏**,面板显示「未测」,不会当成不可用。
121
+
122
+ 延迟不用等这一轮:`/clash-proxy/status` 发现 `measured` 为空时会在后台补一次
123
+ `nodeDelays()`,那是廉价的健康检查通道,几秒就能把能应答的节点延迟填上。所以「全部节点
124
+ 测试」跑完的观感是:测过的节点带三态结论,其余节点先有延迟、结论仍是「未测」。
125
+
126
+ ## 验收
127
+
128
+ `test/regression-0130.mjs`(55 assertions,全绿)分八节:
129
+
130
+ | 节 | 断言的是什么 |
131
+ |---|---|
132
+ | 1 | `{current:true}` 只把当前节点交给矩阵,延迟取最快的那次(120,而不是 180),`healthRows` / `measured` 都写 |
133
+ | 2 | `{all:true}` 三态各自归位(ok / limited / blocked),**受限的节点也带延迟**,`summary` 各计 1 |
134
+ | 3 | `only` 指定节点、不存在的名字回 `no-node`、并发时回 `in-flight`、内核没跑回 `core-not-running` |
135
+ | 4 | 走真实路由:`test+current` 回整份 `rows`(不只是 delays);`health` / `reselect` 得到 `400 unknown action` |
136
+ | 5 | 走真实工具:enum 里没有 health / reselect,`action=test` 的 summary 是「名字 N ms:可用」 |
137
+ | 6 | 自动轮:A 连败三次后切到 B,三次间隔 0,0 ms |
138
+ | 7 | 面板源码:正好两个测速按钮(current + all),中英文案,四个旧键删干净 |
139
+ | 8 | 插件自带技能:不再教 `action=health`,改成 `action=test` |
140
+
141
+ 另外四套旧回归复跑:`regression-0120` 27 / `regression-070` 134 / `regression-0100` 48 /
142
+ `regression-063` 29,全部 0 failed。`test/e2e-0130.mjs`(真内核 + 真订阅):当前节点测出
143
+ 真实延迟与三态,全部节点测出多行,`status.nodeRows` 拿到的就是这些行。
144
+
145
+ ## 影响面
146
+
147
+ - **面板**:四个按钮变两个;设置页与节点行内的 ⟳ 不变。
148
+ - **MCP 工具**:`clash_proxy` 的 `action` 少了 `health` 与 `reselect`;`action=test` 现在回
149
+ `{ rows, tested, skipped, total, summary }`,不再只是 `{ delays }`。原来读 `delays` 的调用方
150
+ 改读 `rows`(每行 `{ name, delay, usable }`)。
151
+ - **HTTP 路由**:`POST /clash-proxy/action` 的 `test` 支持 `current` / `all` / `node` 三种范围。
152
+ - **配置**:没有新增键,升级不需要改配置。
153
+
154
+ ## 升级
155
+
156
+ 装完要**完全退出 DSH 再打开**——宿主进程里跑的是旧模块,面板不会自己变。
package/README.md CHANGED
@@ -68,6 +68,16 @@ name — two providers routinely both name a node `香港01`, and without a pref
68
68
  duplicate names. A provider that fails to download shows `未拉到节点` on its own row and does
69
69
  not stop the others.
70
70
 
71
+ **Checks and downloads go direct.** The plugin installs itself as the process-wide outbound
72
+ policy, so a plain `fetch` — including this plugin's own subscription check — would travel
73
+ through a node. For the subscription link that is backwards: a dead or rate-limited node would
74
+ make a live link look broken, checking a link would spend the quota of the node it is meant to
75
+ evaluate, and the same link could report differently a minute apart. So the check carries its
76
+ own undici `dispatcher` (`lib/direct.js`), the same per-request override undici resolves
77
+ before the global one, and each core provider is written with `proxy: DIRECT` rather than
78
+ relying on the core's unwritten default. Business traffic still goes through the node; only
79
+ the link that supplies the nodes does not.
80
+
71
81
  ## Split routing
72
82
 
73
83
  | Destination | Path |
@@ -190,8 +200,8 @@ Settings → **Clash proxy**:
190
200
 
191
201
  - live state: endpoint, whether the policy is installed, and whether it is actually healthy
192
202
  - one row per subscription: name, node count, last fetch time, its own refresh button
193
- - exit-node table with per-node latency (not measured / measured / no answer)
194
- - a multi-line subscription editor with **检测全部** reporting every line
203
+ - exit-node table with per-node **latency and usability** (可用 / 限流 / 受限 / 未测), written by whichever test ran last
204
+ - exactly **two** test buttons: **当前节点测试** (the node carrying traffic) and **全部节点测试** (the whole subscription). Both measure latency *and* usability in one pass, and both write what they measured into the node table — there is no separate "check health" or "re-pick by capability" button any more
195
205
  - when no core is present: a **下载内核** button, with the download's progress and outcome
196
206
 
197
207
  ## Tool
@@ -204,7 +214,7 @@ Settings → **Clash proxy**:
204
214
  | `import` | `url` (one or more lines) replaces the list; `append: true` adds. Probes, **saves**, restarts |
205
215
  | `bootstrap` | Download and verify a core when this platform has no bundled one |
206
216
  | `start` / `stop` | Bring routing up (unpacking the bundled core if needed) / return to direct |
207
- | `select` / `test` | Switch the exit node / measure latency |
217
+ | `select` / `test` | Switch the exit node / measure **latency and usability** for the current node, one named node (`node`), or every node. The result is what the panel table shows |
208
218
  | `refresh` | Re-download every subscription |
209
219
 
210
220
  ## HTTP routes
package/client.js CHANGED
@@ -19,6 +19,7 @@ const en = {
19
19
  probeOk: 'All {total} subscriptions reachable: {count} nodes, {size} KB.',
20
20
  probePartial: '{reachable}/{total} subscriptions reachable — see the rows below.',
21
21
  probeFailed: 'Check failed: {reason}',
22
+ probeViaProxy: 'Direct fetch was unavailable, so this check went through the installed proxy.',
22
23
  probeNeedsSave: 'Save first — this page writes the links, the running core reads the saved ones.',
23
24
  subscriptions: 'Subscriptions',
24
25
  subscriptionCount: '{count} configured',
@@ -35,11 +36,11 @@ const en = {
35
36
  noNodes: 'No node table yet — start routing first.',
36
37
  select: 'Use',
37
38
  testing: 'Measuring…',
38
- testNow: 'Re-test now',
39
+ testNow: 'Test current node',
39
40
  delay: '{ms} ms',
40
41
  unreachable: 'no answer',
41
42
  untested: 'not measured',
42
- testAll: 'Measure every node',
43
+ testAll: 'Test all nodes',
43
44
  cycle: 'Automatic speed test',
44
45
  cycleHint:
45
46
  'How often the plugin re-measures its nodes and picks a working exit. 0 turns the cycle off; the button above still works.',
@@ -75,8 +76,6 @@ const en = {
75
76
  blockedTag: 'blocked',
76
77
  blockedCount: '{count} nodes hidden',
77
78
  blockedInvalid: 'Invalid regex, not applied:',
78
- reselect: 'Re-pick node by capability',
79
- reselecting: 'Testing nodes…',
80
79
  chosenNode: 'Chosen: {node}',
81
80
  noUsableNode: 'No node reached every required service.',
82
81
  usableCount: '{usable} / {total} nodes usable',
@@ -132,8 +131,6 @@ const en = {
132
131
  limitedNote: '{count} limited, {blocked} blocked',
133
132
  healthRoundNote: 'Every {every}s · last round {state} at {latency} ms (ceiling {ceiling} ms) · streak {strikes}/{limit}',
134
133
  lastSwitchNote: 'Switched {from} → {to} at {time}',
135
- runHealth: 'Check the live node now',
136
- healthRunning: 'Checking the live node…',
137
134
  healthOff: 'Health watch off',
138
135
  readOnly: 'This panel is read-only here; open it from Settings to edit.',
139
136
  }
@@ -153,6 +150,7 @@ const zh = {
153
150
  probeOk: '全部 {total} 条可达:共 {count} 个节点,{size} KB。',
154
151
  probePartial: '{reachable}/{total} 条可达——看下面的逐条结果。',
155
152
  probeFailed: '检测失败:{reason}',
153
+ probeViaProxy: '直连不可用,这次检测走了已安装的代理。',
156
154
  probeNeedsSave: '先保存——这个面板写的是配置,跑着的内核读的是已保存的那份。',
157
155
  subscriptions: '订阅列表',
158
156
  subscriptionCount: '已配置 {count} 条',
@@ -169,11 +167,11 @@ const zh = {
169
167
  noNodes: '还没有节点表——先启动一次。',
170
168
  select: '用这个',
171
169
  testing: '测速中…',
172
- testNow: '立即重测',
170
+ testNow: '当前节点测试',
173
171
  delay: '{ms} ms',
174
172
  unreachable: '无响应',
175
173
  untested: '未测速',
176
- testAll: '测全部节点',
174
+ testAll: '全部节点测试',
177
175
  cycle: '自动测速',
178
176
  cycleHint: '插件多久重新测一次节点并挑一个可用的出口。填 0 关闭周期,上面的按钮仍然可用。',
179
177
  cycleOff: '关闭',
@@ -230,8 +228,6 @@ const zh = {
230
228
  limitedNote: '{count} 个限流,{blocked} 个不通',
231
229
  healthRoundNote: '每 {every} 秒 · 最近一轮 {state},{latency} ms(阈值 {ceiling} ms)· 连续 {strikes}/{limit}',
232
230
  lastSwitchNote: '已于 {time} 从「{from}」切到「{to}」',
233
- runHealth: '立刻检测当前节点',
234
- healthRunning: '正在检测当前节点…',
235
231
  healthOff: '可用性监视已关闭',
236
232
  blockedEmpty: '还没有节点清单——先启动一次,这里就会出现可勾选的节点。',
237
233
  blockedSearch: '筛选节点…',
@@ -242,8 +238,6 @@ const zh = {
242
238
  blockedApplied: '已应用',
243
239
  blockedStale: '订阅里已没有',
244
240
  blockedPick: '勾选屏蔽(图形化)',
245
- reselect: '按能力重挑节点',
246
- reselecting: '正在测节点…',
247
241
  chosenNode: '已选:{node}',
248
242
  noUsableNode: '没有任何节点能访问全部必需服务。',
249
243
  usableCount: '{usable} / {total} 个节点可用',
@@ -687,6 +681,7 @@ function Panel(props) {
687
681
  : fill(t('probePartial'), { reachable: answer.reachable ?? 0, total: answer.total ?? results.length })
688
682
  return h('div', { key: 'pr', className: 'clxp-probe', role: 'status' }, [
689
683
  h('p', { key: 'h', className: answer.ok ? 'clxp-ok' : 'clxp-error' }, headline),
684
+ ...(answer.direct === false ? [h('p', { key: 'd', className: 'clxp-note' }, t('probeViaProxy'))] : []),
690
685
  ...results.map((row) =>
691
686
  h('p', { key: `r-${row.provider ?? row.url}`, className: row.ok ? 'clxp-note' : 'clxp-error' }, [
692
687
  h('span', { key: 'n' }, `${row.name ?? row.url}:`),
@@ -872,11 +867,13 @@ function Panel(props) {
872
867
  }, name === live?.node ? '✓' : t('select')),
873
868
  ])
874
869
  })),
870
+ // Exactly two ways to measure: the node carrying traffic, and the whole subscription.
871
+ // Both answer latency AND usability, because a fast node that cannot reach a required
872
+ // service is not a working node -- the two used to be separate buttons and separate
873
+ // measurements, which is how a list could show "120 ms" beside "blocked".
875
874
  h('div', { key: 'ac', className: 'clxp-actions' }, [
876
- h('button', { key: 'te', type: 'button', disabled: busy !== '' || !running, onClick: () => void props.onAction('test') }, busy === 'test' ? t('testing') : t('testNow')),
877
- h('button', { key: 'ta', type: 'button', disabled: busy !== '' || !running, onClick: () => void props.onAction('test', { all: true }) }, busy === 'test' ? t('testing') : t('testAll')),
878
- h('button', { key: 'hl', type: 'button', disabled: busy !== '' || !running, onClick: () => void props.onAction('health') }, busy === 'health' ? t('healthRunning') : t('runHealth')),
879
- h('button', { key: 'rs', type: 'button', className: 'clxp-primary', disabled: busy !== '' || !running, onClick: () => void props.onAction('reselect') }, busy === 'reselect' ? t('reselecting') : t('reselect')),
875
+ h('button', { key: 'te', type: 'button', disabled: busy !== '' || !running, onClick: () => void props.onAction('test', { current: true }) }, busy === 'test' ? t('testing') : t('testNow')),
876
+ h('button', { key: 'ta', type: 'button', className: 'clxp-primary', disabled: busy !== '' || !running, onClick: () => void props.onAction('test', { all: true }) }, busy === 'test' ? t('testing') : t('testAll')),
880
877
  ]),
881
878
  // What the automatic switch is doing: armed or not, the live node's streak, and the last
882
879
  // switch it performed. Without this the panel shows a limited node and no reason it is
package/index.js CHANGED
@@ -28,6 +28,7 @@ import { readInventory, rememberNodes } from './lib/inventory.js'
28
28
  import { summariseRows } from './lib/health.js'
29
29
  import { installName, loadHttpProxyModule, locateInstallRoot, resolveFromInstall } from './lib/install.js'
30
30
  import { Routing } from './lib/routing.js'
31
+ import { DirectLine } from './lib/direct.js'
31
32
  import {
32
33
  displayName,
33
34
  effectiveSubscriptionText,
@@ -351,6 +352,16 @@ export class Runtime {
351
352
  this.binary = findCoreBinary(config.corePath, this.dataDir)
352
353
  this.core = this.binary === undefined ? undefined : new Core({ binary: this.binary, workDir: this.dataDir, logger })
353
354
  this.routing = undefined
355
+ /**
356
+ * The direct line subscription checks use.
357
+ *
358
+ * Built on first use: an installation whose `undici` cannot be resolved must still
359
+ * open the panel, report, and fall back to the installed policy rather than failing
360
+ * to load.
361
+ */
362
+ this.directLine = undefined
363
+ /** Why that line could not be built, so the panel can say which path it took. */
364
+ this.directError = undefined
354
365
  this.lastError = undefined
355
366
  this.lastProbe = undefined
356
367
  /** Result of the last core download, for the panel and the tool. */
@@ -399,6 +410,12 @@ export class Runtime {
399
410
  this.healthTimer = undefined
400
411
  /** True while a round is running, so two ticks cannot overlap. */
401
412
  this.healthRunning = false
413
+ /** True while a survey matrix is running, so a manual test cannot share the PROBE group. */
414
+ this.switching = false
415
+ /** True while a manual test matrix is running. */
416
+ this.testing = false
417
+ /** Last manual test, so the panel can say when it ran and what it covered. */
418
+ this.lastTest = undefined
402
419
  /** What the last automatic switch did, for the panel. */
403
420
  this.lastSwitch = undefined
404
421
  /** Persistence hook, set by `apply` from the config editor; undefined when the profile has none. */
@@ -491,6 +508,81 @@ export class Runtime {
491
508
  return Object.fromEntries(measured)
492
509
  }
493
510
 
511
+ /**
512
+ * Measure nodes for latency AND usability in one pass, writing both into the tables that
513
+ * `status()` renders from.
514
+ *
515
+ * The panel offers exactly two buttons and both answer the whole question. Latency alone is
516
+ * not an answer: a node that replies in 120 ms but cannot reach a required service is
517
+ * broken, and measuring the two halves in different code paths is what let the list show a
518
+ * fast number beside a failing verdict with nothing connecting them.
519
+ *
520
+ * The matrix runs one node at a time on purpose: the core decides the exit per connection,
521
+ * so the PROBE listener can only carry one selection at a time.
522
+ *
523
+ * @param options - `current` measures the selected node; `only` measures one named node;
524
+ * no option measures every node.
525
+ * @returns `{ state, rows, tested, skipped, total, summary }`.
526
+ */
527
+ async testNodes(options = {}) {
528
+ if (this.core === undefined || this.core.running !== true) return { state: 'core-not-running', rows: [] }
529
+ if (this.healthRunning === true || this.switching === true) return { state: 'busy', rows: [] }
530
+ if (this.testing === true) return { state: 'in-flight', rows: [] }
531
+ this.testing = true
532
+ try {
533
+ const plan = this.probePlan()
534
+ if (plan.specs.length === 0) return { state: 'no-probes', rows: [] }
535
+ const group = await this.core.group()
536
+ const live = group.all.filter((name) => name !== 'DIRECT')
537
+ const only = options.only === undefined ? '' : String(options.only).trim()
538
+ let nodes
539
+ if (only !== '') nodes = live.includes(only) ? [only] : []
540
+ else if (options.current === true) nodes = group.now === undefined || group.now === 'DIRECT' ? [] : [group.now]
541
+ else nodes = live
542
+ if (nodes.length === 0) return { state: 'no-node', rows: [] }
543
+
544
+ const budgetMs = Math.max(5_000, Math.min(Number(this.config.selectBudgetMs ?? 90_000), 300_000))
545
+ const matrix = await this.core.realMatrix({
546
+ nodes,
547
+ specs: plan.specs,
548
+ gating: plan.gating,
549
+ delays: this.measured,
550
+ budgetMs,
551
+ timeoutMs: this.config.probeTimeoutMs ?? 8000,
552
+ })
553
+
554
+ const at = Date.now()
555
+ const measured = new Map(this.measured)
556
+ for (const row of matrix.rows) {
557
+ this.healthRows.set(row.name, { results: row.results, verdict: row.verdict, at })
558
+ // Latency reuses the gating probes that just ran: either number is a real round trip
559
+ // through this node, and measuring again would double the cost for the same answer.
560
+ let fastest
561
+ for (const result of Object.values(row.results)) {
562
+ if (result?.ok === true && typeof result.ms === 'number' && (fastest === undefined || result.ms < fastest)) {
563
+ fastest = result.ms
564
+ }
565
+ }
566
+ if (fastest !== undefined) measured.set(row.name, fastest)
567
+ }
568
+ this.measured = measured
569
+ this.measuredAt = at
570
+ this.lastMatrix = matrix.rows.map((row) => ({ name: row.name, results: row.results }))
571
+ this.lastTest = { at, tested: matrix.tested, skipped: matrix.skipped, total: nodes.length }
572
+ const rows = this.buildRealRows(nodes)
573
+ return {
574
+ state: 'ok',
575
+ rows,
576
+ tested: matrix.tested,
577
+ skipped: matrix.skipped,
578
+ total: nodes.length,
579
+ summary: summariseRows(rows),
580
+ }
581
+ } finally {
582
+ this.testing = false
583
+ }
584
+ }
585
+
494
586
  /** Record a node the user picked, so a restart keeps it without a config edit. */
495
587
  rememberNode(name) {
496
588
  this.config.node = name
@@ -1135,8 +1227,8 @@ export class Runtime {
1135
1227
  }
1136
1228
 
1137
1229
  /**
1138
- * Re-check the current node on demand, as `clash_proxy action=reselect` and the panel's
1139
- * button do.
1230
+ * Re-check the current node on demand, as `clash_proxy action=test` and the panel's
1231
+ * current-node button do.
1140
1232
  *
1141
1233
  * This is the manual entry point now, not a second timer: the scheduled work all lives in
1142
1234
  * `healthRound`, so a manual reselect runs one round with `force` and reports the same shape.
@@ -1422,10 +1514,15 @@ export class Runtime {
1422
1514
  return { ok: false, error: parsed.errors[0]?.reason ?? 'no subscription URL found', errors: parsed.errors }
1423
1515
  }
1424
1516
  try {
1425
- const report = await probeSubscriptions(parsed.entries, { timeoutMs: 15_000 })
1517
+ // The link is what supplies the nodes, so it is checked directly: a node that is
1518
+ // down or rate-limited must not make a live link look unreachable, and the answer
1519
+ // must not change just because a different node happened to be selected.
1520
+ const direct = await this.probeFetch()
1521
+ const report = await probeSubscriptions(parsed.entries, { timeoutMs: 15_000, fetch: direct })
1426
1522
  return {
1427
1523
  ...report,
1428
1524
  ok: report.ok,
1525
+ direct: direct !== undefined,
1429
1526
  maskedUrls: this.maskList(parsed.entries),
1430
1527
  errors: parsed.errors,
1431
1528
  error: report.ok
@@ -1436,12 +1533,58 @@ export class Runtime {
1436
1533
  .join('; '),
1437
1534
  }
1438
1535
  } catch (error) {
1439
- // The probe runs through whatever policy is installed, so a failure here may
1440
- // mean "not routed yet" rather than "wrong URL"; say which.
1536
+ // The check is direct, so a failure here is about the link's own reachability from
1537
+ // this machine (DNS, a firewall, a certificate) rather than "no node is selected".
1441
1538
  return { ok: false, error: `probe failed: ${String(error?.message ?? error)}` }
1442
1539
  }
1443
1540
  }
1444
1541
 
1542
+ /**
1543
+ * The fetch a subscription check must use: direct, never through a node.
1544
+ *
1545
+ * Returns undefined when the installation has no resolvable `undici`, so the check
1546
+ * falls back to the installed policy instead of failing outright — and says so,
1547
+ * rather than reporting a working link as unreachable.
1548
+ *
1549
+ * @returns the bound direct fetch, or undefined to use the global one.
1550
+ */
1551
+ async probeFetch() {
1552
+ const line = await this.ensureDirectLine()
1553
+ if (line === undefined) return undefined
1554
+ try {
1555
+ return await line.connect()
1556
+ } catch (error) {
1557
+ this.directError = String(error?.message ?? error)
1558
+ this.log(`direct line unavailable, checks use the installed policy: ${this.directError}`)
1559
+ return undefined
1560
+ }
1561
+ }
1562
+
1563
+ /**
1564
+ * Build the direct line once, or report why it cannot exist here.
1565
+ *
1566
+ * @returns the line, or undefined when this install cannot supply undici.
1567
+ */
1568
+ async ensureDirectLine() {
1569
+ if (this.directLine !== undefined) return this.directLine
1570
+ if (this.installRoot === undefined) {
1571
+ this.directError =
1572
+ `cannot locate the dsh installation root: no known layout matched process.argv or ${process.execPath}; set DSH_INSTALL_ROOT to the directory holding the dsh package.json`
1573
+ return undefined
1574
+ }
1575
+ try {
1576
+ const undiciPath = resolveFromInstall(this.installRoot, 'undici')
1577
+ const connectTimeoutMs = Math.max(5_000, Number(this.config.probeTimeoutMs) || 20_000)
1578
+ this.directLine = new DirectLine({ undiciPath, logger: this.log, connectTimeoutMs })
1579
+ this.directError = undefined
1580
+ return this.directLine
1581
+ } catch (error) {
1582
+ this.directError = String(error?.message ?? error)
1583
+ this.log(`direct line unavailable, checks use the installed policy: ${this.directError}`)
1584
+ return undefined
1585
+ }
1586
+ }
1587
+
1445
1588
  /** The subscription to use. There is no fallback: an empty value means unconfigured. */
1446
1589
  get subscriptionUrl() {
1447
1590
  return effectiveSubscriptionText(this.config)
@@ -1823,7 +1966,9 @@ export class Runtime {
1823
1966
  */
1824
1967
  async probeEntries(entries) {
1825
1968
  try {
1826
- return await probeSubscriptions(entries, { timeoutMs: 20_000 })
1969
+ const direct = await this.probeFetch()
1970
+ const report = await probeSubscriptions(entries, { timeoutMs: 20_000, fetch: direct })
1971
+ return { ...report, direct: direct !== undefined }
1827
1972
  } catch (error) {
1828
1973
  return {
1829
1974
  results: [],
@@ -1889,6 +2034,7 @@ export class Runtime {
1889
2034
  // closes, or it would see an unexpected exit and restart what was just stopped.
1890
2035
  this.engaged = false
1891
2036
  if (this.routing !== undefined) await this.routing.releaseToDirect()
2037
+ if (this.directLine !== undefined) await this.directLine.close()
1892
2038
  if (this.core !== undefined) await this.core.stop()
1893
2039
  }
1894
2040
 
@@ -2238,15 +2384,15 @@ function subscriptionTool(runtime) {
2238
2384
  'A 403 whose body says "rate limit exceeded" is a spent quota, not a blocked network: the node still works and the answer is another node or a wait, never a repair.',
2239
2385
  'action=import takes one or more subscription URLs (one per line, raw https:// or clash://install-config?url=… import links), probes them, restarts the core on them and routes through it. Without append it replaces the list; with append it adds to it.',
2240
2386
  'action=start brings routing up on the configured subscriptions; action=stop takes it down and restores direct connections.',
2241
- 'action=select switches the exit node by name (see the node list from status); action=test measures latency for one node or the current one; action=refresh re-downloads every subscription.',
2387
+ 'action=select switches the exit node by name (see the node list from status); action=test measures both latency and usability for the current node, one named node, or every node, and the result is what the panel list shows; action=refresh re-downloads every subscription.',
2242
2388
  ].join(' '),
2243
2389
  parameters: {
2244
2390
  type: 'object',
2245
2391
  properties: {
2246
2392
  action: {
2247
2393
  type: 'string',
2248
- enum: ['status', 'import', 'start', 'stop', 'restart', 'select', 'test', 'refresh', 'bootstrap', 'reselect', 'health'],
2249
- description: 'status reports state; import sets or appends subscriptions; start/stop control routing; restart rebuilds the core (use when it runs but its control API does not answer); select switches the exit node; test measures latency; refresh re-downloads every subscription; bootstrap downloads and installs a private mihomo core when the machine has none; health runs one real-request health round on the live node (base connectivity, GitHub quota, git fetch) and switches after enough consecutive failed or too-slow rounds.',
2394
+ enum: ['status', 'import', 'start', 'stop', 'restart', 'select', 'test', 'refresh', 'bootstrap'],
2395
+ description: 'status reports state; import sets or appends subscriptions; start/stop control routing; restart rebuilds the core (use when it runs but its control API does not answer); select switches the exit node; test measures latency and usability for the current node, one node or all of them; refresh re-downloads every subscription; bootstrap downloads and installs a private mihomo core when the machine has none.',
2250
2396
  },
2251
2397
  url: { type: 'string', description: 'One or more subscription URLs for action=import, one per line. A leading "name " is kept as the display name.' },
2252
2398
  append: { type: 'boolean', description: 'For action=import: add to the existing subscriptions instead of replacing them.' },
@@ -2324,37 +2470,17 @@ function subscriptionTool(runtime) {
2324
2470
  const report = await runtime.start()
2325
2471
  return { ...report, summary: `已启动:${report.endpoint},节点「${report.group.now ?? '未选择'}」,共 ${Math.max(0, report.group.all.length - 1)} 个可选节点。` }
2326
2472
  }
2327
- if (action === 'reselect') {
2328
- const result = await runtime.autoReselect({ force: true })
2329
- return {
2330
- ...result,
2331
- summary: result.state === 'kept'
2332
- ? '当前节点「' + result.node + '」仍能访问全部必需服务(' + (result.required ?? []).join('/') + '),未切换。'
2333
- : result.state === 'limited'
2334
- ? '当前节点「' + result.node + '」限流(' + (result.limited ?? []).join(',') + '),但常规联网正常;没有找到配额干净的替代节点,保留当前节点。'
2335
- : result.state === 'switched'
2336
- ? '已从「' + result.from + '」切到「' + result.to + '」(原节点失去 ' + (result.failed ?? []).join(',') + ')。'
2337
- : result.state === 'selected'
2338
- ? '已选「' + result.chosen + '」。'
2339
- : result.state === 'switch-deferred'
2340
- ? '当前节点「' + result.node + '」不合格,但有 ' + result.connections + ' 条连接在进行,本轮不切换。'
2341
- : '没有可用节点:' + (result.required ?? []).join(', ') + ' 无法全部访问。',
2342
- }
2343
- }
2344
- if (action === 'health') {
2345
- const report = await runtime.healthRound({ force: true })
2346
- return { ...report, summary: runtime.describeHealth(report) }
2347
- }
2348
2473
  if (action === 'test') {
2349
2474
  const target = String(args?.node ?? '').trim()
2350
- if (target !== '') {
2351
- const delay = await runtime.core.delay(target)
2352
- return { node: target, delay, summary: delay === null ? `「${target}」测速失败。` : `「${target}」延迟 ${delay} ms。` }
2475
+ const report = await runtime.testNodes(target === '' ? { current: true } : { only: target })
2476
+ const rows = Array.isArray(report.rows) ? report.rows : []
2477
+ const label = (usable) => (usable === 'ok' ? '可用' : usable === 'limited' ? '限流' : usable === 'blocked' ? '受限' : '未测')
2478
+ return {
2479
+ ...report,
2480
+ summary: rows.length === 0
2481
+ ? `没有可测的节点(${report.state})。`
2482
+ : rows.map((row) => `「${row.name}」${row.delay === undefined ? '未测到延迟' : `${row.delay} ms`}:${label(row.usable)}`).join('\n'),
2353
2483
  }
2354
- const status = await runtime.status()
2355
- if (status.node === undefined) throw new Error('no node selected')
2356
- const delay = await runtime.core.delay(status.node)
2357
- return { node: status.node, delay, summary: delay === null ? `「${status.node}」测速失败。` : `「${status.node}」延迟 ${delay} ms。` }
2358
2484
  }
2359
2485
  if (action === 'refresh') {
2360
2486
  const provider = await runtime.core.updateProvider()
package/lib/core.js CHANGED
@@ -193,6 +193,7 @@ export function buildConfig(options) {
193
193
  cnRuleSet,
194
194
  cnRuleSetPath,
195
195
  blocklist,
196
+ providerProxy,
196
197
  singleUrl,
197
198
  subscriptionUrl,
198
199
  providerPath,
@@ -226,6 +227,12 @@ export function buildConfig(options) {
226
227
  if (cnRuleSet !== undefined && cnRuleSet !== '') rules.push(`RULE-SET,${cnRuleSet},DIRECT`)
227
228
  rules.push('MATCH,PROXY')
228
229
 
230
+ // Written out rather than left to the core's default. The core does fetch a provider
231
+ // directly when the key is absent, but that is a default the plugin would silently
232
+ // depend on: if it ever changes, subscription downloads would quietly start spending
233
+ // a node's quota. Naming DIRECT makes the intent part of the config the panel shows.
234
+ const proxyTarget = String(providerProxy ?? 'DIRECT').trim()
235
+
229
236
  const providers = {}
230
237
  const names = []
231
238
  for (const [at, entry] of list.entries()) {
@@ -239,6 +246,7 @@ export function buildConfig(options) {
239
246
  url: String(entry?.url ?? ''),
240
247
  interval: 3600,
241
248
  path: path ?? `providers/${name}.yaml`,
249
+ ...(proxyTarget === '' ? {} : { proxy: proxyTarget }),
242
250
  ...(String(blocklist ?? '').trim() === '' ? {} : { 'exclude-filter': buildExcludeFilter(blocklist) }),
243
251
  'health-check': {
244
252
  enable: true,
package/lib/direct.js ADDED
@@ -0,0 +1,103 @@
1
+ /**
2
+ * A fetch that ignores the process-wide outbound policy.
3
+ *
4
+ * The plugin points undici's global dispatcher at its own core, so every `fetch` in
5
+ * the process — this plugin's subscription check included — travels through a
6
+ * subscription node. That is right for the Harness and wrong for the subscription
7
+ * link itself:
8
+ *
9
+ * - the link is what supplies the nodes, so a dead or rate-limited node must not be
10
+ * able to make a live link look broken;
11
+ * - checking through a node spends that node's quota to answer a question about the
12
+ * link;
13
+ * - and the answer would depend on which node happened to be selected, so the same
14
+ * link could report differently a minute apart with nothing changed.
15
+ *
16
+ * undici resolves a dispatcher per request, so a request carrying its own
17
+ * `dispatcher` bypasses the global one without touching the policy the rest of the
18
+ * process depends on. Measured on this machine with the global dispatcher pointed at
19
+ * a closed port (`http://127.0.0.1:9`): the plain `fetch` failed with
20
+ * `connect ECONNREFUSED 127.0.0.1:9` in 17 ms, while the same URL through this agent
21
+ * returned `200` and the full 723,720-byte document — twice in a row on one agent.
22
+ *
23
+ * The agent is built on first use and reused: with several subscriptions configured a
24
+ * fresh handshake per line costs more than the check itself.
25
+ *
26
+ * @module dsh-clash-proxy/direct
27
+ */
28
+
29
+ /**
30
+ * Owns one direct agent and the fetch bound to it.
31
+ */
32
+ export class DirectLine {
33
+ /**
34
+ * @param options - where undici lives, a logger, and the connect timeout.
35
+ */
36
+ constructor({ undiciPath, logger, connectTimeoutMs = 20_000 } = {}) {
37
+ this.undiciPath = undiciPath
38
+ this.log = logger ?? (() => {})
39
+ this.connectTimeoutMs = connectTimeoutMs
40
+ /** The undici module instance, kept so `fetch` does not re-import per call. */
41
+ this.undici = undefined
42
+ /** The agent this line owns, or undefined when none was built yet. */
43
+ this.agent = undefined
44
+ /** The in-flight build, so concurrent checks share one agent. */
45
+ this.pending = undefined
46
+ // Bound once: the value is handed to `probeSubscriptions` as `options.fetch`, and a
47
+ // bare method reference would lose `this` at the call site.
48
+ this.fetch = this.fetch.bind(this)
49
+ }
50
+
51
+ /** Whether an agent is live, i.e. the last {@link connect} succeeded. */
52
+ get active() {
53
+ return this.agent !== undefined
54
+ }
55
+
56
+ /**
57
+ * Build the agent if it is missing and return the fetch that uses it.
58
+ *
59
+ * @returns the bound fetch.
60
+ */
61
+ async connect() {
62
+ if (this.agent !== undefined) return this.fetch
63
+ if (this.pending === undefined) {
64
+ this.pending = (async () => {
65
+ const { pathToFileURL } = await import('node:url')
66
+ const undici = await import(pathToFileURL(this.undiciPath).href)
67
+ this.undici = undici
68
+ this.agent = new undici.Agent({ connect: { timeout: this.connectTimeoutMs } })
69
+ return this.fetch
70
+ })()
71
+ try {
72
+ return await this.pending
73
+ } finally {
74
+ this.pending = undefined
75
+ }
76
+ }
77
+ return await this.pending
78
+ }
79
+
80
+ /**
81
+ * Fetch with this line's dispatcher, whatever the global one is.
82
+ *
83
+ * @param url - the request target.
84
+ * @param init - the usual fetch init; `dispatcher` is set here and wins.
85
+ * @returns the response.
86
+ */
87
+ async fetch(url, init = {}) {
88
+ await this.connect()
89
+ return await this.undici.fetch(url, { ...init, dispatcher: this.agent })
90
+ }
91
+
92
+ /** Close the agent. Safe to call when none was built, and safe to call twice. */
93
+ async close() {
94
+ const agent = this.agent
95
+ this.agent = undefined
96
+ if (agent === undefined) return
97
+ try {
98
+ await agent.close()
99
+ } catch (error) {
100
+ this.log(`direct agent close failed: ${error?.message ?? error}`)
101
+ }
102
+ }
103
+ }
package/lib/routes.js CHANGED
@@ -305,14 +305,6 @@ export function mountRoutes(webServer, runtime, log) {
305
305
  sendJson(response, answer.ok ? 200 : 400, answer)
306
306
  return
307
307
  }
308
- if (action === 'health') {
309
- // One real-request round on the live node. Long-running by nature (four probes, each a
310
- // full TLS handshake through a node), so the caller gets the finished report rather than
311
- // a stream; the panel polls status meanwhile.
312
- const report = await runtime.healthRound({ force: true })
313
- sendJson(response, 200, { ok: report.state === 'ok' || report.state === 'switched', ...report })
314
- return
315
- }
316
308
  if (action === 'probeNode') {
317
309
  // Measure one named node for real, without moving live traffic.
318
310
  const name = String(body.node ?? '').trim()
@@ -333,15 +325,17 @@ export function mountRoutes(webServer, runtime, log) {
333
325
  return
334
326
  }
335
327
  if (action === 'test') {
336
- // A `node` narrows the run to one node and `all` covers every node; without
337
- // either the cycle measures the configured sample. The panel offers all three.
328
+ // Two buttons, one route: `current` measures the node carrying traffic, `all` measures
329
+ // every node, and `node` still narrows to one name (the per-row button and the tool).
330
+ // Every mode answers latency AND usability, and both land in status, so the list can
331
+ // show them together instead of the delay from one measurement and a stale verdict.
338
332
  const target = String(body.node ?? '').trim()
339
- const delays = await runtime.nodeDelays({
340
- force: true,
333
+ const report = await runtime.testNodes({
341
334
  only: target === '' ? undefined : target,
335
+ current: body.current === true,
342
336
  all: body.all === true,
343
337
  })
344
- sendJson(response, 200, { ok: true, delays })
338
+ sendJson(response, 200, { ok: report.state === 'ok', ...report })
345
339
  return
346
340
  }
347
341
  if (action === 'select') {
package/lib/skill.js CHANGED
@@ -138,7 +138,7 @@ clash_proxy action=select node=<精确节点名>
138
138
  - 不合格 = **不可用**(某个门槛探针没通)**、被限流**(如 GitHub 配额为 0)**或真实延迟过高**(超过 \`health.maxDelayMs\`,默认 400 ms)。带限流但没别的干净节点时,报告会说「限流」,不说「不可用」。
139
139
  - 三次重试是**同一轮内连续**的,所以坏节点几秒内就会被处理,不需要手动介入。
140
140
  - 手动换节点会打断正在进行的切换搜索,没必要别动它。
141
- - 要立刻验证,用 \`action=health\` 强制跑一轮并看明细。
141
+ - 要立刻验证,点面板的「当前节点测试」,或用 \`action=test\`(测当前节点)并看明细。
142
142
 
143
143
  ## 五、按症状查
144
144
 
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "dsh-clash-subscription",
3
- "version": "0.11.0",
4
- "description": "Import one or more Clash/mihomo subscriptions and route the Harness outbound traffic through the private core bundled with this plugin. Runs on Windows, Linux (Ubuntu 22.04/24.04/26.04 LTS) and macOS: the core is fetched and SHA-256 verified on platforms without a bundled copy, from a bare gzip asset unpacked with node:zlib. Every 30 seconds the live node gets up to three immediate real-request attempts; a rate-limited node now counts as a problem, and after three failures every unblocked node is measured and the best one wins: connectivity and a clean quota before the lowest Google latency.",
3
+ "version": "0.13.0",
4
+ "description": "Import one or more Clash/mihomo subscriptions and route the Harness outbound traffic through the private core bundled with this plugin. Runs on Windows, Linux (Ubuntu 22.04/24.04/26.04 LTS) and macOS: the core is fetched and SHA-256 verified on platforms without a bundled copy, from a bare gzip asset unpacked with node:zlib. Every 30 seconds the live node gets up to three immediate real-request attempts; a rate-limited node now counts as a problem, and after three failures every unblocked node is measured and the best one wins: connectivity and a clean quota before the lowest Google latency. The panel offers exactly two test buttons -- current node and all nodes -- and both measure latency and usability in one pass.",
5
5
  "keywords": [
6
6
  "dsh",
7
7
  "dsh-plugin",
@@ -34,7 +34,7 @@
34
34
  "locale/*.json",
35
35
  "icon.svg",
36
36
  "README.md",
37
- "CHANGELOG-0.11.0.md",
37
+ "CHANGELOG-0.13.0.md",
38
38
  "LICENSE"
39
39
  ],
40
40
  "engines": {
@@ -67,7 +67,9 @@
67
67
  },
68
68
  "homepage": "https://github.com/lc297948801/dsh-clash-subscription#readme",
69
69
  "scripts": {
70
- "test": "node test/regression-070.mjs",
70
+ "test": "node test/regression-0130.mjs && node test/regression-0120.mjs && node test/regression-070.mjs",
71
+ "test:direct": "node test/regression-0120.mjs",
72
+ "test:buttons": "node test/regression-0130.mjs",
71
73
  "test:legacy": "node test/regression-063.mjs",
72
74
  "test:linux": "node test/regression-0100.mjs",
73
75
  "test:e2e": "node test/e2e-090.mjs"
@@ -1,173 +0,0 @@
1
- # 0.11.0 · 不再选中被限流的节点
2
-
3
- > 上一版 `0.10.0` · 本版 `0.11.0`
4
-
5
- ## 症状
6
-
7
- 订阅里有能用的节点,自动切换却停在一个**被限流**的节点上。面板上看得见:
8
-
9
- ```
10
- health.lastSwitch: from 🇺🇸 美国02 → to 🇸🇬 新加坡03
11
- failed ["latency"] · degraded true
12
- health.lastRound: node 新加坡03 · usable true · degraded true · limited ["github"]
13
- ```
14
-
15
- `新加坡03` 的 GitHub 配额已经耗尽,而当时存在配额干净的节点。切换还是选中了它。
16
-
17
- ## 根因:同一个问题有两套排序,其中一套不看限流
18
-
19
- `lib/watch.js` 的 `rankHealth()` 是排序的定义,它知道限流要排在干净节点之后。但**运行期的切换路径自己又写了一套**:
20
-
21
- ```js
22
- // 0.10.0 · index.js switchAfterStrikes 里的局部排序
23
- const rank = (row) => [
24
- row.verdict?.usable === true ? 0 : 1, // 可用
25
- typeof row.latency === 'number' ? row.latency : Infinity,
26
- (row.verdict?.failed ?? []).length,
27
- (row.verdict?.blocked ?? []).length,
28
- ]
29
- ```
30
-
31
- 它从不读 `verdict.degraded`。而 `lib/realprobe.js` 里 `usable: blocked.length === 0` **只数 blocked,不数 limited** —— 所以一个被限流的节点 `usable` 仍是 `true`,排名靠的是延迟。限流节点往往更快(配额耗尽不耽误普通请求),于是它赢了。
32
-
33
- 启动时走的是 `lib/core.js` 的 `rankHealth(rows)[0]`,排序正确;运行期走的是这套局部排序,排序错误。**同一件事两个答案,取决于走哪条路**。
34
-
35
- 用真实运行期代码取证(不是手写模拟):
36
-
37
- | 场景 | 切换路径选中 | `rankHealth` 选中 |
38
- |---|---|---|
39
- | `ok` 300 ms vs `limited` 150 ms | `limited-150` ✗ | `ok-300` ✓ |
40
- | `ok` 280 ms vs `limited` 150 / 160 ms | `limited-150` ✗ | `ok-280` ✓ |
41
-
42
- ## 第二处:`rankHealth` 的最后一级不是延迟
43
-
44
- 修好第一处后还有一个洞:`rankHealth` 比到最后一级用的是 `verdict.total`(探针耗时之和),而 **`total` 里根本没有 Google 延迟** —— `lib/realprobe.js` 只累加 `gating` 探针,Google 基线是 `gating: false`。
45
-
46
- ```
47
- A: google 100 ms · total 2300
48
- B: google 300 ms · total 970
49
- → rankHealth 选 B
50
- ```
51
-
52
- 用户要的是「延迟最低」,而 `total` 被 git fetch 的 300–2100 ms 摆动支配,测的不是延迟。
53
-
54
- ## 第三处:限流节点一次就放行
55
-
56
- `healthRound` 的接受条件是 `if (measured.verdict.usable === true) return`。因为限流不算 `blocked`,**限流节点第一次就通过,剩下两次重测和随后的全节点重选都不会发生**。实测:重启后 `lastRound` 是 `degraded / attempt 1/3 / failed ["github"]`,其余 8 个节点状态全是 `unknown` —— 压根没测。
57
-
58
- ## 第四处:名为「暖态中位数」的取值在 2 样本时取较大者
59
-
60
- ```js
61
- // 0.10.0
62
- const forMedian = samples.length > 1 ? samples.slice(1) : samples
63
- const sorted = [...forMedian].sort((a, b) => a - b)
64
- latency = sorted[Math.floor(sorted.length / 2)]
65
- ```
66
-
67
- 3 个样本丢掉第 1 个后剩 2 个,`floor(2 / 2) = 1` 取的是**较大者**。实测 `[513, 420, 380] → 420`(真中位 380)、`[513, 1500, 120] → 1500`。系统性把节点判慢,再把延迟上限当成硬失败,更多好节点被踢出候选。
68
-
69
- ## 改了什么
70
-
71
- ### 1. 只会有一套排序
72
-
73
- `switchAfterStrikes` 里的局部 `rank` 整段删除,改为走 `rankHealth`:
74
-
75
- ```js
76
- const ranked = rankHealth(rows)
77
- rows.sort((a, b) => ranked.indexOf(a) - ranked.indexOf(b))
78
- ```
79
-
80
- ### 2. `rankHealth` 在限流之后、耗时之前比真实延迟
81
-
82
- ```js
83
- (a, b) =>
84
- good(a) - good(b) ||
85
- blockedCount(a) - blockedCount(b) ||
86
- degraded(a) - degraded(b) || // 配额干净优先
87
- latency(a) - latency(b) || // ← 新增:Google 暖态延迟
88
- score(a) - score(b) ||
89
- total(a) - total(b),
90
- ```
91
-
92
- 没有延迟的节点(启动矩阵里还没测过 Google)排在有延迟的之后 —— 不能靠一个不存在的数字取胜。
93
-
94
- ### 3. 限流算「有问题」
95
-
96
- ```js
97
- const clean = measured.verdict.usable === true && measured.verdict.degraded !== true
98
- if (clean === true) { /* 接受,结束本轮 */ }
99
- ```
100
-
101
- 限流节点现在也会连测满 3 次。**这里故意没有 `attempt === attempts` 的逃生口**:加过一次,结果第 3 次仍限流时也走进接受分支、永不切换,正是要修的缺陷原样复活,11 条测试变红后删除。
102
-
103
- 三次都不合格时按「是限流还是硬失败」分流:限流给 `state: 'limited'` 且 `giveUp: false`(不计 strike),硬失败照旧累计。
104
-
105
- ### 4. 找不到干净节点时不说谎
106
-
107
- 当前节点只是被限流、又没有配额干净的替代时,报告**不再说「不可用」**:
108
-
109
- ```js
110
- return { ...report, state: liveUsable === true ? "limited" : "no-alternative", ... }
111
- ```
112
-
113
- 那条线还在承载流量。说它不可用,是在描述用户明明正在用的连接。`health.lastSwitch.state` 相应记为 `no-clean-alternative`,与真正的 `no-alternative` 分开。
114
-
115
- ### 5. 切换候选的门槛随之收紧
116
-
117
- ```js
118
- const improves = (row) =>
119
- row.verdict?.usable === true && (liveUsable !== true || row.verdict?.degraded !== true)
120
- ```
121
-
122
- 当前节点硬失败时,任何可用节点都算改善;当前节点仅限流时,**只有配额干净的才算** —— 换一个同样限流的节点,答复质量一样,却要中断所有在途连接。
123
-
124
- ### 6. 真中位数
125
-
126
- ```js
127
- const mid = sorted.length >> 1
128
- latency = sorted.length % 2 === 1 ? sorted[mid] : Math.round((sorted[mid - 1] + sorted[mid]) / 2)
129
- ```
130
-
131
- ### 7. 摘要说清是哪种情况
132
-
133
- `describeHealth()` 从工具分支里抽成 `Runtime` 方法,测试才断言得到它的措辞。三种历史错法在 JSDoc 里写明:
134
-
135
- - 把正在承载流量的限流节点说成「不可用」
136
- - 把一轮内连测 3 次说成「连续 3 轮失败」
137
- - 打印 `undefined`(`strikes`/`strikeLimit` 从未进过 report)
138
-
139
- ## 验收
140
-
141
- ```
142
- node test/regression-070.mjs → 134 passed, 0 failed ← 新增 9b / 9c / 9d / 18 四节
143
- node test/regression-0100.mjs → 48 passed, 0 failed
144
- node test/regression-063.mjs → 29 passed, 0 failed
145
- node test/e2e-063.mjs → 10 passed, 0 failed
146
- ```
147
-
148
- 负向对照(证明这些测试抓得住回归,不是装饰):
149
-
150
- | 还原哪一处 | 报出的失败 |
151
- |---|---|
152
- | 切回旧接受条件 `usable === true` 即 return | 9c 报 7 条 FAIL |
153
- | 从 comparator 删掉 `latency(a) - latency(b) \|\|` | 9d 报 2 条 FAIL |
154
- | `state` 还原成一律 `"no-alternative"` | 18 报 4 条 FAIL |
155
-
156
- 真机数据验证(把 `/clash-proxy/status` 的 9 个节点喂新 `rankHealth`):
157
-
158
- ```
159
- 新加坡01 ok/123 → 新加坡03 ok/126 → 新加坡02 ok/127 → 台湾02 ok/187
160
- → 台湾01 ok/203 → 美国02 ok/231 → 美国03 ok/253 → 马来西亚01 ok/无延迟
161
- → 美国01 limited/247
162
- ```
163
-
164
- `ok` 全部排在 `limited` 之前,同档内按 Google 延迟升序。
165
-
166
- ## 本版附带
167
-
168
- - 包内补上 `vendor/`(`mihomo.exe.gz` + `SHA256SUMS.json`)。源码归档树一直缺这两份,所以 `e2e-070/080/090` 长期报 `CORE_MISSING` 跑不起来。
169
- - `lib/skill.js` 的自述表同步:`limited` 行改为「不主动选;只有没有 `ok` 节点时才留」,切换规则改为「连通且不限流 → Google 延迟」排序,`lastRound.state` 取值列出 `ok / limited / slow / switched / bad`。
170
-
171
- ## 需要重启才生效
172
-
173
- 宿主进程在加载插件时把代码读进内存。装完本版后**要完全退出 DSH 再打开**,新逻辑才生效。