Skip to content

Open-source Grok Bot alternative with a virtual machine that bots can use

Split usage bars by the models a group ran

BunBnnuy1bca5eec33c7
diff --git a/server/routes/usage.ts b/server/routes/usage.ts
index ac136ebb3c..de99efac3d 100644
--- a/server/routes/usage.ts
+++ b/server/routes/usage.ts
@@ -9,8 +9,10 @@ import {
summarizeUsage,
usageCsv,
USAGE_GROUPINGS,
+ USAGE_SPLITS,
type UsageGroupBy,
type UsageRow,
+ type UsageSplitBy,
} from "../usage-ledger.ts";
import { DETAIL_MAX, ERROR_MAX } from "../usage-trace/detail.ts";
import type { ToolReceipt, TraceRecorder } from "../usage-trace/recorder.ts";
@@ -83,12 +85,18 @@ export function createUsageRoutes(deps: UsageRouteDeps): RouteHandler {
return json(res, 400, { error: `groupBy must be one of ${USAGE_GROUPINGS.join(", ")}` });
}
const groupBy = requested as UsageGroupBy;
+ const requestedSplit = url.searchParams.get("splitBy");
+ if (requestedSplit !== null && !USAGE_SPLITS.includes(requestedSplit as UsageSplitBy)) {
+ return json(res, 400, { error: `splitBy must be one of ${USAGE_SPLITS.join(", ")}` });
+ }
+ const splitBy = requestedSplit === null || requestedSplit === groupBy ? null : requestedSplit as UsageSplitBy;
res.setHeader("cache-control", "no-store");
return json(res, 200, {
from: range.from.toISOString(),
to: range.to.toISOString(),
groupBy,
- ...summarizeUsage(rows, groupBy, prices),
+ splitBy,
+ ...summarizeUsage(rows, groupBy, prices, splitBy),
budget: deps.budget(),
billing: prices ? { currency: deps.currency() } : null,
});
diff --git a/server/usage-ledger.test.ts b/server/usage-ledger.test.ts
index 783a835545..7aec5b1c77 100644
--- a/server/usage-ledger.test.ts
+++ b/server/usage-ledger.test.ts
@@ -146,6 +146,50 @@ describe("usage summaries", () => {
expect(summarizeUsage([], "day")).toEqual({ groups: [], total: expect.objectContaining({ turns: 0, costUsd: null }) });
});
+ it("splits any group by model, largest bar first, only when a different dimension is asked for", () => {
+ const mixed: UsageRow[] = [
+ rows[0]!,
+ { ...rows[0]!, model: "gpt-6.1-sol", driverKind: "codex", instanceId: "codex", input: 100, output: 20, cachedInput: 0, costUsd: 0.001 },
+ rows[1]!,
+ ];
+ const [scout, clerk] = summarizeUsage(mixed, "bot", null, "model").groups;
+ expect(scout!.segments?.map((piece) => [piece.key, piece.input, piece.output])).toEqual([
+ ["model:claudeAgent/claude-sonnet-5", 1200, 300],
+ ["model:codex/gpt-6.1-sol", 100, 20],
+ ]);
+ expect(clerk!.segments?.map((piece) => piece.key)).toEqual(["model:codex/gpt-5"]);
+ expect(summarizeUsage(mixed, "bot").groups[0]!.segments).toBeUndefined();
+ expect(summarizeUsage(mixed, "model", null, "model").groups[0]!.segments).toBeUndefined();
+ expect(summarizeUsage(mixed, "day", null, "model").groups[0]!.segments?.map((piece) => piece.key)).toEqual([
+ "model:claudeAgent/claude-sonnet-5",
+ "model:codex/gpt-5",
+ "model:codex/gpt-6.1-sol",
+ ]);
+ });
+
+ it("orders a group's segments by the fresh tokens its bar draws, not by cached input", () => {
+ const cached: UsageRow = {
+ ...rows[0]!,
+ model: "claude-sonnet-5",
+ input: 10_000,
+ cachedInput: 9_800,
+ output: 100,
+ };
+ const fresh: UsageRow = {
+ ...rows[0]!,
+ model: "gpt-6.1-sol",
+ driverKind: "codex",
+ instanceId: "codex",
+ input: 600,
+ output: 100,
+ cachedInput: 0,
+ };
+ expect(summarizeUsage([cached, fresh], "bot", null, "model").groups[0]!.segments?.map((piece) => piece.key)).toEqual([
+ "model:codex/gpt-6.1-sol",
+ "model:claudeAgent/claude-sonnet-5",
+ ]);
+ });
+
it("groups by routine, with every non-routine turn in one manual bucket", () => {
const summary = summarizeUsage(rows, "routine");
expect(summary.groups.map((g) => [g.key, g.label, g.turns, g.costUsd])).toEqual([
diff --git a/server/usage-ledger.ts b/server/usage-ledger.ts
index 897bfb98ed..bab7517af6 100644
--- a/server/usage-ledger.ts
+++ b/server/usage-ledger.ts
@@ -56,6 +56,10 @@ export interface UsageRow {
export type UsageGroupBy = "bot" | "model" | "user" | "day" | "engine" | "routine" | "department";
export const USAGE_GROUPINGS: readonly UsageGroupBy[] = ["bot", "model", "user", "day", "engine", "routine", "department"];
+/** The dimensions a group can be broken down by inside one bar; each has few enough values to stack. */
+export type UsageSplitBy = "model";
+export const USAGE_SPLITS: readonly UsageSplitBy[] = ["model"];
+
export interface UsageGroup {
key: string;
label: string;
@@ -67,6 +71,8 @@ export interface UsageGroup {
estimatedUsd: number | null;
unpriced: number;
billableUsd: number | null;
+ /** The group broken down by the requested split, largest first. */
+ segments?: UsageGroup[];
}
export interface UsageSummary {
@@ -300,9 +306,21 @@ function add(group: UsageGroup, row: UsageRow, prices: PriceList | null): void {
if (billable !== null) group.billableUsd = (group.billableUsd ?? 0) + billable;
}
-export function summarizeUsage(rows: UsageRow[], groupBy: UsageGroupBy, prices: PriceList | null = null): UsageSummary {
+/** The tokens a bar shows: fresh input plus output, the same count the Usage page writes beside each bar. */
+function barTokens(group: UsageGroup): number {
+ return Math.max(0, group.input - Math.min(group.cachedInput, group.input)) + group.output;
+}
+
+export function summarizeUsage(
+ rows: UsageRow[],
+ groupBy: UsageGroupBy,
+ prices: PriceList | null = null,
+ splitBy: UsageSplitBy | null = null,
+): UsageSummary {
const groups = new Map<string, UsageGroup>();
const total = emptyGroup("total", "total");
+ const splits = new Map<string, Map<string, UsageGroup>>();
+ const split = splitBy && splitBy !== groupBy ? splitBy : null;
for (const row of rows) {
const { key, label } = groupOf(row, groupBy);
let group = groups.get(key);
@@ -312,6 +330,22 @@ export function summarizeUsage(rows: UsageRow[], groupBy: UsageGroupBy, prices:
}
add(group, row, prices);
add(total, row, prices);
+ if (!split) continue;
+ let inside = splits.get(key);
+ if (!inside) {
+ inside = new Map();
+ splits.set(key, inside);
+ }
+ const pieceOf = groupOf(row, split);
+ let piece = inside.get(pieceOf.key);
+ if (!piece) {
+ piece = emptyGroup(pieceOf.key, pieceOf.label);
+ inside.set(pieceOf.key, piece);
+ }
+ add(piece, row, prices);
+ }
+ for (const [key, inside] of splits) {
+ groups.get(key)!.segments = [...inside.values()].sort((a, b) => barTokens(b) - barTokens(a));
}
const ordered = [...groups.values()];
if (groupBy === "day") ordered.sort((a, b) => a.key.localeCompare(b.key));
diff --git a/src/components/UsageSection.bars.test.ts b/src/components/UsageSection.bars.test.ts
new file mode 100644
index 0000000000..71689927c1
--- /dev/null
+++ b/src/components/UsageSection.bars.test.ts
@@ -0,0 +1,101 @@
+// @vitest-environment happy-dom
+// The Usage page bars: a group's bar is its models stacked in their own colours,
+// and the model view repeats those colours as a swatch beside the name.
+import { createElement } from "react";
+import { flushSync } from "react-dom";
+import { createRoot, type Root } from "react-dom/client";
+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
+
+import type { Bot } from "@/state/store";
+
+const scout: Bot = {
+ id: "b1", threadId: "t1", name: "Scout", title: "", description: "", notifications: true,
+ color: "green", unread: false, messages: [], modelSelection: { instanceId: "claude", model: "claude-sonnet-5" },
+};
+
+vi.mock("@/state/store", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("@/state/store")>()),
+ useStore: () => ({ state: { bots: [scout], instances: [] }, dispatch: vi.fn() }),
+}));
+vi.mock("./Avatar", () => ({ BotAvatar: () => null }));
+
+const { GroupBars } = await import("./UsageSection");
+
+let root: Root;
+let host: HTMLDivElement;
+
+beforeEach(() => {
+ host = document.createElement("div");
+ document.body.append(host);
+ root = createRoot(host);
+});
+
+afterEach(() => {
+ flushSync(() => root.unmount());
+ host.remove();
+});
+
+const group = (over: Record<string, unknown>) => ({
+ key: "bot:b1", label: "Scout", turns: 3, input: 900, output: 300, cachedInput: 0, costUsd: 0.5, ...over,
+});
+
+const render = (groupBy: "bot" | "model" | "day", groups: ReturnType<typeof group>[]) => flushSync(() => {
+ root.render(createElement(GroupBars, { groupBy, groups: groups as never }));
+});
+
+const slices = () => [...host.querySelectorAll<HTMLElement>("span[data-model-color]")];
+
+describe("Usage page bars", () => {
+ it("stacks a bot's models into one bar, each slice in the model's own colour and share", () => {
+ render("bot", [group({
+ segments: [
+ group({ key: "model:codex/gpt-6-astra", label: "gpt-6-astra", input: 21_341, output: 298 }),
+ group({ key: "model:opencodeGo/opencode-go/deepseek-v4.1-flash", label: "deepseek-v4.1-flash", input: 11_428, output: 846 }),
+ ],
+ })]);
+ const painted = slices();
+ expect(painted).toHaveLength(2);
+ expect(Number.parseFloat(painted[0]!.style.width)).toBeCloseTo(63.8, 1);
+ expect(Number.parseFloat(painted[1]!.style.width)).toBeCloseTo(36.2, 1);
+ expect(painted[0]!.style.backgroundColor).toBeTruthy();
+ expect(painted[0]!.style.backgroundColor).not.toBe(painted[1]!.style.backgroundColor);
+ expect(painted[0]!.title).toContain("gpt-6-astra");
+ expect(painted[0]!.title).toContain("21.6k");
+ expect(painted[0]!.title).toContain("64%");
+ expect(painted[1]!.title).toContain("deepseek-v4.1-flash");
+ expect(painted[1]!.title).toContain("36%");
+ });
+
+ it("keeps one solid slice when a bot used a single model, and repeats its colour as the model swatch", () => {
+ const segments = [group({ key: "model:codex/gpt-6-astra", label: "gpt-6-astra" })];
+ render("bot", [group({ segments })]);
+ expect(slices()).toHaveLength(1);
+ expect(slices()[0]!.style.width).toBe("100%");
+
+ render("model", segments);
+ const swatch = slices()[0]!;
+ expect(swatch.style.backgroundColor).toBeTruthy();
+ expect(host.textContent).toContain("gpt-6-astra");
+ });
+
+ it("stacks any grouping the bar shows, not only bots", () => {
+ render("day", [group({
+ key: "day:2026-11-06",
+ label: "2026-11-06",
+ segments: [
+ group({ key: "model:codex/gpt-6-astra", label: "gpt-6-astra", input: 700, output: 100 }),
+ group({ key: "model:opencodeGo/opencode-go/deepseek-v4.1-flash", label: "deepseek-v4.1-flash", input: 300, output: 100 }),
+ ],
+ })]);
+ expect(host.textContent).toContain("2026-11-06");
+ expect(slices()).toHaveLength(2);
+ expect(slices()[0]!.title).toContain("gpt-6-astra");
+ expect(slices()[1]!.title).toContain("deepseek-v4.1-flash");
+ });
+
+ it("leaves a group without segments on the app's accent bar", () => {
+ render("bot", [group({})]);
+ expect(slices()).toHaveLength(0);
+ expect(host.querySelector(".bg-accent\\/70")).not.toBeNull();
+ });
+});
diff --git a/src/components/UsageSection.tsx b/src/components/UsageSection.tsx
index 02487d84b2..63473d49db 100644
--- a/src/components/UsageSection.tsx
+++ b/src/components/UsageSection.tsx
@@ -27,6 +27,8 @@ export interface UsageGroup {
output: number;
cachedInput: number;
costUsd: number | null;
+ /** The group broken down by the requested split, largest first. */
+ segments?: UsageGroup[];
}
interface UsageSummary {
@@ -67,18 +69,50 @@ export function usageGroupLabel(groupBy: UsageGroupBy, group: Pick<UsageGroup, "
return group.label;
}
-function useUsageGroups(range: { from: string; to: string }, groupBy: UsageGroupBy, version: number): UsageSummary | null {
+function useUsageGroups(
+ range: { from: string; to: string },
+ groupBy: UsageGroupBy,
+ version: number,
+ splitBy?: "model",
+): UsageSummary | null {
const [summary, setSummary] = useState<UsageSummary | null>(null);
useEffect(() => {
let current = true;
- void api(`/api/usage?from=${encodeURIComponent(range.from)}&to=${encodeURIComponent(range.to)}&groupBy=${groupBy}`)
+ void api(`/api/usage?from=${encodeURIComponent(range.from)}&to=${encodeURIComponent(range.to)}&groupBy=${groupBy}${splitBy ? `&splitBy=${splitBy}` : ""}`)
.then((next: UsageSummary) => { if (current) setSummary(next); })
.catch(() => { if (current) setSummary(null); });
return () => { current = false; };
- }, [range.from, range.to, groupBy, version]);
+ }, [range.from, range.to, groupBy, splitBy, version]);
return summary;
}
+/** One bar: a group's models stacked in their own colours, or a single solid bar when it has no split. */
+function Bar({ group, width, color }: { group: UsageGroup; width: number; color?: string }) {
+ const { state } = useStore();
+ const segments = group.segments ?? [];
+ const stack = segments.reduce((sum, piece) => sum + headlineTokens(piece), 0);
+ if (segments.length && stack > 0) {
+ return (
+ <span className="flex h-full" style={{ width: `${width}%` }}>
+ {segments.map((piece) => {
+ const tokens = headlineTokens(piece);
+ const share = Math.round((tokens / stack) * 100);
+ return (
+ <span
+ key={piece.key}
+ className="h-full"
+ data-model-color={modelColor(piece.key)}
+ style={{ width: `${(tokens / stack) * 100}%`, backgroundColor: modelColor(piece.key) }}
+ title={`${modelName(piece.label, state.instances)} · ${formatTokens(tokens)} · ${share}%`}
+ />
+ );
+ })}
+ </span>
+ );
+ }
+ return <span data-model-color={color} className={cn("block h-full rounded-full", !color && "bg-accent/70")} style={{ width: `${width}%`, backgroundColor: color }} />;
+}
+
export function GroupBars({ groupBy, groups }: { groupBy: UsageGroupBy; groups: readonly UsageGroup[] }) {
const { state } = useStore();
const top = [...groups].sort((a, b) => headlineTokens(b) - headlineTokens(a)).slice(0, 6);
@@ -98,7 +132,7 @@ export function GroupBars({ groupBy, groups }: { groupBy: UsageGroupBy; groups:
<span className="truncate">{groupBy === "model" ? modelName(group.label, state.instances) : usageGroupLabel(groupBy, group)}</span>
</span>
<span className="h-2 overflow-hidden rounded-full bg-raised">
- <span data-model-color={color} className={cn("block h-full rounded-full", !color && "bg-accent/70")} style={{ width: `${Math.max(2, (headlineTokens(group) / max) * 100)}%`, backgroundColor: color }} />
+ <Bar group={group} width={Math.max(2, (headlineTokens(group) / max) * 100)} color={color} />
</span>
<span className="min-w-[4.5rem] text-right tabular-nums text-ink-secondary">
{formatTokens(headlineTokens(group))}
@@ -111,10 +145,34 @@ export function GroupBars({ groupBy, groups }: { groupBy: UsageGroupBy; groups:
);
}
+/** The colours a stacked bar is made of, so its slices read without hovering. */
+function ModelLegend({ groups }: { groups: readonly UsageGroup[] }) {
+ const { state } = useStore();
+ const totals = new Map<string, { label: string; tokens: number }>();
+ for (const group of groups) {
+ for (const piece of group.segments ?? []) {
+ const seen = totals.get(piece.key);
+ totals.set(piece.key, { label: piece.label, tokens: (seen?.tokens ?? 0) + headlineTokens(piece) });
+ }
+ }
+ const items = [...totals.entries()].sort((a, b) => b[1].tokens - a[1].tokens);
+ if (items.length < 2) return null;
+ return (
+ <ul className="mt-2.5 flex flex-wrap gap-x-3 gap-y-1">
+ {items.map(([key, item]) => (
+ <li key={key} className="flex min-w-0 items-center gap-1.5 text-[11px] text-ink-secondary">
+ <span aria-hidden="true" data-model-color={modelColor(key)} className="size-2 shrink-0 rounded-full" style={{ backgroundColor: modelColor(key) }} />
+ <span className="max-w-[9rem] truncate">{modelName(item.label, state.instances)}</span>
+ </li>
+ ))}
+ </ul>
+ );
+}
+
function WhereItWent({ range, version, onBudget }: { range: { from: string; to: string }; version: number; onBudget: (budget: BudgetState | null) => void }) {
const [other, setOther] = useState<UsageGroupBy>("model");
- const byBot = useUsageGroups(range, "bot", version);
- const byOther = useUsageGroups(range, other, version);
+ const byBot = useUsageGroups(range, "bot", version, "model");
+ const byOther = useUsageGroups(range, other, version, other === "model" ? undefined : "model");
useEffect(() => { onBudget(byBot?.budget ?? null); }, [byBot, onBudget]);
return (
<section className="rounded-2xl border border-hairline/50 bg-card p-5" aria-label={t("usage.page.where")}>
@@ -122,7 +180,12 @@ function WhereItWent({ range, version, onBudget }: { range: { from: string; to:
<div className="mt-4 grid gap-6 md:grid-cols-2">
<div>
<div className="mb-3 text-[11px] font-medium uppercase tracking-[0.08em] text-ink-secondary">{t(GROUP_LABEL_KEYS.bot)}</div>
- {byBot ? <GroupBars groupBy="bot" groups={byBot.groups} /> : <Loader2 size={14} className="animate-spin text-ink-secondary" />}
+ {byBot ? (
+ <>
+ <GroupBars groupBy="bot" groups={byBot.groups} />
+ <ModelLegend groups={byBot.groups} />
+ </>
+ ) : <Loader2 size={14} className="animate-spin text-ink-secondary" />}
</div>
<div>
<div role="tablist" aria-label={t("usage.history.groupBy")} className="-mt-1 mb-2 flex flex-wrap gap-1">