dsh-token-dash 2.1.0 → 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
@@ -30,24 +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
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) |
44
- | Ollama Cloud | API usage | `OLLAMA_API_KEY` | Plan + purchased credits (USD), plan usage, 30-day channel usage |
33
+ ## Supported API scope
34
+
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 |
45
48
 
46
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.
47
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.
48
51
  - Keys are detected automatically; GLM / Kimi / OpenCode Go / Command Code can be re-detected from the dashboard footer.
49
52
  - Subscription models count toward Tokens but not cost; billing mode is pinned per key instead of following quota flakiness.
50
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.
51
55
 
52
56
  ## Interface
53
57
 
@@ -80,7 +84,7 @@ Screenshots use mock data so the full layout is visible at once.
80
84
  - Subscription windows use three slots: first left, second center, third right; two windows occupy the first two slots.
81
85
  - Model column is capped at 150; Tokens / requests / hit rate are right-aligned.
82
86
 
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.
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.
84
88
 
85
89
  <p align="center">
86
90
  <img src="https://raw.githubusercontent.com/spartawhy117/dsh-token-dash/main/docs/pic/en/settings.png" alt="Full dashboard" />
@@ -117,7 +121,7 @@ Update: run `update` with the same name, or use the `⤓` button on the right of
117
121
  - The UI currently ships Chinese / English only. Other DSH languages (Japanese, German, Russian, etc.) fall back to English.
118
122
  - After a DSH upgrade the plugin may disappear from the profile; reinstall the same tarball — the ledger is not deleted.
119
123
  - 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.
124
+ - A USD-billed provider that only matches the CNY price table shows "Unpriced" with a reason instead of rendering CNY numbers as USD.
121
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.
122
126
  - Upstream APIs are rate-limited; successful results are cached for 60s, failures for 10s, and concurrent requests are coalesced.
123
127
 
package/README.md CHANGED
@@ -30,24 +30,28 @@
30
30
 
31
31
  **三个入口,一份数据**:输入框底栏右侧 Pill 看当前模型;浮层看预算、余额与用量表;整页看 8 家供应商的全量卡片与模型明细。所有页面共用同一份本地账本,不重复计算。
32
32
 
33
- ## 支持矩阵
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) |
44
- | Ollama Cloud | API 用量 | `OLLAMA_API_KEY` | 套餐剩余 + 购买余额(USD)、套餐已用、渠道 30 天用量 |
33
+ ## 支持的 API 范围
34
+
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 用量 | 只按模型名计价;未定价可补算 |
45
48
 
46
49
  - 在 DSH 的凭据设置中按上表名称保存 Key;插件只通过宿主 `credentials` 读取,不读环境变量或本机登录文件。
47
50
  - Ollama 在 DSH 里需要用「自定义 OpenAI 兼容供应商」接入:route id 必须填 `ollama`(凭据按 `<ROUTE>_API_KEY` 派生成 `OLLAMA_API_KEY`),自定义名填别的会取不到 Key,余额卡也不会出现。
48
51
  - 填 Key 后自动探测;GLM / Kimi / OpenCode Go / Command Code 可在「全量看板」底部重新检测订阅。
49
52
  - 订阅模型计入 Tokens,但不计费用;计费形态按 Key 固化,不随配额接口抖动。
50
53
  - 余额、配额、用量分开展示;余额失败不会把当天的 Token 记账清零。
54
+ - **不覆盖**:不读 Cookie、不抓供应商控制台页面、不读宿主配置文件或本机登录态;余额只查官方接口,不经第三方中转;价格来自社区价目表与 OpenRouter 公开价,不来自供应商账单,金额均为本地估算。
51
55
 
52
56
  ## 界面
53
57
 
@@ -80,7 +84,7 @@
80
84
  - 订阅窗口固定三槽位:第 1 窗左、第 2 窗中、第 3 窗右;只有两窗时占前两个槽位。
