dsh-desktop-statusbar 3.0.7 → 3.0.8

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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-desktop-statusbar",
3
- "version": "3.0.7",
3
+ "version": "3.0.8",
4
4
  "type": "module",
5
5
  "description": "把 DSH 桌面端对话区底部的统计行换成可配置状态栏:9 个可选字段可排序 + 栏首上下文圆环,按官方峰谷口径估算费用,支持自定义模型单价与账户余额。",
6
6
  "icon": "icon.svg",
@@ -100,7 +100,8 @@ function renderBar({ running, timeRange, stats, error }) {
100
100
  return { clocks, timeouts: timeouts.slice(), ringClass: ring === null ? null : ring.props.className, tree: tree, cleanup: () => cleanups.forEach((fn) => fn()), all: intervals.slice() };
101
101
  }
102
102
 
103
- /** 渲染树里第一个上下文占用圆环(svg)的 props:没有占用数据时应当整个缺席 */
103
+ /** 渲染树里第一个上下文占用圆环的外层 span(.dsb-ring-wrap)的 props:没有占用数据时应当整个缺席。
104
+ state 颜色类(dsb-ring-running/error/…)现在挂在这个外层 wrap 上,不再挂在内部 SVG。 */
104
105
  function findRing(node) {
105
106
  if (node === null || node === undefined || typeof node !== 'object') return null;
106
107
  if (Array.isArray(node)) {
@@ -110,7 +111,7 @@ function findRing(node) {
110
111
  }
111
112
  return null;
112
113
  }
113
- if (node.type === 'svg') return node;
114
+ if (typeof node.props?.className === 'string' && node.props.className.indexOf('dsb-ring-wrap') === 0) return node;
114
115
  return findRing(node.children);
115
116
  }
116
117
 
@@ -111,14 +111,21 @@ assert.strictEqual(dash.window, '-', '空态窗口给横杠');
111
111
  assert.deepStrictEqual(Array.from(dash.rows), [], '空态没有图例行');
112
112
  assert.deepStrictEqual(Array.from(dash.segments), [], '空态没有分段');
113
113
  assert.strictEqual(dash.compact, null, '空态没有压缩点缺口');
114
- const dashRing = api.contextRing(dash.percent, 'idle');
115
- assert.strictEqual(Array.from(dashRing.children).length, 3, '圆环 = 底环 + 进度弧 + 环心数字');
116
- assert.strictEqual(Array.from(dashRing.children)[1].props.strokeDashoffset, 2 * Math.PI * 5.5, '0% 时进度弧整段留空');
117
- assert.strictEqual(Array.from(dashRing.children)[2].props.className, 'dsb-ring-percent', '第三项是环心占用数字');
118
- /* 空态(没有占用数据)环心留空:contextMeter.empty === true / 没有数据时都不显示数字 */
119
- assert.strictEqual(String(Array.from(dashRing.children)[2].children[0]), '', '空态环心留空');
120
- assert.strictEqual(Array.from(api.contextRing(0, 'idle', null, null).children)[2].children[0], '', '没有 labelPercent 数据时环心也留空');
121
- console.log('= 缺占用数据 → 空环 + 横杠(不再整块消失)');
114
+ /* ring 现在是外层 span(.dsb-ring-wrap);SVG 与数字都是它的子节点,先解构出来 */
115
+ const ringParts = (wrap) => {
116
+ const kids = Array.from(wrap.children).flat(Infinity);
117
+ const svg = kids.find((k) => k && k.props && typeof k.props.className === 'string' && k.props.className.indexOf('dsb-ring') === 0 && k.type === 'svg');
118
+ const pct = kids.find((k) => k && k.props && k.props.className === 'dsb-ring-percent');
119
+ const circles = svg ? Array.from(svg.children) : [];
120
+ return { wrap, svg, circles, pct };
121
+ };
122
+ const dashRing = ringParts(api.contextRing(dash.percent, 'idle'));
123
+ assert.strictEqual(dashRing.wrap.type, 'span', '圆环外层是 span(HTML 覆盖层)');
124
+ assert.strictEqual(dashRing.circles.length, 2, 'SVG = 底环 + 进度弧');
125
+ assert.strictEqual(dashRing.circles[1].props.strokeDashoffset, 2 * Math.PI * 5.5, '0% 时进度弧整段留空');
126
+ /* 空态(没有占用数据)不渲染数字 span:contextMeter.empty === true / 没有数据时都不显示数字 */
127
+ assert.strictEqual(dashRing.pct, undefined, '空态环心不渲染数字 span');
128
+ assert.strictEqual(ringParts(api.contextRing(0, 'idle', null, null)).pct, undefined, '没有 labelPercent 数据时环心也不渲染数字');
122
129
 
