Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Fix model colour matching and additive bar totals
BunBnnuyd2d4e6d532a9
diff --git a/server/usage-ledger.test.ts b/server/usage-ledger.test.tsindex 7aec5b1c77..7f0bd9a1ad 100644--- a/server/usage-ledger.test.ts+++ b/server/usage-ledger.test.ts@@ -190,6 +190,21 @@ describe("usage summaries", () => {]);});+ it("keeps the bar total additive when one row's cached input exceeds its input", () => {+ const uneven: UsageRow[] = [+ { ...row({ model: "claude-sonnet-5", input: 100, output: 10, cachedInput: 150 }), at: "2026-09-01T10:00:00.000Z" } as UsageRow,+ { ...row({ model: "gpt-6.1-sol", driverKind: "codex", instanceId: "codex", input: 500, output: 50, cachedInput: 100 }), at: "2026-09-01T11:00:00.000Z" } as UsageRow,+ ];+ const [scout] = summarizeUsage(uneven, "bot", null, "model").groups;+ const fresh = (entry: UsageRow) =>+ Math.max(0, entry.input - Math.min(entry.cachedInput ?? 0, entry.input)) + entry.output;+ const expected = uneven.reduce((sum, entry) => sum + fresh(entry), 0);+ expect(scout!.barTokens).toBe(expected);+ expect(scout!.segments!.reduce((sum, piece) => sum + (piece.barTokens ?? 0), 0)).toBe(expected);+ expect(scout!.barTokens).toBe(460);+ expect(scout!.input - Math.min(scout!.cachedInput, scout!.input) + scout!.output).toBe(410);+ });+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.tsindex 80a5601697..6d83b24d8b 100644--- a/server/usage-ledger.ts+++ b/server/usage-ledger.ts@@ -71,6 +71,8 @@ export interface UsageGroup {estimatedUsd: number | null;unpriced: number;billableUsd: number | null;+ /** The additive tokens the bar shows: fresh input plus output, summed row by row. */+ barTokens?: number;/** The group broken down by the requested split, largest first. */segments?: UsageGroup[];}@@ -282,8 +284,9 @@ function groupOf(row: UsageRow, groupBy: UsageGroupBy): { key: string; label: st}}+/** An empty group before any ledger row is booked into it. */function emptyGroup(key: string, label: string): UsageGroup {- return { key, label, turns: 0, input: 0, output: 0, cachedInput: 0, costUsd: null, estimatedUsd: null, unpriced: 0, billableUsd: null };+ return { key, label, turns: 0, input: 0, output: 0, cachedInput: 0, costUsd: null, estimatedUsd: null, unpriced: 0, billableUsd: null, barTokens: 0 };}export function costSourceOf(row: Pick<UsageRow, "costUsd" | "costSource">): CostSource | null {@@ -291,11 +294,16 @@ export function costSourceOf(row: Pick<UsageRow, "costUsd" | "costSource">): Cosreturn row.costSource === "estimated" ? "estimated" : "reported";}+/** Books one row into a group, keeping its raw aggregates and its additive bar total. */function add(group: UsageGroup, row: UsageRow, prices: PriceList | null): void {+ const input = clean(row.input);+ const output = clean(row.output);+ const cachedInput = clean(row.cachedInput);group.turns += 1;- group.input += clean(row.input);- group.output += clean(row.output);- group.cachedInput += clean(row.cachedInput);+ group.input += input;+ group.output += output;+ group.cachedInput += cachedInput;+ group.barTokens = (group.barTokens ?? 0) + Math.max(0, input - Math.min(cachedInput, input)) + output;const cost = finiteOrNull(row.costUsd);if (cost === null) group.unpriced += 1;else {@@ -306,9 +314,9 @@ function add(group: UsageGroup, row: UsageRow, prices: PriceList | null): void {if (billable !== null) group.billableUsd = (group.billableUsd ?? 0) + billable;}-/** 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;+/** The tokens a bar shows: the row-by-row sum when the ledger has it, or the old aggregate for older callers. */+function barTokensOf(group: UsageGroup): number {+ return group.barTokens ?? Math.max(0, group.input - Math.min(group.cachedInput, group.input)) + group.output;}/** Groups ledger rows by `groupBy`; when `splitBy` differs, each group also carries its pieces, largest first. */@@ -346,7 +354,7 @@ export function summarizeUsage(add(piece, row, prices);}for (const [key, inside] of splits) {- groups.get(key)!.segments = [...inside.values()].sort((a, b) => barTokens(b) - barTokens(a));+ groups.get(key)!.segments = [...inside.values()].sort((a, b) => barTokensOf(b) - barTokensOf(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.tsindex 71689927c1..b10cd974aa 100644--- a/src/components/UsageSection.bars.test.ts+++ b/src/components/UsageSection.bars.test.ts@@ -66,6 +66,12 @@ describe("Usage page bars", () => {expect(painted[1]!.title).toContain("36%");});+ it("draws the server's additive bar total instead of a clamped aggregate", () => {+ render("bot", [group({ input: 600, cachedInput: 250, output: 60, barTokens: 460 })]);+ expect(host.textContent).toContain("460");+ expect(host.textContent).not.toContain("410");+ });+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 })]);diff --git a/src/components/UsageSection.tsx b/src/components/UsageSection.tsxindex 6c3e8fcafd..d911358f99 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 additive tokens the bar shows, summed row by row on the server. */+ barTokens?: number;/** The group broken down by the requested split, largest first. */segments?: UsageGroup[];}@@ -69,6 +71,11 @@ export function usageGroupLabel(groupBy: UsageGroupBy, group: Pick<UsageGroup, "return group.label;}+/** The tokens a bar shows: the server's additive sum when present, or the older aggregate. */+function barTokens(group: UsageGroup): number {+ return group.barTokens ?? headlineTokens(group);+}+/** Loads the usage summary for a range and grouping, optionally split by model, and refreshes with `version`. */function useUsageGroups(range: { from: string; to: string },@@ -91,12 +98,12 @@ function useUsageGroups(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);+ const stack = segments.reduce((sum, piece) => sum + barTokens(piece), 0);if (segments.length && stack > 0) {return (<span className="flex h-full" style={{ width: `${width}%` }}>{segments.map((piece) => {- const tokens = headlineTokens(piece);+ const tokens = barTokens(piece);const share = Math.round((tokens / stack) * 100);return (<span@@ -117,8 +124,8 @@ function Bar({ group, width, color }: { group: UsageGroup; width: number; color?/** The six largest groups as proportional bars, with a model colour dot when the grouping is by model. */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);- const max = Math.max(...top.map(headlineTokens), 0);+ const top = [...groups].sort((a, b) => barTokens(b) - barTokens(a)).slice(0, 6);+ const max = Math.max(...top.map(barTokens), 0);if (!top.length || max <= 0) return <p className="text-[13px] text-ink-secondary">{t("usage.page.whereEmpty")}</p>;return (<ul className="flex flex-col gap-2.5">@@ -134,10 +141,10 @@ 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">- <Bar group={group} width={Math.max(2, (headlineTokens(group) / max) * 100)} color={color} />+ <Bar group={group} width={Math.max(2, (barTokens(group) / max) * 100)} color={color} /></span><span className="min-w-[4.5rem] text-right tabular-nums text-ink-secondary">- {formatTokens(headlineTokens(group))}+ {formatTokens(barTokens(group))}{hasFiniteCost(group.costUsd) && group.costUsd > 0 && ` · ${formatCost(group.costUsd)}`}</span></li>diff --git a/src/lib/model-color.test.ts b/src/lib/model-color.test.tsindex 45a2521251..1747423d60 100644--- a/src/lib/model-color.test.ts+++ b/src/lib/model-color.test.ts@@ -30,6 +30,11 @@ describe("model colours", () => {expect(modelColor("model:opencode/beam-free")).toBe(modelColor("model:opencode/beam"));});+ it("canonicalizes a provider namespace before choosing the shade", () => {+ expect(modelColor("model:test/claude-sonnet-5")).toBe(modelColor("model:openrouter/anthropic/claude-sonnet-5"));+ expect(modelColor("model:openrouter/openai/gpt-6.1-sol")).toBe(modelColor("model:codex/gpt-6.1-sol"));+ });+it("names the provider of the models seen in the ledger", () => {expect(modelFamily("model:opencodeGo/opencode-go/deepseek-v4.1-flash").id).toBe("deepseek");expect(modelFamily("model:codex/gpt-6.1-sol").id).toBe("openai");@@ -41,6 +46,19 @@ describe("model colours", () => {expect(modelFamily("model:test/mystery-model").id).toBe("unknown");});+ it("does not read a GPTQ quantization as an OpenAI model", () => {+ expect(modelFamily("model:test/Qwen2.5-72B-GPTQ").id).toBe("qwen");+ expect(modelFamily("model:test/Llama-3-8B-GPTQ").id).toBe("meta");+ expect(modelFamily("model:test/gpt-6.1-sol").id).toBe("openai");+ expect(modelFamily("model:test/gpt4").id).toBe("openai");+ });++ it("falls back to the driver when the model id is empty", () => {+ expect(modelFamily("model:claude/").id).toBe("anthropic");+ expect(modelFamily("model:opencodeGo/").id).toBe("opencode");+ expect(modelFamily("model:test/").id).toBe("unknown");+ });+it("gives each provider family its own colour", () => {const colors = ["model:claude/claude-sonnet-5",diff --git a/src/lib/model-color.ts b/src/lib/model-color.tsindex 3d6fa2d23f..be88016b90 100644--- a/src/lib/model-color.ts+++ b/src/lib/model-color.ts@@ -19,7 +19,7 @@ interface FamilyRule extends ModelFamily {const FAMILIES: readonly FamilyRule[] = [{ id: "anthropic", label: "Anthropic", color: "#D97757", pattern: /claude|anthropic|sonnet|opus|haiku/i },- { id: "openai", label: "OpenAI", color: "#0C9A76", pattern: /gpt|openai|chatgpt|codex|^o[134](?:-|$)/i },+ { id: "openai", label: "OpenAI", color: "#0C9A76", pattern: /(?:^|[-_/])gpt(?:\d|[-_.]|$)|openai|chatgpt|codex|^o[134](?:-|$)/i },{ id: "xai", label: "xAI", color: "#7D8794", pattern: /grok|xai/i },{ id: "deepseek", label: "DeepSeek", color: "#4C7DFF", pattern: /deepseek/i },{ id: "google", label: "Google", color: "#9A6BE0", pattern: /gemini|google|gemma/i },@@ -39,7 +39,7 @@ const FAMILIES: readonly FamilyRule[] = [{ id: "cursor", label: "Cursor", color: "#74818C", pattern: /cursor|composer/i },{ id: "factory", label: "Factory", color: "#7B8794", pattern: /droid/i },{ id: "greenference", label: "Greenference", color: "#3F8F5F", pattern: /greenference/i },- { id: "unknown", label: "Other", color: "#76828F", pattern: /$^/ },+ { id: "unknown", label: "Other", color: "#76828F", pattern: /(?!)/ },];/** Every family's base tone, for the contrast guard in the tests. */@@ -65,6 +65,9 @@ const DRIVER_FAMILIES: ReadonlyArray<readonly [RegExp, string]> = [const GATEWAY = /^(?:opencode-go|opencode|zen|openrouter|vercel|groq|fireworks(?:-ai)?|together(?:_ai)?|deepinfra|cerebras|togetherai|ollama|lmstudio|local)\//;+/** Provider namespaces an aggregator or a model id can carry, stripped before hashing so one model keeps one tone. */+const PROVIDER_NAMESPACE = /^(?:anthropic|openai|google|meta-llama|meta|mistralai|deepseek|qwen|moonshotai|moonshot|x-ai|xai|z-ai|zhipu|minimax|cohere|perplexity|amazon|nvidia|nousresearch|microsoft|cursor|factory)\//;+/** The model id inside a usage group key (`model:<driver>/<model>`), or the key itself. */export function modelIdOf(groupKey: string): string {if (!groupKey.startsWith("model:")) return groupKey;@@ -81,17 +84,18 @@ function driverOf(groupKey: string): string | undefined {return slash === -1 ? undefined : rest.slice(0, slash);}-/** The model name without the gateway prefix or the free/beta marker, so the same model keeps one tone on every engine. */+/** The model name without the gateway prefix, a provider namespace or the free/beta marker, so one model keeps one tone. */function coreModelId(model: string): string {let id = model.trim().toLowerCase();if (GATEWAY.test(id)) id = id.replace(GATEWAY, "");+ while (PROVIDER_NAMESPACE.test(id)) id = id.replace(PROVIDER_NAMESPACE, "");return id.replace(/(?::|-)(?:free|beta|preview|latest)$/, "");}/** The provider family a model belongs to, by its model id or its driver; unknown models use the neutral family. */export function modelFamily(groupKey: string): ModelFamily {const model = coreModelId(modelIdOf(groupKey));- const known = FAMILIES.find((family) => family.pattern.test(model));+ const known = FAMILIES.find((family) => family.id !== "unknown" && family.pattern.test(model));if (known) return known;const driver = driverOf(groupKey);const fallback = driver && DRIVER_FAMILIES.find(([pattern]) => pattern.test(driver))?.[1];