81
85
  - 模型列上限 150,Tokens / 请求 / 命中右对齐;长模型名用省略号,悬浮可看全名。
82
86
 
83
- **P3 · 整页看板**:8 家供应商卡片、摘要带、8 列模型明细、底部设置胶囊;页面自己滚动,滚动条贴窗口右缘。
87
+ **P3 · 整页看板**:8 家供应商卡片、四格摘要带(总费用 / 真实 Tokens / 总请求数 / 缓存命中率)、用量趋势柱、8 列模型明细、底部设置胶囊;页面自己滚动,滚动条贴窗口右缘。
84
88
 
85
89
  <p align="center">
86
90
  <img src="https://raw.githubusercontent.com/spartawhy117/dsh-token-dash/main/docs/pic/settings.png" alt="整页看板" />
@@ -116,7 +120,7 @@ dsh plugin --profile desktop add /path/to/dsh-token-dash-x.y.z.tgz
116
120
  - 界面语言当前仅中文 / English;选择日语、德语、俄语等其他 DSH 语言时,插件文案显示英文回退。
117
121
  - 升级 DSH 后插件可能从 profile 消失,重装同一个 tarball 即可,账本不会被删。
118
122
  - Qwen 只统计用量,余额接口不支持;其余供应商的余额/配额以接口实际返回为准。
119
- - 美元结算的供应商如果只命中人民币价目表,该模型会显示「未定价」并给出原因(不会把人民币数值当成美元);需要更精确的金额时,可在 `prefs.json` 的 `priceOverrides` 里按 `currency: "USD"` 补单价。
123
+ - 美元结算的供应商如果只命中人民币价目表,该模型会显示「未定价」并给出原因,不会把人民币数值当成美元。
120
124
  - Ollama 的余额与用量接口共享 10 次/分钟限流;触发限流时卡片保留上次数值并标「限流中」,恢复后自动更新。
121
125
  - 上游接口有速率限制;成功结果缓存 60s、失败结果缓存 10s,并发请求会合并。
122
126
 
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}',
@@ -117,6 +117,16 @@ window.__ModuleLoader__.load({
117
117
  '周期至 {time}': 'Cycle ends {time}', '限流中': 'Rate limited',
118
118
  '渠道用量 {value}': 'Channel usage {value}',
119
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',
120
130
  }
121
131
  const ZH = Object.fromEntries(Object.keys(EN).map((key) => [key, key]))
122
132
  /** 未定价原因 → 可读文案;未知 reason 回退「未定价」。 */
@@ -499,12 +509,17 @@ window.__ModuleLoader__.load({
499
509
  kvLabel: { color: T.muted, whiteSpace: 'nowrap' },
500
510
  kvValue: { color: T.text, fontWeight: 600, fontVariantNumeric: 'tabular-nums', whiteSpace: 'nowrap' },
501
511
  summaryBand: {
502
- display: 'grid', gridTemplateColumns: '1fr 1fr', border: `1px solid ${T.border}`,
512
+ display: 'grid', gridTemplateColumns: 'repeat(4, minmax(0, 1fr))', border: `1px solid ${T.border}`,
503
513
  borderRadius: 8, overflow: 'hidden',
504
514
  },
505
- 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)` },
506
521
  summaryK: { color: T.muted, fontSize: 12 },
507
- 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' },
508
523
  summarySub: { color: T.weak, fontSize: 11, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', maxWidth: '100%' },
509
524
  rangeBox: {
510
525
  border: `1px solid ${T.border}`, borderRadius: 10, background: T.section,
@@ -513,6 +528,21 @@ window.__ModuleLoader__.load({
513
528
  rangeHead: { display: 'flex', alignItems: 'center', justifyContent: 'flex-start', flexWrap: 'wrap', gap: 16 },
514
529
  rangeMeta: { color: T.weak, fontSize: 11 },
515
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 },
516
546
  quotaCards: { display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(220px, 1fr))', gap: 12 },
517
547
  quotaCard: {
518
548
  border: `1px solid ${T.border}`, borderRadius: 8, background: T.section, padding: 16,
@@ -874,28 +904,171 @@ window.__ModuleLoader__.load({
874
904
  : `${row.approximate === true ? '≈' : ''}${fmtMoney(row.cost, row.currency)}`)))))
875
905
  }
876
906
 
877
- /** P3 两格卡:总费用(多币种同行)与真实 Tokens。 */
878
- function RangeCards({ usage }) {
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)
952
+ }
953
+
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 }) {
879
977
  const pending = usage === null
880
978
  const costEntries = Object.entries(usage?.totals ?? {})
881
979
  const total = usage?.total ?? null
882
980
  const costNodes = costEntries.map(([currency, value]) => h('span', { key: currency }, fmtMoney(value.cost, currency)))
883
- return h('div', { 'data-testid': 'token-dash-range-cards', 'data-td-cards': true, style: styles.summaryBand },
884
- h('div', { 'data-testid': 'token-dash-card-cost', style: styles.summaryHalf },
885
- h('div', { style: styles.summaryK }, tr('总费用')),
886
- h('div', { 'data-testid': 'token-dash-cost-values', style: styles.summaryV },
887
- pending ? '—' : (costNodes.length === 0 ? '—' : costNodes))),
888
- h('div', { 'data-testid': 'token-dash-card-tokens', style: styles.summaryHalf },
889
- h('div', { style: styles.summaryK },
890
- `${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')}`,
891
1005
  h(InfoTip, {
892
1006
  label: tr('Tokens 括号说明'),
893
1007
  text: tr('Tokens 括号顺序:输入 / 缓存(读+写)/ 输出'),
894
1008
  variant: 'inline',
895
1009
  }, h(Icon, { name: 'info', size: 11 }))),
896
- 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)),
897
1011
  h('div', { style: styles.summarySub },
898
- 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))
899
1072
  }
