magpie-multi-usage 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,135 @@
1
+ <!doctype html>
2
+ <html lang="en">
3
+ <head>
4
+ <meta charset="utf-8">
5
+ <meta name="viewport" content="width=device-width, initial-scale=1">
6
+ <title>Multi-Device Usage</title>
7
+ <link rel="icon" href="data:,">
8
+ <link rel="stylesheet" href="./app.css">
9
+ </head>
10
+ <body>
11
+ <main class="view">
12
+ <header class="usage-head">
13
+ <div id="range-group" class="segs" role="group" aria-label="Time range"></div>
14
+ <div id="device-tabs" class="segs" role="tablist" aria-label="Device scope"></div>
15
+ <div class="head-right">
16
+ <div id="usage-cost" class="usage-cost"></div>
17
+ <div class="head-actions">
18
+ <button id="refresh-btn" type="button" class="icon-btn" title="Sync now" aria-label="Sync now">
19
+ <svg viewBox="0 0 16 16" width="14" height="14" aria-hidden="true">
20
+ <path d="M13.5 8a5.5 5.5 0 1 1-1.6-3.9M13.5 2v3h-3" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"/>
21
+ </svg>
22
+ </button>
23
+ <button id="settings-btn" type="button" class="icon-btn" title="Settings" aria-label="Settings">
24
+ <svg viewBox="0 0 24 24" width="14" height="14" aria-hidden="true">
25
+ <g fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
26
+ <path d="M12.22 2h-.44a2 2 0 0 0-2 2v.18a2 2 0 0 1-1 1.73l-.43.25a2 2 0 0 1-2 0l-.15-.08a2 2 0 0 0-2.73.73l-.22.38a2 2 0 0 0 .73 2.73l.15.1a2 2 0 0 1 1 1.72v.51a2 2 0 0 1-1 1.74l-.15.09a2 2 0 0 0-.73 2.73l.22.38a2 2 0 0 0 2.73.73l.15-.08a2 2 0 0 1 2 0l.43.25a2 2 0 0 1 1 1.73V20a2 2 0 0 0 2 2h.44a2 2 0 0 0 2-2v-.18a2 2 0 0 1 1-1.73l.43-.25a2 2 0 0 1 2 0l.15.08a2 2 0 0 0 2.73-.73l.22-.39a2 2 0 0 0-.73-2.73l-.15-.08a2 2 0 0 1-1-1.74v-.5a2 2 0 0 1 1-1.74l.15-.09a2 2 0 0 0 .73-2.73l-.22-.38a2 2 0 0 0-2.73-.73l-.15.08a2 2 0 0 1-2 0l-.43-.25a2 2 0 0 1-1-1.73V4a2 2 0 0 0-2-2z"/>
27
+ <circle cx="12" cy="12" r="3"/>
28
+ </g>
29
+ </svg>
30
+ </button>
31
+ </div>
32
+ </div>
33
+ </header>
34
+
35
+ <section id="banners" class="banners" aria-live="polite"></section>
36
+
37
+ <section id="kpi-strip" class="stats" aria-label="Usage overview"></section>
38
+
39
+ <section class="chart" aria-label="Daily token activity">
40
+ <div class="chart-top">
41
+ <span id="trend-readout" class="chart-readout"></span>
42
+ <span id="trend-peak" class="peak"></span>
43
+ </div>
44
+ <div id="trend-container"></div>
45
+ </section>
46
+
47
+ <div class="sec-head">
48
+ <span id="devices-heading" class="sec-title">Devices</span>
49
+ <span id="devices-meta" class="sec-meta"></span>
50
+ </div>
51
+ <section id="devices-list" class="list" aria-label="Devices"></section>
52
+
53
+ <div class="sec-head sec-head-tabs">
54
+ <div id="breakdown-tabs" class="segs segs-compact" role="tablist" aria-label="Usage breakdown"></div>
55
+ <span id="breakdown-meta" class="sec-meta"></span>
56
+ </div>
57
+ <section id="breakdown-list" class="list" aria-label="Breakdown"></section>
58
+
59
+ <footer id="sync-footer" class="sync-footer"></footer>
60
+ </main>
61
+
62
+ <div id="drawer-backdrop" class="drawer-backdrop hidden"></div>
63
+ <aside id="settings-drawer" class="sheet hidden" role="dialog" aria-modal="true" aria-labelledby="drawer-title">
64
+ <div class="sheet-header">
65
+ <h2 id="drawer-title">Relay settings</h2>
66
+ <button id="drawer-close" type="button" class="icon-btn" aria-label="Close">
67
+ <svg viewBox="0 0 16 16" width="12" height="12" aria-hidden="true">
68
+ <path d="M4 4l8 8M12 4l-8 8" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"/>
69
+ </svg>
70
+ </button>
71
+ </div>
72
+ <form id="settings-form" class="sheet-body">
73
+ <div class="field">
74
+ <label id="lbl-lang" for="cfg-lang"></label>
75
+ <select id="cfg-lang" name="lang">
76
+ <option value="auto" id="opt-lang-auto"></option>
77
+ <option value="en" id="opt-lang-en"></option>
78
+ <option value="zh" id="opt-lang-zh"></option>
79
+ </select>
80
+ </div>
81
+ <div class="field">
82
+ <label id="lbl-device-id" for="cfg-device-id"></label>
83
+ <input id="cfg-device-id" type="text" readonly class="mono">
84
+ </div>
85
+ <div class="field">
86
+ <label id="lbl-device-name" for="cfg-device-name"></label>
87
+ <input id="cfg-device-name" name="deviceName" type="text" maxlength="80">
88
+ </div>
89
+ <div class="field">
90
+ <label id="lbl-repo" for="cfg-repo"></label>
91
+ <input id="cfg-repo" name="repo" type="text" autocomplete="off" spellcheck="false">
92
+ </div>
93
+ <div class="field-row">
94
+ <div class="field">
95
+ <label id="lbl-branch" for="cfg-branch"></label>
96
+ <input id="cfg-branch" name="branch" type="text" autocomplete="off" spellcheck="false">
97
+ </div>
98
+ <div class="field">
99
+ <label id="lbl-prefix" for="cfg-prefix"></label>
100
+ <input id="cfg-prefix" name="prefix" type="text" autocomplete="off" spellcheck="false">
101
+ </div>
102
+ </div>
103
+ <div class="field">
104
+ <label id="lbl-token" for="cfg-token"></label>
105
+ <input id="cfg-token" name="githubToken" type="password" autocomplete="new-password">
106
+ <div id="token-status-row" class="token-status-row">
107
+ <span id="token-hint" class="muted"></span>
108
+ <button id="clear-token-btn" type="button" class="link-btn hidden"></button>
109
+ </div>
110
+ <p id="lbl-token-help" class="field-help muted"></p>
111
+ </div>
112
+ <label class="checkbox-row">
113
+ <input id="cfg-push-enabled" name="pushEnabled" type="checkbox">
114
+ <span id="lbl-push-enabled"></span>
115
+ </label>
116
+ <label class="checkbox-row">
117
+ <input id="cfg-filter-forwarded" name="filterForwarded" type="checkbox">
118
+ <span id="lbl-filter-forwarded"></span>
119
+ </label>
120
+ <div class="field">
121
+ <label id="lbl-push-interval" for="cfg-push-interval"></label>
122
+ <input id="cfg-push-interval" name="pushIntervalSec" type="number" min="30" max="86400" step="10">
123
+ </div>
124
+ <div id="drawer-feedback" class="feedback hidden" aria-live="polite"></div>
125
+ <div class="sheet-footer">
126
+ <button id="test-conn-btn" type="button" class="pill-btn"></button>
127
+ <button id="save-cfg-btn" type="submit" class="pill-btn pill-btn-primary"></button>
128
+ </div>
129
+ </form>
130
+ </aside>
131
+
132
+ <!--MULTI_USAGE_BOOTSTRAP-->
133
+ <script type="module" src="./app.js"></script>
134
+ </body>
135
+ </html>
@@ -0,0 +1,410 @@
1
+ /**
2
+ * Pure dashboard view-model helpers, formatters, SVG stacked chart geometry,
3
+ * proportional mix calculation, and EN/ZH localization catalog.
4
+ */
5
+
6
+ export const MESSAGES = Object.freeze({
7
+ en: Object.freeze({
8
+ title: "Multi-Device Usage",
9
+ subtitle: "Combined token telemetry across your Magpie machines",
10
+ rangeToday: "Today",
11
+ range7d: "7d",
12
+ range30d: "30d",
13
+ rangeAll: "All",
14
+ allDevices: "All devices",
15
+ thisMachine: "Local",
16
+ refresh: "Sync now",
17
+ refreshing: "Syncing...",
18
+ settings: "Settings",
19
+ lastSynced: "Last synced",
20
+ never: "Never",
21
+ kpiRequests: "Calls",
22
+ kpiErrorsSuffix: "failed",
23
+ kpiForwardedSuffix: "forwarded excluded",
24
+ kpiTotalTokens: "Tokens",
25
+ kpiTokensFormula: "Input, output, cache read, and cache write",
26
+ kpiInputOutput: "Input / Output",
27
+ kpiCache: "Cache read",
28
+ kpiCacheHit: "hit rate",
29
+ kpiCost: "Est. cost",
30
+ estCostShort: "estimated",
31
+ devicesUnit: "devices",
32
+ deviceUnitSingular: "device",
33
+ inShort: "in",
34
+ outShort: "out",
35
+ cacheShort: "cache",
36
+ cachedShort: "cached",
37
+ writtenShort: "written",
38
+ callsSingular: "call",
39
+ callsPlural: "calls",
40
+ mixHeading: "Token composition",
41
+ devicesHeading: "Devices",
42
+ devicesHint: "Click a device to filter",
43
+ sortedByTokens: "Sorted by tokens",
44
+ colDevice: "Device",
45
+ colStatus: "Status",
46
+ colUpdated: "Updated",
47
+ colCoverage: "Coverage",
48
+ colRequests: "Requests",
49
+ colInput: "Input",
50
+ colOutput: "Output",
51
+ colCacheRead: "Cache read",
52
+ colCacheWrite: "Cache write",
53
+ colShare: "Share",
54
+ colCost: "Cost",
55
+ statusOk: "Synced",
56
+ statusStale: "Cached",
57
+ statusError: "Error",
58
+ statusEmpty: "No data",
59
+ trendHeading: "Daily token activity",
60
+ trendHint: "Hover a bar for details · light prompt/cache, solid output",
61
+ trendEmpty: "No usage recorded in the selected range.",
62
+ legendInput: "Input",
63
+ legendOutput: "Output",
64
+ legendCacheRead: "Cache read",
65
+ legendCacheWrite: "Cache write",
66
+ topModelsHeading: "Models",
67
+ topAgentsHeading: "Agents",
68
+ topProvidersHeading: "Providers",
69
+ colName: "Name",
70
+ colTokens: "Tokens",
71
+ noRows: "No records in this range.",
72
+ warningPrefix: "Showing cached snapshot for",
73
+ notConfiguredHint: "Configure a dedicated private GitHub repository in Settings to sync usage across machines.",
74
+ relayLocalOnly: "Local only",
75
+ relayRepoPrefix: "Relay:",
76
+ drawerTitle: "Relay settings",
77
+ close: "Close",
78
+ fieldLang: "Language",
79
+ langAuto: "Follow system",
80
+ langEn: "English",
81
+ langZh: "中文",
82
+ openSettingsAction: "Configure",
83
+ fieldDeviceId: "Persistent device ID",
84
+ fieldDeviceName: "Device display name",
85
+ fieldRepo: "Private GitHub repository",
86
+ fieldRepoPlaceholder: "owner/magpie-usage-stats",
87
+ fieldBranch: "Branch (optional)",
88
+ fieldBranchPlaceholder: "Repository default branch",
89
+ fieldPrefix: "Folder prefix",
90
+ fieldToken: "GitHub Fine-grained PAT",
91
+ fieldTokenPlaceholder: "Leave blank to keep existing token",
92
+ fieldTokenHelp: "Requires a dedicated private repo: Contents Read & Write to publish, or Read-only for view-only mode. Stored locally in 0600 credentials.json.",
93
+ fieldTokenEnvNote: "Token supplied by MAGPIE_MULTI_USAGE_GITHUB_TOKEN.",
94
+ tokenConfiguredPrefix: "Configured:",
95
+ clearToken: "Clear token",
96
+ fieldPushEnabled: "Publish this machine's usage",
97
+ fieldFilterForwarded: "Exclude cross-Magpie forwarded calls (via)",
98
+ fieldPushInterval: "Auto-push cooldown (seconds)",
99
+ testConnection: "Test connection",
100
+ saveAndSync: "Save and sync",
101
+ testing: "Testing...",
102
+ saving: "Saving...",
103
+ testSuccess: "Private repository verified",
104
+ savedSuccess: "Settings saved and synced.",
105
+ branchMissingWarning: "branch not initialized yet",
106
+ readOnlyNote: "read-only token",
107
+ readWriteNote: "read/write token",
108
+ }),
109
+ zh: Object.freeze({
110
+ title: "多端用量",
111
+ subtitle: "跨设备 Magpie Token 统计总览",
112
+ rangeToday: "今日",
113
+ range7d: "7 天",
114
+ range30d: "30 天",
115
+ rangeAll: "全部",
116
+ allDevices: "全部设备",
117
+ thisMachine: "本机",
118
+ refresh: "立即同步",
119
+ refreshing: "同步中...",
120
+ settings: "设置",
121
+ lastSynced: "最近同步",
122
+ never: "从未",
123
+ kpiRequests: "调用次数",
124
+ kpiErrorsSuffix: "失败",
125
+ kpiForwardedSuffix: "转发已排除",
126
+ kpiTotalTokens: "总 Token",
127
+ kpiTokensFormula: "输入、输出、缓存读取与缓存写入之和",
128
+ kpiInputOutput: "输入 / 输出",
129
+ kpiCache: "缓存读取",
130
+ kpiCacheHit: "命中率",
131
+ kpiCost: "预估费用",
132
+ estCostShort: "预估",
133
+ devicesUnit: "台设备",
134
+ deviceUnitSingular: "台设备",
135
+ inShort: "输入",
136
+ outShort: "输出",
137
+ cacheShort: "缓存",
138
+ cachedShort: "缓存",
139
+ writtenShort: "写入",
140
+ callsSingular: "次调用",
141
+ callsPlural: "次调用",
142
+ mixHeading: "Token 构成",
143
+ devicesHeading: "设备",
144
+ devicesHint: "点击任意设备筛选范围",
145
+ sortedByTokens: "按总 Token 排序",
146
+ colDevice: "设备",
147
+ colStatus: "状态",
148
+ colUpdated: "更新时间",
149
+ colCoverage: "覆盖日期",
150
+ colRequests: "请求数",
151
+ colInput: "输入",
152
+ colOutput: "输出",
153
+ colCacheRead: "缓存读取",
154
+ colCacheWrite: "缓存写入",
155
+ colShare: "占比",
156
+ colCost: "费用",
157
+ statusOk: "已同步",
158
+ statusStale: "缓存",
159
+ statusError: "异常",
160
+ statusEmpty: "无数据",
161
+ trendHeading: "每日 Token 趋势",
162
+ trendHint: "悬停柱体查看当日明细 · 浅色为输入/缓存,深色为输出",
163
+ trendEmpty: "所选范围内暂无用量数据。",
164
+ legendInput: "输入",
165
+ legendOutput: "输出",
166
+ legendCacheRead: "缓存读取",
167
+ legendCacheWrite: "缓存写入",
168
+ topModelsHeading: "模型",
169
+ topAgentsHeading: "Agents",
170
+ topProvidersHeading: "Providers",
171
+ colName: "名称",
172
+ colTokens: "Token",
173
+ noRows: "当前范围暂无记录。",
174
+ warningPrefix: "当前展示缓存快照:",
175
+ notConfiguredHint: "请在设置中配置专用私有 GitHub 仓库,以开启多端用量同步。",
176
+ relayLocalOnly: "仅本机数据",
177
+ relayRepoPrefix: "中继仓库:",
178
+ drawerTitle: "同步中继设置",
179
+ close: "关闭",
180
+ fieldLang: "界面语言",
181
+ langAuto: "跟随系统",
182
+ langEn: "English",
183
+ langZh: "中文",
184
+ openSettingsAction: "去配置",
185
+ fieldDeviceId: "持久设备 ID",
186
+ fieldDeviceName: "本机名称",
187
+ fieldRepo: "专用私有 GitHub 仓库",
188
+ fieldRepoPlaceholder: "owner/magpie-usage-stats",
189
+ fieldBranch: "分支(可选)",
190
+ fieldBranchPlaceholder: "默认使用仓库默认分支",
191
+ fieldPrefix: "目录前缀",
192
+ fieldToken: "GitHub Fine-grained PAT",
193
+ fieldTokenPlaceholder: "留空以保留已保存令牌",
194
+ fieldTokenHelp: "必须使用专用私有仓库:上报需 Contents Read & Write,只读查看只需 Read-only。令牌仅存于本机 0600 权限的 credentials.json。",
195
+ fieldTokenEnvNote: "当前使用环境变量 MAGPIE_MULTI_USAGE_GITHUB_TOKEN。",
196
+ tokenConfiguredPrefix: "已配置:",
197
+ clearToken: "清除令牌",
198
+ fieldPushEnabled: "上报本机用量",
199
+ fieldFilterForwarded: "过滤跨 Magpie 转发调用(via)",
200
+ fieldPushInterval: "自动上报防抖间隔(秒)",
201
+ testConnection: "测试连接",
202
+ saveAndSync: "保存并同步",
203
+ testing: "测试中...",
204
+ saving: "保存中...",
205
+ testSuccess: "私有仓库校验通过",
206
+ savedSuccess: "设置已保存并完成同步。",
207
+ branchMissingWarning: "分支尚未初始化",
208
+ readOnlyNote: "只读权限",
209
+ readWriteNote: "读写权限",
210
+ }),
211
+ });
212
+
213
+ export function resolveLang(rawLang = "") {
214
+ const lower = String(rawLang || "").trim().toLowerCase();
215
+ return lower.startsWith("zh") ? "zh" : "en";
216
+ }
217
+
218
+ export function t(lang, key) {
219
+ const dict = MESSAGES[resolveLang(lang)] || MESSAGES.en;
220
+ return dict[key] ?? MESSAGES.en[key] ?? key;
221
+ }
222
+
223
+ export function formatCompactTokens(value) {
224
+ const n = Number(value) || 0;
225
+ const abs = Math.abs(n);
226
+ if (abs >= 1e9) {
227
+ return `${(n / 1e9).toFixed(2)}B`;
228
+ }
229
+ if (abs >= 1e6) {
230
+ return `${(n / 1e6).toFixed(2)}M`;
231
+ }
232
+ if (abs >= 1e3) {
233
+ return `${(n / 1e3).toFixed(1)}K`;
234
+ }
235
+ return String(Math.round(n));
236
+ }
237
+
238
+ export function formatExactNumber(value) {
239
+ const n = Number(value) || 0;
240
+ return Math.round(n).toLocaleString("en-US");
241
+ }
242
+
243
+ export function formatUsd(value) {
244
+ const n = Number(value) || 0;
245
+ if (n === 0) {
246
+ return "$0.00";
247
+ }
248
+ if (n < 0.01) {
249
+ return `$${n.toFixed(4)}`;
250
+ }
251
+ return `$${n.toFixed(2)}`;
252
+ }
253
+
254
+ export function formatPercent(ratio) {
255
+ const n = Number(ratio) || 0;
256
+ return `${(n * 100).toFixed(1)}%`;
257
+ }
258
+
259
+ export function formatCoverageWindow(coverage) {
260
+ if (!coverage?.firstDay || !coverage?.lastDay) {
261
+ return "—";
262
+ }
263
+ if (coverage.firstDay === coverage.lastDay) {
264
+ return coverage.firstDay;
265
+ }
266
+ return `${coverage.firstDay} ~ ${coverage.lastDay}`;
267
+ }
268
+
269
+ export function formatTimestamp(isoString, lang = "en") {
270
+ if (!isoString) {
271
+ return t(lang, "never");
272
+ }
273
+ const date = new Date(isoString);
274
+ if (Number.isNaN(date.getTime())) {
275
+ return String(isoString);
276
+ }
277
+ const yyyy = date.getFullYear();
278
+ const mm = String(date.getMonth() + 1).padStart(2, "0");
279
+ const dd = String(date.getDate()).padStart(2, "0");
280
+ const hh = String(date.getHours()).padStart(2, "0");
281
+ const min = String(date.getMinutes()).padStart(2, "0");
282
+ return `${yyyy}-${mm}-${dd} ${hh}:${min}`;
283
+ }
284
+
285
+ export function statusLabel(status, lang = "en") {
286
+ switch (status) {
287
+ case "ok":
288
+ return t(lang, "statusOk");
289
+ case "stale":
290
+ return t(lang, "statusStale");
291
+ case "error":
292
+ return t(lang, "statusError");
293
+ default:
294
+ return t(lang, "statusEmpty");
295
+ }
296
+ }
297
+
298
+ export function extractDeviceWarnings(devices = []) {
299
+ return devices
300
+ .filter((d) => d && (d.status === "stale" || d.status === "error") && d.lastError)
301
+ .map((d) => ({
302
+ deviceId: d.deviceId,
303
+ displayName: d.displayName || d.deviceId,
304
+ status: d.status,
305
+ lastSyncedAt: d.lastSyncedAt || null,
306
+ lastError: d.lastError,
307
+ }));
308
+ }
309
+
310
+ /**
311
+ * Compute proportional share segments for the token composition bar.
312
+ */
313
+ export function buildTokenMix(totals = {}) {
314
+ const input = Number(totals.input) || 0;
315
+ const output = Number(totals.output) || 0;
316
+ const cacheRead = Number(totals.cacheRead) || 0;
317
+ const cacheWrite = Number(totals.cacheWrite) || 0;
318
+ const total = input + output + cacheRead + cacheWrite;
319
+
320
+ return [
321
+ { key: "input", value: input, pct: total > 0 ? (input / total) * 100 : 0 },
322
+ { key: "output", value: output, pct: total > 0 ? (output / total) * 100 : 0 },
323
+ { key: "cacheRead", value: cacheRead, pct: total > 0 ? (cacheRead / total) * 100 : 0 },
324
+ { key: "cacheWrite", value: cacheWrite, pct: total > 0 ? (cacheWrite / total) * 100 : 0 },
325
+ ];
326
+ }
327
+
328
+ /**
329
+ * Compute deterministic stacked bar geometry for the daily token trend SVG.
330
+ */
331
+ export function buildDailyChartModel(daily = [], { width = 880, height = 224 } = {}) {
332
+ const padLeft = 56;
333
+ const padRight = 16;
334
+ const padTop = 16;
335
+ const padBottom = 30;
336
+ const plotWidth = Math.max(100, width - padLeft - padRight);
337
+ const plotHeight = Math.max(60, height - padTop - padBottom);
338
+
339
+ const maxTokens = daily.reduce((max, item) => Math.max(max, Number(item.totalTokens) || 0), 0);
340
+ const scaleMax = maxTokens > 0 ? maxTokens : 1;
341
+
342
+ const count = daily.length;
343
+ const slotWidth = count > 0 ? plotWidth / count : plotWidth;
344
+ const barWidth = Math.max(6, Math.min(40, slotWidth * 0.62));
345
+ const labelEvery = count > 10 ? Math.ceil(count / 8) : 1;
346
+
347
+ const bars = daily.map((item, idx) => {
348
+ const x = padLeft + idx * slotWidth + (slotWidth - barWidth) / 2;
349
+ const parts = [
350
+ { key: "input", value: Number(item.input) || 0 },
351
+ { key: "output", value: Number(item.output) || 0 },
352
+ { key: "cacheRead", value: Number(item.cacheRead) || 0 },
353
+ { key: "cacheWrite", value: Number(item.cacheWrite) || 0 },
354
+ ];
355
+
356
+ let currentTop = padTop + plotHeight;
357
+ const segments = [];
358
+ for (const part of parts) {
359
+ if (part.value <= 0) {
360
+ continue;
361
+ }
362
+ const segHeight = (part.value / scaleMax) * plotHeight;
363
+ const y = currentTop - segHeight;
364
+ segments.push({
365
+ key: part.key,
366
+ x,
367
+ y,
368
+ width: barWidth,
369
+ height: segHeight,
370
+ value: part.value,
371
+ });
372
+ currentTop = y;
373
+ }
374
+
375
+ return {
376
+ day: item.day,
377
+ shortDay: typeof item.day === "string" && item.day.length === 10 ? item.day.slice(5) : String(item.day || ""),
378
+ showLabel: idx === 0 || idx === count - 1 || idx % labelEvery === 0,
379
+ labelX: x + barWidth / 2,
380
+ slotX: padLeft + idx * slotWidth,
381
+ slotWidth,
382
+ input: Number(item.input) || 0,
383
+ output: Number(item.output) || 0,
384
+ cacheRead: Number(item.cacheRead) || 0,
385
+ cacheWrite: Number(item.cacheWrite) || 0,
386
+ totalTokens: Number(item.totalTokens) || 0,
387
+ calls: Number(item.calls) || 0,
388
+ cost: Number(item.cost) || 0,
389
+ segments,
390
+ };
391
+ });
392
+
393
+ const ticks = [0, 0.5, 1].map((frac) => ({
394
+ y: padTop + plotHeight * (1 - frac),
395
+ value: scaleMax * frac,
396
+ label: formatCompactTokens(scaleMax * frac),
397
+ }));
398
+
399
+ return {
400
+ width,
401
+ height,
402
+ padLeft,
403
+ padTop,
404
+ plotWidth,
405
+ plotHeight,
406
+ maxTokens,
407
+ ticks,
408
+ bars,
409
+ };
410
+ }