dsh-token-dash 2.0.2 → 2.2.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
@@ -9,7 +9,7 @@
9
9
  </p>
10
10
 
11
11
  <p align="center">
12
- See today's model spend, monthly budget headroom, and subscription windows for 7 providers right next to the DSH input box.<br />
12
+ See today's model spend, monthly budget headroom, and subscription windows for 8 providers right next to the DSH input box.<br />
13
13
  Paste a key and the billing mode is detected automatically; cost, Tokens and cache hits are estimated locally;<br />
14
14
  export the current month and import it back after switching machines or reinstalling.
15
15
  </p>
@@ -30,22 +30,28 @@
30
30
 
31
31
  **Three entry points, one local ledger**: the composer-footer-right Pill shows the current model; the floating panel shows budget, balance and the usage table; the full dashboard shows every provider card and model breakdown. No duplicated accounting between pages.
32
32
 
33
- ## Provider matrix
33
+ ## Supported API scope
34
34
 
35
- | Provider | Billing | Credential | What you get |
36
- |---|---|---|---|
37
- | DeepSeek | API usage | DS account wallet / `DEEPSEEK_API_KEY` | Balance, month-to-date spend, budget |
38
- | Zhipu GLM Coding | Subscription / API usage | `ZHIPU_API_KEY` / `GLM_API_KEY` / `ZAI_API_KEY` | 5h + weekly windows |
39
- | Kimi Coding | Subscription / API usage | `KIMI_API_KEY` / `KIMI_CODING_API_KEY`, optional `MOONSHOT_API_KEY` | 5h + weekly/monthly windows; falls back to balance |
40
- | OpenRouter | API usage | `OPENROUTER_API_KEY` | Credits (USD) |
41
- | Qwen | API usage | `DASHSCOPE_API_KEY` (CNY) / `DASHSCOPE_INTL_API_KEY` (USD) | Usage only; balance unsupported |
42
- | OpenCode Go | Subscription | `OPENCODE_GO_API_KEY` | 5h / weekly / monthly windows (USD) |
43
- | Command Code | Subscription | `COMMAND_CODE_API_KEY` + `COMMAND_CODE_ORG_ID` | 5h + weekly windows, credits (CNY) |
35
+ Only the official endpoints listed below are called. Any other provider is still recorded (priced by model name) but gets no balance or quota card.
36
+
37
+ | Provider | Credential | Official endpoints called | Billing | What you get |
38
+ |---|---|---|---|---|
39
+ | DeepSeek | DS account wallet / `DEEPSEEK_API_KEY` | `GET api.deepseek.com/user/balance` | API usage | Balance, month-to-date spend, budget |
40
+ | Zhipu GLM Coding | `ZHIPU_API_KEY` / `GLM_API_KEY` / `ZAI_API_KEY` | `GET bigmodel.cn/api/monitor/usage/quota/limit` | Subscription / API usage | 5h + weekly windows |
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
+ | OpenRouter | `OPENROUTER_API_KEY` | `GET openrouter.ai/api/v1/credits` | API usage | Credits (USD) |
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) |
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
+ | 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
+ | Any other provider (self-hosted, relay, local Ollama) | None | No endpoint | API usage | Priced by model name only; unpriced rows can be backfilled |
44
48
 
45
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
+ - 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.
46
51
  - Keys are detected automatically; GLM / Kimi / OpenCode Go / Command Code can be re-detected from the dashboard footer.
47
52
  - Subscription models count toward Tokens but not cost; billing mode is pinned per key instead of following quota flakiness.
48
53
  - Balance, quota and usage are separate; a balance failure never resets today's Token ledger to zero.
54
+ - **Not covered**: no cookies, no provider console scraping, no host config or local login state; balances come from official endpoints only, never through a relay; prices come from the community catalog and OpenRouter's public prices, not from provider bills, so every amount is a local estimate.
49
55
 
50
56
  ## Interface
51
57
 
@@ -78,7 +84,7 @@ Screenshots use mock data so the full layout is visible at once.
78
84
  - Subscription windows use three slots: first left, second center, third right; two windows occupy the first two slots.
79
85
  - Model column is capped at 150; Tokens / requests / hit rate are right-aligned.
80
86
 
81
- **P3 · Full dashboard**: cards for 7 providers, summary band, 8-column model breakdown and a settings capsule; the page owns its scrollbar at the window edge.
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.
82
88
 
83
89
  <p align="center">
84
90
  <img src="https://raw.githubusercontent.com/spartawhy117/dsh-token-dash/main/docs/pic/en/settings.png" alt="Full dashboard" />
@@ -115,6 +121,8 @@ Update: run `update` with the same name, or use the `⤓` button on the right of
115
121
  - The UI currently ships Chinese / English only. Other DSH languages (Japanese, German, Russian, etc.) fall back to English.
116
122
  - After a DSH upgrade the plugin may disappear from the profile; reinstall the same tarball — the ledger is not deleted.
117
123
  - Qwen tracks usage only; its balance endpoint is unsupported. Other balances/quotas follow what each API returns.
124
+ - A USD-billed provider that only matches the CNY price table shows "Unpriced" with a reason instead of rendering CNY numbers as USD.
125
+ - Ollama's balance and usage endpoints share a 10 requests/minute limit; when rate limited the card keeps the last values with a "Rate limited" note and recovers automatically.
118
126
  - Upstream APIs are rate-limited; successful results are cached for 60s, failures for 10s, and concurrent requests are coalesced.
119
127
 
120
128
  ## Data & privacy
package/README.md CHANGED
@@ -9,7 +9,7 @@
9
9
  </p>
10
10
 
11
11
  <p align="center">
