Open-source Grok Bot alternative with a virtual machine that bots can use
TypeScript ai-agentsclaude-codecodexcomputer-usedockerelectrongrokgrok-botgrok-bot-alternativeself-hostedtypescript
Spending: usage analytics charts, shown in Simple mode too (#6612)
Aditya Umale992be62cf380
diff --git a/docs/verification/usage-ledger.md b/docs/verification/usage-ledger.mdindex b99a922715..0a561c263d 100644--- a/docs/verification/usage-ledger.md+++ b/docs/verification/usage-ledger.md@@ -26,9 +26,13 @@## User path-Settings → Usage (in Simple mode, on Account) shows the period's totals, where-the money went by bot and by model (with a switch for person, day, provider and-routine), and every run. Opening a run shows its trace waterfall. In a chat, each+Settings → Spending, in Simple and Advanced mode, opens on the period's charts+(`GET /api/usage/insights`, bucketed by the viewer's time zone): the total+against the same number of days before, each provider's share and daily line,+turns, cost per turn, cache hit rate and turn length, when work happens by+weekday and hour, tokens by type, spend by person, and a breakdown by model,+bot, person, provider or day. Spend and Tokens switch the whole page. Every run+follows; opening a run shows its trace waterfall. In a chat, eachturn's work line reads "Worked for …" with **View trace** beside it. **ExportCSV** stays one line per turn.diff --git a/server/app-settings/host.test.ts b/server/app-settings/host.test.tsindex 0748f7e68e..d1b5ec5984 100644--- a/server/app-settings/host.test.ts+++ b/server/app-settings/host.test.ts@@ -122,7 +122,8 @@ describe("reads", () => {expect(JSON.parse(String(owner.body.text))).toMatchObject({ where: "Settings → Phone & devices → Pair a phone", change: "only the person, in Settings → Phone & devices → Pair a phone" });const none = await host.handle({ action: "find", query: "invoice" }, turn);expect(none.body.text).toMatch(/^No setting you can change matches "invoice"\. Where the person finds it in the app: Settings → Plan & billing/);- expect((await host.handle({ action: "places", query: "spending" }, turn)).body.text).toMatch(/^Settings → Spending \(shown in Advanced mode only/);+ expect((await host.handle({ action: "places", query: "spending" }, turn)).body.text).toMatch(/^Settings → Spending$/m);+ expect((await host.handle({ action: "places", query: "storage" }, turn)).body.text).toMatch(/^Settings → Data.*\(shown in Advanced mode only/m);const every = String((await host.handle({ action: "places" }, turn)).body.text).split("\n");expect(every[0]).toMatch(/^Settings opens from/);expect(every).toContain("Settings → AI → Other services");diff --git a/server/request-auth.test.ts b/server/request-auth.test.tsindex 32934b6737..53750f66d5 100644--- a/server/request-auth.test.ts+++ b/server/request-auth.test.ts@@ -592,6 +592,7 @@ describe("resolveRequestAuth", () => {["POST", "/api/instances/claude-work/auth/sign-out"],["GET", "/api/usage?from=2026-09-01&to=2026-09-30"],["GET", "/api/usage.csv?from=2026-09-01&to=2026-09-30"],+ ["GET", "/api/usage/insights?from=2026-09-01&to=2026-09-30"],["POST", "/api/keys/test"],["GET", "/api/fleet"],["POST", "/api/fleet/workspaces"],diff --git a/server/routes/usage.ts b/server/routes/usage.tsindex f78c1922b3..066b0b6f85 100644--- a/server/routes/usage.ts+++ b/server/routes/usage.ts@@ -15,6 +15,7 @@ import {type UsageRow,type UsageSplitBy,} from "../usage-ledger.ts";+import { insightReadRange, summarizeInsights, validTimeZone } from "../usage-insights.ts";import { DETAIL_MAX, ERROR_MAX } from "../usage-trace/detail.ts";import type { ToolReceipt, TraceRecorder } from "../usage-trace/recorder.ts";import { createTraceService, PAGE_MAX, type TraceServiceDeps } from "../usage-trace/service.ts";@@ -85,6 +86,18 @@ export function createUsageRoutes(deps: UsageRouteDeps): RouteHandler {res.setHeader("cache-control", "no-store");return found ? json(res, 200, found) : json(res, 404, { error: "no such trace" });}+ if (method === "GET" && path === "/api/usage/insights") {+ const from = url.searchParams.get("from");+ const to = url.searchParams.get("to");+ const range = parseUsageRange(from, to);+ if (!range || !from || !to) return json(res, 400, { error: "from and to must be YYYY-MM-DD, from no later than to, at most a year apart" });+ const timeZone = validTimeZone(url.searchParams.get("tz") ?? "UTC");+ if (!timeZone) return json(res, 400, { error: "tz must be an IANA time zone" });+ await flushUsageLedger(deps.dataDir);+ const rows = readUsage(deps.dataDir, insightReadRange(from, to)).map(deps.rowFor(auth));+ res.setHeader("cache-control", "no-store");+ return json(res, 200, summarizeInsights(rows, { from, to }, timeZone));+ }if (!(method === "GET" && (path === "/api/usage" || path === "/api/usage.csv"))) return PASS;const range = parseUsageRange(url.searchParams.get("from"), url.searchParams.get("to"));if (!range) return json(res, 400, { error: "from and to must be YYYY-MM-DD, from no later than to, at most a year apart" });diff --git a/server/usage-insights.test.ts b/server/usage-insights.test.tsnew file mode 100644index 0000000000..a368a7421b--- /dev/null+++ b/server/usage-insights.test.ts@@ -0,0 +1,52 @@+import { describe, expect, it } from "vitest";+import { daysBetween, insightReadRange, summarizeInsights, validTimeZone } from "./usage-insights.ts";+import type { UsageRow } from "./usage-ledger.ts";++const row = (at: string, extra: Partial<UsageRow> = {}): UsageRow => ({+ at, botId: "b1", botName: "Writer", threadId: "t", instanceId: "claude", driverKind: "claudeAgent", model: "claude-sonnet-5-5",+ input: 1_000, output: 200, cachedInput: 400, costUsd: 0.5, trigger: { kind: "owner" }, ...extra,+});++describe("summarizeInsights", () => {+ it("buckets by the viewer's local day, zero-fills the period and compares it with the days before", () => {+ const rows = [+ row("2026-11-02T20:00:00Z"), // Nov 3 in Kolkata+ row("2026-11-03T03:00:00Z", { model: "gpt-5.5-codex", driverKind: "codex", costUsd: 0.25, outcome: { status: "error" } }),+ row("2026-10-31T10:00:00Z", { costUsd: 1 }),+ row("2026-10-20T10:00:00Z", { costUsd: 9 }),+ ];+ const insights = summarizeInsights(rows, { from: "2026-11-01", to: "2026-11-03" }, "Asia/Kolkata");+ expect(insights.unit).toBe("day");+ expect(insights.buckets.map((bucket) => [bucket.start, bucket.turns])).toEqual([["2026-11-01", 0], ["2026-11-02", 0], ["2026-11-03", 2]]);+ expect(insights.buckets[2]!.models).toEqual({ "model:claudeAgent/claude-sonnet-5-5": 800, "model:codex/gpt-5.5-codex": 800 });+ expect(insights.totals).toMatchObject({ turns: 2, costUsd: 0.75, input: 1_200, cachedInput: 800, output: 400, errors: 1, activeDays: 1, days: 3 });+ expect(insights.previous).toMatchObject({ turns: 1, costUsd: 1 });+ expect(insights.models.map((entry) => entry.key)).toEqual(["model:claudeAgent/claude-sonnet-5-5", "model:codex/gpt-5.5-codex"]);+ expect(insights.hours[2]![1]! + insights.hours[2]![8]!).toBe(2);+ expect(insights.routines.map((entry) => entry.key)).toEqual(["manual"]);+ expect(insights.departments.map((entry) => entry.key)).toEqual(["department:"]);+ });++ it("uses hours for a single day and never counts a turn with no price as free", () => {+ const insights = summarizeInsights([row("2026-11-03T14:10:00Z", { costUsd: null })], { from: "2026-11-03", to: "2026-11-03" }, "UTC");+ expect(insights.unit).toBe("hour");+ expect(insights.buckets).toHaveLength(24);+ expect(insights.buckets[14]).toMatchObject({ start: "2026-11-03T14", turns: 1 });+ expect(insights.totals).toMatchObject({ costUsd: null, unpriced: 1 });+ });+});++describe("insight helpers", () => {+ it("accepts only zones the runtime knows", () => {+ expect(validTimeZone("Europe/Berlin")).toBe("Europe/Berlin");+ expect(validTimeZone("Mars/Olympus")).toBeNull();+ expect(validTimeZone(null)).toBeNull();+ });++ it("reads one extra day either side and the whole period before", () => {+ expect(daysBetween("2026-02-27", "2026-03-01")).toEqual(["2026-02-27", "2026-02-28", "2026-03-01"]);+ const range = insightReadRange("2026-11-10", "2026-11-12");+ expect(range.from.toISOString()).toBe("2026-11-06T00:00:00.000Z");+ expect(range.to.toISOString()).toBe("2026-11-13T23:59:59.999Z");+ });+});diff --git a/server/usage-insights.ts b/server/usage-insights.tsnew file mode 100644index 0000000000..a2aedbb6eb--- /dev/null+++ b/server/usage-insights.ts@@ -0,0 +1,158 @@+import type { InsightBucket, InsightEntry, InsightTokens, InsightTotals, UsageInsights } from "../shared/usage-insights.ts";+import { usageGroupOf, type UsageRow } from "./usage-ledger.ts";++const DAY_MS = 24 * 60 * 60_000;+const WEEKDAYS: Record<string, number> = { Sun: 0, Mon: 1, Tue: 2, Wed: 3, Thu: 4, Fri: 5, Sat: 6 };++const count = (value: unknown): number => typeof value === "number" && Number.isFinite(value) ? Math.max(0, Math.trunc(value)) : 0;+const price = (value: unknown): number | null => typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null;++export function validTimeZone(zone: string | null): string | null {+ if (!zone || zone.length > 64) return null;+ try {+ return new Intl.DateTimeFormat("en-US", { timeZone: zone }).resolvedOptions().timeZone;+ } catch {+ return null;+ }+}++interface LocalTime { day: string; weekday: number; hour: number }++function localClock(timeZone: string): (at: number) => LocalTime {+ const format = new Intl.DateTimeFormat("en-US", {+ timeZone, year: "numeric", month: "2-digit", day: "2-digit", hour: "2-digit", hourCycle: "h23", weekday: "short",+ });+ return (at) => {+ const parts: Record<string, string> = {};+ for (const part of format.formatToParts(at)) parts[part.type] = part.value;+ return { day: `${parts.year}-${parts.month}-${parts.day}`, weekday: WEEKDAYS[parts.weekday!] ?? 0, hour: Number(parts.hour) % 24 };+ };+}++export function daysBetween(from: string, to: string): string[] {+ const days: string[] = [];+ for (let at = Date.parse(`${from}T00:00:00Z`); at <= Date.parse(`${to}T00:00:00Z`); at += DAY_MS) {+ days.push(new Date(at).toISOString().slice(0, 10));+ }+ return days;+}++const shiftDay = (day: string, by: number) => new Date(Date.parse(`${day}T00:00:00Z`) + by * DAY_MS).toISOString().slice(0, 10);++export function insightReadRange(from: string, to: string): { from: Date; to: Date } {+ const length = daysBetween(from, to).length;+ return { from: new Date(Date.parse(`${shiftDay(from, -length - 1)}T00:00:00Z`)), to: new Date(Date.parse(`${shiftDay(to, 1)}T23:59:59.999Z`)) };+}++const freshInput = (row: UsageRow) => Math.max(0, count(row.input) - Math.min(count(row.cachedInput), count(row.input)));++function addTokens(into: InsightTokens, row: UsageRow): void {+ into.input += freshInput(row);+ into.cachedInput += Math.min(count(row.cachedInput), count(row.input));+ into.output += count(row.output);+ into.reasoning += count(row.reasoning);+}++const rowDuration = (row: UsageRow): number | null => {+ if (!row.startedAt || !row.endedAt) return null;+ const span = Date.parse(row.endedAt) - Date.parse(row.startedAt);+ return Number.isFinite(span) && span >= 0 ? span : null;+};++const failed = (row: UsageRow) => row.outcome?.status === "error";++function totalsOf(rows: readonly { row: UsageRow; local: LocalTime }[], days: number): InsightTotals {+ const totals: InsightTotals = { input: 0, cachedInput: 0, output: 0, reasoning: 0, turns: 0, costUsd: null, unpriced: 0, errors: 0, tools: 0, durationMs: 0, timedTurns: 0, activeDays: 0, days };+ const active = new Set<string>();+ for (const { row, local } of rows) {+ addTokens(totals, row);+ totals.turns += 1;+ const cost = price(row.costUsd);+ if (cost === null) totals.unpriced += 1;+ else totals.costUsd = (totals.costUsd ?? 0) + cost;+ if (failed(row)) totals.errors += 1;+ totals.tools += count(row.tools);+ const duration = rowDuration(row);+ if (duration !== null) { totals.durationMs += duration; totals.timedTurns += 1; }+ active.add(local.day);+ }+ totals.activeDays = active.size;+ return totals;+}++function entries(rows: readonly UsageRow[], keyOf: (row: UsageRow) => { key: string; label: string; driverKind?: string }): InsightEntry[] {+ const found = new Map<string, InsightEntry>();+ for (const row of rows) {+ const { key, label, driverKind } = keyOf(row);+ let entry = found.get(key);+ if (!entry) {+ entry = { key, label, input: 0, cachedInput: 0, output: 0, reasoning: 0, turns: 0, costUsd: null, errors: 0, durationMs: 0, timedTurns: 0, ...(driverKind ? { driverKind } : {}) };+ found.set(key, entry);+ }+ addTokens(entry, row);+ entry.turns += 1;+ const cost = price(row.costUsd);+ if (cost !== null) entry.costUsd = (entry.costUsd ?? 0) + cost;+ if (failed(row)) entry.errors += 1;+ const duration = rowDuration(row);+ if (duration !== null) { entry.durationMs += duration; entry.timedTurns += 1; }+ }+ const weight = (entry: InsightEntry) => entry.input + entry.output;+ return [...found.values()].sort((a, b) => (b.costUsd ?? -1) - (a.costUsd ?? -1) || weight(b) - weight(a));+}++export function summarizeInsights(rows: readonly UsageRow[], range: { from: string; to: string }, timeZone: string): UsageInsights {+ const clock = localClock(timeZone);+ const dayList = daysBetween(range.from, range.to);+ const previousFrom = shiftDay(range.from, -dayList.length);+ const previousTo = shiftDay(range.from, -1);+ const current: { row: UsageRow; local: LocalTime }[] = [];+ const before: { row: UsageRow; local: LocalTime }[] = [];+ for (const row of rows) {+ const at = Date.parse(row.at);+ if (!Number.isFinite(at)) continue;+ const local = clock(row.startedAt && Number.isFinite(Date.parse(row.startedAt)) ? Date.parse(row.startedAt) : at);+ if (local.day >= range.from && local.day <= range.to) current.push({ row, local });+ else if (local.day >= previousFrom && local.day <= previousTo) before.push({ row, local });+ }++ const unit = dayList.length === 1 ? "hour" : "day";+ const starts = unit === "hour" ? Array.from({ length: 24 }, (_, hour) => `${range.from}T${String(hour).padStart(2, "0")}`) : dayList;+ const buckets = new Map<string, InsightBucket>(starts.map((start) => [start, {+ start, input: 0, cachedInput: 0, output: 0, reasoning: 0, turns: 0, costUsd: 0, unpriced: 0, errors: 0, durationMs: 0, timedTurns: 0, models: {}, modelCosts: {},+ }]));+ const hours = Array.from({ length: 7 }, () => Array<number>(24).fill(0));+ for (const { row, local } of current) {+ const day = buckets.get(unit === "hour" ? `${local.day}T${String(local.hour).padStart(2, "0")}` : local.day)!;+ addTokens(day, row);+ day.turns += 1;+ const cost = price(row.costUsd);+ if (cost === null) day.unpriced += 1;+ else day.costUsd += cost;+ if (failed(row)) day.errors += 1;+ const duration = rowDuration(row);+ if (duration !== null) { day.durationMs += duration; day.timedTurns += 1; }+ const model = usageGroupOf(row, "model").key;+ day.models[model] = (day.models[model] ?? 0) + freshInput(row) + count(row.output);+ day.modelCosts[model] = (day.modelCosts[model] ?? 0) + (cost ?? 0);+ hours[local.weekday]![local.hour]! += 1;+ }++ const rowsNow = current.map((item) => item.row);+ return {+ from: range.from,+ to: range.to,+ timeZone,+ totals: totalsOf(current, dayList.length),+ previous: totalsOf(before, dayList.length),+ unit,+ buckets: [...buckets.values()],+ hours,+ models: entries(rowsNow, (row) => ({ ...usageGroupOf(row, "model"), driverKind: row.driverKind })),+ bots: entries(rowsNow, (row) => usageGroupOf(row, "bot")),+ engines: entries(rowsNow, (row) => usageGroupOf(row, "engine")),+ people: entries(rowsNow, (row) => usageGroupOf(row, "user")),+ routines: entries(rowsNow, (row) => usageGroupOf(row, "routine")),+ departments: entries(rowsNow, (row) => usageGroupOf(row, "department")),+ };+}diff --git a/server/usage-ledger.ts b/server/usage-ledger.tsindex 6d83b24d8b..e1bfe89a6b 100644--- a/server/usage-ledger.ts+++ b/server/usage-ledger.ts@@ -259,7 +259,7 @@ export function triggerLabel(trigger: UsageTrigger): string {}}-function groupOf(row: UsageRow, groupBy: UsageGroupBy): { key: string; label: string } {+export function usageGroupOf(row: UsageRow, groupBy: UsageGroupBy): { key: string; label: string } {switch (groupBy) {case "bot":return { key: `bot:${row.botId}`, label: row.botName || row.botId };@@ -331,7 +331,7 @@ export function summarizeUsage(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);+ const { key, label } = usageGroupOf(row, groupBy);let group = groups.get(key);if (!group) {group = emptyGroup(key, label);@@ -345,7 +345,7 @@ export function summarizeUsage(inside = new Map();splits.set(key, inside);}- const pieceOf = groupOf(row, split);+ const pieceOf = usageGroupOf(row, split);let piece = inside.get(pieceOf.key);if (!piece) {piece = emptyGroup(pieceOf.key, pieceOf.label);diff --git a/shared/settings-places.ts b/shared/settings-places.tsindex d026ba183e..e1134e4196 100644--- a/shared/settings-places.ts+++ b/shared/settings-places.ts@@ -20,7 +20,7 @@ export const SETTINGS_PLACES = [{"id":"page:bots","path":"Settings → You and your bots","words":["all bots","bots","about you","about me","profile","new bots","defaults","effort","limits","rules"],"advanced":true},{"id":"page:desktops","path":"Settings → Desktops & browser","words":["bot desktops","computer","desktop","desktops","browser","built-in browser","proxy","socks5","private desktop","sandbox","docker","podman","container","vps","own server","cloud desktops"],"advanced":true},{"id":"page:vault","path":"Settings → Vault","words":["vault","password","passwords","login","logins","secrets","1password","2fa"]},- {"id":"page:usage","path":"Settings → Spending","words":["spending","usage","cost","costs","tokens","money","runs","export csv"],"advanced":true},+ {"id":"page:usage","path":"Settings → Spending","words":["spending","usage","cost","costs","tokens","money","runs","export csv"]},{"id":"page:transfer","path":"Settings → Import & export","words":["import","export","backup","backups","restore","grok","grok bot","move from","bring"]},{"id":"page:data","path":"Settings → Data","words":["data","storage","attachments","activity","audit"],"advanced":true},{"id":"page:people","path":"Settings → People","words":["people","members","invite","roles","bot access","sharing","team"],"only":"a team's or a self-hosted server's Settings, for admins"},@@ -62,7 +62,7 @@ export const SETTINGS_PLACES = [{"id":"desktop-kinds","path":"Settings → Desktops & browser → Desktops","words":["private desktop","sandbox","docker","podman","container","vps","own server","cloud desktops","desktop","vm"],"advanced":true},{"id":"saved-steps","path":"Settings → Desktops & browser → Repeat computer tasks without AI","words":["repeat","saved steps","without ai"],"advanced":true},{"id":"vault","path":"Settings → Vault","words":["password","passwords","login","logins","secrets","1password","2fa","totp"]},- {"id":"spending","path":"Settings → Spending","words":["spending","cost","costs","tokens","money","usage"],"advanced":true},+ {"id":"spending","path":"Settings → Spending","words":["spending","cost","costs","tokens","money","usage"]},{"id":"grok-move","path":"Settings → Import & export → Bring things in → Move from Grok Bot","words":["grok","grok bot","move from","import","bring","another app"]},{"id":"ai-apps","path":"Settings → Import & export → Bring things in → From your AI apps","words":["import","bring","skills","mcp","claude code","codex","cursor","gemini"]},{"id":"backup-import","path":"Settings → Import & export → Bring things in → Import backup","words":["restore","import","bring","backup","backups","bring back"]},diff --git a/shared/usage-insights.ts b/shared/usage-insights.tsnew file mode 100644index 0000000000..30286d4c77--- /dev/null+++ b/shared/usage-insights.ts@@ -0,0 +1,71 @@+/** Token counts as the insights page shows them: `input` is fresh input, without the cached part. */+export interface InsightTokens {+ input: number;+ cachedInput: number;+ output: number;+ reasoning: number;+}++/** One period's figures. `cost` is null when no turn in it had a price. */+export interface InsightTotals extends InsightTokens {+ turns: number;+ costUsd: number | null;+ /** Turns whose model has no price; they add tokens but no dollars. */+ unpriced: number;+ errors: number;+ tools: number;+ /** Summed over timed turns only; `timedTurns` says how many. */+ durationMs: number;+ timedTurns: number;+ /** Distinct local days with at least one turn, out of `days` in the period. */+ activeDays: number;+ days: number;+}++/** One local day, or one local hour when the period is a single day; zero-filled when nothing ran. `start` is+ * YYYY-MM-DD or YYYY-MM-DDTHH. `models` maps a model key to its fresh-input plus output tokens, `modelCosts` to its dollars.+ * `costUsd` sums the priced turns only; `unpriced` counts the others. */+export interface InsightBucket extends InsightTokens {+ start: string;+ turns: number;+ costUsd: number;+ unpriced: number;+ errors: number;+ durationMs: number;+ timedTurns: number;+ models: Record<string, number>;+ modelCosts: Record<string, number>;+}++/** A series or a leaderboard entry: a bot, a model, an engine or a person. */+export interface InsightEntry extends InsightTokens {+ key: string;+ label: string;+ turns: number;+ costUsd: number | null;+ errors: number;+ durationMs: number;+ timedTurns: number;+ /** Set on a model entry: the engine it ran on. */+ driverKind?: string;+}++/** `GET /api/usage/insights?from&to&tz`: one period read back for charts, in the viewer's time zone. */+export interface UsageInsights {+ from: string;+ to: string;+ timeZone: string;+ totals: InsightTotals;+ /** The same number of days just before `from`, for the change figures. */+ previous: InsightTotals;+ unit: "day" | "hour";+ buckets: InsightBucket[];+ /** Turns started in each hour of each weekday, Sunday first: `hours[weekday][hour]`. */+ hours: number[][];+ models: InsightEntry[];+ bots: InsightEntry[];+ engines: InsightEntry[];+ people: InsightEntry[];+ routines: InsightEntry[];+ departments: InsightEntry[];+}diff --git a/src/components/UsageSection.tsx b/src/components/UsageSection.tsxindex 897e0c5ea0..9cbca20df9 100644--- a/src/components/UsageSection.tsx+++ b/src/components/UsageSection.tsx@@ -1,12 +1,12 @@import { useContext, useEffect, useMemo, useRef, useState } from "react";-import { SettingRow, SettingsEmptyRow, SettingsGroup, SettingsLook, SettingsRows } from "./SettingsPrimitives";+import { Segmented, SettingsEmptyRow, SettingsGroup, SettingsLook, SettingsRows, SIMPLE_CARD } from "./SettingsPrimitives";import { ArrowLeft, ChevronRight, Download, Loader2 } from "lucide-react";import { cn } from "@/lib/cn";import { activeLocale, documentLanguage, t } from "@/lib/i18n";import { listenLiveFrames } from "@/lib/live-events";import { modelColor, modelFamily } from "@/lib/model-color";import { formatTokens, hasFiniteCost, headlineTokens } from "@/lib/usage";-import { currentBotName, fetchTraces, formatCost, formatDuration, runTitle, USAGE_PERIODS, usageExportHref, usagePeriodRange, type UsagePeriod } from "@/lib/usage-trace";+import { currentBotName, fetchTraces, formatCost, formatDuration, localPeriodRange, runTitle, USAGE_PERIODS, usageExportHref, type UsagePeriod } from "@/lib/usage-trace";import { api, useStore } from "@/state/store";import type { LocaleKey } from "@/locales";import type { TraceList, TraceRootSummary } from "../../shared/usage-trace";@@ -16,7 +16,8 @@ import { Select } from "./Select";import { UsageBudgetCards, type BudgetState } from "./UsageBudget";import { UsageCapsCard, type UsageCapView } from "./UsageCaps";import { TraceView } from "./usage/TraceView";-import { LiveBadge, modelName, StatStrip, totalsStats } from "./usage/TraceWaterfall";+import { LiveBadge, modelName } from "./usage/TraceWaterfall";+import { UsageInsightsPanel, type InsightMetric } from "./usage/UsageInsights";export type UsageGroupBy = "bot" | "model" | "user" | "day" | "engine" | "routine" | "department";const OTHER_GROUPINGS: readonly UsageGroupBy[] = ["model", "user", "department", "day", "engine", "routine"];@@ -75,6 +76,7 @@ const PERIOD_LABEL_KEYS: Record<UsagePeriod, LocaleKey> = {month: "usage.history.thisMonth",lastMonth: "usage.history.lastMonth",days30: "usage.history.last30Days",+ days90: "usage.history.last90Days",};const LIVE_REFRESH_MS = 2_000;@@ -202,12 +204,11 @@ function ModelLegend({ groups }: { groups: readonly UsageGroup[] }) {}/** The "Where it went" panel: bots on one side, the chosen grouping on the other, both split by model. */-function WhereItWent({ range, version, onSummary }: { range: { from: string; to: string }; version: number; onSummary: (summary: UsageSummary | null) => void }) {+function WhereItWent({ range, version }: { range: { from: string; to: string }; version: number }) {const [other, setOther] = useState<UsageGroupBy>("model");const settings = useContext(SettingsLook);const byBot = useUsageGroups(range, "bot", version, "model");const byOther = useUsageGroups(range, other, version, other === "model" ? undefined : "model");- useEffect(() => { onSummary(byBot); }, [byBot, onSummary]);if (settings) return null;return (<section className="rounded-2xl border border-hairline/50 bg-card p-5" aria-label={t("usage.page.where")}>@@ -243,37 +244,6 @@ function WhereItWent({ range, version, onSummary }: { range: { from: string; to:);}-const SETTINGS_GROUPINGS: readonly UsageGroupBy[] = ["bot", ...OTHER_GROUPINGS];--/** Settings' Where it went: a select (by bot, model, person…) as the section's action, then one row per item. */-function SettingsWhereItWent({ range, version, onSummary }: { range: { from: string; to: string }; version: number; onSummary: (summary: UsageSummary | null) => void }) {- const { state } = useStore();- const [by, setBy] = useState<UsageGroupBy>("bot");- const byBot = useUsageGroups(range, "bot", version);- const groups = useUsageGroups(range, by, version);- useEffect(() => { onSummary(byBot); }, [byBot, onSummary]);- const top = groups?.groupBy === by ? [...groups.groups].sort((a, b) => headlineTokens(b) - headlineTokens(a)).filter((group) => headlineTokens(group) > 0).slice(0, 8) : null;- return (- <SettingsGroup label={t("usage.page.where")} block="where"- actions={<Select value={by} onChange={(event) => setBy(event.target.value as UsageGroupBy)} aria-label={t("usage.history.groupBy")}>- {SETTINGS_GROUPINGS.map((option) => <option key={option} value={option}>{t(GROUP_LABEL_KEYS[option])}</option>)}- </Select>}>- <SettingsRows>- {!top ? <SettingsEmptyRow>{t("common.checking")}</SettingsEmptyRow>- : top.length === 0 ? <SettingsEmptyRow>{t("usage.page.whereEmpty")}</SettingsEmptyRow>- : top.map((group) => (- <SettingRow key={group.key} title={by === "model" ? modelName(group.label, state.instances) : usageGroupLabel(by, group)}- subtitle={t("usage.page.turns", { count: String(group.turns) })}>- <span className="text-[13px] leading-5 tabular-nums text-ink-secondary">- {formatTokens(headlineTokens(group))}{hasFiniteCost(group.costUsd) && group.costUsd > 0 ? ` · ${formatCost(group.costUsd)}` : ""}- </span>- </SettingRow>- ))}- </SettingsRows>- </SettingsGroup>- );-}-function startedLabel(at: number): string {return new Date(at).toLocaleString(documentLanguage(activeLocale()), { month: "short", day: "numeric", hour: "numeric", minute: "2-digit" });}@@ -310,15 +280,16 @@ export function RunRow({ root, onOpen }: { root: TraceRootSummary; onOpen: () =>);}-/** The Usage page: a period's totals, where the money went, and every run as a trace. */+/** The Usage page: the period's analytics, every run as a trace, and the limits that apply. */export function UsageSection() {const settings = useContext(SettingsLook);- const [period, setPeriod] = useState<UsagePeriod>("month");- const range = useMemo(() => usagePeriodRange(period), [period]);+ const [period, setPeriod] = useState<UsagePeriod>("days30");+ const [metric, setMetric] = useState<InsightMetric>("cost");+ const range = useMemo(() => localPeriodRange(period), [period]);const [list, setList] = useState<TraceList | null>(null);const [error, setError] = useState<string | null>(null);const [version, setVersion] = useState(0);- const [summary, setSummary] = useState<UsageSummary | null>(null);+ const summary = useUsageGroups(range, "bot", version);const budget = summary?.budget ?? null;const [open, setOpen] = useState<{ id: string; at: number } | null>(null);const pending = useRef<ReturnType<typeof setTimeout> | null>(null);@@ -347,9 +318,20 @@ export function UsageSection() {void fetchTraces(range, list.next).then((page) => setList((current) => current ? { ...page, roots: [...current.roots, ...page.roots] } : page));};const untimed = list?.roots.some((root) => !root.timed);+ const choosePeriod = (next: UsagePeriod) => { setPeriod(next); setOpen(null); };+ const controls = (+ <div className="flex flex-wrap items-center gap-2" data-testid="usage-controls">+ <Select size={settings ? undefined : "sm"} value={period} onChange={(event) => choosePeriod(event.target.value as UsagePeriod)} aria-label={t("usage.history.period")}>+ {USAGE_PERIODS.map((option) => <option key={option} value={option}>{t(PERIOD_LABEL_KEYS[option])}</option>)}+ </Select>+ <Segmented<InsightMetric> value={metric} onChange={setMetric} label={t("insights.measure")}+ options={[{ value: "cost", label: t("insights.spend") }, { value: "tokens", label: t("insights.tokens") }]} />+ </div>+ );+ const insights = <UsageInsightsPanel range={range} version={version} metric={metric} groupLabel={usageGroupLabel}+ card={settings ? SIMPLE_CARD : "rounded-2xl border border-hairline/50 bg-card"} />;if (settings) {- const totals = list?.totals;return (<div className="flex flex-col gap-6" data-testid="usage-page">{open ? (@@ -359,27 +341,14 @@ export function UsageSection() {</button>)} />) : <>- {/* The period select is the section's one action; the totals are rows. */}- <SettingsGroup label={t("usage.page.summary")} block="totals"- actions={<Select value={period} onChange={(event) => { setPeriod(event.target.value as UsagePeriod); setOpen(null); }} aria-label={t("usage.history.period")}>- {USAGE_PERIODS.map((option) => <option key={option} value={option}>{t(PERIOD_LABEL_KEYS[option])}</option>)}- </Select>}- footnote={error ? <span role="alert" className="text-danger">{error}</span> : undefined}>- <SettingsRows>- <div data-testid="usage-totals" className="contents">- {totals ? <>- <SettingRow title={t("trace.stat.cost")}><span className="text-[13px] leading-5 tabular-nums text-ink-secondary">{totals.costUsd ? t("usage.page.estimated", { cost: formatCost(totals.costUsd) }) : formatCost(0)}</span></SettingRow>- <SettingRow title={t("usage.page.runs")}><span className="text-[13px] leading-5 tabular-nums text-ink-secondary">{String(list.roots.length)}{list.next !== undefined ? "+" : ""}</span></SettingRow>- <SettingRow title={t("trace.stat.errors")}><span className="text-[13px] leading-5 tabular-nums text-ink-secondary">{String(totals.errors)}</span></SettingRow>- <SettingRow title={t("trace.stat.time")}><span className="text-[13px] leading-5 tabular-nums text-ink-secondary">{totals.durationMs > 0 ? formatDuration(Math.max(1_000, totals.durationMs)) : "—"}</span></SettingRow>- </> : <SettingsEmptyRow>{t("common.checking")}</SettingsEmptyRow>}- </div>- </SettingsRows>- </SettingsGroup>+ <div className="flex flex-wrap items-center justify-between gap-3">+ {controls}+ <a href={usageExportHref(range)} download className="ui-button ui-button-md rounded-full">{t("usage.history.export")}</a>+ </div>+ {error && <p role="alert" className="px-1 text-[12px] text-danger">{error}</p>}+ {insights}<CostCaveats summary={summary} />- <SettingsWhereItWent range={range} version={version} onSummary={setSummary} />- <SettingsGroup label={t("usage.page.runs")} block="runs" footnote={untimed ? t("usage.page.untimedNote") : undefined}- actions={<a href={usageExportHref(range)} download className="ui-button ui-button-md rounded-full">{t("usage.history.export")}</a>}>+ <SettingsGroup label={t("usage.page.runs")} block="runs" footnote={untimed ? t("usage.page.untimedNote") : undefined}><SettingsRows>{list && !list.roots.length && <SettingsEmptyRow>{t("usage.page.runsEmpty")}</SettingsEmptyRow>}{list?.roots.length ? <ul className="flex flex-col p-1">{list.roots.map((root) => <RunRow key={root.id} root={root} onOpen={() => setOpen({ id: root.id, at: root.startedAt })} />)}</ul> : null}@@ -396,16 +365,12 @@ export function UsageSection() {return (<div className="flex flex-col gap-4" data-testid="usage-page">- <div className="flex flex-col gap-3 sm:flex-row sm:items-center sm:gap-4">- <p className="min-w-0 flex-1 text-[13px] leading-relaxed text-ink-secondary">{t("usage.page.subtitle")}</p>- <div className="flex items-center gap-2">- <Select size="sm" value={period} onChange={(event) => { setPeriod(event.target.value as UsagePeriod); setOpen(null); }} aria-label={t("usage.history.period")}>- {USAGE_PERIODS.map((option) => <option key={option} value={option}>{t(PERIOD_LABEL_KEYS[option])}</option>)}- </Select>- <a href={usageExportHref(range)} download className="flex items-center gap-1.5 rounded-lg border border-hairline/40 px-2.5 py-1 text-[12px] text-ink-secondary hover:bg-raised/50 hover:text-ink">- <Download size={13} />{t("usage.history.export")}- </a>- </div>+ <p className="text-[13px] leading-relaxed text-ink-secondary">{t("usage.page.subtitle")}</p>+ <div className="flex flex-wrap items-center justify-between gap-3">+ {controls}+ <a href={usageExportHref(range)} download className="flex items-center gap-1.5 rounded-lg border border-hairline/40 px-2.5 py-1 text-[12px] text-ink-secondary hover:bg-raised/50 hover:text-ink">+ <Download size={13} />{t("usage.history.export")}+ </a></div>{error && <p role="alert" className="text-[12px] text-danger">{error}</p>}{open ? (@@ -416,12 +381,9 @@ export function UsageSection() {)} />) : (<>- <section className="overflow-hidden rounded-2xl border border-hairline/50 bg-card" data-testid="usage-totals">- {list ? <StatStrip items={totalsStats(list.totals, t("trace.stat.time"))} />- : <div className="flex items-center gap-2 p-5 text-[13px] text-ink-secondary"><Loader2 size={14} className="animate-spin" />{t("common.checking")}</div>}- </section>+ {insights}<CostCaveats summary={summary} />- <WhereItWent range={range} version={version} onSummary={setSummary} />+ <WhereItWent range={range} version={version} /><section className="rounded-2xl border border-hairline/50 bg-card p-2" aria-label={t("usage.page.runs")}><div className="px-3 pb-1 pt-3"><h3 className="text-[15px] font-medium text-ink">{t("usage.page.runs")}</h3>diff --git a/src/components/settings/SettingsWindow.test.ts b/src/components/settings/SettingsWindow.test.tsindex 9d3f1bcdab..8fea7b63f4 100644--- a/src/components/settings/SettingsWindow.test.ts+++ b/src/components/settings/SettingsWindow.test.ts@@ -77,21 +77,20 @@ describe("the Settings window", () => {expect(render("appearance")).toContain("MausBot on this device");});- // Owner decisions (Nov 11, Nov 12): Simple's nav is shorter. Nine entries, the same for every person and every rail.- const SIMPLE_NAV = ["overview", "phone", "ai", "vault", "transfer", "account", "plan", "app", "appearance"];+ const SIMPLE_NAV = ["overview", "phone", "ai", "vault", "usage", "transfer", "account", "plan", "app", "appearance"];const SIMPLE_PEOPLE: Array<[string, () => void]> = [["a person with only this computer", () => vi.stubGlobal("window", desktopHere({ cloudAccount: { state: () => new Promise(() => {}), onState: () => () => {} } }))],["This computer's rail, with My Cloud", () => vi.stubGlobal("window", desktopHere({ cloudAccount: { state: () => new Promise(() => {}), onState: () => () => {} }, workspaces: { state: () => new Promise(() => {}), places: () => new Promise(() => {}) } }))],["My Cloud's rail in the desktop window", () => { vi.stubGlobal("window", { ogb: { platform: "darwin", cloudPlan: { state: () => new Promise(() => {}) }, workspaces: { state: () => new Promise(() => {}), places: () => new Promise(() => {}) } } }); fixture.config = { cloudHome: true }; }],["My Cloud in a browser", () => { vi.stubGlobal("window", {}); fixture.config = { cloudHome: true }; }],];- it.each(SIMPLE_PEOPLE)("shows Simple's nine entries for %s", (_who, set) => {+ it.each(SIMPLE_PEOPLE)("shows Simple's ten entries for %s", (_who, set) => {set();fixture.advanced = false;expect(navPages(render("overview"))).toEqual(SIMPLE_NAV);fixture.advanced = true;const advanced = navPages(render("overview"));- for (const page of ["bots", "desktops", "usage", "data", "general"]) expect(advanced).toContain(page);+ for (const page of ["bots", "desktops", "data", "general"]) expect(advanced).toContain(page);});it("keeps the rows a Simple person needs: language and notifications on This app", () => {diff --git a/src/components/settings/closed-scale.test.ts b/src/components/settings/closed-scale.test.tsindex 45149527be..df134ea6ab 100644--- a/src/components/settings/closed-scale.test.ts+++ b/src/components/settings/closed-scale.test.ts@@ -67,6 +67,7 @@ const FILES = ["src/components/ThreadCleanupSettings.tsx","src/components/ThreadConcurrencySettings.tsx","src/components/UsageSection.tsx",+ "src/components/usage/UsageInsights.tsx","src/components/VaultSettings.tsx","src/components/VpsComputersCard.tsx","src/components/WindowFrameBar.tsx",diff --git a/src/components/settings/settings-index.test.ts b/src/components/settings/settings-index.test.tsindex e6d1c27e2b..3c4abae477 100644--- a/src/components/settings/settings-index.test.ts+++ b/src/components/settings/settings-index.test.ts@@ -34,14 +34,12 @@ describe("the pages", () => {expect(ids(ctx).filter((id) => PLACE_PAGES.includes(id))).toEqual(expected);});- // Owner decisions (Nov 11, Nov 12): Simple shows nine entries, Import & export among them; Advanced adds You and your- // bots, Desktops & browser, Spending, Data and General in their places.it.each(["local only", "This computer, with My Cloud", "My Cloud's page in the desktop window", "My Cloud in a browser (owner)"] as const)(- "shows Simple's nine entries for %s", (who) => {- expect(ids({ ...PEOPLE[who], advanced: false })).toEqual(["overview", "phone", "ai", "vault", "transfer", "account", "plan", "app", "appearance"]);+ "shows Simple's ten entries for %s", (who) => {+ expect(ids({ ...PEOPLE[who], advanced: false })).toEqual(["overview", "phone", "ai", "vault", "usage", "transfer", "account", "plan", "app", "appearance"]);});- it("is shorter in Simple: the five Advanced pages come back in Advanced, in place", () => {+ it("is shorter in Simple: the four Advanced pages come back in Advanced, in place", () => {const simple = ids(fullContext({ advanced: false }));for (const page of ADVANCED_PAGES) expect(simple).not.toContain(page);expect(ids(fullContext()).filter((id) => simple.includes(id))).toEqual(simple);@@ -68,11 +66,13 @@ describe("the pages", () => {it("finds every Advanced-only row from Simple, marked Advanced; Simple's own homes win for moved rows", () => {const simple = fullContext({ advanced: false });- for (const query of ["parallel threads", "effort", "spending", "send", "storage"]) {+ for (const query of ["parallel threads", "effort", "send", "storage"]) {const hit = find(query, simple)[0];expect(hit, query).toBeDefined();expect(hit!.advanced, query).toBe(true);}+ expect(find("spending", simple)[0]).toMatchObject({ entry: { page: "usage" } });+ expect(find("spending", simple)[0]?.advanced).toBeUndefined();expect(find("language", simple)[0]?.entry.page).toBe("app");expect(find("backups", simple)[0]).toMatchObject({ entry: { page: "transfer" }, advanced: undefined });});diff --git a/src/components/settings/settings-index.ts b/src/components/settings/settings-index.tsindex 03e7b9dbec..de5477951d 100644--- a/src/components/settings/settings-index.ts+++ b/src/components/settings/settings-index.ts@@ -49,9 +49,9 @@ const notClient = (ctx: SettingsContext) => !ctx.client;const adminPage = (ctx: SettingsContext) => !ctx.client && !(ctx.team && !ctx.admin);/** A page Simple mode leaves out: its everyday rows show elsewhere in Simple (Overview, This app, Plan & billing). */const advancedOnly = (when: (ctx: SettingsContext) => boolean) => (ctx: SettingsContext) => ctx.advanced && when(ctx);-/** Simple mode's nine entries: the place (Overview, Phone & devices, AI, Vault, Import & export), Your account- * (Plan & billing) and This app (Appearance). Advanced adds You and your bots, Desktops & browser, Spending, Data and General. */-export const ADVANCED_PAGES: readonly SettingsPageId[] = ["bots", "desktops", "usage", "data", "general"];+/** Simple mode's ten entries: the place (Overview, Phone & devices, AI, Vault, Spending, Import & export), Your account+ * (Plan & billing) and This app (Appearance). Advanced adds You and your bots, Desktops & browser, Data and General. */+export const ADVANCED_PAGES: readonly SettingsPageId[] = ["bots", "desktops", "data", "general"];export const SETTINGS_PAGES: readonly SettingsPage[] = [{ id: "overview", owner: "place", labelKey: "settings.page.overview", synonyms: ["overview", "place", "status", "version", "domain", "address", "sidebar"], when: () => true },@@ -65,7 +65,7 @@ export const SETTINGS_PAGES: readonly SettingsPage[] = [synonyms: ["bot desktops", "computer", "desktop", "desktops", "browser", "built-in browser", "proxy", "socks5", "private desktop", "sandbox", "docker", "podman", "container", "vps", "own server", "cloud desktops"] },{ id: "vault", owner: "place", labelKey: "settings.section.vault", icon: LockKeyhole, when: notClient,synonyms: ["vault", "password", "passwords", "login", "logins", "secrets", "1password", "2fa"] },- { id: "usage", owner: "place", labelKey: "settings.page.spending", icon: Coins, when: advancedOnly(adminPage),+ { id: "usage", owner: "place", labelKey: "settings.page.spending", icon: Coins, when: adminPage,synonyms: ["spending", "usage", "cost", "costs", "tokens", "money", "runs", "export csv"] },{ id: "transfer", owner: "place", labelKey: "settings.page.importExport", icon: ArrowLeftRight, when: adminPage,synonyms: ["import", "export", "backup", "backups", "restore", "grok", "grok bot", "move from", "bring"] },diff --git a/src/components/usage/UsageInsights.tsx b/src/components/usage/UsageInsights.tsxnew file mode 100644index 0000000000..c09260f089--- /dev/null+++ b/src/components/usage/UsageInsights.tsx@@ -0,0 +1,666 @@+import { useEffect, useLayoutEffect, useMemo, useRef, useState, type KeyboardEvent, type PointerEvent, type ReactNode } from "react";+import { ArrowDownRight, ArrowUpRight, Loader2 } from "lucide-react";+import { cn } from "@/lib/cn";+import { activeLocale, documentLanguage, t } from "@/lib/i18n";+import { modelColor, modelFamily } from "@/lib/model-color";+import { formatTokens, usdText } from "@/lib/usage";+import { formatCost, formatDuration } from "@/lib/usage-trace";+import { api, useStore } from "@/state/store";+import type { LocaleKey } from "@/locales";+import type { InsightBucket, InsightEntry, InsightTotals, UsageInsights } from "../../../shared/usage-insights";+import { BotAvatar } from "../Avatar";+import { Select } from "../Select";+import { modelName } from "./TraceWaterfall";++export type InsightMetric = "cost" | "tokens";++const CHART_TITLES: Record<InsightMetric, Record<UsageInsights["unit"], LocaleKey>> = {+ cost: { day: "insights.dailyCost", hour: "insights.hourlyCost" },+ tokens: { day: "insights.dailyTokens", hour: "insights.hourlyTokens" },+};+type Board = "models" | "bots" | "people" | "engines" | "routines" | "departments" | "time";+/** Names a bot, person, routine or department entry the way the rest of Usage does, in the viewer's language. */+export type GroupLabel = (groupBy: "bot" | "user" | "routine" | "department", entry: Pick<InsightEntry, "key" | "label">) => string;++const ink = (share: number) => `color-mix(in oklab, var(--color-ink) ${share}%, var(--color-menu))`;+const TYPE_COLORS = { input: ink(62), cached: ink(30), output: ink(100) } as const;+/** The validated categorical order (dataviz reference palette), used where a part is a person, not a model. */+const CATEGORICAL = ["#2a78d6", "#eb6834", "#1baf7a", "#eda100", "#e87ba4", "#008300", "#6250d6", "#e34948"];+const OTHER_COLOR = "#76828F";++function viewerTimeZone(): string {+ try {+ return Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC";+ } catch {+ return "UTC";+ }+}++function useUsageInsights(range: { from: string; to: string }, version: number): { data: UsageInsights | null; error: string | null; loading: boolean } {+ const key = `${range.from}|${range.to}`;+ const [state, setState] = useState<{ data: UsageInsights | null; error: string | null; key: string | null }>({ data: null, error: null, key: null });+ useEffect(() => {+ let current = true;+ const query = `from=${encodeURIComponent(range.from)}&to=${encodeURIComponent(range.to)}&tz=${encodeURIComponent(viewerTimeZone())}`;+ void api(`/api/usage/insights?${query}`)+ .then((data: UsageInsights) => { if (current) setState({ data, error: null, key }); })+ .catch((cause) => { if (current) setState((prev) => ({ data: prev.key === key ? prev.data : null, error: cause instanceof Error ? cause.message : String(cause), key })); });+ return () => { current = false; };+ }, [range.from, range.to, version, key]);+ return { data: state.data, error: state.error, loading: state.key !== key };+}++const locale = () => documentLanguage(activeLocale());+const tokensOf = (value: Pick<InsightTotals, "input" | "cachedInput" | "output">) => value.input + value.cachedInput + value.output;+const cacheRate = (value: Pick<InsightTotals, "input" | "cachedInput">) => value.input + value.cachedInput > 0 ? value.cachedInput / (value.input + value.cachedInput) : null;+const percent = (share: number) => share > 0 && share < 0.01 ? "<1%" : `${Math.round(share * 100)}%`;+const metricText = (metric: InsightMetric, value: number) => metric === "cost" ? formatCost(value) : formatTokens(value);+const tickText = (metric: InsightMetric, tick: number, step: number) =>+ metric === "cost" && tick > 0 ? usdText(tick, Math.max(2, -Math.floor(Math.log10(step)))) : metricText(metric, tick);++function bucketLabel(start: string, style: "axis" | "long"): string {+ if (start.length > 10) {+ const hour = Number(start.slice(11, 13));+ return new Date(Date.UTC(2023, 0, 1, hour)).toLocaleTimeString(locale(), { hour: "numeric", timeZone: "UTC" });+ }+ return new Date(`${start}T12:00:00Z`).toLocaleDateString(locale(), style === "long"+ ? { weekday: "short", month: "short", day: "numeric", timeZone: "UTC" }+ : { month: "short", day: "numeric", timeZone: "UTC" });+}++export function niceTicks(max: number): number[] {+ if (!(max > 0)) return [0];+ const raw = max / 4;+ const power = 10 ** Math.floor(Math.log10(raw));+ const normal = raw / power;+ const step = ([1, 2, 5, 10].find((factor) => normal <= factor) ?? 10) * power;+ const ticks: number[] = [];+ for (let index = 0; index * step < max + step * 0.999 && index <= 5; index++) ticks.push(Number((index * step).toPrecision(12)));+ return ticks;+}++/** A smooth line through the points that never overshoots between them, so it never dips under zero (Fritsch–Carlson). */+export function monotonePath(points: ReadonlyArray<readonly [number, number]>): string {+ const n = points.length;+ if (n === 0) return "";+ if (n === 1) return `M${points[0]![0]},${points[0]![1]}`;+ const slopes: number[] = [];+ for (let i = 0; i < n - 1; i++) {+ const dx = points[i + 1]![0] - points[i]![0];+ slopes.push(dx === 0 ? 0 : (points[i + 1]![1] - points[i]![1]) / dx);+ }+ const tangents = points.map((_, i) => {+ if (i === 0) return slopes[0]!;+ if (i === n - 1) return slopes[n - 2]!;+ return slopes[i - 1]! * slopes[i]! <= 0 ? 0 : (slopes[i - 1]! + slopes[i]!) / 2;+ });+ for (let i = 0; i < n - 1; i++) {+ if (slopes[i] === 0) { tangents[i] = 0; tangents[i + 1] = 0; continue; }+ const a = tangents[i]! / slopes[i]!;+ const b = tangents[i + 1]! / slopes[i]!;+ const sum = a * a + b * b;+ if (sum > 9) {+ const scale = 3 / Math.sqrt(sum);+ tangents[i] = scale * a * slopes[i]!;+ tangents[i + 1] = scale * b * slopes[i]!;+ }+ }+ let path = `M${points[0]![0].toFixed(1)},${points[0]![1].toFixed(1)}`;+ for (let i = 0; i < n - 1; i++) {+ const [x0, y0] = points[i]!;+ const [x1, y1] = points[i + 1]!;+ const third = (x1 - x0) / 3;+ path += `C${(x0 + third).toFixed(1)},${(y0 + tangents[i]! * third).toFixed(1)} ${(x1 - third).toFixed(1)},${(y1 - tangents[i + 1]! * third).toFixed(1)} ${x1.toFixed(1)},${y1.toFixed(1)}`;+ }+ return path;+}++function useWidth<T extends HTMLElement>(): [React.RefObject<T | null>, number] {+ const ref = useRef<T | null>(null);+ const [width, setWidth] = useState(0);+ useLayoutEffect(() => {+ const node = ref.current;+ if (!node) return;+ setWidth(node.clientWidth);+ if (typeof ResizeObserver === "undefined") return;+ const observer = new ResizeObserver(([entry]) => setWidth(entry!.contentRect.width));+ observer.observe(node);+ return () => observer.disconnect();+ }, []);+ return [ref, width];+}++interface Provider {+ key: string;+ label: string;+ color: string;+ costUsd: number;+ tokens: number;+ turns: number;+ models: string[];+}++export function providersOf(models: readonly InsightEntry[], metric: InsightMetric): Provider[] {+ const found = new Map<string, Provider>();+ for (const entry of models) {+ const family = modelFamily(entry.key);+ const provider = found.get(family.id) ?? { key: family.id, label: family.label, color: family.color, costUsd: 0, tokens: 0, turns: 0, models: [] };+ provider.costUsd += entry.costUsd ?? 0;+ provider.tokens += tokensOf(entry);+ provider.turns += entry.turns;+ provider.models.push(entry.key);+ found.set(family.id, provider);+ }+ const size = (provider: Provider) => metric === "cost" ? provider.costUsd : provider.tokens;+ return [...found.values()].sort((a, b) => size(b) - size(a) || b.tokens - a.tokens);+}++function bucketValue(bucket: InsightBucket, metric: InsightMetric, models: readonly string[]): number {+ const source = metric === "cost" ? bucket.modelCosts : bucket.models;+ let value = 0;+ for (const model of models) value += source[model] ?? 0;+ return value;+}++function Tooltip({ left, top, children }: { left: number; top: number; children: ReactNode }) {+ return (+ <div role="presentation" className="pointer-events-none absolute z-20 min-w-[10rem] max-w-[16rem] -translate-y-full rounded-[10px] bg-menu/95 px-3 py-2 text-[12px] leading-5 text-ink shadow-[0_8px_24px_rgb(0_0_0/0.18),inset_0_0_0_0.5px_var(--settings-edge,var(--color-hairline))] backdrop-blur-md"+ style={{ left, top }}>+ {children}+ </div>+ );+}++function TooltipRow({ color, label, value, strong = false }: { color?: string; label: string; value: string; strong?: boolean }) {+ return (+ <div className={cn("flex items-center gap-2", strong && "mt-1 border-t-[0.5px] border-(--settings-edge) pt-1")}>+ {color ? <span aria-hidden="true" className="h-[3px] w-2.5 shrink-0 rounded-full" style={{ backgroundColor: color }} /> : <span className="w-2.5 shrink-0" />}+ <span className="min-w-0 flex-1 truncate text-ink-secondary">{label}</span>+ <span className={cn("tabular-nums text-ink", strong ? "font-semibold" : "font-medium")}>{value}</span>+ </div>+ );+}++function Delta({ now, before }: { now: number; before: number }) {+ if (!(before > 0) || !Number.isFinite(now)) return <span className="text-[12px] text-ink-tertiary">{t("insights.noPrevious")}</span>;+ const change = (now - before) / before;+ if (Math.abs(change) < 0.005) return <span className="text-[12px] text-ink-tertiary">{t("insights.flat")}</span>;+ const Icon = change > 0 ? ArrowUpRight : ArrowDownRight;+ return (+ <span className="inline-flex items-center gap-0.5 text-[12px] font-medium tabular-nums text-ink-secondary" title={t("insights.vsPrevious")}>+ <Icon size={13} aria-hidden="true" />+ {percent(Math.abs(change))}+ <span className="ml-1 font-normal text-ink-tertiary">{t("insights.vsPreviousShort")}</span>+ </span>+ );+}++function axisAnchor(index: number, count: number): "start" | "end" | "middle" {+ if (index === 0) return "start";+ return index === count - 1 ? "end" : "middle";+}++function ProviderChart({ data, metric, providers }: { data: UsageInsights; metric: InsightMetric; providers: readonly Provider[] }) {+ const [ref, width] = useWidth<HTMLDivElement>();+ const [hover, setHover] = useState<number | null>(null);+ const buckets = data.buckets;+ const series = providers.map((provider) => ({ ...provider, values: buckets.map((bucket) => bucketValue(bucket, metric, provider.models)) }))+ .filter((item) => item.values.some((value) => value > 0));+ const peak = Math.max(0, ...series.flatMap((item) => item.values));+ const ticks = niceTicks(peak);+ const top = ticks.at(-1) || 1;+ const height = 220;+ const axis = 48;+ const bottom = 22;+ const plot = Math.max(1, width - axis - 6);+ const xAt = (index: number) => axis + (buckets.length > 1 ? (index / (buckets.length - 1)) * plot : plot / 2);+ const yAt = (value: number) => 8 + (1 - value / top) * (height - bottom - 8);+ const totals = buckets.map((_, index) => series.reduce((sum, item) => sum + item.values[index]!, 0));+ const labelled = buckets.length > 2 ? [0, Math.floor((buckets.length - 1) / 2), buckets.length - 1] : buckets.map((_, index) => index);++ const pick = (event: PointerEvent<HTMLDivElement>) => {+ const box = event.currentTarget.getBoundingClientRect();+ const local = event.clientX - box.left - axis;+ setHover(Math.max(0, Math.min(buckets.length - 1, Math.round((local / plot) * (buckets.length - 1)))));+ };+ const onKey = (event: KeyboardEvent<HTMLDivElement>) => {+ if (event.key !== "ArrowRight" && event.key !== "ArrowLeft") return;+ event.preventDefault();+ const last = buckets.length - 1;+ setHover((current) => current === null ? last : Math.max(0, Math.min(last, current + (event.key === "ArrowRight" ? 1 : -1))));+ };++ const title = t(CHART_TITLES[metric][data.unit]);+ return (+ <section className="flex min-w-0 flex-col gap-2" aria-label={title}>+ <h3 className="text-[13px] font-medium leading-[18px] text-ink">{title}</h3>+ <div ref={ref} tabIndex={0} role="group" aria-label={title} data-testid="insight-chart"+ className="relative cursor-crosshair touch-pan-y rounded-lg outline-none focus-visible:outline-2 focus-visible:outline-focus"+ onPointerMove={pick} onPointerDown={pick} onPointerLeave={() => setHover(null)} onKeyDown={onKey} onBlur={() => setHover(null)}>+ {width > 0 && (+ <svg width={width} height={height} className="block overflow-visible" aria-hidden="true">+ {ticks.map((tick) => (+ <g key={tick}>+ <line x1={axis} x2={width} y1={yAt(tick)} y2={yAt(tick)} stroke="var(--settings-edge, var(--color-hairline))" strokeWidth={1} />+ <text x={axis - 10} y={yAt(tick)} dy="0.32em" textAnchor="end" className="fill-ink-tertiary text-[11px] tabular-nums">{tickText(metric, tick, ticks[1] ?? tick)}</text>+ </g>+ ))}+ {[...series].reverse().map((item) => {+ const line = monotonePath(item.values.map((value, index) => [xAt(index), yAt(value)] as const));+ return (+ <g key={item.key}>+ <path d={`${line}L${xAt(buckets.length - 1)},${yAt(0)}L${xAt(0)},${yAt(0)}Z`} fill={item.color} fillOpacity={0.12} />+ <path d={line} fill="none" stroke={item.color} strokeWidth={2} strokeLinejoin="round" strokeLinecap="round" />+ </g>+ );+ })}+ {labelled.map((index) => (+ <text key={index} x={xAt(index)} y={height - 4} textAnchor={axisAnchor(index, buckets.length)}+ className="fill-ink-tertiary text-[11px] uppercase tracking-[0.04em]">{bucketLabel(buckets[index]!.start, "axis")}</text>+ ))}+ {hover !== null && (+ <g>+ <line x1={xAt(hover)} x2={xAt(hover)} y1={8} y2={yAt(0)} stroke="var(--color-ink)" strokeOpacity={0.35} strokeWidth={1} />+ {series.map((item) => <circle key={item.key} cx={xAt(hover)} cy={yAt(item.values[hover]!)} r={4} fill={item.color} stroke="var(--color-menu)" strokeWidth={2} />)}+ </g>+ )}+ </svg>+ )}+ {series.length === 0 && data.totals.turns === 0 && <p className="absolute inset-x-0 top-1/3 text-center text-[13px] text-ink-secondary">{t("insights.empty")}</p>}+ {hover !== null && series.length > 0 && (+ <Tooltip left={Math.min(Math.max(xAt(hover) + 12, axis), Math.max(axis, width - 176))} top={Math.max(84, yAt(Math.max(...series.map((item) => item.values[hover]!))) - 8)}>+ <div className="mb-1 text-ink-secondary">{bucketLabel(buckets[hover]!.start, "long")}</div>+ {series.map((item) => <TooltipRow key={item.key} color={item.color} label={item.label} value={metricText(metric, item.values[hover]!)} />)}+ {series.length > 1 && <TooltipRow label={t("insights.total")} value={metricText(metric, totals[hover]!)} strong />}+ </Tooltip>+ )}+ <table className="sr-only">+ <caption>{title}</caption>+ <thead><tr><th scope="col">{t("insights.when")}</th>{series.map((item) => <th key={item.key} scope="col">{item.label}</th>)}</tr></thead>+ <tbody>+ {buckets.map((bucket, index) => (+ <tr key={bucket.start}><th scope="row">{bucketLabel(bucket.start, "long")}</th>{series.map((item) => <td key={item.key}>{metricText(metric, item.values[index]!)}</td>)}</tr>+ ))}+ </tbody>+ </table>+ </div>+ </section>+ );+}++function Overview({ data, metric }: { data: UsageInsights; metric: InsightMetric }) {+ const providers = useMemo(() => providersOf(data.models, metric), [data.models, metric]);+ const total = metric === "cost" ? data.totals.costUsd ?? 0 : tokensOf(data.totals);+ const totalText = metric === "cost" ? formatCost(data.totals.costUsd) : formatTokens(total);+ const before = metric === "cost" ? data.previous.costUsd ?? 0 : tokensOf(data.previous);+ const size = (provider: Provider) => metric === "cost" ? provider.costUsd : provider.tokens;+ const whole = providers.reduce((sum, provider) => sum + size(provider), 0);+ return (+ <div className="grid gap-6 p-4 @min-[720px]/insights:grid-cols-[15rem_minmax(0,1fr)]">+ <div className="flex min-w-0 flex-col gap-4">+ <div className="flex flex-col gap-1" data-testid="insight-hero">+ <span className="text-[12px] leading-4 text-ink-secondary">{t(metric === "cost" ? "insights.totalSpend" : "insights.totalTokens")}</span>+ <span className="text-[40px] font-semibold leading-[44px] tracking-[-0.02em] text-ink">{totalText}</span>+ <span className="text-[12px] leading-4 text-ink-secondary">+ {t("insights.heroSub", { turns: data.totals.turns.toLocaleString(locale()), days: String(data.totals.days) })}+ </span>+ <Delta now={total} before={before} />+ </div>+ <ul className="flex flex-col gap-3" aria-label={t("insights.providers")}>+ {providers.map((provider) => (+ <li key={provider.key} className="flex min-w-0 flex-col gap-0.5">+ <span className="flex items-center gap-2 text-[13px] leading-5">+ <span aria-hidden="true" className="size-2 shrink-0 rounded-full" style={{ backgroundColor: provider.color }} />+ <span className="min-w-0 flex-1 truncate text-ink">{provider.label}</span>+ <span className="font-medium tabular-nums text-ink">{metricText(metric, size(provider))}</span>+ </span>+ <span className="pl-4 text-[11px] leading-4 tabular-nums text-ink-tertiary">+ {t(metric === "cost" ? "insights.shareOfSpend" : "insights.shareOfTokens", { share: whole > 0 ? percent(size(provider) / whole) : "0%" })}+ {" · "}{metric === "cost" ? t("insights.tokensCount", { tokens: formatTokens(provider.tokens) }) : t("insights.turnsCount", { count: String(provider.turns) })}+ </span>+ </li>+ ))}+ </ul>+ </div>+ <ProviderChart data={data} metric={metric} providers={providers} />+ </div>+ );+}++function Sparkline({ values }: { values: number[] }) {+ const [ref, width] = useWidth<HTMLDivElement>();+ const height = 28;+ const max = Math.max(...values, 0);+ const step = values.length > 1 ? width / (values.length - 1) : 0;+ const points = values.map((value, index) => [index * step, max > 0 ? height - 3 - (value / max) * (height - 8) : height - 3] as const);+ const line = monotonePath(points);+ const last = points.at(-1);+ return (+ <div ref={ref} className="h-7 w-full" aria-hidden="true">+ {width > 0 && values.length > 1 && (+ <svg width={width} height={height} className="overflow-visible">+ <path d={`${line}L${width},${height}L0,${height}Z`} fill="var(--color-ink)" fillOpacity={0.05} />+ <path d={line} fill="none" stroke="var(--color-ink-tertiary)" strokeWidth={1.5} strokeLinejoin="round" strokeLinecap="round" />+ {last && <circle cx={last[0]} cy={last[1]} r={3.5} fill="var(--color-accent)" stroke="var(--color-menu)" strokeWidth={2} />}+ </svg>+ )}+ </div>+ );+}++function Tile({ label, value, sub, spark }: { label: string; value: string; sub: ReactNode; spark: number[] }) {+ return (+ <div className="flex min-w-0 flex-col gap-1 px-4 pb-3 pt-4">+ <dt className="text-[12px] leading-4 text-ink-secondary">{label}</dt>+ <dd className="flex min-w-0 flex-col gap-1">+ <span className="truncate text-[24px] font-semibold leading-8 tracking-[-0.01em] text-ink">{value}</span>+ <span className="min-h-4 leading-4">{sub}</span>+ <Sparkline values={spark} />+ </dd>+ </div>+ );+}++function InsightTiles({ data }: { data: UsageInsights }) {+ const { totals, previous, buckets } = data;+ const rate = cacheRate(totals);+ const before = cacheRate(previous);+ const turnTime = (value: InsightTotals) => value.timedTurns ? value.durationMs / value.timedTurns : 0;+ const perTurn = (value: { costUsd: number | null; turns: number; unpriced: number }) => {+ const priced = value.turns - value.unpriced;+ return priced > 0 && value.costUsd !== null ? value.costUsd / priced : null;+ };+ const costPerTurn = perTurn(totals);+ return (+ <dl data-testid="usage-totals" className="grid grid-cols-2 @min-[720px]/insights:grid-cols-4 [&>*]:border-(--settings-edge) [&>*:nth-child(even)]:border-l-[0.5px] [&>*:nth-child(n+3)]:border-t-[0.5px] @min-[720px]/insights:[&>*:nth-child(n+2)]:border-l-[0.5px] @min-[720px]/insights:[&>*:nth-child(n+3)]:border-t-0">+ <Tile label={t("insights.turns")} value={totals.turns.toLocaleString(locale())}+ sub={<Delta now={totals.turns} before={previous.turns} />} spark={buckets.map((bucket) => bucket.turns)} />+ <Tile label={t("insights.costPerTurn")} value={formatCost(costPerTurn)}+ sub={<Delta now={costPerTurn ?? Number.NaN} before={perTurn(previous) ?? 0} />}+ spark={buckets.map((bucket) => perTurn(bucket) ?? 0)} />+ <Tile label={t("insights.cacheRate")} value={rate === null ? "—" : percent(rate)}+ sub={before !== null && rate !== null+ ? <span className="text-[12px] tabular-nums text-ink-tertiary">{t("insights.cacheBefore", { rate: percent(before) })}</span>+ : <span className="text-[12px] text-ink-tertiary">{t("insights.cacheHint")}</span>}+ spark={buckets.map((bucket) => cacheRate(bucket) ?? 0)} />+ <Tile label={t("insights.avgTurn")} value={totals.timedTurns ? formatDuration(turnTime(totals)) : "—"}+ sub={<Delta now={turnTime(totals)} before={turnTime(previous)} />} spark={buckets.map((bucket) => bucket.timedTurns ? bucket.durationMs / bucket.timedTurns : 0)} />+ </dl>+ );+}++function InsightFacts({ data }: { data: UsageInsights }) {+ const { totals } = data;+ const facts: Array<{ label: string; value: string; danger?: boolean }> = [+ { label: t("insights.tools"), value: totals.tools.toLocaleString(locale()) },+ { label: t("insights.errors"), value: String(totals.errors), danger: totals.errors > 0 },+ { label: t("insights.activeDays"), value: t("insights.activeDaysValue", { active: String(totals.activeDays), total: String(totals.days) }) },+ { label: t("insights.reasoningTokens"), value: formatTokens(totals.reasoning) },+ ...(totals.unpriced ? [{ label: t("insights.unpricedTurns"), value: String(totals.unpriced) }] : []),+ ];+ return (+ <dl className="flex flex-wrap gap-x-6 gap-y-2 border-t-[0.5px] border-(--settings-edge) px-4 py-3">+ {facts.map((fact) => (+ <div key={fact.label} className="flex items-baseline gap-1.5 text-[12px] leading-5">+ <dt className="text-ink-secondary">{fact.label}</dt>+ <dd className={cn("font-medium tabular-nums", fact.danger ? "text-danger" : "text-ink")}>{fact.value}</dd>+ </div>+ ))}+ </dl>+ );+}++const WEEK_ORDER = [1, 2, 3, 4, 5, 6, 0];+const weekdayName = (weekday: number, style: "short" | "long") =>+ new Date(Date.UTC(2023, 0, 1 + weekday, 12)).toLocaleDateString(locale(), { weekday: style, timeZone: "UTC" });+const hourName = (hour: number) => new Date(Date.UTC(2023, 0, 1, hour)).toLocaleTimeString(locale(), { hour: "numeric", timeZone: "UTC" });++function ActivityHeatmap({ data }: { data: UsageInsights }) {+ const [hover, setHover] = useState<{ weekday: number; hour: number; left: number; top: number } | null>(null);+ const max = Math.max(...data.hours.flat(), 0);+ let busiest: { weekday: number; hour: number; turns: number } | null = null;+ for (const weekday of WEEK_ORDER) {+ for (let hour = 0; hour < 24; hour++) {+ const turns = data.hours[weekday]![hour]!;+ if (turns > (busiest?.turns ?? 0)) busiest = { weekday, hour, turns };+ }+ }+ const level = (value: number) => value <= 0 || max <= 0 ? 0 : Math.max(1, Math.ceil((value / max) * 4));+ const fills = [ink(7), "color-mix(in oklab, var(--color-accent) 28%, var(--color-menu))", "color-mix(in oklab, var(--color-accent) 52%, var(--color-menu))",+ "color-mix(in oklab, var(--color-accent) 76%, var(--color-menu))", "var(--color-accent)"];+ return (+ <section className="relative flex flex-col gap-3 p-4" aria-label={t("insights.when")} onPointerLeave={() => setHover(null)}>+ <div className="flex flex-col gap-0.5">+ <h3 className="text-[13px] font-medium leading-[18px] text-ink">{t("insights.when")}</h3>+ <p className="text-[12px] leading-4 text-ink-secondary">+ {busiest ? t("insights.busiest", { day: weekdayName(busiest.weekday, "long"), hour: hourName(busiest.hour) }) : t("insights.empty")}+ </p>+ </div>+ <div className="grid grid-cols-[2rem_minmax(0,1fr)] gap-x-2" data-testid="insight-heatmap">+ <div className="grid grid-rows-7 gap-[3px]">+ {WEEK_ORDER.map((weekday) => <span key={weekday} className="flex items-center text-[11px] uppercase leading-none tracking-[0.04em] text-ink-tertiary">{weekdayName(weekday, "short")}</span>)}+ </div>+ <div className="grid grid-rows-7 gap-[3px]">+ {WEEK_ORDER.map((weekday) => (+ <div key={weekday} className="grid grid-cols-[repeat(24,minmax(0,1fr))] gap-[3px]">+ {data.hours[weekday]!.map((turns, hour) => (+ <span key={hour} aria-label={t("insights.heatCell", { day: weekdayName(weekday, "long"), hour: hourName(hour), count: String(turns) })}+ className={cn("aspect-square rounded-[3px]", hover?.weekday === weekday && hover.hour === hour && "outline-[1.5px] outline-offset-1 outline-ink/50 outline")}+ style={{ backgroundColor: fills[level(turns)] }}+ onPointerEnter={(event) => {+ const box = event.currentTarget.getBoundingClientRect();+ const frame = event.currentTarget.closest("section")!.getBoundingClientRect();+ setHover({ weekday, hour, left: Math.min(box.left - frame.left - 20, frame.width - 170), top: box.top - frame.top - 6 });+ }} />+ ))}+ </div>+ ))}+ </div>+ <span />+ <div className="relative mt-1.5 h-3 text-[11px] uppercase tracking-[0.04em] text-ink-tertiary">+ {[0, 6, 12, 18].map((hour) => <span key={hour} className="absolute" style={{ left: `${(hour / 24) * 100}%` }}>{hourName(hour)}</span>)}+ </div>+ </div>+ <div className="flex items-center justify-end gap-1 text-[11px] text-ink-tertiary" aria-hidden="true">+ <span className="mr-1">{t("insights.less")}</span>+ {fills.map((fill) => <span key={fill} className="size-2.5 rounded-[3px]" style={{ backgroundColor: fill }} />)}+ <span className="ml-1">{t("insights.more")}</span>+ </div>+ {hover && (+ <Tooltip left={Math.max(0, hover.left)} top={hover.top}>+ <div className="text-ink-secondary">{weekdayName(hover.weekday, "long")} · {hourName(hover.hour)}</div>+ <div className="text-[13px] font-semibold tabular-nums text-ink">{t("insights.turnsCount", { count: String(data.hours[hover.weekday]![hover.hour]!) })}</div>+ </Tooltip>+ )}+ </section>+ );+}++interface Part { key: string; label: string; value: number; color: string }++function ShareBar({ title, parts, format, testId, empty = t("insights.empty") }: { title: string; parts: Part[]; format: (value: number) => string; testId?: string; empty?: string }) {+ const whole = parts.reduce((sum, part) => sum + part.value, 0);+ const visible = parts.filter((part) => part.value > 0);+ return (+ <div className="flex flex-col gap-2" data-testid={testId}>+ <div className="flex items-baseline justify-between gap-2">+ <h4 className="text-[12px] font-medium text-ink">{title}</h4>+ <span className="text-[12px] tabular-nums text-ink-secondary">{format(whole)}</span>+ </div>+ {whole > 0 ? (+ <>+ <div className="flex h-2 gap-0.5" role="img" aria-label={visible.map((part) => `${part.label} ${percent(part.value / whole)}`).join(", ")}>+ {visible.map((part) => (+ <span key={part.key} title={`${part.label} · ${format(part.value)} · ${percent(part.value / whole)}`}+ className="h-full min-w-1 rounded-[2px] first:rounded-l-full last:rounded-r-full" style={{ flex: `${part.value} 1 0`, backgroundColor: part.color }} />+ ))}+ </div>+ <ul className="flex flex-wrap gap-x-4 gap-y-1.5">+ {visible.map((part) => (+ <li key={part.key} className="flex min-w-0 items-center gap-1.5 text-[12px]">+ <span aria-hidden="true" className="size-2 shrink-0 rounded-[2px]" style={{ backgroundColor: part.color }} />+ <span className="max-w-[10rem] truncate text-ink-secondary">{part.label}</span>+ <span className="tabular-nums text-ink">{format(part.value)}</span>+ <span className="tabular-nums text-ink-tertiary">{percent(part.value / whole)}</span>+ </li>+ ))}+ </ul>+ </>+ ) : <p className="text-[12px] text-ink-secondary">{empty}</p>}+ </div>+ );+}++function Shares({ data, metric, groupLabel }: { data: UsageInsights; metric: InsightMetric; groupLabel: GroupLabel }) {+ const { totals } = data;+ const size = (entry: InsightEntry) => metric === "cost" ? entry.costUsd ?? 0 : tokensOf(entry);+ const people = [...data.people].sort((a, b) => size(b) - size(a));+ const shown = people.length > CATEGORICAL.length ? people.slice(0, CATEGORICAL.length - 1) : people;+ const rest = people.slice(shown.length).reduce((sum, entry) => sum + size(entry), 0);+ return (+ <section className="flex flex-col gap-5 p-4" aria-label={t("insights.mix")}>+ <ShareBar title={t("insights.tokensByType")} testId="insight-mix" format={formatTokens} parts={[+ { key: "input", label: t("insights.freshInput"), value: totals.input, color: TYPE_COLORS.input },+ { key: "cached", label: t("insights.cachedInput"), value: totals.cachedInput, color: TYPE_COLORS.cached },+ { key: "output", label: t("insights.output"), value: totals.output, color: TYPE_COLORS.output },+ ]} />+ <ShareBar title={t(metric === "cost" ? "insights.spendByPerson" : "insights.tokensByPerson")} format={(value) => metricText(metric, value)}+ empty={totals.turns ? "—" : undefined} parts={[+ ...shown.map((entry, index) => ({ key: entry.key, label: groupLabel("user", entry), value: size(entry), color: CATEGORICAL[index]! })),+ ...(rest > 0 ? [{ key: "rest", label: t("insights.other"), value: rest, color: OTHER_COLOR }] : []),+ ]} />+ </section>+ );+}++const BOARD_KEYS: Record<Board, LocaleKey> = {+ models: "usage.history.byModel",+ bots: "usage.history.byBot",+ people: "usage.history.byUser",+ engines: "usage.history.byEngine",+ routines: "usage.history.byRoutine",+ departments: "usage.history.byDepartment",+ time: "usage.history.byDay",+};++function entryColor(board: Board, entry: InsightEntry): string {+ if (board === "models") return modelColor(entry.key);+ if (board === "engines") return modelFamily(`model:${entry.label}/`).color;+ return "var(--color-accent)";+}++const GROUP_OF: Partial<Record<Board, Parameters<GroupLabel>[0]>> = { bots: "bot", people: "user", routines: "routine", departments: "department" };++function entryLabel(board: Board, entry: InsightEntry, instances: Parameters<typeof modelName>[1], groupLabel: GroupLabel): string {+ if (board === "models") return modelName(entry.label, instances, entry.driverKind);+ const groupBy = GROUP_OF[board];+ return groupBy ? groupLabel(groupBy, entry) : entry.label;+}++function Breakdown({ data, metric, groupLabel }: { data: UsageInsights; metric: InsightMetric; groupLabel: GroupLabel }) {+ const { state } = useStore();+ const [board, setBoard] = useState<Board>("models");+ const size = (value: { costUsd: number | null } & Pick<InsightTotals, "input" | "cachedInput" | "output">) => metric === "cost" ? value.costUsd ?? 0 : tokensOf(value);+ const boardLabel = (value: Board) => t(value === "time" && data.unit === "hour" ? "insights.byHour" : BOARD_KEYS[value]);+ const options = (Object.keys(BOARD_KEYS) as Board[]).map((value) => ({ value, label: boardLabel(value) }));+ const header = "grid grid-cols-[1.25rem_minmax(0,1fr)_3.5rem_4.5rem] items-center gap-3 @min-[600px]/insights:grid-cols-[1.25rem_minmax(0,1fr)_3.5rem_4rem_3.5rem_4.5rem_4.5rem]";+ const wide = "hidden @min-[600px]/insights:block";+ let rows: ReactNode[];+ if (board === "time") {+ const buckets = [...data.buckets].reverse().filter((bucket) => bucket.turns > 0);+ rows = buckets.map((bucket, index) => (+ <div role="row" key={bucket.start} className={cn(header, "rounded-lg px-1 py-2 text-[13px] hover:bg-menu-hover")}>+ <span role="cell" className="text-right text-[11px] tabular-nums text-ink-tertiary">{index + 1}</span>+ <span role="cell" className="truncate text-ink">{bucketLabel(bucket.start, "long")}</span>+ <span role="cell" className="text-right tabular-nums text-ink-secondary">{bucket.turns}</span>+ <span role="cell" className={cn(wide, "text-right tabular-nums text-ink-secondary")}>{bucket.errors || "—"}</span>+ <span role="cell" className={cn(wide, "text-right tabular-nums text-ink-secondary")}>{percent(cacheRate(bucket) ?? 0)}</span>+ <span role="cell" className={cn(wide, "text-right tabular-nums text-ink-secondary")}>{formatTokens(tokensOf(bucket))}</span>+ <span role="cell" className="text-right font-medium tabular-nums text-ink">{formatCost(bucket.costUsd)}</span>+ </div>+ ));+ } else {+ const entries = [...data[board]].sort((a, b) => size(b) - size(a)).slice(0, 10);+ const peak = Math.max(0, ...entries.map(size));+ const whole = data[board].reduce((sum, entry) => sum + size(entry), 0);+ rows = entries.map((entry, index) => {+ const bot = board === "bots" ? state.bots.find((item) => `bot:${item.id}` === entry.key) : undefined;+ const color = entryColor(board, entry);+ const label = bot?.name ?? entryLabel(board, entry, state.instances, groupLabel);+ return (+ <div role="row" key={entry.key} className={cn(header, "rounded-lg px-1 py-2 text-[13px] hover:bg-menu-hover")}>+ <span role="cell" className="text-right text-[11px] tabular-nums text-ink-tertiary">{index + 1}</span>+ <span role="cell" className="flex min-w-0 flex-col gap-1.5">+ <span className="flex min-w-0 items-center gap-2 text-ink" title={board === "models" ? `${label} · ${modelFamily(entry.key).label}` : label}>+ {bot ? <BotAvatar bot={bot} state="idle" size={18} animated={false} />+ : board === "models" && <span aria-hidden="true" className="size-2 shrink-0 rounded-full" style={{ backgroundColor: color }} />}+ <span className="truncate">{label}</span>+ </span>+ <span aria-hidden="true" className="h-0.5 max-w-56">+ <span className="block h-full rounded-full" style={{ width: `max(0.5rem, ${peak > 0 ? (size(entry) / peak) * 100 : 0}%)`, backgroundColor: color }} />+ </span>+ </span>+ <span role="cell" className="text-right tabular-nums text-ink-secondary">{entry.turns}</span>+ <span role="cell" className={cn(wide, "text-right tabular-nums text-ink-secondary")}>{entry.errors || "—"}</span>+ <span role="cell" className={cn(wide, "text-right tabular-nums text-ink-secondary")}>{whole > 0 ? percent(size(entry) / whole) : "—"}</span>+ <span role="cell" className={cn(wide, "text-right tabular-nums text-ink-secondary")}>{metric === "cost" ? formatTokens(tokensOf(entry)) : formatCost(entry.costUsd)}</span>+ <span role="cell" className="text-right font-medium tabular-nums text-ink">{metricText(metric, size(entry))}</span>+ </div>+ );+ });+ }+ const columns = board === "time"+ ? [t("insights.turns"), t("insights.errors"), t("insights.cacheShort"), t("insights.tokens"), t("insights.spend")]+ : [t("insights.turns"), t("insights.errors"), t("insights.share"), t(metric === "cost" ? "insights.tokens" : "insights.spend"), t(metric === "cost" ? "insights.spend" : "insights.tokens")];+ return (+ <section className="flex flex-col gap-3 p-4" aria-label={t("insights.breakdown")}>+ <div className="flex flex-wrap items-center justify-between gap-2">+ <h3 className="text-[13px] font-medium leading-[18px] text-ink">{t("insights.breakdown")}</h3>+ <Select value={board} onChange={(event) => setBoard(event.target.value as Board)} aria-label={t("usage.history.groupBy")}>+ {options.map((option) => <option key={option.value} value={option.value}>{option.label}</option>)}+ </Select>+ </div>+ <div role="table" aria-label={boardLabel(board)} className="flex flex-col" data-testid="insight-breakdown">+ <div role="row" className={cn(header, "border-b-[0.5px] border-(--settings-edge) px-1 pb-2 text-[11px] text-ink-tertiary")}>+ <span role="columnheader" className="text-right">#</span>+ <span role="columnheader">{boardLabel(board)}</span>+ {columns.map((column, index) => (+ <span key={column} role="columnheader" className={cn("text-right", index > 0 && index < 4 && wide)}>{column}</span>+ ))}+ </div>+ {rows.length > 0 ? rows : <p className="px-1 py-3 text-[13px] text-ink-secondary">{t("insights.empty")}</p>}+ </div>+ </section>+ );+}++export function UsageInsightsPanel({ range, version, metric, groupLabel, card }: {+ range: { from: string; to: string };+ version: number;+ metric: InsightMetric;+ groupLabel: GroupLabel;+ card: string;+}) {+ const { data, error, loading } = useUsageInsights(range, version);+ if (!data) {+ return (+ <div className={cn(card, "flex items-center gap-2 p-5 text-[13px] text-ink-secondary")}>+ {error ? <span role="alert" className="text-danger">{error}</span> : <><Loader2 size={14} className="animate-spin" />{t("common.checking")}</>}+ </div>+ );+ }+ return (+ <div className={cn("@container/insights flex flex-col gap-4 transition-opacity duration-150 motion-reduce:transition-none", loading && "opacity-50 delay-150")} data-testid="usage-insights">+ <div className={card}><Overview data={data} metric={metric} /></div>+ <div className={card}>+ <InsightTiles data={data} />+ <InsightFacts data={data} />+ </div>+ <div className="grid gap-4 @min-[720px]/insights:grid-cols-2">+ <div className={card}><ActivityHeatmap data={data} /></div>+ <div className={card}><Shares data={data} metric={metric} groupLabel={groupLabel} /></div>+ </div>+ <div className={card}><Breakdown data={data} metric={metric} groupLabel={groupLabel} /></div>+ </div>+ );+}diff --git a/src/lib/usage-trace.ts b/src/lib/usage-trace.tsindex 256a896060..443c33305b 100644--- a/src/lib/usage-trace.ts+++ b/src/lib/usage-trace.ts@@ -8,8 +8,8 @@ import type {TraceDetail, TraceGroup, TraceList, TraceNode, TraceRootSummary, TraceStep, TraceTokens, TraceTool, TraceTurn,} from "../../shared/usage-trace.ts";-export type UsagePeriod = "today" | "week" | "month" | "lastMonth" | "days30";-export const USAGE_PERIODS: readonly UsagePeriod[] = ["today", "week", "month", "lastMonth", "days30"];+export type UsagePeriod = "today" | "week" | "month" | "lastMonth" | "days30" | "days90";+export const USAGE_PERIODS: readonly UsagePeriod[] = ["today", "week", "month", "lastMonth", "days30", "days90"];const DAY_MS = 24 * 60 * 60_000;const day = (date: Date) => date.toISOString().slice(0, 10);@@ -21,9 +21,15 @@ export function usagePeriodRange(period: UsagePeriod, now = new Date()): { from:if (period === "week") return { from: day(new Date(now.getTime() - 6 * DAY_MS)), to: day(now) };if (period === "month") return { from: day(new Date(Date.UTC(year, month, 1))), to: day(now) };if (period === "lastMonth") return { from: day(new Date(Date.UTC(year, month - 1, 1))), to: day(new Date(Date.UTC(year, month, 0))) };+ if (period === "days90") return { from: day(new Date(now.getTime() - 89 * DAY_MS)), to: day(now) };return { from: day(new Date(now.getTime() - 29 * DAY_MS)), to: day(now) };}+export function localPeriodRange(period: UsagePeriod, now = new Date()): { from: string; to: string } {+ const shifted = new Date(Date.UTC(now.getFullYear(), now.getMonth(), now.getDate(), 12));+ return usagePeriodRange(period, shifted);+}+/** A cost as the trace prints it: a sliver of a cent reads "<$0.001", never "$0.000". */export function formatCost(usd: number | null | undefined): string {if (!hasFiniteCost(usd)) return "—";diff --git a/src/locales/en.json b/src/locales/en.jsonindex f60f33e1f9..02e9b4ee76 100644--- a/src/locales/en.json+++ b/src/locales/en.json@@ -11197,5 +11197,56 @@"cliLogin.scopeAll": "Full control","cliLogin.scopeChat": "Chat only","cliLogin.allow": "Allow",- "cliLogin.deny": "Deny"+ "cliLogin.deny": "Deny",+ "usage.history.last90Days": "Last 90 days",+ "insights.measure": "Measure",+ "insights.spend": "Spend",+ "insights.tokens": "Tokens",+ "insights.turns": "Turns",+ "insights.totalSpend": "Total spend",+ "insights.totalTokens": "Total tokens",+ "insights.heroSub": "{turns} turns · {days} days",+ "insights.providers": "Providers",+ "insights.shareOfSpend": "{share} of spend",+ "insights.shareOfTokens": "{share} of tokens",+ "insights.tokensCount": "{tokens} tokens",+ "insights.turnsCount": "{count} turns",+ "insights.dailyCost": "Daily spend",+ "insights.dailyTokens": "Daily tokens",+ "insights.hourlyCost": "Spend by hour",+ "insights.hourlyTokens": "Tokens by hour",+ "insights.total": "Total",+ "insights.empty": "Nothing ran in this period.",+ "insights.noPrevious": "Nothing to compare with",+ "insights.flat": "Same as the period before",+ "insights.vsPrevious": "Compared with the same number of days before",+ "insights.vsPreviousShort": "vs before",+ "insights.costPerTurn": "Cost per turn",+ "insights.cacheRate": "Cache hit rate",+ "insights.cacheShort": "Cached",+ "insights.cacheBefore": "{rate} the period before",+ "insights.cacheHint": "Input read from the cache",+ "insights.avgTurn": "Average turn",+ "insights.tools": "Tool calls",+ "insights.errors": "Errors",+ "insights.activeDays": "Active days",+ "insights.activeDaysValue": "{active} of {total}",+ "insights.reasoningTokens": "Reasoning tokens",+ "insights.unpricedTurns": "Turns with no price",+ "insights.when": "When work happens",+ "insights.busiest": "Busiest on {day}s around {hour}",+ "insights.heatCell": "{day}, {hour}: {count} turns",+ "insights.less": "Less",+ "insights.more": "More",+ "insights.mix": "Where the tokens went",+ "insights.tokensByType": "Tokens by type",+ "insights.freshInput": "Fresh input",+ "insights.cachedInput": "Cache reads",+ "insights.output": "Output",+ "insights.spendByPerson": "Spend by person",+ "insights.tokensByPerson": "Tokens by person",+ "insights.other": "Other",+ "insights.breakdown": "Breakdown",+ "insights.byHour": "By hour",+ "insights.share": "Share"}