dsh-token-dash 2.3.1 → 2.4.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.
package/README.en.md CHANGED
@@ -41,13 +41,14 @@ Only the official endpoints listed below are called. Any other provider is still
41
41
  | Kimi Coding | `KIMI_API_KEY` / `KIMI_CODING_API_KEY`, optional `MOONSHOT_API_KEY` | `GET api.kimi.com/coding/v1/usages`; falls back to `GET api.moonshot.cn/v1/users/me/balance` | Subscription / API usage | 5h + weekly/monthly windows; falls back to balance |
42
42
  | OpenRouter | `OPENROUTER_API_KEY` | `GET openrouter.ai/api/v1/credits` | API usage | Credits (USD) |
43
43
  | Qwen | `DASHSCOPE_API_KEY` (CNY) / `DASHSCOPE_INTL_API_KEY` (USD) | No balance endpoint | API usage | Local usage only; balance unsupported |
44
- | OpenCode Go | `OPENCODE_GO_API_KEY` | `GET opencode.ai/zen/go/v1/usage`, falls back to `GET opencode.ai/api/v1/usage` | Subscription | 5h / weekly / monthly windows (USD) |
44
+ | OpenCode Go | `OPENCODE_API_KEY` / `OPENCODE_GO_API_KEY` | `GET opencode.ai/zen/go/v1/usage`, falls back to `GET opencode.ai/api/v1/usage` | Subscription | 5h / weekly / monthly windows (USD) |
45
45
  | Command Code | `COMMAND_CODE_API_KEY` + `COMMAND_CODE_ORG_ID` | `GET api.commandcode.ai/alpha/billing/credits` (with `orgId`) | Subscription | 5h + weekly windows, credits (CNY) |
46
46
  | Ollama Cloud | `OLLAMA_API_KEY` | `GET ollama.com/api/balance`; `GET ollama.com/api/usage?range=30d` | API usage | Plan + purchased credits (USD), plan usage, cycle, 30-day channel usage |
47
47
  | Any other provider (self-hosted, relay, local Ollama) | None | No endpoint | API usage | Priced by model name only; unpriced rows can be backfilled |
48
48
 
49
49
  - Save keys under the names above in DSH's credential settings; the plugin reads them through the host `credentials` service, not environment variables or local login files.
50
50
  - Ollama is added through DSH's custom OpenAI-compatible provider: the route id must be `ollama` (the key reference is derived as `<ROUTE>_API_KEY` → `OLLAMA_API_KEY`). Any other id will not resolve the key and the balance card will not appear.
51
+ - OpenCode Go reads `OPENCODE_API_KEY`, the same name pi-ai uses for its routes, so configuring the LLM route is enough; `OPENCODE_GO_API_KEY` remains accepted. The `<ROUTE>_API_KEY` derivation applies to custom providers only — built-in providers get their names from the pi-ai catalog.
51
52
  - Keys are detected automatically; GLM / Kimi / OpenCode Go / Command Code can be re-detected from the dashboard footer.
52
53
  - Subscription models count toward Tokens but not cost; billing mode is pinned per key instead of following quota flakiness.
53
54
  - Balance, quota and usage are separate; a balance failure never resets today's Token ledger to zero.
@@ -57,7 +58,7 @@ Only the official endpoints listed below are called. Any other provider is still
57
58
 
58
59
  Screenshots use mock data so the full layout is visible at once.
59
60
 
60
- **P1 · Composer footer-right Pill**: API usage / subscription variants; click to open, click outside, `×` or `Esc` to close.
61
+ **P1 · Composer footer-right Pill**: API usage / subscription variants; click to open, click outside, `×` or `Esc` to close. The API variant shows one line of budget ring + today's spend + real balance; the subscription variant shows a ring per window. Colour only signals alerts — a healthy state stays neutral.
61
62
 
62
63
  <p align="center">
63
64
  <img src="https://raw.githubusercontent.com/spartawhy117/dsh-token-dash/main/docs/pic/en/pill-api.png" alt="API usage pill" />
@@ -84,14 +85,16 @@ Screenshots use mock data so the full layout is visible at once.
84
85
  - Subscription windows use three slots: first left, second center, third right; two windows occupy the first two slots.
85
86
  - Model column is capped at 150; Tokens / requests / hit rate are right-aligned.
86
87
 
87
- **P3 · Full dashboard**: cards for 8 providers, a four-cell summary (cost / real tokens / requests / cache hit rate), usage trend bars, 8-column model breakdown and a settings capsule; the page owns its scrollbar at the window edge.
88
+ **P3 · Full dashboard**: cards for 8 providers, a four-cell summary (real tokens / cost / cache hit rate / requests), a metric-switchable trend chart (including the dual-currency, dual-axis cost view), a model breakdown with subscription estimates, and a settings capsule; the page owns its scrollbar at the window edge.
88
89
 
89
90
  <p align="center">
90
91
  <img src="https://raw.githubusercontent.com/spartawhy117/dsh-token-dash/main/docs/pic/en/settings.png" alt="Full dashboard" />
91
92
  </p>
92
93
 
93
- - API usage card: budget input, planned balance, real balance, month-to-date spend; subscription card: one ring per window with remaining percentage and countdown.
94
- - Breakdown: model / Tokens / input / cache / output / requests / hit rate / cost; everything except the model column is right-aligned.
94
+ - API usage card: budget input, planned balance, real balance, month-to-date spend; subscription card: one ring per window with remaining percentage and countdown, plus an estimated monthly value when available; cards no longer carry a status line.
95
+ - Trend chart: the vertical axis takes its own column outside the plot, with three ticks that follow the selected metric; three grid lines line up with those ticks; the hit-rate axis is pinned to 100% at the top, and a single 0% day cannot drag its floor back to zero. With **two currencies** the cost metric switches to a **dual-axis, two-bar** layout — CNY on the left axis, USD on the right, each scaled to its own maximum, with a colour legend in the header.
96
+ - Total cost tile: includes subscription estimates alongside actual billing, captioned “{n} currencies · incl. estimates”.
97
+ - Breakdown: its own section heading, then model / Tokens / input / cache / output / requests / hit rate / cost; everything except the model column is right-aligned. Cost is always marked `≈` as a local estimate, and subscription rows show what those tokens would cost at API rates (or “not priced”, or `—` when no estimate exists).
95
98
  - Settings capsule: refresh interval + account-balance toggle; logs, export/import, price table and version below.
96
99
  - The settings section has an external "Settings and data" title above the capsule; the capsule itself keeps the refresh interval, logs/data controls and version row.
