dsh-token-dash 2.0.1 → 2.1.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>
@@ -34,15 +34,17 @@
34
34
 
35
35
  | Provider | Billing | Credential | What you get |
36
36
  |---|---|---|---|
37
- | DeepSeek | Pay-as-you-go | DS account wallet / `DEEPSEEK_API_KEY` | Balance, month-to-date spend, budget |
38
- | Zhipu GLM Coding | Subscription / API | `ZHIPU_API_KEY` / `GLM_API_KEY` / `ZAI_API_KEY` | 5h + weekly windows |
39
- | Kimi Coding | Subscription / API | `KIMI_API_KEY` / `KIMI_CODING_API_KEY`, optional `MOONSHOT_API_KEY` | 5h + weekly/monthly windows; falls back to balance |
40
- | OpenRouter | Pay-as-you-go | `OPENROUTER_API_KEY` | Credits (USD) |
41
- | Qwen | Pay-as-you-go | `DASHSCOPE_API_KEY` (CNY) / `DASHSCOPE_INTL_API_KEY` (USD) | Usage only; balance unsupported |
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
42
  | OpenCode Go | Subscription | `OPENCODE_GO_API_KEY` | 5h / weekly / monthly windows (USD) |
43
43
  | Command Code | Subscription | `COMMAND_CODE_API_KEY` + `COMMAND_CODE_ORG_ID` | 5h + weekly windows, credits (CNY) |
44
+ | Ollama Cloud | API usage | `OLLAMA_API_KEY` | Plan + purchased credits (USD), plan usage, 30-day channel usage |
44
45
 
45
46
  - 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.
47
+ - 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
48
  - Keys are detected automatically; GLM / Kimi / OpenCode Go / Command Code can be re-detected from the dashboard footer.
47
49
  - Subscription models count toward Tokens but not cost; billing mode is pinned per key instead of following quota flakiness.
48
50
  - Balance, quota and usage are separate; a balance failure never resets today's Token ledger to zero.
@@ -51,40 +53,40 @@
51
53
 
52
54
  Screenshots use mock data so the full layout is visible at once.
53
55
 
54
- **P1 · Composer footer-right Pill**: pay-as-you-go / subscription variants; click to open, click outside, `×` or `Esc` to close.
56
+ **P1 · Composer footer-right Pill**: API usage / subscription variants; click to open, click outside, `×` or `Esc` to close.
55
57
 
56
58
  <p align="center">
57
- <img src="https://raw.githubusercontent.com/spartawhy117/dsh-token-dash/main/docs/pic/pill-api.png" alt="Pay-as-you-go pill" />
59
+ <img src="https://raw.githubusercontent.com/spartawhy117/dsh-token-dash/main/docs/pic/en/pill-api.png" alt="API usage pill" />
58
60
  </p>
59
61
 
60
62
  <p align="center">
61
- <img src="https://raw.githubusercontent.com/spartawhy117/dsh-token-dash/main/docs/pic/pill-sub.png" alt="Subscription pill" />
63
+ <img src="https://raw.githubusercontent.com/spartawhy117/dsh-token-dash/main/docs/pic/en/pill-sub.png" alt="Subscription pill" />
62
64
  </p>
63
65
 
64
66
  **P2 · Floating panel (current model)**: fixed 380, one row with three groups — used ring / used-budget / real balance — with the balance right-aligned to the panel edge, a full-width range control and the usage table.
65
67
 
66
68
  <p align="center">
67
- <img src="https://raw.githubusercontent.com/spartawhy117/dsh-token-dash/main/docs/pic/panel-api.png" alt="Floating panel - pay-as-you-go" />
69
+ <img src="https://raw.githubusercontent.com/spartawhy117/dsh-token-dash/main/docs/pic/en/panel-api.png" alt="Floating panel - API usage" />
68
70
  </p>
69
71
 
70
72
  <p align="center">
71
- <img src="https://raw.githubusercontent.com/spartawhy117/dsh-token-dash/main/docs/pic/panel-sub-2.png" alt="Floating panel - two subscription windows" />
73
+ <img src="https://raw.githubusercontent.com/spartawhy117/dsh-token-dash/main/docs/pic/en/panel-sub-2.png" alt="Floating panel - two subscription windows" />
72
74
  </p>
73
75
 
74
76
  <p align="center">
75
- <img src="https://raw.githubusercontent.com/spartawhy117/dsh-token-dash/main/docs/pic/panel-sub-3.png" alt="Floating panel - three subscription windows" />
77
+ <img src="https://raw.githubusercontent.com/spartawhy117/dsh-token-dash/main/docs/pic/en/panel-sub-3.png" alt="Floating panel - three subscription windows" />
76
78
  </p>
77
79
 
