Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Add a custom date range to the admin spend view (#1797)

Eric Bakand7a46fc6b211
diff --git a/plugins/admin/public/admin-components.css b/plugins/admin/public/admin-components.css
index c01ed7259..466a8a552 100644
--- a/plugins/admin/public/admin-components.css
+++ b/plugins/admin/public/admin-components.css
@@ -1250,7 +1250,10 @@ dialog.credential-dialog {
line-height: 1.4;
}
-:where(html body:is([data-subview="audit"], [data-subview="egress"])) #app-view #main .shellbar {
+:where(html body:is([data-subview="audit"], [data-subview="egress"], [data-subview="spend"]))
+ #app-view
+ #main
+ .shellbar {
flex-wrap: wrap;
gap: 12px 20px;
}
@@ -2098,3 +2101,13 @@ dialog.credential-dialog {
max-width: 100%;
margin-right: 12px;
}
+
+#app-view #main .spend-custom {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ margin: 0 0 16px;
+}
+#app-view #main .spend-custom input[type="date"] {
+ width: auto;
+}
diff --git a/plugins/admin/public/index.html b/plugins/admin/public/index.html
index 87e966617..98e8f19a3 100644
--- a/plugins/admin/public/index.html
+++ b/plugins/admin/public/index.html
@@ -7280,7 +7280,11 @@
if (st.own && SCOPED.has(st.view)) p.set("own", st.own);
if (st.view === "memory" && st.mem) p.set("mem", st.mem);
if (st.view === "metrics" && st.phase) p.set("phase", st.phase);
- if (st.view === "spend" && st.range) p.set("range", st.range);
+ const spendWindow = st.view === "spend" ? governanceUI.spend.spendWindow(st) : null;
+ if (spendWindow?.custom) {
+ p.set("from", spendWindow.from);
+ p.set("to", spendWindow.to);
+ } else if (st.view === "spend" && st.range) p.set("range", st.range);
if (st.view === "slack" && st.container) p.set("container", st.container);
if (st.view === "slack" && st.container && st.ts) p.set("ts", st.ts);
if (st.view === "judgments" && st.container) p.set("container", st.container);
@@ -7346,6 +7350,8 @@
mem: p.get("mem") || null,
phase: p.get("phase") || null,
range: p.get("range") || null,
+ from: p.get("from") || null,
+ to: p.get("to") || null,
historyKind: normalizedHistoryKind,
page: Math.max(1, parseInt(p.get("page"), 10) || 1),
cursor: p.get("cursor") || null,
@@ -9333,18 +9339,9 @@
sparkline,
});
}
- const SPEND_RANGES = { "7d": 7, "30d": 30, "90d": 90 };
function spendQuery(st) {
- const DAY = 86400000;
- const range = SPEND_RANGES[st.range] ? st.range : "30d";
- const to = Math.floor(Date.now() / DAY) * DAY + DAY;
- const iso = (t) => new Date(t).toISOString().slice(0, 10);
- const params = new URLSearchParams({
- from: iso(to - SPEND_RANGES[range] * DAY),
- to: iso(to),
- bucket: range === "90d" ? "week" : "day",
- });
- return params.toString();
+ const { from, to, bucket } = governanceUI.spend.spendWindow(st);
+ return new URLSearchParams({ from, to, bucket }).toString();
}
function renderSpend(root, d) {
governanceUI.spend.spend(root, d, {
@@ -9354,8 +9351,10 @@
shortName,
plural,
range: urlToState().range || "30d",
+ window: governanceUI.spend.spendWindow(urlToState()),
openUser: (principal) => go({ view: "user", scope, session: null, principal }),
- setRange: (range) => go({ ...urlToState(), view: "spend", range }),
+ setRange: (range) => go({ ...urlToState(), view: "spend", range, from: null, to: null }),
+ setCustomRange: (from, to) => go({ ...urlToState(), view: "spend", range: null, from, to }),
downloadCsv: (breakdown = "entity") => {
const a = document.createElement("a");
a.href =
diff --git a/plugins/admin/test/history-urls.test.ts b/plugins/admin/test/history-urls.test.ts
index 713ec9e9e..5825f939f 100644
--- a/plugins/admin/test/history-urls.test.ts
+++ b/plugins/admin/test/history-urls.test.ts
@@ -3,6 +3,7 @@ import { renderDesign } from "./design-source.ts";
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import test from "node:test";
+import { spendWindow } from "../ui/spend.ts";
const html = readFileSync(new URL("../public/index.html", import.meta.url), "utf8");
@@ -21,6 +22,7 @@ function routerAt(pathname: string, search = "", base = "/admin") {
"location",
"scope",
"orgId",
+ "governanceUI",
`${grab("decodePathSegment")};
${grab("stateToUrl")};
${grab("urlToState")};
@@ -51,6 +53,7 @@ function routerAt(pathname: string, search = "", base = "/admin") {
{ pathname, search },
"channel:LAST-VIEWED",
"acme",
+ { spend: { spendWindow } },
) as {
stateToUrl: (st: Record<string, unknown>) => string;
urlToState: () => {
@@ -62,6 +65,8 @@ function routerAt(pathname: string, search = "", base = "/admin") {
cron: string | null;
turn: string | null;
range: string | null;
+ from: string | null;
+ to: string | null;
page: number;
cursor: string | null;
};
@@ -111,6 +116,33 @@ test("the spend window round-trips through the URL so Back restores the prior ra
assert.equal(routerAt("/admin/spend").urlToState().range, null);
});
+test("a custom spend window round-trips through the URL and replaces the preset range", () => {
+ const { stateToUrl } = routerAt("/admin/spend");
+ assert.equal(
+ stateToUrl({ view: "spend", scope: "org:acme", range: "7d", from: "2026-09-01", to: "2026-10-01" }),
+ "/admin/spend?from=2026-09-01&to=2026-10-01",
+ );
+ assert.equal(
+ stateToUrl({ view: "spend", scope: "org:acme", range: "7d", from: null, to: null }),
+ "/admin/spend?range=7d",
+ );
+ assert.equal(
+ stateToUrl({ view: "spend", scope: "org:acme", range: "7d", from: "2026-02-30", to: "2026-03-02" }),
+ "/admin/spend?range=7d",
+ "an impossible custom window never displaces the preset",
+ );
+ assert.equal(
+ stateToUrl({ view: "metrics", scope: "org:acme", from: "2026-09-01", to: "2026-10-01" }),
+ "/admin/metrics?scope=org%3Aacme",
+ );
+ const router = routerAt("/admin/spend", "?from=2026-09-01&to=2026-10-01");
+ const st = router.urlToState();
+ assert.equal(st.from, "2026-09-01");
+ assert.equal(st.to, "2026-10-01");
+ assert.equal(router.stateToUrl(st), "/admin/spend?from=2026-09-01&to=2026-10-01");
+ assert.equal(routerAt("/admin/spend", "?range=7d").urlToState().from, null);
+});
+
test("non-history views keep their query-param scope", () => {
const { stateToUrl } = routerAt("/admin/files");
assert.equal(stateToUrl({ view: "files", scope: SCOPE }), `/admin/files?scope=${SCOPE_ENC}`);
diff --git a/plugins/admin/test/spend-lit.test.ts b/plugins/admin/test/spend-lit.test.ts
index 9b2494f96..1a46340c8 100644
--- a/plugins/admin/test/spend-lit.test.ts
+++ b/plugins/admin/test/spend-lit.test.ts
@@ -71,11 +71,12 @@ const EMPTY = {
scopes: [],
};
-function render(data: any) {
+function render(data: any, services: Record<string, unknown> = {}) {
const f = litFixture();
- const calls: any = { shell: null, ranges: [], opened: [], downloads: 0, modelDownloads: 0, api: 0 };
+ const calls: any = { shell: null, ranges: [], customs: [], opened: [], downloads: 0, modelDownloads: 0, api: 0 };
const view = f.ui.spend.spend(f.root, data, {
range: "30d",
+ window: { from: "2026-09-01", to: "2026-10-01", custom: false, bucket: "day" },
defaultShell: (opts: any) => {
calls.shell = opts;
},
@@ -89,10 +90,12 @@ function render(data: any) {
plural: (n: number, one: string) => `${n} ${one}`,
openUser: (principal: string) => calls.opened.push(principal),
setRange: (range: string) => calls.ranges.push(range),
+ setCustomRange: (from: string, to: string) => calls.customs.push([from, to]),
downloadCsv: (breakdown?: string) => {
if (breakdown === "model") calls.modelDownloads += 1;
else calls.downloads += 1;
},
+ ...services,
});
const peopleRows = () =>
[...f.root.querySelectorAll(".tablewrap")[0]!.querySelectorAll("tbody tr")].map((r) =>
@@ -119,6 +122,7 @@ test("spend view: KPI stats, stacked chart and range tabs describe the whole org
["7d", false],
["30d", true],
["90d", false],
+ ["Custom", false],
]);
assert.equal(f.root.querySelectorAll(".spend-column").length, 30, "zero-spend dates retain their space");
assert.ok(f.root.textContent!.includes("$0.53"), "daily average includes zero-spend days");
@@ -379,3 +383,31 @@ test("spend chart: person toggle is disabled for reports without person buckets"
);
f.window.close();
});
+
+test("spend view: Custom turns the current window into two editable UTC days, applied as a sorted half-open window", () => {
+ const preset = render(DATA);
+ assert.equal(preset.f.root.querySelector(".spend-custom"), null);
+ preset.calls.shell.tabs.at(-1).onClick();
+ assert.deepEqual(preset.calls.customs, [["2026-09-01", "2026-10-01"]]);
+ preset.f.window.close();
+
+ const { f, calls } = render(DATA, { window: { from: "2026-08-28", to: "2026-09-03", custom: true, bucket: "day" } });
+ assert.deepEqual(JSON.parse(JSON.stringify(calls.shell.tabs.map((t: any) => [t.label, t.active]))), [
+ ["7d", false],
+ ["30d", false],
+ ["90d", false],
+ ["Custom", true],
+ ]);
+ const [first, last] = [...f.root.querySelectorAll<HTMLInputElement>(".spend-custom input")];
+ assert.deepEqual([first!.value, last!.value], ["2026-08-28", "2026-09-02"]);
+ last!.value = "2026-08-01";
+ last!.dispatchEvent(new f.window.Event("change"));
+ assert.deepEqual(calls.customs, [["2026-08-01", "2026-08-29"]]);
+ first!.value = "";
+ first!.dispatchEvent(new f.window.Event("change"));
+ assert.equal(calls.customs.length, 1, "a cleared day applies nothing");
+ calls.shell.tabs[0].onClick();
+ assert.deepEqual(calls.ranges, ["7d"]);
+ assert.equal(calls.api, 0);
+ f.window.close();
+});
diff --git a/plugins/admin/test/spend-query.test.ts b/plugins/admin/test/spend-query.test.ts
new file mode 100644
index 000000000..678c21408
--- /dev/null
+++ b/plugins/admin/test/spend-query.test.ts
@@ -0,0 +1,39 @@
+import assert from "node:assert/strict";
+import test from "node:test";
+import { spendWindow } from "../ui/spend.ts";
+
+const NOW = Date.parse("2026-09-30T15:00:00.000Z");
+
+test("spend window: a valid custom window is used as-is, in daily buckets up to 62 days and weekly beyond", () => {
+ assert.deepEqual(spendWindow({ range: "7d", from: "2026-09-01", to: "2026-10-01" }, NOW), {
+ from: "2026-09-01",
+ to: "2026-10-01",
+ custom: true,
+ bucket: "day",
+ });
+ assert.equal(spendWindow({ from: "2026-07-01", to: "2026-09-01" }, NOW).bucket, "day");
+ assert.equal(spendWindow({ from: "2026-06-30", to: "2026-09-01" }, NOW).bucket, "week");
+});
+
+test("spend window: presets end tomorrow in UTC, and impossible, empty or reversed custom windows fall back to the preset", () => {
+ assert.deepEqual(spendWindow({ range: "90d" }, NOW), {
+ from: "2026-07-03",
+ to: "2026-10-01",
+ custom: false,
+ bucket: "week",
+ });
+ assert.deepEqual(spendWindow({}, NOW), { from: "2026-09-01", to: "2026-10-01", custom: false, bucket: "day" });
+ for (const [from, to] of [
+ ["2026-09-01", "2026-09-01"],
+ ["2026-10-01", "2026-09-01"],
+ ["2026-02-30", "2026-03-02"],
+ ["2026-9-1", "2026-10-01"],
+ ["2026-09-01", null],
+ ]) {
+ assert.deepEqual(
+ spendWindow({ range: "7d", from, to }, NOW),
+ { from: "2026-09-24", to: "2026-10-01", custom: false, bucket: "day" },
+ `${from} to ${to}`,
+ );
+ }
+});
diff --git a/plugins/admin/ui/spend.ts b/plugins/admin/ui/spend.ts
index d6b46f741..b8d2b6b4b 100644
--- a/plugins/admin/ui/spend.ts
+++ b/plugins/admin/ui/spend.ts
@@ -5,7 +5,8 @@ import { table, card, renderer } from "./shared.ts";
type Services = Record<string, any>;
-const RANGES = ["7d", "30d", "90d"];
+const DAY = 86400000;
+const RANGES: Record<string, number> = { "7d": 7, "30d": 30, "90d": 90 };
const COLUMNS: Array<[string, string]> = [
["person", "Person"],
["costUsd", "Total"],
@@ -21,6 +22,37 @@ const rowName = (row: any) =>
const fmtUsd = (n: any) => "$" + (Number(n) || 0).toFixed(2);
+const isoDay = (ms: number) => new Date(ms).toISOString().slice(0, 10);
+
+function dayMs(day: unknown): number | null {
+ const ms = Date.parse(`${day}T00:00:00.000Z`);
+ return Number.isFinite(ms) && isoDay(ms) === day ? ms : null;
+}
+
+interface SpendWindow {
+ from: string;
+ to: string;
+ custom: boolean;
+ bucket: "day" | "week";
+}
+
+export function spendWindow(
+ state: { range?: string | null; from?: string | null; to?: string | null },
+ now = Date.now(),
+): SpendWindow {
+ const from = dayMs(state.from);
+ const to = dayMs(state.to);
+ const custom = from !== null && to !== null && from < to ? { start: from, end: to } : null;
+ const end = custom?.end ?? Math.floor(now / DAY) * DAY + DAY;
+ const start = custom?.start ?? end - (RANGES[state.range ?? ""] ?? RANGES["30d"]!) * DAY;
+ return {
+ from: isoDay(start),
+ to: isoDay(end),
+ custom: custom !== null,
+ bucket: end - start > 62 * DAY ? "week" : "day",
+ };
+}
+
function sortValue(row: any, key: string): number | string {
if (key === "person") return String(rowName(row)).toLowerCase();
if (key === "live" || key === "cron" || key === "background") return Number(row[key]?.costUsd || 0);
@@ -67,11 +99,14 @@ export class SpendView {
[fmtUsd(org.cron?.costUsd), "Crons"],
[org.cacheHitRatio == null ? "n/a" : s.fmtPct(org.cacheHitRatio), "Cache hit rate"],
],
- tabs: RANGES.map((range) => ({
- label: range,
- active: (s.range || "30d") === range,
- onClick: () => s.setRange(range),
- })),
+ tabs: [
+ ...Object.keys(RANGES).map((range) => ({
+ label: range,
+ active: !s.window.custom && (s.range || "30d") === range,
+ onClick: () => s.setRange(range),
+ })),
+ { label: "Custom", active: s.window.custom, onClick: () => s.setCustomRange(s.window.from, s.window.to) },
+ ],
search: {
value: this.filter,
placeholder: "person, scope or model",
@@ -88,6 +123,30 @@ export class SpendView {
if (focused) active?.focus({ preventScroll: true });
} else this.search = search;
}
+ customRange() {
+ const current: SpendWindow = this.services.window;
+ if (!current.custom) return null;
+ const today = isoDay(Date.now());
+ const apply = () => {
+ const [first, last] = [...this.root.querySelectorAll<HTMLInputElement>(".spend-custom input")]
+ .map((input) => input.value)
+ .sort();
+ const end = dayMs(last);
+ if (dayMs(first) !== null && end !== null) this.services.setCustomRange(first, isoDay(end + DAY));
+ };
+ return html`<div class="spend-custom">
+ <input type="date" aria-label="First day" max=${today} .value=${current.from} @change=${apply} />
+ <span>to</span>
+ <input
+ type="date"
+ aria-label="Last day"
+ max=${today}
+ .value=${isoDay(Date.parse(current.to) - DAY)}
+ @change=${apply}
+ />
+ <span class="hint">UTC</span>
+ </div>`;
+ }
sortBy(key: string) {
if (this.sortKey === key) this.sortDir = this.sortDir === "asc" ? "desc" : "asc";
else {
@@ -140,7 +199,7 @@ export class SpendView {
const series = this.data.series || [];
const org = this.data.org || {};
this.paint(
- html`${
+ html`${this.customRange()}${
this.data.asOf == null
? null
: html`<p class="subline">