97
100
  - Spacing uses only 4 / 8 / 12 / 16 / 24 / 32; P2 and P3 share the same tokens.
package/README.md CHANGED
@@ -41,13 +41,14 @@
41
41
  | Kimi Coding | `KIMI_API_KEY` / `KIMI_CODING_API_KEY`,可选 `MOONSHOT_API_KEY` | `GET api.kimi.com/coding/v1/usages`;回落 `GET api.moonshot.cn/v1/users/me/balance` | 订阅 / API 用量 | 5h + 周/月窗口;订阅查询失败可回落余额 |
42
42
  | OpenRouter | `OPENROUTER_API_KEY` | `GET openrouter.ai/api/v1/credits` | API 用量 | Credits(USD) |
43
43
  | Qwen | `DASHSCOPE_API_KEY`(CNY)/ `DASHSCOPE_INTL_API_KEY`(USD) | 不请求余额接口 | API 用量 | 仅本地用量;余额不支持 |
44
- | OpenCode Go | `OPENCODE_GO_API_KEY` | `GET opencode.ai/zen/go/v1/usage`,回落 `GET opencode.ai/api/v1/usage` | 订阅 | 5h / 周 / 月窗口(USD) |
44
+ | OpenCode Go | `OPENCODE_API_KEY` / `OPENCODE_GO_API_KEY` | `GET opencode.ai/zen/go/v1/usage`,回落 `GET opencode.ai/api/v1/usage` | 订阅 | 5h / 周 / 月窗口(USD) |
45
45
  | Command Code | `COMMAND_CODE_API_KEY` + `COMMAND_CODE_ORG_ID` | `GET api.commandcode.ai/alpha/billing/credits`(带 `orgId`) | 订阅 | 5h + 周窗口、Credits(CNY) |
46
46
  | Ollama Cloud | `OLLAMA_API_KEY` | `GET ollama.com/api/balance`;`GET ollama.com/api/usage?range=30d` | API 用量 | 套餐剩余 + 购买余额(USD)、套餐已用、周期、渠道 30 天用量 |
47
47
  | 其他任意 provider(自建、中转、Ollama 本地) | 无需凭据 | 不请求任何接口 | API 用量 | 只按模型名计价;未定价可补算 |
48
48
 
49
49
  - 在 DSH 的凭据设置中按上表名称保存 Key;插件只通过宿主 `credentials` 读取,不读环境变量或本机登录文件。
50
50
  - Ollama 在 DSH 里需要用「自定义 OpenAI 兼容供应商」接入:route id 必须填 `ollama`(凭据按 `<ROUTE>_API_KEY` 派生成 `OLLAMA_API_KEY`),自定义名填别的会取不到 Key,余额卡也不会出现。
51
+ - OpenCode Go 的 `OPENCODE_API_KEY` 与 pi-ai 路由配置同名,配好 LLM 路由后无需再填第二份;旧名 `OPENCODE_GO_API_KEY` 仍兼容。`<ROUTE>_API_KEY` 派生只适用于自定义供应商,内置供应商的凭据名由 pi-ai 目录决定。
51
52
  - 填 Key 后自动探测;GLM / Kimi / OpenCode Go / Command Code 可在「全量看板」底部重新检测订阅。
52
53
  - 订阅模型计入 Tokens,但不计费用;计费形态按 Key 固化,不随配额接口抖动。
53
54
  - 余额、配额、用量分开展示;余额失败不会把当天的 Token 记账清零。
@@ -57,7 +58,7 @@
57
58
 
58
59
  以下截图使用假数据演示,便于一次看到完整效果。
59
60
 
60
- **P1 · 输入框底栏右侧 Pill**:API 用量 / 订阅两种形态,点击展开浮层,点击外部、`×` 或 `Esc` 收起。
61
+ **P1 · 输入框底栏右侧 Pill**:API 用量 / 订阅两种形态,点击展开浮层,点击外部、`×` 或 `Esc` 收起。API 态一行显示「预算环 + 今日花费 + 真实余额」,订阅态显示各窗口的用量环;颜色只表达告警,正常时保持中性色。
61
62
 
62
63
  <p align="center">
63
64
  <img src="https://raw.githubusercontent.com/spartawhy117/dsh-token-dash/main/docs/pic/pill-api.png" alt="API 用量 Pill" />
@@ -84,14 +85,16 @@
84
85
  - 订阅窗口固定三槽位:第 1 窗左、第 2 窗中、第 3 窗右;只有两窗时占前两个槽位。
85
86
  - 模型列上限 150,Tokens / 请求 / 命中右对齐;长模型名用省略号,悬浮可看全名。
86
87
 
87
- **P3 · 整页看板**:8 家供应商卡片、四格摘要带(总费用 / 真实 Tokens / 总请求数 / 缓存命中率)、用量趋势柱、8 列模型明细、底部设置胶囊;页面自己滚动,滚动条贴窗口右缘。
88
+ **P3 · 整页看板**:8 家供应商卡片、四格摘要带(真实 Tokens / 总费用 / 缓存命中率 / 总请求数)、可切指标的趋势图(含双币种双轴成本柱)、模型明细区块(含订阅估算价)、底部设置胶囊;页面自己滚动,滚动条贴窗口右缘。
88
89
 
89
90
  <p align="center">
90
91
  <img src="https://raw.githubusercontent.com/spartawhy117/dsh-token-dash/main/docs/pic/settings.png" alt="整页看板" />
91
92
  </p>
92
93
 
93
- - API 用量卡:预算输入、计划余额、真实余额、本月已花;订阅卡:每个窗口一个环 + 剩余百分比 + 倒计时。
94
- - 明细表:模型 / Tokens / 输入 / 缓存 / 输出 / 请求 / 命中 / 费用;除模型列外全部右对齐。
94
+ - API 用量卡:预算输入、计划余额、真实余额、本月已花;订阅卡:每个窗口一个环 + 剩余百分比 + 倒计时;有估算数据时订阅卡底部显示「本月估算」,卡片不再附带状态行。
95
+ - 趋势图:纵坐标独立占左侧一列(在绘图区之外),三档刻度随指标切换;上 / 中 / 下三条网格线与刻度对齐;命中率轴顶档固定 100%,单个 0% 日不会把下限拉回 0。切到「费用」且出现两种币种时改为**双轴双柱**:人民币走左轴、美元走右轴,各自按自身最大值缩放,标题行给色块图例。
96
+ - 四格总费用:与实际计费同列,**含订阅估算**,副行标注「{n} 个币种 · 含估算」。
97
+ - 明细表:独立「模型明细」区块,模型 / Tokens / 输入 / 缓存 / 输出 / 请求 / 命中 / 费用;除模型列外全部右对齐。费用一律以 `≈` 标注为本地估算,订阅行给出「若按 API 计」的估算金额(无价显示「未定价」,无估算数据显示 `—`)。
95
98
  - 设置区:胶囊外是「设置与数据管理」区块标题;胶囊内第一行刷新间隔 + 账户余额开关,下面是日志、导出导入、价格表与版本。
