From 799af5bf82383676ae3b8cb2166091e7c55e273f Mon Sep 17 00:00:00 2001 From: Nam Rodriguez Date: Sun, 18 Oct 2026 22:16:13 -0400 Subject: [PATCH] feat(dashboard): every token meter shows the total of all four parts, with the parts, cache hit rate and split by feature --- dashboard/e2e/settings.spec.ts | 64 +++++++++++++++++ dashboard/src/app/analytics/page.tsx | 2 +- dashboard/src/app/runs/detail/page.tsx | 41 ++++++++--- dashboard/src/app/settings/budget/page.tsx | 46 ++++++++++++- dashboard/src/app/settings/page.tsx | 2 +- .../src/app/settings/use-settings-status.ts | 11 ++- dashboard/src/components/client-shell.tsx | 68 +++++++++++-------- dashboard/src/lib/api.ts | 21 ++++++ dashboard/src/lib/usage.ts | 64 +++++++++++++++++ 9 files changed, 272 insertions(+), 47 deletions(-) diff --git a/dashboard/e2e/settings.spec.ts b/dashboard/e2e/settings.spec.ts index 37963c23..b888a337 100644 --- a/dashboard/e2e/settings.spec.ts +++ b/dashboard/e2e/settings.spec.ts @@ -230,6 +230,70 @@ test("a member sees the token limit without a form", async ({ page }) => { await shot(page, "token-limit-member-1280.png"); }); +test("every token meter shows the total of all four parts, never input plus output", async ({ page }) => { + await mockApi(page, { role: "member" }); + // What the gateway returns: total_tokens is the four parts added up; + // counted_tokens is the old rule while the limit doesn't count cache yet. + const usage = { + month: "2026-10", + total_tokens: 71_320_000, + tokens_in: 120_000, + cache_read_tokens: 61_400_000, + cache_write_tokens: 8_800_000, + tokens_out: 1_000_000, + cache_hit_rate: 61_400_000 / 70_320_000, + counted_tokens: 1_120_000, + limit_counts_cache: false, + features: [ + { feature: "run", total_tokens: 60_000_000, tokens_in: 100_000, cache_read_tokens: 52_000_000, cache_write_tokens: 7_100_000, tokens_out: 800_000 }, + { feature: "review", total_tokens: 11_320_000, tokens_in: 20_000, cache_read_tokens: 9_400_000, cache_write_tokens: 1_700_000, tokens_out: 200_000 }, + ], + total_runs: 64, + max_tokens: 200_000_000, + }; + await page.route((url) => url.pathname === "/api/usage", (route) => + route.fulfill({ status: 200, contentType: "application/json", body: JSON.stringify(usage) }), + ); + + // Sidebar meter: the total, with the four parts on hover. + await page.goto("/settings/"); + const meter = page.getByTestId("sidebar-token-meter-value"); + await expect(meter).toHaveText("71.3M / 200M"); + await expect(meter).not.toContainText("1.1M"); + const hover = await page.getByTestId("sidebar-token-meter").locator("[title]").first().getAttribute("title"); + expect(hover).toContain("New input 120K"); + expect(hover).toContain("Read from cache 61.4M"); + expect(hover).toContain("Written to cache 8.8M"); + expect(hover).toContain("Output 1M"); + expect(hover).toContain("Cache hit rate 87%"); + + // Settings hub row. + await expect(hubLink(page, "Token limit")).toContainText("71.3M of 200M used this month"); + + // Token limit page: the total equals the four parts from the API, plus the + // hit rate, the split by feature, and no money anywhere. + await page.goto("/settings/budget/"); + await expect(page.getByRole("region", { name: /Used in/ })).toContainText("71.3M of 200M tokens"); + const parts = page.getByTestId("usage-part"); + await expect(parts).toHaveCount(4); + await expect(parts.locator("dt")).toHaveText(["New input", "Read from cache", "Written to cache", "Output"]); + const values = await parts.locator("dd").evaluateAll((els) => els.map((e) => Number(e.getAttribute("data-value")))); + expect(values).toEqual([120_000, 61_400_000, 8_800_000, 1_000_000]); + expect(values.reduce((a, b) => a + b, 0)).toBe(usage.total_tokens); + await expect(page.getByTestId("cache-hit-rate")).toContainText("Cache hit rate 87%"); + await expect(page.getByRole("list", { name: "Tokens by feature" })).toContainText("Ticket runs"); + await expect(page.getByRole("list", { name: "Tokens by feature" })).toContainText("PR reviews"); + await expect(page.getByTestId("limit-rule")).toContainText("1.1M so far"); + await expect(page.locator("main")).not.toContainText("$"); + await shot(page, "token-limit-four-parts-1280.png"); + + await page.setViewportSize({ width: 375, height: 812 }); + await page.goto("/settings/budget/"); + await expect(page.getByTestId("usage-part")).toHaveCount(4); + expect(await page.evaluate(() => document.documentElement.scrollWidth)).toBeLessThanOrEqual(375); + await shot(page, "token-limit-four-parts-375.png"); +}); + test("the token limit page explains a failed load and retries", async ({ page }) => { await mockApi(page, { role: "owner" }); let fail = true; diff --git a/dashboard/src/app/analytics/page.tsx b/dashboard/src/app/analytics/page.tsx index 380e5aa0..069bc2ee 100644 --- a/dashboard/src/app/analytics/page.tsx +++ b/dashboard/src/app/analytics/page.tsx @@ -38,7 +38,7 @@ function tokens(v: number) { return String(Math.round(v)); } const plural = (n: number, one: string, many = `${one}s`) => `${count(n)} ${n === 1 ? one : many}`; -/** Tokens in and out, the measure of what Coderhelm used. */ +/** All four token parts (new input, cache read, cache write, output), the measure of what Coderhelm used. */ const totalTokens = (s: { tokens?: number; tokens_in: number; tokens_out: number }) => s.tokens ?? s.tokens_in + s.tokens_out; const perPr = (s: { tokens?: number; tokens_in: number; tokens_out: number; prs_merged: number; tokens_per_merged_pr?: number | null }) => s.tokens_per_merged_pr ?? (s.prs_merged ? Math.round(totalTokens(s) / s.prs_merged) : null); diff --git a/dashboard/src/app/runs/detail/page.tsx b/dashboard/src/app/runs/detail/page.tsx index a1a0b706..69af57fb 100644 --- a/dashboard/src/app/runs/detail/page.tsx +++ b/dashboard/src/app/runs/detail/page.tsx @@ -5,6 +5,7 @@ import { useSearchParams, useRouter } from "next/navigation"; import Link from "next/link"; import { api, type RunDetail, type Openspec, type UsageInfo, type PluginDef, type PassTrace, type AgentLogPass, errorStatus } from "@/lib/api"; import { Skeleton } from "@/components/skeleton"; +import { usageBreakdown, usageTotal } from "@/lib/usage"; import { useToast } from "@/components/toast"; import { useConfirm } from "@/components/confirm-dialog"; import { Callout } from "@/components/callout"; @@ -105,6 +106,16 @@ function PassProgress({ currentPass, status, passHistory }: { currentPass?: stri ); } +/** A run's four token parts (missing ones count as 0). */ +function usageOf(r: RunDetail) { + return { + tokens_in: r.tokens_in ?? 0, + tokens_out: r.tokens_out ?? 0, + cache_read_tokens: r.cache_read_tokens ?? 0, + cache_write_tokens: r.cache_write_tokens ?? 0, + }; +} + function formatTokens(n?: number): string { if (n == null) return "—"; if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`; @@ -260,7 +271,7 @@ function AgentLogTurnView({ turn }: { turn: AgentLogPass["conversation"][number] )} {turn.usage && ( - {((turn.usage.input_tokens + turn.usage.output_tokens) / 1000).toFixed(1)}k tokens + {((turn.usage.input_tokens + (turn.usage.cache_read ?? 0) + (turn.usage.cache_write ?? 0) + turn.usage.output_tokens) / 1000).toFixed(1)}k tokens )} @@ -601,19 +612,23 @@ function RunDetailInner() { )} {/* Stats cards */} -
+ {/* Tokens: the total of all four parts, then each part. */} +
- - - - + + + + +
{/* Pass pipeline (collapsed by default) */} {traces.length > 0 && (() => { const maxDuration = Math.max(...traces.map((t) => t.duration_ms), 1); const totalDuration = traces.reduce((s, t) => s + t.duration_ms, 0); - const totalTokens = traces.reduce((s, t) => s + (t.input_tokens || 0) + (t.output_tokens || 0), 0); + const traceTokens = (t: (typeof traces)[number]) => + (t.input_tokens || 0) + (t.cache_read_tokens || 0) + (t.cache_write_tokens || 0) + (t.output_tokens || 0); + const totalTokens = traces.reduce((s, t) => s + traceTokens(t), 0); const passColors: Record = { triage: "from-violet-500/80 to-violet-600/40", plan: "from-blue-500/80 to-blue-600/40", @@ -685,7 +700,7 @@ function RunDetailInner() { const baseName = trace.pass.split(":")[0]; const stepLabel = passLabel(trace.pass); const pct = (trace.duration_ms / maxDuration) * 100; - const passTokens = (trace.input_tokens || 0) + (trace.output_tokens || 0); + const passTokens = traceTokens(trace); const tokenPct = totalTokens > 0 ? (passTokens / totalTokens) * 100 : 0; const cached = trace.cache_read_tokens || 0; const duration = trace.duration_ms >= 60000 @@ -715,11 +730,15 @@ function RunDetailInner() {
{passTokens > 0 ? ( <> - {formatTokens(trace.input_tokens)} in - {formatTokens(trace.output_tokens)} out + {formatTokens(passTokens)} tokens + {formatTokens(trace.input_tokens)} new input {cached > 0 && ( - {formatTokens(cached)} cached + {formatTokens(cached)} read from cache + )} + {(trace.cache_write_tokens || 0) > 0 && ( + {formatTokens(trace.cache_write_tokens || 0)} written to cache )} + {formatTokens(trace.output_tokens)} output {tokenPct.toFixed(0)}% of tokens ) : ( diff --git a/dashboard/src/app/settings/budget/page.tsx b/dashboard/src/app/settings/budget/page.tsx index 84989998..990b4239 100644 --- a/dashboard/src/app/settings/budget/page.tsx +++ b/dashboard/src/app/settings/budget/page.tsx @@ -8,7 +8,7 @@ import { Callout } from "@/components/callout"; import { StatusPill } from "@/components/status-pill"; import { Skeleton } from "@/components/skeleton"; import { inputClass, primaryButton, secondaryButton } from "@/components/ui"; -import { formatTokens, USAGE_CHANGED, usageTone } from "@/lib/usage"; +import { cacheHitRate, FEATURE_LABELS, formatTokens, USAGE_CHANGED, usageBreakdown, usageParts, usageTone, usageTotal } from "@/lib/usage"; import { hasRole } from "@/lib/roles"; // Who may change the limit. The gateway checks the same role on save. @@ -152,7 +152,11 @@ function TokenLimitPage() { function UsageCard({ usage }: { usage: UsageInfo }) { const limit = usage.max_tokens; - const used = usage.total_tokens; + // All four parts: new input, read from cache, written to cache, output. + const used = usageTotal(usage); + const parts = usageParts(usage); + const hitRate = Math.round(cacheHitRate(usage) * 100); + const features = (usage.features ?? []).filter((f) => f.total_tokens > 0); const pct = limit > 0 ? Math.min(100, Math.round((used / limit) * 100)) : 0; const tone = usageTone(used, limit); const bar = tone === "error" ? "bg-red-500" : tone === "warning" ? "bg-amber-500" : "bg-emerald-500"; @@ -186,6 +190,44 @@ function UsageCard({ usage }: { usage: UsageInfo }) { {usage.total_runs.toLocaleString()} {usage.total_runs === 1 ? "run" : "runs"} this month {limit > 0 ? ` · ${pct}% of the limit` : ""}

+ +
+ {parts.map((p) => ( +
+
{p.label}
+
+ {formatTokens(p.value)} +
+
+ ))} +
+

+ Cache hit rate {hitRate}%: the share of input read from the cache instead of sent new or written to it. +

+ + {features.length > 0 && ( +
+

Where the tokens went

+
    + {features.map((f) => ( +
  • + {FEATURE_LABELS[f.feature] ?? f.feature} + + {formatTokens(f.total_tokens)} + · {used > 0 ? Math.round((f.total_tokens / used) * 100) : 0}% + +
  • + ))} +
+
+ )} + + {limit > 0 && usage.limit_counts_cache === false && ( +

+ Runs pause when new input and output reach the limit ({formatTokens(usage.counted_tokens ?? usage.tokens_in + usage.tokens_out)} so far). + Tokens read from or written to the cache are shown above but not counted toward it yet. +

+ )} ); } diff --git a/dashboard/src/app/settings/page.tsx b/dashboard/src/app/settings/page.tsx index ea4e0328..55b2f9f2 100644 --- a/dashboard/src/app/settings/page.tsx +++ b/dashboard/src/app/settings/page.tsx @@ -102,7 +102,7 @@ function SettingsRow({ item, readOnly, status }: { item: SettingsItem; readOnly: {item.description} {status && ( - {status.text} + {status.text} )} diff --git a/dashboard/src/app/settings/use-settings-status.ts b/dashboard/src/app/settings/use-settings-status.ts index 0934c478..7dee29b1 100644 --- a/dashboard/src/app/settings/use-settings-status.ts +++ b/dashboard/src/app/settings/use-settings-status.ts @@ -2,7 +2,7 @@ import { useEffect, useState } from "react"; import { api } from "@/lib/api"; -import { formatTokens, usageTone } from "@/lib/usage"; +import { formatTokens, usageBreakdown, usageTone, usageTotal } from "@/lib/usage"; import { hasRole } from "@/lib/roles"; import { SETTINGS_ITEMS, type SettingsStatusKey } from "@/components/settings-items"; @@ -11,6 +11,8 @@ export type StatusTone = "neutral" | "success" | "warning" | "error"; export interface ItemStatus { text: string; tone: StatusTone; + /** More detail on hover (the token limit's four parts). */ + title?: string; } export interface Me { @@ -27,8 +29,11 @@ const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? o const LOADERS: Record Promise> = { usage: async () => { const u = await api.getUsage(); - if (u.max_tokens <= 0) return { text: `No limit · ${formatTokens(u.total_tokens)} used this month`, tone: "neutral" }; - return { text: `${formatTokens(u.total_tokens)} of ${formatTokens(u.max_tokens)} used this month`, tone: usageTone(u.total_tokens, u.max_tokens) }; + // All four parts (new input, read from cache, written to cache, output). + const used = usageTotal(u); + const title = usageBreakdown(u); + if (u.max_tokens <= 0) return { text: `No limit · ${formatTokens(used)} used this month`, tone: "neutral", title }; + return { text: `${formatTokens(used)} of ${formatTokens(u.max_tokens)} used this month`, tone: usageTone(used, u.max_tokens), title }; }, repos: async () => { const { repos } = await api.listRepos(); diff --git a/dashboard/src/components/client-shell.tsx b/dashboard/src/components/client-shell.tsx index b20af7e3..b88d460a 100644 --- a/dashboard/src/components/client-shell.tsx +++ b/dashboard/src/components/client-shell.tsx @@ -5,7 +5,7 @@ import { usePathname } from "next/navigation"; import { type ReactNode, useEffect, useRef, useState } from "react"; import { api, type UsageInfo, type Banner, type TeamInfo } from "@/lib/api"; import { pushToDataLayer } from "@/lib/gtm"; -import { formatTokens, USAGE_CHANGED } from "@/lib/usage"; +import { formatTokens, USAGE_CHANGED, usageBreakdown, usageTotal } from "@/lib/usage"; import { ToastProvider } from "./toast"; import { ConfirmProvider } from "./confirm-dialog"; import { focusRing } from "./ui"; @@ -434,7 +434,7 @@ export function ClientShell({ children }: { children: React.ReactNode }) { )}
))} - {usage && usage.max_tokens > 0 && usage.total_tokens >= usage.max_tokens && !dismissedBanners.has("token-limit-banner") && ( + {usage && usage.max_tokens > 0 && (usage.counted_tokens ?? usage.total_tokens) >= usage.max_tokens && !dismissedBanners.has("token-limit-banner") && (
@@ -443,7 +443,7 @@ export function ClientShell({ children }: { children: React.ReactNode }) { Token limit reached — all runs are paused

- You've used {formatTokens(usage.total_tokens)} of your {formatTokens(usage.max_tokens)} token limit this month.{" "} + You've used {formatTokens(usageTotal(usage))} of your {formatTokens(usage.max_tokens)} token limit this month.{" "} {user?.role === "owner" ? "Raise the limit or wait for next month." : "Ask the team owner to raise the limit, or wait for next month."}

@@ -680,34 +680,44 @@ function Sidebar({
{/* Tokens remaining */} - {usage && usage.max_tokens > 0 && ( -
-
- Tokens used - = usage.max_tokens - ? "text-red-400" - : usage.total_tokens >= usage.max_tokens * 0.8 - ? "text-yellow-400" - : "text-zinc-300" - }`}> - {formatTokens(usage.total_tokens)} / {formatTokens(usage.max_tokens)} - -
-
+ {usage && usage.max_tokens > 0 && (() => { + // All four parts: new input, read from cache, written to cache, output. + const used = usageTotal(usage); + return ( +
= usage.max_tokens - ? "bg-red-500" - : usage.total_tokens >= usage.max_tokens * 0.8 - ? "bg-yellow-500" - : "bg-emerald-500" - }`} - style={{ width: `${Math.min((usage.total_tokens / usage.max_tokens) * 100, 100)}%` }} - /> + className="flex items-center justify-between text-xs" + title={`${usageBreakdown(usage)} · Limit ${formatTokens(usage.max_tokens)}`} + > + Tokens used + = usage.max_tokens + ? "text-red-400" + : used >= usage.max_tokens * 0.8 + ? "text-yellow-400" + : "text-zinc-300" + }`} + > + {formatTokens(used)} / {formatTokens(usage.max_tokens)} + +
+
+
= usage.max_tokens + ? "bg-red-500" + : used >= usage.max_tokens * 0.8 + ? "bg-yellow-500" + : "bg-emerald-500" + }`} + style={{ width: `${Math.min((used / usage.max_tokens) * 100, 100)}%` }} + /> +
-
- )} + ); + })()} {user && (
diff --git a/dashboard/src/lib/api.ts b/dashboard/src/lib/api.ts index a10a6121..ae9f3a7d 100644 --- a/dashboard/src/lib/api.ts +++ b/dashboard/src/lib/api.ts @@ -1208,11 +1208,32 @@ export interface WorkflowSettings { allow_plan_log_analyzer: boolean; } +/** One feature's share of the month (all four parts). */ +export interface FeatureUsage { + feature: string; + total_tokens: number; + tokens_in: number; + cache_read_tokens: number; + cache_write_tokens: number; + tokens_out: number; +} + export interface UsageInfo { month: string; + /** All four parts: new input + read from cache + written to cache + output. */ total_tokens: number; + /** New input (not read from or written to the cache). */ tokens_in: number; tokens_out: number; + cache_read_tokens?: number; + cache_write_tokens?: number; + /** Read from cache ÷ (read from cache + written to cache + new input). */ + cache_hit_rate?: number; + /** What the limit compares with max_tokens today. */ + counted_tokens?: number; + /** False while the limit still counts new input and output only. */ + limit_counts_cache?: boolean; + features?: FeatureUsage[]; total_runs: number; max_tokens: number; } diff --git a/dashboard/src/lib/usage.ts b/dashboard/src/lib/usage.ts index f7b21c37..76a656dd 100644 --- a/dashboard/src/lib/usage.ts +++ b/dashboard/src/lib/usage.ts @@ -13,6 +13,70 @@ export function formatTokens(n: number): string { return n.toString(); } +type UsageParts = { + tokens_in: number; + tokens_out: number; + cache_read_tokens?: number; + cache_write_tokens?: number; + total_tokens?: number; +}; + +/** The four parts, in the order they are shown everywhere. */ +export function usageParts(u: UsageParts): { label: string; value: number }[] { + return [ + { label: "New input", value: u.tokens_in }, + { label: "Read from cache", value: u.cache_read_tokens ?? 0 }, + { label: "Written to cache", value: u.cache_write_tokens ?? 0 }, + { label: "Output", value: u.tokens_out }, + ]; +} + +/** + * All four parts added up: the total every meter shows. A response without + * the cache parts (an older gateway) falls back to its own total. + */ +export function usageTotal(u: UsageParts): number { + if (u.cache_read_tokens == null && u.cache_write_tokens == null && u.total_tokens != null) { + return u.total_tokens; + } + return usageParts(u).reduce((sum, p) => sum + p.value, 0); +} + +/** Read from cache ÷ (read from cache + written to cache + new input). */ +export function cacheHitRate(u: UsageParts): number { + const read = u.cache_read_tokens ?? 0; + const denom = read + (u.cache_write_tokens ?? 0) + u.tokens_in; + return denom > 0 ? read / denom : 0; +} + +/** "71.3M tokens: New input 124K · Read from cache 61.4M · ..." for hovers. */ +export function usageBreakdown(u: UsageParts): string { + const parts = usageParts(u) + .map((p) => `${p.label} ${formatTokens(p.value)}`) + .join(" · "); + return `${formatTokens(usageTotal(u))} tokens: ${parts} · Cache hit rate ${Math.round(cacheHitRate(u) * 100)}%`; +} + +/** Plain names for the features usage is split by. */ +export const FEATURE_LABELS: Record = { + run: "Ticket runs", + feedback: "PR follow-ups", + review: "PR reviews", + agent_ask: "Team agent questions", + skill_sync: "Team agent sync", + alert: "Alerts", + onboard: "Onboarding", + infra: "Infrastructure analysis", + chat: "Plan chat", + plan: "Plan tasks", + log_analysis: "Log analysis", + release_notes: "Release notes", + tests: "Test results", + live_sources: "Live sources", + memory: "Memory", + other: "Other", +}; + /** "success" under 80% of the limit, "warning" from 80%, "error" at or over it. */ export function usageTone(used: number, limit: number): "success" | "warning" | "error" | "neutral" { if (limit <= 0) return "neutral";