magpie-multi-usage 0.1.2 → 0.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.md +1 -1
- package/README.zh-CN.md +1 -1
- package/package.json +1 -1
- package/src/aggregator.mjs +271 -2
- package/src/github-store.mjs +1 -1
- package/src/http-server.mjs +2 -1
- package/src/sync-engine.mjs +26 -5
- package/src/ui/app.css +47 -4
- package/src/ui/app.js +260 -42
- package/src/ui/dashboard-state.mjs +131 -0
- package/src/ui/index.html +2 -1
- package/src/ui/view-model.mjs +165 -3
package/README.md
CHANGED
|
@@ -53,7 +53,7 @@ Create a GitHub **fine-grained personal access token** scoped strictly to **Only
|
|
|
53
53
|
## How it works
|
|
54
54
|
|
|
55
55
|
1. Each device incrementally pulls its own usage from Magpie's loopback API and publishes sanitized monthly snapshots into its own `<prefix>/<device-id>/` folder — one atomic commit per device, no cross-machine conflicts.
|
|
56
|
-
2. Any machine aggregates on read: combined and per-device totals, two-tone daily
|
|
56
|
+
2. Any machine aggregates on read: combined and per-device totals, two-tone token bars (hourly slots for **Today**, consecutive daily slots for **7d/30d**, active days for **All**), clickable device filters, and tabbed **Agents / Models / Providers** breakdowns. Today's local usage is bucketed by civil hour in the reporting timezone; remote devices only publish daily totals, so their contribution appears as a separate daily-only total instead of invented hours. Today keeps all 24 hourly bars while the axis labels every two hours (compact on narrow screens). Hover a bar, or focus the chart and use the arrow keys, for the same per-bucket detail. Offline devices keep their last hash-verified cached snapshot, flagged as cached, and unavailable sources never render as false zeros.
|
|
57
57
|
|
|
58
58
|
## Configuration reference
|
|
59
59
|
|
package/README.zh-CN.md
CHANGED
|
@@ -53,7 +53,7 @@ magpie plugin add /path/to/magpie-multi-usage
|
|
|
53
53
|
## 工作原理
|
|
54
54
|
|
|
55
55
|
1. 每台设备增量拉取自身用量(Magpie 回环 API),并将脱敏后的每月快照发布到仓库中自己的 `<prefix>/<device-id>/` 目录——每设备一次原子提交,互不冲突。
|
|
56
|
-
2.
|
|
56
|
+
2. 任意机器按读取聚合:合并与按设备总量、双色 Token 柱状图(**今日**按实际小时分桶,**7/30 天**为连续日期槽位,**全部**按有数据的日期)、可点击的设备筛选、**Agents / Models / Providers** 标签页明细。今日的本机用量按上报时区的自然小时分桶;远端设备只上报每日合计,因此其数据单独显示为“无小时明细的当日合计”,不会伪造小时分布。今日保留全部 24 个小时柱,横轴每两小时标注一次(窄屏使用紧凑标签)。悬停柱体,或聚焦图表后使用方向键,可查看相同的单桶明细。离线设备保留最后一次通过哈希校验的缓存快照并标记为缓存,不可用来源绝不会显示成错误的零值。
|
|
57
57
|
|
|
58
58
|
## 配置参考
|
|
59
59
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "magpie-multi-usage",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Multi-device token usage dashboard plugin for Magpie using a dedicated private GitHub repository relay (no decryption passphrase required).",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./index.mjs",
|
package/src/aggregator.mjs
CHANGED
|
@@ -129,6 +129,113 @@ export function formatLocalDateParts(timestamp, timeZone) {
|
|
|
129
129
|
};
|
|
130
130
|
}
|
|
131
131
|
|
|
132
|
+
/**
|
|
133
|
+
* Build a single cached civil-hour formatter for one chart request.
|
|
134
|
+
*/
|
|
135
|
+
function createHourFormatter(timeZone) {
|
|
136
|
+
return new Intl.DateTimeFormat("en-CA", {
|
|
137
|
+
timeZone,
|
|
138
|
+
year: "numeric",
|
|
139
|
+
month: "2-digit",
|
|
140
|
+
day: "2-digit",
|
|
141
|
+
hour: "2-digit",
|
|
142
|
+
hourCycle: "h23",
|
|
143
|
+
});
|
|
144
|
+
}
|
|
145
|
+
|
|
146
|
+
function formatHourPartsWith(formatter, timestamp) {
|
|
147
|
+
const date = timestamp instanceof Date ? timestamp : new Date(timestamp);
|
|
148
|
+
if (Number.isNaN(date.getTime())) {
|
|
149
|
+
throw new AggregatorError("INVALID_TIMESTAMP", `Invalid timestamp: ${String(timestamp)}`);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const parts = formatter.formatToParts(date);
|
|
153
|
+
const pick = (type) => parts.find((p) => p.type === type)?.value;
|
|
154
|
+
const year = pick("year");
|
|
155
|
+
const month = pick("month");
|
|
156
|
+
const day = pick("day");
|
|
157
|
+
const hourValue = pick("hour");
|
|
158
|
+
|
|
159
|
+
if (!year || !month || !day || hourValue === undefined) {
|
|
160
|
+
throw new AggregatorError("INVALID_TIMESTAMP", `Unable to format time parts for ${date.toISOString()}`);
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
// Some ICU builds render midnight as "24" even with hourCycle h23.
|
|
164
|
+
return {
|
|
165
|
+
iso: date.toISOString(),
|
|
166
|
+
day: `${year}-${month}-${day}`,
|
|
167
|
+
month: `${year}-${month}`,
|
|
168
|
+
hour: Number(hourValue) % 24,
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Format an ISO timestamp (or Date / epoch ms) into a civil wall-clock hour in
|
|
174
|
+
* the requested timezone. Hours use the 00..23 range so repeated DST hours can
|
|
175
|
+
* be combined into one named slot.
|
|
176
|
+
*/
|
|
177
|
+
export function formatLocalHourParts(timestamp, timeZone) {
|
|
178
|
+
return formatHourPartsWith(createHourFormatter(timeZone), timestamp);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function padHour(hour) {
|
|
182
|
+
return String(hour).padStart(2, "0");
|
|
183
|
+
}
|
|
184
|
+
|
|
185
|
+
/**
|
|
186
|
+
* Bucket normalized local ledger rows into the fixed 24 named wall-clock hours
|
|
187
|
+
* of one civil day. Repeated DST hours combine; a nonexistent hour simply
|
|
188
|
+
* stays empty. Rows whose calculated local date disagrees with the
|
|
189
|
+
* authoritative feed day are deliberately left out; the caller exposes them as
|
|
190
|
+
* a daily-only remainder so totals still reconcile.
|
|
191
|
+
*/
|
|
192
|
+
export function buildHourlyTrendPoints(rows = [], { day, timeZone, filterForwarded = true } = {}) {
|
|
193
|
+
if (!isValidCalendarDay(day)) {
|
|
194
|
+
throw new AggregatorError("INVALID_DAY", `Invalid YYYY-MM-DD date: ${day}`);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
const formatter = createHourFormatter(timeZone);
|
|
198
|
+
const buckets = new Map();
|
|
199
|
+
for (const row of rows) {
|
|
200
|
+
if (!row || row.day !== day) {
|
|
201
|
+
continue;
|
|
202
|
+
}
|
|
203
|
+
if (filterForwarded && row.via !== "") {
|
|
204
|
+
continue;
|
|
205
|
+
}
|
|
206
|
+
const parts = formatHourPartsWith(formatter, row.t);
|
|
207
|
+
if (parts.day !== row.day) {
|
|
208
|
+
continue;
|
|
209
|
+
}
|
|
210
|
+
if (!buckets.has(parts.hour)) {
|
|
211
|
+
buckets.set(parts.hour, createEmptyBucket());
|
|
212
|
+
}
|
|
213
|
+
addMetrics(buckets.get(parts.hour), {
|
|
214
|
+
calls: 1,
|
|
215
|
+
errors: isErrorRow(row) ? 1 : 0,
|
|
216
|
+
input: Number(row.in) || 0,
|
|
217
|
+
output: Number(row.out) || 0,
|
|
218
|
+
cacheRead: Number(row.cacheRead) || 0,
|
|
219
|
+
cacheWrite: Number(row.cacheWrite) || 0,
|
|
220
|
+
cost: Number(row.cost) || 0,
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
const points = [];
|
|
225
|
+
for (let hour = 0; hour < 24; hour += 1) {
|
|
226
|
+
const metrics = buckets.get(hour) || createEmptyBucket();
|
|
227
|
+
points.push({
|
|
228
|
+
key: `${day}T${padHour(hour)}`,
|
|
229
|
+
day,
|
|
230
|
+
hour,
|
|
231
|
+
label: `${padHour(hour)}:00`,
|
|
232
|
+
...metrics,
|
|
233
|
+
totalTokens: computeTotalTokens(metrics),
|
|
234
|
+
});
|
|
235
|
+
}
|
|
236
|
+
return points;
|
|
237
|
+
}
|
|
238
|
+
|
|
132
239
|
/**
|
|
133
240
|
* Normalize a raw Magpie feed row into a strictly non-sensitive ledger record.
|
|
134
241
|
* Strips all unapproved fields and validates calendar date/month consistency.
|
|
@@ -361,7 +468,7 @@ export function buildDeviceManifest({
|
|
|
361
468
|
deviceId,
|
|
362
469
|
displayName,
|
|
363
470
|
platform = process.platform,
|
|
364
|
-
pluginVersion = "0.
|
|
471
|
+
pluginVersion = "0.2.0",
|
|
365
472
|
revision = 1,
|
|
366
473
|
updatedAt = new Date().toISOString(),
|
|
367
474
|
snapshots = [],
|
|
@@ -500,6 +607,118 @@ function sortBreakdownEntries(map) {
|
|
|
500
607
|
.sort((a, b) => b.totalTokens - a.totalTokens || b.cost - a.cost || a.name.localeCompare(b.name));
|
|
501
608
|
}
|
|
502
609
|
|
|
610
|
+
function computeTrendAvailability({ verifiedDeviceCount, staleDeviceCount, unknownDeviceCount }) {
|
|
611
|
+
if (verifiedDeviceCount === 0) {
|
|
612
|
+
return "unavailable";
|
|
613
|
+
}
|
|
614
|
+
if (staleDeviceCount > 0 || unknownDeviceCount > 0) {
|
|
615
|
+
return "partial";
|
|
616
|
+
}
|
|
617
|
+
return "ok";
|
|
618
|
+
}
|
|
619
|
+
|
|
620
|
+
const TREND_METRIC_KEYS = ["calls", "errors", "input", "output", "cacheRead", "cacheWrite"];
|
|
621
|
+
|
|
622
|
+
function sumPointMetrics(points) {
|
|
623
|
+
const totals = createEmptyBucket();
|
|
624
|
+
for (const point of points) {
|
|
625
|
+
for (const key of TREND_METRIC_KEYS) {
|
|
626
|
+
totals[key] += Number(point[key]) || 0;
|
|
627
|
+
}
|
|
628
|
+
totals.cost += Number(point.cost) || 0;
|
|
629
|
+
}
|
|
630
|
+
totals.cost = roundCost(totals.cost);
|
|
631
|
+
return totals;
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
function hasAnyMetric(metrics) {
|
|
635
|
+
return TREND_METRIC_KEYS.some((key) => Boolean(metrics[key])) || Boolean(metrics.cost);
|
|
636
|
+
}
|
|
637
|
+
|
|
638
|
+
function subtractMetrics(source, deducted) {
|
|
639
|
+
const remainder = createEmptyBucket();
|
|
640
|
+
for (const key of TREND_METRIC_KEYS) {
|
|
641
|
+
remainder[key] = Math.max(0, (Number(source[key]) || 0) - (Number(deducted[key]) || 0));
|
|
642
|
+
}
|
|
643
|
+
remainder.cost = roundCost(Math.max(0, (Number(source.cost) || 0) - (Number(deducted.cost) || 0)));
|
|
644
|
+
return remainder;
|
|
645
|
+
}
|
|
646
|
+
|
|
647
|
+
function buildDayTrendPoint(day, bucket) {
|
|
648
|
+
return {
|
|
649
|
+
key: day,
|
|
650
|
+
day,
|
|
651
|
+
label: day.slice(5),
|
|
652
|
+
...bucket,
|
|
653
|
+
totalTokens: computeTotalTokens(bucket),
|
|
654
|
+
};
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
function buildTrendSeries({
|
|
658
|
+
range,
|
|
659
|
+
bounds,
|
|
660
|
+
timeZone,
|
|
661
|
+
filterForwarded,
|
|
662
|
+
daily,
|
|
663
|
+
dailyMap,
|
|
664
|
+
hourlyRows,
|
|
665
|
+
hasHourlySource,
|
|
666
|
+
availability,
|
|
667
|
+
}) {
|
|
668
|
+
const points = [];
|
|
669
|
+
let dailyOnly = null;
|
|
670
|
+
|
|
671
|
+
if (range === "today") {
|
|
672
|
+
if (hasHourlySource && availability !== "unavailable") {
|
|
673
|
+
for (const point of buildHourlyTrendPoints(hourlyRows, {
|
|
674
|
+
day: bounds.startDay,
|
|
675
|
+
timeZone,
|
|
676
|
+
filterForwarded,
|
|
677
|
+
})) {
|
|
678
|
+
points.push(point);
|
|
679
|
+
}
|
|
680
|
+
}
|
|
681
|
+
const dayBucket = dailyMap[bounds.startDay];
|
|
682
|
+
if (dayBucket) {
|
|
683
|
+
const remainder = subtractMetrics(dayBucket, sumPointMetrics(points));
|
|
684
|
+
if (hasAnyMetric(remainder)) {
|
|
685
|
+
dailyOnly = {
|
|
686
|
+
day: bounds.startDay,
|
|
687
|
+
...remainder,
|
|
688
|
+
totalTokens: computeTotalTokens(remainder),
|
|
689
|
+
};
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
} else if (availability !== "unavailable") {
|
|
693
|
+
if (range === "7d" || range === "30d") {
|
|
694
|
+
const slotCount = range === "7d" ? 7 : 30;
|
|
695
|
+
for (let offset = 0; offset < slotCount; offset += 1) {
|
|
696
|
+
const day = shiftCalendarDay(bounds.startDay, offset);
|
|
697
|
+
points.push(buildDayTrendPoint(day, dailyMap[day] || createEmptyBucket()));
|
|
698
|
+
}
|
|
699
|
+
} else {
|
|
700
|
+
for (const entry of daily) {
|
|
701
|
+
points.push({
|
|
702
|
+
key: entry.day,
|
|
703
|
+
day: entry.day,
|
|
704
|
+
label: entry.day.slice(5),
|
|
705
|
+
...entry,
|
|
706
|
+
});
|
|
707
|
+
}
|
|
708
|
+
}
|
|
709
|
+
}
|
|
710
|
+
|
|
711
|
+
return {
|
|
712
|
+
bucket: range === "today" ? "hour" : "day",
|
|
713
|
+
timeZone: range === "today" ? (timeZone || null) : null,
|
|
714
|
+
startDay: bounds.startDay,
|
|
715
|
+
endDay: bounds.endDay,
|
|
716
|
+
points,
|
|
717
|
+
dailyOnly,
|
|
718
|
+
availability,
|
|
719
|
+
};
|
|
720
|
+
}
|
|
721
|
+
|
|
503
722
|
/**
|
|
504
723
|
* Aggregate local and cached remote device snapshots across a date range and
|
|
505
724
|
* optional device filter.
|
|
@@ -509,6 +728,8 @@ export function aggregateDevices({
|
|
|
509
728
|
range = "7d",
|
|
510
729
|
deviceFilter = "all",
|
|
511
730
|
todayDay = formatLocalDateParts(new Date()).day,
|
|
731
|
+
timeZone,
|
|
732
|
+
filterForwarded = true,
|
|
512
733
|
} = {}) {
|
|
513
734
|
const bounds = getDateRangeBounds(range, todayDay);
|
|
514
735
|
|
|
@@ -521,6 +742,11 @@ export function aggregateDevices({
|
|
|
521
742
|
const agentMap = Object.create(null);
|
|
522
743
|
const providerMap = Object.create(null);
|
|
523
744
|
const deviceSummaries = [];
|
|
745
|
+
const hourlyRows = [];
|
|
746
|
+
let hasHourlySource = false;
|
|
747
|
+
let verifiedDeviceCount = 0;
|
|
748
|
+
let staleDeviceCount = 0;
|
|
749
|
+
let unknownDeviceCount = 0;
|
|
524
750
|
|
|
525
751
|
for (const device of devices) {
|
|
526
752
|
const deviceTotals = {
|
|
@@ -531,8 +757,26 @@ export function aggregateDevices({
|
|
|
531
757
|
let coverageLastDay = null;
|
|
532
758
|
|
|
533
759
|
const included = deviceFilter === "all" || deviceFilter === device.deviceId;
|
|
760
|
+
const verified = device.verified !== false;
|
|
761
|
+
|
|
762
|
+
if (included) {
|
|
763
|
+
if (verified) {
|
|
764
|
+
verifiedDeviceCount += 1;
|
|
765
|
+
if (device.status === "stale" || device.status === "error") {
|
|
766
|
+
staleDeviceCount += 1;
|
|
767
|
+
}
|
|
768
|
+
if (range === "today" && Array.isArray(device.hourRows)) {
|
|
769
|
+
hasHourlySource = true;
|
|
770
|
+
for (const row of device.hourRows) {
|
|
771
|
+
hourlyRows.push(row);
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
} else {
|
|
775
|
+
unknownDeviceCount += 1;
|
|
776
|
+
}
|
|
777
|
+
}
|
|
534
778
|
|
|
535
|
-
for (const snapshot of device.months || []) {
|
|
779
|
+
for (const snapshot of (verified ? device.months || [] : [])) {
|
|
536
780
|
const days = snapshot?.days || {};
|
|
537
781
|
for (const dayKey of Object.keys(days)) {
|
|
538
782
|
if (!isValidCalendarDay(dayKey)) {
|
|
@@ -625,6 +869,23 @@ export function aggregateDevices({
|
|
|
625
869
|
totalTokens: computeTotalTokens(dailyMap[day]),
|
|
626
870
|
}));
|
|
627
871
|
|
|
872
|
+
const availability = computeTrendAvailability({
|
|
873
|
+
verifiedDeviceCount,
|
|
874
|
+
staleDeviceCount,
|
|
875
|
+
unknownDeviceCount,
|
|
876
|
+
});
|
|
877
|
+
const trend = buildTrendSeries({
|
|
878
|
+
range,
|
|
879
|
+
bounds,
|
|
880
|
+
timeZone,
|
|
881
|
+
filterForwarded,
|
|
882
|
+
daily,
|
|
883
|
+
dailyMap,
|
|
884
|
+
hourlyRows,
|
|
885
|
+
hasHourlySource,
|
|
886
|
+
availability,
|
|
887
|
+
});
|
|
888
|
+
|
|
628
889
|
return {
|
|
629
890
|
range,
|
|
630
891
|
deviceFilter,
|
|
@@ -636,6 +897,14 @@ export function aggregateDevices({
|
|
|
636
897
|
},
|
|
637
898
|
devices: deviceSummaries,
|
|
638
899
|
daily,
|
|
900
|
+
trend: {
|
|
901
|
+
...trend,
|
|
902
|
+
sources: {
|
|
903
|
+
verified: verifiedDeviceCount,
|
|
904
|
+
stale: staleDeviceCount,
|
|
905
|
+
unknown: unknownDeviceCount,
|
|
906
|
+
},
|
|
907
|
+
},
|
|
639
908
|
topModels: sortBreakdownEntries(modelMap),
|
|
640
909
|
topAgents: sortBreakdownEntries(agentMap),
|
|
641
910
|
topProviders: sortBreakdownEntries(providerMap),
|
package/src/github-store.mjs
CHANGED
|
@@ -224,7 +224,7 @@ export function createGitHubRelayStore({
|
|
|
224
224
|
apiBaseUrl = DEFAULT_API_BASE_URL,
|
|
225
225
|
fetchImpl = globalThis.fetch,
|
|
226
226
|
timeoutMs = 15000,
|
|
227
|
-
pluginVersion = "0.
|
|
227
|
+
pluginVersion = "0.2.0",
|
|
228
228
|
} = {}) {
|
|
229
229
|
const normalizedRepo = normalizeRepo(repo);
|
|
230
230
|
if (!normalizedRepo) {
|
package/src/http-server.mjs
CHANGED
|
@@ -19,7 +19,7 @@ import { createSyncEngine } from "./sync-engine.mjs";
|
|
|
19
19
|
|
|
20
20
|
export const TOKEN_HEADER = "x-multi-usage-token";
|
|
21
21
|
export const DEFAULT_PORT = DEFAULT_CONFIG.port;
|
|
22
|
-
export const PLUGIN_VERSION = "0.
|
|
22
|
+
export const PLUGIN_VERSION = "0.2.0";
|
|
23
23
|
|
|
24
24
|
const MAX_JSON_BODY_BYTES = 256 * 1024;
|
|
25
25
|
const ALLOWED_RANGES = new Set(["today", "7d", "30d", "all"]);
|
|
@@ -29,6 +29,7 @@ const UI_DIR = path.join(SERVER_DIR, "ui");
|
|
|
29
29
|
const STATIC_ASSETS = Object.freeze({
|
|
30
30
|
"/app.css": { file: "app.css", contentType: "text/css; charset=utf-8", cors: false },
|
|
31
31
|
"/app.js": { file: "app.js", contentType: "application/javascript; charset=utf-8", cors: true },
|
|
32
|
+
"/dashboard-state.mjs": { file: "dashboard-state.mjs", contentType: "application/javascript; charset=utf-8", cors: true },
|
|
32
33
|
"/view-model.mjs": { file: "view-model.mjs", contentType: "application/javascript; charset=utf-8", cors: true },
|
|
33
34
|
});
|
|
34
35
|
|
package/src/sync-engine.mjs
CHANGED
|
@@ -160,7 +160,7 @@ export function createSyncEngine({
|
|
|
160
160
|
fetchImpl = globalThis.fetch,
|
|
161
161
|
apiBaseUrl,
|
|
162
162
|
gatewayBaseUrl,
|
|
163
|
-
pluginVersion = "0.
|
|
163
|
+
pluginVersion = "0.2.0",
|
|
164
164
|
timeZone,
|
|
165
165
|
now = () => Date.now(),
|
|
166
166
|
storeFactory = createGitHubRelayStore,
|
|
@@ -188,13 +188,18 @@ export function createSyncEngine({
|
|
|
188
188
|
});
|
|
189
189
|
}
|
|
190
190
|
|
|
191
|
-
async function buildLocalSnapshots({ config, identity, revision }) {
|
|
191
|
+
async function buildLocalSnapshots({ config, identity, revision, todayDay }) {
|
|
192
192
|
const months = await listLocalMonths(resolvedDataDir);
|
|
193
193
|
const snapshots = [];
|
|
194
194
|
const monthHashes = {};
|
|
195
|
+
const hourMonth = typeof todayDay === "string" && todayDay.length >= 7 ? todayDay.slice(0, 7) : null;
|
|
196
|
+
let hourRows = null;
|
|
195
197
|
|
|
196
198
|
for (const month of months) {
|
|
197
199
|
const rows = await loadLocalMonthRows(resolvedDataDir, month);
|
|
200
|
+
if (hourMonth && month === hourMonth) {
|
|
201
|
+
hourRows = rows;
|
|
202
|
+
}
|
|
198
203
|
const { snapshot, sha256 } = buildMonthlySnapshot({
|
|
199
204
|
deviceId: identity.deviceId,
|
|
200
205
|
month,
|
|
@@ -219,7 +224,7 @@ export function createSyncEngine({
|
|
|
219
224
|
snapshots,
|
|
220
225
|
});
|
|
221
226
|
|
|
222
|
-
return { snapshots, monthHashes, manifest };
|
|
227
|
+
return { snapshots, monthHashes, manifest, hourRows };
|
|
223
228
|
}
|
|
224
229
|
|
|
225
230
|
async function runIngestLocal() {
|
|
@@ -755,14 +760,21 @@ export function createSyncEngine({
|
|
|
755
760
|
const committed = await readCommittedDeviceGeneration(deviceDir);
|
|
756
761
|
|
|
757
762
|
if (committed.status !== "ok") {
|
|
763
|
+
const hadPreviousData = Boolean(
|
|
764
|
+
meta.lastSyncedAt
|
|
765
|
+
|| meta.status === "ok"
|
|
766
|
+
|| meta.status === "stale"
|
|
767
|
+
|| (meta.monthHashes && Object.keys(meta.monthHashes).length > 0),
|
|
768
|
+
);
|
|
758
769
|
remoteDevices.push({
|
|
759
770
|
deviceId,
|
|
760
771
|
displayName: typeof meta.displayName === "string" && meta.displayName ? meta.displayName : deviceId,
|
|
761
772
|
isLocal: false,
|
|
762
|
-
status:
|
|
773
|
+
status: committed.status === "corrupt" || hadPreviousData ? "error" : (meta.status || "empty"),
|
|
763
774
|
lastSyncedAt: meta.lastSyncedAt || null,
|
|
764
775
|
lastError: meta.lastError || (committed.status === "corrupt" ? committed.error : null),
|
|
765
776
|
months: [],
|
|
777
|
+
verified: false,
|
|
766
778
|
});
|
|
767
779
|
continue;
|
|
768
780
|
}
|
|
@@ -778,6 +790,7 @@ export function createSyncEngine({
|
|
|
778
790
|
lastSyncedAt: meta.lastSyncedAt || manifest.updatedAt || null,
|
|
779
791
|
lastError: meta.lastError || null,
|
|
780
792
|
months: committed.snapshots,
|
|
793
|
+
verified: true,
|
|
781
794
|
});
|
|
782
795
|
}
|
|
783
796
|
|
|
@@ -866,10 +879,13 @@ export function createSyncEngine({
|
|
|
866
879
|
? state.pushedTargets[activeTargetKey].revision
|
|
867
880
|
: 0;
|
|
868
881
|
|
|
882
|
+
const reportingTimeZone = timeZone || Intl.DateTimeFormat().resolvedOptions().timeZone || null;
|
|
883
|
+
const effectiveToday = todayDay || formatLocalDateParts(new Date(now()), reportingTimeZone).day;
|
|
869
884
|
const localBuilt = await buildLocalSnapshots({
|
|
870
885
|
config,
|
|
871
886
|
identity,
|
|
872
887
|
revision: pushRev,
|
|
888
|
+
todayDay: effectiveToday,
|
|
873
889
|
});
|
|
874
890
|
|
|
875
891
|
const localDevice = {
|
|
@@ -882,20 +898,25 @@ export function createSyncEngine({
|
|
|
882
898
|
lastSyncedAt: localSyncStatus.lastSyncedAt || state.lastLocalSyncAt || null,
|
|
883
899
|
lastError: localSyncStatus.lastError,
|
|
884
900
|
months: localBuilt.snapshots,
|
|
901
|
+
hourRows: localBuilt.hourRows || [],
|
|
902
|
+
verified: localSyncStatus.status !== "error",
|
|
885
903
|
};
|
|
886
904
|
|
|
887
905
|
const remoteDevices = await loadCachedRemoteDevices(identity.deviceId, config, state);
|
|
888
906
|
|
|
889
|
-
const effectiveToday = todayDay || formatLocalDateParts(new Date(now()), timeZone).day;
|
|
890
907
|
const aggregated = aggregateDevices({
|
|
891
908
|
devices: [localDevice, ...remoteDevices],
|
|
892
909
|
range,
|
|
893
910
|
deviceFilter,
|
|
894
911
|
todayDay: effectiveToday,
|
|
912
|
+
timeZone: reportingTimeZone,
|
|
913
|
+
filterForwarded: config.filterForwarded,
|
|
895
914
|
});
|
|
896
915
|
|
|
897
916
|
return {
|
|
898
917
|
...aggregated,
|
|
918
|
+
todayDay: effectiveToday,
|
|
919
|
+
reportingTimeZone,
|
|
899
920
|
sync: {
|
|
900
921
|
pushEnabled: config.pushEnabled,
|
|
901
922
|
repoConfigured: Boolean(config.repo),
|
package/src/ui/app.css
CHANGED
|
@@ -446,6 +446,12 @@ select:focus-visible {
|
|
|
446
446
|
background: var(--pill);
|
|
447
447
|
}
|
|
448
448
|
|
|
449
|
+
.chart .bar:focus-visible {
|
|
450
|
+
background: var(--pill);
|
|
451
|
+
outline: 2px solid var(--accent);
|
|
452
|
+
outline-offset: 2px;
|
|
453
|
+
}
|
|
454
|
+
|
|
449
455
|
.chart .bar i {
|
|
450
456
|
display: block;
|
|
451
457
|
background: var(--accent);
|
|
@@ -464,18 +470,42 @@ select:focus-visible {
|
|
|
464
470
|
font-variant-numeric: tabular-nums;
|
|
465
471
|
}
|
|
466
472
|
|
|
467
|
-
.chart .labels span {
|
|
473
|
+
.chart .labels > span {
|
|
468
474
|
flex: 1 1 0;
|
|
469
475
|
min-width: 0;
|
|
470
476
|
text-align: center;
|
|
471
477
|
white-space: nowrap;
|
|
472
478
|
}
|
|
473
479
|
|
|
474
|
-
.chart .labels span:last-child {
|
|
480
|
+
.chart .labels > span:last-child {
|
|
475
481
|
display: flex;
|
|
476
482
|
justify-content: flex-end;
|
|
477
483
|
}
|
|
478
484
|
|
|
485
|
+
.chart .labels .axis-compact {
|
|
486
|
+
display: none;
|
|
487
|
+
}
|
|
488
|
+
|
|
489
|
+
@media (max-width: 560px) {
|
|
490
|
+
.chart .labels .axis-full {
|
|
491
|
+
display: none;
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
.chart .labels .axis-compact {
|
|
495
|
+
display: inline;
|
|
496
|
+
}
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
.chart .trend-note {
|
|
500
|
+
margin-top: 5px;
|
|
501
|
+
font-size: 10.5px;
|
|
502
|
+
color: var(--muted);
|
|
503
|
+
font-variant-numeric: tabular-nums;
|
|
504
|
+
overflow: hidden;
|
|
505
|
+
text-overflow: ellipsis;
|
|
506
|
+
white-space: nowrap;
|
|
507
|
+
}
|
|
508
|
+
|
|
479
509
|
/* Section header & Finder-style .list cards */
|
|
480
510
|
.sec-head {
|
|
481
511
|
display: flex;
|
|
@@ -662,6 +692,18 @@ select:focus-visible {
|
|
|
662
692
|
font-size: 12.5px;
|
|
663
693
|
}
|
|
664
694
|
|
|
695
|
+
.sr-only {
|
|
696
|
+
position: absolute;
|
|
697
|
+
width: 1px;
|
|
698
|
+
height: 1px;
|
|
699
|
+
padding: 0;
|
|
700
|
+
margin: -1px;
|
|
701
|
+
overflow: hidden;
|
|
702
|
+
clip: rect(0, 0, 0, 0);
|
|
703
|
+
white-space: nowrap;
|
|
704
|
+
border: 0;
|
|
705
|
+
}
|
|
706
|
+
|
|
665
707
|
/* Subtle relay status footer */
|
|
666
708
|
.sync-footer {
|
|
667
709
|
margin-top: 14px;
|
|
@@ -829,7 +871,7 @@ select:focus-visible {
|
|
|
829
871
|
transition: background-color .12s;
|
|
830
872
|
}
|
|
831
873
|
|
|
832
|
-
.pill-btn:hover {
|
|
874
|
+
.pill-btn:hover:not(:disabled) {
|
|
833
875
|
background: var(--pill-hover);
|
|
834
876
|
}
|
|
835
877
|
|
|
@@ -838,7 +880,8 @@ select:focus-visible {
|
|
|
838
880
|
color: var(--accent-fg);
|
|
839
881
|
}
|
|
840
882
|
|
|
841
|
-
.pill-btn-primary:hover {
|
|
883
|
+
.pill-btn-primary:hover:not(:disabled) {
|
|
884
|
+
background: var(--accent);
|
|
842
885
|
filter: brightness(1.06);
|
|
843
886
|
}
|
|
844
887
|
|
package/src/ui/app.js
CHANGED
|
@@ -1,14 +1,25 @@
|
|
|
1
1
|
import {
|
|
2
|
+
applySummaryResult,
|
|
3
|
+
beginSummaryRequest,
|
|
4
|
+
failSummaryRequest,
|
|
5
|
+
} from "./dashboard-state.mjs";
|
|
6
|
+
import {
|
|
7
|
+
buildTrendAxisModel,
|
|
2
8
|
extractDeviceWarnings,
|
|
3
9
|
formatCompactTokens,
|
|
4
10
|
formatCoverageWindow,
|
|
5
11
|
formatExactNumber,
|
|
6
12
|
formatPercent,
|
|
7
13
|
formatTimestamp,
|
|
14
|
+
formatTrendPointTitle,
|
|
8
15
|
formatUsd,
|
|
16
|
+
isUnverifiedEmptyTrendPoint,
|
|
9
17
|
resolveLang,
|
|
10
18
|
statusLabel,
|
|
19
|
+
summarySelectionKey,
|
|
11
20
|
t,
|
|
21
|
+
trendFocusTarget,
|
|
22
|
+
trendLabelEvery,
|
|
12
23
|
} from "./view-model.mjs";
|
|
13
24
|
|
|
14
25
|
const TOKEN_HEADER = "X-Multi-Usage-Token";
|
|
@@ -30,6 +41,13 @@ const state = {
|
|
|
30
41
|
breakdownTab: "agents",
|
|
31
42
|
loading: false,
|
|
32
43
|
summary: null,
|
|
44
|
+
summarySelection: null,
|
|
45
|
+
chartStale: false,
|
|
46
|
+
requestError: null,
|
|
47
|
+
trendFocusIndex: 0,
|
|
48
|
+
deviceChoices: [],
|
|
49
|
+
pendingSelection: null,
|
|
50
|
+
sync: null,
|
|
33
51
|
config: null,
|
|
34
52
|
clearTokenRequested: false,
|
|
35
53
|
requestGen: 0,
|
|
@@ -152,6 +170,8 @@ function renderStaticText() {
|
|
|
152
170
|
document.getElementById("devices-heading").textContent = t(state.lang, "devicesHeading");
|
|
153
171
|
document.getElementById("devices-meta").textContent = t(state.lang, "devicesHint");
|
|
154
172
|
document.getElementById("breakdown-meta").textContent = t(state.lang, "sortedByTokens");
|
|
173
|
+
document.getElementById("trend-section").setAttribute("aria-label", t(state.lang, "trendHeading"));
|
|
174
|
+
document.getElementById("trend-keyboard-hint").textContent = t(state.lang, "trendKeyboardHint");
|
|
155
175
|
|
|
156
176
|
document.getElementById("drawer-title").textContent = t(state.lang, "drawerTitle");
|
|
157
177
|
document.getElementById("drawer-close").setAttribute("aria-label", t(state.lang, "close"));
|
|
@@ -259,6 +279,13 @@ function renderBanners(summary) {
|
|
|
259
279
|
const box = document.getElementById("banners");
|
|
260
280
|
box.replaceChildren();
|
|
261
281
|
|
|
282
|
+
if (state.requestError) {
|
|
283
|
+
const err = el("div", "banner banner-warn");
|
|
284
|
+
err.appendChild(el("span", "dot dot-error"));
|
|
285
|
+
err.appendChild(el("span", "", state.requestError));
|
|
286
|
+
box.appendChild(err);
|
|
287
|
+
}
|
|
288
|
+
|
|
262
289
|
if (summary.sync && !summary.sync.repoConfigured) {
|
|
263
290
|
const info = el("div", "banner banner-info");
|
|
264
291
|
info.appendChild(el("span", "dot dot-ok"));
|
|
@@ -326,35 +353,108 @@ function renderKpis(summary) {
|
|
|
326
353
|
}
|
|
327
354
|
}
|
|
328
355
|
|
|
356
|
+
function legacyTrend(summary) {
|
|
357
|
+
const daily = summary.daily || [];
|
|
358
|
+
return {
|
|
359
|
+
bucket: "day",
|
|
360
|
+
points: daily.map((entry) => ({
|
|
361
|
+
...entry,
|
|
362
|
+
key: entry.day,
|
|
363
|
+
label: typeof entry.day === "string" ? entry.day.slice(5) : String(entry.day || ""),
|
|
364
|
+
})),
|
|
365
|
+
dailyOnly: null,
|
|
366
|
+
availability: "ok",
|
|
367
|
+
};
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
function appendDailyOnlyNote(container, dailyOnly) {
|
|
371
|
+
if (!dailyOnly) {
|
|
372
|
+
return;
|
|
373
|
+
}
|
|
374
|
+
const text = [
|
|
375
|
+
t(state.lang, "trendDailyOnly"),
|
|
376
|
+
dailyOnly.day || "",
|
|
377
|
+
`${formatCompactTokens(dailyOnly.totalTokens)} ${t(state.lang, "tokensUnit")}`,
|
|
378
|
+
formatCallsLabel(dailyOnly.calls),
|
|
379
|
+
formatUsd(dailyOnly.cost),
|
|
380
|
+
].filter(Boolean).join(" · ");
|
|
381
|
+
container.appendChild(el("div", "trend-note", text));
|
|
382
|
+
}
|
|
383
|
+
|
|
329
384
|
function renderTrendChart(summary) {
|
|
330
385
|
const container = document.getElementById("trend-container");
|
|
331
386
|
const readout = document.getElementById("trend-readout");
|
|
332
387
|
const peakEl = document.getElementById("trend-peak");
|
|
333
388
|
container.replaceChildren();
|
|
334
389
|
|
|
335
|
-
const
|
|
336
|
-
|
|
337
|
-
|
|
390
|
+
const trend = summary.trend && Array.isArray(summary.trend.points)
|
|
391
|
+
? summary.trend
|
|
392
|
+
: legacyTrend(summary);
|
|
393
|
+
const points = trend.points || [];
|
|
394
|
+
const dailyOnly = trend.dailyOnly || null;
|
|
395
|
+
const availability = trend.availability || "ok";
|
|
396
|
+
|
|
397
|
+
const notices = [];
|
|
398
|
+
if (state.chartStale) {
|
|
399
|
+
notices.push(t(state.lang, "trendStale"));
|
|
400
|
+
}
|
|
401
|
+
if (availability === "partial") {
|
|
402
|
+
notices.push(t(state.lang, "trendPartial"));
|
|
403
|
+
}
|
|
404
|
+
const noticeText = notices.join(" · ");
|
|
405
|
+
const withNotices = (text) => (noticeText ? `${noticeText} · ${text}` : text);
|
|
406
|
+
|
|
407
|
+
if (availability === "unavailable") {
|
|
408
|
+
readout.textContent = noticeText;
|
|
338
409
|
peakEl.textContent = "";
|
|
339
|
-
container.appendChild(el("div", "empty-state", t(state.lang, "
|
|
410
|
+
container.appendChild(el("div", "empty-state", t(state.lang, "trendUnavailable")));
|
|
340
411
|
return;
|
|
341
412
|
}
|
|
342
413
|
|
|
343
|
-
|
|
414
|
+
if (points.length === 0) {
|
|
415
|
+
readout.textContent = noticeText;
|
|
416
|
+
peakEl.textContent = "";
|
|
417
|
+
const message = trend.bucket === "hour" && dailyOnly
|
|
418
|
+
? t(state.lang, "trendNoHourly")
|
|
419
|
+
: t(state.lang, "trendEmpty");
|
|
420
|
+
container.appendChild(el("div", "empty-state", message));
|
|
421
|
+
appendDailyOnlyNote(container, dailyOnly);
|
|
422
|
+
return;
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
const defaultReadout = withNotices(t(state.lang, "trendHint"));
|
|
344
426
|
readout.textContent = defaultReadout;
|
|
345
427
|
|
|
346
|
-
const peak =
|
|
428
|
+
const peak = points.reduce((max, point) => Math.max(max, Number(point.totalTokens) || 0), 0);
|
|
347
429
|
const scalePeak = Math.max(1, peak);
|
|
348
430
|
peakEl.textContent = formatCompactTokens(peak);
|
|
349
431
|
|
|
350
432
|
const bars = el("div", "bars");
|
|
433
|
+
bars.setAttribute("role", "group");
|
|
434
|
+
bars.setAttribute("aria-label", t(state.lang, "trendHeading"));
|
|
435
|
+
bars.setAttribute("aria-describedby", "trend-keyboard-hint");
|
|
351
436
|
const labels = el("div", "labels");
|
|
352
|
-
const n =
|
|
353
|
-
const every =
|
|
437
|
+
const n = points.length;
|
|
438
|
+
const every = trendLabelEvery(n);
|
|
439
|
+
const axisLabels = buildTrendAxisModel(points, { bucket: trend.bucket, every });
|
|
440
|
+
let activeIndex = Number.isInteger(state.trendFocusIndex) && state.trendFocusIndex >= 0 && state.trendFocusIndex < n
|
|
441
|
+
? state.trendFocusIndex
|
|
442
|
+
: 0;
|
|
443
|
+
state.trendFocusIndex = activeIndex;
|
|
444
|
+
const barNodes = [];
|
|
445
|
+
const detailTexts = [];
|
|
446
|
+
|
|
447
|
+
const applyActiveBar = (nextIndex) => {
|
|
448
|
+
activeIndex = nextIndex;
|
|
449
|
+
state.trendFocusIndex = nextIndex;
|
|
450
|
+
barNodes.forEach((node, nodeIndex) => {
|
|
451
|
+
node.tabIndex = nodeIndex === nextIndex ? 0 : -1;
|
|
452
|
+
});
|
|
453
|
+
};
|
|
354
454
|
|
|
355
|
-
|
|
356
|
-
const total = Number(
|
|
357
|
-
const output = Number(
|
|
455
|
+
points.forEach((point, idx) => {
|
|
456
|
+
const total = Number(point.totalTokens) || 0;
|
|
457
|
+
const output = Number(point.output) || 0;
|
|
358
458
|
const promptPart = Math.max(0, total - output);
|
|
359
459
|
|
|
360
460
|
const bar = el("div", "bar");
|
|
@@ -365,23 +465,66 @@ function renderTrendChart(summary) {
|
|
|
365
465
|
bar.appendChild(outEl);
|
|
366
466
|
bar.appendChild(inEl);
|
|
367
467
|
|
|
368
|
-
const
|
|
468
|
+
const title = formatTrendPointTitle(point);
|
|
469
|
+
const summaryText = isUnverifiedEmptyTrendPoint(point, availability)
|
|
470
|
+
? `${title} · ${t(state.lang, "trendNoVerifiedPoint")}`
|
|
471
|
+
: `${title} · ${formatCompactTokens(total)} ${t(state.lang, "tokensUnit")} · ${formatCallsLabel(point.calls)} · ${formatUsd(point.cost)}`;
|
|
369
472
|
bar.title = summaryText;
|
|
473
|
+
barNodes.push(bar);
|
|
474
|
+
detailTexts.push(summaryText);
|
|
475
|
+
bars.appendChild(bar);
|
|
476
|
+
|
|
477
|
+
const axis = axisLabels[idx];
|
|
478
|
+
const labelNode = el("span");
|
|
479
|
+
if (axis.show) {
|
|
480
|
+
if (axis.compactLabel && axis.compactLabel !== axis.fullLabel) {
|
|
481
|
+
labelNode.appendChild(el("span", "axis-full", axis.fullLabel));
|
|
482
|
+
labelNode.appendChild(el("span", "axis-compact", axis.compactLabel));
|
|
483
|
+
} else {
|
|
484
|
+
labelNode.textContent = axis.fullLabel;
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
labels.appendChild(labelNode);
|
|
488
|
+
});
|
|
489
|
+
|
|
490
|
+
barNodes.forEach((bar, idx) => {
|
|
491
|
+
bar.tabIndex = idx === activeIndex ? 0 : -1;
|
|
492
|
+
bar.setAttribute("role", "img");
|
|
493
|
+
bar.setAttribute("aria-label", detailTexts[idx]);
|
|
494
|
+
bar.setAttribute("aria-keyshortcuts", "ArrowLeft ArrowRight ArrowUp ArrowDown Home End");
|
|
495
|
+
bar.addEventListener("focus", () => {
|
|
496
|
+
applyActiveBar(idx);
|
|
497
|
+
readout.textContent = withNotices(detailTexts[idx]);
|
|
498
|
+
});
|
|
499
|
+
bar.addEventListener("blur", (event) => {
|
|
500
|
+
if (event.relatedTarget && bars.contains(event.relatedTarget)) {
|
|
501
|
+
return;
|
|
502
|
+
}
|
|
503
|
+
readout.textContent = defaultReadout;
|
|
504
|
+
});
|
|
505
|
+
bar.addEventListener("keydown", (event) => {
|
|
506
|
+
const target = trendFocusTarget(idx, event.key, n);
|
|
507
|
+
if (target === null) {
|
|
508
|
+
return;
|
|
509
|
+
}
|
|
510
|
+
event.preventDefault();
|
|
511
|
+
applyActiveBar(target);
|
|
512
|
+
barNodes[target].focus();
|
|
513
|
+
});
|
|
370
514
|
bar.addEventListener("mouseenter", () => {
|
|
371
|
-
readout.textContent =
|
|
515
|
+
readout.textContent = withNotices(detailTexts[idx]);
|
|
372
516
|
});
|
|
373
517
|
bar.addEventListener("mouseleave", () => {
|
|
374
|
-
|
|
518
|
+
const focusedIndex = barNodes.indexOf(document.activeElement);
|
|
519
|
+
readout.textContent = focusedIndex >= 0
|
|
520
|
+
? withNotices(detailTexts[focusedIndex])
|
|
521
|
+
: defaultReadout;
|
|
375
522
|
});
|
|
376
|
-
bars.appendChild(bar);
|
|
377
|
-
|
|
378
|
-
const shortDay = typeof d.day === "string" && d.day.length === 10 ? d.day.slice(5) : String(d.day || "");
|
|
379
|
-
const showLast = idx === n - 1 && (n - 1) % every >= every / 2;
|
|
380
|
-
labels.appendChild(el("span", "", idx % every === 0 || showLast ? shortDay : ""));
|
|
381
523
|
});
|
|
382
524
|
|
|
383
525
|
container.appendChild(bars);
|
|
384
526
|
container.appendChild(labels);
|
|
527
|
+
appendDailyOnlyNote(container, dailyOnly);
|
|
385
528
|
}
|
|
386
529
|
|
|
387
530
|
function renderDevicesList(summary) {
|
|
@@ -566,6 +709,13 @@ function renderDashboard() {
|
|
|
566
709
|
if (!summary) {
|
|
567
710
|
return;
|
|
568
711
|
}
|
|
712
|
+
if (state.summarySelection !== summarySelectionKey(state.range, state.device)) {
|
|
713
|
+
state.summary = null;
|
|
714
|
+
state.summarySelection = null;
|
|
715
|
+
state.chartStale = false;
|
|
716
|
+
renderSummaryPlaceholder("trendUnavailable", "summaryUnavailable");
|
|
717
|
+
return;
|
|
718
|
+
}
|
|
569
719
|
|
|
570
720
|
renderHeaderCost(summary);
|
|
571
721
|
renderDeviceTabs(summary.devices || []);
|
|
@@ -577,6 +727,55 @@ function renderDashboard() {
|
|
|
577
727
|
renderSyncFooter(summary);
|
|
578
728
|
}
|
|
579
729
|
|
|
730
|
+
function renderSummaryPlaceholder(kpiKey, chartKey) {
|
|
731
|
+
document.getElementById("usage-cost").replaceChildren();
|
|
732
|
+
renderDeviceTabs(state.deviceChoices || []);
|
|
733
|
+
renderBanners({ devices: [], sync: state.sync || null });
|
|
734
|
+
document.getElementById("kpi-strip").replaceChildren(el("div", "empty-state", t(state.lang, kpiKey)));
|
|
735
|
+
const container = document.getElementById("trend-container");
|
|
736
|
+
container.replaceChildren(el("div", "empty-state", t(state.lang, chartKey)));
|
|
737
|
+
document.getElementById("trend-readout").textContent = "";
|
|
738
|
+
document.getElementById("trend-peak").textContent = "";
|
|
739
|
+
document.getElementById("devices-list").replaceChildren(el("div", "empty-state", t(state.lang, "noRows")));
|
|
740
|
+
document.getElementById("breakdown-list").replaceChildren(el("div", "empty-state", t(state.lang, "noRows")));
|
|
741
|
+
document.getElementById("sync-footer").replaceChildren();
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
function renderSummaryPending() {
|
|
745
|
+
renderSummaryPlaceholder("trendLoading", "trendLoading");
|
|
746
|
+
}
|
|
747
|
+
|
|
748
|
+
function renderSummaryUnavailable() {
|
|
749
|
+
renderSummaryPlaceholder("summaryUnavailable", "trendUnavailable");
|
|
750
|
+
}
|
|
751
|
+
|
|
752
|
+
function handleSummarySuccess(gen, reqRange, reqDevice, result) {
|
|
753
|
+
if (!applySummaryResult(state, {
|
|
754
|
+
gen,
|
|
755
|
+
range: reqRange,
|
|
756
|
+
device: reqDevice,
|
|
757
|
+
result,
|
|
758
|
+
})) {
|
|
759
|
+
return;
|
|
760
|
+
}
|
|
761
|
+
state.sync = result.sync || state.sync || null;
|
|
762
|
+
renderDashboard();
|
|
763
|
+
}
|
|
764
|
+
|
|
765
|
+
function handleSummaryFailure(gen, reqRange, reqDevice, message) {
|
|
766
|
+
const outcome = failSummaryRequest(state, {
|
|
767
|
+
gen,
|
|
768
|
+
range: reqRange,
|
|
769
|
+
device: reqDevice,
|
|
770
|
+
message,
|
|
771
|
+
});
|
|
772
|
+
if (outcome === "retained") {
|
|
773
|
+
renderDashboard();
|
|
774
|
+
} else if (outcome === "unavailable") {
|
|
775
|
+
renderSummaryUnavailable();
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
|
|
580
779
|
function setFeedback(text, kind = "ok") {
|
|
581
780
|
const box = document.getElementById("drawer-feedback");
|
|
582
781
|
if (!text) {
|
|
@@ -668,6 +867,10 @@ async function syncLocalOnBoot() {
|
|
|
668
867
|
const gen = ++state.requestGen;
|
|
669
868
|
const reqRange = state.range;
|
|
670
869
|
const reqDevice = state.device;
|
|
870
|
+
const { invalidated } = beginSummaryRequest(state, { range: reqRange, device: reqDevice, gen });
|
|
871
|
+
if (invalidated) {
|
|
872
|
+
renderSummaryPending();
|
|
873
|
+
}
|
|
671
874
|
try {
|
|
672
875
|
const result = await apiFetch("./api/refresh", {
|
|
673
876
|
method: "POST",
|
|
@@ -678,12 +881,11 @@ async function syncLocalOnBoot() {
|
|
|
678
881
|
pull: false,
|
|
679
882
|
},
|
|
680
883
|
});
|
|
681
|
-
if (
|
|
682
|
-
|
|
683
|
-
renderDashboard();
|
|
884
|
+
if (result.summary) {
|
|
885
|
+
handleSummarySuccess(gen, reqRange, reqDevice, result.summary);
|
|
684
886
|
}
|
|
685
|
-
} catch {
|
|
686
|
-
|
|
887
|
+
} catch (err) {
|
|
888
|
+
handleSummaryFailure(gen, reqRange, reqDevice, err.message);
|
|
687
889
|
} finally {
|
|
688
890
|
state.loading = false;
|
|
689
891
|
renderRefreshButton();
|
|
@@ -694,20 +896,16 @@ async function loadSummary() {
|
|
|
694
896
|
const gen = ++state.requestGen;
|
|
695
897
|
const reqRange = state.range;
|
|
696
898
|
const reqDevice = state.device;
|
|
899
|
+
const { invalidated } = beginSummaryRequest(state, { range: reqRange, device: reqDevice, gen });
|
|
900
|
+
if (invalidated) {
|
|
901
|
+
renderSummaryPending();
|
|
902
|
+
}
|
|
697
903
|
try {
|
|
698
904
|
const qs = new URLSearchParams({ range: reqRange, device: reqDevice });
|
|
699
905
|
const result = await apiFetch(`./api/summary?${qs.toString()}`);
|
|
700
|
-
|
|
701
|
-
return;
|
|
702
|
-
}
|
|
703
|
-
state.summary = result;
|
|
704
|
-
renderDashboard();
|
|
906
|
+
handleSummarySuccess(gen, reqRange, reqDevice, result);
|
|
705
907
|
} catch (err) {
|
|
706
|
-
|
|
707
|
-
return;
|
|
708
|
-
}
|
|
709
|
-
const banners = document.getElementById("banners");
|
|
710
|
-
banners.replaceChildren(el("div", "banner banner-warn", err.message));
|
|
908
|
+
handleSummaryFailure(gen, reqRange, reqDevice, err.message);
|
|
711
909
|
}
|
|
712
910
|
}
|
|
713
911
|
|
|
@@ -720,18 +918,20 @@ async function triggerRefresh() {
|
|
|
720
918
|
const gen = ++state.requestGen;
|
|
721
919
|
const reqRange = state.range;
|
|
722
920
|
const reqDevice = state.device;
|
|
921
|
+
const { invalidated } = beginSummaryRequest(state, { range: reqRange, device: reqDevice, gen });
|
|
922
|
+
if (invalidated) {
|
|
923
|
+
renderSummaryPending();
|
|
924
|
+
}
|
|
723
925
|
try {
|
|
724
926
|
const result = await apiFetch("./api/refresh", {
|
|
725
927
|
method: "POST",
|
|
726
928
|
body: { range: reqRange, device: reqDevice },
|
|
727
929
|
});
|
|
728
|
-
if (
|
|
729
|
-
|
|
730
|
-
renderDashboard();
|
|
930
|
+
if (result.summary) {
|
|
931
|
+
handleSummarySuccess(gen, reqRange, reqDevice, result.summary);
|
|
731
932
|
}
|
|
732
933
|
} catch (err) {
|
|
733
|
-
|
|
734
|
-
banners.replaceChildren(el("div", "banner banner-warn", err.message));
|
|
934
|
+
handleSummaryFailure(gen, reqRange, reqDevice, err.message);
|
|
735
935
|
} finally {
|
|
736
936
|
state.loading = false;
|
|
737
937
|
renderRefreshButton();
|
|
@@ -794,17 +994,32 @@ async function handleSaveSettings(event) {
|
|
|
794
994
|
btn.disabled = true;
|
|
795
995
|
btn.textContent = t(state.lang, "saving");
|
|
796
996
|
setFeedback("");
|
|
997
|
+
let refreshGen = null;
|
|
998
|
+
let refreshRange = null;
|
|
999
|
+
let refreshDevice = null;
|
|
797
1000
|
try {
|
|
798
1001
|
const payload = readFormPayload();
|
|
799
1002
|
const saved = await apiFetch("./api/config", { method: "POST", body: payload });
|
|
800
1003
|
populateSettingsForm(saved);
|
|
1004
|
+
|
|
1005
|
+
refreshRange = state.range;
|
|
1006
|
+
refreshDevice = state.device;
|
|
1007
|
+
refreshGen = ++state.requestGen;
|
|
1008
|
+
const { invalidated } = beginSummaryRequest(state, {
|
|
1009
|
+
range: refreshRange,
|
|
1010
|
+
device: refreshDevice,
|
|
1011
|
+
gen: refreshGen,
|
|
1012
|
+
});
|
|
1013
|
+
if (invalidated) {
|
|
1014
|
+
renderSummaryPending();
|
|
1015
|
+
}
|
|
1016
|
+
|
|
801
1017
|
const refreshed = await apiFetch("./api/refresh", {
|
|
802
1018
|
method: "POST",
|
|
803
|
-
body: { range:
|
|
1019
|
+
body: { range: refreshRange, device: refreshDevice },
|
|
804
1020
|
});
|
|
805
1021
|
if (refreshed.summary) {
|
|
806
|
-
|
|
807
|
-
renderDashboard();
|
|
1022
|
+
handleSummarySuccess(refreshGen, refreshRange, refreshDevice, refreshed.summary);
|
|
808
1023
|
}
|
|
809
1024
|
const syncErrors = [
|
|
810
1025
|
refreshed.local?.error,
|
|
@@ -817,6 +1032,9 @@ async function handleSaveSettings(event) {
|
|
|
817
1032
|
setFeedback(t(state.lang, "savedSuccess"), "ok");
|
|
818
1033
|
}
|
|
819
1034
|
} catch (err) {
|
|
1035
|
+
if (refreshGen !== null) {
|
|
1036
|
+
handleSummaryFailure(refreshGen, refreshRange, refreshDevice, err.message);
|
|
1037
|
+
}
|
|
820
1038
|
setFeedback(err.message, "err");
|
|
821
1039
|
} finally {
|
|
822
1040
|
btn.disabled = false;
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Pure UI request-lifecycle helpers for the dashboard. Keeping the
|
|
3
|
+
* selection/race logic here makes pending replacement, late responses,
|
|
4
|
+
* same-selection last-good retention, and navigation recovery executable in
|
|
5
|
+
* Node without a browser DOM.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { summarySelectionKey } from "./view-model.mjs";
|
|
9
|
+
|
|
10
|
+
const SUMMARY_DEVICE_FIELDS = ["deviceId", "displayName", "status", "isLocal"];
|
|
11
|
+
|
|
12
|
+
export function formatDayInTimeZone(value, timeZone) {
|
|
13
|
+
const date = value instanceof Date ? value : new Date(value);
|
|
14
|
+
if (Number.isNaN(date.getTime())) {
|
|
15
|
+
return null;
|
|
16
|
+
}
|
|
17
|
+
try {
|
|
18
|
+
return new Intl.DateTimeFormat("en-CA", {
|
|
19
|
+
timeZone,
|
|
20
|
+
year: "numeric",
|
|
21
|
+
month: "2-digit",
|
|
22
|
+
day: "2-digit",
|
|
23
|
+
}).format(date);
|
|
24
|
+
} catch {
|
|
25
|
+
return null;
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export function summaryChartDay(summary) {
|
|
30
|
+
const trendEnd = summary?.trend?.endDay;
|
|
31
|
+
if (typeof trendEnd === "string" && trendEnd) {
|
|
32
|
+
return trendEnd;
|
|
33
|
+
}
|
|
34
|
+
const boundsEnd = summary?.bounds?.endDay;
|
|
35
|
+
return typeof boundsEnd === "string" && boundsEnd ? boundsEnd : null;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
/**
|
|
39
|
+
* All-history charts have no bounded end day. Finite ranges can be reused only
|
|
40
|
+
* in the server-reported timezone, so a browser in a different host timezone
|
|
41
|
+
* cannot mislabel yesterday's chart as today's.
|
|
42
|
+
*/
|
|
43
|
+
export function isSummaryChartCurrent(summary, now = new Date()) {
|
|
44
|
+
const chartDay = summaryChartDay(summary);
|
|
45
|
+
if (!chartDay) {
|
|
46
|
+
return true;
|
|
47
|
+
}
|
|
48
|
+
const zone = typeof summary?.reportingTimeZone === "string"
|
|
49
|
+
? summary.reportingTimeZone.trim()
|
|
50
|
+
: "";
|
|
51
|
+
if (!zone) {
|
|
52
|
+
return false;
|
|
53
|
+
}
|
|
54
|
+
return formatDayInTimeZone(now, zone) === chartDay;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function selectDeviceChoices(devices = []) {
|
|
58
|
+
return devices
|
|
59
|
+
.filter((device) => device && typeof device.deviceId === "string" && device.deviceId)
|
|
60
|
+
.map((device) => {
|
|
61
|
+
const choice = {};
|
|
62
|
+
for (const field of SUMMARY_DEVICE_FIELDS) {
|
|
63
|
+
choice[field] = device[field];
|
|
64
|
+
}
|
|
65
|
+
choice.displayName = typeof choice.displayName === "string" && choice.displayName
|
|
66
|
+
? choice.displayName
|
|
67
|
+
: choice.deviceId;
|
|
68
|
+
choice.status = typeof choice.status === "string" && choice.status ? choice.status : "empty";
|
|
69
|
+
choice.isLocal = Boolean(choice.isLocal);
|
|
70
|
+
return choice;
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export function beginSummaryRequest(state, { range, device, gen }) {
|
|
75
|
+
state.requestGen = gen;
|
|
76
|
+
const key = summarySelectionKey(range, device);
|
|
77
|
+
state.pendingSelection = key;
|
|
78
|
+
state.requestError = null;
|
|
79
|
+
|
|
80
|
+
if (state.summary && state.summarySelection !== key) {
|
|
81
|
+
state.summary = null;
|
|
82
|
+
state.summarySelection = null;
|
|
83
|
+
state.chartStale = false;
|
|
84
|
+
return { key, invalidated: true };
|
|
85
|
+
}
|
|
86
|
+
return { key, invalidated: false };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function isCurrentSummaryRequest(state, { gen, range, device }) {
|
|
90
|
+
return state.requestGen === gen
|
|
91
|
+
&& state.range === range
|
|
92
|
+
&& state.device === device
|
|
93
|
+
&& state.pendingSelection === summarySelectionKey(range, device);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
export function applySummaryResult(state, { gen, range, device, result }) {
|
|
97
|
+
if (!result || !isCurrentSummaryRequest(state, { gen, range, device })) {
|
|
98
|
+
return false;
|
|
99
|
+
}
|
|
100
|
+
state.summary = result;
|
|
101
|
+
state.summarySelection = summarySelectionKey(range, device);
|
|
102
|
+
state.chartStale = false;
|
|
103
|
+
state.requestError = null;
|
|
104
|
+
state.pendingSelection = null;
|
|
105
|
+
state.deviceChoices = selectDeviceChoices(result.devices || []);
|
|
106
|
+
return true;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/**
|
|
110
|
+
* Returns "retained" when the previous chart is still for this exact selection
|
|
111
|
+
* and its chart day is still current, "unavailable" when the chart must be
|
|
112
|
+
* dropped, and "ignored" for a late response from a superseded request.
|
|
113
|
+
*/
|
|
114
|
+
export function failSummaryRequest(state, { gen, range, device, message, now = new Date() }) {
|
|
115
|
+
if (!isCurrentSummaryRequest(state, { gen, range, device })) {
|
|
116
|
+
return "ignored";
|
|
117
|
+
}
|
|
118
|
+
state.pendingSelection = null;
|
|
119
|
+
state.requestError = message;
|
|
120
|
+
const key = summarySelectionKey(range, device);
|
|
121
|
+
|
|
122
|
+
if (state.summary && state.summarySelection === key && isSummaryChartCurrent(state.summary, now)) {
|
|
123
|
+
state.chartStale = true;
|
|
124
|
+
return "retained";
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
state.summary = null;
|
|
128
|
+
state.summarySelection = null;
|
|
129
|
+
state.chartStale = false;
|
|
130
|
+
return "unavailable";
|
|
131
|
+
}
|
package/src/ui/index.html
CHANGED
|
@@ -36,11 +36,12 @@
|
|
|
36
36
|
|
|
37
37
|
<section id="kpi-strip" class="stats" aria-label="Usage overview"></section>
|
|
38
38
|
|
|
39
|
-
<section class="chart" aria-label="
|
|
39
|
+
<section id="trend-section" class="chart" aria-label="Token activity">
|
|
40
40
|
<div class="chart-top">
|
|
41
41
|
<span id="trend-readout" class="chart-readout"></span>
|
|
42
42
|
<span id="trend-peak" class="peak"></span>
|
|
43
43
|
</div>
|
|
44
|
+
<span id="trend-keyboard-hint" class="sr-only"></span>
|
|
44
45
|
<div id="trend-container"></div>
|
|
45
46
|
</section>
|
|
46
47
|
|
package/src/ui/view-model.mjs
CHANGED
|
@@ -56,9 +56,19 @@ export const MESSAGES = Object.freeze({
|
|
|
56
56
|
statusStale: "Cached",
|
|
57
57
|
statusError: "Error",
|
|
58
58
|
statusEmpty: "No data",
|
|
59
|
-
trendHeading: "
|
|
59
|
+
trendHeading: "Token activity",
|
|
60
60
|
trendHint: "Hover a bar for details · light prompt/cache, solid output",
|
|
61
61
|
trendEmpty: "No usage recorded in the selected range.",
|
|
62
|
+
trendUnavailable: "Chart unavailable: no verified data for this selection.",
|
|
63
|
+
trendNoHourly: "Hourly detail is unavailable for the selected devices; showing the daily total.",
|
|
64
|
+
trendPartial: "Some sources are cached or unavailable; bars show verified values only.",
|
|
65
|
+
trendStale: "Showing the last successful data for this selection.",
|
|
66
|
+
trendDailyOnly: "Daily total without hourly detail",
|
|
67
|
+
trendNoVerifiedPoint: "No verified usage recorded in this bucket",
|
|
68
|
+
tokensUnit: "tokens",
|
|
69
|
+
summaryUnavailable: "Summary unavailable for this selection.",
|
|
70
|
+
trendLoading: "Loading usage…",
|
|
71
|
+
trendKeyboardHint: "Use the arrow keys, Home, or End to move between time buckets; press Tab to leave the chart.",
|
|
62
72
|
legendInput: "Input",
|
|
63
73
|
legendOutput: "Output",
|
|
64
74
|
legendCacheRead: "Cache read",
|
|
@@ -158,9 +168,19 @@ export const MESSAGES = Object.freeze({
|
|
|
158
168
|
statusStale: "缓存",
|
|
159
169
|
statusError: "异常",
|
|
160
170
|
statusEmpty: "无数据",
|
|
161
|
-
trendHeading: "
|
|
162
|
-
trendHint: "
|
|
171
|
+
trendHeading: "Token 趋势",
|
|
172
|
+
trendHint: "悬停柱体查看明细 · 浅色为输入/缓存,深色为输出",
|
|
163
173
|
trendEmpty: "所选范围内暂无用量数据。",
|
|
174
|
+
trendUnavailable: "图表不可用:当前选择没有已校验的数据。",
|
|
175
|
+
trendNoHourly: "所选设备没有小时级明细,以下显示当日总量。",
|
|
176
|
+
trendPartial: "部分数据来源为缓存或不可用,图表仅展示已校验的数据。",
|
|
177
|
+
trendStale: "当前显示该选择上次成功获取的数据。",
|
|
178
|
+
trendDailyOnly: "无小时明细的当日合计",
|
|
179
|
+
trendNoVerifiedPoint: "该时间段没有已校验的用量",
|
|
180
|
+
tokensUnit: "Token",
|
|
181
|
+
summaryUnavailable: "当前选择的汇总数据不可用。",
|
|
182
|
+
trendLoading: "正在加载用量…",
|
|
183
|
+
trendKeyboardHint: "使用方向键、Home 或 End 在各时间桶之间移动;按 Tab 离开图表。",
|
|
164
184
|
legendInput: "输入",
|
|
165
185
|
legendOutput: "输出",
|
|
166
186
|
legendCacheRead: "缓存读取",
|
|
@@ -408,3 +428,145 @@ export function buildDailyChartModel(daily = [], { width = 880, height = 224 } =
|
|
|
408
428
|
bars,
|
|
409
429
|
};
|
|
410
430
|
}
|
|
431
|
+
|
|
432
|
+
/**
|
|
433
|
+
* Format a trend point's compact axis label. Hour buckets use 24-hour labels;
|
|
434
|
+
* day buckets use the backend-provided MM-DD label or the day suffix.
|
|
435
|
+
*/
|
|
436
|
+
export function formatTrendPointLabel(point) {
|
|
437
|
+
if (!point || typeof point !== "object") {
|
|
438
|
+
return "";
|
|
439
|
+
}
|
|
440
|
+
if (Number.isInteger(point.hour) && point.hour >= 0 && point.hour <= 23) {
|
|
441
|
+
return `${String(point.hour).padStart(2, "0")}:00`;
|
|
442
|
+
}
|
|
443
|
+
if (typeof point.label === "string" && point.label) {
|
|
444
|
+
return point.label;
|
|
445
|
+
}
|
|
446
|
+
const day = typeof point.day === "string" ? point.day : "";
|
|
447
|
+
return day.length === 10 ? day.slice(5) : day;
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
/**
|
|
451
|
+
* Format a trend point's full hover title. Hour buckets include the calendar
|
|
452
|
+
* day so repeated daily hours can never be confused.
|
|
453
|
+
*/
|
|
454
|
+
export function formatTrendPointTitle(point) {
|
|
455
|
+
if (!point || typeof point !== "object") {
|
|
456
|
+
return "";
|
|
457
|
+
}
|
|
458
|
+
const day = typeof point.day === "string" ? point.day : "";
|
|
459
|
+
if (Number.isInteger(point.hour) && point.hour >= 0 && point.hour <= 23) {
|
|
460
|
+
return `${day} ${formatTrendPointLabel(point)}`.trim();
|
|
461
|
+
}
|
|
462
|
+
return day;
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
/**
|
|
466
|
+
* Choose a sparse axis-label interval that keeps dense 24/30-slot charts legible.
|
|
467
|
+
*/
|
|
468
|
+
export function trendLabelEvery(count) {
|
|
469
|
+
const n = Number(count) || 0;
|
|
470
|
+
if (n <= 8) {
|
|
471
|
+
return 1;
|
|
472
|
+
}
|
|
473
|
+
return n <= 31 ? Math.ceil(n / 6) : Math.ceil(n / 5);
|
|
474
|
+
}
|
|
475
|
+
|
|
476
|
+
/**
|
|
477
|
+
* Decide whether a sparse axis tick should render. The terminal tick is always
|
|
478
|
+
* kept, but a penultimate regular tick is dropped when it would crowd the last
|
|
479
|
+
* label at narrow widths. With a one-slot interval every label remains visible.
|
|
480
|
+
*/
|
|
481
|
+
export function trendShowLabel(index, count, every) {
|
|
482
|
+
const n = Math.max(0, Math.floor(Number(count) || 0));
|
|
483
|
+
const step = Math.max(1, Math.floor(Number(every) || 1));
|
|
484
|
+
if (!Number.isInteger(index) || index < 0 || index >= n) {
|
|
485
|
+
return false;
|
|
486
|
+
}
|
|
487
|
+
if (index === 0 || index === n - 1) {
|
|
488
|
+
return true;
|
|
489
|
+
}
|
|
490
|
+
if (index % step !== 0) {
|
|
491
|
+
return false;
|
|
492
|
+
}
|
|
493
|
+
return n - 1 - index >= step;
|
|
494
|
+
}
|
|
495
|
+
|
|
496
|
+
/**
|
|
497
|
+
* Build the visual axis plan for a trend chart. Today keeps all hourly bars but
|
|
498
|
+
* labels only the 12 even hours (00, 02, … 22), while date buckets keep the
|
|
499
|
+
* existing sparse terminal-tick policy. Hover/keyboard detail is unaffected.
|
|
500
|
+
*/
|
|
501
|
+
export function buildTrendAxisModel(points = [], { bucket = "day", every = 1 } = {}) {
|
|
502
|
+
const n = points.length;
|
|
503
|
+
return points.map((point, index) => {
|
|
504
|
+
if (bucket === "hour") {
|
|
505
|
+
const hour = point?.hour;
|
|
506
|
+
const show = Number.isInteger(hour) && hour >= 0 && hour < 24 && hour % 2 === 0;
|
|
507
|
+
const compactLabel = show ? String(hour).padStart(2, "0") : "";
|
|
508
|
+
return {
|
|
509
|
+
index,
|
|
510
|
+
show,
|
|
511
|
+
fullLabel: show ? `${compactLabel}:00` : "",
|
|
512
|
+
compactLabel,
|
|
513
|
+
};
|
|
514
|
+
}
|
|
515
|
+
const show = trendShowLabel(index, n, every);
|
|
516
|
+
const label = show ? formatTrendPointLabel(point) : "";
|
|
517
|
+
return {
|
|
518
|
+
index,
|
|
519
|
+
show,
|
|
520
|
+
fullLabel: label,
|
|
521
|
+
compactLabel: label,
|
|
522
|
+
};
|
|
523
|
+
});
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
/**
|
|
527
|
+
* Resolve a roving-tab-stop target for chart keyboard navigation. Returns null
|
|
528
|
+
* for keys the chart does not handle so Tab and other shortcuts keep working.
|
|
529
|
+
*/
|
|
530
|
+
export function trendFocusTarget(currentIndex, key, count) {
|
|
531
|
+
const n = Math.max(0, Math.floor(Number(count) || 0));
|
|
532
|
+
if (n === 0) {
|
|
533
|
+
return null;
|
|
534
|
+
}
|
|
535
|
+
const current = Number.isInteger(currentIndex) && currentIndex >= 0 && currentIndex < n
|
|
536
|
+
? currentIndex
|
|
537
|
+
: 0;
|
|
538
|
+
switch (key) {
|
|
539
|
+
case "ArrowRight":
|
|
540
|
+
case "ArrowDown":
|
|
541
|
+
return Math.min(n - 1, current + 1);
|
|
542
|
+
case "ArrowLeft":
|
|
543
|
+
case "ArrowUp":
|
|
544
|
+
return Math.max(0, current - 1);
|
|
545
|
+
case "Home":
|
|
546
|
+
return 0;
|
|
547
|
+
case "End":
|
|
548
|
+
return n - 1;
|
|
549
|
+
default:
|
|
550
|
+
return null;
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
|
|
554
|
+
/**
|
|
555
|
+
* Stable key for a range/device selection so last-good data can be reused only
|
|
556
|
+
* for the exact selection that produced it.
|
|
557
|
+
*/
|
|
558
|
+
export function summarySelectionKey(range, device) {
|
|
559
|
+
return `${range}|${device}`;
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
/**
|
|
563
|
+
* True only for a partial chart's completely empty bucket. A bucket with calls
|
|
564
|
+
* or cost but no tokens is verified activity and must keep its real tooltip.
|
|
565
|
+
*/
|
|
566
|
+
export function isUnverifiedEmptyTrendPoint(point, availability = "ok") {
|
|
567
|
+
if (availability !== "partial" || !point || typeof point !== "object") {
|
|
568
|
+
return false;
|
|
569
|
+
}
|
|
570
|
+
return ["totalTokens", "calls", "errors", "cost", "input", "output", "cacheRead", "cacheWrite"]
|
|
571
|
+
.every((key) => !Number(point[key]));
|
|
572
|
+
}
|