12
- 在 DSH 输入框旁看清今天的模型消耗、本月的预算余量,以及 7 家供应商的订阅窗口。<br />
12
+ 在 DSH 输入框旁看清今天的模型消耗、本月的预算余量,以及 8 家供应商的订阅窗口。<br />
13
13
  填 Key 自动识别订阅或 API 用量;费用、Tokens、缓存命中全部在本地估算;<br />
14
14
  当月数据可导出备份,换机或重装后一键导入恢复。
15
15
  </p>
@@ -28,24 +28,30 @@
28
28
  <a href="https://awesome-dsh-plugin.com/zh/p/spartawhy117/dsh-token-dash"><img src="https://img.shields.io/badge/awesome--dsh--plugin-listed-6ea8ff" alt="awesome-dsh-plugin" /></a>
29
29
  </p>
30
30
 
31
- **三个入口,一份数据**:输入框底栏右侧 Pill 看当前模型;浮层看预算、余额与用量表;整页看 7 家供应商的全量卡片与模型明细。所有页面共用同一份本地账本,不重复计算。
31
+ **三个入口,一份数据**:输入框底栏右侧 Pill 看当前模型;浮层看预算、余额与用量表;整页看 8 家供应商的全量卡片与模型明细。所有页面共用同一份本地账本,不重复计算。
32
32
 
33
- ## 支持矩阵
33
+ ## 支持的 API 范围
34
34
 
35
- | 供应商 | 计费形态 | 凭据 | 能看到什么 |
36
- |---|---|---|---|
37
- | DeepSeek | API 用量 | DS 账号钱包 / `DEEPSEEK_API_KEY` | 账户余额、本月已花、预算 |
38
- | Zhipu GLM Coding | 订阅 / API 用量 | `ZHIPU_API_KEY` / `GLM_API_KEY` / `ZAI_API_KEY` | 5h + 周窗口 |
39
- | Kimi Coding | 订阅 / API 用量 | `KIMI_API_KEY` / `KIMI_CODING_API_KEY`,可选 `MOONSHOT_API_KEY` | 5h + 周/月窗口;订阅查询失败可回落余额 |
40
- | OpenRouter | API 用量 | `OPENROUTER_API_KEY` | Credits(USD) |
41
- | Qwen | API 用量 | `DASHSCOPE_API_KEY`(CNY)/ `DASHSCOPE_INTL_API_KEY`(USD) | 仅用量;余额不支持 |
42
- | OpenCode Go | 订阅 | `OPENCODE_GO_API_KEY` | 5h / 周 / 月窗口(USD) |
43
- | Command Code | 订阅 | `COMMAND_CODE_API_KEY` + `COMMAND_CODE_ORG_ID` | 5h + 周窗口、Credits(CNY) |
35
+ 只读取下表列出的官方接口;未列出的供应商仍可记账(按模型名计价),但没有余额/配额卡片。
36
+
37
+ | 供应商 | 支持的凭据 | 调用的官方接口 | 计费形态 | 展示内容 |
38
+ |---|---|---|---|---|
39
+ | DeepSeek | DS 账号钱包 / `DEEPSEEK_API_KEY` | `GET api.deepseek.com/user/balance` | API 用量 | 账户余额、本月已花、预算 |
40
+ | Zhipu GLM Coding | `ZHIPU_API_KEY` / `GLM_API_KEY` / `ZAI_API_KEY` | `GET bigmodel.cn/api/monitor/usage/quota/limit` | 订阅 / API 用量 | 5h + 周窗口 |
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
+ | OpenRouter | `OPENROUTER_API_KEY` | `GET openrouter.ai/api/v1/credits` | API 用量 | Credits(USD) |
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) |
45
+ | Command Code | `COMMAND_CODE_API_KEY` + `COMMAND_CODE_ORG_ID` | `GET api.commandcode.ai/alpha/billing/credits`(带 `orgId`) | 订阅 | 5h + 周窗口、Credits(CNY) |
46
+ | Ollama Cloud | `OLLAMA_API_KEY` | `GET ollama.com/api/balance`;`GET ollama.com/api/usage?range=30d` | API 用量 | 套餐剩余 + 购买余额(USD)、套餐已用、周期、渠道 30 天用量 |
47
+ | 其他任意 provider(自建、中转、Ollama 本地) | 无需凭据 | 不请求任何接口 | API 用量 | 只按模型名计价;未定价可补算 |
44
48
 
45
49
  - 在 DSH 的凭据设置中按上表名称保存 Key;插件只通过宿主 `credentials` 读取,不读环境变量或本机登录文件。
50
+ - Ollama 在 DSH 里需要用「自定义 OpenAI 兼容供应商」接入:route id 必须填 `ollama`(凭据按 `<ROUTE>_API_KEY` 派生成 `OLLAMA_API_KEY`),自定义名填别的会取不到 Key,余额卡也不会出现。
46
51
  - 填 Key 后自动探测;GLM / Kimi / OpenCode Go / Command Code 可在「全量看板」底部重新检测订阅。
47
52
  - 订阅模型计入 Tokens,但不计费用;计费形态按 Key 固化,不随配额接口抖动。
48
53
  - 余额、配额、用量分开展示;余额失败不会把当天的 Token 记账清零。
54
+ - **不覆盖**:不读 Cookie、不抓供应商控制台页面、不读宿主配置文件或本机登录态;余额只查官方接口,不经第三方中转;价格来自社区价目表与 OpenRouter 公开价,不来自供应商账单,金额均为本地估算。
49
55
 
50
56
  ## 界面
51
57
 
@@ -78,7 +84,7 @@
78
84
  - 订阅窗口固定三槽位:第 1 窗左、第 2 窗中、第 3 窗右;只有两窗时占前两个槽位。