123
130
  /* ------------------------------------------------------------- 段渲染 */
124
131
  const baseSrc = {
@@ -145,38 +152,44 @@ assert.strictEqual(contextMeter.compact, null, '没有 capacity 时压缩点为
145
152
  console.log('= 圆环带上下文占用气泡;压缩点随模型自适应;token 计数段已并入总计,峰谷可点');
146
153
 
147
154
  /* ------------------------------------------------------------- 圆环几何 */
148
- const ring = api.contextRing(62, 'idle', null, 62);
149
- assert.strictEqual(ring.type, 'svg', '圆环是 svg');
150
- assert.ok(String(ring.props.className).indexOf('dsb-ring') === 0, '圆环类名');
151
- const circles = Array.from(ring.children);
155
+ const ring = ringParts(api.contextRing(62, 'idle', null, 62));
156
+ assert.strictEqual(ring.wrap.type, 'span', '圆环外层是 span');
157
+ assert.ok(String(ring.wrap.props.className).indexOf('dsb-ring-wrap') === 0, '外层类名 dsb-ring-wrap');
158
+ assert.strictEqual(ring.svg.type, 'svg', '内部是 svg');
159
+ assert.strictEqual(ring.svg.props.className, 'dsb-ring', 'SVG 类名 dsb-ring');
160
+ assert.strictEqual(ring.svg.props.viewBox, '0 0 14 14', 'SVG viewBox 不变');
161
+ const circles = ring.circles;
152
162
  assert.strictEqual(circles[0].props.className, 'dsb-ring-track', '底环');
153
163
  assert.strictEqual(circles[1].props.className, 'dsb-ring-fill', '进度弧');
154
164
  assert.strictEqual(circles[1].props.transform, 'rotate(-90 7 7)', '起点在 12 点方向(整体转 -90°)');
155
165
  assert.strictEqual(Math.round(circles[1].props.strokeDasharray), Math.round(2 * Math.PI * 5.5), '周长 = 2πr');
156
166
  assert.strictEqual(Math.round(circles[1].props.strokeDashoffset), Math.round(2 * Math.PI * 5.5 * 0.38), '62% 时留 38% 的缺口');
157
- /* 环心数字:显示**主会话自己**的占用(第 4 参 labelPercent),与弧长(第 1 参 percent)不同源。
158
- 用户拍板:弧长在团队运行时切到成员/深层数据,环心数字永远只显示主会话自己的百分比。 */
159
- assert.strictEqual(circles[2].props.className, 'dsb-ring-percent', '环心是占用数字 text');
160
- assert.strictEqual(String(circles[2].children[0]), '62', '环心数字 = labelPercent(无 % 号)');
161
- assert.strictEqual(circles[2].props.fontSize, undefined, '不再写动态 fontSize(字号只由 CSS 固定 6px)');
162
- assert.strictEqual(circles[2].props['aria-hidden'], 'true', '环心数字对读屏隐藏(气泡已读百分比)');
167
+ /* 环心数字:HTML span 覆盖层,显示**主会话自己**的占用(第 4 参 labelPercent),与弧长不同源。 */
168
+ assert.strictEqual(ring.pct.props.className, 'dsb-ring-percent', '环心是占用数字 span');
169
+ assert.strictEqual(String(ring.pct.children[0]), '62', '环心数字 = labelPercent(无 % 号)');
170
+ assert.strictEqual(ring.pct.props['aria-hidden'], 'true', '环心数字对读屏隐藏(气泡已读百分比)');
171
+ /* 不再依赖 SVG 基线:数字不是 SVG text,不带 dy / dominantBaseline / fontSize */
172
+ assert.strictEqual(ring.pct.type, 'span', '环心数字是 HTML span 而非 svg text');
173
+ assert.strictEqual(ring.pct.props.dy, undefined, '不再写 SVG dy 基线微调');
174
+ assert.strictEqual(ring.pct.props.dominantBaseline, undefined, '不再写 dominantBaseline');
175
+ assert.strictEqual(ring.pct.props.fontSize, undefined, '不再写动态 fontSize(字号只由 CSS 固定 6px)');
163
176
  /* 主会话百分比 vs 团队弧长不同源:弧长 55% 但环心数字显示主会话自己的 20 */
164
- const mixed = Array.from(api.contextRing(55, 'teamRunning', null, 20).children);
165
- assert.ok(Math.abs(mixed[1].props.strokeDashoffset - 2 * Math.PI * 5.5 * 0.45) < 1e-9, '弧长按第 1 参 55%(团队级)');
166
- assert.strictEqual(String(mixed[2].children[0]), '20', '环心数字按第 4 参 20(主会话自己),不是团队的 55');
177
+ const mixed = ringParts(api.contextRing(55, 'teamRunning', null, 20));
178
+ assert.ok(Math.abs(mixed.circles[1].props.strokeDashoffset - 2 * Math.PI * 5.5 * 0.45) < 1e-9, '弧长按第 1 参 55%(团队级)');
179
+ assert.strictEqual(String(mixed.pct.children[0]), '20', '环心数字按第 4 参 20(主会话自己),不是团队的 55');
167
180
  /* 小数取整:32.6 → 33(四舍五入,不显示小数点) */
168
- assert.strictEqual(String(Array.from(api.contextRing(32.6, 'idle', null, 32.6).children)[2].children[0]), '33', '小数四舍五入成整数');
169
- assert.strictEqual(String(Array.from(api.contextRing(33.4, 'idle', null, 33.4).children)[2].children[0]), '33', '33.4 向下取整为 33');
181
+ assert.strictEqual(String(ringParts(api.contextRing(32.6, 'idle', null, 32.6)).pct.children[0]), '33', '小数四舍五入成整数');
182
+ assert.strictEqual(String(ringParts(api.contextRing(33.4, 'idle', null, 33.4)).pct.children[0]), '33', '33.4 向下取整为 33');
170
183
  /* 100 留空:14px 环心塞不下三位 */
171
- assert.strictEqual(String(Array.from(api.contextRing(100, 'idle', null, 100).children)[2].children[0]), '', '达到 100 时环心留空');
172
- assert.strictEqual(String(Array.from(api.contextRing(99.6, 'idle', null, 99.6).children)[2].children[0]), '', '99.6 四舍五入成 100 后同样留空');
173
- assert.ok(String(api.contextRing(62, 'running').props.className).includes('dsb-ring-running'), '运行中 → 绿色');
184
+ assert.strictEqual(ringParts(api.contextRing(100, 'idle', null, 100)).pct, undefined, '达到 100 时不渲染数字');
185
+ assert.strictEqual(ringParts(api.contextRing(99.6, 'idle', null, 99.6)).pct, undefined, '99.6 四舍五入成 100 后同样不留数字');
186
+ assert.ok(String(api.contextRing(62, 'running').props.className).includes('dsb-ring-running'), '运行中 → 绿色(state class 挂在外层 wrap)');
174
187
  assert.ok(String(api.contextRing(62, 'error').props.className).includes('dsb-ring-error'), '报错 → 红色');
175
188
  assert.ok(String(api.contextRing(62, 'approval').props.className).includes('dsb-ring-approval'), '待审批 → 黄色');
176
189
  /* 底环:没有压缩点时整圈(不旋转、不设 dasharray);有压缩点时在压缩点处开一个圆头缺口 */
177
190
  assert.strictEqual(circles[0].props.transform, undefined, '没有压缩点时底环不旋转');
178
191
  assert.strictEqual(circles[0].props.strokeDasharray, undefined, '没有压缩点时底环整圈');
179
- const notchTrack = Array.from(api.contextRing(62, 'idle', 55.0464).children)[0];
192
+ const notchTrack = ringParts(api.contextRing(62, 'idle', 55.0464)).circles[0];
180
193
  assert.strictEqual(notchTrack.props.transform, 'rotate(-90 7 7)', '开缺口时底环转到 12 点起(与进度弧同一口径)');
181
194
  assert.strictEqual(notchTrack.props.strokeLinecap, 'round', '缺口两端是圆头');
182
195
  const notchDashes = notchTrack.props.strokeDasharray.split(' ').map(Number);
@@ -184,7 +197,7 @@ assert.strictEqual(notchDashes.length, 3, '缺口 = 画-空-画 三段');
184
197
  assert.strictEqual(notchDashes[1], 3, '空洞 = 净宽 1 + 描边 2(圆头各向洞内啃半个线宽)');
185
198
  assert.ok(Math.abs(notchDashes[0] + notchDashes[1] + notchDashes[2] - 2 * Math.PI * 5.5) < 1e-12, '三段之和精确等于周长');
186
199
  assert.ok(Math.abs((notchDashes[0] + notchDashes[1] / 2) - 2 * Math.PI * 5.5 * 0.550464) < 1e-12, '缺口中心落在压缩点上');
187
- console.log('= 圆环:12 点起、周长与进度正确、颜色随状态;压缩点处开圆头缺口;环心同源显示占用数字');
200
+ console.log('= 圆环:外层 span + 内部 SVG/数字 span;12 点起、周长与进度正确、颜色随状态;压缩点处开圆头缺口;环心同源显示占用数字');
188
201
 
189
202
  /* 点击与收起的契约:圆环包在按钮里(hover/展开有灰底),面板点别处收起 */
190
203
  const source = fs.readFileSync(PLUGIN, 'utf8');
@@ -172,7 +172,7 @@ const STYLES = [
172
172
  ['占位文字更淡', 'input::placeholder{color:var(--dsw-alias-label-tertiary);opacity:.5}'],
173
173
  ['最后一条模型贴齐卡片底', 'dsb-model:last-child{padding-bottom:0}'],
174
174
  ['数字输入右对齐(价格框那条规则一并管宽度与高度)', 'dsb-field input[type=text],.dsb-settings .dsb-field input[type=number]{width:calc(6ch + 18px);min-width:calc(6ch + 18px);flex:none;height:24px;text-align:right}'],
175
- ['藏官方统计行挂在 html.dsb-on 上(关掉开关就恢复)', 'html.dsb-on [data-slot="conversation.composer.dock"] > *:not(.dsb-root):not(:has(.dsb-root)){display:none !important}'],
175
+ ['藏官方统计行挂在 html.dsb-on 上(只藏含官方特征的直接子节点,第三方不藏)', 'html.dsb-on [data-slot="conversation.composer.dock"] > *:not(.dsb-root):not(:has(.dsb-root)):has([data-composer-stat],button[aria-haspopup="dialog"]'],
176
176
  ['藏官方上下文按钮同样挂在 html.dsb-on 上', 'html.dsb-on button[aria-haspopup="dialog"][aria-label*="上下文"]'],
177
177
  ['藏官方「用量」按钮(TurnUsagePanel)', 'html.dsb-on span[class$="_root"]>button[aria-haspopup="dialog"][class$="_trigger"]'],
178
178
  ['气泡宽度按内容自适应', 'width:max-content;max-width:min(560px,100vw - 24px)'],
@@ -520,7 +520,7 @@ const bookOf = (entry) => ({ x: entry });
520
520
  ② MutationObserver 只在新增节点匹配(或包含匹配)官方选择器时重扫一次,普通流式文字变化
521
521
  不触发,避免卡顿;卸载只还原被我们藏过的官方节点。 */
522
522
  assert.ok(/new MutationObserver\(/.test(clientCode), '藏官方底栏必须用 MutationObserver(不能只跑一次)');
523
- assert.ok(/observer\.observe\(dock,\s*\{\s*childList:\s*true/.test(clientCode), '观察 dock 的 childList 变动(不观察 attributes,避免自激)');
523
+ assert.ok(/observer\.observe\(observeRoot,\s*\{\s*childList:\s*true,\s*subtree:\s*true\s*\}\)/.test(clientCode), '观察 body/documentElement 的 childList+subtree(侧栏重构/深层子树插入也能压住)');
524
524
  assert.ok(/observer\.disconnect\(\)/.test(clientCode), '卸载时必须断开 observer');
525
525
  assert.ok(/hidden\.forEach\(\(prev, el\) => \{ el\.style\.display = prev; \}\)/.test(clientCode),
526
526
  '卸载时把藏过的节点逐个还原(关侧栏/关插件都不留异常)');
@@ -541,6 +541,34 @@ const bookOf = (entry) => ({ x: entry });
541
541
  assert.ok(/const touchesOfficial = \(node\)/.test(clientCode), 'observer 回调必须有"是否牵涉官方节点"的过滤函数');
542
542
  assert.ok(/record\.addedNodes/.test(clientCode), 'observer 只检查 addedNodes(新增节点)');
543
543
  assert.ok(/if \(relevant\) sweep\(\);/.test(clientCode), '只有新增节点牵涉官方节点时才重扫(普通文字变化不触发)');
544
+ /* ③ 官方 dock 根 [data-composer-dock]:dockOf 优先查它;sweep 还要藏它除 .dsb-root/含 .dsb-root 外的直接子节点 */
545
+ assert.ok(/querySelector\("\[data-composer-dock\]"\)/.test(clientCode), 'dockOf 必须优先查 [data-composer-dock](官方 ContextMeter/图标是它的直接子节点)');
546
+ assert.ok(/\|\| document\.querySelector\('\[data-slot="conversation\.composer\.dock"\]'\)/.test(clientCode), '没有 [data-composer-dock] 时退回 slot(老结构不退化)');
547
+ assert.ok(/officials\.forEach\(\(node\) => \{/.test(clientCode), 'sweep 对每个官方节点向上找直属 dock 的包装层(不再无条件遍历隐藏全部直接子节点)');
548
+ assert.ok(/cur\.classList\.contains\("dsb-root"\)/.test(clientCode), '向上找包装层时跳过 .dsb-root(自己的根不藏)');
549
+ assert.ok(!/child\.querySelector\("\.dsb-root"\) !== null\) return/.test(clientCode), '不再用「直接子节点是否含 .dsb-root」来决定隐藏(那会误藏/误留)');
550
+ assert.ok(/\[data-composer-dock\] > \*:not\(\.dsb-root\):not\(:has\(\.dsb-root\)\):has\(\[data-composer-stat\]/.test(clientCode), 'CSS 只藏含官方特征的直接子节点(:has 官方标记),第三方直接子节点不藏');
551
+ assert.ok(/\[data-slot="conversation\.composer\.dock"\] > \*:not\(\.dsb-root\):not\(:has\(\.dsb-root\)\):has\(\[data-composer-stat\]/.test(clientCode), '[data-slot] 规则同样只藏含官方特征的直接子节点');
552
+ assert.ok(/attributeFilter: \["class"\]/.test(clientCode) && /classObserver\.observe\(document\.documentElement/.test(clientCode), '额外盯 documentElement 的 class 变化(dsb-on 被移除时补回)');
553
+ assert.ok(/document\.body !== null && document\.body !== undefined\)\s*\?\s*document\.body\s*:\s*document\.documentElement/.test(clientCode), '观察目标优先 body,没有时退回 documentElement');
554
+ /* ④ 官方 StatsPills(活动/数据库用量 pill)根节点带 data-composer-stat:CSS 隐藏 + 进 OFFICIAL_SELECTORS */
555
+ assert.ok(/html\.dsb-on \[data-composer-stat\]\{display:none !important\}/.test(clientCode), 'CSS 要有 [data-composer-stat] 隐藏规则');
556
+ assert.ok(/const OFFICIAL_SELECTORS = \[[\s\S]*?'\[data-composer-stat\]'/.test(clientCode), 'OFFICIAL_SELECTORS 必须包含 [data-composer-stat](sweep 与 observer 都能识别)');
557
+ /* ⑤ 消息操作行 [data-clock="end"] 的官方 TurnUsagePanel:两条行作用域 CSS + 进 OFFICIAL_SELECTORS */
558
+ assert.ok(/html\.dsb-on \[data-clock="end"\] span\[class\$="_root"\]\{display:none !important\}/.test(clientCode), 'CSS 要有 [data-clock=end] span[class$=_root] 隐藏规则');
559
+ assert.ok(/html\.dsb-on \[data-clock="end"\] span:has\(>button\[aria-haspopup="dialog"\]\)\{display:none !important\}/.test(clientCode), 'CSS 要有 [data-clock=end] span:has(>button[aria-haspopup]) 隐藏规则');
560
+ assert.ok(/const OFFICIAL_SELECTORS = \[[\s\S]*?\[data-clock="end"\] span:has\(>button\[aria-haspopup="dialog"\]\)/.test(clientCode), 'OFFICIAL_SELECTORS 必须含 [data-clock=end] span:has(>button[aria-haspopup])');
561
+ console.log(' 只认官方选择器、无兄弟全隐藏循环;observer 有官方节点过滤,卸载只还原官方节点');
562
+ /* ⑥ 建议修-1:sweep 不再无条件藏 dock 全部直接子节点,只藏官方节点 + 其直属 dock 的包装层。
563
+ 这里断言「先藏官方节点,再按官方节点向上找直属 dock 的包装层一起藏」的结构都在,
564
+ 且不再有「遍历 dock.children 直接 hide」那种会误藏第三方节点的写法。 */
565
+ assert.ok(/const officials = Array\.from\(dock\.querySelectorAll\(OFFICIAL\)\)/.test(clientCode),
566
+ 'sweep 先收集官方节点(querySelectorAll(OFFICIAL))');
567
+ assert.ok(/officials\.forEach\(hideNode\)/.test(clientCode), 'sweep 藏每个官方节点');
568
+ assert.ok(/cur\.parentNode !== dock/.test(clientCode), 'sweep 按官方节点向上找到 parent 恰为 dock 的包装层(只藏这一层)');
569
+ /* 包装层若**包含** .dsb-root(官方与本插件根同层)绝不能藏 —— 否则连状态栏一起藏掉。 */
570
+ assert.ok(/cur\.querySelector\("\.dsb-root"\) !== null\)\) \{/.test(clientCode),
571
+ '向上找到的包装层若包含 .dsb-root 则不隐藏(避免同层带本插件根时误藏整层)');
544
572
  console.log(' 只认官方选择器、无兄弟全隐藏循环;observer 有官方节点过滤,卸载只还原官方节点');
545
573
 
546
574
  console.log('\nFIX REGRESSION CHECKS PASSED');
@@ -223,7 +223,10 @@ function headerOf(headers, name) {
223
223
  assert.equal(failed.ok, false, '全部候选失败时 ok=false')
224
224
  assert.equal(failed.reason, 'relay-endpoint-empty', '失败原因明确为 relay-endpoint-empty')
225
225
  assert.equal(failed.provider, 'relay-fail', '失败态标明平台名')
226
- assert.equal(calls.length, 7, '失败时也只探测 7 个候选一次')
226
+ /* 失败后新增了「透传 Magpie 余额」的兜底探测(quotas/models):这里只断言**候选端点**恰好 7 个,
227
+ Magpie 探测不计入(用 URL 过滤掉本机 Magpie 网关请求)。 */
228
+ const candidateCalls = calls.filter((one) => one.url.indexOf('127.0.0.1:3425') < 0 && one.url.indexOf('/magpie/') < 0)
229
+ assert.equal(candidateCalls.length, 7, '失败时也只探测 7 个候选一次(Magpie 兜底探测不计),实际 ' + candidateCalls.length)
227
230
  const afterFail = JSON.parse(fs.readFileSync(configPath, 'utf8'))
228
231
  const failChannel = afterFail.channels.find((one) => one.channelKey === 'relay-fail')
229
232
  assert.ok(failChannel !== undefined, '探测失败不清空平台记录')
@@ -234,11 +237,12 @@ function headerOf(headers, name) {
234
237
  assert.deepEqual(secretWrites, [], '探测失败不写/删凭据服务')
235
238
 
236
239
  /* ---- 同一刷新周期内不每轮重试 7 个 ---- */
237
- const beforeRetry = calls.length
240
+ const candidateBefore = calls.filter((one) => one.url.indexOf('127.0.0.1:3425') < 0 && one.url.indexOf('/magpie/') < 0).length
238
241
  const again = await mod.queryBalanceForTest(ctx, false, 'relay-fail', 'any-model', null, null)
239
242
  assert.equal(again.ok, false, '冷却期内仍然 ok=false')
240
243
  assert.equal(again.reason, 'relay-endpoint-empty', '冷却期内原因不变')
241
- assert.equal(calls.length, beforeRetry, '冷却期内不重复发 7 个候选,实际增加 ' + (calls.length - beforeRetry) + ' 次')
244
+ const candidateAfter = calls.filter((one) => one.url.indexOf('127.0.0.1:3425') < 0 && one.url.indexOf('/magpie/') < 0).length
245
+ assert.equal(candidateAfter, candidateBefore, '冷却期内不重复发 7 个候选,实际增加 ' + (candidateAfter - candidateBefore) + ' 次')
242
246
  console.log('GENERIC RELAY DISCOVERY CHECKS PASSED')
243
247
  } finally {
244
248
  globalThis.fetch = realFetch
@@ -313,6 +317,9 @@ function headerOf(headers, name) {
313
317
  }
314
318
 
315
319
  const calls = []
320
+ /* 本机 Magpie 透传探测(127.0.0.1:3425)单列,不计入「候选端点」次数。 */
321
+ const isMagpieProbe = (one) => one.url.indexOf('127.0.0.1:3425') >= 0 || one.url.indexOf('/magpie/') >= 0
322
+ const candCount = () => calls.filter((one) => isMagpieProbe(one) !== true).length
316
323
  const realFetch = globalThis.fetch
317
324
  const jsonOk = (body) => new Response(JSON.stringify(body), { status: 200, headers: { 'content-type': 'application/json' } })
318
325
  const jsonNo = () => new Response(JSON.stringify({ error: 'not-found' }), { status: 404, headers: { 'content-type': 'application/json' } })
@@ -333,7 +340,7 @@ function headerOf(headers, name) {
333
340
  const first = await mod.queryBalanceForTest(ctx, false, 'relay-default', 'any-model', null, null)
334
341
  assert.equal(first.ok, true, '默认 balancePath 首次探测应成功: ' + JSON.stringify(first))
335
342
  assert.equal(first.total, '10.00', 'quota 5000000 / 500000 = 10.00')
336
- assert.equal(calls.length, 7, '首次并发探测 7 个候选,实际 ' + calls.length)
343
+ assert.equal(candCount(), 7, '首次并发探测 7 个候选,实际 ' + candCount())
337
344
  const savedDefault = JSON.parse(fs.readFileSync(configPath, 'utf8')).channels.find((one) => one.channelKey === 'relay-default')
338
345
  assert.equal(savedDefault.endpoint, 'https://default.example/api/user/self', '命中 endpoint 写回')
339
346
  assert.equal(savedDefault.balancePath, 'data.quota', '解析字段 balancePath 一并写回(旧 bug:不写,第二次按 $.balance 失败)')
@@ -342,8 +349,8 @@ function headerOf(headers, name) {
342
349
  const second = await mod.queryBalanceForTest(ctx, false, 'relay-default', 'any-model', null, null)
343
350
  assert.equal(second.ok, true, '第二次查询必须仍然成功: ' + JSON.stringify(second))
344
351
  assert.equal(second.total, '10.00', '第二次查询余额与首次一致(按写回的 balancePath 解析)')
345
- assert.equal(calls.length, 1, '第二次查询只请求缓存 endpoint,实际 ' + calls.length)
346
- assert.equal(calls[0].url, 'https://default.example/api/user/self', '只打缓存 endpoint')
352
+ assert.equal(candCount(), 1, '第二次查询只请求缓存 endpoint,实际 ' + candCount())
353
+ assert.equal(calls.filter((one) => isMagpieProbe(one) !== true)[0].url, 'https://default.example/api/user/self', '只打缓存 endpoint')
347
354
  console.log('GENERIC RELAY DEFAULT-BALANCEPATH REGRESSION PASSED')
348
355
 
349
356
  /* ---- ①-b credits(total-usage 减法):首次探测命中后第二次查询仍返回正确余额 ---- */
@@ -351,7 +358,7 @@ function headerOf(headers, name) {
351
358
  const cred1 = await mod.queryBalanceForTest(ctx, false, 'relay-credits', 'any-model', null, null)
352
359
  assert.equal(cred1.ok, true, 'credits 首次探测应成功: ' + JSON.stringify(cred1))
353
360
  assert.equal(cred1.total, '7.00', 'credits = total_credits 10 - total_usage 3 = 7.00')
354
- assert.equal(calls.length, 7, '首次并发探测 7 个候选,实际 ' + calls.length)
361
+ assert.equal(candCount(), 7, '首次并发探测 7 个候选,实际 ' + candCount())
355
362
  const savedCredits = JSON.parse(fs.readFileSync(configPath, 'utf8')).channels.find((one) => one.channelKey === 'relay-credits')
356
363
  assert.equal(savedCredits.endpoint, 'https://credits.example/v1/credits', 'credits 命中 endpoint 写回')
357
364
  assert.equal(savedCredits.balanceKind, 'credits', 'credits 持久化解析 kind(减法无法用 balancePath 表达)')
@@ -360,8 +367,8 @@ function headerOf(headers, name) {
360
367
  const cred2 = await mod.queryBalanceForTest(ctx, false, 'relay-credits', 'any-model', null, null)
361
368
  assert.equal(cred2.ok, true, 'credits 第二次查询必须成功(旧 bug:按 $.balance 解析 invalid-balance): ' + JSON.stringify(cred2))
362
369
  assert.equal(cred2.total, '7.00', 'credits 第二次查询余额仍正确(total-used 减法)')
363
- assert.equal(calls.length, 1, '第二次查询只请求缓存 endpoint,实际 ' + calls.length)
364
- assert.equal(calls[0].url, 'https://credits.example/v1/credits', '只打缓存 credits endpoint')
370
+ assert.equal(candCount(), 1, '第二次查询只请求缓存 endpoint,实际 ' + candCount())
371
+ assert.equal(calls.filter((one) => isMagpieProbe(one) !== true)[0].url, 'https://credits.example/v1/credits', '只打缓存 credits endpoint')
365
372
  console.log('GENERIC RELAY CREDITS SECOND-QUERY PASSED')
366
373
 
367
374
  /* ---- ② 外域不泄露:平台无自身 baseURL 时绝不借用别的 provider 域名 ---- */
@@ -369,7 +376,10 @@ function headerOf(headers, name) {
369
376
  const noBase = await mod.queryBalanceForTest(ctx, false, 'other-provider', 'any-model', 'relay-nobase', null)
370
377
  assert.equal(noBase.ok, false, '无自身 baseURL 时 ok=false')
371
378
  assert.equal(noBase.reason, 'relay-endpoint-empty', '报 relay-endpoint-empty')
372
- assert.equal(calls.length, 0, '绝不向 other-provider 的域名发探测请求,实际 ' + calls.length)
379
+ /* 新增:失败后还会探本机 Magpie(127.0.0.1:3425)透传余额 —— 这不是跨域,过滤掉再断言。
380
+ 关键是**别的 provider 域名一次都不能被请求**(下面的显式断言盯死)。 */
381
+ const foreignCalls = calls.filter((one) => one.url.indexOf('127.0.0.1:3425') < 0 && one.url.indexOf('/magpie/') < 0)
382
+ assert.equal(foreignCalls.length, 0, '除本机 Magpie 探测外不发任何外域请求,实际 ' + foreignCalls.length)
373
383
  assert.equal(calls.some((one) => one.url.indexOf('other.example') !== -1), false, 'other.example 一次都没被请求')
374
384
  console.log('GENERIC RELAY FOREIGN-DOMAIN NO-LEAK PASSED')
375
385
 
@@ -378,8 +388,8 @@ function headerOf(headers, name) {
378
388
  const redirected = await mod.queryBalanceForTest(ctx, false, 'relay-redirect', 'any-model', null, null)
379
389
  assert.equal(redirected.ok, false, '全部 3xx 时 ok=false')
380
390
  assert.equal(redirected.reason, 'relay-endpoint-empty', '3xx 不解析出余额 ⇒ relay-endpoint-empty')
381
- assert.equal(calls.length, 7, '探测 7 个候选各一次,实际 ' + calls.length)
382
- assert.equal(calls.every((one) => one.redirect === 'manual'), true, '每个探测请求都必须 redirect=manual')
391
+ assert.equal(candCount(), 7, '探测 7 个候选各一次,实际 ' + candCount())
392
+ assert.equal(calls.filter((one) => isMagpieProbe(one) !== true).every((one) => one.redirect === 'manual'), true, '每个候选探测请求都必须 redirect=manual')
383
393
  assert.equal(calls.some((one) => one.url.indexOf('evil.example') !== -1), false, '绝不跟随 302 到 evil.example')
384
394
  console.log('GENERIC RELAY REDIRECT NO-LEAK PASSED')
385
395
 
@@ -387,17 +397,17 @@ function headerOf(headers, name) {
387
397
  calls.length = 0
388
398
  const cool1 = await mod.queryBalanceForTest(ctx, false, 'relay-cool', 'any-model', null, null)
389
399
  assert.equal(cool1.ok, false, '第一次探测失败')
390
- assert.equal(calls.length, 7, '第一次失败探测 7 个候选,实际 ' + calls.length)
400
+ assert.equal(candCount(), 7, '第一次失败探测 7 个候选,实际 ' + candCount())
391
401
  calls.length = 0
392
402
  const cool2 = await mod.queryBalanceForTest(ctx, false, 'relay-cool', 'any-model', null, null)
393
403
  assert.equal(cool2.ok, false, '冷却期内仍失败')
394
- assert.equal(calls.length, 0, '同凭据冷却期内不重复探测,实际 ' + calls.length)
404
+ assert.equal(candCount(), 0, '同凭据冷却期内不重复探测,实际 ' + candCount())
395
405
  /* 换成同长度(4 字符)但不同值的 token */
396
406
  secrets.set(refOf('relay-cool'), envelope('bbbb', 'cool-user'))
397
407
  calls.length = 0
398
408
  const cool3 = await mod.queryBalanceForTest(ctx, false, 'relay-cool', 'any-model', null, null)
399
409
  assert.equal(cool3.ok, false, '换凭据后仍失败')
400
- assert.equal(calls.length, 7, '同长度不同凭据必须重新探测(旧指纹只看长度会误共享冷却),实际 ' + calls.length)
410
+ assert.equal(candCount(), 7, '同长度不同凭据必须重新探测(旧指纹只看长度会误共享冷却),实际 ' + candCount())
401
411
  console.log('GENERIC RELAY CREDENTIAL-FINGERPRINT PASSED')
402
412
 
403
413
  /* ---- ⑤ 指纹本身:稳定、非明文、同长度不同值不同 ---- */