dsh-desktop-statusbar 3.0.6 → 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/lib/index.js CHANGED
@@ -44,7 +44,7 @@
44
44
  import { z } from './vendor/zod/index.js'
45
45
  import {
46
46
  adapterFor, adaptersFor, BALANCE_PROVIDER_ENV, parseDeepSeekBalance, pluginRoutesIn,
47
- magpieModelProvider, magpieModelPrefix, magpieQuotaEntries, magpieBalanceOf, magpieAccountFromRoute,
47
+ magpieModelProvider, magpieModelPrefix, magpieModelQuotaProvider, magpieQuotaEntries, magpieBalanceOf, magpieAccountFromRoute,
48
48
  } from './balance-api.js'
49
49
  import { holidayHtmlToText, parseHolidayNotice } from './holiday.js'
50
50
  import { isUpdating, lastUpdateResult, resolveSelfDir, selfUpdateOnce } from './self-update.js'
@@ -2238,7 +2238,26 @@ async function queryRelayBalance(ctx, config, now) {
2238
2238
  }
2239
2239
  const raw = relayValueAt(data, relayPathSegments(config.balancePath))
2240
2240
  const parsed = typeof raw === 'number' ? raw : typeof raw === 'string' && raw.trim().length > 0 ? Number(raw) : NaN
2241
- if (!Number.isFinite(parsed)) return { ok: false, at: now, reason: 'invalid-balance', provider: config.channelKey }
2241
+ if (!Number.isFinite(parsed)) {
2242
+ /* 配置的 balancePath 在这份响应上解析不出来(典型:默认 `data.quota`,上游却返回
2243
+ `{ balance, unit }`)时,先按通用形状在同一响应上再试一遍,成功就按 generic 结果返回。
2244
+ 这条对所有自定义中转站生效,不针对任何具体站点。 */
2245
+ const generic = parseGenericRelayBalanceAny(data)
2246
+ if (generic !== null) {
2247
+ return {
2248
+ ok: true,
2249
+ at: now,
2250
+ source: 'relay',
2251
+ provider: config.channelKey,
2252
+ currency: generic.currency.length > 0 ? generic.currency : config.currency,
2253
+ total: generic.total,
2254
+ feeMultiplier: config.feeMultiplier,
2255
+ parts: [],
2256
+ available: true,
2257
+ }
2258
+ }
2259
+ return { ok: false, at: now, reason: 'invalid-balance', provider: config.channelKey }
2260
+ }
2242
2261
  /* 只做单位换算,不乘费用倍率:余额是账上真实金额,不是计费口径。 */
2243
2262
  const amount = parsed / config.balanceDivisor