79
85
  - 模型列上限 150,Tokens / 请求 / 命中右对齐;长模型名用省略号,悬浮可看全名。
80
86
 
81
- **P3 · 整页看板**:7 家供应商卡片、摘要带、8 列模型明细、底部设置胶囊;页面自己滚动,滚动条贴窗口右缘。
87
+ **P3 · 整页看板**:8 家供应商卡片、四格摘要带(总费用 / 真实 Tokens / 总请求数 / 缓存命中率)、用量趋势柱、8 列模型明细、底部设置胶囊;页面自己滚动,滚动条贴窗口右缘。
82
88
 
83
89
  <p align="center">
84
90
  <img src="https://raw.githubusercontent.com/spartawhy117/dsh-token-dash/main/docs/pic/settings.png" alt="整页看板" />
@@ -114,6 +120,8 @@ dsh plugin --profile desktop add /path/to/dsh-token-dash-x.y.z.tgz
114
120
  - 界面语言当前仅中文 / English;选择日语、德语、俄语等其他 DSH 语言时,插件文案显示英文回退。
115
121
  - 升级 DSH 后插件可能从 profile 消失,重装同一个 tarball 即可,账本不会被删。
116
122
  - Qwen 只统计用量,余额接口不支持;其余供应商的余额/配额以接口实际返回为准。
123
+ - 美元结算的供应商如果只命中人民币价目表,该模型会显示「未定价」并给出原因,不会把人民币数值当成美元。
124
+ - Ollama 的余额与用量接口共享 10 次/分钟限流;触发限流时卡片保留上次数值并标「限流中」,恢复后自动更新。
117
125
  - 上游接口有速率限制;成功结果缓存 60s、失败结果缓存 10s,并发请求会合并。
118
126
 
119
127
  ## 数据与隐私