96
99
  - 间距只使用 4 / 8 / 12 / 16 / 24 / 32 六档,P2 / P3 同一套 token。
97
100
 
package/client.js CHANGED
@@ -11,6 +11,36 @@ window.__ModuleLoader__.load({
11
11
 
12
12
  const API = '/token-dash/api'
13
13
  const PKG = 'dsh-token-dash'
14
+
15
+ // 客户端事件上报:走宿主 /log 落到本机日志。三层限流防止「增强本身变成故障源」。
16
+ const CLIENT_LOG_PER_EVENT = 20
17
+ const CLIENT_LOG_PER_HOUR = 100
18
+ const clientLogState = { seen: new Set(), perEvent: new Map(), windowStart: 0, total: 0 }
19
+
20
+ function reportClientLog(module, event, meta) {
21
+ try {
22
+ const now = Date.now()
23
+ const state = clientLogState
24
+ if (now - state.windowStart > 3600_000) {
25
+ state.windowStart = now
26
+ state.perEvent.clear()
27
+ state.seen.clear()
28
+ state.total = 0
29
+ }
30
+ const key = `${event}|${meta?.message ?? ''}|${meta?.path ?? ''}`
31
+ if (state.seen.has(key)) return
32
+ if ((state.perEvent.get(event) ?? 0) >= CLIENT_LOG_PER_EVENT) return
33
+ if (state.total >= CLIENT_LOG_PER_HOUR) return
34
+ state.seen.add(key)
35
+ state.perEvent.set(event, (state.perEvent.get(event) ?? 0) + 1)
36
+ state.total += 1
37
+ void fetch(`${API}/log`, {
38
+ method: 'POST',
39
+ headers: { 'content-type': 'application/json' },
40
+ body: JSON.stringify({ module, event, meta }),
41
+ }).catch(() => {})
42
+ } catch { /* 日志失败绝不影响渲染 */ }
43
+ }
14
44
  const PAGE_ID = 'token-dash'
15
45
  const REPO_URL = 'https://github.com/spartawhy117/dsh-token-dash'
16
46
  const SUB_CRITICAL = 90
@@ -44,6 +74,11 @@ window.__ModuleLoader__.load({
44
74
  '30秒': '30s', '1分钟': '1m', '5分钟': '5m',
45
75
  '社区': 'Community', '内置兜底': 'Built-in fallback',
46
76
  '查询失败': 'Query failed', '套餐查询失败': 'Quota query failed',
77
+ '数据加载中': 'Loading data',
78
+ '含估算': 'incl. estimates',
79
+ 'API 与订阅金额均为本地按目录价估算,非供应商账单;缓存读按缓存价计,命中率高的行每 token 成本显著更低,不同行不可直接按 token 数比较;不同币种需自行换算': 'Both API and subscription amounts are estimated locally from catalog prices, not provider invoices; cached reads use the cache price, so rows with a higher hit rate cost much less per token and rows are not directly comparable by token count; currencies are not converted.',
80
+ '本月估算': 'Est. this month',
81
+ '订阅不计价,估算值仅作参考': 'Subscription is not billed; the estimate is for reference only',
47
82
  '周': 'Week', '月': 'Month', '重置': 'Reset',
48
83
  'API 用量': 'API usage', '订阅': 'Subscription', '账户套餐': 'Account plan',
49
84
  '预算': 'Budget', '未设置': 'Not set', '今日 {value}': 'Today {value}',
@@ -158,6 +193,8 @@ window.__ModuleLoader__.load({
158
193
  muted: 'var(--dsw-alias-label-secondary, rgba(235,235,235,.65))',
159
194
  weak: 'var(--dsw-alias-label-tertiary, rgba(235,235,235,.45))',
160
195
  accent: 'var(--dsw-alias-state-business-primary, #6ea8ff)',
196
+ // 第二条数据序列(双轴图的次币种柱):独立色相,不借用绿/黄/红等状态语义色
197
+ series2: 'var(--td-series-2, #c9a5ff)',
161
198
  warn: 'var(--dsw-alias-state-warn-primary, #f0a020)',
162
199
  over: 'var(--dsw-alias-state-error-primary, #e05a5a)',
163
200
  ok: 'var(--td-state-ok, var(--dsw-alias-state-success-primary, #4ed17e))',
@@ -243,7 +280,8 @@ window.__ModuleLoader__.load({
243
280
  }
244
281
 
245
282
  async function getJson(path) {
246
- const res = await fetch(`${API}${path}`, { headers: { accept: 'application/json' } })
283
+ // 10 秒超时:把「一直等」转成可重试的失败态,避免长时间无反馈(REQ-07)
284
+ const res = await fetch(`${API}${path}`, { headers: { accept: 'application/json' }, signal: AbortSignal.timeout(10_000) })
247
285
  const body = await res.json().catch(() => ({}))
248
286
  if (!res.ok || body?.ok !== true) throw new Error(body?.reason ?? `http-${res.status}`)
249
287
  return body.data
@@ -571,7 +609,7 @@ window.__ModuleLoader__.load({
571
609
  apiCard: {
572
610
  flex: '1 1 220px', maxWidth: 260, minWidth: 220, boxSizing: 'border-box',
573
611
  border: `1px solid ${T.border}`, borderRadius: 8, background: T.section, padding: 16,
574
- display: 'grid', gap: 8, alignContent: 'start',
612
+ display: 'grid', gridTemplateColumns: 'minmax(0, 1fr)', gap: 8, alignContent: 'start',
575
613
  },
576
614
  apiCardHead: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 8, minWidth: 0 },
577
615
  apiCardName: { fontSize: 13, fontWeight: 600, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' },
@@ -618,6 +656,13 @@ window.__ModuleLoader__.load({
618
656
  trendSpacer: { flex: '1 1 auto' },
619
657
  // 轴与绘图区两列:轴在绘图区之外(与 CC Switch 的 <YAxis> 同构),绘图区自己承担网格与柱
620
658
  trendPlot: { display: 'grid', gridTemplateColumns: 'auto minmax(0, 1fr)', height: 132, minWidth: 0 },
659
+ trendPlotDual: { gridTemplateColumns: 'auto minmax(0, 1fr) auto' },
660
+ trendAxisColRight: { paddingRight: 0, paddingLeft: 6 },
661
+ trendAxisRight: {
662
+ position: 'absolute', left: 0, fontSize: 11, color: T.weak, fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap',
663
+ },
664
+ trendLegend: { display: 'flex', alignItems: 'center', gap: 6, marginRight: 8, fontSize: 11, color: T.muted, whiteSpace: 'nowrap' },
665
+ trendLegendDot: { width: 8, height: 8, borderRadius: 999, display: 'inline-block', marginRight: 3 },
621
666
  trendAxisCol: { position: 'relative', minWidth: 0, paddingRight: 6 },
622
667
  trendAxis: {
623
668
  position: 'absolute', right: 6, color: T.weak, fontSize: 11, lineHeight: '14px',
@@ -673,13 +718,16 @@ window.__ModuleLoader__.load({
673
718
  },
674
719
  // 空态文案:绘图区内居中(轴已在左列,无需再让出留白)
675
720
  trendMsg: { position: 'absolute', inset: '0 0 18px 0', display: 'flex', alignItems: 'center', justifyContent: 'center', color: T.muted, fontSize: 11 },
676
- quotaCards: { display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 12 },
721
+ // 订阅卡与按量卡同一套宽度规则:flex 等分 + 上限 260,单家时不再铺满
722
+ quotaCards: { display: 'flex', flexWrap: 'wrap', justifyContent: 'center', alignItems: 'start', gap: 12 },
677
723
  quotaCard: {
678
724
  border: `1px solid ${T.border}`, borderRadius: 8, background: T.section, padding: 16,
679
- display: 'grid', gap: 12, alignContent: 'start', minWidth: 0,
725
+ display: 'grid', gridTemplateColumns: 'minmax(0, 1fr)', gap: 12, alignContent: 'start', minWidth: 0,
726
+ flex: '1 1 220px', maxWidth: 260, boxSizing: 'border-box',
680
727
  },
681
728
  quotaWindows: { display: 'grid', gap: 12, minWidth: 0 },
682
- cardCaption: { color: T.weak, fontSize: 11, textAlign: 'center', marginTop: 4, whiteSpace: 'nowrap' },
729
+ // 说明行可能很长(周期 / 限流 / 渠道用量叠加),必须允许换行,否则会把卡片撑宽(Issue #4)
730
+ cardCaption: { color: T.weak, fontSize: 11, textAlign: 'center', marginTop: 4, whiteSpace: 'normal', overflowWrap: 'anywhere' },
683
731
  rangeCapsule: { width: '100%', minWidth: 0 },
684
732
  }
685
733
  styles.button['--td-accent'] = T.accent
@@ -692,6 +740,35 @@ window.__ModuleLoader__.load({
692
740
  styles.ghost = { ...styles.button, color: T.accent, borderColor: 'transparent', background: 'transparent' }
693
741
  styles.outline = { ...styles.button, color: T.text, borderColor: T.border, background: 'transparent' }
694
742
 
743
+ /** 看板渲染兜底:异常时给可读文案 + 重试,而不是整块空白;并把 componentStack 上报落盘。 */
744
+ class BoardBoundary extends React.Component {
745
+ constructor(props) {
746
+ super(props)
747
+ this.state = { failed: false }
748
+ }
749
+
750
+ static getDerivedStateFromError() { return { failed: true } }
751
+
752
+ componentDidCatch(error, info) {
753
+ reportClientLog('board', 'render.error', {
754
+ message: String(error?.message ?? error).slice(0, 200),
755
+ stack: String(info?.componentStack ?? '').slice(0, 400),
756
+ })
757
+ }
758
+
759
+ render() {
760
+ if (this.state.failed) {
761
+ return h('div', { 'data-testid': 'token-dash-board-error', style: styles.cardBox },
762
+ h('div', { style: styles.empty }, tr('数据渲染失败')),
763
+ h('button', {
764
+ type: 'button', style: styles.button,
765
+ onClick: () => this.setState({ failed: false }),
766
+ }, tr('重试')))
767
+ }
768
+ return this.props.children
769
+ }
770
+ }
771
+
695
772
  function Icon({ name, size = 14, style }) {
696
773
  const props = { width: size, height: size, viewBox: '0 0 24 24', fill: 'none', stroke: 'currentColor', strokeWidth: 2, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true, style }
697
774
  if (name === 'info') return h('svg', props, h('circle', { cx: 12, cy: 12, r: 9 }), h('path', { d: 'M12 11v5' }), h('path', { d: 'M12 8h.01' }))
@@ -988,8 +1065,9 @@ window.__ModuleLoader__.load({
988
1065
  /** P3 明细表:八列,费用只对 API 计价行展示。 */
989
1066
  function DetailTable({ rows, providerNames = {} }) {
990
1067
  if (rows.length === 0) return h('div', { style: styles.empty }, tr('范围内暂无消耗'))
991
- const headCell = (text, align = 'right') => h('span', {
1068
+ const headCell = (text, align = 'right', title) => h('span', {
992
1069
  role: 'columnheader',
1070
+ ...(title === undefined ? {} : { title }),
993
1071
  style: { color: T.weak, fontSize: 11, textAlign: align, paddingBottom: 8, borderBottom: `1px solid ${T.border}` },
994
1072
  }, text)
995
1073
  const cell = { padding: '4px 0', borderBottom: TABLE_BORDER, fontSize: 13, minWidth: 0 }
@@ -998,7 +1076,9 @@ window.__ModuleLoader__.load({
998
1076
  h('div', { style: { display: 'contents' } },
999
1077
  headCell(tr('模型'), 'left'),
1000
1078
  headCell('Tokens'), headCell(tr('输入')), headCell(tr('缓存')), headCell(tr('输出')),
1001
- headCell(tr('请求')), headCell(tr('命中')), headCell(tr('费用'))),
1079
+ headCell(tr('请求')), headCell(tr('命中')),
1080
+ headCell(h('span', { style: { display: 'inline-flex', alignItems: 'center', gap: 4 } },
1081
+ tr('费用'), h(Icon, { name: 'info', size: 11 })), 'right', tr('API 与订阅金额均为本地按目录价估算,非供应商账单;缓存读按缓存价计,命中率高的行每 token 成本显著更低,不同行不可直接按 token 数比较;不同币种需自行换算'))),
1002
1082
  ...rows.map((row) => h('div', {
1003
1083
  key: `${row.providerId}:${row.modelId}`,
1004
1084
  role: 'row',
@@ -1027,11 +1107,17 @@ window.__ModuleLoader__.load({
1027
1107
  : undefined,
1028
1108
  style: { ...styles.cellNum, ...cell, textAlign: 'right' },
1029
1109
  },
1030
- row.kind !== 'api' || row.priced === 'empty'
1031
- ? '—'
1032
- : row.priced === false
1033
- ? tr('未定价')
1034
- : `${row.approximate === true ? '≈' : ''}${fmtMoney(row.cost, row.currency)}`)))))
1110
+ row.kind !== 'api'
1111
+ ? (row.estimatedPriced === undefined
1112
+ ? '—'
1113
+ : row.estimatedPriced === true
1114
+ ? `≈${fmtMoney(row.estimatedCost, row.currency)}`
1115
+ : tr('未定价'))
1116
+ : row.priced === 'empty'
1117
+ ? '—'
1118
+ : row.priced === false
1119
+ ? tr('未定价')
1120
+ : `≈${fmtMoney(row.cost, row.currency)}`)))))
1035
1121
  }
1036
1122
 
1037
1123
  /** P3 趋势指标:唯一顺序源——四格摘要带与右侧胶囊都从这里派生,禁止各自维护顺序。 */
@@ -1137,6 +1223,7 @@ window.__ModuleLoader__.load({
1137
1223
  const costEntries = Object.entries(usage?.totals ?? {})
1138
1224
  const total = usage?.total ?? null
1139
1225
  const dash = '—'
1226
+ // 总费用含订阅估算:金额不加前缀,口径说明只由副行「含估算」承担(REQ-10,修正 D-04 的一半)
1140
1227
  const costNodes = costEntries.map(([currency, value]) => h('span', { key: currency }, fmtMoney(value.cost, currency)))
1141
1228
  const tokensLabel = h('span', null,
1142
1229
  tr('真实 Tokens'),
@@ -1157,7 +1244,7 @@ window.__ModuleLoader__.load({
1157
1244
  label: tr('总费用'),
1158
1245
  main: () => h('div', { style: styles.summaryV },
1159
1246
  pending ? dash : (costNodes.length === 0 ? dash : costNodes)),
1160
- sub: () => (pending ? dash : tr('{n} 个币种', { n: costEntries.length })),
1247
+ sub: () => (pending ? dash : `${tr('{n} 个币种', { n: costEntries.length })} · ${tr('含估算')}`),
1161
1248
  },
1162
1249
  hitRate: {
1163
1250
  label: tr('缓存命中率'),
@@ -1249,16 +1336,25 @@ window.__ModuleLoader__.load({
1249
1336
  // 悬停态:{ center: 柱位百分比, ratio: 柱高百分比, text: 浮层文案 };null 表示未悬停
1250
1337
  const [hover, setHover] = useState(null)
1251
1338
  const points = Array.isArray(series) ? series : []
1252
- const values = points.map((point) => trendValue(point, metric))
1339
+ // 成本指标:两个币种走双轴双柱;>2 仍给出口文案(三轴不可读,明确不做)
1340
+ const currencies = new Set()
1341
+ for (const point of points) for (const currency of Object.keys(point.cost ?? {})) currencies.add(currency)
1342
+ const currencyList = [...currencies]
1343
+ const dual = metric === 'cost' && currencyList.length === 2
1344
+ const primary = currencyList.includes('CNY') ? 'CNY' : (currencyList[0] ?? 'CNY')
1345
+ const secondary = dual ? currencyList.find((code) => code !== primary) : null
1346
+ const costBlocked = metric === 'cost' && currencyList.length > 2
1347
+ const costCurrency = currencyList.length === 1 ? currencyList[0] : primary
1348
+ const costAt = (point, code) => Number(point?.cost?.[code]?.cost) || 0
1349
+ const primaryValues = dual ? points.map((point) => costAt(point, primary)) : null
1350
+ const secondaryValues = dual ? points.map((point) => costAt(point, secondary)) : null
1351
+ const values = dual ? primaryValues : points.map((point) => trendValue(point, metric))
1253
1352
  const known = values.filter((value) => value !== null && value > 0)
1254
1353
  const max = known.length > 0 ? Math.max(...known) : 0
1354
+ const secondaryKnown = dual ? secondaryValues.filter((value) => value > 0) : []
1355
+ const secondaryMax = secondaryKnown.length > 0 ? Math.max(...secondaryKnown) : 0
1255
1356
  const floor = metric === 'hitRate' ? hitRateFloor(values) : 0
1256
1357
  const span = Math.max(max - floor, 1e-9)
1257
- // 多币种时一根柱无法表达,按既定决策禁用成本指标并给出口文案
1258
- const currencies = new Set()
1259
- for (const point of points) for (const currency of Object.keys(point.cost ?? {})) currencies.add(currency)
1260
- const costBlocked = metric === 'cost' && currencies.size > 1
1261
- const costCurrency = currencies.size === 1 ? [...currencies][0] : 'CNY'
1262
1358
  // 换指标 / 换范围后旧的柱位与文案都已失效,直接清空悬停态
1263
1359
  useEffect(() => { setHover(null) }, [metric, series])
1264
1360
  const tickOf = (dayKey) => {
@@ -1267,10 +1363,14 @@ window.__ModuleLoader__.load({
1267
1363
  }
1268
1364
  // 日期刻度按可用宽度抽稀,末点必显
1269
1365
  const step = Math.max(1, Math.ceil(points.length / 6))
1366
+ const hasData = dual ? (known.length > 0 || secondaryKnown.length > 0) : known.length > 0
1270
1367
  const emptyMessage = costBlocked
1271
1368
  ? tr('多币种下成本柱不可用,请切换其他指标')
1272
- : (points.length === 0 || known.length === 0 ? tr('范围内暂无消耗') : null)
1369
+ : (points.length === 0 || !hasData ? tr('范围内暂无消耗') : null)
1273
1370
  const axisTicks = emptyMessage === null ? trendAxisTicks({ floor, max, metric, currency: costCurrency }) : []
1371
+ const rightTicks = emptyMessage === null && dual
1372
+ ? trendAxisTicks({ floor: 0, max: secondaryMax, metric, currency: secondary })
1373
+ : []
1274
1374
  // 轴宽随最长刻度自适应:字号 11px 下中文≈11px、其余≈6.2px,再留 6px 与柱体的间距
1275
1375
  // 轴列宽度由内容自适应(grid auto 列),这里只保证空态时左侧不塌陷
1276
1376
  const axisWidth = axisTicks.reduce((widest, tick) => {
@@ -1279,17 +1379,28 @@ window.__ModuleLoader__.load({
1279
1379
  return Math.max(widest, px)
1280
1380
  }, 0)
1281
1381
  const axisPad = axisTicks.length === 0 ? 34 : Math.max(28, Math.ceil(axisWidth) + 6)
1382
+ const rightWidth = rightTicks.reduce((widest, tick) => {
1383
+ let px = 0
1384
+ for (const char of tick.text) px += /[\u4e00-\u9fff]/.test(char) ? 11 : 6.2
1385
+ return Math.max(widest, px)
1386
+ }, 0)
1387
+ const rightPad = rightTicks.length === 0 ? 0 : Math.max(28, Math.ceil(rightWidth) + 6)
1282
1388
  return h('div', { 'data-testid': 'token-dash-trend', 'data-td-trend': metric, style: styles.trendBox },
1283
1389
  h('div', { style: styles.trendHead },
1284
1390
  h('b', { 'data-testid': 'token-dash-trend-title', style: styles.trendTitle },
1285
1391
  tr('使用趋势 · {metric}', { metric: tr(METRIC_LABELS[metric]) })),
1286
1392
  h('span', { style: styles.trendHint }, tr(grain === 'month' ? '按月' : '按天')),
1287
1393
  h('span', { style: styles.trendSpacer }),
1394
+ dual
1395
+ ? h('span', { 'data-testid': 'token-dash-trend-legend', style: styles.trendLegend },
1396
+ h('i', { style: { ...styles.trendLegendDot, background: T.accent } }), fmtMoney(0, primary).slice(0, 1) + primary,
1397
+ h('i', { style: { ...styles.trendLegendDot, background: T.series2, marginLeft: 8 } }), fmtMoney(0, secondary).slice(0, 1) + secondary)
1398
+ : null,
1288
1399
  h(Segmented, {
1289
1400
  value: metric, onChange: onMetricChange, label: tr('趋势指标'), kind: 'radiogroup', fit: true,
1290
1401
  options: TREND_METRICS.map(([value, label]) => ({ value, label: tr(label) })),
1291
1402
  })),
1292
- h('div', { style: styles.trendPlot },
1403
+ h('div', { style: dual ? { ...styles.trendPlot, ...styles.trendPlotDual } : styles.trendPlot },
1293
1404
  // 左列:Y 轴(在绘图区之外,与 CC Switch 的 <YAxis> 同构)
1294
1405
  h('div', { 'data-testid': 'token-dash-trend-axis-col', style: { ...styles.trendAxisCol, minWidth: axisPad } },
1295
1406
  ...axisTicks.map((tick) => h('span', {
@@ -1312,21 +1423,40 @@ window.__ModuleLoader__.load({
1312
1423
  ...points.map((point, index) => {
1313
1424
  const value = values[index]
1314
1425
  const ratio = value === null || value <= floor ? 0 : Math.max(0, Math.min(100, ((value - floor) / span) * 100))
1426
+ const secondaryRatio = dual && secondaryMax > 0
1427
+ ? Math.max(0, Math.min(100, (secondaryValues[index] / secondaryMax) * 100))
1428
+ : 0
1429
+ const hoverText = dual
1430
+ ? `${point.dayKey} · ${fmtMoney(value, primary)} · ${fmtMoney(secondaryValues[index], secondary)}`
1431
+ : `${point.dayKey} · ${fmtMetric(value, metric, costCurrency)}`
1315
1432
  // 悬停即渲染虚线与浮层:不挂原生 title,避免系统 tooltip 的 ~1s 延迟
1316
1433
  return h('span', {
1317
1434
  key: point.dayKey,
1318
1435
  'data-testid': `token-dash-trend-slot-${point.dayKey}`,
1319
- style: styles.trendSlot,
1436
+ style: dual ? { ...styles.trendSlot, display: 'flex', alignItems: 'flex-end', gap: 1 } : styles.trendSlot,
1320
1437
  onMouseEnter: () => setHover({
1321
1438
  center: ((index + 0.5) / points.length) * 100,
1322
1439
  ratio,
1323
- text: `${point.dayKey} · ${fmtMetric(value, metric, costCurrency)}`,
1440
+ text: hoverText,
1324
1441
  }),
1325
1442
  },
1326
- h('span', {
1327
- 'data-testid': `token-dash-trend-bar-${point.dayKey}`,
1328
- style: { ...styles.trendBar, height: `${ratio}%`, background: ratio === 0 ? 'transparent' : T.accent },
1329
- }))
1443
+ dual
1444
+ ? [
1445
+ h('span', {
1446
+ key: primary,
1447
+ 'data-testid': `token-dash-trend-bar-${point.dayKey}-${primary}`,
1448
+ style: { ...styles.trendBar, flex: '1 1 0', height: `${ratio}%`, background: ratio === 0 ? 'transparent' : T.accent },
1449
+ }),
1450
+ h('span', {
1451
+ key: secondary,
1452
+ 'data-testid': `token-dash-trend-bar-${point.dayKey}-${secondary}`,
1453
+ style: { ...styles.trendBar, flex: '1 1 0', height: `${secondaryRatio}%`, background: secondaryRatio === 0 ? 'transparent' : T.series2 },
1454
+ }),
1455
+ ]
1456
+ : h('span', {
1457
+ 'data-testid': `token-dash-trend-bar-${point.dayKey}`,
1458
+ style: { ...styles.trendBar, height: `${ratio}%`, background: ratio === 0 ? 'transparent' : T.accent },
1459
+ }))
1330
1460
  })) : h('div', { 'data-testid': 'token-dash-trend-empty', style: styles.trendMsg }, emptyMessage),
1331
1461
  emptyMessage === null && hover !== null ? h('span', {
1332
1462
  'data-testid': 'token-dash-trend-hover-line',
@@ -1348,7 +1478,18 @@ window.__ModuleLoader__.load({
1348
1478
  emptyMessage === null && hover !== null ? h('div', {
1349
1479
  'data-testid': 'token-dash-trend-hover-tip',
1350
1480
  style: { ...styles.trendTip, left: `${hover.center}%` },
1351
- }, hover.text) : null)))
1481
+ }, hover.text) : null),
1482
+ dual
1483
+ ? h('div', { 'data-testid': 'token-dash-trend-axis-col-right', style: { ...styles.trendAxisCol, ...styles.trendAxisColRight, minWidth: rightPad } },
1484
+ ...rightTicks.map((tick) => h('span', {
1485
+ key: tick.key,
1486
+ 'data-testid': `token-dash-trend-axis-right-${tick.key}`,
1487
+ 'aria-hidden': true,
1488
+ style: tick.top === null
1489
+ ? { ...styles.trendAxisRight, bottom: 18 }
1490
+ : { ...styles.trendAxisRight, top: tick.top, transform: tick.top === '50%' ? 'translateY(-50%)' : undefined },
1491
+ }, tick.text)))
1492
+ : null))
1352
1493
  }
1353
1494
 
1354
1495
  function MiniBar({ ratio = 0, neutral = false, stretch = false }) {
@@ -1371,7 +1512,8 @@ window.__ModuleLoader__.load({
1371
1512
 
1372
1513
  /** P3 API 卡底部说明:状态 · 比例,再补余额周期 / 限流 / 渠道用量(渠道值只读)。 */
1373
1514
  function apiCardCaption(provider, { hasBudget, percent, budget }) {
1374
- const parts = [`${hasBudget ? stateOf(percent, API_CRITICAL) : 'unset'} · ${hasBudget ? fmtRatio(budget.percent) : '—'}`]
1515
+ // 状态与比例已由环和百分比表达,说明行只留环上放不下的信息(D-07)
1516
+ const parts = []
1375
1517
  const periodEnd = Number(provider.balance?.periodEnd)
1376
1518
  const period = Number.isFinite(periodEnd) && periodEnd > 0 ? resetParts(periodEnd).absolute : null
1377
1519
  if (period !== null) parts.push(tr('周期至 {time}', { time: period }))
@@ -2112,7 +2254,9 @@ window.__ModuleLoader__.load({
2112
2254
  style: { fontSize: 10, color: T.weak },
2113
2255
  }, tr('按社区表 CNY'))
2114
2256
  : null)),
2115
- h('div', { style: styles.cardCaption }, apiCardCaption(provider, { hasBudget, percent, budget })))
2257
+ apiCardCaption(provider, { hasBudget, percent, budget }) === ''
2258
+ ? null
2259
+ : h('div', { style: styles.cardCaption }, apiCardCaption(provider, { hasBudget, percent, budget })))
2116
2260
  }))
2117
2261
  }
2118
2262
 
@@ -2154,7 +2298,10 @@ window.__ModuleLoader__.load({
2154
2298
  }, windows.map((plan) => h(QuotaCell, {
2155
2299
  key: plan.key, providerId: provider.id, plan, windowKey: plan.key,
2156
2300
  }))),
2157
- h('div', { style: styles.cardCaption }, `${windows.length} ${tr('窗')}`))
2301
+ Number(provider.usage?.monthEstimate) > 0
2302
+ ? h('div', { style: styles.cardCaption },
2303
+ `${tr('本月估算')} ${fmtMoney(provider.usage.monthEstimate, provider.currency)}`)
2304
+ : null)
2158
2305
  }))
2159
2306
  }
2160
2307
 
@@ -2216,6 +2363,7 @@ window.__ModuleLoader__.load({
2216
2363
  setError(false)
2217
2364
  } catch {
2218
2365
  setError(true)
2366
+ reportClientLog('board', 'fetch.error', { path: 'summary' })
2219
2367
  }
2220
2368
  }, [active])
2221
2369
 
@@ -2230,6 +2378,7 @@ window.__ModuleLoader__.load({
2230
2378
  setUsageError(false)
2231
2379
  } catch {
2232
2380
  setUsageError(true)
2381
+ reportClientLog('board', 'fetch.error', { path: 'usage' })
2233
2382
  }
2234
2383
  }, [range])
2235
2384
 
@@ -2271,9 +2420,20 @@ window.__ModuleLoader__.load({
2271
2420
  const models = Array.isArray(usage?.models) ? usage.models : []
2272
2421
  const updated = fmtClock(summary?.updatedAt)
2273
2422
  const degraded = summary?.providersDegraded === true
2423
+ // 无数据时只给一行加载提示,避免重挂载后长时间空白(REQ-07)
2424
+ if (summary === null) {
2425
+ return h('div', { 'data-testid': 'token-dash-board-loading', style: styles.empty }, tr('数据加载中'))
2426
+ }
2274
2427
  const emptyAll = summary !== null && api.length === 0 && subscriptions.length === 0
2428
+ // 空态快照:确认「空白」到底是走了空态分支还是渲染异常
2429
+ if (api.length + subscriptions.length === 0) {
2430
+ reportClientLog('board', 'render.empty', {
2431
+ api: api.length, subscriptions: subscriptions.length,
2432
+ degraded, emptyAll, hasSummary: summary !== null,
2433
+ })
2434
+ }
2275
2435
 
2276
- return h('div', { 'data-testid': 'token-dash-board-scroll', style: styles.boardScroll },
2436
+ return h(BoardBoundary, null, h('div', { 'data-testid': 'token-dash-board-scroll', style: styles.boardScroll },
2277
2437
  h('div', { 'data-testid': 'token-dash-board', style: styles.board },
2278
2438
  h('style', null, TD_CSS),
2279
2439
  h('div', { style: styles.boardHead },
@@ -2344,7 +2504,7 @@ window.__ModuleLoader__.load({
2344
2504
  style: styles.settingsHint,
2345
2505
  }, tr('语言跟随DSH设置;当前仅中文/English,其他语言回退英文')))),
2346
2506
  h('div', { 'data-testid': 'token-dash-settings-capsule', style: styles.capsule },
2347
- h(SettingsRows, { summary, prefs, onSave: savePrefs, onRefresh: refresh, onRefreshSubs: refreshSubs })))))
2507
+ h(SettingsRows, { summary, prefs, onSave: savePrefs, onRefresh: refresh, onRefreshSubs: refreshSubs }))))))
2348
2508
  }
2349
2509
 
2350
2510
  return {
package/index.js CHANGED
@@ -13,8 +13,8 @@ import { logAdapterEvents, logAdapterFailures, missSignature, readProviders, rea
13
13
  import { PROVIDER_SOURCES } from './src/quota-sources.js'
14
14
  import { catalogInfo, configurePricing, loadCommunityPricing, loadRouterPricing } from './src/pricing.js'
15
15
  import { providerCurrency } from './src/providers.js'
16
- import { clearLog, createLogger, exportLog } from './src/diagnostics.js'
17
- import { isNewer } from './src/version.js'
16
+ import { clearLog, createLogger, exportLog, pruneLogs } from './src/diagnostics.js'
17
+ import { isNewer, sameBase } from './src/version.js'
18
18
 
19
19
  export const name = 'dsh-token-dash'
20
20
 
@@ -52,7 +52,7 @@ function hostVersion() {
52
52
  }
53
53
  let updateCache = { at: 0, data: null }
54
54
  /** 允许 client 上报日志的模块白名单:只放已知来源,避免任意日志注入。 */
55
- const CLIENT_LOG_MODULES = new Set(['slot', 'update'])
55
+ const CLIENT_LOG_MODULES = new Set(['slot', 'update', 'board'])
56
56
 
57
57
  /** Locate the bundled dsh CLI (same layout scripts/e2e.mjs relies on). */
58
58
  function findDshCli() {
@@ -87,9 +87,9 @@ async function fetchLatest() {
87
87
  if (!response.ok) throw new Error(`registry-${response.status}`)
88
88
  const meta = await response.json()
89
89
  if (typeof meta?.version !== 'string') throw new Error('invalid-registry-response')
90
- return { current: CURRENT_VERSION, latest: meta.version, hasUpdate: isNewer(meta.version, CURRENT_VERSION), published: true }
91
- if (typeof meta?.version !== 'string') throw new Error('invalid-registry-response')
92
- return { current: CURRENT_VERSION, latest: meta.version, hasUpdate: isNewer(meta.version, CURRENT_VERSION), published: true, source: 'registry' }
90
+ // 本地构建与 npm 同 base 时不提示更新:本地包代码更新,装正式版反而会退回(REQ-09)
91
+ const hasUpdate = isNewer(meta.version, CURRENT_VERSION) && !sameBase(meta.version, CURRENT_VERSION)
92
+ return { current: CURRENT_VERSION, latest: meta.version, hasUpdate, published: true, source: 'registry' }
93
93
  }
94
94
 
95
95
  /** 安装 spec:默认按 npm 版本号安装,仍走与真实更新完全相同的 CLI 路径。 */
@@ -223,6 +223,12 @@ export function apply(ctx) {
223
223
  const dir = dataDir(ctx)
224
224
  const logDir = logsDir(ctx)
225
225
  const logger = createLogger({ dir: logDir, version: CURRENT_VERSION, dshVersion: hostVersion() })
226
+ // 启动即按保留策略清理:等价于「更新后清理一次旧目录」,之后每次启动持续生效
227
+ try {
228
+ const pruned = pruneLogs({ dir: logDir, activeFile: logger.file })
229
+ // 无条件记录:即使 removed 为 0 也要能确认保留策略执行过(REQ-08)
230
+ logger.info('diag', 'prune', pruned)
231
+ } catch { /* 日志治理失败不影响插件 */ }
226
232
  let prefs
227
233
  let state
228
234
  let providerCache = new Map()
@@ -368,7 +374,17 @@ export function apply(ctx) {
368
374
  const refreshProviderCache = async () => {
369
375
  if (providerRefresh !== null) return providerRefresh
370
376
  providerRefresh = (async () => {
377
+ const probeStartedAt = Date.now()
371
378
  const data = await readProviders(scoped, prefs, providerCache)
379
+ const probeElapsed = Date.now() - probeStartedAt
380
+ // 慢刷新:一次探测超过 5s 会连带阻塞排队中的请求,单独留痕便于定位是哪一轮、哪些源拖慢
381
+ if (probeElapsed > 5000) {
382
+ logger.warn('provider', 'slow', {
383
+ probeMs: probeElapsed,
384
+ misses: (data.misses ?? []).length,
385
+ failures: (data.failures ?? []).map((item) => item.id),
386
+ })
387
+ }
372
388
  const hadProviders = providerCacheMeta.hadProviders === true || data.length > 0
373
389
  providerCacheMeta = {
374
390
  ...providerCacheMeta,
@@ -384,11 +400,15 @@ export function apply(ctx) {
384
400
  })
385
401
  }
386
402
  logAdapterEvents(logger, data)
387
- logAdapterFailures(logger, data.failures)
403
+ // 缺凭据是稳定状态,并入下方「清单变化才记」的去重口径,避免每轮探测刷屏;其余失败照常每次记录
404
+ const failures = data.failures ?? []
405
+ const isMissingCredential = (item) => item.error?.kind === 'missing-credential'
406
+ logAdapterFailures(logger, failures.filter((item) => !isMissingCredential(item)))
388
407
  // 只在探测清单变化时记一次:启动首轮必打,之后配 Key / 断网导致清单变动才再打,避免每轮刷屏
389
408
  const signature = missSignature(data)
390
409
  if (signature !== providerCacheMeta.missSignature) {
391
410
  providerCacheMeta = { ...providerCacheMeta, missSignature: signature }
411
+ logAdapterFailures(logger, failures.filter(isMissingCredential))
392
412
  logger.info('provider', 'cache.state', {
393
413
  entries: providerCache.size,
394
414
  providers: data.length,
@@ -553,7 +573,9 @@ export function apply(ctx) {
553
573
  json(res, 400, { ok: false, reason: 'invalid-log' })
554
574
  return
555
575
  }
556
- logger.info(body.module, body.event, typeof body.meta === 'object' && body.meta !== null ? body.meta : {})
576
+ // level 仅接受 warn,其余一律 info;非法值不报错,避免客户端因日志失败而重试
577
+ const write = body.level === 'warn' ? logger.warn : logger.info
578
+ write(body.module, body.event, typeof body.meta === 'object' && body.meta !== null ? body.meta : {})
557
579
  json(res, 200, { ok: true, data: { logged: true } })
558
580
  return
559
581
  }
package/locale/en.json CHANGED
@@ -10,6 +10,11 @@
10
10
  "内置兜底": "Built-in fallback",
11
11
  "查询失败": "Query failed",
12
12
  "套餐查询失败": "Quota query failed",
13
+ "数据加载中": "Loading data",
14
+ "含估算": "incl. estimates",
15
+ "API 与订阅金额均为本地按目录价估算,非供应商账单;缓存读按缓存价计,命中率高的行每 token 成本显著更低,不同行不可直接按 token 数比较;不同币种需自行换算": "Both API and subscription amounts are estimated locally from catalog prices, not provider invoices; cached reads use the cache price, so rows with a higher hit rate cost much less per token and rows are not directly comparable by token count; currencies are not converted.",
16
+ "本月估算": "Est. this month",
17
+ "订阅不计价,估算值仅作参考": "Subscription is not billed; the estimate is for reference only",
13
18
  "周": "Week",
14
19
  "月": "Month",
15
20
  "重置": "Reset",