Skip to content

armgit / qm

Public Imported from GitHub
0

Multiplayer agent harness for work.

Apply custom spend windows explicitly and bound them (#2213)

Eric Bakan05a62c145014
diff --git a/plugins/admin/public/admin-components.css b/plugins/admin/public/admin-components.css
index 466a8a552..980677b4b 100644
--- a/plugins/admin/public/admin-components.css
+++ b/plugins/admin/public/admin-components.css
@@ -2104,6 +2104,7 @@ dialog.credential-dialog {
#app-view #main .spend-custom {
display: flex;
+ flex-wrap: wrap;
align-items: center;
gap: 8px;
margin: 0 0 16px;
@@ -2111,3 +2112,6 @@ dialog.credential-dialog {
#app-view #main .spend-custom input[type="date"] {
width: auto;
}
+#app-view #main .spend-custom .hint {
+ margin: 0;
+}
diff --git a/plugins/admin/public/index.html b/plugins/admin/public/index.html
index 98e8f19a3..4879d35c4 100644
--- a/plugins/admin/public/index.html
+++ b/plugins/admin/public/index.html
@@ -7281,10 +7281,10 @@
if (st.view === "memory" && st.mem) p.set("mem", st.mem);
if (st.view === "metrics" && st.phase) p.set("phase", st.phase);
const spendWindow = st.view === "spend" ? governanceUI.spend.spendWindow(st) : null;
- if (spendWindow?.custom) {
+ if (spendWindow && spendWindow.preset === null) {
p.set("from", spendWindow.from);
p.set("to", spendWindow.to);
- } else if (st.view === "spend" && st.range) p.set("range", st.range);
+ } else if (spendWindow && st.range) p.set("range", spendWindow.preset);
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);
@@ -9350,7 +9350,6 @@
fmtTokens,
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, from: null, to: null }),
diff --git a/plugins/admin/test/history-urls.test.ts b/plugins/admin/test/history-urls.test.ts
index 5825f939f..3a30bc83b 100644
--- a/plugins/admin/test/history-urls.test.ts
+++ b/plugins/admin/test/history-urls.test.ts
@@ -108,6 +108,11 @@ test("the spend window round-trips through the URL so Back restores the prior ra
const { stateToUrl } = routerAt("/admin/spend");
assert.equal(stateToUrl({ view: "spend", scope: "org:acme", range: "7d" }), "/admin/spend?range=7d");
assert.equal(stateToUrl({ view: "spend", scope: "org:acme", range: null }), "/admin/spend");
+ assert.equal(
+ stateToUrl({ view: "spend", scope: "org:acme", range: "constructor" }),
+ "/admin/spend?range=30d",
+ "an unknown preset neither throws nor survives into the URL",
+ );
const router = routerAt("/admin/spend", "?range=90d");
const st = router.urlToState();
assert.equal(st.view, "spend");
diff --git a/plugins/admin/test/spend-lit.test.ts b/plugins/admin/test/spend-lit.test.ts
index 1a46340c8..9041adfb2 100644
--- a/plugins/admin/test/spend-lit.test.ts
+++ b/plugins/admin/test/spend-lit.test.ts
@@ -75,8 +75,7 @@ function render(data: any, services: Record<string, unknown> = {}) {
const f = litFixture();
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" },
+ window: { from: "2026-09-01", to: "2026-10-01", preset: "30d", bucket: "day" },
defaultShell: (opts: any) => {
calls.shell = opts;
},
@@ -384,14 +383,20 @@ 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);
+test("spend view: Custom turns the current window into two editable UTC days, applied on Apply as a sorted half-open window", () => {
+ const preset = render(DATA, { window: { from: "2026-09-24", to: "2026-10-01", preset: "7d", bucket: "day" } });
assert.equal(preset.f.root.querySelector(".spend-custom"), null);
+ assert.deepEqual(JSON.parse(JSON.stringify(preset.calls.shell.tabs.map((t: any) => t.active))), [
+ true,
+ false,
+ false,
+ false,
+ ]);
preset.calls.shell.tabs.at(-1).onClick();
- assert.deepEqual(preset.calls.customs, [["2026-09-01", "2026-10-01"]]);
+ assert.deepEqual(preset.calls.customs, [["2026-09-24", "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" } });
+ const { f, calls } = render(DATA, { window: { from: "2026-08-28", to: "2026-09-03", preset: null, bucket: "day" } });
assert.deepEqual(JSON.parse(JSON.stringify(calls.shell.tabs.map((t: any) => [t.label, t.active]))), [
["7d", false],
["30d", false],
@@ -400,11 +405,14 @@ test("spend view: Custom turns the current window into two editable UTC days, ap
]);
const [first, last] = [...f.root.querySelectorAll<HTMLInputElement>(".spend-custom input")];
assert.deepEqual([first!.value, last!.value], ["2026-08-28", "2026-09-02"]);
+ const applyButton = f.root.querySelector<HTMLButtonElement>(".spend-custom button")!;
last!.value = "2026-08-01";
- last!.dispatchEvent(new f.window.Event("change"));
+ last!.dispatchEvent(new f.window.Event("change", { bubbles: true }));
+ assert.deepEqual(calls.customs, [], "editing a day applies nothing until Apply");
+ applyButton.click();
assert.deepEqual(calls.customs, [["2026-08-01", "2026-08-29"]]);
first!.value = "";
- first!.dispatchEvent(new f.window.Event("change"));
+ applyButton.click();
assert.equal(calls.customs.length, 1, "a cleared day applies nothing");
calls.shell.tabs[0].onClick();
assert.deepEqual(calls.ranges, ["7d"]);
diff --git a/plugins/admin/test/spend-query.test.ts b/plugins/admin/test/spend-query.test.ts
index 678c21408..658ae7b5d 100644
--- a/plugins/admin/test/spend-query.test.ts
+++ b/plugins/admin/test/spend-query.test.ts
@@ -8,7 +8,7 @@ test("spend window: a valid custom window is used as-is, in daily buckets up to
assert.deepEqual(spendWindow({ range: "7d", from: "2026-09-01", to: "2026-10-01" }, NOW), {
from: "2026-09-01",
to: "2026-10-01",
- custom: true,
+ preset: null,
bucket: "day",
});
assert.equal(spendWindow({ from: "2026-07-01", to: "2026-09-01" }, NOW).bucket, "day");
@@ -19,10 +19,10 @@ test("spend window: presets end tomorrow in UTC, and impossible, empty or revers
assert.deepEqual(spendWindow({ range: "90d" }, NOW), {
from: "2026-07-03",
to: "2026-10-01",
- custom: false,
+ preset: "90d",
bucket: "week",
});
- assert.deepEqual(spendWindow({}, NOW), { from: "2026-09-01", to: "2026-10-01", custom: false, bucket: "day" });
+ assert.deepEqual(spendWindow({}, NOW), { from: "2026-09-01", to: "2026-10-01", preset: "30d", bucket: "day" });
for (const [from, to] of [
["2026-09-01", "2026-09-01"],
["2026-10-01", "2026-09-01"],
@@ -32,8 +32,36 @@ test("spend window: presets end tomorrow in UTC, and impossible, empty or revers
]) {
assert.deepEqual(
spendWindow({ range: "7d", from, to }, NOW),
- { from: "2026-09-24", to: "2026-10-01", custom: false, bucket: "day" },
+ { from: "2026-09-24", to: "2026-10-01", preset: "7d", bucket: "day" },
`${from} to ${to}`,
);
}
});
+
+test("spend window: unknown or inherited preset names fall back to 30d, and a custom window ends by tomorrow and spans at most 366 days", () => {
+ for (const range of ["constructor", "__proto__", "toString", "1d"]) {
+ assert.deepEqual(
+ spendWindow({ range }, NOW),
+ { from: "2026-09-01", to: "2026-10-01", preset: "30d", bucket: "day" },
+ range,
+ );
+ }
+ assert.deepEqual(spendWindow({ from: "2026-09-15", to: "2027-01-01" }, NOW), {
+ from: "2026-09-15",
+ to: "2026-10-01",
+ preset: null,
+ bucket: "day",
+ });
+ assert.equal(
+ spendWindow({ range: "7d", from: "2026-10-01", to: "2026-11-01" }, NOW).preset,
+ "7d",
+ "a window starting after today falls back to the preset",
+ );
+ assert.deepEqual(spendWindow({ from: "0002-10-15", to: "2026-10-01" }, NOW), {
+ from: "2025-09-30",
+ to: "2026-10-01",
+ preset: null,
+ bucket: "week",
+ });
+ assert.equal(spendWindow({ from: "2024-01-01", to: "2025-01-01" }, NOW).from, "2024-01-01", "a leap year fits");
+});
diff --git a/plugins/admin/ui/spend.ts b/plugins/admin/ui/spend.ts
index b8d2b6b4b..e46af9ae1 100644
--- a/plugins/admin/ui/spend.ts
+++ b/plugins/admin/ui/spend.ts
@@ -6,7 +6,12 @@ import { table, card, renderer } from "./shared.ts";
type Services = Record<string, any>;
const DAY = 86400000;
-const RANGES: Record<string, number> = { "7d": 7, "30d": 30, "90d": 90 };
+const PRESETS = new Map([
+ ["7d", 7],
+ ["30d", 30],
+ ["90d", 90],
+]);
+const MAX_CUSTOM_DAYS = 366;
const COLUMNS: Array<[string, string]> = [
["person", "Person"],
["costUsd", "Total"],
@@ -32,25 +37,26 @@ function dayMs(day: unknown): number | null {
interface SpendWindow {
from: string;
to: string;
- custom: boolean;
+ preset: string | null;
bucket: "day" | "week";
}
+function windowOf(start: number, end: number, preset: string | null): SpendWindow {
+ return { from: isoDay(start), to: isoDay(end), preset, bucket: end - start > 62 * DAY ? "week" : "day" };
+}
+
export function spendWindow(
state: { range?: string | null; from?: string | null; to?: string | null },
now = Date.now(),
): SpendWindow {
+ const tomorrow = Math.floor(now / DAY) * DAY + DAY;
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",
- };
+ const end = to === null ? null : Math.min(to, tomorrow);
+ if (from !== null && end !== null && from < end)
+ return windowOf(Math.max(from, end - MAX_CUSTOM_DAYS * DAY), end, null);
+ const preset = state.range && PRESETS.has(state.range) ? state.range : "30d";
+ return windowOf(tomorrow - PRESETS.get(preset)! * DAY, tomorrow, preset);
}
function sortValue(row: any, key: string): number | string {
@@ -100,12 +106,16 @@ export class SpendView {
[org.cacheHitRatio == null ? "n/a" : s.fmtPct(org.cacheHitRatio), "Cache hit rate"],
],
tabs: [
- ...Object.keys(RANGES).map((range) => ({
+ ...[...PRESETS.keys()].map((range) => ({
label: range,
- active: !s.window.custom && (s.range || "30d") === range,
+ active: s.window.preset === range,
onClick: () => s.setRange(range),
})),
- { label: "Custom", active: s.window.custom, onClick: () => s.setCustomRange(s.window.from, s.window.to) },
+ {
+ label: "Custom",
+ active: s.window.preset === null,
+ onClick: () => s.setCustomRange(s.window.from, s.window.to),
+ },
],
search: {
value: this.filter,
@@ -125,27 +135,23 @@ export class SpendView {
}
customRange() {
const current: SpendWindow = this.services.window;
- if (!current.custom) return null;
+ if (current.preset !== null) return null;
const today = isoDay(Date.now());
- const apply = () => {
+ const apply = (event: Event) => {
+ event.preventDefault();
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} />
+ return html`<form class="spend-custom" @submit=${apply}>
+ <input type="date" aria-label="First day" required max=${today} .value=${current.from} />
<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>`;
+ <input type="date" aria-label="Last day" required max=${today} .value=${isoDay(Date.parse(current.to) - DAY)} />
+ <button class="primary">Apply</button>
+ <span class="hint">UTC, up to ${MAX_CUSTOM_DAYS} days</span>
+ </form>`;
}
sortBy(key: string) {
if (this.sortKey === key) this.sortDir = this.sortDir === "asc" ? "desc" : "asc";