78
80
  - Subscription windows use three slots: first left, second center, third right; two windows occupy the first two slots.
79
81
  - Model column is capped at 150; Tokens / requests / hit rate are right-aligned.
80
82
 
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.
83
+ **P3 · Full dashboard**: cards for 8 providers, summary band, 8-column model breakdown and a settings capsule; the page owns its scrollbar at the window edge.
82
84
 
83
85
  <p align="center">
84
- <img src="https://raw.githubusercontent.com/spartawhy117/dsh-token-dash/main/docs/pic/settings.png" alt="Full dashboard" />
86
+ <img src="https://raw.githubusercontent.com/spartawhy117/dsh-token-dash/main/docs/pic/en/settings.png" alt="Full dashboard" />
85
87
  </p>
86
88
 
87
- - Pay-as-you-go card: budget input, planned balance, real balance, month-to-date spend; subscription card: one ring per window with remaining percentage and countdown.
89
+ - API usage card: budget input, planned balance, real balance, month-to-date spend; subscription card: one ring per window with remaining percentage and countdown.
88
90
  - Breakdown: model / Tokens / input / cache / output / requests / hit rate / cost; everything except the model column is right-aligned.
89
91
  - Settings capsule: refresh interval + account-balance toggle; logs, export/import, price table and version below.
90
92
  - 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.
@@ -115,6 +117,8 @@ Update: run `update` with the same name, or use the `⤓` button on the right of
115
117
  - The UI currently ships Chinese / English only. Other DSH languages (Japanese, German, Russian, etc.) fall back to English.
116
118
  - After a DSH upgrade the plugin may disappear from the profile; reinstall the same tarball — the ledger is not deleted.
117
119
  - Qwen tracks usage only; its balance endpoint is unsupported. Other balances/quotas follow what each API returns.
120
+ - A USD-billed provider that only matches the CNY price table shows "Unpriced" with a reason instead of rendering CNY numbers as USD; add a `currency: "USD"` entry to `prefs.json` `priceOverrides` for exact amounts.
121
+ - 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
122
  - Upstream APIs are rate-limited; successful results are cached for 60s, failures for 10s, and concurrent requests are coalesced.
119
123
 
120
124
  ## Data & privacy
@@ -146,7 +150,8 @@ Common events:
146
150
  ```bash
147
151
  npm test # unit tests (80 passing)
148
152
  npm run e2e # end-to-end (temp DSH_HOME + web profile + Playwright)
149
- npm run shots # regenerate the P1/P2/P3 screenshots in docs/pic from mock data
153
+ npm run shots # regenerate the Chinese P1/P2/P3 screenshots in docs/pic
154
+ npm run shots -- --en # regenerate the English screenshots in docs/pic/en
150
155
  npm run pack # build the release tarball into build/
151
156
  ```
152
157
 
package/README.md CHANGED
@@ -9,8 +9,8 @@
9
9
  </p>
10
10
 
11
11
  <p align="center">
12
- 在 DSH 输入框旁看清今天的模型消耗、本月的预算余量,以及 7 家供应商的订阅窗口。<br />
13
- 填 Key 自动识别订阅或按量计费;费用、Tokens、缓存命中全部在本地估算;<br />
12
+ 在 DSH 输入框旁看清今天的模型消耗、本月的预算余量,以及 8 家供应商的订阅窗口。<br />
13
+ 填 Key 自动识别订阅或 API 用量;费用、Tokens、缓存命中全部在本地估算;<br />
14
14
  当月数据可导出备份,换机或重装后一键导入恢复。
15
15
  </p>
16
16
 
@@ -28,21 +28,23 @@
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
  ## 支持矩阵
34
34
 
35
35
  | 供应商 | 计费形态 | 凭据 | 能看到什么 |
36
36
  |---|---|---|---|
37
- | DeepSeek | 按量 | DS 账号钱包 / `DEEPSEEK_API_KEY` | 账户余额、本月已花、预算 |
38
- | Zhipu GLM Coding | 订阅 / 按量 | `ZHIPU_API_KEY` / `GLM_API_KEY` / `ZAI_API_KEY` | 5h + 周窗口 |
39
- | Kimi Coding | 订阅 / 按量 | `KIMI_API_KEY` / `KIMI_CODING_API_KEY`,可选 `MOONSHOT_API_KEY` | 5h + 周/月窗口;订阅查询失败可回落余额 |
40
- | OpenRouter | 按量 | `OPENROUTER_API_KEY` | Credits(USD) |
41
- | Qwen | 按量 | `DASHSCOPE_API_KEY`(CNY)/ `DASHSCOPE_INTL_API_KEY`(USD) | 仅用量;余额不支持 |
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
42
  | OpenCode Go | 订阅 | `OPENCODE_GO_API_KEY` | 5h / 周 / 月窗口(USD) |
