Repository navigation
Expand file tree
/
Copy pathplugin.js
More file actions
385 lines (381 loc) · 27.6 KB
/
Copy pathplugin.js
File metadata and controls
385 lines (381 loc) · 27.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
// Standalone, uncompiled Hermes Desktop plugin. No gateway or provider requests.
import * as sdk from '@hermes/plugin-sdk'
import { useState } from 'react'
import { jsx } from 'react/jsx-runtime'
const ID = 'token-usage'
const ROUTE = '/token-usage'
// Installer replaces this JSON-string placeholder with a local configuration object.
const CONFIG = '__HERMES_TOKEN_USAGE_CONFIG__'
const SUMMARY = CONFIG.summaryPath
const FIELDS = ['total','input_tokens','output_tokens','cache_read_tokens','cache_write_tokens','reasoning_tokens','api_call_count']
const HEADERS = ['Effective total','Input (uncached)','Output','Cache read','Cache write','Reasoning (output subset)','Calls']
const compact = n => Number(n || 0) >= 1e6 ? (Number(n)/1e6).toFixed(2).replace(/\.?0+$/, '')+'M' : Number(n || 0) >= 1e3 ? (Number(n)/1e3).toFixed(1).replace(/\.?0+$/, '')+'K' : fmt(n)
const fmt = n => Number(n || 0).toLocaleString('en-US')
const when = (n, timezone = 'UTC') => n ? new Date(n * 1000).toLocaleString('en-GB', { timeZone: timezone }) + ' ' + timezone : 'unavailable'
const button = { border: '1px solid var(--ui-stroke-secondary)', borderRadius: 5, padding: '4px 8px', color: 'var(--ui-text-secondary)', background: 'transparent', cursor: 'pointer' }
const muted = { color: 'var(--ui-text-tertiary)', fontSize: 12 }
const routeKey = r => r.identity || r.billing_provider
const routeLabel = r => r.provider_label || r.billing_provider
const routeDetails = r => `Raw ID: ${r.billing_provider} · ${r.endpoint || 'endpoint unavailable'} · route ${r.route_hint || 'unavailable'}${r.model ? ' · model ' + r.model : ''}${r.billing_mode ? ' · mode ' + r.billing_mode : ''}${r.task ? ' · task ' + r.task : ''} · ${r.attribution || 'stored provider ID'}${r.provider_candidates?.length ? ' · Candidates (not assigned): ' + r.provider_candidates.join(', ') : ''}`
// Pure display derivation. Never mutate route evidence or infer identities from labels.
function aggregateUsage(rows, profileFilter = '') {
const profiles = new Map(), models = new Map()
let total = 0, missingModelTotal = 0
const add = (target, row) => { for (const field of FIELDS) target[field] = (target[field] || 0) + (row[field] || 0) }
for (const r of rows) {
if ((profileFilter && r.profile !== profileFilter) || !r.total) continue
total += r.total
const unidentified = r.legacy_unidentified || r.attribution === 'legacy unidentified' || ['Unknown','unknown',''].includes(r.billing_provider) && !['unique exact endpoint','ambiguous endpoint','unmatched endpoint'].includes(r.attribution)
// Old summaries without provider_identity fail closed: keep each route distinct.
const key = r.provider_identity || r.identity || JSON.stringify([r.billing_provider, r.endpoint, r.model, r.billing_mode, r.task])
if (!profiles.has(r.profile)) profiles.set(r.profile, {profile:r.profile,total:0,providers:new Map()})
const p = profiles.get(r.profile)
p.total += r.total
if (!p.providers.has(key)) p.providers.set(key, {key,label:unidentified ? 'Unattributed' : ['ambiguous endpoint','unmatched endpoint'].includes(r.attribution) ? `${r.endpoint || 'Unknown endpoint'} · ${key.slice(0,10)}` : routeLabel(r),unidentified,routes:[]})
const provider = p.providers.get(key)
add(provider,r); provider.routes.push(r)
if (!r.model || r.legacy_unidentified) { missingModelTotal += r.total; continue }
if (!models.has(r.model)) models.set(r.model, {model:r.model,routes:[]})
const model = models.get(r.model)
add(model,r); model.routes.push(r)
}
const descending = (a,b) => b.total-a.total || String(a.key || a.model || a.profile).localeCompare(String(b.key || b.model || b.profile))
return {total,missingModelTotal,profiles:[...profiles.values()].map(p=>({...p,providers:[...p.providers.values()].sort(descending)})).sort(descending),models:[...models.values()].sort(descending)}
}
async function readSummary() {
if (typeof CONFIG !== 'object' || typeof SUMMARY !== 'string') throw new Error('Run the installer to configure this plugin.')
const bridge = window.hermesDesktop
if (!bridge || typeof bridge.readFileText !== 'function') throw new Error('Local Desktop readFileText bridge unavailable. This plugin only reads this Mac; no remote gateway fallback.')
const result = await bridge.readFileText(SUMMARY)
if (result?.error || result?.truncated || result?.binary || typeof result?.text !== 'string') throw new Error('Local collector summary missing or unreadable; check collector installation.')
const data = JSON.parse(result.text)
const invalid = () => { throw new Error('Unsupported or malformed token ledger summary schema') }
const object = v => v !== null && typeof v === 'object' && !Array.isArray(v)
const count = v => Number.isSafeInteger(v) && v >= 0
if (!object(data) || data.schema_version !== 1 || !object(data.periods) || !object(data.sources) || !Number.isFinite(data.generated_at) || !count(data.anomaly_count) || !Array.isArray(data.limitations) || data.limitations.some(s => typeof s !== 'string')) invalid()
if (typeof data.timezone !== 'string') invalid()
try { new Intl.DateTimeFormat('en', { timeZone: data.timezone }) } catch { invalid() }
const hourly = value => {
if (value === undefined) return
if (!Array.isArray(value) || value.length !== 24) invalid()
for (const bucket of value) {
if (!object(bucket) || !Number.isInteger(bucket.hour) || bucket.hour < 0 || bucket.hour > 23 || !count(bucket.total) || !count(bucket.calls) || !Array.isArray(bucket.providers)) invalid()
const identities = new Set()
for (const provider of bucket.providers) {
if (!object(provider) || typeof provider.identity !== 'string' || !provider.identity || typeof provider.label !== 'string' || !provider.label || !count(provider.total) || identities.has(provider.identity)) invalid()
identities.add(provider.identity)
}
if (bucket.providers.reduce((total, provider) => total + provider.total, 0) !== bucket.total) invalid()
}
}
for (const period of ['day', 'week', 'month']) {
const p = data.periods[period]
if (!object(p) || !Number.isFinite(p.start) || !count(p.total) || !count(p.boundary_ambiguous_total)) invalid()
hourly(p.hourly)
for (const rows of [p.groups, p.boundary_ambiguous_groups]) {
if (!Array.isArray(rows)) invalid()
for (const row of rows) if (!object(row) || typeof row.profile !== 'string' || typeof row.billing_provider !== 'string' || FIELDS.some(k => !count(row[k]))) invalid()
}
}
if (data.days !== undefined) {
if (!object(data.days)) invalid()
for (const [key, day] of Object.entries(data.days)) {
if (!/^\d{4}-\d{2}-\d{2}$/.test(key) || !object(day) || !Number.isFinite(day.start) || !count(day.total) || !count(day.boundary_ambiguous_total)) invalid()
hourly(day.hourly)
for (const rows of [day.groups, day.boundary_ambiguous_groups]) {
if (!Array.isArray(rows)) invalid()
for (const row of rows) if (!object(row) || typeof row.profile !== 'string' || typeof row.billing_provider !== 'string' || FIELDS.some(k => !count(row[k]))) invalid()
}
}
}
for (const source of Object.values(data.sources)) if (!object(source) || typeof source.ok !== 'boolean' || (source.providers !== undefined && (!Array.isArray(source.providers) || source.providers.some(p => typeof p !== 'string')))) invalid()
return data
}
function useSummary() {
return sdk.useQuery({ queryKey: [ID, 'local-summary'], queryFn: readSummary, refetchInterval: 30_000, refetchIntervalInBackground: true, staleTime: 10_000, retry: false })
}
function status(data) {
if (!data) return 'loading'
if (Date.now()/1000 - data.generated_at > 95) return 'STALE'
if (Object.values(data.sources).some(s => !s.ok)) return 'PARTIAL'
return 'observed'
}
function Chip() {
const q = useSummary()
const d = q.data
return jsx('button', {
type: 'button', 'data-token-usage': 'chip',
style: { ...button, border: 'none', fontSize: 11, fontFamily: 'monospace', whiteSpace: 'nowrap', padding: '0 6px', height: '100%' },
title: `Local token ledger · ${status(d)}. ${d ? `Today: ${fmt(d.periods.day.total)} · Week: ${fmt(d.periods.week.total)} · Month: ${fmt(d.periods.month.total)} tokens. ` : ''}D/W/M are ${d?.timezone || CONFIG.timezone || 'UTC'} calendar periods (week starts Monday). * Observed deltas since installation only; historical breakdown unavailable.`,
onClick: () => sdk.host.navigate(ROUTE),
children: q.isError ? 'Tokens ⚠' : !d ? 'Tokens …' : `D* ${compact(d.periods.day.total)} · W* ${compact(d.periods.week.total)} · M* ${compact(d.periods.month.total)}${status(d) === 'observed' ? '' : ' ⚠ ' + status(d)}`
})
}
const cell = { padding: '7px 6px', textAlign: 'right', verticalAlign: 'top', borderBottom: '1px solid var(--ui-stroke-secondary)' }
const percent = (n, total) => total ? (100*n/total).toFixed(1)+'%' : '0.0%'
function Share({ total, denominator }) {
return jsx('div', {style:{minWidth:80},children:[
jsx('span',{children:percent(total,denominator)},'number'),
jsx('div',{style:{height:3,marginTop:4,background:'var(--ui-stroke-secondary)'},children:jsx('div',{style:{height:'100%',width:denominator ? `${Math.min(100,100*total/denominator)}%` : '0%',background:'var(--ui-accent)'}})},'bar')
]})
}
function Metrics({ row }) {
return jsx('div',{style:{...muted,display:'flex',gap:12,flexWrap:'wrap',padding:'8px 0'},children:FIELDS.slice(1).map((field,i)=>jsx('span',{children:`${HEADERS[i+1]}: ${fmt(row[field])}`},field))})
}
function Evidence({ routes }) {
return jsx('div',{style:muted,children:routes.map((r,i)=>jsx('div',{style:{padding:'3px 0',overflowWrap:'anywhere'},children:[
jsx('div',{children:`${r.profile} · ${fmt(r.total)} tokens · ${routeDetails(r)}`},'identity'),
jsx(Metrics,{row:r},'counts')
]},r.profile+':'+routeKey(r)+':'+i))})
}
function CompactTable({ rows, denominator, models = false }) {
const headers = models ? ['Model','Tokens','Share','Calls'] : ['Provider','Tokens','Share']
return jsx('table',{style:{width:'100%',borderCollapse:'collapse',fontSize:12,fontVariantNumeric:'tabular-nums'},children:[
jsx('thead',{children:jsx('tr',{children:headers.map((h,i)=>jsx('th',{style:{...cell,textAlign:i===0?'left':'right',color:'var(--ui-text-tertiary)',fontWeight:500},children:h},h))})},'head'),
jsx('tbody',{children:rows.map(r=>jsx('tr',{'data-model-row':models?'':undefined,'data-provider-row':!models?'':undefined,children:[
jsx('td',{style:{...cell,textAlign:'left',overflowWrap:'anywhere'},children:jsx('details',{children:[
jsx('summary',{style:{cursor:'pointer',fontFamily:'monospace'},children:models?r.model:r.label},'label'),
jsx(Metrics,{row:r},'metrics'),
models ? jsx('div',{style:muted,children:aggregateUsage(r.routes).profiles.map(p=>jsx('div',{style:{padding:'4px 0'},children:[
jsx('strong',{children:`${p.profile} · ${fmt(p.total)} tokens`},'profile'),
...p.providers.map(v=>jsx('div',{children:`${v.label}: ${fmt(v.total)} tokens · ${fmt(v.api_call_count)} calls · ${percent(v.total,r.total)} of model`},v.key))
]},p.profile))},'distribution') : null,
jsx(Evidence,{routes:r.routes},'evidence')
]})},'label'),
jsx('td',{style:{...cell,whiteSpace:'nowrap'},title:fmt(r.total),children:fmt(r.total)},'tokens'),
jsx('td',{style:cell,children:jsx(Share,{total:r.total,denominator})},'share'),
models ? jsx('td',{style:cell,children:fmt(r.api_call_count)},'calls'):null
]},r.key || r.model))},'body')
]})
}
function combineHourly(days) {
const available = days.map(day => day?.hourly).filter(Array.isArray)
if (!available.length) return undefined
const result = Array.from({length:24}, (_, hour) => ({hour,total:0,calls:0,providers:[]}))
for (const hourly of available) for (const bucket of hourly) {
if (bucket.hour >= 0 && bucket.hour < 24) {
const target = result[bucket.hour]
target.total += bucket.total
target.calls += bucket.calls
for (const provider of bucket.providers || []) {
let combined = target.providers.find(item => item.identity === provider.identity)
if (!combined) {
combined = {identity:provider.identity,label:provider.label,total:0}
target.providers.push(combined)
}
combined.total += provider.total
}
target.providers.sort((a,b) => b.total-a.total || a.identity.localeCompare(b.identity))
}
}
for (const bucket of result) if (bucket.providers.reduce((total, provider) => total + provider.total, 0) !== bucket.total) throw new Error('Combined hourly provider totals do not conserve bucket total')
return result
}
const chartTitle = bucket => [
`${String(bucket.hour).padStart(2,'0')}:00 - ${String(bucket.hour).padStart(2,'0')}:59`,
`Total tokens: ${fmt(bucket.total)}`,
`Calls: ${fmt(bucket.calls)}`,
...(bucket.providers || []).slice().sort((a,b) => b.total-a.total || a.identity.localeCompare(b.identity)).map(provider => `${provider.label}: ${fmt(provider.total)} tokens`)
].join('\n')
function getSplinePath(points) {
let d = `M ${points[0].x.toFixed(1)} ${points[0].y.toFixed(1)}`
for (let i = 0; i < points.length - 1; i++) {
const p0 = points[Math.max(0, i - 1)]
const p1 = points[i]
const p2 = points[i + 1]
const p3 = points[Math.min(points.length - 1, i + 2)]
let cp1x = p1.x + (p2.x - p0.x) / 6
let cp1y = p1.y + (p2.y - p0.y) / 6
let cp2x = p2.x - (p3.x - p1.x) / 6
let cp2y = p2.y - (p3.y - p1.y) / 6
if (p1.y === 135 && p2.y === 135) {
cp1y = 135
cp2y = 135
} else {
cp1y = Math.min(135, Math.max(15, cp1y))
cp2y = Math.min(135, Math.max(15, cp2y))
}
d += ` C ${cp1x.toFixed(1)} ${cp1y.toFixed(1)}, ${cp2x.toFixed(1)} ${cp2y.toFixed(1)}, ${p2.x.toFixed(1)} ${p2.y.toFixed(1)}`
}
return d
}
function HourlyChart({ hourly }) {
if (!Array.isArray(hourly) || hourly.length !== 24) return null
const [style, setStyle] = useState('wave')
const peak = hourly.reduce((best, bucket) => bucket.total > best.total ? bucket : best, {hour:0,total:0,calls:0})
const peakLabel = `${String(peak.hour).padStart(2,'0')}:00`
const max = Math.max(1, peak.total)
const chartHeight = 120
const baseline = 135
const plotLeft = 64
const plotRight = 704
const step = (plotRight - plotLeft) / 23
const points = hourly.map(b => ({
x: plotLeft + b.hour * step,
y: baseline - (b.total / max) * chartHeight,
bucket: b
}))
const lineD = getSplinePath(points)
const areaD = `${lineD} L ${points[points.length - 1].x.toFixed(1)} ${baseline} L ${points[0].x.toFixed(1)} ${baseline} Z`
return jsx('details', {'data-hourly-chart':'', open:true, style:{border:'1px solid var(--ui-stroke-secondary)',borderRadius:6,padding:'6px 8px'}, children:[
jsx('summary',{style:{cursor:'pointer',fontSize:12,color:'var(--ui-text-secondary)',display:'flex',alignItems:'center',justifyContent:'space-between',userSelect:'none'},children:[
jsx('span',{children:`24h Activity · Peak: ${fmt(peak.total)} tokens at ${peakLabel}`},'title'),
jsx('div',{style:{display:'flex',gap:4,alignItems:'center'},children:[
jsx('button',{type:'button',style:{...button,padding:'2px 8px',fontSize:11,color:style==='wave'?'var(--ui-accent)':'var(--ui-text-secondary)',borderColor:style==='wave'?'var(--ui-accent)':'var(--ui-stroke-secondary)'},onClick:e=>{e.preventDefault();e.stopPropagation();setStyle('wave')},children:'Wave'},'toggle-wave'),
jsx('button',{type:'button',style:{...button,padding:'2px 8px',fontSize:11,color:style==='bars'?'var(--ui-accent)':'var(--ui-text-secondary)',borderColor:style==='bars'?'var(--ui-accent)':'var(--ui-stroke-secondary)'},onClick:e=>{e.preventDefault();e.stopPropagation();setStyle('bars')},children:'Bars'},'toggle-bars')
]},'toggles')
]},'summary'),
jsx('svg',{viewBox:'0 0 720 170',role:'img','aria-label':'24 hour token activity chart',style:{width:'100%',height:170,display:'block',marginTop:6},children:[
jsx('defs',{children:jsx('linearGradient',{id:'wave-grad',x1:'0',y1:'0',x2:'0',y2:'1',children:[
jsx('stop',{offset:'0%',stopColor:'var(--ui-accent)',stopOpacity:0.25},'stop-0'),
jsx('stop',{offset:'100%',stopColor:'var(--ui-accent)',stopOpacity:0.0},'stop-1')
]},'grad')},'defs'),
jsx('line',{x1:plotLeft,y1:15,x2:plotRight,y2:15,stroke:'var(--ui-stroke-secondary)',strokeDasharray:'4 4',opacity:0.4},'grid-100'),
jsx('line',{x1:plotLeft,y1:75,x2:plotRight,y2:75,stroke:'var(--ui-stroke-secondary)',strokeDasharray:'4 4',opacity:0.4},'grid-50'),
jsx('line',{x1:plotLeft,y1:baseline,x2:plotRight,y2:baseline,stroke:'var(--ui-stroke-secondary)',strokeDasharray:'4 4',opacity:0.4},'grid-0'),
...[
[15,compact(max),'axis-max'],
[75,compact(max / 2),'axis-half'],
[baseline,'0','axis-zero']
].map(([y,label,key]) => jsx('text',{x:58,y:y+3,textAnchor:'end',fill:'var(--ui-text-tertiary)',fontSize:10,children:label},key)),
...(style === 'wave' ? [
jsx('path',{d:areaD,fill:'url(#wave-grad)'},'wave-area'),
jsx('path',{d:lineD,fill:'none',stroke:'var(--ui-accent, #3b82f6)',strokeWidth:2},'wave-line'),
...points.filter(p => p.bucket.total > 0).map(p => jsx('circle',{
cx: p.x,
cy: p.y,
r: 3,
fill: 'var(--ui-accent)',
stroke: 'var(--ui-bg)',
children: jsx('title',{children:chartTitle(p.bucket)})
},`circle-${p.bucket.hour}`))
] : hourly.map(bucket => {
const x = plotLeft + bucket.hour * step - 10
const height = bucket.total ? Math.max(2, (bucket.total / max) * chartHeight) : 2
const y = baseline - height
return jsx('rect',{
x,
y,
width: 20,
height,
rx: 2,
fill: bucket.total ? 'var(--ui-accent, #3b82f6)' : 'var(--ui-stroke-secondary)',
children: jsx('title',{children:chartTitle(bucket)})
},`bar-${bucket.hour}`)
})),
...[0, 3, 6, 9, 12, 15, 18, 21, 23].map(hour => jsx('text',{
x: plotLeft + hour * step,
y: 158,
textAnchor: 'middle',
fill: 'var(--ui-text-tertiary)',
fontSize: 10,
children: `${String(hour).padStart(2,'0')}:00`
},`axis-${hour}`))
]},'chart')
]})
}
function dateKey(timestamp, timezone) {
const parts = new Intl.DateTimeFormat('en', {timeZone: timezone, year:'numeric', month:'2-digit', day:'2-digit'}).formatToParts(new Date(timestamp * 1000))
return `${parts.find(p=>p.type==='year').value}-${parts.find(p=>p.type==='month').value}-${parts.find(p=>p.type==='day').value}`
}
function shiftDate(key, amount) {
const value = new Date(`${key}T00:00:00Z`)
value.setUTCDate(value.getUTCDate() + amount)
return value.toISOString().slice(0, 10)
}
function dateRange(start, end) {
const result = []
for (let key = start; key <= end; key = shiftDate(key, 1)) result.push(key)
return result
}
function dateLabel(start, end) {
return start === end ? start : `${start} – ${end}`
}
function selectionFor(data, preset, fromDate, toDate) {
const today = dateKey(data.generated_at, data.timezone)
const legacy = {today:'day', 'this-week':'week', 'this-month':'month'}
if (legacy[preset]) {
const period = data.periods[legacy[preset]]
const periodStart = dateKey(period.start, data.timezone)
const days = data.days || {}
const selectedDays = dateRange(periodStart, today).map(key => days[key]).filter(Boolean)
return {label:{today:'Today', 'this-week':'This week', 'this-month':'This month'}[preset], start:periodStart, groups:period.groups, ambiguous:period.boundary_ambiguous_groups, hourly:preset === 'today' ? (period.hourly || combineHourly(selectedDays)) : (combineHourly(selectedDays) || period.hourly), startTimestamp:period.start}
}
let start = today
let end = today
if (preset === 'yesterday') start = end = shiftDate(today, -1)
if (preset === 'last-7') start = shiftDate(today, -6)
if (preset === 'last-30') start = shiftDate(today, -29)
if (preset === 'custom') {
start = fromDate || today
end = toDate || start
if (start > end) [start, end] = [end, start]
}
const days = data.days || {}
const selectedDays = dateRange(start, end).map(key => days[key]).filter(Boolean)
return {label:preset === 'custom' ? dateLabel(start, end) : ({yesterday:'Yesterday','last-7':'Last 7 days','last-30':'Last 30 days'}[preset] || dateLabel(start, end)), groups:selectedDays.flatMap(day=>day.groups), ambiguous:selectedDays.flatMap(day=>day.boundary_ambiguous_groups), hourly:combineHourly(selectedDays), startTimestamp:selectedDays[0]?.start || null}
}
function Details() {
const q = useSummary()
const [preset,setPreset] = useState('today')
const [fromDate,setFromDate] = useState('')
const [toDate,setToDate] = useState('')
const [profile,setProfile] = useState('')
const [tab,setTab] = useState('Providers')
const [showAll,setShowAll] = useState(false)
const d=q.data
if (!d) return jsx('div',{style:{padding:20,color:'var(--ui-text-secondary)'},children:q.isError?String(q.error?.message || q.error):'Loading local ledger…'})
const selection = selectionFor(d, preset, fromDate, toDate)
const usage=aggregateUsage(selection.groups,profile)
const profiles=[...new Set([...Object.keys(d.sources),...Object.values(d.periods).flatMap(v=>v.groups.map(r=>r.profile)),...Object.values(d.days || {}).flatMap(v=>v.groups.map(r=>r.profile))])].sort()
const ambiguous=selection.ambiguous.filter(r=>!profile || r.profile===profile)
const boundaryTotal=ambiguous.reduce((n,r)=>n+r.total,0)
const sources=Object.entries(d.sources).filter(([name])=>!profile || profile===name)
const dateInputStyle={...button,background:'var(--ui-bg)',color:'var(--ui-text-secondary)'}
return jsx('section',{'data-token-usage':'details',style:{padding:16,overflow:'auto',height:'100%',color:'var(--ui-text-secondary)',display:'flex',flexDirection:'column',gap:12},children:[
jsx('div',{style:{display:'flex',alignItems:'center',gap:8,flexWrap:'wrap'},children:[
jsx('h2',{style:{fontSize:16,fontWeight:600,margin:0,marginRight:'auto'},children:'Token usage · this Mac'},'title'),
jsx('select',{'aria-label':'Date range',value:preset,onChange:e=>setPreset(e.target.value),style:{...button,background:'var(--ui-bg)'},children:[
['today','Today'],['yesterday','Yesterday'],['this-week','This week'],['last-7','Last 7 days'],['this-month','This month'],['last-30','Last 30 days'],['custom','Custom range']
].map(([value,label])=>jsx('option',{value,children:label},value))},'date-range'),
preset==='custom' ? jsx('div',{style:{display:'flex',gap:6,alignItems:'center'},children:[
jsx('label',{style:muted,children:'From'},'from-label'),jsx('input',{type:'date','aria-label':'From date',value:fromDate,onChange:e=>setFromDate(e.target.value),style:dateInputStyle},'from'),
jsx('label',{style:muted,children:'To'},'to-label'),jsx('input',{type:'date','aria-label':'To date',value:toDate,onChange:e=>setToDate(e.target.value),style:dateInputStyle},'to')
]},'date-inputs') : null,
jsx('select',{'aria-label':'Profile',value:profile,onChange:e=>setProfile(e.target.value),style:{...button,background:'var(--ui-bg)'},children:[jsx('option',{value:'',children:'All profiles'},'all'),...profiles.map(name=>jsx('option',{value:name,children:name},name))]},'profile'),
jsx('button',{type:'button',style:button,disabled:q.isFetching,onClick:()=>q.refetch(),children:q.isFetching?'Refreshing…':'Refresh'},'refresh')
]},'header'),
selection.hourly ? jsx(HourlyChart,{hourly:selection.hourly},'hourly') : jsx('div',{style:muted,children:'Hourly activity unavailable for this snapshot.'},'hourly-fallback'),
jsx('div',{role:'tablist','aria-label':'Usage views',style:{display:'flex',gap:6},children:['Providers','Top models'].map(name=>jsx('button',{type:'button',role:'tab','aria-selected':tab===name,style:{...button,color:tab===name?'var(--ui-accent)':'var(--ui-text-secondary)'},onClick:()=>setTab(name),children:name},name))},'tabs'),
jsx('div',{style:muted,children:`${selection.label} · ${fmt(usage.total)} tokens · Share denominator: ${fmt(usage.total)} confirmed selected tokens · ${d.timezone} · ${status(d)}`},'summary'),
q.isError?jsx('p',{style:muted,children:'Refresh failed: '+String(q.error?.message || q.error)+'. Showing last cached data.'},'error'):null,
tab==='Providers' ? jsx('div',{role:'tabpanel',children:usage.profiles.length?usage.profiles.map(pr=>jsx('details',{'data-profile':pr.profile,open:true,style:{borderTop:'1px solid var(--ui-stroke-secondary)',paddingTop:8,marginBottom:10},children:[
jsx('summary',{style:{cursor:'pointer',fontWeight:600,fontSize:13},children:`${pr.profile} · ${fmt(pr.total)} tokens`},'profile'),
jsx(CompactTable,{rows:pr.providers,denominator:usage.total},'table')
]},pr.profile)):jsx('p',{style:muted,children:'No confirmed usage for this selection.'})},'providers') : jsx('div',{role:'tabpanel',children:[
jsx('div',{style:{display:'flex',alignItems:'center',gap:8,justifyContent:'space-between'},children:[
jsx('span',{style:muted,children:`${fmt(usage.missingModelTotal)} tokens (${percent(usage.missingModelTotal,usage.total)}) legacy/missing model excluded from ranking; still included in share denominator.`},'missing'),
jsx('button',{type:'button',style:button,'aria-pressed':showAll,onClick:()=>setShowAll(!showAll),children:showAll?'Top 5':'Show all'},'toggle')
]},'ranking'),
usage.models.length?jsx(CompactTable,{rows:showAll?usage.models:usage.models.slice(0,5),denominator:usage.total,models:true},'table'):jsx('p',{style:muted,children:'No confirmed usage with an identified model.'},'empty')
]},'models'),
jsx('details',{'data-coverage':'',style:muted,children:[
jsx('summary',{style:{cursor:'pointer'},children:`Coverage & history · observed only · ${fmt(boundaryTotal)} boundary-excluded tokens · ${status(d)}${sources.some(([,s])=>!s.ok || s.config_ok===false)?' · source warnings':''}`},'summary'),
jsx('p',{children:`Observed since ${when(d.installed_at,d.timezone)}. Selected range starts ${selection.startTimestamp ? when(selection.startTimestamp,d.timezone) : 'unavailable'}. Snapshot ${when(d.generated_at,d.timezone)}. NOT complete historical day/week/month totals: pre-existing cumulative usage was baselined, never inferred by last_seen.`},'history'),
jsx('p',{children:`Boundary-ambiguous: ${fmt(boundaryTotal)} tokens excluded from confirmed total. Effective total = canonical input + output; cache read/write remain raw detail fields. Reasoning is an output subset, not additive. Counter reset anomalies: ${fmt(d.anomaly_count)}.`},'accounting'),
...sources.map(([name,s])=>jsx('p',{children:`${name}: ${s.ok?`${fmt(s.row_count)} source rows`:'READ FAILED · '+(s.error || 'source unavailable')+'; prior ledger retained'}${s.config_ok===false?' · '+s.config_status:''}. Zero usage rows hidden, not discarded.`},name)),
jsx(Evidence,{routes:ambiguous},'boundary'),
jsx('ul',{style:{paddingLeft:18},children:d.limitations.map((s,i)=>jsx('li',{children:s},i))},'limits')
]},'coverage')
]})
}
export default {
id: ID, name: 'Token Usage Ledger', defaultEnabled: true,
description: 'Local observed day/week/month token deltas, profile → exact billing provider, cache and reasoning breakdown. No historical estimates.',
register(ctx) {
ctx.register({ id: 'chip', area: 'statusBar.right', order: 205, render: () => jsx(Chip, {}) })
ctx.register({ id: 'page', area: sdk.ROUTES_AREA || 'routes', data: { path: ROUTE }, render: () => jsx(Details, {}) })
ctx.register({ id: 'nav', area: sdk.SIDEBAR_NAV_AREA || 'sidebar.nav', data: { path: ROUTE, label: 'Token Usage', codicon: 'graph' } })
ctx.register({ id: 'open', area: sdk.PALETTE_AREA || 'palette', data: { id: ID+'.open', label: 'Token Usage: local ledger', keywords: ['tokens','usage','billing','cache'], run: () => sdk.host.navigate(ROUTE) } })
}
}