@natgurlain/dsh-token-usage 0.0.0-stage → 0.2.1
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/LICENSE +21 -0
- package/README.md +204 -2
- package/cordis.patch.yml +16 -0
- package/icon.svg +17 -0
- package/lib/cli.js +102 -0
- package/lib/client.js +502 -0
- package/lib/index.js +318 -0
- package/lib/openrouter-Ygu9q4uX.js +855 -0
- package/lib/types/cli.d.ts +17 -0
- package/lib/types/index.d.ts +39 -0
- package/lib/types/ledger.d.ts +28 -0
- package/lib/types/openrouter.d.ts +72 -0
- package/lib/types/query.d.ts +41 -0
- package/lib/types/report.d.ts +82 -0
- package/lib/types/scan.d.ts +77 -0
- package/lib/types/snapshot.d.ts +77 -0
- package/package.json +86 -3
- package/src/cli.ts +94 -0
- package/src/client.js +502 -0
- package/src/index.ts +195 -0
- package/src/ledger.ts +98 -0
- package/src/openrouter.ts +165 -0
- package/src/query.ts +97 -0
- package/src/report.ts +244 -0
- package/src/scan.ts +289 -0
- package/src/snapshot.ts +151 -0
package/src/client.js
ADDED
|
@@ -0,0 +1,502 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Browser half of `@natgurlain/dsh-token-usage`: a **Usage** page in Settings.
|
|
3
|
+
*
|
|
4
|
+
* Period chips (today, 7, 30 and 90 days, all time), headline tiles, a
|
|
5
|
+
* stacked daily bar chart (cache read, uncached input, output) with a hover
|
|
6
|
+
* tooltip, and a breakdown table by model, workspace or session. The data
|
|
7
|
+
* comes from `POST api/token-usage.report` (snapshot.ts) on dsh's
|
|
8
|
+
* authenticated `/api` channel, like every other call of this page.
|
|
9
|
+
*
|
|
10
|
+
* Hand-written for dsh's module loader (no build step), like
|
|
11
|
+
* dsh-browser-agent's client: `npm run build` copies it to lib/client.js.
|
|
12
|
+
*/
|
|
13
|
+
window.__ModuleLoader__.load({
|
|
14
|
+
id: '@natgurlain/dsh-token-usage',
|
|
15
|
+
factory: (require) => {
|
|
16
|
+
const module = { exports: {} }
|
|
17
|
+
const React = require('react')
|
|
18
|
+
const h = React.createElement
|
|
19
|
+
const { useCallback, useEffect, useMemo, useRef, useState } = React
|
|
20
|
+
|
|
21
|
+
const API_ROUTE = 'api/token-usage.report'
|
|
22
|
+
const NS = 'token-usage'
|
|
23
|
+
const SECTION_ID = 'token-usage'
|
|
24
|
+
const STYLE_ID = '@natgurlain/dsh-token-usage/UsageSection'
|
|
25
|
+
const REFRESH_MS = 60_000
|
|
26
|
+
const inject = ['slots', 'locale']
|
|
27
|
+
|
|
28
|
+
const dictionaries = {
|
|
29
|
+
en: {
|
|
30
|
+
nav: 'Usage',
|
|
31
|
+
title: 'Token usage',
|
|
32
|
+
subtitle: 'Every DSH session, counted from its logs',
|
|
33
|
+
updated: 'Updated {0}',
|
|
34
|
+
refresh: 'Refresh',
|
|
35
|
+
'period.today': 'Today',
|
|
36
|
+
'period.week': '7 days',
|
|
37
|
+
'period.month': '30 days',
|
|
38
|
+
'period.90': '90 days',
|
|
39
|
+
'period.all': 'All time',
|
|
40
|
+
'tile.total': 'Total tokens',
|
|
41
|
+
'tile.totalSub': '{0} calls · {1} sessions',
|
|
42
|
+
'tile.input': 'Input',
|
|
43
|
+
'tile.inputSub': 'cache write {0}',
|
|
44
|
+
'tile.cache': 'Cache read',
|
|
45
|
+
'tile.cacheSub': '{0} of prompt',
|
|
46
|
+
'tile.output': 'Output',
|
|
47
|
+
'tile.outputSub': 'reasoning {0}',
|
|
48
|
+
'tile.share': '{0} of total',
|
|
49
|
+
'tile.cost': 'Est. cost',
|
|
50
|
+
'tile.costSub': 'from configured prices',
|
|
51
|
+
'tile.costPartial': '{0} calls unpriced',
|
|
52
|
+
'tile.costOpenRouter': '≈ OpenRouter prices',
|
|
53
|
+
'price.openRouter': 'Priced at OpenRouter list prices (fetched {0}): {1}. These are what the same models would cost on OpenRouter, not a bill.',
|
|
54
|
+
'price.via': 'OpenRouter price of {0}',
|
|
55
|
+
'chart.title': 'Tokens per day',
|
|
56
|
+
'chart.empty': 'No model calls in this period.',
|
|
57
|
+
'series.cache': 'Cache read',
|
|
58
|
+
'series.input': 'Input',
|
|
59
|
+
'series.output': 'Output',
|
|
60
|
+
'tip.total': 'Total',
|
|
61
|
+
'tip.calls': 'Calls',
|
|
62
|
+
'tip.none': 'No model calls',
|
|
63
|
+
'tab.models': 'Models',
|
|
64
|
+
'tab.workspaces': 'Workspaces',
|
|
65
|
+
'tab.sessions': 'Sessions',
|
|
66
|
+
'col.name': 'Name',
|
|
67
|
+
'col.share': 'Share',
|
|
68
|
+
'col.total': 'Total',
|
|
69
|
+
'col.input': 'Input',
|
|
70
|
+
'col.cache': 'Cache read',
|
|
71
|
+
'col.output': 'Output',
|
|
72
|
+
'col.calls': 'Calls',
|
|
73
|
+
'col.cost': 'Cost',
|
|
74
|
+
noFolder: '(no folder)',
|
|
75
|
+
loading: 'Reading session logs…',
|
|
76
|
+
failed: 'Usage could not be read. {0}',
|
|
77
|
+
unavailable: 'The token-usage plugin is not running on this host. Restart DSH after installing it.',
|
|
78
|
+
overview: 'Today {0} · 7 days {1} · 30 days {2} · all time {3}',
|
|
79
|
+
footnote: 'Replies, failed or retried calls and compaction, as each provider reported them. Title generation is not logged by DSH. /usage shows the same numbers in a conversation.',
|
|
80
|
+
},
|
|
81
|
+
zh: {
|
|
82
|
+
nav: '用量',
|
|
83
|
+
title: 'Token 用量',
|
|
84
|
+
subtitle: '统计所有 DSH 会话日志',
|
|
85
|
+
updated: '更新于 {0}',
|
|
86
|
+
refresh: '刷新',
|
|
87
|
+
'period.today': '今天',
|
|
88
|
+
'period.week': '7 天',
|
|
89
|
+
'period.month': '30 天',
|
|
90
|
+
'period.90': '90 天',
|
|
91
|
+
'period.all': '全部',
|
|
92
|
+
'tile.total': 'Token 总量',
|
|
93
|
+
'tile.totalSub': '{0} 次调用 · {1} 个会话',
|
|
94
|
+
'tile.input': '输入',
|
|
95
|
+
'tile.inputSub': '缓存写入 {0}',
|
|
96
|
+
'tile.cache': '缓存读取',
|
|
97
|
+
'tile.cacheSub': '占提示 Token 的 {0}',
|
|
98
|
+
'tile.output': '输出',
|
|
99
|
+
'tile.outputSub': '推理 {0}',
|
|
100
|
+
'tile.share': '占全部 Token 的 {0}',
|
|
101
|
+
'tile.cost': '估算费用',
|
|
102
|
+
'tile.costSub': '按配置的价格计算',
|
|
103
|
+
'tile.costPartial': '{0} 次调用无价格',
|
|
104
|
+
'tile.costOpenRouter': '≈ OpenRouter 价格',
|
|
105
|
+
'price.openRouter': '按 OpenRouter 标价估算(获取于 {0}):{1}。这是相同模型在 OpenRouter 上的费用,并非实际账单。',
|
|
106
|
+
'price.via': '{0} 在 OpenRouter 的价格',
|
|
107
|
+
'chart.title': '每日 Token',
|
|
108
|
+
'chart.empty': '这段时间没有模型调用。',
|
|
109
|
+
'series.cache': '缓存读取',
|
|
110
|
+
'series.input': '输入',
|
|
111
|
+
'series.output': '输出',
|
|
112
|
+
'tip.total': '合计',
|
|
113
|
+
'tip.calls': '调用',
|
|
114
|
+
'tip.none': '没有模型调用',
|
|
115
|
+
'tab.models': '模型',
|
|
116
|
+
'tab.workspaces': '工作区',
|
|
117
|
+
'tab.sessions': '会话',
|
|
118
|
+
'col.name': '名称',
|
|
119
|
+
'col.share': '占比',
|
|
120
|
+
'col.total': '合计',
|
|
121
|
+
'col.input': '输入',
|
|
122
|
+
'col.cache': '缓存读取',
|
|
123
|
+
'col.output': '输出',
|
|
124
|
+
'col.calls': '调用',
|
|
125
|
+
'col.cost': '费用',
|
|
126
|
+
noFolder: '(无文件夹)',
|
|
127
|
+
loading: '正在读取会话日志…',
|
|
128
|
+
failed: '无法读取用量。{0}',
|
|
129
|
+
unavailable: '此主机上没有运行 token-usage 插件。安装后请重启 DSH。',
|
|
130
|
+
overview: '今天 {0} · 7 天 {1} · 30 天 {2} · 全部 {3}',
|
|
131
|
+
footnote: '包括回复、失败或重试的调用以及压缩,数值为各服务商报告的用量。DSH 不记录标题生成的用量。在对话中输入 /usage 可查看相同数据。',
|
|
132
|
+
},
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const PERIODS = [
|
|
136
|
+
{ id: 'today', key: 'period.today' },
|
|
137
|
+
{ id: 'week', key: 'period.week' },
|
|
138
|
+
{ id: 'month', key: 'period.month' },
|
|
139
|
+
{ id: '90', key: 'period.90' },
|
|
140
|
+
{ id: 'all', key: 'period.all' },
|
|
141
|
+
]
|
|
142
|
+
// Stacked bottom to top; colours follow the entity (validated light/dark set).
|
|
143
|
+
const SERIES = [
|
|
144
|
+
{ id: 'cache', key: 'series.cache', value: (d) => d.cacheRead },
|
|
145
|
+
{ id: 'input', key: 'series.input', value: (d) => d.input + d.cacheWrite },
|
|
146
|
+
{ id: 'output', key: 'series.output', value: (d) => d.output },
|
|
147
|
+
]
|
|
148
|
+
const TABS = [
|
|
149
|
+
{ id: 'models', key: 'tab.models', rows: (s) => s.models },
|
|
150
|
+
{ id: 'workspaces', key: 'tab.workspaces', rows: (s) => s.workspaces },
|
|
151
|
+
{ id: 'sessions', key: 'tab.sessions', rows: (s) => s.sessionRows },
|
|
152
|
+
]
|
|
153
|
+
|
|
154
|
+
function fill(template, ...values) {
|
|
155
|
+
return values.reduce((text, value, i) => text.replace(`{${i}}`, String(value)), template)
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** A slot may render without a translator: fall back to English. */
|
|
159
|
+
function translator(t) {
|
|
160
|
+
return typeof t === 'function' ? t : (key) => dictionaries.en[key] ?? key
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function compact(n) {
|
|
164
|
+
if (!Number.isFinite(n)) return '–'
|
|
165
|
+
if (n < 1000) return String(Math.round(n))
|
|
166
|
+
const units = [[1e12, 'T'], [1e9, 'B'], [1e6, 'M'], [1e3, 'k']]
|
|
167
|
+
for (const [size, unit] of units) {
|
|
168
|
+
if (n >= size) {
|
|
169
|
+
const v = n / size
|
|
170
|
+
return `${v >= 100 ? v.toFixed(0) : v >= 10 ? v.toFixed(1) : v.toFixed(2)}${unit}`
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
return String(n)
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
function exact(n) {
|
|
177
|
+
return Math.round(n).toLocaleString()
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function usd(n) {
|
|
181
|
+
if (n === undefined) return '–'
|
|
182
|
+
return n >= 100 ? `$${n.toFixed(0)}` : n >= 1 ? `$${n.toFixed(2)}` : `$${n.toFixed(3)}`
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
function percent(part, whole) {
|
|
186
|
+
return whole > 0 ? `${Math.round(part / whole * 100)}%` : '–'
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
function shortDay(day) {
|
|
190
|
+
const date = new Date(`${day}T12:00:00Z`)
|
|
191
|
+
return date.toLocaleDateString(undefined, { month: 'short', day: 'numeric', timeZone: 'UTC' })
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function longDay(day) {
|
|
195
|
+
const date = new Date(`${day}T12:00:00Z`)
|
|
196
|
+
return date.toLocaleDateString(undefined, { weekday: 'short', year: 'numeric', month: 'short', day: 'numeric', timeZone: 'UTC' })
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** A round axis maximum: 1, 2 or 5 times a power of ten. */
|
|
200
|
+
function niceMax(value) {
|
|
201
|
+
if (value <= 0) return 1
|
|
202
|
+
const power = 10 ** Math.floor(Math.log10(value))
|
|
203
|
+
for (const step of [1, 2, 5, 10]) if (step * power >= value) return step * power
|
|
204
|
+
return 10 * power
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
async function requestReport(period) {
|
|
208
|
+
const transport = window.__DSH_TRANSPORT__
|
|
209
|
+
const send = typeof transport?.fetch === 'function' ? transport.fetch : (input, init) => fetch(input, init)
|
|
210
|
+
const response = await send(API_ROUTE, {
|
|
211
|
+
method: 'POST',
|
|
212
|
+
headers: { 'content-type': 'application/json' },
|
|
213
|
+
body: JSON.stringify({ period }),
|
|
214
|
+
signal: AbortSignal.timeout(120_000),
|
|
215
|
+
})
|
|
216
|
+
let body = null
|
|
217
|
+
try { body = await response.json() } catch { /* not JSON: a routing or auth page */ }
|
|
218
|
+
if (response.status === 404) return { unavailable: true }
|
|
219
|
+
if (body === null || body.ok !== true) throw new Error(body?.message ?? body?.error ?? `HTTP ${response.status}`)
|
|
220
|
+
return { snapshot: body }
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
function installStyle() {
|
|
224
|
+
if (typeof document === 'undefined') return () => {}
|
|
225
|
+
if (document.querySelector(`style[data-plugin-css=${JSON.stringify(STYLE_ID)}]`) !== null) return () => {}
|
|
226
|
+
const style = document.createElement('style')
|
|
227
|
+
style.dataset.plugin = '@natgurlain/dsh-token-usage'
|
|
228
|
+
style.dataset.pluginCss = STYLE_ID
|
|
229
|
+
style.textContent = [
|
|
230
|
+
'.dshTU{container-type:inline-size;--tu-cache:#f47230;--tu-input:#257de0;--tu-output:#00b894;--tu-share:#257de0;display:flex;flex-direction:column;gap:16px;padding:8px 0 24px;color:var(--dsw-alias-label-primary);font-size:13px;line-height:20px}',
|
|
231
|
+
'body[data-ds-dark-theme] .dshTU{--tu-cache:#e76624;--tu-input:#338ced;--tu-output:#00a888;--tu-share:#338ced}',
|
|
232
|
+
'.dshTUHead{display:flex;align-items:flex-start;justify-content:space-between;gap:12px;flex-wrap:wrap}',
|
|
233
|
+
'.dshTUTitle{margin:0;font-size:16px;font-weight:600;line-height:24px}',
|
|
234
|
+
'.dshTUSub{margin:0;color:var(--dsw-alias-label-tertiary);font-size:12px;line-height:18px}',
|
|
235
|
+
'.dshTUControls{display:flex;align-items:center;gap:8px;flex-wrap:wrap}',
|
|
236
|
+
'.dshTUChips{display:inline-flex;padding:2px;gap:2px;border-radius:10px;background:var(--dsw-alias-bg-module-platform)}',
|
|
237
|
+
'.dshTUChip{height:28px;padding:0 10px;border:none;border-radius:8px;background:transparent;color:var(--dsw-alias-label-secondary);font:inherit;font-size:12px;cursor:pointer}',
|
|
238
|
+
'.dshTUChip:hover{color:var(--dsw-alias-label-primary)}',
|
|
239
|
+
'.dshTUChip[aria-pressed=true]{background:var(--dsw-alias-bg-base,Canvas);color:var(--dsw-alias-label-primary);box-shadow:0 1px 2px rgba(0,0,0,.12)}',
|
|
240
|
+
'.dshTUButton{height:32px;padding:0 12px;border:none;border-radius:16px;background:var(--dsw-alias-bg-module-platform);color:var(--dsw-alias-label-primary);font:inherit;font-size:12px;cursor:pointer}',
|
|
241
|
+
'.dshTUButton:hover{background:var(--dsw-alias-interactive-bg-hover)}',
|
|
242
|
+
'.dshTUButton:disabled{cursor:default;opacity:.6}',
|
|
243
|
+
'.dshTUTiles{display:grid;grid-template-columns:repeat(auto-fit,minmax(92px,1fr));gap:8px}',
|
|
244
|
+
'.dshTUTile{padding:10px 12px}',
|
|
245
|
+
'@container (max-width:680px){.dshTUTiles{grid-template-columns:repeat(6,1fr)}.dshTUTiles>*{grid-column:span 3}.dshTUTiles[data-count="5"]>:nth-child(-n+3){grid-column:span 2}}',
|
|
246
|
+
'@container (max-width:400px){.dshTUTiles>*,.dshTUTiles[data-count="5"]>:nth-child(-n+3){grid-column:span 3}.dshTUTiles>:first-child{grid-column:1/-1}}',
|
|
247
|
+
'.dshTUCard{padding:12px 16px;border:.5px solid var(--dsw-alias-settings-card-stroke,var(--dsw-alias-border-l2));border-radius:var(--dsw-radius-xl,14px);background:var(--dsw-alias-settings-card-fill,transparent);min-width:0}',
|
|
248
|
+
'.dshTUTileLabel{display:flex;white-space:nowrap;overflow:hidden;align-items:center;gap:6px;color:var(--dsw-alias-label-tertiary);font-size:12px;line-height:18px}',
|
|
249
|
+
'.dshTUSwatch{flex:none;width:8px;height:8px;border-radius:2px}',
|
|
250
|
+
'.dshTUTileValue{margin-top:2px;font-size:20px;white-space:nowrap;font-weight:600;line-height:30px;font-variant-numeric:tabular-nums}',
|
|
251
|
+
'.dshTUTileSub{color:var(--dsw-alias-label-tertiary);font-size:12px;line-height:16px;overflow-wrap:anywhere}',
|
|
252
|
+
'.dshTUCardHead{display:flex;align-items:center;justify-content:space-between;gap:12px;flex-wrap:wrap;margin-bottom:12px}',
|
|
253
|
+
'.dshTUCardTitle{margin:0;font-size:14px;font-weight:600;line-height:22px}',
|
|
254
|
+
'.dshTULegend{display:flex;gap:14px;flex-wrap:wrap;color:var(--dsw-alias-label-secondary);font-size:12px}',
|
|
255
|
+
'.dshTULegendItem{display:inline-flex;align-items:center;gap:6px}',
|
|
256
|
+
'.dshTUPlot{--tu-axis:44px;position:relative;display:grid;grid-template-columns:36px 1fr;gap:0 8px}',
|
|
257
|
+
'.dshTUAxis{position:relative;height:180px;width:36px;color:var(--dsw-alias-label-tertiary);font-size:11px;font-variant-numeric:tabular-nums;text-align:right}',
|
|
258
|
+
'.dshTUAxis span{position:absolute;right:0;transform:translateY(50%)}',
|
|
259
|
+
'.dshTUBars{position:relative;display:flex;align-items:flex-end;gap:2px;height:180px;border-bottom:1px solid var(--dsw-alias-border-l2)}',
|
|
260
|
+
'.dshTUGrid{position:absolute;left:0;right:0;border-top:1px dashed var(--dsw-alias-border-l1,var(--dsw-alias-border-l2));pointer-events:none}',
|
|
261
|
+
'.dshTUBar{position:relative;flex:1 1 0;min-width:0;height:100%;display:flex;flex-direction:column-reverse;align-items:center;justify-content:flex-start;cursor:default}',
|
|
262
|
+
'.dshTUBar:hover,.dshTUBar[data-active=true]{background:var(--dsw-alias-interactive-bg-hover);border-radius:4px 4px 0 0}',
|
|
263
|
+
'.dshTUBar[data-empty=true]:hover,.dshTUBar[data-empty=true][data-active=true]{background:none;box-shadow:inset 0 -2px 0 var(--dsw-alias-label-tertiary)}',
|
|
264
|
+
'.dshTUStack{display:flex;flex-direction:column-reverse;gap:2px;width:100%;max-width:40px}',
|
|
265
|
+
'.dshTUBar[data-out=true] .dshTUStack{opacity:.35}',
|
|
266
|
+
'.dshTUSeg{width:100%;min-height:0}',
|
|
267
|
+
'.dshTUSeg:last-child{border-radius:4px 4px 0 0}',
|
|
268
|
+
'.dshTUX{grid-column:2;display:flex;justify-content:space-between;margin-top:4px;color:var(--dsw-alias-label-tertiary);font-size:11px}',
|
|
269
|
+
'.dshTUTip{position:absolute;z-index:3;top:0;min-width:150px;padding:8px 10px;border:1px solid var(--dsw-alias-border-l2);border-radius:10px;background:var(--dsw-alias-bg-base,Canvas);box-shadow:0 6px 20px rgba(0,0,0,.16);font-size:12px;line-height:18px;pointer-events:none}',
|
|
270
|
+
'.dshTUTipHead{margin-bottom:4px;font-weight:600}',
|
|
271
|
+
'.dshTUTipRow{display:flex;align-items:center;justify-content:space-between;gap:12px;font-variant-numeric:tabular-nums}',
|
|
272
|
+
'.dshTUTipRow span:first-child{display:inline-flex;align-items:center;gap:6px;color:var(--dsw-alias-label-secondary)}',
|
|
273
|
+
'.dshTUTabs{display:inline-flex;gap:4px}',
|
|
274
|
+
'.dshTUTab{height:28px;padding:0 10px;border:none;border-radius:8px;background:transparent;color:var(--dsw-alias-label-secondary);font:inherit;font-size:12px;cursor:pointer}',
|
|
275
|
+
'.dshTUTab[aria-selected=true]{background:var(--dsw-alias-bg-module-platform);color:var(--dsw-alias-label-primary)}',
|
|
276
|
+
'.dshTUTableWrap{overflow-x:auto}',
|
|
277
|
+
'.dshTUTable{width:100%;border-collapse:collapse;font-size:12px;line-height:18px;font-variant-numeric:tabular-nums}',
|
|
278
|
+
'.dshTUTable th{padding:6px 8px;border-bottom:1px solid var(--dsw-alias-border-l2);color:var(--dsw-alias-label-tertiary);font-weight:400;text-align:right;white-space:nowrap}',
|
|
279
|
+
'.dshTUTable td{padding:6px 8px;border-bottom:1px solid var(--dsw-alias-border-l1,var(--dsw-alias-border-l2));text-align:right;white-space:nowrap}',
|
|
280
|
+
'.dshTUTable th:first-child,.dshTUTable td:first-child{text-align:left;white-space:normal;min-width:150px;max-width:320px;overflow-wrap:break-word}',
|
|
281
|
+
'@container (max-width:640px){.dshTUTable .dshTUWide{display:none}.dshTUShare{min-width:72px}.dshTUTable th,.dshTUTable td{padding:6px 6px}}',
|
|
282
|
+
'.dshTUTable tr:hover td{background:var(--dsw-alias-interactive-bg-hover)}',
|
|
283
|
+
'.dshTUShare{display:flex;align-items:center;gap:6px;min-width:96px}',
|
|
284
|
+
'.dshTUShareTrack{flex:1;height:6px;border-radius:3px;background:var(--dsw-alias-bg-module-platform);overflow:hidden}',
|
|
285
|
+
'.dshTUShareFill{height:100%;border-radius:3px;background:var(--tu-share)}',
|
|
286
|
+
'.dshTUShareText{width:34px;color:var(--dsw-alias-label-tertiary);text-align:right}',
|
|
287
|
+
'.dshTUNote{margin:0;color:var(--dsw-alias-label-tertiary);font-size:12px;line-height:18px}',
|
|
288
|
+
'.dshTUEmpty{padding:24px 0;color:var(--dsw-alias-label-tertiary);text-align:center}',
|
|
289
|
+
'.dshTUError{color:var(--dsw-alias-state-error-primary)}',
|
|
290
|
+
'.dshTUBusy{opacity:.6;transition:opacity .15s}',
|
|
291
|
+
].join('\n')
|
|
292
|
+
document.head.appendChild(style)
|
|
293
|
+
return () => { style.remove() }
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
function Tile({ label, value, sub, swatch, title }) {
|
|
297
|
+
return h('div', { className: 'dshTUCard dshTUTile', title },
|
|
298
|
+
h('div', { className: 'dshTUTileLabel', title: label },
|
|
299
|
+
swatch === undefined ? null : h('span', { className: 'dshTUSwatch', style: { background: swatch }, 'aria-hidden': true }),
|
|
300
|
+
label),
|
|
301
|
+
h('div', { className: 'dshTUTileValue' }, value),
|
|
302
|
+
sub === undefined ? null : h('div', { className: 'dshTUTileSub', title: sub }, sub),
|
|
303
|
+
)
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
function Chart({ snapshot, tr }) {
|
|
307
|
+
const [hover, setHover] = useState({ index: -1, left: 0, width: 0, plot: 0 })
|
|
308
|
+
const active = hover.index
|
|
309
|
+
const setActive = (index, element) => {
|
|
310
|
+
if (index < 0 || element === undefined) { setHover({ index: -1, left: 0, width: 0, plot: 0 }); return }
|
|
311
|
+
setHover({ index, left: element.offsetLeft, width: element.offsetWidth, plot: element.parentElement?.clientWidth ?? 0 })
|
|
312
|
+
}
|
|
313
|
+
const days = snapshot.days
|
|
314
|
+
const max = useMemo(() => niceMax(Math.max(0, ...days.map((d) => SERIES.reduce((sum, s) => sum + s.value(d), 0)))), [days])
|
|
315
|
+
const hasData = days.some((d) => d.total > 0)
|
|
316
|
+
const legend = h('div', { className: 'dshTULegend' }, SERIES.slice().reverse().map((s) =>
|
|
317
|
+
h('span', { key: s.id, className: 'dshTULegendItem' },
|
|
318
|
+
h('span', { className: 'dshTUSwatch', style: { background: `var(--tu-${s.id})` }, 'aria-hidden': true }),
|
|
319
|
+
tr(s.key))))
|
|
320
|
+
const head = h('div', { className: 'dshTUCardHead' }, h('h3', { className: 'dshTUCardTitle' }, tr('chart.title')), legend)
|
|
321
|
+
if (!hasData) return h('div', { className: 'dshTUCard' }, head, h('div', { className: 'dshTUEmpty' }, tr('chart.empty')))
|
|
322
|
+
|
|
323
|
+
const point = active >= 0 ? days[active] : undefined
|
|
324
|
+
// Beside the hovered bar, on whichever side has room; the plot starts after the axis column.
|
|
325
|
+
const TIP = 170
|
|
326
|
+
const right = hover.left + hover.width + 8
|
|
327
|
+
const tipLeft = right + TIP <= hover.plot ? right : Math.max(0, hover.left - TIP - 8)
|
|
328
|
+
const ticks = [0, 0.5, 1]
|
|
329
|
+
return h('div', { className: 'dshTUCard' },
|
|
330
|
+
head,
|
|
331
|
+
h('div', { className: 'dshTUPlot' },
|
|
332
|
+
h('div', { className: 'dshTUAxis', 'aria-hidden': true }, ticks.map((f) => h('span', { key: f, style: { bottom: `${f * 100}%` } }, compact(max * f)))),
|
|
333
|
+
h('div', {
|
|
334
|
+
className: 'dshTUBars',
|
|
335
|
+
role: 'img',
|
|
336
|
+
'aria-label': `${tr('chart.title')}: ${days.map((d) => `${d.day} ${compact(d.total)}`).join(', ')}`,
|
|
337
|
+
onMouseLeave: () => { setActive(-1) },
|
|
338
|
+
onBlur: () => { setActive(-1) },
|
|
339
|
+
},
|
|
340
|
+
[0.5, 1].map((f) => h('div', { key: f, className: 'dshTUGrid', style: { bottom: `${f * 100}%` } })),
|
|
341
|
+
days.map((d, i) => h('div', {
|
|
342
|
+
key: d.day,
|
|
343
|
+
className: 'dshTUBar',
|
|
344
|
+
'data-active': i === active ? 'true' : undefined,
|
|
345
|
+
'data-out': d.inPeriod === false ? 'true' : undefined,
|
|
346
|
+
'data-empty': d.total === 0 ? 'true' : undefined,
|
|
347
|
+
onMouseEnter: (event) => { setActive(i, event.currentTarget) },
|
|
348
|
+
onFocus: (event) => { setActive(i, event.currentTarget) },
|
|
349
|
+
tabIndex: 0,
|
|
350
|
+
'aria-label': `${longDay(d.day)}: ${exact(d.total)}`,
|
|
351
|
+
}, h('div', { className: 'dshTUStack' }, SERIES.filter((s) => s.value(d) > 0).map((s) =>
|
|
352
|
+
h('div', { key: s.id, className: 'dshTUSeg', style: { height: `${s.value(d) / max * 180}px`, background: `var(--tu-${s.id})` } })))))),
|
|
353
|
+
point === undefined ? null : h('div', { className: 'dshTUTip', style: { left: `calc(${tipLeft}px + var(--tu-axis, 44px))` }, role: 'status' },
|
|
354
|
+
h('div', { className: 'dshTUTipHead' }, longDay(point.day)),
|
|
355
|
+
point.total === 0 ? h('div', { className: 'dshTUTipRow' }, h('span', null, tr('tip.none'))) : null,
|
|
356
|
+
point.total === 0 ? null : SERIES.slice().reverse().map((s) => h('div', { key: s.id, className: 'dshTUTipRow' },
|
|
357
|
+
h('span', null, h('span', { className: 'dshTUSwatch', style: { background: `var(--tu-${s.id})` } }), tr(s.key)),
|
|
358
|
+
h('span', null, exact(s.value(point))))),
|
|
359
|
+
point.total === 0 ? null : h('div', { className: 'dshTUTipRow' }, h('span', null, tr('tip.total')), h('strong', null, exact(point.total))),
|
|
360
|
+
point.total === 0 ? null : h('div', { className: 'dshTUTipRow' }, h('span', null, tr('tip.calls')), h('span', null, exact(point.calls))),
|
|
361
|
+
point.total > 0 && snapshot.priced && point.cost !== undefined ? h('div', { className: 'dshTUTipRow' }, h('span', null, tr('col.cost')), h('span', null, usd(point.cost))) : null,
|
|
362
|
+
),
|
|
363
|
+
h('div', { className: 'dshTUX', 'aria-hidden': true },
|
|
364
|
+
h('span', null, shortDay(days[0].day)),
|
|
365
|
+
days.length > 2 ? h('span', null, shortDay(days[Math.floor((days.length - 1) / 2)].day)) : null,
|
|
366
|
+
h('span', null, shortDay(days[days.length - 1].day))),
|
|
367
|
+
),
|
|
368
|
+
)
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
const WIDE = new Set(['col.input', 'col.cache', 'col.output'])
|
|
372
|
+
// Lets long model ids wrap after a slash rather than mid-word.
|
|
373
|
+
const breakable = (text) => String(text).replace(/\//g, '/\u200b')
|
|
374
|
+
|
|
375
|
+
function Breakdown({ snapshot, tr }) {
|
|
376
|
+
const [tab, setTab] = useState('models')
|
|
377
|
+
const current = TABS.find((x) => x.id === tab) ?? TABS[0]
|
|
378
|
+
const rows = current.rows(snapshot)
|
|
379
|
+
const whole = snapshot.totals.total
|
|
380
|
+
const columns = ['col.name', 'col.share', 'col.total', 'col.input', 'col.cache', 'col.output', 'col.calls', ...(snapshot.priced ? ['col.cost'] : [])]
|
|
381
|
+
return h('div', { className: 'dshTUCard' },
|
|
382
|
+
h('div', { className: 'dshTUCardHead' },
|
|
383
|
+
h('div', { className: 'dshTUTabs', role: 'tablist' }, TABS.map((x) => h('button', {
|
|
384
|
+
key: x.id, type: 'button', role: 'tab', className: 'dshTUTab', 'aria-selected': x.id === tab ? 'true' : 'false', onClick: () => { setTab(x.id) },
|
|
385
|
+
}, tr(x.key))))),
|
|
386
|
+
rows.length === 0 ? h('div', { className: 'dshTUEmpty' }, tr('chart.empty')) : h('div', { className: 'dshTUTableWrap' },
|
|
387
|
+
h('table', { className: 'dshTUTable' },
|
|
388
|
+
h('thead', null, h('tr', null, columns.map((c) => h('th', { key: c, scope: 'col', className: WIDE.has(c) ? 'dshTUWide' : undefined }, tr(c))))),
|
|
389
|
+
h('tbody', null, rows.map((row) => h('tr', { key: row.key },
|
|
390
|
+
h('td', { title: `${row.key}\n${tr('col.input')} ${exact(row.input + row.cacheWrite)} · ${tr('col.cache')} ${exact(row.cacheRead)} · ${tr('col.output')} ${exact(row.output)}` }, row.key === '' ? tr('noFolder') : breakable(row.label)),
|
|
391
|
+
h('td', null, h('div', { className: 'dshTUShare' },
|
|
392
|
+
h('div', { className: 'dshTUShareTrack' }, h('div', { className: 'dshTUShareFill', style: { width: whole > 0 ? `${Math.max(1, row.total / whole * 100)}%` : '0%' } })),
|
|
393
|
+
h('span', { className: 'dshTUShareText' }, percent(row.total, whole)))),
|
|
394
|
+
h('td', { title: exact(row.total) }, compact(row.total)),
|
|
395
|
+
h('td', { className: 'dshTUWide', title: exact(row.input + row.cacheWrite) }, compact(row.input + row.cacheWrite)),
|
|
396
|
+
h('td', { className: 'dshTUWide', title: exact(row.cacheRead) }, compact(row.cacheRead)),
|
|
397
|
+
h('td', { className: 'dshTUWide', title: exact(row.output) }, compact(row.output)),
|
|
398
|
+
h('td', null, exact(row.calls)),
|
|
399
|
+
snapshot.priced ? h('td', { title: tab === 'models' && snapshot.priceSources?.[row.key] !== undefined ? fill(tr('price.via'), snapshot.priceSources[row.key]) : undefined },
|
|
400
|
+
row.cost === undefined ? '–' : `${tab === 'models' && snapshot.priceSources?.[row.key] !== undefined ? '≈' : ''}${usd(row.cost)}${row.unpriced > 0 ? '*' : ''}`) : null,
|
|
401
|
+
))))),
|
|
402
|
+
)
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
function UsageSection({ t }) {
|
|
406
|
+
const tr = translator(t)
|
|
407
|
+
const [period, setPeriod] = useState('month')
|
|
408
|
+
const [state, setState] = useState({ snapshot: null, error: null, unavailable: false, busy: true })
|
|
409
|
+
const generation = useRef(0)
|
|
410
|
+
|
|
411
|
+
const load = useCallback(async (which) => {
|
|
412
|
+
const mine = ++generation.current
|
|
413
|
+
setState((s) => ({ ...s, busy: true }))
|
|
414
|
+
try {
|
|
415
|
+
const result = await requestReport(which)
|
|
416
|
+
if (mine !== generation.current) return
|
|
417
|
+
setState({ snapshot: result.snapshot ?? null, error: null, unavailable: result.unavailable === true, busy: false })
|
|
418
|
+
} catch (error) {
|
|
419
|
+
if (mine !== generation.current) return
|
|
420
|
+
setState((s) => ({ ...s, error: error instanceof Error ? error.message : String(error), busy: false }))
|
|
421
|
+
}
|
|
422
|
+
}, [])
|
|
423
|
+
|
|
424
|
+
useEffect(() => {
|
|
425
|
+
void load(period)
|
|
426
|
+
const timer = setInterval(() => { if (document.visibilityState === 'visible') void load(period) }, REFRESH_MS)
|
|
427
|
+
return () => { clearInterval(timer) }
|
|
428
|
+
}, [period, load])
|
|
429
|
+
|
|
430
|
+
const { snapshot, error, unavailable, busy } = state
|
|
431
|
+
const header = h('div', { className: 'dshTUHead' },
|
|
432
|
+
h('div', null,
|
|
433
|
+
h('h2', { className: 'dshTUTitle' }, tr('title')),
|
|
434
|
+
h('p', { className: 'dshTUSub' }, snapshot === null
|
|
435
|
+
? tr('subtitle')
|
|
436
|
+
: `${tr('subtitle')} · ${fill(tr('updated'), new Date(snapshot.generatedAt).toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit' }))}`)),
|
|
437
|
+
h('div', { className: 'dshTUControls' },
|
|
438
|
+
h('div', { className: 'dshTUChips', role: 'group' }, PERIODS.map((p) => h('button', {
|
|
439
|
+
key: p.id, type: 'button', className: 'dshTUChip', 'aria-pressed': p.id === period ? 'true' : 'false', onClick: () => { setPeriod(p.id) },
|
|
440
|
+
}, tr(p.key)))),
|
|
441
|
+
h('button', { type: 'button', className: 'dshTUButton', disabled: busy, onClick: () => { void load(period) } }, tr('refresh'))),
|
|
442
|
+
)
|
|
443
|
+
|
|
444
|
+
let body
|
|
445
|
+
if (unavailable) body = h('p', { className: 'dshTUNote' }, tr('unavailable'))
|
|
446
|
+
else if (snapshot === null) body = h('p', { className: error === null ? 'dshTUNote' : 'dshTUNote dshTUError', role: 'status' }, error === null ? tr('loading') : fill(tr('failed'), error))
|
|
447
|
+
else {
|
|
448
|
+
const totals = snapshot.totals
|
|
449
|
+
const prompt = totals.input + totals.cacheRead + totals.cacheWrite
|
|
450
|
+
const o = snapshot.overview
|
|
451
|
+
body = h('div', { className: busy ? 'dshTUBusy' : undefined, style: { display: 'flex', flexDirection: 'column', gap: '16px' } },
|
|
452
|
+
error === null ? null : h('p', { className: 'dshTUNote dshTUError', role: 'status' }, fill(tr('failed'), error)),
|
|
453
|
+
h('p', { className: 'dshTUNote' }, fill(tr('overview'), compact(o.today), compact(o.week), compact(o.month), compact(o.all))),
|
|
454
|
+
h('div', { className: 'dshTUTiles', 'data-count': snapshot.priced ? '5' : '4' },
|
|
455
|
+
h(Tile, { label: tr('tile.total'), value: compact(totals.total), title: exact(totals.total), sub: fill(tr('tile.totalSub'), exact(totals.calls), exact(snapshot.sessions)) }),
|
|
456
|
+
h(Tile, { label: tr('tile.input'), swatch: 'var(--tu-input)', value: compact(totals.input), title: exact(totals.input), sub: totals.cacheWrite > 0 ? fill(tr('tile.inputSub'), compact(totals.cacheWrite)) : fill(tr('tile.share'), percent(totals.input, totals.total)) }),
|
|
457
|
+
h(Tile, { label: tr('tile.cache'), swatch: 'var(--tu-cache)', value: compact(totals.cacheRead), title: exact(totals.cacheRead), sub: fill(tr('tile.cacheSub'), percent(totals.cacheRead, prompt)) }),
|
|
458
|
+
h(Tile, { label: tr('tile.output'), swatch: 'var(--tu-output)', value: compact(totals.output), title: exact(totals.output), sub: totals.reasoning > 0 ? fill(tr('tile.outputSub'), compact(totals.reasoning)) : fill(tr('tile.share'), percent(totals.output, totals.total)) }),
|
|
459
|
+
snapshot.priced ? h(Tile, { label: tr('tile.cost'), value: usd(totals.cost), sub: totals.unpriced > 0 ? fill(tr('tile.costPartial'), exact(totals.unpriced)) : Object.keys(snapshot.priceSources ?? {}).length > 0 ? tr('tile.costOpenRouter') : tr('tile.costSub') }) : null,
|
|
460
|
+
),
|
|
461
|
+
h(Chart, { snapshot, tr }),
|
|
462
|
+
h(Breakdown, { snapshot, tr }),
|
|
463
|
+
Object.keys(snapshot.priceSources ?? {}).length === 0 ? null : h('p', { className: 'dshTUNote' }, fill(tr('price.openRouter'),
|
|
464
|
+
snapshot.pricesAsOf === undefined ? '–' : new Date(snapshot.pricesAsOf).toLocaleDateString(),
|
|
465
|
+
Object.entries(snapshot.priceSources).map(([route, id]) => `${route} → ${id}`).join(', '))),
|
|
466
|
+
h('p', { className: 'dshTUNote' }, tr('footnote')),
|
|
467
|
+
)
|
|
468
|
+
}
|
|
469
|
+
return h('section', { className: 'dshTU', 'aria-label': tr('title') }, header, body)
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
function UsageIcon({ size }) {
|
|
473
|
+
const s = typeof size === 'number' ? size : 16
|
|
474
|
+
return h('svg', { width: s, height: s, viewBox: '0 0 16 16', fill: 'none', 'aria-hidden': true },
|
|
475
|
+
h('path', { d: 'M2.5 13.5h11', stroke: 'currentColor', strokeWidth: 1.3, strokeLinecap: 'round' }),
|
|
476
|
+
h('rect', { x: 3, y: 8, width: 2.2, height: 4, rx: 0.8, fill: 'currentColor' }),
|
|
477
|
+
h('rect', { x: 6.9, y: 4.5, width: 2.2, height: 7.5, rx: 0.8, fill: 'currentColor' }),
|
|
478
|
+
h('rect', { x: 10.8, y: 6.5, width: 2.2, height: 5.5, rx: 0.8, fill: 'currentColor' }))
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
function apply(ctx) {
|
|
482
|
+
ctx.effect(() => installStyle(), 'token-usage: page styles')
|
|
483
|
+
ctx.effect(() => ctx.locale.register(NS, dictionaries), 'token-usage: dictionaries')
|
|
484
|
+
const t = ctx.locale.bind(NS)
|
|
485
|
+
ctx.slots.inject('settings.section', () => ctx.slots.register({
|
|
486
|
+
name: 'settings.section',
|
|
487
|
+
id: SECTION_ID,
|
|
488
|
+
order: 60,
|
|
489
|
+
label: () => t('nav'),
|
|
490
|
+
locale: NS,
|
|
491
|
+
}, UsageSection))
|
|
492
|
+
ctx.slots.inject('settings.section.icon', () => ctx.slots.register({
|
|
493
|
+
name: 'settings.section.icon',
|
|
494
|
+
id: SECTION_ID,
|
|
495
|
+
}, UsageIcon))
|
|
496
|
+
}
|
|
497
|
+
|
|
498
|
+
module.exports.apply = apply
|
|
499
|
+
module.exports.inject = inject
|
|
500
|
+
return module.exports
|
|
501
|
+
},
|
|
502
|
+
})
|