Skip to content

"Vibe-Trading: Your Personal Trading Agent"

feat(frontend): render per-run token usage section in Run Detail (11 locales)

shadowinlife3dc25ca104bb
diff --git a/frontend/src/components/run/LlmUsagePanel.tsx b/frontend/src/components/run/LlmUsagePanel.tsx
new file mode 100644
index 000000000..47a8a3429
--- /dev/null
+++ b/frontend/src/components/run/LlmUsagePanel.tsx
@@ -0,0 +1,80 @@
+import { useTranslation } from "react-i18next";
+import { Coins, Hash } from "lucide-react";
+import type { LlmUsage } from "@/lib/api";
+import { KeyValueTable, RunCardPanel } from "@/components/run/RunCard";
+
+// A missing cache key means the provider never reported a cache event for
+// that scope — never "0 tokens". Totals rows render only when their key is
+// present; the per-iteration table only gains a cache column when at least
+// one iteration reported it, and unreported cells show this marker.
+const NOT_REPORTED = "—";
+
+function cacheCell(value: number | undefined): string {
+ return value === undefined ? NOT_REPORTED : String(value);
+}
+
+export function LlmUsagePanel({ usage }: { usage: LlmUsage }) {
+ const { t } = useTranslation();
+ const { totals } = usage;
+
+ const summary: Record<string, unknown> = {
+ [t("runDetail.llmUsage.provider")]: usage.provider,
+ [t("runDetail.llmUsage.model")]: usage.model,
+ [t("runDetail.llmUsage.inputTokens")]: totals.input_tokens,
+ [t("runDetail.llmUsage.outputTokens")]: totals.output_tokens,
+ [t("runDetail.llmUsage.totalTokens")]: totals.total_tokens,
+ [t("runDetail.llmUsage.calls")]: totals.calls,
+ };
+ if (totals.cache_read_tokens !== undefined) {
+ summary[t("runDetail.llmUsage.cacheRead")] = totals.cache_read_tokens;
+ }
+ if (totals.cache_creation_tokens !== undefined) {
+ summary[t("runDetail.llmUsage.cacheCreation")] = totals.cache_creation_tokens;
+ }
+
+ const calls = usage.per_iteration;
+ const hasCacheRead = calls.some((call) => call.cache_read_tokens !== undefined);
+ const hasCacheCreation = calls.some((call) => call.cache_creation_tokens !== undefined);
+
+ return (
+ <div className="p-4 space-y-4">
+ <div data-testid="llm-usage-summary">
+ <RunCardPanel title={t("runDetail.llmUsage.tab")} icon={Coins}>
+ <KeyValueTable data={summary} empty={t("runDetail.noneRecorded")} />
+ </RunCardPanel>
+ </div>
+ {calls.length > 0 && (
+ <div data-testid="llm-usage-iterations">
+ <RunCardPanel title={t("runDetail.llmUsage.perIteration")} icon={Hash}>
+ <div className="overflow-x-auto">
+ <table className="w-full text-sm">
+ <thead>
+ <tr className="border-b bg-muted/40 text-left text-[11px] uppercase tracking-wide text-muted-foreground [&_th]:font-medium">
+ <th className="py-2 ps-4 pr-4">{t("runDetail.llmUsage.iteration")}</th>
+ <th className="py-2 pr-4 text-end">{t("runDetail.llmUsage.inputTokens")}</th>
+ <th className="py-2 pr-4 text-end">{t("runDetail.llmUsage.outputTokens")}</th>
+ <th className="py-2 pr-4 text-end">{t("runDetail.llmUsage.totalTokens")}</th>
+ {hasCacheRead && <th className="py-2 pr-4 text-end">{t("runDetail.llmUsage.cacheRead")}</th>}
+ {hasCacheCreation && <th className="py-2 text-end">{t("runDetail.llmUsage.cacheCreation")}</th>}
+ </tr>
+ </thead>
+ <tbody>
+ {calls.map((call, index) => (
+ <tr key={`${index}-${call.iter}`} className="border-b last:border-0 hover:bg-muted/40">
+ <td className="py-2 ps-4 pr-4 font-mono tabular-nums">{call.iter}</td>
+ <td className="py-2 pr-4 text-end tabular-nums">{call.input_tokens}</td>
+ <td className="py-2 pr-4 text-end tabular-nums">{call.output_tokens}</td>
+ <td className="py-2 pr-4 text-end tabular-nums">{call.total_tokens}</td>
+ {hasCacheRead && <td className="py-2 pr-4 text-end tabular-nums">{cacheCell(call.cache_read_tokens)}</td>}
+ {hasCacheCreation && <td className="py-2 text-end tabular-nums">{cacheCell(call.cache_creation_tokens)}</td>}
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ </RunCardPanel>
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/frontend/src/components/run/RunCard.tsx b/frontend/src/components/run/RunCard.tsx
index 667fc4999..dfe19ced9 100644
--- a/frontend/src/components/run/RunCard.tsx
+++ b/frontend/src/components/run/RunCard.tsx
@@ -39,3 +39,29 @@ export function formatRunCardValue(value: unknown): string {
if (typeof value === "object" && value !== null) return JSON.stringify(value);
return String(value ?? "");
}
+
+/**
+ * Key/value table used by the Run-Card panels and the token-usage panel.
+ * Lives here (not in pages/RunDetail.tsx) so components can reuse it without
+ * importing the page module, which imports them back.
+ */
+export function KeyValueTable({ data, empty, monospaceValues = false }: { data: Record<string, unknown>; empty: string; monospaceValues?: boolean }) {
+ const entries = Object.entries(data).filter(([, value]) => value !== undefined && value !== null && value !== "");
+ if (entries.length === 0) {
+ return <p className="text-sm text-muted-foreground">{empty}</p>;
+ }
+ return (
+ <div className="overflow-x-auto">
+ <table className="w-full table-fixed text-sm">
+ <tbody>
+ {entries.map(([key, value]) => (
+ <tr key={key} className="border-b last:border-0 hover:bg-muted/40">
+ <td className="w-36 break-all py-2 ps-4 pr-4 align-top text-muted-foreground">{key}</td>
+ <td className={cn("py-2 align-top", monospaceValues ? "break-all font-mono text-xs" : "break-words text-right tabular-nums")}>{formatRunCardValue(value)}</td>
+ </tr>
+ ))}
+ </tbody>
+ </table>
+ </div>
+ );
+}
diff --git a/frontend/src/i18n/locales/ar.json b/frontend/src/i18n/locales/ar.json
index eadb9335a..6c6b47dff 100644
--- a/frontend/src/i18n/locales/ar.json
+++ b/frontend/src/i18n/locales/ar.json
@@ -1361,6 +1361,19 @@
"ddNotRecovered": "لم يتعافَ",
"ddDays": "{{count}} يوم",
"dashboard": "لوحة البحث",
+ "llmUsage": {
+ "tab": "استخدام الرموز",
+ "provider": "المزوّد",
+ "model": "النموذج",
+ "inputTokens": "رموز الإدخال",
+ "outputTokens": "رموز الإخراج",
+ "totalTokens": "إجمالي الرموز",
+ "calls": "عدد الاستدعاءات",
+ "cacheRead": "رموز قراءة التخزين المؤقت",
+ "cacheCreation": "رموز إنشاء التخزين المؤقت",
+ "perIteration": "التفصيل لكل تكرار",
+ "iteration": "التكرار"
+ },
"positions": {
"tab": "المراكز",
"weightDistribution": "توزيع الأوزان",
diff --git a/frontend/src/i18n/locales/de.json b/frontend/src/i18n/locales/de.json
index 20cedce5e..7d29fb6ca 100644
--- a/frontend/src/i18n/locales/de.json
+++ b/frontend/src/i18n/locales/de.json
@@ -1366,6 +1366,19 @@
"ddNotRecovered": "Nicht erholt",
"ddDays": "{{count}} T",
"dashboard": "Research-Dashboard",
+ "llmUsage": {
+ "tab": "Token-Nutzung",
+ "provider": "Anbieter",
+ "model": "Modell",
+ "inputTokens": "Eingabe-Tokens",
+ "outputTokens": "Ausgabe-Tokens",
+ "totalTokens": "Tokens gesamt",
+ "calls": "Aufrufe",
+ "cacheRead": "Cache-Lese-Tokens",
+ "cacheCreation": "Tokens für Cache-Erstellung",
+ "perIteration": "Detail nach Iteration",
+ "iteration": "Iteration"
+ },
"positions": {
"tab": "Positionen",
"weightDistribution": "Gewichtsverteilung",
diff --git a/frontend/src/i18n/locales/en.json b/frontend/src/i18n/locales/en.json
index bc70317a0..a8be60eab 100644
--- a/frontend/src/i18n/locales/en.json
+++ b/frontend/src/i18n/locales/en.json
@@ -1366,6 +1366,19 @@
"ddNotRecovered": "Not recovered",
"ddDays": "{{count}} d",
"dashboard": "Research dashboard",
+ "llmUsage": {
+ "tab": "Token Usage",
+ "provider": "Provider",
+ "model": "Model",
+ "inputTokens": "Input tokens",
+ "outputTokens": "Output tokens",
+ "totalTokens": "Total tokens",
+ "calls": "Calls",
+ "cacheRead": "Cache read tokens",
+ "cacheCreation": "Cache creation tokens",
+ "perIteration": "Per-iteration detail",
+ "iteration": "Iteration"
+ },
"positions": {
"tab": "Positions",
"weightDistribution": "Weight distribution",
diff --git a/frontend/src/i18n/locales/es.json b/frontend/src/i18n/locales/es.json
index 238237536..36ad0d56c 100644
--- a/frontend/src/i18n/locales/es.json
+++ b/frontend/src/i18n/locales/es.json
@@ -1366,6 +1366,19 @@
"ddNotRecovered": "No recuperado",
"ddDays": "{{count}} d",
"dashboard": "Panel de investigación",
+ "llmUsage": {
+ "tab": "Uso de tokens",
+ "provider": "Proveedor",
+ "model": "Modelo",
+ "inputTokens": "Tokens de entrada",
+ "outputTokens": "Tokens de salida",
+ "totalTokens": "Tokens totales",
+ "calls": "Llamadas",
+ "cacheRead": "Tokens de lectura de caché",
+ "cacheCreation": "Tokens de creación de caché",
+ "perIteration": "Detalle por iteración",
+ "iteration": "Iteración"
+ },
"positions": {
"tab": "Posiciones",
"weightDistribution": "Distribución de pesos",
diff --git a/frontend/src/i18n/locales/fa.json b/frontend/src/i18n/locales/fa.json
index 25041deee..15beb84bd 100644
--- a/frontend/src/i18n/locales/fa.json
+++ b/frontend/src/i18n/locales/fa.json
@@ -1366,6 +1366,19 @@
"ddNotRecovered": "بازیابی نشده",
"ddDays": "{{count}} روز",
"dashboard": "داشبورد پژوهش",
+ "llmUsage": {
+ "tab": "مصرف توکن",
+ "provider": "ارائه‌دهنده",
+ "model": "مدل",
+ "inputTokens": "توکن‌های ورودی",
+ "outputTokens": "توکن‌های خروجی",
+ "totalTokens": "مجموع توکن‌ها",
+ "calls": "تعداد فراخوانی‌ها",
+ "cacheRead": "توکن‌های خواندن کش",
+ "cacheCreation": "توکن‌های ایجاد کش",
+ "perIteration": "جزئیات هر تکرار",
+ "iteration": "تکرار"
+ },
"positions": {
"tab": "موقعیت‌ها",
"weightDistribution": "توزیع وزن",
diff --git a/frontend/src/i18n/locales/id.json b/frontend/src/i18n/locales/id.json
index 7d7415695..1861ff957 100644
--- a/frontend/src/i18n/locales/id.json
+++ b/frontend/src/i18n/locales/id.json
@@ -1366,6 +1366,19 @@
"ddNotRecovered": "Belum pulih",
"ddDays": "{{count}} hari",
"dashboard": "Dashboard Riset",
+ "llmUsage": {
+ "tab": "Pemakaian token",
+ "provider": "Penyedia",
+ "model": "Model",
+ "inputTokens": "Token input",
+ "outputTokens": "Token output",
+ "totalTokens": "Total token",
+ "calls": "Jumlah panggilan",
+ "cacheRead": "Token baca cache",
+ "cacheCreation": "Token pembuatan cache",
+ "perIteration": "Rincian per iterasi",
+ "iteration": "Iterasi"
+ },
"positions": {
"tab": "Posisi",
"weightDistribution": "Distribusi bobot",
diff --git a/frontend/src/i18n/locales/ja.json b/frontend/src/i18n/locales/ja.json
index dea9cc266..6d9eeeec8 100644
--- a/frontend/src/i18n/locales/ja.json
+++ b/frontend/src/i18n/locales/ja.json
@@ -1361,6 +1361,19 @@
"ddNotRecovered": "未回復",
"ddDays": "{{count}}日",
"dashboard": "リサーチダッシュボード",
+ "llmUsage": {
+ "tab": "トークン使用量",
+ "provider": "プロバイダー",
+ "model": "モデル",
+ "inputTokens": "入力トークン",
+ "outputTokens": "出力トークン",
+ "totalTokens": "合計トークン",
+ "calls": "呼び出し回数",
+ "cacheRead": "キャッシュ読み込みトークン",
+ "cacheCreation": "キャッシュ作成トークン",
+ "perIteration": "イテレーション別明細",
+ "iteration": "イテレーション"
+ },
"positions": {
"tab": "ポジション",
"weightDistribution": "ウェイト分布",
diff --git a/frontend/src/i18n/locales/ko.json b/frontend/src/i18n/locales/ko.json
index 0f8ad6ae6..791156ebd 100644
--- a/frontend/src/i18n/locales/ko.json
+++ b/frontend/src/i18n/locales/ko.json
@@ -1361,6 +1361,19 @@
"ddNotRecovered": "미회복",
"ddDays": "{{count}}일",
"dashboard": "리서치 대시보드",
+ "llmUsage": {
+ "tab": "토큰 사용량",
+ "provider": "제공자",
+ "model": "모델",
+ "inputTokens": "입력 토큰",
+ "outputTokens": "출력 토큰",
+ "totalTokens": "총 토큰",
+ "calls": "호출 횟수",
+ "cacheRead": "캐시 읽기 토큰",
+ "cacheCreation": "캐시 생성 토큰",
+ "perIteration": "반복별 명세",
+ "iteration": "반복"
+ },
"positions": {
"tab": "포지션",
"weightDistribution": "비중 분포",
diff --git a/frontend/src/i18n/locales/pt-BR.json b/frontend/src/i18n/locales/pt-BR.json
index cbe454389..637e09646 100644
--- a/frontend/src/i18n/locales/pt-BR.json
+++ b/frontend/src/i18n/locales/pt-BR.json
@@ -1366,6 +1366,19 @@
"ddNotRecovered": "Não recuperado",
"ddDays": "{{count}}d",
"dashboard": "Painel de pesquisa",
+ "llmUsage": {
+ "tab": "Uso de tokens",
+ "provider": "Provedor",
+ "model": "Modelo",
+ "inputTokens": "Tokens de entrada",
+ "outputTokens": "Tokens de saída",
+ "totalTokens": "Tokens totais",
+ "calls": "Chamadas",
+ "cacheRead": "Tokens de leitura de cache",
+ "cacheCreation": "Tokens de criação de cache",
+ "perIteration": "Detalhe por iteração",
+ "iteration": "Iteração"
+ },
"positions": {
"tab": "Posições",
"weightDistribution": "Distribuição de peso",
diff --git a/frontend/src/i18n/locales/tr.json b/frontend/src/i18n/locales/tr.json
index fd7a8e599..82d30f087 100644
--- a/frontend/src/i18n/locales/tr.json
+++ b/frontend/src/i18n/locales/tr.json
@@ -1305,6 +1305,19 @@
"ddNotRecovered": "Toparlanmadı",
"ddDays": "{{count}} gün",
"dashboard": "Araştırma paneli",
+ "llmUsage": {
+ "tab": "Token kullanımı",
+ "provider": "Sağlayıcı",
+ "model": "Model",
+ "inputTokens": "Girdi belirteçleri",
+ "outputTokens": "Çıktı belirteçleri",
+ "totalTokens": "Toplam belirteç",
+ "calls": "Çağrı sayısı",
+ "cacheRead": "Önbellek okuma belirteçleri",
+ "cacheCreation": "Önbellek oluşturma belirteçleri",
+ "perIteration": "Yineleme ayrıntıları",
+ "iteration": "Yineleme"
+ },
"positions": {
"tab": "Pozisyonlar",
"weightDistribution": "Ağırlık dağılımı",
diff --git a/frontend/src/i18n/locales/zh-CN.json b/frontend/src/i18n/locales/zh-CN.json
index ff8e1cdf2..0996e80bd 100644
--- a/frontend/src/i18n/locales/zh-CN.json
+++ b/frontend/src/i18n/locales/zh-CN.json
@@ -1361,6 +1361,19 @@
"ddNotRecovered": "未恢复",
"ddDays": "{{count}} 天",
"dashboard": "研究仪表盘",
+ "llmUsage": {
+ "tab": "Token 用量",
+ "provider": "服务商",
+ "model": "模型",
+ "inputTokens": "输入 Token",
+ "outputTokens": "输出 Token",
+ "totalTokens": "总 Token",
+ "calls": "调用次数",
+ "cacheRead": "缓存读取 Token",
+ "cacheCreation": "缓存写入 Token",
+ "perIteration": "按迭代明细",
+ "iteration": "迭代"
+ },
"positions": {
"tab": "持仓",
"weightDistribution": "权重分布",
diff --git a/frontend/src/pages/RunDetail.tsx b/frontend/src/pages/RunDetail.tsx
index d5a1a3b37..d9532b328 100644
--- a/frontend/src/pages/RunDetail.tsx
+++ b/frontend/src/pages/RunDetail.tsx
@@ -13,6 +13,7 @@ import {
CalendarRange,
CheckCircle2,
Code2,
+ Coins,
Copy,
Database,
Download,
@@ -52,14 +53,15 @@ import { ErrorBoundary } from "@/components/common/ErrorBoundary";
import { getStrategyReportIdentity, StrategyResearchDashboard } from "@/components/charts/StrategyResearchDashboard";
import { FactorResearchPanel } from "@/components/charts/FactorResearchPanel";
import { AttributionTab } from "@/components/charts/AttributionTab";
+import { LlmUsagePanel } from "@/components/run/LlmUsagePanel";
import { PositionsTab } from "@/components/run/PositionsTab";
-import { RunCardPanel, RunCardStat, formatRunCardValue } from "@/components/run/RunCard";
+import { KeyValueTable, RunCardPanel, RunCardStat, formatRunCardValue } from "@/components/run/RunCard";
import { isDateColumn } from "@/lib/positions";
import { runTrades } from "@/lib/runReports";
const rehypePlugins = [rehypeHighlight];
-type Tab = "dashboard" | "chart" | "tearsheet" | "trades" | "positions" | "attribution" | "runCard" | "code" | "validation" | "studio" | "factor";
+type Tab = "dashboard" | "chart" | "tearsheet" | "trades" | "positions" | "attribution" | "runCard" | "llmUsage" | "code" | "validation" | "studio" | "factor";
type ChartPayload = Pick<RunData, "price_series" | "indicator_series" | "trade_markers">;
type ChartCache = Record<string, ChartPayload>;
type ChartLoadProgress = { done: number; total: number };
@@ -153,6 +155,7 @@ export function RunDetail() {
const hasPositions = !!run?.artifacts_positions_csv?.some(
(row) => Object.keys(row).some((key) => !isDateColumn(key)),
);
+ const hasLlmUsage = !!run?.llm_usage?.totals;
const TABS: { id: Tab; label: string; icon: typeof BarChart3; hidden?: boolean }[] = [
{ id: "dashboard", label: i18n.t("runDetail.dashboard"), icon: LayoutDashboard },
{ id: "chart", label: i18n.t("runDetail.chart"), icon: BarChart3 },
@@ -164,6 +167,7 @@ export function RunDetail() {
{ id: "studio", label: i18n.t("runDetail.studio"), icon: Gauge, hidden: !hasStudio },
{ id: "validation", label: i18n.t("runDetail.validation"), icon: ShieldCheck, hidden: !hasValidation },
{ id: "runCard", label: i18n.t("runDetail.runCard"), icon: FileCheck2, hidden: !hasRunCard },
+ { id: "llmUsage", label: i18n.t("runDetail.llmUsage.tab"), icon: Coins, hidden: !hasLlmUsage },
{ id: "code", label: i18n.t("runDetail.code"), icon: Code2 },
];
@@ -462,6 +466,7 @@ export function RunDetail() {
<StudioTab xray={run.risk_xray} notes={run.rebalance_notes} />
)}
{tab === "runCard" && run.run_card && <RunCardTab card={run.run_card} />}
+ {tab === "llmUsage" && run.llm_usage && <LlmUsagePanel usage={run.llm_usage} />}
{tab === "code" && <CodeTab code={code} />}
</ErrorBoundary>
</div>
@@ -800,27 +805,6 @@ function FactorTab({ runId }: { runId: string }) {
);
}
-function KeyValueTable({ data, empty, monospaceValues = false }: { data: Record<string, unknown>; empty: string; monospaceValues?: boolean }) {
- const entries = Object.entries(data).filter(([, value]) => value !== undefined && value !== null && value !== "");
- if (entries.length === 0) {
- return <p className="text-sm text-muted-foreground">{empty}</p>;
- }
- return (
- <div className="overflow-x-auto">
- <table className="w-full table-fixed text-sm">
- <tbody>
- {entries.map(([key, value]) => (
- <tr key={key} className="border-b last:border-0 hover:bg-muted/40">
- <td className="w-36 break-all py-2 ps-4 pr-4 align-top text-muted-foreground">{key}</td>
- <td className={cn("py-2 align-top", monospaceValues ? "break-all font-mono text-xs" : "break-words text-right tabular-nums")}>{formatRunCardValue(value)}</td>
- </tr>
- ))}
- </tbody>
- </table>
- </div>
- );
-}
-
function hasStructuredValidation(value: unknown): boolean {
if (!value || typeof value !== "object") return false;
const v = value as Record<string, unknown>;
diff --git a/frontend/src/pages/__tests__/RunDetail.usage.test.tsx b/frontend/src/pages/__tests__/RunDetail.usage.test.tsx
new file mode 100644
index 000000000..12f37efd3
--- /dev/null
+++ b/frontend/src/pages/__tests__/RunDetail.usage.test.tsx
@@ -0,0 +1,146 @@
+import { fireEvent, render, screen, within } from "@testing-library/react";
+import { createMemoryRouter, RouterProvider } from "react-router";
+import { RunDetail } from "../RunDetail";
+
+const apiMock = vi.hoisted(() => ({
+ getRun: vi.fn(),
+ getRunCode: vi.fn(),
+}));
+
+vi.mock("@/lib/api", () => ({ api: apiMock }));
+vi.mock("@/components/charts/CandlestickChart", () => ({
+ CandlestickChart: () => <div data-testid="candlestick-chart" />,
+}));
+vi.mock("@/components/charts/EquityChart", () => ({
+ EquityChart: () => <div data-testid="equity-chart" />,
+}));
+
+function renderRunDetail(path = "/runs/usage-run") {
+ const router = createMemoryRouter(
+ [{ path: "/runs/:runId", element: <RunDetail /> }],
+ { initialEntries: [path] },
+ );
+ render(<RouterProvider router={router} />);
+ return router;
+}
+
+const perIterationNoCache = [
+ { iter: 0, input_tokens: 500, output_tokens: 900, total_tokens: 1400 },
+ { iter: 1, input_tokens: 414, output_tokens: 2278, total_tokens: 2692 },
+ { iter: 2, input_tokens: 320, output_tokens: 2500, total_tokens: 2820 },
+];
+
+const usageNoCache = {
+ provider: "openai",
+ model: "gpt-5.6-terra",
+ totals: { input_tokens: 1234, output_tokens: 5678, total_tokens: 6912, calls: 3 },
+ per_iteration: perIterationNoCache,
+ updated_at: "2026-10-16T00:00:00Z",
+};
+
+const usageWithCache = {
+ provider: "anthropic",
+ model: "claude-sonnet-5",
+ totals: {
+ input_tokens: 1234,
+ output_tokens: 5678,
+ total_tokens: 6912,
+ calls: 3,
+ cache_read_tokens: 300,
+ cache_creation_tokens: 40,
+ },
+ per_iteration: [
+ { ...perIterationNoCache[0], cache_read_tokens: 100, cache_creation_tokens: 40 },
+ perIterationNoCache[1],
+ { ...perIterationNoCache[2], cache_read_tokens: 200 },
+ ],
+ updated_at: "2026-10-16T00:00:00Z",
+};
+
+async function openUsageTab(prompt = "Usage run") {
+ await screen.findByText(prompt);
+ fireEvent.click(screen.getByRole("tab", { name: "Token Usage" }));
+}
+
+describe("RunDetail token-usage tab", () => {
+ beforeEach(() => {
+ apiMock.getRun.mockReset();
+ apiMock.getRunCode.mockReset();
+ apiMock.getRunCode.mockResolvedValue({});
+ });
+
+ it("shows the reported totals without inventing cache rows", async () => {
+ apiMock.getRun.mockResolvedValue({
+ status: "success",
+ run_id: "usage-run",
+ prompt: "Usage run",
+ llm_usage: usageNoCache,
+ });
+
+ renderRunDetail();
+ await openUsageTab();
+
+ const summary = await screen.findByTestId("llm-usage-summary");
+ expect(within(summary).getByText("1234")).toBeInTheDocument();
+ expect(within(summary).getByText("5678")).toBeInTheDocument();
+ expect(within(summary).getByText("6912")).toBeInTheDocument();
+ expect(within(summary).getByText("3")).toBeInTheDocument();
+ expect(within(summary).getByText("openai")).toBeInTheDocument();
+ expect(within(summary).getByText("gpt-5.6-terra")).toBeInTheDocument();
+ expect(within(summary).queryByText("Cache read tokens")).not.toBeInTheDocument();
+ expect(within(summary).queryByText("Cache creation tokens")).not.toBeInTheDocument();
+
+ const iterations = screen.getByTestId("llm-usage-iterations");
+ expect(within(iterations).queryByText("Cache read tokens")).not.toBeInTheDocument();
+ expect(within(iterations).getByText("414")).toBeInTheDocument();
+ });
+
+ it("renders cache totals and per-iteration cache columns when the provider reported them", async () => {
+ apiMock.getRun.mockResolvedValue({
+ status: "success",
+ run_id: "usage-run",
+ prompt: "Cached usage run",
+ llm_usage: usageWithCache,
+ });
+
+ renderRunDetail();
+ await openUsageTab("Cached usage run");
+
+ const summary = await screen.findByTestId("llm-usage-summary");
+ expect(within(summary).getByText("Cache read tokens")).toBeInTheDocument();
+ expect(within(summary).getByText("300")).toBeInTheDocument();
+ expect(within(summary).getByText("Cache creation tokens")).toBeInTheDocument();
+ expect(within(summary).getByText("40")).toBeInTheDocument();
+
+ const iterations = screen.getByTestId("llm-usage-iterations");
+ const rows = within(iterations).getAllByRole("row");
+ expect(within(rows[1]).getAllByRole("cell").map((cell) => cell.textContent)).toEqual([
+ "0", "500", "900", "1400", "100", "40",
+ ]);
+ // an iteration that never reported cache gets the not-reported marker,
+ // never a fabricated 0
+ expect(within(rows[2]).getAllByRole("cell").map((cell) => cell.textContent)).toEqual([
+ "1", "414", "2278", "2692", "—", "—",
+ ]);
+ expect(within(rows[3]).getAllByRole("cell").map((cell) => cell.textContent)).toEqual([
+ "2", "320", "2500", "2820", "200", "—",
+ ]);
+ });
+
+ it.each([
+ { label: "null", llm_usage: null },
+ { label: "absent", llm_usage: undefined },
+ ])("hides the Token Usage tab when llm_usage is $label", async ({ llm_usage }) => {
+ apiMock.getRun.mockResolvedValue({
+ status: "success",
+ run_id: "usage-run",
+ prompt: "Silent run",
+ llm_usage,
+ });
+
+ renderRunDetail();
+ await screen.findByText("Silent run");
+
+ expect(screen.queryByRole("tab", { name: "Token Usage" })).not.toBeInTheDocument();
+ });
+});