43
43
  | Command Code | 订阅 | `COMMAND_CODE_API_KEY` + `COMMAND_CODE_ORG_ID` | 5h + 周窗口、Credits(CNY) |
44
+ | Ollama Cloud | API 用量 | `OLLAMA_API_KEY` | 套餐剩余 + 购买余额(USD)、套餐已用、渠道 30 天用量 |
44
45
 
45
46
  - 在 DSH 的凭据设置中按上表名称保存 Key;插件只通过宿主 `credentials` 读取,不读环境变量或本机登录文件。
47
+ - Ollama 在 DSH 里需要用「自定义 OpenAI 兼容供应商」接入:route id 必须填 `ollama`(凭据按 `<ROUTE>_API_KEY` 派生成 `OLLAMA_API_KEY`),自定义名填别的会取不到 Key,余额卡也不会出现。
46
48
  - 填 Key 后自动探测;GLM / Kimi / OpenCode Go / Command Code 可在「全量看板」底部重新检测订阅。
47
49
  - 订阅模型计入 Tokens,但不计费用;计费形态按 Key 固化,不随配额接口抖动。
48
50
  - 余额、配额、用量分开展示;余额失败不会把当天的 Token 记账清零。
@@ -51,10 +53,10 @@
51
53
 
52
54
  以下截图使用假数据演示,便于一次看到完整效果。
53
55
 
54
- **P1 · 输入框底栏右侧 Pill**:按量 / 订阅两种形态,点击展开浮层,点击外部、`×` 或 `Esc` 收起。
56
+ **P1 · 输入框底栏右侧 Pill**:API 用量 / 订阅两种形态,点击展开浮层,点击外部、`×` 或 `Esc` 收起。
55
57
 
56
58
  <p align="center">
57
- <img src="https://raw.githubusercontent.com/spartawhy117/dsh-token-dash/main/docs/pic/pill-api.png" alt="按量 Pill" />
59
+ <img src="https://raw.githubusercontent.com/spartawhy117/dsh-token-dash/main/docs/pic/pill-api.png" alt="API 用量 Pill" />
58
60
  </p>
59
61
 
60
62
  <p align="center">
@@ -64,7 +66,7 @@
64
66
  **P2 · 浮层(当前模型)**:固定 380,单行三组「已用环 / 已用·预算 / 真实余额」,真实余额右对齐到面板右缘;时间范围撑满,下面是用量表。
65
67
 
66
68
  <p align="center">
67
- <img src="https://raw.githubusercontent.com/spartawhy117/dsh-token-dash/main/docs/pic/panel-api.png" alt="浮层 · 按量形态" />
69
+ <img src="https://raw.githubusercontent.com/spartawhy117/dsh-token-dash/main/docs/pic/panel-api.png" alt="浮层 · API 用量形态" />
68
70
  </p>
69
71
 
70
72
  <p align="center">
@@ -78,13 +80,13 @@
78
80
  - 订阅窗口固定三槽位:第 1 窗左、第 2 窗中、第 3 窗右;只有两窗时占前两个槽位。
79
81
  - 模型列上限 150,Tokens / 请求 / 命中右对齐;长模型名用省略号,悬浮可看全名。
80
82
 
81
- **P3 · 整页看板**:7 家供应商卡片、摘要带、8 列模型明细、底部设置胶囊;页面自己滚动,滚动条贴窗口右缘。
83
+ **P3 · 整页看板**:8 家供应商卡片、摘要带、8 列模型明细、底部设置胶囊;页面自己滚动,滚动条贴窗口右缘。
82
84
 
83
85
  <p align="center">
84
86
  <img src="https://raw.githubusercontent.com/spartawhy117/dsh-token-dash/main/docs/pic/settings.png" alt="整页看板" />
85
87
  </p>
86
88
 
87
- - 按量卡:预算输入、计划余额、真实余额、本月已花;订阅卡:每个窗口一个环 + 剩余百分比 + 倒计时。
89
+ - API 用量卡:预算输入、计划余额、真实余额、本月已花;订阅卡:每个窗口一个环 + 剩余百分比 + 倒计时。
88
90
  - 明细表:模型 / Tokens / 输入 / 缓存 / 输出 / 请求 / 命中 / 费用;除模型列外全部右对齐。
89
91
  - 设置区:胶囊外是「设置与数据管理」区块标题;胶囊内第一行刷新间隔 + 账户余额开关,下面是日志、导出导入、价格表与版本。
90
92
  - 间距只使用 4 / 8 / 12 / 16 / 24 / 32 六档,P2 / P3 同一套 token。
@@ -114,6 +116,8 @@ dsh plugin --profile desktop add /path/to/dsh-token-dash-x.y.z.tgz
114
116
  - 界面语言当前仅中文 / English;选择日语、德语、俄语等其他 DSH 语言时,插件文案显示英文回退。
