Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
64 changes: 64 additions & 0 deletions dashboard/e2e/settings.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
2 changes: 1 addition & 1 deletion dashboard/src/app/analytics/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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);
Expand Down
41 changes: 30 additions & 11 deletions dashboard/src/app/runs/detail/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
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";
Expand Down Expand Up @@ -105,6 +106,16 @@
);
}

/** 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`;
Expand Down Expand Up @@ -260,7 +271,7 @@
)}
{turn.usage && (
<span className="text-zinc-600 ml-auto">
{((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
</span>
)}
</button>
Expand Down Expand Up @@ -389,7 +400,7 @@
if (idx > max) max = idx;
});
return max;
}, [run?.current_pass, run?.pass_history]);

Check warning on line 403 in dashboard/src/app/runs/detail/page.tsx

View workflow job for this annotation

GitHub Actions / Lint & Build

React Hook useMemo has a missing dependency: 'run'. Either include it or remove the dependency array

const backLink = (
<Link href="/" className={`text-zinc-500 hover:text-zinc-300 text-sm rounded ${focusRing}`}>← Runs</Link>
Expand Down Expand Up @@ -601,19 +612,23 @@
)}

{/* Stats cards */}
<div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-3 mb-6">
{/* Tokens: the total of all four parts, then each part. */}
<div className="grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-6 gap-3 mb-6" title={usageBreakdown(usageOf(run))}>
<StatCard label="Duration" value={formatDuration(run.duration_s)} />
<StatCard label="Tokens in" value={formatTokens(run.tokens_in)} />
<StatCard label="Tokens out" value={formatTokens(run.tokens_out)} />
<StatCard label="Cache read" value={formatTokens(run.cache_read_tokens)} />
<StatCard label="Cache write" value={formatTokens(run.cache_write_tokens)} />
<StatCard label="Total tokens" value={formatTokens(usageTotal(usageOf(run)))} />
<StatCard label="New input" value={formatTokens(run.tokens_in)} />
<StatCard label="Read from cache" value={formatTokens(run.cache_read_tokens)} />
<StatCard label="Written to cache" value={formatTokens(run.cache_write_tokens)} />
<StatCard label="Output" value={formatTokens(run.tokens_out)} />
</div>

{/* 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<string, string> = {
triage: "from-violet-500/80 to-violet-600/40",
plan: "from-blue-500/80 to-blue-600/40",
Expand Down Expand Up @@ -685,7 +700,7 @@
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
Expand Down Expand Up @@ -715,11 +730,15 @@
<div className="flex items-center gap-3 text-[11px]">
{passTokens > 0 ? (
<>
<span className="text-zinc-500">{formatTokens(trace.input_tokens)} in</span>
<span className="text-zinc-500">{formatTokens(trace.output_tokens)} out</span>
<span className="text-zinc-400">{formatTokens(passTokens)} tokens</span>
<span className="text-zinc-500">{formatTokens(trace.input_tokens)} new input</span>
{cached > 0 && (
<span className="text-zinc-600">{formatTokens(cached)} cached</span>
<span className="text-zinc-600">{formatTokens(cached)} read from cache</span>
)}
{(trace.cache_write_tokens || 0) > 0 && (
<span className="text-zinc-600">{formatTokens(trace.cache_write_tokens || 0)} written to cache</span>
)}
<span className="text-zinc-500">{formatTokens(trace.output_tokens)} output</span>
<span className="ml-auto text-zinc-600 tabular-nums">{tokenPct.toFixed(0)}% of tokens</span>
</>
) : (
Expand Down
46 changes: 44 additions & 2 deletions dashboard/src/app/settings/budget/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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";
Expand Down Expand Up @@ -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` : ""}
</p>

<dl aria-label="Tokens by kind" className="mt-4 grid grid-cols-2 gap-x-4 gap-y-3 border-t border-zinc-800 pt-4 sm:grid-cols-4">
{parts.map((p) => (
<div key={p.label} data-testid="usage-part">
<dt className="text-xs text-zinc-500">{p.label}</dt>
<dd className="mt-0.5 text-sm font-medium tabular-nums text-zinc-100" data-value={p.value}>
{formatTokens(p.value)}
</dd>
</div>
))}
</dl>
<p className="mt-3 text-xs text-zinc-500" data-testid="cache-hit-rate">
Cache hit rate {hitRate}%: the share of input read from the cache instead of sent new or written to it.
</p>

{features.length > 0 && (
<div className="mt-4 border-t border-zinc-800 pt-4">
<h3 className="text-xs font-medium text-zinc-400">Where the tokens went</h3>
<ul className="mt-2 space-y-1.5" aria-label="Tokens by feature">
{features.map((f) => (
<li key={f.feature} className="flex items-center justify-between gap-3 text-sm" title={usageBreakdown(f)}>
<span className="text-zinc-300">{FEATURE_LABELS[f.feature] ?? f.feature}</span>
<span className="tabular-nums text-zinc-400">
{formatTokens(f.total_tokens)}
<span className="text-zinc-600"> · {used > 0 ? Math.round((f.total_tokens / used) * 100) : 0}%</span>
</span>
</li>
))}
</ul>
</div>
)}

{limit > 0 && usage.limit_counts_cache === false && (
<p className="mt-4 text-xs text-zinc-500" data-testid="limit-rule">
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.
</p>
)}
</section>
);
}
2 changes: 1 addition & 1 deletion dashboard/src/app/settings/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -102,7 +102,7 @@ function SettingsRow({ item, readOnly, status }: { item: SettingsItem; readOnly:
<span className="block text-sm text-zinc-400 mt-0.5">{item.description}</span>
{status && (
<span className="mt-2 flex">
<StatusPill tone={status.tone}>{status.text}</StatusPill>
<span title={status.title}><StatusPill tone={status.tone}>{status.text}</StatusPill></span>
</span>
)}
</span>
Expand Down
11 changes: 8 additions & 3 deletions dashboard/src/app/settings/use-settings-status.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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";

Expand All @@ -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 {
Expand All @@ -27,8 +29,11 @@ const plural = (n: number, one: string, many = `${one}s`) => `${n} ${n === 1 ? o
const LOADERS: Record<SettingsStatusKey, (me: Me) => Promise<ItemStatus | null>> = {
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();
Expand Down
Loading
Loading