900
1073
 
901
1074
  function MiniBar({ ratio = 0, neutral = false, stretch = false }) {
@@ -1769,6 +1942,7 @@ window.__ModuleLoader__.load({
1769
1942
  const [usage, setUsage] = useState(null)
1770
1943
  const [prefs, setPrefs] = useState(null)
1771
1944
  const [range, setRange] = useState('all')
1945
+ const [metric, setMetric] = useState('tokens')
1772
1946
  const [refreshing, setRefreshing] = useState(false)
1773
1947
  const [error, setError] = useState(false)
1774
1948
  const [usageError, setUsageError] = useState(false)
@@ -1887,7 +2061,8 @@ window.__ModuleLoader__.load({
1887
2061
  usageError ? h('div', { style: styles.errorStrip, role: 'alert' },
1888
2062
  h('span', null, tr('范围数据加载失败')),
1889
2063
  h('button', { type: 'button', style: styles.button, onClick: () => { void loadUsage() } }, tr('重试'))) : null,
1890
- h(RangeCards, { usage }),
2064
+ h(RangeCards, { usage, metric, onMetricChange: setMetric }),
2065
+ h(TrendChart, { series: usage?.series, metric, grain: usage?.grain, onMetricChange: setMetric }),
1891
2066
  h('div', { style: styles.detailWrap }, h(DetailTable, {
1892
2067
  rows: models,
1893
2068
  providerNames: Object.fromEntries(providers.map((provider) => [provider.id, provider.name])),
package/index.js CHANGED
@@ -450,6 +450,9 @@ export function apply(ctx) {
450
450
  billable: usage.models.filter((item) => item.billable === true).length,
451
451
  tokens: usage.total.tokens,
452
452
  currencies: Object.keys(usage.totals).length,
453
+ grain: usage.grain,
454
+ points: usage.series.length,
455
+ seriesCurrencies: Object.keys(usage.series.reduce((acc, point) => Object.assign(acc, point.cost), {})).length,
453
456
  probeMs,
454
457
  durationMs: Date.now() - startedAt,
455
458
  })
package/locale/en.json CHANGED
@@ -118,5 +118,19 @@
118
118
  "周期至 {time}": "Cycle ends {time}",
119
119
  "限流中": "Rate limited",
120
120
  "渠道用量 {value}": "Channel usage {value}",
121
- "价目表为 CNY,该 provider 按 USD 结算;可用 priceOverrides 补 USD 单价": "Price table is CNY while this provider bills in USD; add a USD priceOverrides entry"
121
+ "价目表为 CNY,该 provider 按 USD 结算;可用 priceOverrides 补 USD 单价": "Price table is CNY while this provider bills in USD; add a USD priceOverrides entry",
122
+ "总请求数": "Total requests",
123
+ "缓存命中率": "Cache hit rate",
124
+ "{n} 个币种": "{n} currencies",
125
+ "范围内全部模型": "All models in range",
126
+ "创建 {a} · 命中 {b}": "Created {a} · hit {b}",
127
+ "趋势指标": "Trend metric",
128
+ "使用趋势 · {metric}": "Trend · {metric}",
129
+ "按天": "Daily",
130
+ "按月": "Monthly",
131
+ "与上方卡片同口径": "Same scope as cards above",
132
+ "命中率": "Hit rate",
133
+ "无数据": "No data",
134
+ "多币种下成本柱不可用,请切换其他指标": "Cost bars unavailable with multiple currencies; switch metric",
135
+ "万": "K"
122
136
  }
package/locale/zh.json CHANGED
@@ -118,5 +118,19 @@
118
118
  "周期至 {time}": "周期至 {time}",
119
119
  "限流中": "限流中",
120
120
  "渠道用量 {value}": "渠道用量 {value}",
121
- "价目表为 CNY,该 provider 按 USD 结算;可用 priceOverrides 补 USD 单价": "价目表为 CNY,该 provider 按 USD 结算;可用 priceOverrides 补 USD 单价"
121
+ "价目表为 CNY,该 provider 按 USD 结算;可用 priceOverrides 补 USD 单价": "价目表为 CNY,该 provider 按 USD 结算;可用 priceOverrides 补 USD 单价",
122
+ "总请求数": "总请求数",
123
+ "缓存命中率": "缓存命中率",
124
+ "{n} 个币种": "{n} 个币种",
125
+ "范围内全部模型": "范围内全部模型",
126
+ "创建 {a} · 命中 {b}": "创建 {a} · 命中 {b}",
127
+ "趋势指标": "趋势指标",
128
+ "使用趋势 · {metric}": "使用趋势 · {metric}",
129
+ "按天": "按天",
130
+ "按月": "按月",
131
+ "与上方卡片同口径": "与上方卡片同口径",
132
+ "命中率": "命中率",
133
+ "无数据": "无数据",
134
+ "多币种下成本柱不可用,请切换其他指标": "多币种下成本柱不可用,请切换其他指标",
135
+ "万": "万"
122
136
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-token-dash",
3
- "version": "2.1.0",
3
+ "version": "2.2.0",
4
4
  "description": "DeepSeek Harness Token 看板:月度预算与订阅配额、账户余额、时间范围费用与真实 Tokens 明细,支持本地 JSON 导出 / 导入备份。",
5
5
  "type": "module",
6
6
  "main": "./index.js",
package/src/core.js CHANGED
@@ -79,6 +79,25 @@ function dayStartTs(dayKey) {
79
79
  return new Date(year, month - 1, day).getTime()
80
80
  }
81
81
 
82
+ /**
83
+ * 枚举 [startKey, endKey] 内的全部本地日键(含两端)。
84
+ * 用 setDate 逐日推进而不是加 86400000,跨夏令时切换时日期才不会漂。
85
+ */
86
+ export function eachDayKey(startKey, endKey) {
87
+ const start = dayStartTs(startKey)
88
+ if (start === null || String(endKey) < String(startKey)) return []
89
+ const out = []
90
+ const cursor = new Date(start)
91
+ // 账本不可能超过 100 年;非法 key 时也靠这个上限兜底退出,避免死循环
92
+ for (let guard = 0; guard < 36600; guard += 1) {
93
+ const key = localDayKey(cursor.getTime())
94
+ if (key > endKey) break
95
+ out.push(key)
96
+ cursor.setDate(cursor.getDate() + 1)
97
+ }
98
+ return out
99
+ }
100
+
82
101
  /**
83
102
  * 旧计价模型的成本在入账时写死;定价修复后按日级 token 与当日 00:00 价目重算。
84
103
  * 日级聚合没有单条记录时间,峰谷只能按 00:00(闲时)代表,结果属于估算。
@@ -346,6 +365,54 @@ export function stampProviderKinds(state, snapshots) {
346
365
  return changed
347
366
  }
348
367
 
368
+ /** 日点数超过这个值就切「按月」桶:柱数稳定在 12 上下,避免柱子被压成线。 */
369
+ const MONTHLY_GRAIN_THRESHOLD = 60
370
+
371
+ /**
372
+ * 日序列超过阈值时按月合并:柱数稳定在 12 上下,避免柱子被压成线。
373
+ * 只做加法,口径与日序列完全一致;命中率按当月总量重算,不是日命中率的平均。
374
+ */
375
+ export function buildMonthlySeries(series) {
376
+ if (!Array.isArray(series) || series.length <= MONTHLY_GRAIN_THRESHOLD) return { grain: 'day', series }
377
+ const byMonth = new Map()
378
+ for (const point of series) {
379
+ const month = String(point.dayKey).slice(0, 7)
380
+ let entry = byMonth.get(month)
381
+ if (entry === undefined) {
382
+ entry = {
383
+ dayKey: month,
384
+ cost: {},
385
+ requests: 0,
386
+ input: 0,
387
+ cacheRead: 0,
388
+ cacheWrite: 0,
389
+ output: 0,
390
+ tokens: 0,
391
+ hitRate: null,
392
+ }
393
+ byMonth.set(month, entry)
394
+ }
395
+ entry.requests += point.requests
396
+ entry.input += point.input
397
+ entry.cacheRead += point.cacheRead
398
+ entry.cacheWrite += point.cacheWrite
399
+ entry.output += point.output
400
+ entry.tokens += point.tokens
401
+ for (const [currency, bucket] of Object.entries(point.cost)) {
402
+ const target = (entry.cost[currency] ??= { cost: 0, requests: 0 })
403
+ target.cost += bucket.cost
404
+ target.requests += bucket.requests
405
+ }
406
+ }
407
+ const merged = [...byMonth.values()]
408
+ for (const entry of merged) {
409
+ for (const bucket of Object.values(entry.cost)) bucket.cost = round2(bucket.cost)
410
+ const denominator = entry.input + entry.cacheRead + entry.cacheWrite
411
+ entry.hitRate = denominator > 0 ? entry.cacheRead / denominator : null
412
+ }
413
+ return { grain: 'month', series: merged }
414
+ }
415
+
349
416
  /**
350
417
  * Range-only aggregation for P2. Unlike buildSummary this never adds
351
418
  * "configured but unused" default rows, and it does not touch month budgets.
@@ -371,7 +438,26 @@ export function buildUsage(state, prefs, range, now, providerInfoInput) {
371
438
  }
372
439
  const models = new Map()
373
440
  const totals = {}
374
- const add = (providerId, modelId, row) => {
441
+ // 逐日点:口径与 P3 两格卡一致——cost 只累 billable 行,其余字段累全部行(含订阅)
442
+ const points = new Map()
443
+ const pointOf = (dayKey) => {
444
+ const existing = points.get(dayKey)
445
+ if (existing !== undefined) return existing
446
+ const point = {
447
+ dayKey,
448
+ cost: {},
449
+ requests: 0,
450
+ input: 0,
451
+ cacheRead: 0,
452
+ cacheWrite: 0,
453
+ output: 0,
454
+ tokens: 0,
455
+ hitRate: null,
456
+ }
457
+ points.set(dayKey, point)
458
+ return point
459
+ }
460
+ const add = (providerId, modelId, row, point) => {
375
461
  if (hidden.has(providerId)) return
376
462
  const meta = info.get(providerId)
377
463
  const kind = resolveProviderKind(state, prefs, providerId, meta)
@@ -409,10 +495,23 @@ export function buildUsage(state, prefs, range, now, providerInfoInput) {
409
495
  entry.currency = currency
410
496
  entry.currencySource = currencySourceOf(prefs, providerId, meta)
411
497
  models.set(key, entry)
498
+ const rowTokens = num(row.input) + num(row.cacheRead) + num(row.cacheWrite) + num(row.output)
499
+ point.requests += num(row.requests)
500
+ point.input += num(row.input)
501
+ point.cacheRead += num(row.cacheRead)
502
+ point.cacheWrite += num(row.cacheWrite)
503
+ point.output += num(row.output)
504
+ point.tokens += rowTokens
505
+ if (billable) {
506
+ const bucket = (point.cost[currency] ??= { cost: 0, requests: 0 })
507
+ bucket.cost += num(row.cost)
508
+ bucket.requests += num(row.requests)
509
+ }
412
510
  }
413
511
 
414
512
  for (const dayKey of dayKeys) {
415
513
  if (dayKey < startKey || dayKey > todayKey) continue
514
+ const point = pointOf(dayKey)
416
515
  const bucket = state.days[dayKey]
417
516
  const providers = bucket.providers ?? { unknown: { models: bucket.models ?? {} } }
418
517
  for (const [rawProvider, providerBucket] of Object.entries(providers)) {
@@ -420,12 +519,12 @@ export function buildUsage(state, prefs, range, now, providerInfoInput) {
420
519
  if (providerId === 'unknown') {
421
520
  for (const [rawModel, row] of Object.entries(providerBucket.models ?? {})) {
422
521
  const owner = providerFromModel(rawModel)
423
- if (owner !== null) add(owner, normalizeModel(rawModel), row)
522
+ if (owner !== null) add(owner, normalizeModel(rawModel), row, point)
424
523
  }
425
524
  continue
426
525
  }
427
526
  for (const [rawModel, row] of Object.entries(providerBucket.models ?? {})) {
428
- add(providerId, normalizeModel(rawModel), row)
527
+ add(providerId, normalizeModel(rawModel), row, point)
429
528
  }
430
529
  }
431
530
  }
@@ -491,6 +590,16 @@ export function buildUsage(state, prefs, range, now, providerInfoInput) {
491
590
  ? total.cacheRead / (total.input + total.cacheRead + total.cacheWrite)
492
591
  : null
493
592
 
593
+ // 等距连续:窗口内没有数据的日补零,柱距才不会塌;hitRate 留 null 表示「无数据」而不是 0%
594
+ const daySeries = eachDayKey(startKey, todayKey).map((dayKey) => {
595
+ const point = pointOf(dayKey)
596
+ for (const bucket of Object.values(point.cost)) bucket.cost = round2(bucket.cost)
597
+ const denominator = point.input + point.cacheRead + point.cacheWrite
598
+ point.hitRate = denominator > 0 ? point.cacheRead / denominator : null
599
+ return point
600
+ })
601
+ const { grain, series } = buildMonthlySeries(daySeries)
602
+
494
603
  return {
495
604
  range: selected,
496
605
  startAt: dayStartTs(startKey) ?? now,
@@ -500,6 +609,8 @@ export function buildUsage(state, prefs, range, now, providerInfoInput) {
500
609
  totals,
501
610
  total,
502
611
  models: rows,
612
+ series,
613
+ grain,
503
614
  }
504
615
  }
505
616