2244
2263
  return {
@@ -2933,6 +2952,10 @@ const GENERIC_RELAY_AMOUNT_FIELDS = ['available', 'remaining_balance', 'balance_
2933
2952
  * 普通调用者请用下面的 parseGenericRelayBalance(只返回 { currency, total })。
2934
2953
  * 注意:subscription 的总额度字段不是余额,已从候选与解析中删除。
2935
2954
  */
2955
+ /* 通用中转站解析支持的响应种类(与 parseGenericRelayBalanceDetailed 的 kind 分支一一对应)。
2956
+ parseGenericRelayBalanceAny 与解析器共用这一份,避免两处维护漂移。 */
2957
+ const GENERIC_RELAY_KINDS = ['usage', 'user-self', 'credit-grants', 'credits']
2958
+
2936
2959
  function parseGenericRelayBalanceDetailed(kind, data) {
2937
2960
  if (data === null || data === undefined || typeof data !== 'object' || Array.isArray(data)) return null
2938
2961
  const objectOf = (value) => value !== null && value !== undefined
@@ -3031,6 +3054,22 @@ function parseGenericRelayBalance(kind, data) {
3031
3054
  return detailed === null ? null : { currency: detailed.currency, total: detailed.total }
3032
3055
  }
3033
3056
 
3057
+ /**
3058
+ * 通用中转站「形状未知」时的兜底解析:依次试 usage / user-self / credit-grants / credits,
3059
+ * 第一个能解析出余额的胜出,返回同样的 { currency, total }。全失败返回 null。
3060
+ *
3061
+ * 用途:平台配置了 endpoint、但配置的 balancePath 在这份响应上解析不出来(例如配置了默认
3062
+ * `data.quota`,而上游返回的是 `{ balance: 34.5, unit: 'USD' }`)时,先按同一份响应再试一遍通用
3063
+ * 形状,命中就用通用结果,避免只因路径不符就 invalid-balance。
3064
+ */
3065
+ function parseGenericRelayBalanceAny(data) {
3066
+ for (let i = 0; i < GENERIC_RELAY_KINDS.length; i += 1) {
3067
+ const parsed = parseGenericRelayBalance(GENERIC_RELAY_KINDS[i], data)
3068
+ if (parsed !== null) return parsed
3069
+ }
3070
+ return null
3071
+ }
3072
+
3034
3073
  /**
3035
3074
  * 从 settings 服务的 live config 里找 provider 的接入配置。
3036
3075
  * settings.describe() 返回每个插件 entry 的 SettingsDescriptor,value 是当前配置;
@@ -3499,6 +3538,13 @@ async function queryMagpieBalance(ctx, now, options) {
3499
3538
  const byPrefix = magpieModelPrefix(model)
3500
3539
  providerName = byPrefix === null ? null : providerAlias(byPrefix)
3501
3540
  }
3541
+ /* owned_by / 前缀都可能命不中 quotas:`owned_by=work`(前缀也只取第一段=work),
3542
+ 而 quotas 里是 `work/codex`。此时按「模型 id 的最长前缀」匹配 quotas.provider
3543
+ (通用最长前缀逻辑,不写死任何站名;任何 `<provider>/<model>` 形模型都适用)。 */
3544
+ if (providerName === null || magpieQuotaEntries(quotas, providerName).length === 0) {
3545
+ const byLongest = magpieModelQuotaProvider(quotas, model)
3546
+ if (byLongest !== null) providerName = providerAlias(byLongest)
3547
+ }
3502
3548
  /* 模型也认不出时保留 hint 作为诊断用的最后候选(让下游如实报 provider-not-found)。 */
3503
3549
  if (providerName === null && providerHint.length > 0) providerName = providerAlias(providerHint)
3504
3550
  if (providerName === null) {
@@ -3524,8 +3570,9 @@ async function queryMagpieBalance(ctx, now, options) {
3524
3570
  ok: true, at: now, source: 'magpie-quotas', provider: 'magpie',
3525
3571
  upstream: providerName, account: parsed.account,
3526
3572
  currency: parsed.currency, total: parsed.total,
3527
- isCredits: parsed.isCredits === true, isPercent: false,
3573
+ isCredits: parsed.isCredits === true, isPercent: parsed.isPercent === true,
3528
3574
  parts: parsed.parts,
3575
+ ...(parsed.windows === undefined ? {} : { windows: parsed.windows }),
3529
3576
  toppedUp: parsed.toppedUp === undefined ? '0.00' : parsed.toppedUp,
3530
3577
  granted: parsed.granted === undefined ? '0.00' : parsed.granted,
3531
3578
  ...(parsed.rewards === undefined ? {} : { rewards: parsed.rewards }),
@@ -3578,13 +3625,45 @@ async function queryBalance(ctx, force, provider, model, relay, session) {
3578
3625
  : undefined
3579
3626
  }
3580
3627
  const matches = [byRelay, byProvider, byModel]
3628
+ /* 直连余额失败时,若该中转站同时配置在 Magpie 里(quotas 有 provider 条目/百分比),
3629
+ 则透传 Magpie 查到的余额。不写站名、不伪造值:只有 Magpie 明确查不到才返回原 relay 失败。 */
3630
+ const magpieFallback = async (channelKey) => {
3631
+ const fromMagpie = await queryMagpieBalance(ctx, now, { model: model, session: session, providerHint: channelKey })
3632
+ /* 命中值得返回时打 viaMagpie:true(source 仍 'magpie-quotas'),让前端/调用方识别这是 Magpie 兜底。 */
3633
+ if (fromMagpie.ok === true) return Object.assign({}, fromMagpie, { viaMagpie: true })
3634
+ if (fromMagpie.reason === 'magpie-provider-not-found' || fromMagpie.reason === 'magpie-unknown-model') return null
3635
+ return null
3636
+ }
3581
3637
  for (const one of matches) {
3582
- if (usable(one) === true) return queryRelayBalance(ctx, one, now)
3638
+ if (usable(one) === true) {
3639
+ const relayResult = await queryRelayBalance(ctx, one, now)
3640
+ if (relayResult !== null && relayResult.ok === true) return relayResult
3641
+ const fromMagpie = await magpieFallback(one.channelKey)
3642
+ if (fromMagpie !== null) return fromMagpie
3643
+ return relayResult
3644
+ }
3583
3645
  }
3584
3646
  const emptyHit = matches.find((one) => emptyEndpoint(one) === true)
3585
3647
  if (emptyHit !== undefined) {
3586
3648
  const discovered = await queryDiscoveredRelayBalance(ctx, now, emptyHit)
3587
3649
  if (discovered !== null) return discovered
3650
+ /* 首次自动探测失败后,再用该平台自身的 relayProviderBaseUrl + provider 的 key 走一次
3651
+ 通用中转站探测(不跨站、不拿别家 baseURL)。成功就返回;仍失败原样报 relay-endpoint-empty。 */
3652
+ const platformBase = relayProviderBaseUrl(ctx, emptyHit.channelKey)
3653
+ if (platformBase !== null) {
3654
+ const platformKey = await resolveGenericRelayKey(ctx, emptyHit.channelKey, null)
3655
+ if (platformKey !== null) {
3656
+ const fromGeneric = await queryGenericRelayBalance(ctx, now, emptyHit.channelKey, {
3657
+ baseURL: platformBase,
3658
+ key: platformKey,
3659
+ })
3660
+ if (fromGeneric !== null) return fromGeneric
3661
+ }
3662
+ }
3663
+ /* 直连 discovered/generic 都失败:若该平台同时配置在 Magpie 里,透传 Magpie 余额;
3664
+ Magpie 明确查不到(provider-not-found/unknown-model)才原样报 relay-endpoint-empty。 */
3665
+ const fromMagpie = await queryMagpieBalance(ctx, now, { model: model, session: session, providerHint: emptyHit.channelKey })
3666
+ if (fromMagpie.ok === true) return Object.assign({}, fromMagpie, { viaMagpie: true })
3588
3667
  return { ok: false, at: now, reason: 'relay-endpoint-empty', provider: emptyHit.channelKey }
3589
3668
  }
3590
3669
  }
@@ -3650,6 +3729,20 @@ async function queryBalance(ctx, force, provider, model, relay, session) {
3650
3729
  })
3651
3730
  if (fromGeneric !== null) return fromGeneric
3652
3731
  }
3732
+ } else {
3733
+ /* settings 里取不到 provider 配置时(模型页没有该 provider 的条目),用 cordis.patch.yml 的
3734
+ baseURL + 按引用名解析的 key 再探一次通用中转站端点。对所有自定义 provider 生效。 */
3735
+ const patchBase = providerBaseUrlOf(provider)
3736
+ if (typeof patchBase === 'string' && patchBase.trim().length > 0) {
3737
+ const patchKey = await resolveGenericRelayKey(ctx, provider, null)
3738
+ if (patchKey !== null) {
3739
+ const fromPatch = await queryGenericRelayBalance(ctx, now, provider, {
3740
+ baseURL: patchBase.trim(),
3741
+ key: patchKey,
3742
+ })
3743
+ if (fromPatch !== null) return fromPatch
3744
+ }
3745
+ }
3653
3746
  }
3654
3747
  /* 内置适配器认不出的自定义 provider 也可能挂在 Magpie 网关:
3655
3748
  拿 provider 名直接问,明确"查不到"才退回未知平台;上游明确报错则原样返回。 */
@@ -4383,12 +4476,25 @@ function tokenCost(model, at, parts, provider, feeMultiplier, book) {
4383
4476
  const price = entry.tiered === false ? entry.peak : (isPeakTime(at) ? entry.peak : entry.offPeak)
4384
4477
  const use = price !== null && price !== undefined ? price : entry.peak
4385
4478
  if (use === null || use === undefined) return 0
4479
+ /* Magpie 是**本机聚合网关**,不套用通用自建 relay「缺倍率不计价」的门槛:
4480
+ provider 含 magpie / 模型走 remote-magpie/、magpie/ 时,缺价格条目倍率默认按 1 计价,
4481
+ 与子代理 Magpie 路径(magpieSubagentTokenCost)口径一致,否则主会话里走 Magpie
4482
+ 的调用会一律算成 0、只在台账里挂成欠账(用户报的「走 Magpie 有时不被计费」)。
4483
+ 通用 relay(非 Magpie)仍走下面「缺 feeConfigured 就返回 0 / 记欠账」的老行为。 */
4484
+ const magpie = isMagpieMainUsage(provider, model)
4386
4485
  /* relay:必须明确配置过价格条目的费用倍率,否则视为无价(由调用方记欠账)。 */
4387
- const entryFee = relayPriceFee(entry)
4486
+ const entryFeeRaw = relayPriceFee(entry)
4487
+ const entryFee = entryFeeRaw === null ? (magpie === true ? 1 : null) : entryFeeRaw
4388
4488
  if (entryFee === null) return 0
4389
- const channelMultiplier = typeof feeMultiplier === 'number' && Number.isFinite(feeMultiplier) && feeMultiplier > 0
4390
- ? feeMultiplier
4391
- : relayFeeMultiplierForProvider(provider)
4489
+ /* Magpie 与子代理路径一致:通道倍率一律取 magpieChannelMultiplier(含 channelKey 大小写/别名
4490
+ 兜底到唯一 Magpie 通道),不用事件上那个通用 relay 的 feeMultiplier —— 后者按 channelKey
4491
+ 精确匹配,provider 写作小写 magpie 时匹配不到 'Magpie' 通道会退回 1,配置就丢了。
4492
+ 通用 relay 仍走 feeMultiplier 参数 / relayFeeMultiplierForProvider。 */
4493
+ const channelMultiplier = magpie === true
4494
+ ? magpieChannelMultiplier(provider)
4495
+ : (typeof feeMultiplier === 'number' && Number.isFinite(feeMultiplier) && feeMultiplier > 0
4496
+ ? feeMultiplier
4497
+ : relayFeeMultiplierForProvider(provider))
4392
4498
  /* 旧 relay 通道倍率(兼容存量)× 价格条目倍率(新口径) */
4393
4499
  return ((parts.input * numOrZero(use.input) + parts.cacheRead * numOrZero(use.cacheRead)
4394
4500
  + parts.cacheWrite * numOrZero(use.cacheWrite) + parts.output * numOrZero(use.output)) / 1e6)
@@ -4401,6 +4507,19 @@ function isMagpieSubagentUsage(provider, model) {
4401
4507
  return typeof model === 'string' && /^(?:remote-magpie|magpie)\//i.test(model) === true
4402
4508
  }
4403
4509
 
4510
+ /**
4511
+ * 主会话(非子代理)用量是否按 Magpie 计价:provider 含 magpie(magpie / remote-magpie 等别名),
4512
+ * **或**模型走 `remote-magpie/`、`magpie/` 命名空间(无论 provider 是否为空)。
4513
+ *
4514
+ * remote-magpie/ 前缀就是局域网 Magpie 的模型命名空间,前缀本身即归属 Magpie,
4515
+ * 不能因为 provider 为空就降级成通用 relay。与 isMagpieSubagentUsage 口径一致。
4516
+ */
4517
+ function isMagpieMainUsage(provider, model) {
4518
+ const providerText = typeof provider === 'string' ? provider : ''
4519
+ if (providerText.length > 0 && relayIsMagpie(providerText) === true) return true
4520
+ return typeof model === 'string' && /^(?:remote-magpie|magpie)\//i.test(model) === true
4521
+ }
4522
+
4404
4523
  /**
4405
4524
  * Magpie 通道倍率:先按 channelKey 精确匹配;provider 大小写/别名对不上(magpie vs Magpie)时,
4406
4525
  * 退回配置里唯一的 Magpie 通道(readRelayConfig 保证最多一个)。缺省 1。
@@ -5645,6 +5764,7 @@ export {
5645
5764
  /* relaySettings 合并逻辑(仅测试:验证改地址/解析字段清 balanceKind、无关更新保留)。 */
5646
5765
  relaySettings as relaySettingsForTest,
5647
5766
  parseGenericRelayBalance,
5767
+ parseGenericRelayBalanceAny,
5648
5768
  queryGenericRelayBalance,
5649
5769
  /* 空地址探测的冷却表与指纹(仅测试:验证同长度不同凭据不共享冷却、Map 容量上限)。 */
5650
5770
  relayDiscoveryFailures as relayDiscoveryFailuresForTest,
@@ -6584,10 +6704,23 @@ function settleUnpriced(ledger) {
6584
6704
  ? peakPrice
6585
6705
  : (entry.offPeak !== null && entry.offPeak !== undefined ? entry.offPeak : entry.peak)
6586
6706
  const affiliation = providerAffiliation(debt.provider, debt.model)
6587
- const entryFee = affiliation === 'relay' ? relayPriceFee(entry) : 1
6588
- /* 新口径:relay 必须明确配置倍率才结算;旧债务(feeMultiplier>1)保持兼容。 */
6589
- if (affiliation === 'relay' && entryFee === null && !(debt.feeMultiplier > 1)) { remaining.push(debt); continue }
6590
- const effectiveEntryFee = affiliation === 'relay' && entryFee !== null ? entryFee : 1
6707
+ /* Magpie 归属(provider 含 magpie / 模型 remote-magpie/、magpie/)缺倍率默认 1,
6708
+ 与 tokenCost / magpieSubagentTokenCost 口径一致:老台账里挂了 Magpie 欠账的,
6709
+ 这里也照 1 结算掉,不再永远留在欠账里。通用 relay 缺倍率仍要求显式配置。 */
6710
+ const magpie = isMagpieMainUsage(debt.provider, debt.model)
6711
+ /* 两条路径,互斥且各自写清:
6712
+ · Magpie:恒可结算,价格条目倍率优先用**已配置**的(relayPriceFee 非 null),没配默认 1 ——
6713
+ 不能把已配置的倍率抹成 1。
6714
+ · 普通 relay:必须明确配置倍率才结算(旧债务 feeMultiplier>1 保持兼容),否则继续挂欠账。 */
6715
+ let effectiveEntryFee
6716
+ if (magpie === true) {
6717
+ const magpieEntryFee = relayPriceFee(entry)
6718
+ effectiveEntryFee = magpieEntryFee === null ? 1 : magpieEntryFee
6719
+ } else {
6720
+ const relayEntryFee = affiliation === 'relay' ? relayPriceFee(entry) : null
6721
+ if (affiliation === 'relay' && relayEntryFee === null && !(debt.feeMultiplier > 1)) { remaining.push(debt); continue }
6722
+ effectiveEntryFee = affiliation === 'relay' && relayEntryFee !== null ? relayEntryFee : 1
6723
+ }
6591
6724
  const cost = (costOfTier(debt.peak, peakPrice) + costOfTier(debt.offPeak, offPeakPrice))
6592
6725
  * debt.feeMultiplier * effectiveEntryFee
6593
6726
  addDayCost(day, debt.model, cost)
@@ -6679,7 +6812,9 @@ async function auditProviderPricingHistory(ledger, book) {
6679
6812
  slot.oldCost += officialCost
6680
6813
  slot.oldCurrency[code] = numOrZero(slot.oldCurrency[code]) + officialCost
6681
6814
  const entryFee = relayPriceFee(entry)
6682
- if (entryFee === null) {
6815
+ /* Magpie 缺倍率默认按 1(与 tokenCost 一致),不当欠账处理。 */
6816
+ const magpieAudit = isMagpieMainUsage(one.provider, one.model)
6817
+ if (entryFee === null && magpieAudit !== true) {
6683
6818
  slot.debts.push({ provider: one.provider, model: one.model, parts: one.parts, peakTime: isPeakTime(one.time) })
6684
6819
  } else {
6685
6820
  const newCost = tokenCost(one.model, one.time, one.parts, one.provider, 1, auditBook)
@@ -7046,8 +7181,12 @@ async function collectFileIntoLedger(ledger, file, text, fromMs, rebuilding) {
7046
7181
  v4 重算那一轮的钱由重建通道独立算出并在末尾覆盖,这里不吃双份。 */
7047
7182
  const affiliation = providerAffiliation(one.provider, one.model)
7048
7183
  const entry = priceEntryFor(one.model)
7184
+ /* Magpie 归属(provider 含 magpie / 模型 remote-magpie/、magpie/)即使价格条目没配倍率也
7185
+ 视为「有价」(tokenCost 对 Magpie 缺倍率默认按 1 折),绝不能挂成欠账 —— 否则主会话
7186
+ 走 Magpie 的调用会一直不计费,与子代理 Magpie 路径口径不一致。通用 relay 不变。 */
7187
+ const magpie = isMagpieMainUsage(one.provider, one.model)
7049
7188
  const relayFee = affiliation === "relay" && entry !== null ? relayPriceFee(entry) : null
7050
- const priced = entry !== null && (affiliation !== "relay" || relayFee !== null)
7189
+ const priced = entry !== null && (affiliation !== "relay" || relayFee !== null || magpie === true)
7051
7190
  if (priced !== true) {
7052
7191
  /* relay 没配倍率:记 provider/model 欠账(feeMultiplier 记 1),绝不按官方价结算。 */
7053
7192
  addUnpricedByProvider(day, one.provider, one.model, one.parts, peakTime, affiliation === "relay" ? 1 : one.feeMultiplier)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-desktop-statusbar",
3
- "version": "3.0.6",
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,10 +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, 2, '空态圆环照旧是底环 + 进度弧');
116
- assert.strictEqual(Array.from(dashRing.children)[1].props.strokeDashoffset, 2 * Math.PI * 5.5, '0% 时进度弧整段留空');
117
- 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 数据时环心也不渲染数字');
118
129
 
119
130
  /* ------------------------------------------------------------- 段渲染 */
120
131
  const baseSrc = {
@@ -141,22 +152,44 @@ assert.strictEqual(contextMeter.compact, null, '没有 capacity 时压缩点为
141
152
  console.log('= 圆环带上下文占用气泡;压缩点随模型自适应;token 计数段已并入总计,峰谷可点');
142
153
 
143
154
  /* ------------------------------------------------------------- 圆环几何 */
144
- const ring = api.contextRing(62, 'idle');
145
- assert.strictEqual(ring.type, 'svg', '圆环是 svg');
146
- assert.ok(String(ring.props.className).indexOf('dsb-ring') === 0, '圆环类名');
147
- 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;
148
162
  assert.strictEqual(circles[0].props.className, 'dsb-ring-track', '底环');
149
163
  assert.strictEqual(circles[1].props.className, 'dsb-ring-fill', '进度弧');
150
164
  assert.strictEqual(circles[1].props.transform, 'rotate(-90 7 7)', '起点在 12 点方向(整体转 -90°)');
151
165
  assert.strictEqual(Math.round(circles[1].props.strokeDasharray), Math.round(2 * Math.PI * 5.5), '周长 = 2πr');
152
166
  assert.strictEqual(Math.round(circles[1].props.strokeDashoffset), Math.round(2 * Math.PI * 5.5 * 0.38), '62% 时留 38% 的缺口');
153
- assert.ok(String(api.contextRing(62, 'running').props.className).includes('dsb-ring-running'), '运行中 → 绿色');
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)');
176
+ /* 主会话百分比 vs 团队弧长不同源:弧长 55% 但环心数字显示主会话自己的 20 */
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');
180
+ /* 小数取整:32.6 → 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');
183
+ /* 100 留空:14px 环心塞不下三位 */
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)');
154
187
  assert.ok(String(api.contextRing(62, 'error').props.className).includes('dsb-ring-error'), '报错 → 红色');
155
188
  assert.ok(String(api.contextRing(62, 'approval').props.className).includes('dsb-ring-approval'), '待审批 → 黄色');
156
189
  /* 底环:没有压缩点时整圈(不旋转、不设 dasharray);有压缩点时在压缩点处开一个圆头缺口 */
157
190
  assert.strictEqual(circles[0].props.transform, undefined, '没有压缩点时底环不旋转');
158
191
  assert.strictEqual(circles[0].props.strokeDasharray, undefined, '没有压缩点时底环整圈');
159
- const notchTrack = Array.from(api.contextRing(62, 'idle', 55.0464).children)[0];
192
+ const notchTrack = ringParts(api.contextRing(62, 'idle', 55.0464)).circles[0];
160
193
  assert.strictEqual(notchTrack.props.transform, 'rotate(-90 7 7)', '开缺口时底环转到 12 点起(与进度弧同一口径)');
161
194
  assert.strictEqual(notchTrack.props.strokeLinecap, 'round', '缺口两端是圆头');
162
195
  const notchDashes = notchTrack.props.strokeDasharray.split(' ').map(Number);
@@ -164,7 +197,7 @@ assert.strictEqual(notchDashes.length, 3, '缺口 = 画-空-画 三段');
164
197
  assert.strictEqual(notchDashes[1], 3, '空洞 = 净宽 1 + 描边 2(圆头各向洞内啃半个线宽)');
165
198
  assert.ok(Math.abs(notchDashes[0] + notchDashes[1] + notchDashes[2] - 2 * Math.PI * 5.5) < 1e-12, '三段之和精确等于周长');
166
199
  assert.ok(Math.abs((notchDashes[0] + notchDashes[1] / 2) - 2 * Math.PI * 5.5 * 0.550464) < 1e-12, '缺口中心落在压缩点上');
167
- console.log('= 圆环:12 点起、周长与进度正确、颜色随状态;压缩点处开圆头缺口');
200
+ console.log('= 圆环:外层 span + 内部 SVG/数字 span;12 点起、周长与进度正确、颜色随状态;压缩点处开圆头缺口;环心同源显示占用数字');
168
201
 
169
202
  /* 点击与收起的契约:圆环包在按钮里(hover/展开有灰底),面板点别处收起 */
170
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)'],
@@ -513,6 +513,64 @@ const bookOf = (entry) => ({ x: entry });
513
513
  }
514
514
  }
515
515
 
516
+ console.log('\n===== ⑯ 官方状态栏只藏官方节点:官方选择器定位 + observer 过滤 =====');
517
+ /* 3.0.7 用户实测两条要求:
518
+ ① 隐藏必须**只认官方节点**:旧的"从 .dsb-root 逐层向上把非本插件兄弟节点全 display:none"
519
+ 会把第三方插件后插入的节点也误藏。改成与 CSS 相同的官方选择器精确定位、只藏官方节点。
520
+ ② MutationObserver 只在新增节点匹配(或包含匹配)官方选择器时重扫一次,普通流式文字变化
521
+ 不触发,避免卡顿;卸载只还原被我们藏过的官方节点。 */
522
+ assert.ok(/new MutationObserver\(/.test(clientCode), '藏官方底栏必须用 MutationObserver(不能只跑一次)');
523
+ assert.ok(/observer\.observe\(observeRoot,\s*\{\s*childList:\s*true,\s*subtree:\s*true\s*\}\)/.test(clientCode), '观察 body/documentElement 的 childList+subtree(侧栏重构/深层子树插入也能压住)');
524
+ assert.ok(/observer\.disconnect\(\)/.test(clientCode), '卸载时必须断开 observer');
525
+ assert.ok(/hidden\.forEach\(\(prev, el\) => \{ el\.style\.display = prev; \}\)/.test(clientCode),
526
+ '卸载时把藏过的节点逐个还原(关侧栏/关插件都不留异常)');
527
+ assert.ok(/typeof MutationObserver === "function"/.test(clientCode), '老环境无 MutationObserver 时要优雅降级(退回单次清扫)');
528
+ /* ① 只认官方选择器:三条官方选择器都在,且用 querySelectorAll 定位;
529
+ 不许再出现"逐层向上扫兄弟节点"的 indexOf 循环(node = parent / parent.children)。 */
530
+ assert.ok(/aria-label\*="上下文"/.test(clientCode) && /aria-label\*="context used"/.test(clientCode),
531
+ '必须用官方上下文按钮的 aria-label 选择器定位');
532
+ assert.ok(/span\[class\$="_root"\]>button\[aria-haspopup="dialog"\]\[class\$="_trigger"\]/.test(clientCode),
533
+ '必须用官方用量按钮的结构选择器(span[class$=_root]>button[..._trigger])定位');
534
+ assert.ok(/const OFFICIAL_SELECTORS = \[/.test(clientCode), '官方选择器应集中成一个常量表,与 CSS 同源');
535
+ assert.ok(/dock\.querySelectorAll\(OFFICIAL\)/.test(clientCode), '只对官方选择器匹配的节点做隐藏(querySelectorAll(OFFICIAL))');
536
+ assert.ok(!/while \(node && node !== dock\)/.test(clientCode),
537
+ '不许再有"从 .dsb-root 逐层向上到 dock"的兄弟节点清扫循环(会误藏第三方插件节点)');
538
+ assert.ok(!/child\.contains\(barRoot\)/.test(clientCode),
539
+ '不许再用 child.contains(barRoot) 判断兄弟节点并整层 display:none');
540
+ /* ② observer 有官方节点过滤:回调里遍历 addedNodes,touchesOfficial(node) 命中才 sweep。 */
541
+ assert.ok(/const touchesOfficial = \(node\)/.test(clientCode), 'observer 回调必须有"是否牵涉官方节点"的过滤函数');
542
+ assert.ok(/record\.addedNodes/.test(clientCode), 'observer 只检查 addedNodes(新增节点)');
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 则不隐藏(避免同层带本插件根时误藏整层)');
572
+ console.log(' 只认官方选择器、无兄弟全隐藏循环;observer 有官方节点过滤,卸载只还原官方节点');
573
+
516
574
  console.log('\nFIX REGRESSION CHECKS PASSED');
517
575
  })().catch((error) => {
518
576
  console.error('FIX REGRESSION CHECKS FAILED:', error && error.message ? error.message : error);
@@ -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
  /* ---- ⑤ 指纹本身:稳定、非明文、同长度不同值不同 ---- */