Skip to content

Job application tracker and AI-powered job search assistant. Helps job seekers manage their search journey with AI resume review, job matching, task logging, and application analytics, all while keeping your data private.

feat(settings): add the AI Usage section — token, call, response-time and failure cards, daily tokens by provider, provider/model and feature breakdowns with context-limit flags, failures with timeouts, and the last 50 calls

Khuram Niazf0bc7c4fdc8e
diff --git a/__tests__/AiUsageSettings.spec.tsx b/__tests__/AiUsageSettings.spec.tsx
new file mode 100644
index 0000000..8d44345
--- /dev/null
+++ b/__tests__/AiUsageSettings.spec.tsx
@@ -0,0 +1,132 @@
+import { render, screen, waitFor } from "@testing-library/react";
+import userEvent from "@testing-library/user-event";
+import AiUsageSettings from "@/components/settings/AiUsageSettings";
+import { getAiUsage } from "@/actions/aiUsage.actions";
+import type { AiUsageSummary } from "@/models/aiUsage.model";
+
+vi.mock("@/actions/aiUsage.actions", () => ({ getAiUsage: vi.fn() }));
+vi.mock("@nivo/bar", () => ({ ResponsiveBar: () => <div data-testid="daily-chart" /> }));
+vi.mock("next-themes", () => ({ useTheme: () => ({ resolvedTheme: "dark" }) }));
+
+const summary = (over: Partial<AiUsageSummary> = {}): AiUsageSummary => ({
+ rangeDays: 30,
+ totals: {
+ inputTokens: 3_020_000,
+ outputTokens: 630_000,
+ calls: 837,
+ previousCalls: 747,
+ failures: 13,
+ stopped: 5,
+ medianMs: 8400,
+ p95Ms: 41200,
+ medianFirstTokenMs: 1900,
+ },
+ failuresByStatus: { error: 7, truncated: 3, interrupted: 2, timed_out: 1 },
+ days: [{ date: "2026-09-28", tokensByProvider: { ollama: 1000 } }],
+ providers: [
+ {
+ provider: "ollama",
+ tokens: 1_840_000,
+ calls: 412,
+ models: [{ model: "qwen3.5:9b", tokens: 1_840_000, calls: 412, medianMs: 14200, p95Ms: 58000, medianFirstTokenMs: 3100, nearContextLimit: 9 }],
+ },
+ ],
+ features: [{ feature: "agent_chat", tokens: 1_280_000, calls: 318, medianMs: 6100 }],
+ recent: [
+ {
+ id: "c1",
+ startedAt: new Date(),
+ feature: "resume_review",
+ provider: "ollama",
+ model: "qwen3.5:9b",
+ status: "timed_out",
+ inputTokens: 7950,
+ outputTokens: null,
+ durationMs: 180000,
+ firstTokenMs: 3900,
+ },
+ ],
+ ...over,
+});
+
+describe("AiUsageSettings", () => {
+ beforeEach(() => {
+ vi.clearAllMocks();
+ (getAiUsage as any).mockResolvedValue({ success: true, data: summary() });
+ });
+
+ it("loads 30 days by default with the viewer's timezone", async () => {
+ render(<AiUsageSettings />);
+ await screen.findByText("3.65M");
+ const arg = (getAiUsage as any).mock.calls[0][0];
+ expect(arg.rangeDays).toBe(30);
+ expect(arg.timeZone).toBe(Intl.DateTimeFormat().resolvedOptions().timeZone);
+ expect(arg.since.getHours()).toBe(0);
+ });
+
+ it("renders the stat cards from the design, without a thinking line", async () => {
+ render(<AiUsageSettings />);
+ expect(await screen.findByText("3.02M input · 0.63M output")).toBeInTheDocument();
+ expect(screen.queryByText(/thinking/i)).not.toBeInTheDocument();
+ expect(screen.getByText("837")).toBeInTheDocument();
+ expect(screen.getByText("+12% vs previous 30 days")).toBeInTheDocument();
+ expect(screen.getByText("8.4s")).toBeInTheDocument();
+ expect(screen.getByText("p95 41.2s")).toBeInTheDocument();
+ expect(screen.getByText("7 error · 3 truncated · 2 interrupted · 1 timed out")).toBeInTheDocument();
+ });
+
+ it("shows the four failure kinds and the stopped footer", async () => {
+ render(<AiUsageSettings />);
+ await screen.findByText("Provider error");
+ expect(screen.getAllByText("Timed out").length).toBeGreaterThan(0);
+ expect(screen.getByText("13 of 837 calls")).toBeInTheDocument();
+ expect(screen.getByText("Stopped by you — not counted as failures")).toBeInTheDocument();
+ });
+
+ it("flags models near their context limit", async () => {
+ render(<AiUsageSettings />);
+ expect(await screen.findByText("9 calls near context limit")).toBeInTheDocument();
+ });
+
+ it("collapses a provider's models", async () => {
+ render(<AiUsageSettings />);
+ const toggle = await screen.findByRole("button", { name: /Ollama/ });
+ await userEvent.click(toggle);
+ expect(screen.queryByText("9 calls near context limit")).not.toBeInTheDocument();
+ });
+
+ it("refetches when switching to 7 days", async () => {
+ render(<AiUsageSettings />);
+ await screen.findByText("3.65M");
+ await userEvent.click(screen.getByRole("button", { name: "7 days" }));
+ await waitFor(() => expect((getAiUsage as any).mock.calls.at(-1)[0].rangeDays).toBe(7));
+ });
+
+ it("hides the change line when the previous period was empty", async () => {
+ (getAiUsage as any).mockResolvedValue({ success: true, data: summary({ totals: { ...summary().totals, previousCalls: 0 } }) });
+ render(<AiUsageSettings />);
+ await screen.findByText("837");
+ expect(screen.queryByText(/vs previous/)).not.toBeInTheDocument();
+ });
+
+ it("shows an empty state when the range has no calls", async () => {
+ (getAiUsage as any).mockResolvedValue({
+ success: true,
+ data: summary({ totals: { ...summary().totals, calls: 0 }, providers: [], features: [], recent: [] }),
+ });
+ render(<AiUsageSettings />);
+ expect(await screen.findByText("No AI calls in the last 30 days.")).toBeInTheDocument();
+ });
+
+ it("shows an inline error when loading fails", async () => {
+ (getAiUsage as any).mockResolvedValue({ success: false, message: "boom" });
+ render(<AiUsageSettings />);
+ expect(await screen.findByText("Couldn't load AI usage.")).toBeInTheDocument();
+ });
+
+ it("shows the inline error, not a spinner, when the action throws", async () => {
+ (getAiUsage as any).mockRejectedValue(new Error("fetch failed"));
+ render(<AiUsageSettings />);
+ expect(await screen.findByText("Couldn't load AI usage.")).toBeInTheDocument();
+ });
+});
diff --git a/__tests__/aiUsageFormat.spec.ts b/__tests__/aiUsageFormat.spec.ts
new file mode 100644
index 0000000..76c2c29
--- /dev/null
+++ b/__tests__/aiUsageFormat.spec.ts
@@ -0,0 +1,46 @@
+import {
+ formatCallTime,
+ formatChange,
+ formatCount,
+ formatSeconds,
+ formatTokens,
+ providerLabel,
+} from "@/components/settings/ai-usage-settings/format";
+
+it.each([
+ [3_650_000, "3.65M"],
+ [410_000, "410K"],
+ [140_400, "140K"],
+ [999_600, "1.00M"],
+ [950, "950"],
+ [0, "0"],
+])("formatTokens(%i) = %s", (n, s) => expect(formatTokens(n)).toBe(s));
+
+it("formats counts with separators and blanks", () => {
+ expect(formatCount(4812)).toBe("4,812");
+ expect(formatCount(null)).toBe("—");
+});
+
+it("formats seconds with one decimal", () => {
+ expect(formatSeconds(8400)).toBe("8.4s");
+ expect(formatSeconds(400)).toBe("0.4s");
+ expect(formatSeconds(null)).toBe("—");
+});
+
+it("labels today, yesterday and older calls", () => {
+ const now = new Date(2026, 8, 28, 15, 0);
+ expect(formatCallTime(new Date(2026, 8, 28, 14, 32), now)).toBe("Today 14:32");
+ expect(formatCallTime(new Date(2026, 8, 27, 21, 48), now)).toBe("Yesterday 21:48");
+ expect(formatCallTime(new Date(2026, 8, 12, 9, 0), now)).toBe("Sep 12 09:00");
+});
+
+it("reports change only against a non-empty previous period", () => {
+ expect(formatChange(837, 747)).toEqual({ text: "+12%", up: true });
+ expect(formatChange(50, 100)).toEqual({ text: "-50%", up: false });
+ expect(formatChange(10, 0)).toBeNull();
+});
+
+it("labels providers and falls back to the raw id", () => {
+ expect(providerLabel("deepseek")).toBe("DeepSeek");
+ expect(providerLabel("mystery")).toBe("mystery");
+});
diff --git a/src/app/dashboard/settings/page.tsx b/src/app/dashboard/settings/page.tsx
index 7c271aa..c3d1f97 100644
--- a/src/app/dashboard/settings/page.tsx
+++ b/src/app/dashboard/settings/page.tsx
@@ -2,6 +2,7 @@
import { useState } from "react";
import AiSettings from "@/components/settings/AiSettings";
+import AiUsageSettings from "@/components/settings/AiUsageSettings";
import ApiKeySettings from "@/components/settings/ApiKeySettings";
import DataSettings from "@/components/settings/DataSettings";
import DisplaySettings from "@/components/settings/DisplaySettings";
@@ -23,6 +24,7 @@ function Settings() {
/>
<div className="flex-1 min-w-0">
{activeSection === "ai-provider" && <AiSettings />}
+ {activeSection === "ai-usage" && <AiUsageSettings />}
{activeSection === "api-keys" && <ApiKeySettings />}
{activeSection === "appearance" && <DisplaySettings />}
{activeSection === "mcp-access" && <McpAccessSettings />}
diff --git a/src/components/settings/AiUsageSettings.tsx b/src/components/settings/AiUsageSettings.tsx
new file mode 100644
index 0000000..703788d
--- /dev/null
+++ b/src/components/settings/AiUsageSettings.tsx
@@ -0,0 +1,133 @@
+"use client";
+
+import { useEffect, useRef, useState } from "react";
+import { startOfDay, subDays } from "date-fns";
+import { Loader2 } from "lucide-react";
+import { cn } from "@/lib/utils";
+import { getAiUsage } from "@/actions/aiUsage.actions";
+import type { AiUsageRange, AiUsageSummary } from "@/models/aiUsage.model";
+import UsageSummaryCards from "./ai-usage-settings/UsageSummaryCards";
+import DailyTokensChart from "./ai-usage-settings/DailyTokensChart";
+import ProviderModelTable from "./ai-usage-settings/ProviderModelTable";
+import FeatureBreakdown from "./ai-usage-settings/FeatureBreakdown";
+import FailuresCard from "./ai-usage-settings/FailuresCard";
+import RecentCallsTable from "./ai-usage-settings/RecentCallsTable";
+
+const RANGES: AiUsageRange[] = [7, 30];
+
+export default function AiUsageSettings() {
+ const [range, setRange] = useState<AiUsageRange>(30);
+ const [summary, setSummary] = useState<AiUsageSummary | null>(null);
+ const [failed, setFailed] = useState(false);
+ const [loading, setLoading] = useState(true);
+ const failuresRef = useRef<HTMLElement>(null);
+
+ useEffect(() => {
+ let cancelled = false;
+ setLoading(true);
+ // Local midnight of the oldest day: only the browser knows its calendar.
+ const since = startOfDay(subDays(new Date(), range - 1));
+ const timeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
+ getAiUsage({ rangeDays: range, since, timeZone })
+ .then((res) => {
+ if (cancelled) return;
+ setFailed(!res.success);
+ if (res.success) setSummary(res.data);
+ })
+ // A thrown action (server restart, dropped network) must not spin forever.
+ .catch(() => {
+ if (!cancelled) setFailed(true);
+ })
+ .finally(() => {
+ if (!cancelled) setLoading(false);
+ });
+ return () => {
+ cancelled = true;
+ };
+ }, [range]);
+
+ return (
+ // Named: @container/main also spans the settings sidebar.
+ <div className="@container/ai-usage flex flex-col gap-5">
+ <div className="flex flex-wrap items-end justify-between gap-4">
+ <div className="flex flex-col gap-1">
+ <h2 className="text-xl font-semibold">AI Usage</h2>
+ <p className="text-sm text-muted-foreground">
+ Tokens, response times and failures across your providers and
+ models.
+ </p>
+ </div>
+ <div
+ role="group"
+ aria-label="Date range"
+ className="flex gap-0.5 rounded-md bg-muted p-1"
+ >
+ {RANGES.map((r) => (
+ <button
+ key={r}
+ type="button"
+ aria-pressed={range === r}
+ onClick={() => setRange(r)}
+ className={cn(
+ "h-8 rounded px-3 text-[13px]",
+ range === r
+ ? "bg-background font-medium shadow-sm"
+ : "text-muted-foreground",
+ )}
+ >
+ {`${r} days`}
+ </button>
+ ))}
+ </div>
+ </div>
+
+ {loading && !summary && (
+ <div className="flex justify-center py-16">
+ <Loader2 className="h-5 w-5 animate-spin text-muted-foreground" />
+ </div>
+ )}
+ {failed && (
+ <p className="text-sm text-muted-foreground">
+ Couldn&apos;t load AI usage.
+ </p>
+ )}
+
+ {summary && !failed && (
+ <div className={cn("flex flex-col gap-5", loading && "opacity-60")}>
+ {summary.totals.calls === 0 ? (
+ <div className="rounded-lg border px-5 py-10 text-center text-sm text-muted-foreground">
+ {`No AI calls in the last ${summary.rangeDays} days.`}
+ </div>
+ ) : (
+ <>
+ <UsageSummaryCards
+ totals={summary.totals}
+ failuresByStatus={summary.failuresByStatus}
+ rangeDays={summary.rangeDays}
+ onShowFailures={() =>
+ failuresRef.current?.scrollIntoView({ behavior: "smooth" })
+ }
+ />
+ <DailyTokensChart
+ days={summary.days}
+ providers={summary.providers}
+ />
+ <ProviderModelTable providers={summary.providers} />
+ <div className="grid grid-cols-1 gap-4 @3xl/ai-usage:grid-cols-2">
+ <FeatureBreakdown features={summary.features} />
+ <FailuresCard
+ ref={failuresRef}
+ totals={summary.totals}
+ failuresByStatus={summary.failuresByStatus}
+ />
+ </div>
+ </>
+ )}
+ {summary.recent.length > 0 && (
+ <RecentCallsTable recent={summary.recent} />
+ )}
+ </div>
+ )}
+ </div>
+ );
+}
diff --git a/src/components/settings/SettingsSidebar.tsx b/src/components/settings/SettingsSidebar.tsx
index 0349388..b382c2b 100644
--- a/src/components/settings/SettingsSidebar.tsx
+++ b/src/components/settings/SettingsSidebar.tsx
@@ -1,10 +1,10 @@
"use client";
-import { Bot, Database, Key, Palette, Plug } from "lucide-react";
+import { BarChart3, Bot, Database, Key, Palette, Plug } from "lucide-react";
import { Button } from "../ui/button";
import { cn } from "@/lib/utils";
-export type SettingsSection = "ai-provider" | "api-keys" | "appearance" | "mcp-access" | "data";
+export type SettingsSection = "ai-provider" | "ai-usage" | "api-keys" | "appearance" | "mcp-access" | "data";
const SETTINGS_SECTIONS: {
id: SettingsSection;
@@ -12,6 +12,7 @@ const SETTINGS_SECTIONS: {
icon: typeof Bot;
}[] = [
{ id: "ai-provider", label: "AI Provider", icon: Bot },
+ { id: "ai-usage", label: "AI Usage", icon: BarChart3 },
{ id: "api-keys", label: "API Keys", icon: Key },
{ id: "appearance", label: "Appearance", icon: Palette },
{ id: "mcp-access", label: "MCP Access", icon: Plug },
diff --git a/src/components/settings/ai-usage-settings/DailyTokensChart.tsx b/src/components/settings/ai-usage-settings/DailyTokensChart.tsx
new file mode 100644
index 0000000..40bc634
--- /dev/null
+++ b/src/components/settings/ai-usage-settings/DailyTokensChart.tsx
@@ -0,0 +1,90 @@
+"use client";
+
+import { useMemo } from "react";
+import { useTheme } from "next-themes";
+import { ResponsiveBar } from "@nivo/bar";
+import { format, parseISO } from "date-fns";
+import type { AiUsageSummary } from "@/models/aiUsage.model";
+import {
+ FALLBACK_PROVIDER_COLOR,
+ PROVIDER_COLORS,
+ formatTokens,
+ providerLabel,
+} from "./format";
+
+export default function DailyTokensChart({
+ days,
+ providers,
+}: Pick<AiUsageSummary, "days" | "providers">) {
+ const { resolvedTheme } = useTheme();
+ const theme = resolvedTheme === "light" ? "light" : "dark";
+ const keys = providers.map((p) => p.provider);
+ const data = useMemo(
+ () => days.map((d) => ({ day: d.date, ...d.tokensByProvider })),
+ [days],
+ );
+ // About five labels whatever the range, always ending on today.
+ const step = Math.max(1, Math.round(days.length / 5));
+ const tickValues = days
+ .filter((_, i) => i % step === 0 || i === days.length - 1)
+ .map((d) => d.date);
+ const colorOf = (id: string) =>
+ PROVIDER_COLORS[theme][id] ?? FALLBACK_PROVIDER_COLOR;
+
+ return (
+ <section className="flex flex-col gap-4 rounded-lg border p-5">
+ <div className="flex flex-wrap items-center justify-between gap-2">
+ <h2 className="text-[15px] font-semibold">Daily tokens by provider</h2>
+ <div className="flex flex-wrap gap-4 text-xs text-muted-foreground">
+ {keys.map((key) => (
+ <span key={key} className="flex items-center gap-1.5">
+ <span
+ className="h-2.5 w-2.5 rounded-sm"
+ style={{ background: colorOf(key) }}
+ />
+ {providerLabel(key)}
+ </span>
+ ))}
+ </div>
+ </div>
+ <div className="h-[200px]">
+ <ResponsiveBar
+ data={data}
+ keys={keys}
+ indexBy="day"
+ groupMode="stacked"
+ margin={{ top: 8, right: 8, bottom: 28, left: 48 }}
+ padding={0.25}
+ colors={(bar) => colorOf(String(bar.id))}
+ enableLabel={false}
+ enableGridY
+ axisTop={null}
+ axisRight={null}
+ axisLeft={{
+ tickSize: 0,
+ tickPadding: 8,
+ tickValues: 4,
+ format: (v) => formatTokens(Number(v)),
+ }}
+ axisBottom={{
+ tickSize: 0,
+ tickPadding: 8,
+ tickValues,
+ format: (v: string) => format(parseISO(v), "MMM d"),
+ }}
+ valueFormat={(v) => formatTokens(v)}
+ tooltipLabel={(bar) =>
+ `${providerLabel(String(bar.id))} · ${format(parseISO(String(bar.indexValue)), "MMM d")}`
+ }
+ theme={{
+ text: { fill: "#94A3B8" },
+ grid: {
+ line: { stroke: theme === "dark" ? "#1E293B" : "#E2E8F0" },
+ },
+ tooltip: { container: { background: "#1E293B", color: "#FFFFFF" } },
+ }}
+ />
+ </div>
+ </section>
+ );
+}
diff --git a/src/components/settings/ai-usage-settings/FailuresCard.tsx b/src/components/settings/ai-usage-settings/FailuresCard.tsx
new file mode 100644
index 0000000..4443fe8
--- /dev/null
+++ b/src/components/settings/ai-usage-settings/FailuresCard.tsx
@@ -0,0 +1,53 @@
+import { forwardRef } from "react";
+import { AI_FAILURE_STATUSES, type AiUsageSummary } from "@/models/aiUsage.model";
+import { FAILURE_META } from "./format";
+
+const FailuresCard = forwardRef<
+ HTMLElement,
+ Pick<AiUsageSummary, "totals" | "failuresByStatus">
+>(function FailuresCard({ totals, failuresByStatus }, ref) {
+ return (
+ <section
+ ref={ref}
+ id="ai-usage-failures"
+ className="flex flex-col overflow-hidden rounded-lg border"
+ >
+ <div className="flex items-center justify-between border-b px-5 py-3.5">
+ <h2 className="text-[15px] font-semibold">Failures</h2>
+ <span className="text-xs text-muted-foreground">
+ {`${totals.failures.toLocaleString("en-US")} of ${totals.calls.toLocaleString("en-US")} calls`}
+ </span>
+ </div>
+ <div className="grow py-1.5">
+ {AI_FAILURE_STATUSES.map((status) => {
+ const meta = FAILURE_META[status];
+ return (
+ <div
+ key={status}
+ className="flex items-start gap-3 px-5 py-2.5 text-[13px]"
+ >
+ <span
+ className={`mt-1 h-2.5 w-2.5 shrink-0 rounded-sm ${meta.dotClassName}`}
+ />
+ <span className="flex grow flex-col gap-0.5">
+ <span className="font-medium">{meta.label}</span>
+ <span className="text-xs text-muted-foreground">
+ {meta.description}
+ </span>
+ </span>
+ <span className="w-8 text-right font-semibold tabular-nums">
+ {failuresByStatus[status]}
+ </span>
+ </div>
+ );
+ })}
+ </div>
+ <div className="flex justify-between border-t px-5 py-3 text-xs text-muted-foreground">
+ <span>Stopped by you — not counted as failures</span>
+ <span className="tabular-nums">{totals.stopped}</span>
+ </div>
+ </section>
+ );
+});
+
+export default FailuresCard;
diff --git a/src/components/settings/ai-usage-settings/FeatureBreakdown.tsx b/src/components/settings/ai-usage-settings/FeatureBreakdown.tsx
new file mode 100644
index 0000000..962045c
--- /dev/null
+++ b/src/components/settings/ai-usage-settings/FeatureBreakdown.tsx
@@ -0,0 +1,45 @@
+import { AI_USAGE_FEATURES, type AiUsageSummary } from "@/models/aiUsage.model";
+import { formatSeconds, formatTokens } from "./format";
+
+export default function FeatureBreakdown({
+ features,
+}: Pick<AiUsageSummary, "features">) {
+ const maxTokens = Math.max(1, ...features.map((f) => f.tokens));
+ return (
+ <section className="overflow-hidden rounded-lg border">
+ <div className="flex items-center justify-between border-b px-5 py-3.5">
+ <h2 className="text-[15px] font-semibold">By feature</h2>
+ <span className="text-xs text-muted-foreground">
+ Tokens · Calls · Median
+ </span>
+ </div>
+ <div className="py-1.5">
+ {features.map((f) => (
+ <div
+ key={f.feature}
+ className="flex items-center gap-2.5 px-5 py-2 text-[13px]"
+ >
+ <span className="w-[110px] shrink-0">
+ {AI_USAGE_FEATURES[f.feature] ?? f.feature}
+ </span>
+ <span className="block h-1.5 grow overflow-hidden rounded-full bg-muted">
+ <span
+ className="block h-1.5 bg-teal-500"
+ style={{ width: `${(f.tokens / maxTokens) * 100}%` }}
+ />
+ </span>
+ <span className="w-[52px] text-right font-medium tabular-nums">
+ {formatTokens(f.tokens)}
+ </span>
+ <span className="w-9 text-right tabular-nums text-muted-foreground">
+ {f.calls.toLocaleString("en-US")}
+ </span>
+ <span className="w-11 text-right tabular-nums text-muted-foreground">
+ {formatSeconds(f.medianMs)}
+ </span>
+ </div>
+ ))}
+ </div>
+ </section>
+ );
+}
diff --git a/src/components/settings/ai-usage-settings/ProviderModelTable.tsx b/src/components/settings/ai-usage-settings/ProviderModelTable.tsx
new file mode 100644
index 0000000..4e228d8
--- /dev/null
+++ b/src/components/settings/ai-usage-settings/ProviderModelTable.tsx
@@ -0,0 +1,122 @@
+"use client";
+
+import { useState } from "react";
+import { AlertTriangle, ChevronDown } from "lucide-react";
+import { cn } from "@/lib/utils";
+import type { AiUsageSummary } from "@/models/aiUsage.model";
+import { formatSeconds, formatTokens, providerLabel } from "./format";
+
+const NUM = "text-right tabular-nums";
+
+export default function ProviderModelTable({
+ providers,
+}: Pick<AiUsageSummary, "providers">) {
+ const [collapsed, setCollapsed] = useState<Set<string>>(new Set());
+ const maxTokens = Math.max(1, ...providers.map((p) => p.tokens));
+ const toggle = (provider: string) =>
+ setCollapsed((prev) => {
+ const next = new Set(prev);
+ if (next.has(provider)) next.delete(provider);
+ else next.add(provider);
+ return next;
+ });
+
+ return (
+ <section className="overflow-hidden rounded-lg border">
+ <div className="flex flex-wrap items-center justify-between gap-2 border-b px-5 py-3.5">
+ <h2 className="text-[15px] font-semibold">By provider and model</h2>
+ <span className="text-xs text-muted-foreground">
+ Per call · chat excludes the review, match or letter it started
+ </span>
+ </div>
+ <div className="overflow-x-auto">
+ <div className="min-w-[720px]">
+ <div className="flex items-center gap-2.5 border-b px-5 py-2.5 text-xs font-medium text-muted-foreground">
+ <span className="w-[204px]">Provider / model</span>
+ <span className="grow">Share of tokens</span>
+ <span className={cn("w-16", NUM)}>Tokens</span>
+ <span className={cn("w-12", NUM)}>Calls</span>
+ <span className={cn("w-16", NUM)}>Median</span>
+ <span className={cn("w-16", NUM)}>p95</span>
+ <span className={cn("w-20", NUM)}>First token</span>
+ </div>
+ {providers.map((p) => {
+ const open = !collapsed.has(p.provider);
+ return (
+ <div key={p.provider} className="border-b last:border-b-0">
+ <div className="flex items-center gap-2.5 px-5 py-2.5 text-[13px]">
+ <button
+ type="button"
+ onClick={() => toggle(p.provider)}
+ aria-expanded={open}
+ className="flex w-[204px] items-center gap-2.5 text-left font-semibold"
+ >
+ <ChevronDown
+ className={cn(
+ "h-3.5 w-3.5 text-muted-foreground transition-transform",
+ !open && "-rotate-90",
+ )}
+ />
+ {providerLabel(p.provider)}
+ </button>
+ <span className="block h-1.5 grow overflow-hidden rounded-full bg-muted">
+ <span
+ className="block h-1.5 bg-blue-500"
+ style={{ width: `${(p.tokens / maxTokens) * 100}%` }}
+ />
+ </span>
+ <span className={cn("w-16 font-medium", NUM)}>
+ {formatTokens(p.tokens)}
+ </span>
+ <span className={cn("w-12 text-muted-foreground", NUM)}>
+ {p.calls.toLocaleString("en-US")}
+ </span>
+ <span className="w-16" />
+ <span className="w-16" />
+ <span className="w-20" />
+ </div>
+ {open &&
+ p.models.map((m) => (
+ <div
+ key={m.model}
+ className="flex items-center gap-2.5 pb-2.5 pl-11 pr-5 text-xs text-muted-foreground"
+ >
+ <span
+ className="w-[180px] truncate font-mono text-foreground/80"
+ title={m.model}
+ >
+ {m.model}
+ </span>
+ <span className="flex grow">
+ {m.nearContextLimit > 0 && (
+ <span className="inline-flex h-[22px] items-center gap-1.5 rounded-full bg-amber-100 px-2 text-[11px] font-medium text-amber-800 dark:bg-amber-950 dark:text-amber-400">
+ <AlertTriangle className="h-3 w-3" />
+ {`${m.nearContextLimit} ${m.nearContextLimit === 1 ? "call" : "calls"} near context limit`}
+ </span>
+ )}
+ </span>
+ <span className={cn("w-16", NUM)}>
+ {formatTokens(m.tokens)}
+ </span>
+ <span className={cn("w-12", NUM)}>
+ {m.calls.toLocaleString("en-US")}
+ </span>
+ <span className={cn("w-16", NUM)}>
+ {formatSeconds(m.medianMs)}
+ </span>
+ <span className={cn("w-16", NUM)}>
+ {formatSeconds(m.p95Ms)}
+ </span>
+ <span className={cn("w-20", NUM)}>
+ {formatSeconds(m.medianFirstTokenMs)}
+ </span>
+ </div>
+ ))}
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ </section>
+ );
+}
diff --git a/src/components/settings/ai-usage-settings/RecentCallsTable.tsx b/src/components/settings/ai-usage-settings/RecentCallsTable.tsx
new file mode 100644
index 0000000..63b03b7
--- /dev/null
+++ b/src/components/settings/ai-usage-settings/RecentCallsTable.tsx
@@ -0,0 +1,82 @@
+import { cn } from "@/lib/utils";
+import { AI_USAGE_CONSTANTS } from "@/lib/constants";
+import { AI_USAGE_FEATURES, type AiCallRow } from "@/models/aiUsage.model";
+import {
+ STATUS_META,
+ formatCallTime,
+ formatCount,
+ formatSeconds,
+} from "./format";
+
+const NUM = "text-right tabular-nums";
+
+export default function RecentCallsTable({ recent }: { recent: AiCallRow[] }) {
+ return (
+ <section className="overflow-hidden rounded-lg border">
+ <div className="flex items-center justify-between border-b px-5 py-3.5">
+ <h2 className="text-[15px] font-semibold">Recent calls</h2>
+ <span className="text-xs text-muted-foreground">
+ {`Last ${AI_USAGE_CONSTANTS.RECENT_LIMIT} · kept for ${AI_USAGE_CONSTANTS.RETENTION_DAYS} days`}
+ </span>
+ </div>
+ <div className="overflow-x-auto">
+ <div className="min-w-[760px]">
+ <div className="flex items-center gap-3 border-b px-5 py-2.5 text-xs font-medium text-muted-foreground">
+ <span className="w-[104px]">Time</span>
+ <span className="w-[110px]">Feature</span>
+ <span className="grow">Model</span>
+ <span className={cn("w-[60px]", NUM)}>Input</span>
+ <span className={cn("w-[60px]", NUM)}>Output</span>
+ <span className={cn("w-[68px]", NUM)}>Duration</span>
+ <span className={cn("w-20", NUM)}>First token</span>
+ <span className="w-24 text-right">Status</span>
+ </div>
+ {recent.map((r) => {
+ const status = STATUS_META[r.status];
+ return (
+ <div
+ key={r.id}
+ className="flex h-10 items-center gap-3 border-b px-5 text-[13px] last:border-b-0"
+ >
+ <span className="w-[104px] tabular-nums text-muted-foreground">
+ {formatCallTime(new Date(r.startedAt))}
+ </span>
+ <span className="w-[110px]">
+ {AI_USAGE_FEATURES[r.feature] ?? r.feature}
+ </span>
+ <span
+ className="grow truncate font-mono text-xs text-foreground/80"
+ title={r.model}
+ >
+ {r.model}
+ </span>
+ <span className={cn("w-[60px]", NUM)}>
+ {formatCount(r.inputTokens)}
+ </span>
+ <span className={cn("w-[60px]", NUM)}>
+ {formatCount(r.outputTokens)}
+ </span>
+ <span className={cn("w-[68px]", NUM)}>
+ {formatSeconds(r.durationMs)}
+ </span>
+ <span className={cn("w-20 text-muted-foreground", NUM)}>
+ {formatSeconds(r.firstTokenMs)}
+ </span>
+ <span className="flex w-24 justify-end">
+ <span
+ className={cn(
+ "inline-flex h-[22px] items-center rounded-full px-2 text-[11px] font-medium",
+ status.className,
+ )}
+ >
+ {status.label}
+ </span>
+ </span>
+ </div>
+ );
+ })}
+ </div>
+ </div>
+ </section>
+ );
+}
diff --git a/src/components/settings/ai-usage-settings/UsageSummaryCards.tsx b/src/components/settings/ai-usage-settings/UsageSummaryCards.tsx
new file mode 100644
index 0000000..a5c26e1
--- /dev/null
+++ b/src/components/settings/ai-usage-settings/UsageSummaryCards.tsx
@@ -0,0 +1,92 @@
+import { cn } from "@/lib/utils";
+import type { AiUsageSummary } from "@/models/aiUsage.model";
+import { formatChange, formatSeconds, formatTokens } from "./format";
+
+function StatCard({
+ label,
+ value,
+ children,
+}: {
+ label: string;
+ value: string;
+ children: React.ReactNode;
+}) {
+ return (
+ <div className="flex flex-col gap-1.5 rounded-lg border px-5 py-4">
+ <div className="text-[13px] font-medium text-muted-foreground">
+ {label}
+ </div>
+ <div className="text-[26px] font-semibold tracking-tight">{value}</div>
+ {children}
+ </div>
+ );
+}
+
+export default function UsageSummaryCards({
+ totals,
+ failuresByStatus,
+ rangeDays,
+ onShowFailures,
+}: Pick<AiUsageSummary, "totals" | "failuresByStatus" | "rangeDays"> & {
+ onShowFailures: () => void;
+}) {
+ const change = formatChange(totals.calls, totals.previousCalls);
+ const errorRate =
+ totals.calls === 0 ? 0 : (totals.failures / totals.calls) * 100;
+ const f = failuresByStatus;
+ return (
+ <div className="grid grid-cols-1 gap-4 @xl/ai-usage:grid-cols-2 @3xl/ai-usage:grid-cols-4">
+ <StatCard
+ label="Total tokens"
+ value={formatTokens(totals.inputTokens + totals.outputTokens)}
+ >
+ <div className="text-xs text-muted-foreground">
+ {`${(totals.inputTokens / 1_000_000).toFixed(2)}M input · ${(totals.outputTokens / 1_000_000).toFixed(2)}M output`}
+ </div>
+ </StatCard>
+ <StatCard label="API calls" value={totals.calls.toLocaleString("en-US")}>
+ {change && (
+ <div
+ className={cn(
+ "text-xs",
+ change.up
+ ? "text-green-600 dark:text-green-400"
+ : "text-muted-foreground",
+ )}
+ >
+ {`${change.text} vs previous ${rangeDays} days`}
+ </div>
+ )}
+ <div className="text-xs text-muted-foreground">
+ A chat turn counts as one call
+ </div>
+ </StatCard>
+ <StatCard
+ label="Median response time"
+ value={formatSeconds(totals.medianMs)}
+ >
+ <div className="text-xs text-muted-foreground">
+ {`p95 ${formatSeconds(totals.p95Ms)}`}
+ </div>
+ <div className="text-xs text-muted-foreground">
+ {`First token ${formatSeconds(totals.medianFirstTokenMs)} (streamed features)`}
+ </div>
+ </StatCard>
+ <StatCard
+ label="Failed calls"
+ value={totals.failures.toLocaleString("en-US")}
+ >
+ <div className="text-xs text-muted-foreground">
+ {`${errorRate.toFixed(1)}% error rate`}
+ </div>
+ <button
+ type="button"
+ onClick={onShowFailures}
+ className="w-fit text-left text-xs text-primary hover:underline"
+ >
+ {`${f.error} error · ${f.truncated} truncated · ${f.interrupted} interrupted · ${f.timed_out} timed out`}
+ </button>
+ </StatCard>
+ </div>
+ );
+}
diff --git a/src/components/settings/ai-usage-settings/format.ts b/src/components/settings/ai-usage-settings/format.ts
new file mode 100644
index 0000000..5bd140a
--- /dev/null
+++ b/src/components/settings/ai-usage-settings/format.ts
@@ -0,0 +1,128 @@
+import { format } from "date-fns";
+import {
+ AI_PROVIDER_LABELS,
+ type AiCallStatus,
+ type AiFailureStatus,
+} from "@/models/aiUsage.model";
+
+export function formatTokens(n: number): string {
+ // 999,600 would round to "1000K"; switch to M before that happens.
+ if (n >= 999_500) return `${(n / 1_000_000).toFixed(2)}M`;
+ if (n >= 1_000) return `${Math.round(n / 1_000)}K`;
+ return String(n);
+}
+
+export function formatCount(n: number | null): string {
+ return n === null ? "—" : n.toLocaleString("en-US");
+}
+
+export function formatSeconds(ms: number | null): string {
+ return ms === null ? "—" : `${(ms / 1000).toFixed(1)}s`;
+}
+
+// Compares against the passed now, not date-fns' isToday, which reads the
+// real clock and so can't be tested.
+export function formatCallTime(date: Date, now: Date = new Date()): string {
+ const time = format(date, "HH:mm");
+ if (format(now, "yyyy-MM-dd") === format(date, "yyyy-MM-dd")) {
+ return `Today ${time}`;
+ }
+ const yesterday = new Date(now);
+ yesterday.setDate(now.getDate() - 1);
+ if (format(yesterday, "yyyy-MM-dd") === format(date, "yyyy-MM-dd")) {
+ return `Yesterday ${time}`;
+ }
+ return format(date, "MMM d HH:mm");
+}
+
+export function formatChange(
+ calls: number,
+ previous: number,
+): { text: string; up: boolean } | null {
+ if (previous === 0) return null;
+ const pct = Math.round(((calls - previous) / previous) * 100);
+ return { text: `${pct > 0 ? "+" : ""}${pct}%`, up: pct > 0 };
+}
+
+export function providerLabel(provider: string): string {
+ return AI_PROVIDER_LABELS[provider] ?? provider;
+}
+
+// Hand-picked like the dashboard charts: dark values are the design's.
+export const PROVIDER_COLORS: Record<
+ "light" | "dark",
+ Record<string, string>
+> = {
+ dark: {
+ ollama: "#60A5FA",
+ deepseek: "#F59E0B",
+ openai: "#14B8A6",
+ gemini: "#C4B5FD",
+ openrouter: "#F472B6",
+ },
+ light: {
+ ollama: "#2563EB",
+ deepseek: "#D97706",
+ openai: "#0D9488",
+ gemini: "#7C3AED",
+ openrouter: "#DB2777",
+ },
+};
+
+export const FALLBACK_PROVIDER_COLOR = "#94A3B8";
+
+export const STATUS_META: Record<
+ AiCallStatus,
+ { label: string; className: string }
+> = {
+ ok: {
+ label: "OK",
+ className:
+ "bg-green-100 text-green-800 dark:bg-green-950 dark:text-green-400",
+ },
+ truncated: {
+ label: "Truncated",
+ className:
+ "bg-amber-100 text-amber-800 dark:bg-amber-950 dark:text-amber-400",
+ },
+ error: {
+ label: "Error",
+ className: "bg-red-100 text-red-800 dark:bg-red-950 dark:text-red-300",
+ },
+ timed_out: {
+ label: "Timed out",
+ className:
+ "bg-orange-100 text-orange-800 dark:bg-orange-950 dark:text-orange-300",
+ },
+ interrupted: {
+ label: "Interrupted",
+ className: "bg-muted text-muted-foreground",
+ },
+ stopped: { label: "Stopped", className: "bg-muted text-muted-foreground" },
+};
+
+export const FAILURE_META: Record<
+ AiFailureStatus,
+ { label: string; description: string; dotClassName: string }
+> = {
+ error: {
+ label: "Provider error",
+ description: "Unreachable, rejected key or rate limit",
+ dotClassName: "bg-red-400",
+ },
+ timed_out: {
+ label: "Timed out",
+ description: "Hit the time limit before finishing",
+ dotClassName: "bg-orange-400",
+ },
+ truncated: {
+ label: "Truncated",
+ description: "Hit the output limit before finishing",
+ dotClassName: "bg-amber-400",
+ },
+ interrupted: {
+ label: "Interrupted",
+ description: "Stream ended early with no error",
+ dotClassName: "bg-slate-400",
+ },
+};