115
117
  - 升级 DSH 后插件可能从 profile 消失,重装同一个 tarball 即可,账本不会被删。
116
118
  - Qwen 只统计用量,余额接口不支持;其余供应商的余额/配额以接口实际返回为准。
119
+ - 美元结算的供应商如果只命中人民币价目表,该模型会显示「未定价」并给出原因(不会把人民币数值当成美元);需要更精确的金额时,可在 `prefs.json` 的 `priceOverrides` 里按 `currency: "USD"` 补单价。
120
+ - Ollama 的余额与用量接口共享 10 次/分钟限流;触发限流时卡片保留上次数值并标「限流中」,恢复后自动更新。
117
121
  - 上游接口有速率限制;成功结果缓存 60s、失败结果缓存 10s,并发请求会合并。
118
122
 
119
123
  ## 数据与隐私
package/client.js CHANGED
@@ -45,9 +45,9 @@ window.__ModuleLoader__.load({
45
45
  '社区': 'Community', '内置兜底': 'Built-in fallback',
46
46
  '查询失败': 'Query failed', '套餐查询失败': 'Quota query failed',
47
47
  '周': 'Week', '月': 'Month', '重置': 'Reset',
48
- '按量 API': 'Pay-as-you-go', '订阅': 'Subscription', '账户套餐': 'Account plan',
48
+ 'API 用量': 'API usage', '订阅': 'Subscription', '账户套餐': 'Account plan',
49
49
  '预算': 'Budget', '未设置': 'Not set', '今日 {value}': 'Today {value}',
50
- '余额 {value}': 'Balance {value}', '预算已用 {value}': 'Budget used {value}',
50
+ '余额': 'Balance', '余额 {value}': 'Balance {value}', '预算已用 {value}': 'Budget used {value}',
51
51
  '预算未设置': 'Budget not set', '收起': 'Collapse', '展开': 'Expand',
52
52
  'Token 看板': 'Token dashboard', '点击查看 Token 看板': 'Click to view Token dashboard',
53
53
  'Token 看板:{text}': 'Token dashboard: {text}',
@@ -56,12 +56,12 @@ window.__ModuleLoader__.load({
56
56
  '目前支持 DeepSeek / Kimi / GLM / OpenRouter / Qwen API Key': 'Supports DeepSeek / Kimi / GLM / OpenRouter / Qwen API Keys',
57
57
  '刷新': 'Refresh', '关闭': 'Close',
58
58
  '未定价': 'Unpriced', '请求': 'Req', '命中': 'Hit',
59
- '按量计价(按供应商)': 'Pay-as-you-go (by provider)',
59
+ 'API 用量(按供应商)': 'API usage (by provider)',
60
60
  '订阅套餐(按供应商)': 'Subscription plans (by provider)',
61
61
  '名称': 'Name', '已用': 'Used', '已用 / 预算': 'Used / budget', '计划余额': 'Planned left', '真实余额': 'Real balance',
62
62
  '剩余 {value}': '{value} left', '本月已花': 'Spent this month',
63
63
  '今日': 'Today', '总费用': 'Total cost', '重试': 'Retry',
64
- '模型': 'Model', '共 {n} 个模型': 'Total {n} models', '窗': 'windows', '数据来源': 'Data source', '数据来自本机会话记录,费用与 Tokens 均在本地估算': 'Estimated locally from local session records', '范围与明细': 'Range & details', '输入': 'In', '缓存': 'Cache', '输出': 'Out', '费用': 'Cost',
64
+ '模型用量明细': 'Model usage details', '模型': 'Model', '共 {n} 个模型': 'Total {n} models', '窗': 'windows', '数据来源': 'Data source', '数据来自本机会话记录,费用与 Tokens 均在本地估算': 'Estimated locally from local session records', '范围与明细': 'Range & details', '输入': 'In', '缓存': 'Cache', '输出': 'Out', '费用': 'Cost',
65
65
  '费用(API 计价估算)': 'Cost (API estimate)',
66
66
  '重新检测订阅配额': 'Recheck subscription quota',
67
67
  '未检测到已配置供应商': 'No configured provider detected',
@@ -85,6 +85,7 @@ window.__ModuleLoader__.load({
85
85
  '日志已导出': 'Logs exported', '日志导出失败': 'Log export failed',
86
86
  '数据': 'Data', '备份与恢复': 'Backup and restore',
87
87
  '{n} 分钟后': 'in {n} min', '{n} 小时后': 'in {n} h', '{n} 天后': 'in {n} d',
88
+ '导出数据': 'Export data', '导入数据': 'Import data', '版本': 'Version',
88
89
  '导入中…': 'Importing…', '数据已导出': 'Data exported', '数据导出失败': 'Data export failed',
89
90
  '已导入 {month} 数据': 'Imported {month} data', '导入失败:{reason}': 'Import failed: {reason}',
90
91
  '检查失败': 'Check failed', '未发布': 'Not published', '已是最新': 'Up to date',
@@ -98,7 +99,7 @@ window.__ModuleLoader__.load({
98
99
  '版本 {version}': 'Version {version}',
99
100
  '{name} · {action} Token 看板': '{name} · {action} Token dashboard',
100
101
  '{name} 月度预算': '{name} monthly budget',
101
- '{name},按量 API,{budget},今日 {today}{balance}': '{name}, pay-as-you-go, {budget}, today {today}{balance}',
102
+ '{name},API 用量,{budget},今日 {today}{balance}': '{name}, API usage, {budget}, today {today}{balance}',
102
103
  '{name},订阅,账户套餐,{value}': '{name}, subscription, account plan, {value}',
103
104
  '更新于 {time}': 'Updated {time}', '数据来自本机会话记录': 'From local session records',
104
105
  '未配置凭据': 'No credentials', '刷新中': 'Refreshing',
@@ -108,8 +109,24 @@ window.__ModuleLoader__.load({
108
109
  '账户真实余额,不受预算影响': 'Account balance; not affected by budget',
109
110
  '本月累计消耗,等于已用/预算 的分子': 'Month-to-date spend; numerator of used/budget',
110
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',
111
120
  }
112
121
  const ZH = Object.fromEntries(Object.keys(EN).map((key) => [key, key]))
122
+ /** 未定价原因 → 可读文案;未知 reason 回退「未定价」。 */
123
+ const REASON_TEXT = {
124
+ 'no-model-price': '无匹配价目',
125
+ ambiguous: '候选模型不唯一',
126
+ 'invalid-model': '模型名无效',
127
+ 'kind-skip': '订阅不计价',
128
+ 'currency-mismatch': '价目表为 CNY,该 provider 按 USD 结算;可用 priceOverrides 补 USD 单价',
129
+ }
113
130
  const MESSAGES = { zh: ZH, en: EN }
114
131
  let localeService = null
115
132
  let ctxRef = null
@@ -639,11 +656,14 @@ window.__ModuleLoader__.load({
639
656
  } }))
640
657
  }
641
658
 
642
- function Segmented({ value, options, onChange, label, kind = 'tablist' }) {
659
+ function Segmented({ value, options, onChange, label, kind = 'tablist', fit = false }) {
643
660
  const itemRole = kind === 'radiogroup' ? 'radio' : 'tab'
644
661
  return h('div', {
645
662
  role: kind, 'aria-label': label,
646
- style: { display: 'flex', width: '100%', height: 28, padding: 2, boxSizing: 'border-box', gap: 2, borderRadius: 8, background: T.segment },
663
+ style: {
664
+ display: 'flex', width: fit ? 'max-content' : '100%', height: 28, padding: 2,
665
+ boxSizing: 'border-box', gap: 2, borderRadius: 8, background: T.segment,
666
+ },
647
667
  }, options.map((option, index) => {
648
668
  const selected = option.value === value
649
669
  return h('button', {
@@ -659,8 +679,8 @@ window.__ModuleLoader__.load({
659
679
  onChange(options[(index + direction + options.length) % options.length].value)
660
680
  },
661
681
  style: {
662
- flex: 1, minWidth: 0, height: 24, padding: '0 4px', borderRadius: 6, border: 'none',
663
- fontSize: 11, fontWeight: 500, cursor: 'pointer', font: 'inherit',
682
+ flex: fit ? '0 0 auto' : 1, minWidth: 0, height: 24, padding: '0 4px', borderRadius: 6, border: 'none',
683
+ fontSize: 11, fontWeight: 500, cursor: 'pointer', font: 'inherit', whiteSpace: 'nowrap',
664
684
  background: selected ? T.segmentOn : 'transparent',
665
685
  color: selected ? T.text : T.muted,
666
686
  boxShadow: selected ? 'var(--dsw-shadow-lv1, 0 1px 2px rgba(0,0,0,.08))' : 'none',
@@ -837,10 +857,21 @@ window.__ModuleLoader__.load({
837
857
  h('span', { role: 'cell', style: { ...styles.cellNum, ...cell, textAlign: 'right' } }, row.requests),
838
858
  h('span', { role: 'cell', style: { ...styles.cellNum, ...cell, textAlign: 'right' } },
839
859
  row.hitRate === null || row.hitRate === undefined ? '—' : fmtRatio(row.hitRate)),
840
- h('span', { role: 'cell', style: { ...styles.cellNum, ...cell, textAlign: 'right' } },
841
- row.kind !== 'api' ? '—' : row.priced === false
842
- ? tr('未定价')
843
- : `${row.approximate === true ? '≈' : ''}${fmtMoney(row.cost, row.currency)}`)))))
860
+ h('span', {
861
+ role: 'cell',
862
+ 'data-testid': 'token-dash-detail-cost',
863
+ title: row.kind !== 'api'
864
+ ? tr('订阅不计价')
865
+ : row.priced === false
866
+ ? tr(REASON_TEXT[row.reason] ?? '未定价')
867
+ : undefined,
868
+ style: { ...styles.cellNum, ...cell, textAlign: 'right' },
869
+ },
870
+ row.kind !== 'api' || row.priced === 'empty'
871
+ ? '—'
872
+ : row.priced === false
873
+ ? tr('未定价')
874
+ : `${row.approximate === true ? '≈' : ''}${fmtMoney(row.cost, row.currency)}`)))))
844
875
  }
845
876
 
846
877
  /** P3 两格卡:总费用(多币种同行)与真实 Tokens。 */
@@ -885,6 +916,18 @@ window.__ModuleLoader__.load({
885
916
  return tr('查询失败')
886
917
  }
887
918
 
919
+ /** P3 API 卡底部说明:状态 · 比例,再补余额周期 / 限流 / 渠道用量(渠道值只读)。 */
920
+ function apiCardCaption(provider, { hasBudget, percent, budget }) {
921
+ const parts = [`${hasBudget ? stateOf(percent, API_CRITICAL) : 'unset'} · ${hasBudget ? fmtRatio(budget.percent) : '—'}`]
922
+ const periodEnd = Number(provider.balance?.periodEnd)
923
+ const period = Number.isFinite(periodEnd) && periodEnd > 0 ? resetParts(periodEnd).absolute : null
924
+ if (period !== null) parts.push(tr('周期至 {time}', { time: period }))
925
+ if (provider.rateLimited === true) parts.push(tr('限流中'))
926
+ const usageUsd = Number(provider.channel?.usageUsd)
927
+ if (Number.isFinite(usageUsd)) parts.push(tr('渠道用量 {value}', { value: fmtMoney(usageUsd, provider.currency) }))
928
+ return parts.join(' · ')
929
+ }
930
+
888
931
  function windowLabel(key) { return { '5h': '5h', week: tr('周'), month: tr('月') }[key] ?? key }
889
932
 
890
933
  function subscriptionText(provider) {
@@ -956,12 +999,14 @@ window.__ModuleLoader__.load({
956
999
  const [panelShift, setPanelShift] = useState(0)
957
1000
  const pillRef = useRef(null)
958
1001
  const panelRef = useRef(null)
1002
+ const lastLoadAt = useRef(0)
959
1003
 
960
1004
  useEffect(() => {
961
1005
  try { if (window.localStorage.getItem('token-dash-hint-seen') !== '1') setHint(true) } catch { /* ignore */ }
962
1006
  }, [])
963
1007
 
964
1008
  const load = useCallback(async () => {
1009
+ lastLoadAt.current = Date.now()
965
1010
  setRefreshing(true)
966
1011
  try {
967
1012
  const data = await getJson(summaryPath(active))
@@ -980,7 +1025,13 @@ window.__ModuleLoader__.load({
980
1025
  }, [])
981
1026
 
982
1027
  useEffect(() => { load() }, [load])
983
- usePolling(load, { refreshMs })
1028
+ // 展开即刷新:距上次拉取超过 2s 才发,避免开合抖动与 refreshMs 变化引起的重跑;可见期轮询缩到 10s
1029
+ useEffect(() => {
1030
+ if (!open) return
1031
+ if (Date.now() - lastLoadAt.current < 2000) return
1032
+ void load()
1033
+ }, [open, load])
1034
+ usePolling(load, { refreshMs: open ? Math.min(10_000, refreshMs) : refreshMs })
984
1035
 
985
1036
  const refreshSubs = useCallback(async () => {
986
1037
  try { await fetch(`${API}/providers/refresh`, { method: 'POST', headers: { accept: 'application/json' } }) } catch { /* fall through */ }
@@ -1035,7 +1086,7 @@ window.__ModuleLoader__.load({
1035
1086
  const current = providers.find((provider) => provider.id === summary?.currentProviderId) ?? providers[0]
1036
1087
  let prefix = '[API]'
1037
1088
  let bodyNodes = [h('span', { key: 'unknown' }, '--')]
1038
- let ariaText = tr('按量 API')
1089
+ let ariaText = tr('API 用量')
1039
1090
  if (current?.kind === 'subscription') {
1040
1091
  prefix = `[${tr('订阅')}]`
1041
1092
  bodyNodes = subscriptionNodes(current)
@@ -1062,7 +1113,7 @@ window.__ModuleLoader__.load({
1062
1113
  h('span', { 'data-td-label': true, style: styles.summaryLabel }, tr('余额')),
1063
1114
  h('span', { style: styles.num }, balance)),
1064
1115
  ].filter(Boolean)
1065
- ariaText = tr('{name},按量 API,{budget},今日 {today}{balance}', { name: current.name, budget: hasBudget ? tr('预算已用 {value}', { value: fmtRatio(budget.percent) }) : tr('预算未设置'), today: fmtMoney(current.usage?.todayCost, current.currency), balance: balance === null ? '' : `,${tr('余额 {value}', { value: balance })}` })
1116
+ ariaText = tr('{name},API 用量,{budget},今日 {today}{balance}', { name: current.name, budget: hasBudget ? tr('预算已用 {value}', { value: fmtRatio(budget.percent) }) : tr('预算未设置'), today: fmtMoney(current.usage?.todayCost, current.currency), balance: balance === null ? '' : `,${tr('余额 {value}', { value: balance })}` })
1066
1117
  }
1067
1118
  const hoverTitle = tr('{name} · {action} Token 看板', { name: current?.name ?? '', action: open ? tr('收起') : tr('展开') })
1068
1119
 
@@ -1227,7 +1278,7 @@ window.__ModuleLoader__.load({
1227
1278
  return h(React.Fragment, null,
1228
1279
  h('div', { style: styles.providerLine },
1229
1280
  h('span', { style: styles.title, title: provider.name }, provider.name),
1230
- h('span', { style: styles.providerChip }, `[ ${tr('按量 API')} ]`)),
1281
+ h('span', { style: styles.providerChip }, `[ ${tr('API 用量')} ]`)),
1231
1282
  h('div', { 'data-testid': 'token-dash-summary-row', style: styles.summaryRow },
1232
1283
  h('span', { style: styles.summaryCell },
1233
1284
  h(InlineRing, {
@@ -1502,7 +1553,7 @@ window.__ModuleLoader__.load({
1502
1553
  updateControl)))
1503
1554
  }
1504
1555
 
1505
- /** P3 按量卡:每 provider 一张,竖排 Gauge + 常显预算输入 + 三行字段。 */
1556
+ /** P3 API 用量卡:每 provider 一张,竖排 Gauge + 常显预算输入 + 三行字段。 */
1506
1557
  function BudgetTable({ providers, prefs, onSave }) {
1507
1558
  const [errors, setErrors] = useState({})
1508
1559
  const [saving, setSaving] = useState(null)
@@ -1540,6 +1591,9 @@ window.__ModuleLoader__.load({
1540
1591
  const used = Number(budget?.used ?? 0)
1541
1592
  const plan = hasBudget ? Number(budget.amount) - used : null
1542
1593
  const balance = balanceText(provider, true)
1594
+ // Ollama 这类「额度 + 购买余额」的 provider:进度只用 allowance / used,单值位不重复
1595
+ const allowance = Number(provider.balance?.allowance)
1596
+ const purchased = Number(provider.balance?.purchased)
1543
1597
  const entry = prefs?.budgets?.[provider.id]
1544
1598
  const initial = entry === undefined ? '' : (entry.amount > 0 ? entry.amount.toFixed(2) : '')
1545
1599
  const error = errors[provider.id]
@@ -1550,7 +1604,7 @@ window.__ModuleLoader__.load({
1550
1604
  },
1551
1605
  h('div', { style: styles.apiCardHead },
1552
1606
  h('span', { style: styles.apiCardName, title: provider.name }, provider.name),
1553
- h('span', { style: styles.apiChip }, `[ ${tr('按量 API')} ]`)),
1607
+ h('span', { style: styles.apiChip }, `[ ${tr('API 用量')} ]`)),
1554
1608
  h('div', { style: styles.apiGaugeWrap },
1555
1609
  h(QuotaGauge, {
1556
1610
  label: tr('已用'), percent,
@@ -1595,12 +1649,37 @@ window.__ModuleLoader__.load({
1595
1649
  h('div', { style: styles.kvRow },
1596
1650
  h('span', { style: styles.kvLabel }, tr('真实余额')),
1597
1651
  h('span', { 'data-testid': `token-dash-budget-balance-${provider.id}`, style: styles.kvValue }, balance ?? '—')),
1652
+ Number.isFinite(allowance) && allowance > 0
1653
+ ? h('div', { style: styles.kvRow },
1654
+ h('span', { style: styles.kvLabel }, tr('套餐已用')),
1655
+ h('span', {
1656
+ 'data-testid': `token-dash-budget-allowance-${provider.id}`,
1657
+ style: styles.kvValue,
1658
+ }, `${fmtMoney(provider.balance?.used, provider.currency)} / ${fmtMoney(allowance, provider.currency)}`))
1659
+ : null,
1660
+ Number.isFinite(purchased) && purchased > 0
1661
+ ? h('div', { style: styles.kvRow },
1662
+ h('span', { style: styles.kvLabel }, tr('购买余额')),
1663
+ h('span', {
1664
+ 'data-testid': `token-dash-budget-purchased-${provider.id}`,
1665
+ style: styles.kvValue,
1666
+ }, fmtMoney(purchased, provider.currency)))
1667
+ : null,
1598
1668
  h('div', { style: styles.kvRow },
1599
1669
  h('span', { style: styles.kvLabel }, tr('本月已花')),
1600
- h('span', { 'data-testid': `token-dash-budget-month-${provider.id}`, style: styles.kvValue },
1601
- fmtMoney(provider.usage?.monthCost, provider.currency))),
1602
- h('div', { style: styles.cardCaption },
1603
- `${hasBudget ? stateOf(percent, API_CRITICAL) : 'unset'} · ${hasBudget ? fmtRatio(budget.percent) : '—'}`))
1670
+ h('span', {
1671
+ 'data-testid': `token-dash-budget-month-${provider.id}`,
1672
+ style: { ...styles.kvValue, display: 'inline-flex', alignItems: 'baseline', gap: 4 },
1673
+ },
1674
+ fmtMoney(provider.usage?.monthCost, provider.currency),
1675
+ provider.currencySource === 'community' && provider.currency === 'CNY'
1676
+ ? h('span', {
1677
+ 'data-testid': `token-dash-currency-source-${provider.id}`,
1678
+ title: tr('价格取社区价目表(人民币),与渠道账单可能有差异'),
1679
+ style: { fontSize: 10, color: T.weak },
1680
+ }, tr('按社区表 CNY'))
1681
+ : null)),
1682
+ h('div', { style: styles.cardCaption }, apiCardCaption(provider, { hasBudget, percent, budget })))
1604
1683
  }))
1605
1684
  }
1606
1685
 
@@ -1730,7 +1809,8 @@ window.__ModuleLoader__.load({
1730
1809
  }, [loadSummary, loadPrefs, loadUsage])
1731
1810
 
1732
1811
  useEffect(() => { void refresh() }, [refresh])
1733
- usePolling(() => { void loadSummary() }, { refreshMs: Number(summary?.refreshMs) || 60000 })
1812
+ // 看板常驻,轮询周期取 min(10s, refreshMs);费用与明细来自 /usage,必须一起刷
1813
+ usePolling(() => { void loadSummary(); void loadUsage() }, { refreshMs: Math.min(10_000, Number(summary?.refreshMs) || 60000) })
1734
1814
 
1735
1815
  const savePrefs = useCallback(async (patch) => {
1736
1816
  if (prefsRef.current === null) return { ok: false, reason: 'not-ready' }
@@ -1781,7 +1861,7 @@ window.__ModuleLoader__.load({
1781
1861
  h('span', null, tr('刷新失败,保留上次数据')),
1782
1862
  h('button', { type: 'button', style: styles.button, onClick: () => { void refresh() } }, tr('重试'))) : null,
1783
1863
  api.length > 0 ? h('section', { style: styles.boardSection },
1784
- h('div', { style: styles.boardSectionHead }, h('b', { style: styles.sectionTitle }, tr('按量计价(按供应商)'))),
1864
+ h('div', { style: styles.boardSectionHead }, h('b', { style: styles.sectionTitle }, tr('API 用量(按供应商)'))),
1785
1865
  h(BudgetTable, { providers: api, prefs, onSave: savePrefs })) : null,
1786
1866
  subscriptions.length > 0 ? h('section', { style: styles.boardSection },
1787
1867
  h('div', { style: styles.boardSectionHead },
@@ -1798,8 +1878,8 @@ window.__ModuleLoader__.load({
1798
1878
  h('div', { style: styles.boardSectionHead }, h('b', { style: styles.sectionTitle }, tr('范围与明细'))),
1799
1879
  h('div', { style: styles.rangeBox },
1800
1880
  h('div', { style: styles.rangeHead },
1801
- h('div', { style: { width: 300, maxWidth: '100%', flex: '0 0 300px', minWidth: 0 } }, h(Segmented, {
1802
- value: range, onChange: setRange, label: tr('时间范围'),
1881
+ h('div', { style: { width: 'max-content', maxWidth: '100%', flex: '0 0 auto', minWidth: 0 } }, h(Segmented, {
1882
+ value: range, onChange: setRange, label: tr('时间范围'), fit: true,
1803
1883
  options: RANGES.map(([value, label]) => ({ value, label: tr(label) })),
1804
1884
  })),
1805
1885
  h('span', { style: styles.rangeMeta },