package/client.js CHANGED
@@ -32,7 +32,7 @@ window.__ModuleLoader__.load({
32
32
  '[data-td-pill]:hover{background:color-mix(in srgb,currentColor 8%,transparent)}',
33
33
  '[data-td-btn]:hover{background:color-mix(in srgb,var(--td-accent) 24%,transparent);border-color:color-mix(in srgb,var(--td-accent) 48%,transparent)}',
34
34
  '[data-td-btn]:active{background:color-mix(in srgb,var(--td-accent) 28%,transparent)}',
35
- '@media (max-width:560px){[data-td-cards]{grid-template-columns:minmax(0,1fr)}}',
35
+ '@media (max-width:560px){[data-td-cards]{grid-template-columns:repeat(2,minmax(0,1fr))}[data-td-cards]>*:nth-child(n+3){border-top:1px solid color-mix(in srgb,currentColor 18%,transparent)}[data-td-cards]>*:nth-child(3){border-left:0}}',
36
36
  '[data-td-scroll]{overflow-x:auto}',
37
37
  '[data-td-scroll] > *{min-width:560px}',
38
38
  '[data-testid=token-dash-board-scroll]::-webkit-scrollbar{width:8px}',
@@ -109,8 +109,34 @@ window.__ModuleLoader__.load({
109
109
  '账户真实余额,不受预算影响': 'Account balance; not affected by budget',
110
110
  '本月累计消耗,等于已用/预算 的分子': 'Month-to-date spend; numerator of used/budget',
111
111
  '提示': 'Note',
112
+ '按社区表 CNY': 'Community table (CNY)',
113
+ '价格取社区价目表(人民币),与渠道账单可能有差异': 'Priced from the community table (CNY); may differ from your provider bill',
114
+ '无匹配价目': 'No matching price', '候选模型不唯一': 'Ambiguous model match',
115
+ '模型名无效': 'Invalid model name', '订阅不计价': 'Subscription, not billed',
116
+ '套餐已用': 'Plan used', '购买余额': 'Purchased credits',
117
+ '周期至 {time}': 'Cycle ends {time}', '限流中': 'Rate limited',
118
+ '渠道用量 {value}': 'Channel usage {value}',
119
+ '价目表为 CNY,该 provider 按 USD 结算;可用 priceOverrides 补 USD 单价': 'Price table is CNY while this provider bills in USD; add a USD priceOverrides entry',
120
+ '总请求数': 'Total requests', '缓存命中率': 'Cache hit rate',
121
+ '{n} 个币种': '{n} currencies', '范围内全部模型': 'All models in range',
122
+ '创建 {a} · 命中 {b}': 'Created {a} · hit {b}',
123
+ '趋势指标': 'Trend metric', '使用趋势 · {metric}': 'Trend · {metric}',
124
+ '按天': 'Daily', '按月': 'Monthly',
125
+ '与上方卡片同口径': 'Same scope as cards above',
126
+ '命中率': 'Hit rate', '无数据': 'No data',
127
+ '多币种下成本柱不可用,请切换其他指标': 'Cost bars unavailable with multiple currencies; switch metric',
128
+ // 刻度单位:中文用「万 / 亿」,英文用 K / M / B;'万' 同时是语言探针(见 isChinese)
129
+ '万': 'K',
112
130
  }
113
131
  const ZH = Object.fromEntries(Object.keys(EN).map((key) => [key, key]))
132
+ /** 未定价原因 → 可读文案;未知 reason 回退「未定价」。 */
133
+ const REASON_TEXT = {
134
+ 'no-model-price': '无匹配价目',
135
+ ambiguous: '候选模型不唯一',
136
+ 'invalid-model': '模型名无效',
137
+ 'kind-skip': '订阅不计价',
138
+ 'currency-mismatch': '价目表为 CNY,该 provider 按 USD 结算;可用 priceOverrides 补 USD 单价',
139
+ }
114
140
  const MESSAGES = { zh: ZH, en: EN }
115
141
  let localeService = null
116
142
  let ctxRef = null
@@ -483,12 +509,17 @@ window.__ModuleLoader__.load({
483
509
  kvLabel: { color: T.muted, whiteSpace: 'nowrap' },
484
510
  kvValue: { color: T.text, fontWeight: 600, fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' },
485
511
  summaryBand: {
486
- display: 'grid', gridTemplateColumns: '1fr 1fr', border: `1px solid ${T.border}`,
512
+ display: 'grid', gridTemplateColumns: 'repeat(4, minmax(0, 1fr))', border: `1px solid ${T.border}`,
487
513
  borderRadius: 8, overflow: 'hidden',
488
514
  },
489
- summaryHalf: { padding: 16, display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center', gap: 8, minWidth: 0 },
515
+ summaryHalf: {
516
+ padding: '12px 8px', display: 'flex', flexDirection: 'column', alignItems: 'center', textAlign: 'center',
517
+ gap: 4, minWidth: 0, border: 0, background: 'transparent', color: 'inherit', font: 'inherit', cursor: 'pointer',
518
+ transition: 'background .15s',
519
+ },
520
+ summaryHalfOn: { background: `color-mix(in srgb, ${T.accent} 10%, transparent)` },
490
521
  summaryK: { color: T.muted, fontSize: 12 },
491
- summaryV: { display: 'flex', alignItems: 'baseline', justifyContent: 'center', flexWrap: 'wrap', gap: 8, fontSize: 26, fontWeight: 600, lineHeight: '30px', fontVariantNumeric: 'tabular-nums' },
522
+ summaryV: { display: 'flex', alignItems: 'baseline', justifyContent: 'center', flexWrap: 'wrap', gap: 8, fontSize: 22, fontWeight: 600, lineHeight: '26px', fontVariantNumeric: 'tabular-nums' },
492
523
  summarySub: { color: T.weak, fontSize: 11, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: '100%' },
493
524
  rangeBox: {
494
525
  border: `1px solid ${T.border}`, borderRadius: 10, background: T.section,
@@ -497,6 +528,21 @@ window.__ModuleLoader__.load({
497
528
  rangeHead: { display: 'flex', alignItems: 'center', justifyContent: 'flex-start', flexWrap: 'wrap', gap: 16 },
498
529
  rangeMeta: { color: T.weak, fontSize: 11 },
499
530
  detailWrap: { overflowX: 'auto', borderTop: `1px solid ${T.border}`, paddingTop: 12 },
531
+ trendBox: { display: 'flex', flexDirection: 'column', gap: 8, borderTop: `1px solid ${T.border}`, paddingTop: 12, minWidth: 0 },
532
+ trendHead: { display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap', minWidth: 0 },
533
+ trendTitle: { fontSize: 13, fontWeight: 600 },
534
+ trendHint: { color: T.weak, fontSize: 11 },
535
+ trendSpacer: { flex: '1 1 auto' },
536
+ trendPlot: { position: 'relative', height: 132, minWidth: 0 },
537
+ trendGrid: { position: 'absolute', left: 0, right: 0, height: 1, background: T.border, pointerEvents: 'none' },
538
+ trendAxis: { position: 'absolute', left: 0, color: T.weak, fontSize: 11, fontVariantNumeric: 'tabular-nums' },
539
+ trendBars: { position: 'absolute', inset: '0 0 18px 0', display: 'flex', alignItems: 'flex-end', gap: 2, paddingLeft: 34 },
540
+ // 每根柱独占一个等分槽并在槽内居中:只对柱体设 maxWidth 会让所有柱挤到一侧
541
+ trendSlot: { flex: '1 1 0', minWidth: 1, height: '100%', display: 'flex', alignItems: 'flex-end', justifyContent: 'center' },
542
+ trendBar: { width: '100%', maxWidth: 36, borderRadius: '3px 3px 0 0', background: T.accent },
543
+ trendTicks: { position: 'absolute', left: 34, right: 0, bottom: 0, height: 18, display: 'flex', alignItems: 'center', gap: 2, color: T.weak, fontSize: 11 },
544
+ trendTick: { flex: '1 1 0', minWidth: 0, textAlign: 'center', whiteSpace: 'nowrap' },
545
+ trendMsg: { position: 'absolute', inset: '0 0 18px 34px', display: 'flex', alignItems: 'center', justifyContent: 'center', color: T.muted, fontSize: 11 },
500
546
  quotaCards: { display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 12 },
501
547
  quotaCard: {
502
548
  border: `1px solid ${T.border}`, borderRadius: 8, background: T.section, padding: 16,
@@ -841,34 +887,188 @@ window.__ModuleLoader__.load({
841
887
  h('span', { role: 'cell', style: { ...styles.cellNum, ...cell, textAlign: 'right' } }, row.requests),
842
888
  h('span', { role: 'cell', style: { ...styles.cellNum, ...cell, textAlign: 'right' } },
843
889
  row.hitRate === null || row.hitRate === undefined ? '—' : fmtRatio(row.hitRate)),
844
- h('span', { role: 'cell', style: { ...styles.cellNum, ...cell, textAlign: 'right' } },
845
- row.kind !== 'api' ? '—' : row.priced === false
846
- ? tr('未定价')
847
- : `${row.approximate === true ? '≈' : ''}${fmtMoney(row.cost, row.currency)}`)))))
890
+ h('span', {
891
+ role: 'cell',
892
+ 'data-testid': 'token-dash-detail-cost',
893
+ title: row.kind !== 'api'
894
+ ? tr('订阅不计价')
895
+ : row.priced === false
896
+ ? tr(REASON_TEXT[row.reason] ?? '未定价')
897
+ : undefined,
898
+ style: { ...styles.cellNum, ...cell, textAlign: 'right' },
899
+ },
900
+ row.kind !== 'api' || row.priced === 'empty'
901
+ ? '—'
902
+ : row.priced === false
903
+ ? tr('未定价')
904
+ : `${row.approximate === true ? '≈' : ''}${fmtMoney(row.cost, row.currency)}`)))))
905
+ }
906
+
907
+ /** P3 趋势指标:顺序即四格与胶囊的显示顺序。 */
908
+ const TREND_METRICS = [['tokens', 'Tokens'], ['requests', '请求'], ['cost', '费用'], ['hitRate', '命中率']]
909
+ const METRIC_LABELS = { tokens: 'Tokens', requests: '请求', cost: '费用', hitRate: '命中率' }
910
+ /** 词典里 '万' 的英文值是 K:据此判断当前是否中文,不依赖 localeService 暴露语言码。 */
911
+ const isChinese = () => tr('万') === '万'
912
+
913
+ /** 趋势轴刻度:中文「万 / 亿」,英文沿用 fmtTokens 的 K / M / B。 */
914
+ function fmtTrendTokens(value) {
915
+ const n = Math.max(0, Number(value) || 0)
916
+ if (!isChinese()) return fmtTokens(n)
917
+ if (n >= 1e8) return `${trimZeros((n / 1e8).toFixed(1))}亿`
918
+ if (n >= 1e4) return `${trimZeros((n / 1e4).toFixed(1))}万`
919
+ return fmtTokens(n)
920
+ }
921
+
922
+ /** 命中率轴的中间档:留一位小数,避免 96.5% 被压成 96%。 */
923
+ const fmtHitTick = (value) => `${trimZeros(((Number(value) || 0) * 100).toFixed(1))}%`
924
+
925
+ /** 单点取值:命中率缺数据返回 null(不画柱),其余字段缺失按 0。 */
926
+ function trendValue(point, metric) {
927
+ if (point === null || point === undefined) return null
928
+ if (metric === 'hitRate') return point.hitRate === undefined ? null : point.hitRate
929
+ if (metric === 'cost') return costTotalOf(point)
930
+ return Number(point[metric]) || 0
931
+ }
932
+
933
+ /** 成本点的标量:多币种时调用方已禁用成本指标,这里只处理单币种;空对象按 0。 */
934
+ function costTotalOf(point) {
935
+ const entries = Object.entries(point.cost ?? {})
936
+ if (entries.length === 0) return 0
937
+ return Number(entries[0][1]?.cost) || 0
938
+ }
939
+
940
+ function fmtMetric(value, metric, currency = 'CNY') {
941
+ if (value === null || value === undefined) return tr('无数据')
942
+ if (metric === 'hitRate') return fmtRatio(value)
943
+ if (metric === 'cost') return fmtMoney(value, currency)
944
+ if (metric === 'requests') return String(Math.round(value))
945
+ return fmtTokens(value)
946
+ }
947
+
948
+ function fmtAxisMetric(value, metric, currency = 'CNY') {
949
+ if (metric === 'hitRate') return fmtHitTick(value)
950
+ if (metric === 'cost') return fmtMoney(value, currency)
951
+ return fmtTrendTokens(value)
848
952
  }
849
953
 
850
- /** P3 两格卡:总费用(多币种同行)与真实 Tokens。 */
851
- function RangeCards({ usage }) {
954
+ /** 命中率轴下限:命中率普遍在 90% 以上,从 0 起画柱子几乎等高;最低值往下留余量并取整到 5%。 */
955
+ function hitRateFloor(values) {
956
+ const known = values.filter((value) => value !== null)
957
+ if (known.length === 0) return 0
958
+ const min = Math.min(...known)
959
+ const padded = min - Math.max((1 - min) / 2, 0.02)
960
+ const floor = Math.floor(padded * 20 + 1e-9) / 20
961
+ return floor < 0.5 ? 0 : floor
962
+ }
963
+
964
+ /** 英文月份短名:用 Intl 而不是手写表,大小写与语言差异交给平台。 */
965
+ function monthNameOf(dayKey) {
966
+ const [year, month] = String(dayKey).split('-').map(Number)
967
+ if (!Number.isFinite(year) || !Number.isFinite(month)) return dayKey
968
+ try {
969
+ return new Intl.DateTimeFormat('en', { month: 'short' }).format(new Date(year, month - 1, 1))
970
+ } catch {
971
+ return dayKey
972
+ }
973
+ }
974
+
975
+ /** P3 四格卡:兼作趋势指标选择器;每格 button[role=radio],选中态由 metric 决定。 */
976
+ function RangeCards({ usage, metric = 'tokens', onMetricChange }) {
852
977
  const pending = usage === null
853
978
  const costEntries = Object.entries(usage?.totals ?? {})
854
979
  const total = usage?.total ?? null
855
980
  const costNodes = costEntries.map(([currency, value]) => h('span', { key: currency }, fmtMoney(value.cost, currency)))
856
- return h('div', { 'data-testid': 'token-dash-range-cards', 'data-td-cards': true, style: styles.summaryBand },
857
- h('div', { 'data-testid': 'token-dash-card-cost', style: styles.summaryHalf },
858
- h('div', { style: styles.summaryK }, tr('总费用')),
859
- h('div', { 'data-testid': 'token-dash-cost-values', style: styles.summaryV },
860
- pending ? '—' : (costNodes.length === 0 ? '—' : costNodes))),
861
- h('div', { 'data-testid': 'token-dash-card-tokens', style: styles.summaryHalf },
862
- h('div', { style: styles.summaryK },
863
- `${tr('真实 Tokens')} `,
981
+ const cell = (key, label, valueNode, subNode) => h('button', {
982
+ type: 'button', role: 'radio', 'aria-pressed': metric === key,
983
+ 'data-testid': `token-dash-card-${key}`,
984
+ onClick: () => onMetricChange?.(key),
985
+ style: { ...styles.summaryHalf, ...(metric === key ? styles.summaryHalfOn : null) },
986
+ },
987
+ h('span', { style: { ...styles.summaryK, ...(metric === key ? { color: T.accent } : null) } }, label),
988
+ h('div', { style: styles.summaryV }, valueNode),
989
+ h('div', { style: styles.summarySub }, subNode))
990
+ return h('div', {
991
+ 'data-testid': 'token-dash-range-cards', 'data-td-cards': true, role: 'radiogroup',
992
+ 'aria-label': tr('趋势指标'), style: styles.summaryBand,
993
+ },
994
+ cell('cost', tr('总费用'),
995
+ pending ? '—' : (costNodes.length === 0 ? '—' : costNodes),
996
+ pending ? '—' : tr('{n} 个币种', { n: costEntries.length })),
997
+ h('button', {
998
+ type: 'button', role: 'radio', 'aria-pressed': metric === 'tokens',
999
+ 'data-testid': 'token-dash-card-tokens',
1000
+ onClick: () => onMetricChange?.('tokens'),
1001
+ style: { ...styles.summaryHalf, ...(metric === 'tokens' ? styles.summaryHalfOn : null) },
1002
+ },
1003
+ h('span', { style: { ...styles.summaryK, ...(metric === 'tokens' ? { color: T.accent } : null) } },
1004
+ `${tr('真实 Tokens')}`,
864
1005
  h(InfoTip, {
865
1006
  label: tr('Tokens 括号说明'),
866
1007
  text: tr('Tokens 括号顺序:输入 / 缓存(读+写)/ 输出'),
867
1008
  variant: 'inline',
868
1009
  }, h(Icon, { name: 'info', size: 11 }))),
869
- h('div', { style: styles.summaryV }, pending ? '—' : fmtTokens(total?.tokens ?? 0)),
1010
+ h('div', { 'data-testid': 'token-dash-cost-values', style: styles.summaryV }, pending ? '—' : fmtTokens(total?.tokens ?? 0)),
870
1011
  h('div', { style: styles.summarySub },
871
- pending ? '—' : `${fmtTokens(total?.input ?? 0)} · ${fmtTokens(total?.cache ?? 0)} · ${fmtTokens(total?.output ?? 0)}`)))
1012
+ pending ? '—' : `${fmtTokens(total?.input ?? 0)} · ${fmtTokens(total?.cache ?? 0)} · ${fmtTokens(total?.output ?? 0)}`)),
1013
+ cell('requests', tr('总请求数'),
1014
+ pending ? '—' : String(total?.requests ?? 0), tr('范围内全部模型')),
1015
+ cell('hitRate', tr('缓存命中率'),
1016
+ pending ? '—' : (total?.hitRate === null || total?.hitRate === undefined ? '—' : fmtRatio(total.hitRate)),
1017
+ pending ? '—' : tr('创建 {a} · 命中 {b}', { a: fmtTokens(total?.cacheWrite ?? 0), b: fmtTokens(total?.cacheRead ?? 0) })))
1018
+ }
1019
+
1020
+ /** P3 趋势柱:连续日/月序列 → flex 柱 + 绝对定位网格线;悬停走原生 title,无交互状态。 */
1021
+ function TrendChart({ series, metric, grain = 'day', onMetricChange }) {
1022
+ const points = Array.isArray(series) ? series : []
1023
+ const values = points.map((point) => trendValue(point, metric))
1024
+ const known = values.filter((value) => value !== null && value > 0)
1025
+ const max = known.length > 0 ? Math.max(...known) : 0
1026
+ const floor = metric === 'hitRate' ? hitRateFloor(values) : 0
1027
+ const span = Math.max(max - floor, 1e-9)
1028
+ // 多币种时一根柱无法表达,按既定决策禁用成本指标并给出口文案
1029
+ const currencies = new Set()
1030
+ for (const point of points) for (const currency of Object.keys(point.cost ?? {})) currencies.add(currency)
1031
+ const costBlocked = metric === 'cost' && currencies.size > 1
1032
+ const costCurrency = currencies.size === 1 ? [...currencies][0] : 'CNY'
1033
+ const tickOf = (dayKey) => {
1034
+ if (grain !== 'month') return String(dayKey).slice(5)
1035
+ return isChinese() ? `${String(dayKey).slice(5)}月` : monthNameOf(dayKey)
1036
+ }
1037
+ // 日期刻度按可用宽度抽稀,末点必显
1038
+ const step = Math.max(1, Math.ceil(points.length / 6))
1039
+ const emptyMessage = costBlocked
1040
+ ? tr('多币种下成本柱不可用,请切换其他指标')
1041
+ : (points.length === 0 || known.length === 0 ? tr('该范围内暂无消耗') : null)
1042
+ return h('div', { 'data-testid': 'token-dash-trend', 'data-td-trend': metric, style: styles.trendBox },
1043
+ h('div', { style: styles.trendHead },
1044
+ h('b', { 'data-testid': 'token-dash-trend-title', style: styles.trendTitle },
1045
+ tr('使用趋势 · {metric}', { metric: tr(METRIC_LABELS[metric]) })),
1046
+ h('span', { style: styles.trendHint }, tr(grain === 'month' ? '按月' : '按天')),
1047
+ h('span', { style: styles.trendSpacer }),
1048
+ h(Segmented, {
1049
+ value: metric, onChange: onMetricChange, label: tr('趋势指标'), kind: 'radiogroup', fit: true,
1050
+ options: TREND_METRICS.map(([value, label]) => ({ value, label: tr(label) })),
1051
+ })),
1052
+ h('div', { style: styles.trendPlot },
1053
+ h('span', { 'aria-hidden': true, style: { ...styles.trendGrid, top: 0 } }),
1054
+ h('span', { 'aria-hidden': true, style: { ...styles.trendGrid, top: '50%' } }),
1055
+ h('span', { 'aria-hidden': true, style: { ...styles.trendGrid, bottom: 18 } }),
1056
+ emptyMessage === null ? h('span', { style: { ...styles.trendAxis, top: 0 } }, fmtAxisMetric(max, metric, costCurrency)) : null,
1057
+ emptyMessage === null ? h('span', { style: { ...styles.trendAxis, top: '50%', transform: 'translateY(-100%)' } }, fmtAxisMetric(floor + span / 2, metric, costCurrency)) : null,
1058
+ emptyMessage === null ? h('div', { style: styles.trendBars },
1059
+ ...points.map((point, index) => {
1060
+ const value = values[index]
1061
+ const ratio = value === null || value <= floor ? 0 : Math.max(0, Math.min(100, ((value - floor) / span) * 100))
1062
+ return h('span', { key: point.dayKey, style: styles.trendSlot },
1063
+ h('span', {
1064
+ 'data-testid': `token-dash-trend-bar-${point.dayKey}`,
1065
+ title: `${point.dayKey} · ${fmtMetric(value, metric, costCurrency)}`,
1066
+ style: { ...styles.trendBar, height: `${ratio}%`, background: ratio === 0 ? 'transparent' : T.accent },
1067
+ }))
1068
+ })) : h('div', { 'data-testid': 'token-dash-trend-empty', style: styles.trendMsg }, emptyMessage),
1069
+ emptyMessage === null ? h('div', { style: styles.trendTicks },
1070
+ ...points.map((point, index) => h('span', { key: point.dayKey, style: styles.trendTick },
1071
+ index % step === 0 || index === points.length - 1 ? tickOf(point.dayKey) : ''))) : null))
872
1072
  }
873
1073
 
874
1074
  function MiniBar({ ratio = 0, neutral = false, stretch = false }) {
@@ -889,6 +1089,18 @@ window.__ModuleLoader__.load({
889
1089
  return tr('查询失败')
890
1090
  }
891
1091
 
1092
+ /** P3 API 卡底部说明:状态 · 比例,再补余额周期 / 限流 / 渠道用量(渠道值只读)。 */
1093
+ function apiCardCaption(provider, { hasBudget, percent, budget }) {
1094
+ const parts = [`${hasBudget ? stateOf(percent, API_CRITICAL) : 'unset'} · ${hasBudget ? fmtRatio(budget.percent) : '—'}`]
1095
+ const periodEnd = Number(provider.balance?.periodEnd)
1096
+ const period = Number.isFinite(periodEnd) && periodEnd > 0 ? resetParts(periodEnd).absolute : null
1097
+ if (period !== null) parts.push(tr('周期至 {time}', { time: period }))
1098
+ if (provider.rateLimited === true) parts.push(tr('限流中'))
1099
+ const usageUsd = Number(provider.channel?.usageUsd)
1100
+ if (Number.isFinite(usageUsd)) parts.push(tr('渠道用量 {value}', { value: fmtMoney(usageUsd, provider.currency) }))
1101
+ return parts.join(' · ')
1102
+ }
1103
+
892
1104
  function windowLabel(key) { return { '5h': '5h', week: tr('周'), month: tr('月') }[key] ?? key }
893
1105
 
894
1106
  function subscriptionText(provider) {
@@ -960,12 +1172,14 @@ window.__ModuleLoader__.load({
960
1172
  const [panelShift, setPanelShift] = useState(0)
961
1173
  const pillRef = useRef(null)
962
1174
  const panelRef = useRef(null)
1175
+ const lastLoadAt = useRef(0)
963
1176
 
964
1177
  useEffect(() => {
965
1178
  try { if (window.localStorage.getItem('token-dash-hint-seen') !== '1') setHint(true) } catch { /* ignore */ }
966
1179
  }, [])
967
1180
 
968
1181
  const load = useCallback(async () => {
1182
+ lastLoadAt.current = Date.now()
969
1183
  setRefreshing(true)
970
1184
  try {
971
1185
  const data = await getJson(summaryPath(active))
@@ -984,7 +1198,13 @@ window.__ModuleLoader__.load({
984
1198
  }, [])
985
1199
 
986
1200
  useEffect(() => { load() }, [load])
987
- usePolling(load, { refreshMs })
1201
+ // 展开即刷新:距上次拉取超过 2s 才发,避免开合抖动与 refreshMs 变化引起的重跑;可见期轮询缩到 10s
1202
+ useEffect(() => {
1203
+ if (!open) return
1204
+ if (Date.now() - lastLoadAt.current < 2000) return
1205
+ void load()
1206
+ }, [open, load])
1207
+ usePolling(load, { refreshMs: open ? Math.min(10_000, refreshMs) : refreshMs })
988
1208
 
989
1209
  const refreshSubs = useCallback(async () => {
990
1210
  try { await fetch(`${API}/providers/refresh`, { method: 'POST', headers: { accept: 'application/json' } }) } catch { /* fall through */ }
@@ -1544,6 +1764,9 @@ window.__ModuleLoader__.load({
1544
1764
  const used = Number(budget?.used ?? 0)
1545
1765
  const plan = hasBudget ? Number(budget.amount) - used : null
1546
1766
  const balance = balanceText(provider, true)
1767
+ // Ollama 这类「额度 + 购买余额」的 provider:进度只用 allowance / used,单值位不重复
1768
+ const allowance = Number(provider.balance?.allowance)
1769
+ const purchased = Number(provider.balance?.purchased)
1547
1770
  const entry = prefs?.budgets?.[provider.id]
1548
1771
  const initial = entry === undefined ? '' : (entry.amount > 0 ? entry.amount.toFixed(2) : '')
1549
1772
  const error = errors[provider.id]
@@ -1599,12 +1822,37 @@ window.__ModuleLoader__.load({
1599
1822
  h('div', { style: styles.kvRow },
1600
1823
  h('span', { style: styles.kvLabel }, tr('真实余额')),
1601
1824
  h('span', { 'data-testid': `token-dash-budget-balance-${provider.id}`, style: styles.kvValue }, balance ?? '—')),
1825
+ Number.isFinite(allowance) && allowance > 0
1826
+ ? h('div', { style: styles.kvRow },
1827
+ h('span', { style: styles.kvLabel }, tr('套餐已用')),
1828
+ h('span', {
1829
+ 'data-testid': `token-dash-budget-allowance-${provider.id}`,
1830
+ style: styles.kvValue,
1831
+ }, `${fmtMoney(provider.balance?.used, provider.currency)} / ${fmtMoney(allowance, provider.currency)}`))
1832
+ : null,
1833
+ Number.isFinite(purchased) && purchased > 0
1834
+ ? h('div', { style: styles.kvRow },
1835
+ h('span', { style: styles.kvLabel }, tr('购买余额')),
1836
+ h('span', {
1837
+ 'data-testid': `token-dash-budget-purchased-${provider.id}`,
1838
+ style: styles.kvValue,
1839
+ }, fmtMoney(purchased, provider.currency)))
1840
+ : null,
1602
1841
  h('div', { style: styles.kvRow },
1603
1842
  h('span', { style: styles.kvLabel }, tr('本月已花')),
1604
- h('span', { 'data-testid': `token-dash-budget-month-${provider.id}`, style: styles.kvValue },
1605
- fmtMoney(provider.usage?.monthCost, provider.currency))),
1606
- h('div', { style: styles.cardCaption },
1607
- `${hasBudget ? stateOf(percent, API_CRITICAL) : 'unset'} · ${hasBudget ? fmtRatio(budget.percent) : '—'}`))
1843
+ h('span', {
1844
+ 'data-testid': `token-dash-budget-month-${provider.id}`,
1845
+ style: { ...styles.kvValue, display: 'inline-flex', alignItems: 'baseline', gap: 4 },
1846
+ },
1847
+ fmtMoney(provider.usage?.monthCost, provider.currency),
1848
+ provider.currencySource === 'community' && provider.currency === 'CNY'
1849
+ ? h('span', {
1850
+ 'data-testid': `token-dash-currency-source-${provider.id}`,
1851
+ title: tr('价格取社区价目表(人民币),与渠道账单可能有差异'),
1852
+ style: { fontSize: 10, color: T.weak },
1853
+ }, tr('按社区表 CNY'))
1854
+ : null)),
1855
+ h('div', { style: styles.cardCaption }, apiCardCaption(provider, { hasBudget, percent, budget })))
1608
1856
  }))
1609
1857
  }
1610
1858
 
@@ -1694,6 +1942,7 @@ window.__ModuleLoader__.load({
1694
1942
  const [usage, setUsage] = useState(null)
1695
1943
  const [prefs, setPrefs] = useState(null)
1696
1944
  const [range, setRange] = useState('all')
1945
+ const [metric, setMetric] = useState('tokens')
1697
1946
  const [refreshing, setRefreshing] = useState(false)
1698
1947
  const [error, setError] = useState(false)
1699
1948
  const [usageError, setUsageError] = useState(false)
@@ -1734,7 +1983,8 @@ window.__ModuleLoader__.load({
1734
1983
  }, [loadSummary, loadPrefs, loadUsage])
1735
1984
 
1736
1985
  useEffect(() => { void refresh() }, [refresh])
1737
- usePolling(() => { void loadSummary() }, { refreshMs: Number(summary?.refreshMs) || 60000 })
1986
+ // 看板常驻,轮询周期取 min(10s, refreshMs);费用与明细来自 /usage,必须一起刷
1987
+ usePolling(() => { void loadSummary(); void loadUsage() }, { refreshMs: Math.min(10_000, Number(summary?.refreshMs) || 60000) })
1738
1988
 
1739
1989
  const savePrefs = useCallback(async (patch) => {
1740
1990
  if (prefsRef.current === null) return { ok: false, reason: 'not-ready' }
@@ -1811,7 +2061,8 @@ window.__ModuleLoader__.load({
1811
2061
  usageError ? h('div', { style: styles.errorStrip, role: 'alert' },
1812
2062
  h('span', null, tr('范围数据加载失败')),
1813
2063
  h('button', { type: 'button', style: styles.button, onClick: () => { void loadUsage() } }, tr('重试'))) : null,
1814
- h(RangeCards, { usage }),
2064
+ h(RangeCards, { usage, metric, onMetricChange: setMetric }),
2065
+ h(TrendChart, { series: usage?.series, metric, grain: usage?.grain, onMetricChange: setMetric }),
1815
2066
  h('div', { style: styles.detailWrap }, h(DetailTable, {
1816
2067
  rows: models,
1817
2068
  providerNames: Object.fromEntries(providers.map((provider) => [provider.id, provider.name])),