magpie-multi-usage 0.1.1 → 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 +25 -48
- package/README.zh-CN.md +46 -69
- package/package.json +1 -1
- package/src/aggregator.mjs +271 -2
- package/src/github-store.mjs +1 -1
- package/src/http-server.mjs +12 -2
- 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/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
|
|
|
@@ -385,8 +386,17 @@ export async function startHttpServer({
|
|
|
385
386
|
? template.replace("<!--MULTI_USAGE_BOOTSTRAP-->", bootstrapTag)
|
|
386
387
|
: template.replace("</head>", `${bootstrapTag}\n</head>`);
|
|
387
388
|
|
|
389
|
+
// WebKit can fail to match 'self' inside Magpie's opaque-origin iframe.
|
|
390
|
+
// The Host header has already passed the loopback host allowlist.
|
|
391
|
+
const loopbackOrigin = `http://${req.headers.host.trim().toLowerCase()}`;
|
|
388
392
|
sendResponse(res, 200, "text/html; charset=utf-8", html, {
|
|
389
|
-
"Content-Security-Policy":
|
|
393
|
+
"Content-Security-Policy": [
|
|
394
|
+
"default-src 'self'",
|
|
395
|
+
`script-src 'self' ${loopbackOrigin} 'nonce-${nonce}'`,
|
|
396
|
+
`style-src 'self' ${loopbackOrigin} 'unsafe-inline'`,
|
|
397
|
+
"img-src 'self' data:",
|
|
398
|
+
`connect-src 'self' ${loopbackOrigin}`,
|
|
399
|
+
].join("; "),
|
|
390
400
|
});
|
|
391
401
|
return;
|
|
392
402
|
}
|
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;
|