Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(dashboard): rename Usage to Analytics with Usage / Errors tabs, rework filters and freshness (MUL-5759) (#6508)

Naiyuan Qing364462c4b8f4
diff --git a/packages/core/dashboard/queries.ts b/packages/core/dashboard/queries.ts
index fc95723a60..ca06ede433 100644
--- a/packages/core/dashboard/queries.ts
+++ b/packages/core/dashboard/queries.ts
@@ -42,8 +42,13 @@ export const dashboardKeys = {
[...dashboardKeys.all(wsId), "failures-by-agent", days, projectId, tz] as const,
};
-// 5-min rollup cadence on the server, 60s background refetch on the client.
+// The server materializes these rollups on a 5-minute cadence, so a mounted
+// dashboard re-polls on that same cadence — polling faster would only re-read
+// an unchanged rollup. The short staleTime keeps re-entering the page honest:
+// anything older than a minute refetches on mount instead of waiting out the
+// interval. Neither fires for unmounted queries or backgrounded windows.
const STALE_TIME = 60 * 1000;
+const REFETCH_INTERVAL = 5 * 60 * 1000;
// Range changes should keep the previous result mounted so KPI cards and
// charts transition in place instead of falling back to a full-page skeleton.
@@ -80,6 +85,7 @@ export function dashboardUsageDailyOptions(
}),
enabled: !!wsId,
staleTime: STALE_TIME,
+ refetchInterval: REFETCH_INTERVAL,
placeholderData: (previousData, previousQuery) =>
isSameDashboardScope(previousQuery?.queryKey, queryKey)
? keepPreviousData(previousData)
@@ -104,6 +110,7 @@ export function dashboardUsageByAgentOptions(
}),
enabled: !!wsId,
staleTime: STALE_TIME,
+ refetchInterval: REFETCH_INTERVAL,
placeholderData: (previousData, previousQuery) =>
isSameDashboardScope(previousQuery?.queryKey, queryKey)
? keepPreviousData(previousData)
@@ -128,6 +135,7 @@ export function dashboardAgentRunTimeOptions(
}),
enabled: !!wsId,
staleTime: STALE_TIME,
+ refetchInterval: REFETCH_INTERVAL,
placeholderData: (previousData, previousQuery) =>
isSameDashboardScope(previousQuery?.queryKey, queryKey)
? keepPreviousData(previousData)
@@ -152,6 +160,7 @@ export function dashboardRunTimeDailyOptions(
}),
enabled: !!wsId,
staleTime: STALE_TIME,
+ refetchInterval: REFETCH_INTERVAL,
placeholderData: (previousData, previousQuery) =>
isSameDashboardScope(previousQuery?.queryKey, queryKey)
? keepPreviousData(previousData)
@@ -176,6 +185,7 @@ export function dashboardFailuresDailyOptions(
}),
enabled: !!wsId,
staleTime: STALE_TIME,
+ refetchInterval: REFETCH_INTERVAL,
placeholderData: (previousData, previousQuery) =>
isSameDashboardScope(previousQuery?.queryKey, queryKey)
? keepPreviousData(previousData)
@@ -200,6 +210,7 @@ export function dashboardFailuresByAgentOptions(
}),
enabled: !!wsId,
staleTime: STALE_TIME,
+ refetchInterval: REFETCH_INTERVAL,
placeholderData: (previousData, previousQuery) =>
isSameDashboardScope(previousQuery?.queryKey, queryKey)
? keepPreviousData(previousData)
diff --git a/packages/views/dashboard/components/dashboard-filters.tsx b/packages/views/dashboard/components/dashboard-filters.tsx
new file mode 100644
index 0000000000..9c88449b03
--- /dev/null
+++ b/packages/views/dashboard/components/dashboard-filters.tsx
@@ -0,0 +1,145 @@
+"use client";
+
+import { CalendarDays, ChevronDown, FolderKanban } from "lucide-react";
+import { Button } from "@multica/ui/components/ui/button";
+import {
+ DropdownMenu,
+ DropdownMenuTrigger,
+ DropdownMenuContent,
+ DropdownMenuRadioGroup,
+ DropdownMenuRadioItem,
+} from "@multica/ui/components/ui/dropdown-menu";
+import { ProjectIcon } from "../../projects/components/project-icon";
+import { useT } from "../../i18n";
+import { ALL_PROJECTS, TIME_RANGES, type TimeRange } from "./dashboard-shared";
+
+type DashboardProject = { id: string; title: string; icon: string | null };
+
+/**
+ * Page-scoped time range.
+ *
+ * A button that states the current value plus a single-select menu, rather
+ * than five permanently-expanded segments. The five segments were the widest
+ * thing in the header and the least informative: the value they encode is
+ * already repeated in every KPI label ("Cost · 30D"). Collapsing them costs one
+ * click per change and buys the header back.
+ *
+ * No "clear" entry: the range is a required parameter of every query on the
+ * page, so it has no empty value to return to.
+ */
+export function TimeRangeFilter({
+ days,
+ onChange,
+}: {
+ days: TimeRange;
+ onChange: (days: TimeRange) => void;
+}) {
+ const { t } = useT("usage");
+ const current = TIME_RANGES.find((r) => r.days === days) ?? TIME_RANGES[2];
+
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <Button
+ variant="outline"
+ size="sm"
+ aria-label={t(($) => $.filter.period_label)}
+ className="gap-1 px-2.5"
+ >
+ <CalendarDays className="size-3.5 text-muted-foreground" />
+ <span className="tabular-nums">{current.label}</span>
+ <ChevronDown className="size-3 text-muted-foreground" />
+ </Button>
+ }
+ />
+ <DropdownMenuContent align="end" className="w-auto min-w-32">
+ <DropdownMenuRadioGroup
+ value={String(days)}
+ onValueChange={(value) => onChange(Number(value) as TimeRange)}
+ >
+ {TIME_RANGES.map((range) => (
+ <DropdownMenuRadioItem
+ key={range.days}
+ value={String(range.days)}
+ className="tabular-nums"
+ >
+ {range.label}
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
+
+/**
+ * Page-scoped project filter.
+ *
+ * A single-level dropdown, deliberately not a generic "Filter" menu: with one
+ * dimension, a wrapper menu only hides what is filterable behind an extra
+ * hover. The trigger states the current value like `TimeRangeFilter` does:
+ * a neutral outline throughout, showing the selected project's own icon and
+ * name once narrowed — the named value is the active-state signal, no filled
+ * tier. If a second dimension ships (agent, model, runtime), fold this back
+ * into a combined menu in the `IssueDisplayControls` grammar.
+ */
+export function ProjectFilter({
+ projects,
+ projectValue,
+ onProjectChange,
+}: {
+ projects: DashboardProject[];
+ projectValue: string;
+ onProjectChange: (value: string) => void;
+}) {
+ const { t } = useT("usage");
+ const allLabel = t(($) => $.filter.all_projects);
+ // A project id that no longer resolves (deleted project, or a stale id left
+ // over from another workspace) counts as no filter — the same reading the
+ // page applies when it derives the effective `projectId` for the queries, so
+ // the chip cannot claim a filter the data is not actually narrowed by.
+ const selected = projects.find((p) => p.id === projectValue);
+
+ return (
+ <DropdownMenu>
+ <DropdownMenuTrigger
+ render={
+ <Button
+ variant="outline"
+ size="sm"
+ aria-label={t(($) => $.filter.project_label)}
+ className={selected ? "gap-1 px-2.5" : "gap-1 px-2.5 text-muted-foreground"}
+ >
+ {selected ? (
+ <ProjectIcon project={selected} size="sm" />
+ ) : (
+ <FolderKanban className="size-3.5" />
+ )}
+ <span className="max-w-40 truncate">
+ {selected ? selected.title : allLabel}
+ </span>
+ <ChevronDown className="size-3 text-muted-foreground" />
+ </Button>
+ }
+ />
+ <DropdownMenuContent align="end" className="max-h-72 w-auto min-w-52">
+ <DropdownMenuRadioGroup
+ value={projectValue}
+ onValueChange={(value) => onProjectChange(value ?? ALL_PROJECTS)}
+ >
+ <DropdownMenuRadioItem value={ALL_PROJECTS}>
+ <FolderKanban className="size-3.5 shrink-0 text-muted-foreground" />
+ <span className="truncate">{allLabel}</span>
+ </DropdownMenuRadioItem>
+ {projects.map((project) => (
+ <DropdownMenuRadioItem key={project.id} value={project.id}>
+ <ProjectIcon project={project} size="sm" />
+ <span className="truncate">{project.title}</span>
+ </DropdownMenuRadioItem>
+ ))}
+ </DropdownMenuRadioGroup>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ );
+}
diff --git a/packages/views/dashboard/components/dashboard-page.test.tsx b/packages/views/dashboard/components/dashboard-page.test.tsx
index 4ce28a5b59..bc817a67b1 100644
--- a/packages/views/dashboard/components/dashboard-page.test.tsx
+++ b/packages/views/dashboard/components/dashboard-page.test.tsx
@@ -1,3 +1,4 @@
+import { useMemo, useState } from "react";
import { describe, it, expect, afterEach, beforeEach, vi } from "vitest";
import { cleanup, screen, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
@@ -63,6 +64,9 @@ vi.mock("@tanstack/react-query", async () => {
);
return {
...actual,
+ // The page reads the client only to invalidate the dashboard keys from
+ // the refresh button; there is no provider in these renders.
+ useQueryClient: () => ({ invalidateQueries: vi.fn() }),
useQuery: (opts: { queryKey: unknown[] }) => {
queryKeys.push(opts.queryKey);
if (dashboardDataRef.current) {
@@ -244,33 +248,57 @@ vi.mock("@multica/core/runtimes/custom-pricing-store", () => {
import { DashboardPage } from "./dashboard-page";
-// A minimal adapter — the Errors breakdown's drill-down renders an <AppLink>,
-// which reads the navigation context. Asserting on the rendered href (rather
-// than a push spy) keeps the test on the contract that matters: the row points
-// at the agent's Overview, whose ActivityTab lists its runs and each failure's
-// reason.
-const navAdapter: NavigationAdapter = {
- push: vi.fn(),
- replace: vi.fn(),
- back: vi.fn(),
- pathname: "/acme/usage",
- searchParams: new URLSearchParams(),
- getShareableUrl: (path: string) => `https://example.test${path}`,
-};
-
-function renderDashboard() {
- return renderWithI18n(
- <NavigationProvider value={navAdapter}>
+const replaceSpy = vi.fn();
+
+/**
+ * A navigation adapter that actually holds the query string, because the tab
+ * IS the URL: the page reads `?tab=` and writes it back through `replace`. A
+ * spy-only adapter would swallow the write and the tab could never change,
+ * which would make every Errors assertion below test a screen the user cannot
+ * reach.
+ *
+ * The adapter also backs the offender drill-down's <AppLink>. Asserting on the
+ * rendered href (rather than a push spy) keeps that test on the contract that
+ * matters: the row points at the agent's Overview, whose ActivityTab lists its
+ * runs and each failure's reason.
+ */
+function DashboardHarness({ initialSearch = "" }: { initialSearch?: string }) {
+ const [search, setSearch] = useState(initialSearch);
+ const adapter = useMemo<NavigationAdapter>(
+ () => ({
+ push: vi.fn(),
+ replace: (path: string) => {
+ replaceSpy(path);
+ setSearch(path.split("?")[1] ?? "");
+ },
+ back: vi.fn(),
+ pathname: "/acme/usage",
+ searchParams: new URLSearchParams(search),
+ getShareableUrl: (path: string) => `https://example.test${path}`,
+ }),
+ [search],
+ );
+ return (
+ <NavigationProvider value={adapter}>
<DashboardPage />
- </NavigationProvider>,
+ </NavigationProvider>
);
}
-// The Top offenders section — the sort control and column headers sit beside
-// the list, not inside it.
-function offenderCard(): HTMLElement {
- return screen.getByRole("list", { name: "Top offenders" })
- .parentElement as HTMLElement;
+function renderDashboard(initialSearch = "") {
+ return renderWithI18n(<DashboardHarness initialSearch={initialSearch} />);
+}
+
+/** Everything about failures now lives behind its own tab, so a test that
+ * wants it has to go there first — exactly as a reader does. */
+async function openErrorsTab(user: ReturnType<typeof userEvent.setup>) {
+ await user.click(screen.getByRole("tab", { name: /Errors/ }));
+}
+
+// The offender ranking control. Named rather than reached through the DOM
+// tree so it survives the card's internal layout changing.
+function offenderSort(): HTMLElement {
+ return screen.getByRole("group", { name: "Rank offenders by" });
}
// The filled part of one offender row's bar. `role="img"` is on the fill (it
@@ -300,7 +328,7 @@ describe("DashboardPage — viewing timezone drives the query key", () => {
it("uses the stored timezone in every dashboard query key", () => {
tzRef.current = "UTC";
- renderWithI18n(<DashboardPage />);
+ renderDashboard();
const tzs = tzSegments();
expect(tzs.length).toBeGreaterThan(0);
@@ -309,14 +337,14 @@ describe("DashboardPage — viewing timezone drives the query key", () => {
it("flips the query key when the stored timezone changes", () => {
tzRef.current = "UTC";
- renderWithI18n(<DashboardPage />);
+ renderDashboard();
const utcKeys = queryKeys.filter((k) => k[0] === "dashboard");
queryKeys.length = 0;
cleanup();
tzRef.current = "Asia/Tokyo";
- renderWithI18n(<DashboardPage />);
+ renderDashboard();
const tokyoKeys = queryKeys.filter((k) => k[0] === "dashboard");
expect(utcKeys.length).toBe(tokyoKeys.length);
@@ -358,24 +386,31 @@ describe("DashboardPage — failure visibility", () => {
queryKeys.length = 0;
dashboardDataRef.current = true;
tzRef.current = "UTC";
+ replaceSpy.mockClear();
cleanup();
});
- it("states the error rate with its denominator spelled out", () => {
- // The run-time rollup sees 1 failure out of 12 tasks — it only counts
- // tasks that actually started. The failure rollup also sees tasks that
- // never started, so it reports 4 out of 10. The Errors card quotes the
- // latter *with* its denominator, which is what keeps it from reading as
- // a contradiction of the Tasks tile above.
+ it("states the error rate with its denominator spelled out", async () => {
+ const user = userEvent.setup();
renderDashboard();
- expect(screen.getByText("4 of 10 runs failed · 40%")).toBeInTheDocument();
- // The Tasks tile keeps its own started-tasks-only figure.
+ // The Tasks tile on the Usage tab keeps its own started-tasks-only figure.
expect(screen.getByText("1 failed")).toBeInTheDocument();
+
+ await openErrorsTab(user);
+
+ // The run-time rollup sees 1 failure out of 12 tasks — it only counts
+ // tasks that actually started. The failure rollup also sees tasks that
+ // never started, so it reports 4 out of 10. The rate tile quotes the
+ // latter *with* its denominator, which is what keeps it from reading as a
+ // contradiction of the Tasks tile on the other tab.
+ expect(screen.getByText("4 of 10 runs failed · 40%")).toBeInTheDocument();
});
- it("breaks failures down by class and links the offending agent to its runs", () => {
+ it("breaks failures down by class and links the offending agent to its runs", async () => {
+ const user = userEvent.setup();
renderDashboard();
+ await openErrorsTab(user);
// Auth (3) outranks Timeout (1), and both are named by class rather than
// by the raw failure_reason enum.
@@ -384,7 +419,7 @@ describe("DashboardPage — failure visibility", () => {
"Auth3",
"Timeout1",
]);
- // The section names its own denominator: the header above it quotes a
+ // The section names its own denominator: the rate tile above quotes a
// rate over all 10 runs, this one splits the 4 failures.
expect(screen.getByText("Failure mix · 4")).toBeInTheDocument();
@@ -408,6 +443,7 @@ describe("DashboardPage — failure visibility", () => {
it("moves the bar onto whichever metric the list is ranked by", async () => {
const user = userEvent.setup();
renderDashboard();
+ await openErrorsTab(user);
// Agent One failed 4 of 10; the anonymous bucket failed 2 of 2. Under
// Failures the bucket is half the leader's bar. Under Rate it is 100% —
@@ -415,7 +451,7 @@ describe("DashboardPage — failure visibility", () => {
// exactly the mismatch this control exists to remove.
expect(offenderBar(1).style.width).toBe("50%");
- await user.click(within(offenderCard()).getByRole("button", { name: "Rate" }));
+ await user.click(within(offenderSort()).getByRole("button", { name: "Rate" }));
expect(offenderBar(1).style.width).toBe("100%");
});
@@ -423,11 +459,12 @@ describe("DashboardPage — failure visibility", () => {
it("says which metric the list is ranked by without relying on colour", async () => {
const user = userEvent.setup();
renderDashboard();
+ await openErrorsTab(user);
// The active option used to be a colour swap and nothing else, which is
// invisible to a screen reader. The group is named too — "Rate, pressed"
// means nothing until you know the group ranks the offender list.
- const group = screen.getByRole("group", { name: "Rank offenders by" });
+ const group = offenderSort();
expect(
within(group).getByRole("button", { name: "Failures" }),
).toHaveAttribute("aria-pressed", "true");
@@ -447,8 +484,9 @@ describe("DashboardPage — failure visibility", () => {
it("keeps a two-run agent from hijacking the rate ranking", async () => {
const user = userEvent.setup();
renderDashboard();
+ await openErrorsTab(user);
- await user.click(within(offenderCard()).getByRole("button", { name: "Rate" }));
+ await user.click(within(offenderSort()).getByRole("button", { name: "Rate" }));
// 2/2 is a 100% rate and 4/10 is 40%, but two runs is not evidence. The
// small-sample row is demoted, not dropped — the list still has to
@@ -463,6 +501,7 @@ describe("DashboardPage — failure visibility", () => {
it("reveals the raw failure_reason values behind the class summary", async () => {
const user = userEvent.setup();
renderDashboard();
+ await openErrorsTab(user);
expect(
screen.queryByText("agent_error.provider_auth_or_access"),
@@ -477,11 +516,20 @@ describe("DashboardPage — failure visibility", () => {
).toBeInTheDocument();
});
- it("adds Errors to the trend toggle without disturbing the other metrics", async () => {
+ it("gives failures their own chart instead of a slot on the spend toggle", async () => {
const user = userEvent.setup();
const { container } = renderDashboard();
- await user.click(screen.getByRole("button", { name: "Errors" }));
+ // Charting failures used to mean hiding spend: Errors was the fifth option
+ // of the single trend toggle, so "what did it cost" and "what broke" could
+ // not be on screen in the same breath.
+ const metrics = within(screen.getByRole("group", { name: "Metric" }));
+ expect(
+ metrics.queryByRole("button", { name: "Errors" }),
+ ).not.toBeInTheDocument();
+ expect(metrics.getByRole("button", { name: "Tokens" })).toBeInTheDocument();
+
+ await openErrorsTab(user);
expect(container).toHaveTextContent("Daily errors");
});
@@ -492,15 +540,18 @@ describe("DashboardPage — the Errors list never exposes an agent the viewer ca
queryKeys.length = 0;
dashboardDataRef.current = true;
tzRef.current = "UTC";
+ replaceSpy.mockClear();
cleanup();
});
- it("folds an unresolvable agent into an anonymous row instead of printing its UUID", () => {
+ it("folds an unresolvable agent into an anonymous row instead of printing its UUID", async () => {
// The failure rollups are workspace-scoped and deliberately skip
// per-agent visibility, but the agent list does not: a private agent
// this member can't see never appears there. Rendering `row.agentId`
// would leak its existence, failure count and failure rate.
+ const user = userEvent.setup();
const { container } = renderDashboard();
+ await openErrorsTab(user);
expect(container).not.toHaveTextContent("0f9d1c2e-private-agent-uuid");
@@ -513,35 +564,68 @@ describe("DashboardPage — the Errors list never exposes an agent the viewer ca
});
});
-describe("DashboardPage — Errors card placement and density", () => {
+// The page answers two questions — "what did this cost" and "what broke" —
+// and used to answer both on one scroll, where the failure breakdown sat
+// below a leaderboard that can itself run to thirty rows (MUL-5759).
+describe("DashboardPage — the two questions are separate tabs", () => {
beforeEach(() => {
queryKeys.length = 0;
dashboardDataRef.current = true;
manyAgentsRef.current = false;
tzRef.current = "UTC";
+ replaceSpy.mockClear();
cleanup();
});
- it("renders the Errors card after the leaderboard, at the bottom of the page", () => {
- // Spend is the headline; failures are the follow-up question you ask
- // after seeing who is spending. Asserting document order rather than a
- // class name keeps this about the reading sequence.
+ it("keeps failures off the Usage tab and reaches them in one click", async () => {
+ const user = userEvent.setup();
renderDashboard();
- // By heading, not by text: "Errors" also names the trend-chart toggle.
- const leaderboard = screen.getByRole("heading", { name: "Leaderboard" });
- const errors = screen.getByRole("heading", { name: "Errors" });
+ expect(
+ screen.queryByRole("list", { name: "Top offenders" }),
+ ).not.toBeInTheDocument();
+ expect(screen.getByRole("list", { name: "Leaderboard" })).toBeInTheDocument();
+
+ await openErrorsTab(user);
+ expect(screen.getByRole("list", { name: "Top offenders" })).toBeInTheDocument();
+ // The two per-agent rankings had near-identical shapes and used to stack
+ // one above the other; each now belongs to the question it answers.
expect(
- leaderboard.compareDocumentPosition(errors) &
- Node.DOCUMENT_POSITION_FOLLOWING,
- ).toBeTruthy();
+ screen.queryByRole("list", { name: "Leaderboard" }),
+ ).not.toBeInTheDocument();
+ });
+
+ it("puts the tab in the URL so an Errors view can be linked", async () => {
+ const user = userEvent.setup();
+ renderDashboard();
+
+ await openErrorsTab(user);
+ expect(replaceSpy).toHaveBeenLastCalledWith("/acme/usage?tab=errors");
+
+ // Returning to the default view drops the param instead of pinning
+ // ?tab=usage onto every link out of this page.
+ await user.click(screen.getByRole("tab", { name: "Usage" }));
+ expect(replaceSpy).toHaveBeenLastCalledWith("/acme/usage");
+ });
+
+ it("opens straight onto Errors when the URL asks for it", () => {
+ renderDashboard("tab=errors");
+
+ expect(screen.getByRole("list", { name: "Top offenders" })).toBeInTheDocument();
+ });
+
+ it("falls back to Usage for a tab value it does not recognise", () => {
+ renderDashboard("tab=nonsense");
+
+ expect(screen.getByRole("list", { name: "Leaderboard" })).toBeInTheDocument();
});
it("caps the offender list and expands it on demand", async () => {
manyAgentsRef.current = true;
const user = userEvent.setup();
renderDashboard();
+ await openErrorsTab(user);
const list = () => screen.getByRole("list", { name: "Top offenders" });
// 12 agents have failures, but an unbounded list is what made this card
@@ -556,8 +640,10 @@ describe("DashboardPage — Errors card placement and density", () => {
expect(within(list()).getAllByRole("listitem")).toHaveLength(8);
});
- it("shows no expand affordance when every offender already fits", () => {
+ it("shows no expand affordance when every offender already fits", async () => {
+ const user = userEvent.setup();
renderDashboard();
+ await openErrorsTab(user);
expect(
screen.queryByRole("button", { name: /Show all/ }),
diff --git a/packages/views/dashboard/components/dashboard-page.tsx b/packages/views/dashboard/components/dashboard-page.tsx
index 3eae62cbac..2c5f8696ba 100644
--- a/packages/views/dashboard/components/dashboard-page.tsx
+++ b/packages/views/dashboard/components/dashboard-page.tsx
@@ -1,58 +1,34 @@
"use client";
import { useMemo, useState } from "react";
-import { BarChart3, EyeOff, FolderKanban, Trash2 } from "lucide-react";
-import { useQuery } from "@tanstack/react-query";
+import { BarChart3, RefreshCw } from "lucide-react";
+import { useQuery, useQueryClient } from "@tanstack/react-query";
+import { Button } from "@multica/ui/components/ui/button";
import { Skeleton } from "@multica/ui/components/ui/skeleton";
+import { Tabs, TabsContent, TabsList, TabsTrigger } from "@multica/ui/components/ui/tabs";
import {
CompactNumberFlow,
CurrencyNumberFlow,
NumberFlow,
- NumberFlowGroup,
} from "@multica/ui/components/ui/number-flow";
-import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "@multica/ui/components/ui/select";
import { useWorkspaceId } from "@multica/core/hooks";
import type { Agent } from "@multica/core/types";
import { agentListOptions } from "@multica/core/workspace/queries";
import { projectListOptions } from "@multica/core/projects/queries";
import {
+ dashboardKeys,
dashboardUsageDailyOptions,
dashboardUsageByAgentOptions,
dashboardAgentRunTimeOptions,
dashboardRunTimeDailyOptions,
dashboardFailuresDailyOptions,
dashboardFailuresByAgentOptions,
- FAILURE_CLASSES,
- type FailureClass,
} from "@multica/core/dashboard";
-import { useWorkspacePaths } from "@multica/core/paths";
import { useCustomPricingStore } from "@multica/core/runtimes/custom-pricing-store";
import { useViewingTimezone } from "../../common/use-viewing-timezone";
import { PageHeader } from "../../layout/page-header";
import { KpiCard } from "../../runtimes/components/shared";
-import {
- DailyCostChart,
- DailyTokensChart,
- DailyTimeChart,
- DailyTasksChart,
- DailyErrorsChart,
- WeeklyCostChart,
- WeeklyTokensChart,
- WeeklyTimeChart,
- WeeklyTasksChart,
- WeeklyErrorsChart,
- FAILURE_CLASS_COLOR,
- formatRate,
-} from "../../runtimes/components/charts";
-import { ProjectIcon } from "../../projects/components/project-icon";
-import { ActorAvatar } from "../../common/actor-avatar";
-import { AppLink } from "../../navigation";
+import { useNavigation } from "../../navigation";
import {
addDaysIso,
aggregateByWeek,
@@ -77,56 +53,19 @@ import {
anonymizeUnresolvedAgentRows,
computeDailyTotals,
computeFailureTotals,
- DELETED_AGENTS_ROW_ID,
- formatDuration,
- hasRateSample,
isSyntheticAgentRow,
mergeAgentDashboardRows,
- MIN_RATE_SAMPLE,
- OFFENDER_METRIC,
- RESTRICTED_AGENTS_ROW_ID,
- sortAgentFailures,
- type AgentDashboardRow,
- type AgentFailureRow,
- type FailureClassRow,
- type FailureReasonRow,
- type FailureTotals,
- type OffenderSort,
} from "../utils";
-
-// Period selector — mirrors the runtime detail page so users see the same
-// option set across both dashboards. `dims` declares which dimensions each
-// range is allowed in: 1d / 7d at the weekly grain collapse to a single bar,
-// 180d at the daily grain is 180 unreadable bars, so each end of the range
-// belongs to a single dimension. Switching dimensions resets `days` if the
-// current value isn't in the new dimension's allowed set (see
-// `handleDimChange` below).
-//
-// 1d semantic: "today" (the natural calendar day from 00:00 in the viewer's
-// timezone), not "the last 24 hours". The client-side `dailyCutoffIso` filter
-// below enforces this even at the midnight edge.
-const TIME_RANGES = [
- { label: "1d", days: 1, dims: ["daily"] as const },
- { label: "7d", days: 7, dims: ["daily"] as const },
- { label: "30d", days: 30, dims: ["daily", "weekly"] as const },
- { label: "90d", days: 90, dims: ["daily", "weekly"] as const },
- { label: "180d", days: 180, dims: ["weekly"] as const },
-] as const;
-type TimeRange = (typeof TIME_RANGES)[number]["days"];
-type Dim = "daily" | "weekly";
-
-const DEFAULT_DAYS_BY_DIM: Record<Dim, TimeRange> = {
- daily: 30,
- weekly: 90,
-};
-
-function rangesForDim(dim: Dim) {
- return TIME_RANGES.filter((r) => (r.dims as readonly string[]).includes(dim));
-}
-
-// Sentinel for "no project filter" — kept distinct from the empty string
-// so it survives a refactor that ever lets a project be slug-keyed.
-const ALL_PROJECTS = "__all__";
+import {
+ ALL_PROJECTS,
+ DurationNumberFlow,
+ dimsForDays,
+ type TimeRange,
+} from "./dashboard-shared";
+import { ProjectFilter, TimeRangeFilter } from "./dashboard-filters";
+import { UsageTrendCard } from "./usage-trend-card";
+import { Leaderboard } from "./leaderboard";
+import { ErrorsTab } from "./errors-tab";
// Stable references — `data ?? []` would create a new empty array on
// every render while the query is loading, which breaks useMemo's
@@ -140,97 +79,68 @@ const EMPTY_FAILURE_BY_AGENT: import("@multica/core/types").DashboardFailureByAg
[];
const EMPTY_AGENTS: Agent[] = [];
-// Local segmented control — same visual language the runtime usage section
-// uses for its period / tab toggles. shadcn's Tabs is wired for full tab
-// pages with ARIA semantics the compact toolbar pill doesn't need.
-//
-// Which option is active was expressed only as a colour swap, which no screen
-// reader can see, so `aria-pressed` carries it too. `label` is required rather
-// than optional because a naked group of toggle buttons is announced without
-// saying WHAT it toggles — "Rate, pressed" is useless until you know the group
-// is the offender ranking. Toggle buttons rather than a radiogroup: a
-// radiogroup owes the user arrow-key roving focus, and these are tab stops
-// wherever they appear in the page.
-function Segmented<T extends string | number>({
- value,
- onChange,
- options,
- label,
-}: {
- value: T;
- onChange: (v: T) => void;
- options: readonly { label: string; value: T }[];
- label: string;
-}) {
- return (
- <div
- role="group"
- aria-label={label}
- className="inline-flex items-center gap-0.5 rounded-md bg-muted p-0.5"
- >
- {options.map((o) => (
- <button
- key={String(o.value)}
- type="button"
- aria-pressed={o.value === value}
- onClick={() => onChange(o.value)}
- className={`rounded-sm px-2.5 py-1 text-caption font-medium transition-colors ${
- o.value === value
- ? "bg-background text-foreground shadow-sm"
- : "text-muted-foreground hover:text-foreground"
- }`}
- >
- {o.label}
- </button>
- ))}
- </div>
- );
-}
-
-function DurationNumberFlow({
- seconds,
- lessThanMinuteLabel,
- locales,
-}: {
- seconds: number;
- lessThanMinuteLabel: string;
- locales?: Intl.LocalesArgument;
-}) {
- const label = formatDuration(seconds, lessThanMinuteLabel);
- const parts = Array.from(label.matchAll(/(\d+)([a-z]+)/gi), (match) => ({
- value: Number(match[1]),
- unit: match[2] ?? "",
- }));
-
- if (parts.length === 0) return label;
-
- return (
- <>
- <span className="sr-only">{label}</span>
- <NumberFlowGroup>
- <span aria-hidden className="inline-flex items-baseline gap-1">
- {parts.map((part) => (
- <NumberFlow
- key={part.unit}
- value={part.value}
- locales={locales}
- suffix={part.unit}
- format={{ maximumFractionDigits: 0, useGrouping: false }}
- />
- ))}
- </span>
- </NumberFlowGroup>
- </>
- );
+type DashboardTab = "usage" | "errors";
+const TAB_QUERY_KEY = "tab";
+const DEFAULT_TAB: DashboardTab = "usage";
+
+/** Local time of the most recent successful fetch, in the viewer's timezone.
+ * Every number on this page is bucketed on that timezone, so the header says
+ * which one it is — the same figures under a different tz are a different
+ * answer, and nothing on the page used to admit that. */
+function useDataFreshness(
+ updatedAts: (number | undefined)[],
+ viewTZ: string,
+ locales: Intl.LocalesArgument,
+): { tzLabel: string | null; updatedLabel: string | null } {
+ return useMemo(() => {
+ const stamps = updatedAts.filter(
+ (n): n is number => typeof n === "number" && n > 0,
+ );
+ const latest = stamps.length > 0 ? Math.max(...stamps) : null;
+ // A stored timezone is user input and reaches us unvalidated; Intl throws
+ // on a string it does not recognise, and a header label is not worth
+ // taking the page down for.
+ try {
+ const tzLabel =
+ new Intl.DateTimeFormat(locales, {
+ timeZone: viewTZ,
+ timeZoneName: "shortOffset",
+ })
+ .formatToParts(new Date())
+ .find((part) => part.type === "timeZoneName")?.value ?? null;
+ const updatedLabel =
+ latest === null
+ ? null
+ : new Intl.DateTimeFormat(locales, {
+ timeZone: viewTZ,
+ hour: "2-digit",
+ minute: "2-digit",
+ }).format(new Date(latest));
+ return { tzLabel, updatedLabel };
+ } catch {
+ return { tzLabel: null, updatedLabel: null };
+ }
+ // `updatedAts` is a fresh array each render; spreading it into the dep list
+ // keeps the memo keyed on the values rather than the identity.
+ // eslint-disable-next-line react-hooks/exhaustive-deps
+ }, [...updatedAts, viewTZ, locales]);
}
/**
- * Workspace + project token / run-time dashboard.
+ * Workspace + project usage dashboard.
*
- * Lives at `/{slug}/dashboard`. Three independent rollups (daily cost,
- * per-agent tokens, per-agent run-time) feed four KPI tiles, a daily cost
- * chart, and a combined "by agent" list. A project dropdown narrows every
- * query to one project; the period selector applies to all three.
+ * Lives at `/{slug}/usage`. Two tabs, split by the question the reader arrived
+ * with rather than by which rollup feeds them: Usage answers "what did this
+ * cost", Errors answers "what broke". They used to share one scrolling page,
+ * where the failure breakdown sat below a leaderboard that could itself run to
+ * thirty rows, and the only way to chart failures was to hide spend.
+ *
+ * Scope is expressed by where a control lives: the toolbar under the header
+ * carries the tabs and the two page-scoped filters (time range, project),
+ * every card carries its own view switches. All six rollups are fetched for
+ * both tabs — they are small, and prefetching is what makes switching tabs
+ * instant — but the loading and empty states are per tab, so Usage does not
+ * wait on the failure queries.
*
* Cost math runs client-side via the runtimes utils — keeps the dashboard
* and the runtime page using one pricing table.
@@ -239,18 +149,24 @@ export function DashboardPage() {
const { t, i18n } = useT("usage");
const wsId = useWorkspaceId();
const viewTZ = useViewingTimezone();
+ const navigation = useNavigation();
const locales = i18n.resolvedLanguage ?? i18n.language;
- const [dim, setDim] = useState<Dim>("daily");
const [days, setDays] = useState<TimeRange>(30);
const [projectValue, setProjectValue] = useState<string>(ALL_PROJECTS);
- const allowedRanges = rangesForDim(dim);
- const handleDimChange = (next: Dim) => {
- setDim(next);
- const stillAllowed = (rangesForDim(next) as readonly { days: number }[]).some(
- (r) => r.days === days,
- );
- if (!stillAllowed) setDays(DEFAULT_DAYS_BY_DIM[next]);
+ // The tab lives in the URL because the Errors view is the half of this page
+ // people paste at each other ("this agent failed 54 times, see for
+ // yourself"); component state cannot be linked to. `replace`, not `push`, so
+ // flipping tabs does not stack up history entries. An unknown ?tab= value
+ // falls back to Usage rather than rendering nothing.
+ const tabFromUrl = navigation.searchParams.get(TAB_QUERY_KEY);
+ const tab: DashboardTab = tabFromUrl === "errors" ? "errors" : DEFAULT_TAB;
+ const handleTabChange = (next: string) => {
+ const params = new URLSearchParams(navigation.searchParams);
+ if (next === DEFAULT_TAB) params.delete(TAB_QUERY_KEY);
+ else params.set(TAB_QUERY_KEY, next);
+ const query = params.toString();
+ navigation.replace(query ? `${navigation.pathname}?${query}` : navigation.pathname);
};
// The user can save model prices from the runtimes page; re-render when
@@ -263,23 +179,29 @@ export function DashboardPage() {
// Validate the picked project against the current workspace's list. A
// stale UUID — left over from a project that's been deleted, or from the
- // previous workspace after a switch — would silently filter all three
- // queries to empty rows while the dropdown still reads "All projects".
- // Derive the effective filter so the API call matches the user-visible
- // selection.
+ // previous workspace after a switch — would silently filter every query to
+ // empty rows while the header still reads "All projects". Derive the
+ // effective filter so the API call matches the user-visible selection.
const projectId = useMemo(() => {
if (projectValue === ALL_PROJECTS) return null;
return projects.some((p) => p.id === projectValue) ? projectValue : null;
}, [projectValue, projects]);
- // The weekly chart paints `ceil(days / 7)` trailing calendar weeks anchored
+ // The weekly charts paint `ceil(days / 7)` trailing calendar weeks anchored
// at today-in-UTC. In the worst case (today = Sunday) the leftmost Monday
// sits `weekCount * 7 - 1` days back, so a vanilla `days=30` request would
- // silently truncate the leftmost bucket. Over-fetch the per-date queries
- // to cover the full first week; the per-agent rollups stay at `days` so
- // KPI/leaderboard labels (e.g. "Tasks · 30D") keep their advertised window.
+ // silently truncate the leftmost bucket. Over-fetch the per-date queries to
+ // cover the full first week.
+ //
+ // Unconditionally, not only when a chart is weekly: the dimension is now a
+ // card-level control, so the page cannot know which grain is on screen — and
+ // fetching for the wider of the two means flipping a card between Daily and
+ // Weekly never refetches. Daily aggregations trim back to exactly `days`
+ // client-side via `dailyCutoffIso` below, so the extra rows change nothing
+ // they show. The per-agent rollups stay at `days` so KPI/leaderboard labels
+ // (e.g. "Tasks · 30D") keep their advertised window.
const weekCount = Math.max(1, Math.ceil(days / 7));
- const chartFetchDays = dim === "weekly" ? weekCount * 7 : days;
+ const chartFetchDays = weekCount * 7;
const dailyQuery = useQuery(
dashboardUsageDailyOptions(wsId, chartFetchDays, projectId, viewTZ),
@@ -314,13 +236,40 @@ export function DashboardPage() {
const failureDailyRows = failuresDailyQuery.data ?? EMPTY_FAILURE_DAILY;
const failureByAgentRows = failuresByAgentQuery.data ?? EMPTY_FAILURE_BY_AGENT;
- // Daily-aggregation surfaces (cost/tokens/time/tasks KPIs and the Daily
- // trend chart) re-scope to the user-selected `days` even when we
- // over-fetched for the weekly chart. The cutoff is anchored on the viewer's
- // timezone — the same axis the backend slices `bucket_hour` on — so it
- // lands on the same calendar boundary. Applied in both dims so 1d strictly
- // means "today" even at the midnight edge where a wall-clock cutoff would
- // otherwise include yesterday.
+ const queryClient = useQueryClient();
+ // "Refreshing" covers any of the six rollups being in flight, whichever
+ // trigger started it (button, interval, mount) — the header spinner and the
+ // timestamp describe the same set of queries.
+ const isRefreshing =
+ dailyQuery.isFetching ||
+ byAgentQuery.isFetching ||
+ runTimeQuery.isFetching ||
+ runTimeDailyQuery.isFetching ||
+ failuresDailyQuery.isFetching ||
+ failuresByAgentQuery.isFetching;
+ const handleRefresh = () => {
+ void queryClient.invalidateQueries({ queryKey: dashboardKeys.all(wsId) });
+ };
+
+ const { tzLabel, updatedLabel } = useDataFreshness(
+ [
+ dailyQuery.dataUpdatedAt,
+ byAgentQuery.dataUpdatedAt,
+ runTimeQuery.dataUpdatedAt,
+ runTimeDailyQuery.dataUpdatedAt,
+ failuresDailyQuery.dataUpdatedAt,
+ failuresByAgentQuery.dataUpdatedAt,
+ ],
+ viewTZ,
+ locales,
+ );
+
+ // Daily-aggregation surfaces re-scope to the user-selected `days` even
+ // though the per-date queries over-fetch for the weekly charts. The cutoff is
+ // anchored on the viewer's timezone — the same axis the backend slices
+ // `bucket_hour` on — so it lands on the same calendar boundary. Applied in
+ // both dims so 1d strictly means "today" even at the midnight edge where a
+ // wall-clock cutoff would otherwise include yesterday.
const dailyCutoffIso = useMemo(
() => addDaysIso(todayIso(viewTZ), -(days - 1)),
[days, viewTZ],
@@ -338,25 +287,23 @@ export function DashboardPage() {
[failureDailyRows, dailyCutoffIso],
);
- const isLoading =
+ // Loading and empty are per tab: the Usage tab has no reason to wait on the
+ // two failure rollups, and a workspace with spend but no failures is not an
+ // empty dashboard.
+ const usageLoading =
dailyQuery.isLoading ||
byAgentQuery.isLoading ||
runTimeQuery.isLoading ||
- runTimeDailyQuery.isLoading ||
- failuresDailyQuery.isLoading ||
- failuresByAgentQuery.isLoading;
+ runTimeDailyQuery.isLoading;
+ const errorsLoading =
+ failuresDailyQuery.isLoading || failuresByAgentQuery.isLoading;
- // Six independent rollups, but the empty-state is one decision — only
- // show "no data yet" when ALL came back empty so a project with tokens
- // but no runs (or vice-versa) doesn't look broken.
- const hasNoData =
- !isLoading &&
+ const usageHasNoData =
+ !usageLoading &&
dailyUsage.length === 0 &&
byAgentUsage.length === 0 &&
runTimeRows.length === 0 &&
- runTimeDailyRows.length === 0 &&
- failureDailyRows.length === 0 &&
- failureByAgentRows.length === 0;
+ runTimeDailyRows.length === 0;
// Cost / token math — re-derived when usage, days, or pricings change.
const totals = useMemo(
@@ -384,16 +331,16 @@ export function DashboardPage() {
[failureDailyInWindow],
);
- // Failure summaries for the Errors breakdown card.
+ // Failure summaries.
//
// Totals / classes / reasons are derived from the DATE-BUCKETED rollup after
// the same `dailyCutoffIso` trim the charts use, not from the per-agent one.
// `parseSinceParamInTZ` deliberately returns N+1 calendar days of headroom
// (see sinceFromDays in server/internal/handler/runtime.go), and only a
// series carrying a date can trim that back client-side. Reading these off
- // the per-agent rollup put the card one calendar day wider than the chart
- // directly above it — at 1D the chart could show no failures while the card
- // counted yesterday's.
+ // the per-agent rollup put the summary one calendar day wider than the chart
+ // beside it — at 1D the chart could show no failures while the tile counted
+ // yesterday's.
const failureTotals = useMemo(
() => computeFailureTotals(failureDailyInWindow),
[failureDailyInWindow],
@@ -504,1025 +451,191 @@ export function DashboardPage() {
[agentRows, knownAgentIds],
);
+ const allowedDims = dimsForDays(days);
+ const lessThanMinuteLabel = t(($) => $.duration.less_than_minute);
+
return (
- <div className="flex h-full flex-col">
- {/* h-auto + min-h-12 + flex-wrap: the toolbar (project filter,
- dimension switch, range switch) wraps on narrow viewports so every
- control stays reachable. Wider viewports still render the original
- single row. */}
- <PageHeader className="h-auto min-h-12 flex-wrap justify-between gap-y-1.5 px-5 py-1.5 sm:py-0">
+ <Tabs
+ value={tab}
+ onValueChange={handleTabChange}
+ className="flex h-full min-h-0 flex-col gap-0"
+ >
+ <PageHeader className="justify-between gap-2 px-5">
<div className="flex min-w-0 items-center gap-2">
<BarChart3 className="h-4 w-4 shrink-0 text-muted-foreground" />
- <h1 className="truncate text-body font-medium">{t(($) => $.title)}</h1>
+ <h1 className="text-body font-medium">{t(($) => $.title)}</h1>
</div>
- <div className="flex flex-wrap items-center gap-2">
- <ProjectFilter
- projects={projects}
- value={projectValue}
- onChange={setProjectValue}
- />
- <Segmented
- label={t(($) => $.dim.label)}
- value={dim}
- onChange={handleDimChange}
- options={[
- { label: t(($) => $.dim.daily), value: "daily" as const },
- { label: t(($) => $.dim.weekly), value: "weekly" as const },
- ]}
- />
- <Segmented
- label={t(($) => $.filter.period_label)}
- value={days}
- onChange={setDays}
- options={allowedRanges.map((r) => ({ label: r.label, value: r.days }))}
- />
+ {/* Data freshness cluster: the timestamp and the action that advances
+ it stay together. Refresh re-pulls the same scope, so it lives here
+ with the page metadata rather than among the scope controls. */}
+ <div className="flex shrink-0 items-center gap-1">
+ {tzLabel ? (
+ <span className="hidden text-caption text-muted-foreground lg:inline">
+ {updatedLabel
+ ? t(($) => $.header.timezone_and_updated, {
+ tz: tzLabel,
+ time: updatedLabel,
+ })
+ : tzLabel}
+ </span>
+ ) : null}
+ <Button
+ variant="ghost"
+ size="icon-sm"
+ aria-label={t(($) => $.header.refresh)}
+ onClick={handleRefresh}
+ disabled={isRefreshing}
+ >
+ <RefreshCw className={isRefreshing ? "animate-spin" : undefined} />
+ </Button>
</div>
</PageHeader>
- <div className="flex-1 overflow-y-auto">
- <div className="mx-auto max-w-6xl space-y-5 p-6">
- <p className="text-caption text-muted-foreground">{t(($) => $.subtitle)}</p>
+ {/* View toolbar, same grammar as the issues surface header: view
+ switching on the left, page-scoped filters on the right. Both tabs
+ share the range and project filter, which is why the filters live
+ here and not inside a tab. */}
+ <div className="h-12 shrink-0 overflow-x-auto border-b px-5 [-webkit-overflow-scrolling:touch]">
+ <div className="flex h-full w-max min-w-full items-center justify-between gap-2">
+ <TabsList variant="line" className="gap-0 p-0 group-data-horizontal/tabs:h-full">
+ <TabsTrigger
+ value="usage"
+ className="h-full rounded-none px-2.5 text-label group-data-horizontal/tabs:after:bottom-0"
+ >
+ {t(($) => $.tab_usage)}
+ </TabsTrigger>
+ <TabsTrigger
+ value="errors"
+ className="h-full rounded-none px-2.5 text-label group-data-horizontal/tabs:after:bottom-0"
+ >
+ {t(($) => $.errors.title)}
+ </TabsTrigger>
+ </TabsList>
+ <div className="flex shrink-0 items-center gap-2">
+ <TimeRangeFilter days={days} onChange={setDays} />
+ <ProjectFilter
+ projects={projects}
+ projectValue={projectValue}
+ onProjectChange={setProjectValue}
+ />
+ </div>
+ </div>
+ </div>
- {isLoading ? (
- <DashboardSkeleton />
- ) : hasNoData ? (
- <DashboardEmpty />
- ) : (
- <>
- {/* KPI row — same 3-divide-x card grid the runtime usage
- section uses, expanded to four tiles. */}
- <div className="grid grid-cols-1 divide-y rounded-lg border bg-card sm:grid-cols-2 sm:divide-x sm:divide-y-0 lg:grid-cols-4">
- <KpiCard
- label={t(($) => $.kpi.cost_label, { days })}
- value={
- <CurrencyNumberFlow value={totals.cost} locales={locales} />
- }
- />
- <KpiCard
- label={t(($) => $.kpi.tokens_label, { days })}
- value={
- <CompactNumberFlow
- value={
- totals.input +
- totals.output +
- totals.cacheRead +
- totals.cacheWrite
- }
- locales={locales}
- />
- }
- hint={t(($) => $.kpi.tokens_hint, {
- input: formatTokens(totals.input),
- output: formatTokens(totals.output),
- })}
- />
- <KpiCard
- label={t(($) => $.kpi.run_time_label, { days })}
- value={
- <DurationNumberFlow
- seconds={runTimeTotals.totalSeconds}
- lessThanMinuteLabel={t(($) => $.duration.less_than_minute)}
- locales={locales}
- />
- }
- hint={t(($) => $.kpi.run_time_hint, {
- tasks: runTimeTotals.taskCount,
- })}
- />
- <KpiCard
- label={t(($) => $.kpi.tasks_label, { days })}
- value={
- <NumberFlow
- value={runTimeTotals.taskCount}
- locales={locales}
- format={{ maximumFractionDigits: 0 }}
- aria-label={String(runTimeTotals.taskCount)}
- />
- }
- // Deliberately still sourced from `runTimeTotals`, not the
- // failure rollup: the tile's own value counts started tasks
- // only, so quoting the failure rollup's larger failure count
- // here would put two different denominators in one tile. The
- // Errors card below states its rate with the denominator
- // spelled out instead.
- hint={t(($) => $.kpi.tasks_hint, {
- failed: runTimeTotals.failedCount,
- })}
- accent={runTimeTotals.failedCount > 0 ? "default" : "default"}
+ <div className="flex-1 overflow-y-auto">
+ <div className="mx-auto max-w-6xl p-6">
+ <TabsContent value="usage" className="space-y-5">
+ <p className="text-caption text-muted-foreground">{t(($) => $.subtitle)}</p>
+ {usageLoading ? (
+ <DashboardSkeleton />
+ ) : usageHasNoData ? (
+ <DashboardEmpty />
+ ) : (
+ <>
+ {/* KPI row — same 3-divide-x card grid the runtime usage
+ section uses, expanded to four tiles. */}
+ <div className="grid grid-cols-1 divide-y rounded-lg border bg-card sm:grid-cols-2 sm:divide-x sm:divide-y-0 lg:grid-cols-4">
+ <KpiCard
+ label={t(($) => $.kpi.cost_label, { days })}
+ value={<CurrencyNumberFlow value={totals.cost} locales={locales} />}
+ />
+ <KpiCard
+ label={t(($) => $.kpi.tokens_label, { days })}
+ value={
+ <CompactNumberFlow
+ value={
+ totals.input +
+ totals.output +
+ totals.cacheRead +
+ totals.cacheWrite
+ }
+ locales={locales}
+ />
+ }
+ hint={t(($) => $.kpi.tokens_hint, {
+ input: formatTokens(totals.input),
+ output: formatTokens(totals.output),
+ })}
+ />
+ <KpiCard
+ label={t(($) => $.kpi.run_time_label, { days })}
+ value={
+ <DurationNumberFlow
+ seconds={runTimeTotals.totalSeconds}
+ lessThanMinuteLabel={lessThanMinuteLabel}
+ locales={locales}
+ />
+ }
+ hint={t(($) => $.kpi.run_time_hint, {
+ tasks: runTimeTotals.taskCount,
+ })}
+ />
+ <KpiCard
+ label={t(($) => $.kpi.tasks_label, { days })}
+ value={
+ <NumberFlow
+ value={runTimeTotals.taskCount}
+ locales={locales}
+ format={{ maximumFractionDigits: 0 }}
+ aria-label={String(runTimeTotals.taskCount)}
+ />
+ }
+ // Deliberately sourced from `runTimeTotals`, not the
+ // failure rollup: the tile's own value counts started tasks
+ // only, so quoting the failure rollup's larger failure count
+ // here would put two different denominators in one tile. The
+ // Errors tab states its rate with the denominator spelled
+ // out instead.
+ hint={t(($) => $.kpi.tasks_hint, {
+ failed: runTimeTotals.failedCount,
+ })}
+ />
+ </div>
+
+ <UsageTrendCard
+ allowedDims={allowedDims}
+ dailyCost={dailyCost}
+ dailyTokens={dailyTokens}
+ dailyTime={dailyTime}
+ dailyTasks={dailyTasks}
+ weeklyCost={weeklyCost}
+ weeklyTokens={weeklyTokens}
+ weeklyTime={weeklyTime}
+ weeklyTasks={weeklyTasks}
+ lessThanMinuteLabel={lessThanMinuteLabel}
/>
- </div>
- {/* Trend chart — toggle picks Tokens / Cost / Time / Tasks /
- Errors and the parent's dim selector decides whether the
- bars are per-day or per-calendar-week. All five metrics
- share the same x-axis so the user can mentally overlay them
- by flipping the toggle. */}
- <TrendBlock
- dim={dim}
- dailyCost={dailyCost}
- dailyTokens={dailyTokens}
- dailyTime={dailyTime}
- dailyTasks={dailyTasks}
- dailyErrors={dailyErrors}
- weeklyCost={weeklyCost}
- weeklyTokens={weeklyTokens}
- weeklyTime={weeklyTime}
- weeklyTasks={weeklyTasks}
- weeklyErrors={weeklyErrors}
- lessThanMinuteLabel={t(($) => $.duration.less_than_minute)}
- />
-
- {/* Per-agent leaderboard — user picks the ranking metric;
- the progress bar and column emphasis follow the metric. */}
- <Leaderboard
- rows={visibleAgentRows}
- agents={agents}
- deletedAgentCount={deletedAgentCount}
- lessThanMinuteLabel={t(($) => $.duration.less_than_minute)}
- />
+ <Leaderboard
+ rows={visibleAgentRows}
+ agents={agents}
+ deletedAgentCount={deletedAgentCount}
+ lessThanMinuteLabel={lessThanMinuteLabel}
+ />
+ </>
+ )}
+ </TabsContent>
- {/* Failure breakdown — what broke and who it broke for. Rendered
- unconditionally (not only when failures exist) so "no failed
- runs" is an answer the page gives rather than an absence the
- reader has to infer. */}
- <ErrorsBreakdown
+ <TabsContent value="errors">
+ {errorsLoading ? (
+ <DashboardSkeleton />
+ ) : (
+ <ErrorsTab
+ days={days}
+ allowedDims={allowedDims}
totals={failureTotals}
classRows={failureClassRows}
reasonRows={failureReasonRows}
agentRows={agentFailureRows}
+ dailyErrors={dailyErrors}
+ weeklyErrors={weeklyErrors}
agents={agents}
+ locales={locales}
/>
- </>
- )}
- </div>
- </div>
- </div>
- );
-}
-
-function ProjectFilter({
- projects,
- value,
- onChange,
-}: {
- projects: { id: string; title: string; icon: string | null }[];
- value: string;
- onChange: (v: string) => void;
-}) {
- const { t } = useT("usage");
- const allLabel = t(($) => $.filter.all_projects);
- const selected = projects.find((p) => p.id === value);
- const selectedTitle =
- value === ALL_PROJECTS ? allLabel : selected?.title ?? allLabel;
- const projectItems = [
- { value: ALL_PROJECTS, label: allLabel },
- ...projects.map((project) => ({ value: project.id, label: project.title })),
- ];
-
- return (
- <Select
- items={projectItems}
- value={value}
- onValueChange={(v) => onChange(v ?? ALL_PROJECTS)}
- >
- <SelectTrigger size="sm" className="min-w-[180px]">
- <SelectValue>
- {() => (
- <>
- {selected ? (
- <ProjectIcon project={selected} size="sm" />
- ) : (
- <FolderKanban className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
- )}
- <span className="truncate">{selectedTitle}</span>
- </>
- )}
- </SelectValue>
- </SelectTrigger>
- {/* alignItemWithTrigger=false: the default aligns the *selected* item
- to the trigger, which pushes "All projects" above the trigger and
- clips it off-screen when the usage header sits at the top of the
- viewport. Anchor the dropdown to the bottom of the trigger so
- every entry stays reachable.
- max-h-72: cap the dropdown so a long project list scrolls instead
- of stretching to the bottom of the window. */}
- <SelectContent align="start" alignItemWithTrigger={false} className="max-h-72">
- <SelectItem value={ALL_PROJECTS}>
- <FolderKanban className="h-3.5 w-3.5 shrink-0 text-muted-foreground" />
- <span className="truncate">{allLabel}</span>
- </SelectItem>
- {projects.map((p) => (
- <SelectItem key={p.id} value={p.id}>
- <ProjectIcon project={p} size="sm" />
- <span className="truncate">{p.title}</span>
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- );
-}
-
-type DailyMetric = "tokens" | "cost" | "time" | "tasks" | "errors";
-
-function TrendBlock({
- dim,
- dailyCost,
- dailyTokens,
- dailyTime,
- dailyTasks,
- dailyErrors,
- weeklyCost,
- weeklyTokens,
- weeklyTime,
- weeklyTasks,
- weeklyErrors,
- lessThanMinuteLabel,
-}: {
- dim: Dim;
- dailyCost: ReturnType<typeof aggregateDailyCost>;
- dailyTokens: ReturnType<typeof aggregateDailyTokens>;
- dailyTime: ReturnType<typeof aggregateDailyTime>;
- dailyTasks: ReturnType<typeof aggregateDailyTasks>;
- dailyErrors: ReturnType<typeof aggregateDailyErrors>;
- weeklyCost: ReturnType<typeof aggregateByWeek>["weeklyCostStack"];
- weeklyTokens: ReturnType<typeof aggregateByWeek>["weeklyTokens"];
- weeklyTime: ReturnType<typeof aggregateWeeklyTime>;
- weeklyTasks: ReturnType<typeof aggregateWeeklyTasks>;
- weeklyErrors: ReturnType<typeof aggregateWeeklyErrors>;
- lessThanMinuteLabel: string;
-}) {
- const { t } = useT("usage");
- const [metric, setMetric] = useState<DailyMetric>("tokens");
-
- // Empty-state is per-metric so each toggle option independently decides
- // whether it has data — e.g. tokens recorded but no terminal runs yet
- // should show Tokens normally while Time / Tasks fall through to empty.
- const costData = dim === "weekly" ? weeklyCost : dailyCost;
- const tokensData = dim === "weekly" ? weeklyTokens : dailyTokens;
- const timeData = dim === "weekly" ? weeklyTime : dailyTime;
- const tasksData = dim === "weekly" ? weeklyTasks : dailyTasks;
- const errorsData = dim === "weekly" ? weeklyErrors : dailyErrors;
-
- const totalCost = costData.reduce((sum, d) => sum + d.total, 0);
- const totalTokens = tokensData.reduce(
- (sum, d) => sum + d.input + d.output + d.cacheRead + d.cacheWrite,
- 0,
- );
- const totalSeconds = timeData.reduce((sum, d) => sum + d.totalSeconds, 0);
- const totalTasks = tasksData.reduce(
- (sum, d) => sum + d.completed + d.failed,
- 0,
- );
- // A window with runs but zero failures is a *good* outcome, not missing
- // data — but an all-zero bar chart says nothing a sentence can't say
- // better, so it still routes to the empty state.
- const totalFailed = errorsData.reduce((sum, d) => sum + d.failed, 0);
- const isEmpty =
- metric === "cost"
- ? totalCost === 0
- : metric === "tokens"
- ? totalTokens === 0
- : metric === "time"
- ? totalSeconds === 0
- : metric === "tasks"
- ? totalTasks === 0
- : totalFailed === 0;
-
- const title =
- dim === "weekly"
- ? metric === "cost"
- ? t(($) => $.weekly.title_cost)
- : metric === "tokens"
- ? t(($) => $.weekly.title_tokens)
- : metric === "time"
- ? t(($) => $.weekly.title_time)
- : metric === "tasks"
- ? t(($) => $.weekly.title_tasks)
- : t(($) => $.weekly.title_errors)
- : metric === "cost"
- ? t(($) => $.daily.title_cost)
- : metric === "tokens"
- ? t(($) => $.daily.title_tokens)
- : metric === "time"
- ? t(($) => $.daily.title_time)
- : metric === "tasks"
- ? t(($) => $.daily.title_tasks)
- : t(($) => $.daily.title_errors);
-
- return (
- <div className="rounded-lg border bg-card p-4">
- <div className="mb-3 flex flex-wrap items-center justify-between gap-3">
- <h4 className="text-body font-semibold">{title}</h4>
- <Segmented
- label={t(($) => $.daily.metric_label)}
- value={metric}
- onChange={setMetric}
- options={[
- { label: t(($) => $.daily.metric_tokens), value: "tokens" as const },
- { label: t(($) => $.daily.metric_cost), value: "cost" as const },
- { label: t(($) => $.daily.metric_time), value: "time" as const },
- { label: t(($) => $.daily.metric_tasks), value: "tasks" as const },
- { label: t(($) => $.daily.metric_errors), value: "errors" as const },
- ]}
- />
- </div>
- <div className="min-h-[240px]">
- {isEmpty ? (
- <div className="flex aspect-[3/1] flex-col items-center justify-center gap-2 rounded-md border border-dashed bg-muted/20 p-6 text-center">
- <BarChart3 className="h-5 w-5 text-faint-foreground" />
- <p className="text-caption text-muted-foreground">
- {metric === "errors"
- ? t(($) => $.errors.no_data)
- : t(($) => $.daily.no_data)}
- </p>
- </div>
- ) : dim === "weekly" ? (
- metric === "cost" ? (
- <WeeklyCostChart data={weeklyCost} />
- ) : metric === "tokens" ? (
- <WeeklyTokensChart data={weeklyTokens} />
- ) : metric === "time" ? (
- <WeeklyTimeChart
- data={weeklyTime}
- formatY={(s) => formatDuration(s, lessThanMinuteLabel)}
- formatTooltip={(s) => formatDuration(s, lessThanMinuteLabel)}
- />
- ) : metric === "tasks" ? (
- <WeeklyTasksChart data={weeklyTasks} />
- ) : (
- <WeeklyErrorsChart data={weeklyErrors} />
- )
- ) : metric === "cost" ? (
- <DailyCostChart data={dailyCost} />
- ) : metric === "tokens" ? (
- <DailyTokensChart data={dailyTokens} />
- ) : metric === "time" ? (
- <DailyTimeChart
- data={dailyTime}
- formatY={(s) => formatDuration(s, lessThanMinuteLabel)}
- formatTooltip={(s) => formatDuration(s, lessThanMinuteLabel)}
- />
- ) : metric === "tasks" ? (
- <DailyTasksChart data={dailyTasks} />
- ) : (
- <DailyErrorsChart data={dailyErrors} />
- )}
- </div>
- </div>
- );
-}
-
-// Translated label for a failure class. The mapping is a switch rather than
-// an index into a lookup object so the type checker flags a class added to
-// FAILURE_CLASSES without matching copy.
-function useFailureClassLabel(): (c: FailureClass) => string {
- const { t } = useT("usage");
- return (c) => {
- switch (c) {
- case "auth":
- return t(($) => $.errors.class.auth);
- case "rate_limit":
- return t(($) => $.errors.class.rate_limit);
- case "timeout":
- return t(($) => $.errors.class.timeout);
- case "provider":
- return t(($) => $.errors.class.provider);
- case "runtime":
- return t(($) => $.errors.class.runtime);
- case "agent":
- return t(($) => $.errors.class.agent);
- case "other":
- return t(($) => $.errors.class.other);
- }
- };
-}
-
-// How many offenders the list shows before collapsing the tail behind a
-// toggle. The list is ranked by absolute failure count, so the tail is
-// agents that failed once or twice — real, but not what anyone opens this
-// card to see. Eight keeps the card roughly as tall as the class summary
-// plus a header, instead of running to 30+ rows on a busy workspace.
-const TOP_OFFENDER_LIMIT = 8;
-
-// Shared by the offender column header and every offender row, so the two
-// cannot drift out of alignment.
-const OFFENDER_GRID =
- "grid grid-cols-[minmax(0,1.4fr)_minmax(0,1fr)_4rem_4rem_4rem] items-center gap-3";
-
-/**
- * Failure breakdown for the selected window: what class of thing broke, and
- * which agents it broke for.
- *
- * Laid out as two stacked full-width sections rather than side-by-side
- * columns. The two halves have structurally different lengths — classes are
- * capped at seven and usually show three or four, while the agent list is
- * unbounded — so a 2-column grid left one side stranded next to a column of
- * whitespace. Stacking also lets each section use the full width for what it
- * actually needs: proportion for the classes, a leaderboard-shaped row for
- * the agents.
- */
-function ErrorsBreakdown({
- totals,
- classRows,
- reasonRows,
- agentRows,
- agents,
-}: {
- totals: FailureTotals;
- classRows: FailureClassRow[];
- reasonRows: FailureReasonRow[];
- agentRows: AgentFailureRow[];
- agents: { id: string; name: string }[];
-}) {
- const { t } = useT("usage");
- const classLabel = useFailureClassLabel();
- const [showReasons, setShowReasons] = useState(false);
- const [showAllAgents, setShowAllAgents] = useState(false);
- const [sortBy, setSortBy] = useState<OffenderSort>("failed");
-
- const sortOptions = useMemo(
- () => [
- { value: "failed" as const, label: t(($) => $.errors.sort_failed) },
- { value: "rate" as const, label: t(($) => $.errors.sort_rate) },
- ],
- [t],
- );
-
- const sortedAgents = useMemo(
- () => sortAgentFailures(agentRows, sortBy),
- [agentRows, sortBy],
- );
-
- // The leader fills the track, measured over every row rather than the
- // visible ones so a bar means the same thing collapsed and expanded. Reading
- // it off the leader (instead of a max over the raw rows) also keeps the Rate
- // scale usable: a demoted small-sample row can out-rate the leader, and
- // scaling to it would squash every meaningful bar to a sliver.
- const leader = sortedAgents[0];
- const maxValue = leader ? OFFENDER_METRIC[sortBy](leader) : 0;
-
- const visibleAgents = showAllAgents
- ? sortedAgents
- : sortedAgents.slice(0, TOP_OFFENDER_LIMIT);
-
- return (
- <div className="rounded-lg border bg-card">
- <div className="flex flex-wrap items-center justify-between gap-3 border-b px-4 pt-4 pb-3">
- <h4 className="text-body font-semibold">{t(($) => $.errors.title)}</h4>
- <span className="text-caption text-muted-foreground">
- {totals.failed > 0
- ? t(($) => $.errors.summary, {
- failed: totals.failed,
- total: totals.total,
- rate: formatRate(totals.failed, totals.total),
- })
- : t(($) => $.errors.no_data)}
- </span>
- </div>
-
- {totals.failed === 0 ? null : (
- <>
- <div className="border-b p-4">
- <div className="mb-2.5 flex items-center justify-between gap-2">
- {/* Spells out its own denominator. The header above quotes a
- rate over every run (3.3% of 8575); this section splits the
- failures alone (287). Two percentages one above the other
- with different denominators read as a contradiction unless
- each says what it is counting. */}
- <h5 className="text-caption font-medium text-muted-foreground">
- {t(($) => $.errors.mix_title, { failed: totals.failed })}
- </h5>
- <button
- type="button"
- onClick={() => setShowReasons((v) => !v)}
- className="text-caption text-muted-foreground underline-offset-2 hover:text-foreground hover:underline"
- >
- {showReasons
- ? t(($) => $.errors.hide_reasons)
- : t(($) => $.errors.show_reasons)}
- </button>
- </div>
- {showReasons ? (
- <ReasonList rows={reasonRows} />
- ) : (
- <ClassComposition rows={classRows} classLabel={classLabel} />
)}
- </div>
-
- <div className="p-4">
- <div className="mb-2 flex flex-wrap items-center justify-between gap-2">
- <h5 className="text-caption font-medium text-muted-foreground">
- {t(($) => $.errors.by_agent)}
- </h5>
- <div className="flex flex-wrap items-center justify-end gap-3">
- <Segmented
- label={t(($) => $.errors.sort_label)}
- value={sortBy}
- onChange={setSortBy}
- options={sortOptions}
- />
- {sortedAgents.length > TOP_OFFENDER_LIMIT ? (
- <button
- type="button"
- onClick={() => setShowAllAgents((v) => !v)}
- className="text-caption text-muted-foreground underline-offset-2 hover:text-foreground hover:underline"
- >
- {showAllAgents
- ? t(($) => $.errors.show_less, {
- count: TOP_OFFENDER_LIMIT,
- })
- : t(($) => $.errors.show_all, {
- count: sortedAgents.length,
- })}
- </button>
- ) : null}
- </div>
- </div>
- {/* Column headers, as on the leaderboard: `4 / 10 · 40%` was one
- unlabelled blob and the reader had to guess which number was
- which. The active metric's column is emphasised so it is
- obvious what the ranking and the bars measure. */}
- {sortedAgents.length > 0 ? (
- <div
- className={`${OFFENDER_GRID} border-b py-2 text-caption font-medium text-muted-foreground`}
- >
- <span>{t(($) => $.errors.header_agent)}</span>
- <span />
- <span
- className={`text-right ${sortBy === "failed" ? "text-foreground" : ""}`}
- >
- {t(($) => $.errors.header_failed)}
- </span>
- <span className="text-right">
- {t(($) => $.errors.header_runs)}
- </span>
- <span
- className={`text-right ${sortBy === "rate" ? "text-foreground" : ""}`}
- >
- {t(($) => $.errors.header_rate)}
- </span>
- </div>
- ) : null}
- <ul aria-label={t(($) => $.errors.by_agent)} className="divide-y">
- {visibleAgents.map((row) => (
- <AgentFailureItem
- key={row.agentId}
- row={row}
- name={agents.find((a) => a.id === row.agentId)?.name ?? null}
- maxValue={maxValue}
- sortBy={sortBy}
- classLabel={classLabel}
- />
- ))}
- </ul>
- </div>
- </>
- )}
- </div>
- );
-}
-
-/**
- * Class breakdown as one 100%-stacked bar plus a legend.
- *
- * Replaces seven stacked progress bars. The question this answers is "what is
- * the mix", and a single bar shows share-of-total directly — with separate
- * bars the reader has to compare lengths and mentally total them. It also
- * collapses ~340px of vertical space into ~70px, which is what let the card
- * stop being a column of whitespace.
- */
-function ClassComposition({
- rows,
- classLabel,
-}: {
- rows: FailureClassRow[];
- classLabel: (c: FailureClass) => string;
-}) {
- const { t } = useT("usage");
- const total = rows.reduce((sum, r) => sum + r.count, 0);
- if (total === 0) return null;
-
- return (
- <div className="space-y-2.5">
- {/* Segments are ordered by count desc (the aggregator's order), so the
- bar reads heaviest-first left to right. */}
- <div className="flex h-2 w-full overflow-hidden rounded-full bg-muted">
- {rows.map((row) => (
- <div
- key={row.failureClass}
- className="h-full transition-[width] duration-300 ease-out"
- style={{
- width: `${(row.count / total) * 100}%`,
- backgroundColor: FAILURE_CLASS_COLOR[row.failureClass],
- }}
- />
- ))}
- </div>
- <ul
- aria-label={t(($) => $.errors.mix_label)}
- className="flex flex-wrap items-center gap-x-4 gap-y-1.5"
- >
- {rows.map((row) => (
- <li key={row.failureClass} className="flex items-center gap-1.5">
- <span
- aria-hidden
- className="h-2 w-2 shrink-0 rounded-[2px]"
- style={{ backgroundColor: FAILURE_CLASS_COLOR[row.failureClass] }}
- />
- <span className="text-caption">{classLabel(row.failureClass)}</span>
- <span className="text-caption tabular-nums text-muted-foreground">
- {row.count}
- </span>
- </li>
- ))}
- </ul>
- </div>
- );
-}
-
-/**
- * Raw `failure_reason` values behind the class summary. Unlocalised on
- * purpose: they are the backend's wire enum, and an operator pasting one into
- * a log search or an issue needs the exact string.
- *
- * Two columns on wide viewports — the list runs to ~20 rows at its longest,
- * and the card now has the full page width to spend on it.
- */
-function ReasonList({ rows }: { rows: FailureReasonRow[] }) {
- const { t } = useT("usage");
- return (
- <ul
- aria-label={t(($) => $.errors.codes_label)}
- className="grid grid-cols-1 gap-x-6 gap-y-1.5 sm:grid-cols-2"
- >
- {rows.map((row) => (
- <li key={row.reason} className="flex items-center justify-between gap-2">
- <span className="flex min-w-0 items-center gap-2">
- <span
- aria-hidden
- className="h-2 w-2 shrink-0 rounded-[2px]"
- style={{ backgroundColor: FAILURE_CLASS_COLOR[row.failureClass] }}
- />
- <code className="truncate text-caption text-muted-foreground">
- {row.reason}
- </code>
- </span>
- <span className="shrink-0 text-caption tabular-nums">{row.count}</span>
- </li>
- ))}
- </ul>
- );
-}
-
-/**
- * One offender row, shaped like the leaderboard row directly above this card:
- * identity, then a proportional bar, then one column per number.
- *
- * The bar measures whatever the list is currently sorted by, and the matching
- * column is emphasised — the same lockstep the leaderboard keeps. Before, the
- * bar always measured absolute failures while the loudest number on the row
- * was the rate, so the worst-rate agent could sit near the bottom with one of
- * the shortest bars.
- *
- * The bar is stacked by failure class, which is also the only thing its colour
- * means. A row that fails one way is a solid block; a row failing five ways is
- * visibly striped — a distinction the old single dominant-class badge erased.
- */
-function AgentFailureItem({
- row,
- name,
- maxValue,
- sortBy,
- classLabel,
-}: {
- row: AgentFailureRow;
- name: string | null;
- maxValue: number;
- sortBy: OffenderSort;
- classLabel: (c: FailureClass) => string;
-}) {
- const { t } = useT("usage");
- const wsPaths = useWorkspacePaths();
-
- const segments = FAILURE_CLASSES.filter((c) => row.classes[c] > 0);
- // Text equivalent of the stacked bar. The bar is the only place the class
- // split is rendered now that the badge is gone, so it has to carry a name
- // for screen readers as well as a hover affordance for everyone else.
- const composition = segments
- .map((c) => `${classLabel(c)} ${row.classes[c]}`)
- .join(" · ");
-
- // Clamped, not just scaled: under the Rate ranking a small-sample row is
- // demoted below the leader while still able to carry a higher rate, and an
- // unclamped width would overflow the track.
- const value = OFFENDER_METRIC[sortBy](row);
- const pct = maxValue > 0 ? Math.min(100, (value / maxValue) * 100) : 0;
-
- // Below MIN_RATE_SAMPLE runs the rate is arithmetic, not signal (1/1 is
- // 100%). Those rows sort last under Rate and never take the emphasis that
- // marks the active column, but they keep rendering and say why on hover.
- const weakSample = !hasRateSample(row);
-
- // The row links into the agent's Overview, whose ActivityTab lists recent
- // runs with each failure's reason — the drill-down from "this agent is the
- // problem" to the actual failed runs. NOT the Work tab: that one lists the
- // issues assigned to the agent, which is a different question entirely.
- //
- // An agent with no resolvable name is either hard-deleted or private to
- // someone else; either way there is no page to open and no name to show,
- // so the row degrades to a neutral placeholder. Rendering `row.agentId`
- // here would leak a bare UUID — and, for a private agent, leak its
- // existence and failure profile to a member who cannot see it.
- const label = (
- <span
- className={`block truncate text-caption${name ? "" : " italic text-muted-foreground"}`}
- >
- {name ?? t(($) => $.errors.other_agents)}
- </span>
- );
-
- return (
- <li className={`${OFFENDER_GRID} py-2`}>
- {name ? (
- <AppLink
- href={`${wsPaths.agentDetail(row.agentId)}?view=overview`}
- newTabTitle={name}
- className="min-w-0 hover:underline"
- >
- {label}
- </AppLink>
- ) : (
- label
- )}
- <div className="h-1.5 overflow-hidden rounded-full bg-muted">
- <div
- role="img"
- aria-label={composition}
- title={composition}
- className="flex h-full overflow-hidden rounded-full transition-[width] duration-300 ease-out"
- style={{ width: `${pct}%` }}
- >
- {segments.map((c) => (
- <div
- key={c}
- className="h-full"
- style={{
- width: `${(row.classes[c] / row.failed) * 100}%`,
- backgroundColor: FAILURE_CLASS_COLOR[c],
- }}
- />
- ))}
+ </TabsContent>
</div>
</div>
- <span
- className={`text-right text-caption tabular-nums ${sortBy === "failed" ? "font-medium text-foreground" : "text-muted-foreground"}`}
- >
- {row.failed}
- </span>
- <span className="text-right text-caption tabular-nums text-muted-foreground">
- {row.total}
- </span>
- <span
- title={
- weakSample
- ? t(($) => $.errors.low_sample, { count: MIN_RATE_SAMPLE })
- : undefined
- }
- className={`text-right text-caption tabular-nums ${
- sortBy === "rate" && !weakSample
- ? "font-medium text-foreground"
- : "text-muted-foreground"
- }`}
- >
- {formatRate(row.failed, row.total)}
- </span>
- </li>
- );
-}
-
-// Which metric ranks the leaderboard. Drives row order, progress bar
-// width, and which column header is emphasised — keeping the three in
-// lockstep so the user always sees what the ranking actually measures.
-type LeaderboardSort = "tokens" | "cost" | "time" | "tasks";
-
-const SORT_METRIC: Record<LeaderboardSort, (r: AgentDashboardRow) => number> = {
- tokens: (r) => r.tokens,
- cost: (r) => r.cost,
- time: (r) => r.seconds,
- tasks: (r) => r.taskCount,
-};
-
-// How many agents the leaderboard ranks before collapsing the tail behind a
-// toggle, mirroring the Errors card's top-offenders cap. A workspace with
-// dozens of agents rendered every one of them, which pushed the Errors card a
-// full screen or more below the fold (MUL-5388). Ten answers "who is spending
-// the most" — the tail is reachable via the toggle.
-const LEADERBOARD_LIMIT = 10;
-
-function Leaderboard({
- rows,
- agents,
- deletedAgentCount,
- lessThanMinuteLabel,
-}: {
- rows: AgentDashboardRow[];
- agents: { id: string; name: string }[];
- deletedAgentCount: number;
- lessThanMinuteLabel: string;
-}) {
- const { t } = useT("usage");
- const [sortBy, setSortBy] = useState<LeaderboardSort>("tokens");
- const [showAll, setShowAll] = useState(false);
-
- const sortOptions = useMemo(
- () => [
- { value: "tokens" as const, label: t(($) => $.leaderboard.header_tokens) },
- { value: "cost" as const, label: t(($) => $.leaderboard.header_cost) },
- { value: "time" as const, label: t(($) => $.leaderboard.header_time) },
- { value: "tasks" as const, label: t(($) => $.leaderboard.header_tasks) },
- ],
- [t],
- );
-
- // Re-rank when the metric changes; keep the merged input untouched so
- // upstream `mergeAgentDashboardRows`'s tiebreaker (run time desc) still
- // applies inside an equal-bucket.
- const sortedRows = useMemo(() => {
- const metric = SORT_METRIC[sortBy];
- return rows.toSorted((a, b) => metric(b) - metric(a));
- }, [rows, sortBy]);
-
- // Measured across every row, not just the visible ones, so a bar's width
- // means the same thing collapsed and expanded — the leader always fills the
- // track and nothing re-scales when the tail comes into view.
- const maxValue = useMemo(() => {
- const metric = SORT_METRIC[sortBy];
- return sortedRows.reduce((m, r) => Math.max(m, metric(r)), 0);
- }, [sortedRows, sortBy]);
-
- const visibleRows = showAll
- ? sortedRows
- : sortedRows.slice(0, LEADERBOARD_LIMIT);
-
- // "N agents" counts the rows that actually name an agent. Up to two of the
- // rows are synthetic buckets (deleted, restricted), and subtracting a fixed 1
- // reported one agent too many whenever both were present.
- const namedAgentCount = useMemo(
- () => rows.filter((r) => !isSyntheticAgentRow(r.agentId)).length,
- [rows],
- );
-
- // Active column gets foreground text; others stay muted. Helps the user
- // see "this is what the bar is measuring" at a glance.
- const colClass = (key: LeaderboardSort) =>
- `text-right ${sortBy === key ? "text-foreground" : "text-muted-foreground"}`;
-
- return (
- <div className="rounded-lg border bg-card">
- <div className="flex flex-wrap items-center justify-between gap-3 border-b px-4 pt-4 pb-3">
- <h4 className="text-body font-semibold">{t(($) => $.leaderboard.title)}</h4>
- <div className="flex flex-wrap items-center justify-end gap-3">
- <Segmented
- label={t(($) => $.leaderboard.sort_label)}
- value={sortBy}
- onChange={setSortBy}
- options={sortOptions}
- />
- <span className="text-caption text-muted-foreground">
- {deletedAgentCount > 0
- ? t(($) => $.leaderboard.caption_with_deleted, {
- count: namedAgentCount,
- deleted: deletedAgentCount,
- })
- : t(($) => $.leaderboard.caption, { count: namedAgentCount })}
- </span>
- {/* The caption right beside this already states how many agents the
- window covers, so the toggle carries a count only when
- collapsing — spelling the total out twice reads as two different
- numbers once the deleted-agents bucket splits the caption. */}
- {sortedRows.length > LEADERBOARD_LIMIT ? (
- <button
- type="button"
- onClick={() => setShowAll((v) => !v)}
- className="text-caption text-muted-foreground underline-offset-2 hover:text-foreground hover:underline"
- >
- {showAll
- ? t(($) => $.leaderboard.show_less, { count: LEADERBOARD_LIMIT })
- : t(($) => $.leaderboard.show_all)}
- </button>
- ) : null}
- </div>
- </div>
- {sortedRows.length === 0 ? (
- <p className="px-4 py-8 text-center text-caption text-muted-foreground">
- {t(($) => $.leaderboard.no_data)}
- </p>
- ) : (
- <>
- <div className="grid grid-cols-[minmax(0,1.6fr)_minmax(0,1fr)_5rem_5rem_5rem_4rem] items-center gap-3 border-b px-4 py-2 text-caption font-medium text-muted-foreground">
- <span>{t(($) => $.leaderboard.header_agent)}</span>
- <span />
- <span className={colClass("tokens")}>{t(($) => $.leaderboard.header_tokens)}</span>
- <span className={colClass("cost")}>{t(($) => $.leaderboard.header_cost)}</span>
- <span className={colClass("time")}>{t(($) => $.leaderboard.header_time)}</span>
- <span className={colClass("tasks")}>{t(($) => $.leaderboard.header_tasks)}</span>
- </div>
- {/* A real list, like the Errors card's offender list: the rows are
- now a truncated ranking, so screen readers need the count and the
- item boundaries rather than a bag of divs. */}
- <ul aria-label={t(($) => $.leaderboard.title)} className="divide-y">
- {visibleRows.map((row) => {
- // Two synthetic rows, neither a real agent: both render a neutral
- // placeholder (no avatar fetch / hover card / UUID) instead of
- // looking the id up in the agent list.
- //
- // Only the deleted bucket dashes out Time/Tasks — it genuinely
- // never carries them (see bucketUnknownAgentRows). The server's
- // bucket does: those agents are alive and ran, the server just
- // merged them (MUL-5409), so zeroing their columns would
- // under-report the workspace's run time.
- //
- // Its copy is the neutral "Other agents" rather than anything
- // about permissions, because it covers two populations: agents
- // this viewer may not see, and the hidden system carriers behind
- // agent-builder sessions, which nobody can name — including the
- // admin who owns them.
- const isDeletedBucket = row.agentId === DELETED_AGENTS_ROW_ID;
- const isRestrictedBucket = row.agentId === RESTRICTED_AGENTS_ROW_ID;
- const isBucket = isDeletedBucket || isRestrictedBucket;
- const agent = agents.find((a) => a.id === row.agentId);
- const value = SORT_METRIC[sortBy](row);
- const pct = maxValue > 0 ? (value / maxValue) * 100 : 0;
- return (
- <li
- key={row.agentId}
- className="grid grid-cols-[minmax(0,1.6fr)_minmax(0,1fr)_5rem_5rem_5rem_4rem] items-center gap-3 px-4 py-2"
- >
- <div className="flex min-w-0 items-center gap-2">
- {isBucket ? (
- <>
- <span className="flex h-[22px] w-[22px] shrink-0 items-center justify-center rounded-full bg-muted text-muted-foreground">
- {isDeletedBucket ? (
- <Trash2 className="h-3 w-3" />
- ) : (
- <EyeOff className="h-3 w-3" />
- )}
- </span>
- <span className="truncate text-body font-medium italic text-muted-foreground">
- {isDeletedBucket
- ? t(($) => $.leaderboard.deleted_agents)
- : t(($) => $.leaderboard.other_agents)}
- </span>
- </>
- ) : (
- <>
- <ActorAvatar
- actorType="agent"
- actorId={row.agentId}
- size="md"
- enableHoverCard
- />
- <span className="cursor-pointer truncate text-body font-medium">
- {agent?.name ?? row.agentId}
- </span>
- </>
- )}
- </div>
- <div className="relative h-2 overflow-hidden rounded-full bg-muted">
- <div
- className="h-full rounded-full bg-chart-1 transition-[width] duration-300 ease-out"
- style={{ width: `${pct}%` }}
- />
- </div>
- <div
- className={`text-right text-caption tabular-nums ${sortBy === "tokens" ? "font-medium text-foreground" : "text-muted-foreground"}`}
- >
- {formatTokens(row.tokens)}
- </div>
- <div
- className={`text-right tabular-nums ${sortBy === "cost" ? "text-body font-medium" : "text-caption text-muted-foreground"}`}
- >
- ${row.cost.toFixed(2)}
- </div>
- <div
- className={`text-right text-caption tabular-nums ${sortBy === "time" ? "font-medium text-foreground" : "text-muted-foreground"}`}
- >
- {isDeletedBucket
- ? "—"
- : formatDuration(row.seconds, lessThanMinuteLabel)}
- </div>
- <div
- className={`text-right text-caption tabular-nums ${sortBy === "tasks" ? "font-medium text-foreground" : "text-muted-foreground"}`}
- >
- {isDeletedBucket ? "—" : row.taskCount}
- </div>
- </li>
- );
- })}
- </ul>
- </>
- )}
- </div>
+ </Tabs>
);
}
diff --git a/packages/views/dashboard/components/dashboard-shared.tsx b/packages/views/dashboard/components/dashboard-shared.tsx
new file mode 100644
index 0000000000..a1ad05eef0
--- /dev/null
+++ b/packages/views/dashboard/components/dashboard-shared.tsx
@@ -0,0 +1,135 @@
+"use client";
+
+import {
+ NumberFlow,
+ NumberFlowGroup,
+} from "@multica/ui/components/ui/number-flow";
+import { formatDuration } from "../utils";
+
+// Period selector — mirrors the runtime detail page so users see the same
+// option set across both dashboards. `dims` declares which chart dimensions
+// each range may be drawn at: 1d / 7d at the weekly grain collapse to a single
+// bar, 180d at the daily grain is 180 unreadable bars.
+//
+// 1d semantic: "today" (the natural calendar day from 00:00 in the viewer's
+// timezone), not "the last 24 hours". The `dailyCutoffIso` filter on the page
+// enforces this even at the midnight edge.
+export const TIME_RANGES = [
+ { label: "1d", days: 1, dims: ["daily"] as const },
+ { label: "7d", days: 7, dims: ["daily"] as const },
+ { label: "30d", days: 30, dims: ["daily", "weekly"] as const },
+ { label: "90d", days: 90, dims: ["daily", "weekly"] as const },
+ { label: "180d", days: 180, dims: ["weekly"] as const },
+] as const;
+
+export type TimeRange = (typeof TIME_RANGES)[number]["days"];
+export type Dim = "daily" | "weekly";
+
+/**
+ * Which chart dimensions the current range may be drawn at.
+ *
+ * The constraint between range and dimension used to be enforced in both
+ * directions by two sibling controls in the page header: picking Weekly while
+ * on 1d silently reset the range to 90d, which moved every KPI on the page.
+ * The range is now the page-scoped filter and the dimension is card-scoped, so
+ * the dependency runs one way only — a card offers whichever dimensions its
+ * range allows, and nothing resets. A card-scoped control must never reach up
+ * and change a page-scoped one (MUL-5759).
+ */
+export function dimsForDays(days: TimeRange): readonly Dim[] {
+ return (
+ TIME_RANGES.find((r) => r.days === days)?.dims ?? (["daily"] as const)
+ );
+}
+
+/** Sentinel for "no project filter" — kept distinct from the empty string so
+ * it survives a refactor that ever lets a project be slug-keyed. */
+export const ALL_PROJECTS = "__all__";
+
+/**
+ * Card-local segmented control — the pill toggle used *inside* a card to pick
+ * what that card shows. The page header deliberately uses outline Buttons
+ * instead, so the shape of a control tells you its scope: pills change one
+ * card, buttons change the page.
+ *
+ * shadcn's Tabs is wired for full tab pages with ARIA semantics the compact
+ * toolbar pill doesn't need. Which option is active was expressed only as a
+ * colour swap, which no screen reader can see, so `aria-pressed` carries it
+ * too. `label` is required rather than optional because a naked group of
+ * toggle buttons is announced without saying WHAT it toggles — "Rate, pressed"
+ * is useless until you know the group is the offender ranking. Toggle buttons
+ * rather than a radiogroup: a radiogroup owes the user arrow-key roving focus,
+ * and these are tab stops wherever they appear in the page.
+ */
+export function Segmented<T extends string | number>({
+ value,
+ onChange,
+ options,
+ label,
+}: {
+ value: T;
+ onChange: (v: T) => void;
+ options: readonly { label: string; value: T }[];
+ label: string;
+}) {
+ return (
+ <div
+ role="group"
+ aria-label={label}
+ className="inline-flex items-center gap-0.5 rounded-md bg-muted p-0.5"
+ >
+ {options.map((o) => (
+ <button
+ key={String(o.value)}
+ type="button"
+ aria-pressed={o.value === value}
+ onClick={() => onChange(o.value)}
+ className={`rounded-sm px-2.5 py-1 text-caption font-medium transition-colors ${
+ o.value === value
+ ? "bg-background text-foreground shadow-sm"
+ : "text-muted-foreground hover:text-foreground"
+ }`}
+ >
+ {o.label}
+ </button>
+ ))}
+ </div>
+ );
+}
+
+export function DurationNumberFlow({
+ seconds,
+ lessThanMinuteLabel,
+ locales,
+}: {
+ seconds: number;
+ lessThanMinuteLabel: string;
+ locales?: Intl.LocalesArgument;
+}) {
+ const label = formatDuration(seconds, lessThanMinuteLabel);
+ const parts = Array.from(label.matchAll(/(\d+)([a-z]+)/gi), (match) => ({
+ value: Number(match[1]),
+ unit: match[2] ?? "",
+ }));
+
+ if (parts.length === 0) return label;
+
+ return (
+ <>
+ <span className="sr-only">{label}</span>
+ <NumberFlowGroup>
+ <span aria-hidden className="inline-flex items-baseline gap-1">
+ {parts.map((part) => (
+ <NumberFlow
+ key={part.unit}
+ value={part.value}
+ locales={locales}
+ suffix={part.unit}
+ format={{ maximumFractionDigits: 0, useGrouping: false }}
+ />
+ ))}
+ </span>
+ </NumberFlowGroup>
+ </>
+ );
+}
diff --git a/packages/views/dashboard/components/dim-segmented.tsx b/packages/views/dashboard/components/dim-segmented.tsx
new file mode 100644
index 0000000000..fff065e762
--- /dev/null
+++ b/packages/views/dashboard/components/dim-segmented.tsx
@@ -0,0 +1,44 @@
+"use client";
+
+import { useT } from "../../i18n";
+import { Segmented, type Dim } from "./dashboard-shared";
+
+/**
+ * Daily / Weekly, scoped to the card it sits in.
+ *
+ * Renders only the dimensions the page's current range allows, which is what
+ * removed the hidden coupling this control used to carry: it lived in the page
+ * header next to the range, and picking a dimension the range disallowed
+ * silently rewrote the range — moving every KPI on the page (MUL-5759). With
+ * the illegal options simply absent there is nothing to reset.
+ *
+ * A single allowed dimension renders nothing at all: a one-option toggle is a
+ * control that cannot be operated, and the chart title ("Weekly cost") already
+ * says which grain is on screen.
+ */
+export function DimSegmented({
+ allowedDims,
+ value,
+ onChange,
+}: {
+ allowedDims: readonly Dim[];
+ value: Dim;
+ onChange: (dim: Dim) => void;
+}) {
+ const { t } = useT("usage");
+ if (allowedDims.length < 2) return null;
+
+ const label: Record<Dim, string> = {
+ daily: t(($) => $.dim.daily),
+ weekly: t(($) => $.dim.weekly),
+ };
+
+ return (
+ <Segmented
+ label={t(($) => $.dim.label)}
+ value={value}
+ onChange={onChange}
+ options={allowedDims.map((dim) => ({ label: label[dim], value: dim }))}
+ />
+ );
+}
diff --git a/packages/views/dashboard/components/errors-tab.tsx b/packages/views/dashboard/components/errors-tab.tsx
new file mode 100644
index 0000000000..6f267e1345
--- /dev/null
+++ b/packages/views/dashboard/components/errors-tab.tsx
@@ -0,0 +1,591 @@
+"use client";
+
+import { useMemo, useState } from "react";
+import { BarChart3 } from "lucide-react";
+import { NumberFlow } from "@multica/ui/components/ui/number-flow";
+import { FAILURE_CLASSES, type FailureClass } from "@multica/core/dashboard";
+import { useWorkspacePaths } from "@multica/core/paths";
+import { KpiCard } from "../../runtimes/components/shared";
+import {
+ DailyErrorsChart,
+ WeeklyErrorsChart,
+ FAILURE_CLASS_COLOR,
+ formatRate,
+} from "../../runtimes/components/charts";
+import { AppLink } from "../../navigation";
+import { useT } from "../../i18n";
+import {
+ aggregateDailyErrors,
+ aggregateWeeklyErrors,
+ hasRateSample,
+ MIN_RATE_SAMPLE,
+ OFFENDER_METRIC,
+ sortAgentFailures,
+ type AgentFailureRow,
+ type FailureClassRow,
+ type FailureReasonRow,
+ type FailureTotals,
+ type OffenderSort,
+} from "../utils";
+import { type Dim } from "./dashboard-shared";
+import { Segmented } from "./dashboard-shared";
+import { DimSegmented } from "./dim-segmented";
+
+// How many offenders the list shows before collapsing the tail behind a
+// toggle. The list is ranked by absolute failure count, so the tail is
+// agents that failed once or twice — real, but not what anyone opens this
+// view to see.
+const TOP_OFFENDER_LIMIT = 8;
+
+// Shared by the offender column header and every offender row, so the two
+// cannot drift out of alignment.
+const OFFENDER_GRID =
+ "grid grid-cols-[minmax(0,1.4fr)_minmax(0,1fr)_4rem_4rem_4rem] items-center gap-3";
+
+// Translated label for a failure class. The mapping is a switch rather than
+// an index into a lookup object so the type checker flags a class added to
+// FAILURE_CLASSES without matching copy.
+function useFailureClassLabel(): (c: FailureClass) => string {
+ const { t } = useT("usage");
+ return (c) => {
+ switch (c) {
+ case "auth":
+ return t(($) => $.errors.class.auth);
+ case "rate_limit":
+ return t(($) => $.errors.class.rate_limit);
+ case "timeout":
+ return t(($) => $.errors.class.timeout);
+ case "provider":
+ return t(($) => $.errors.class.provider);
+ case "runtime":
+ return t(($) => $.errors.class.runtime);
+ case "agent":
+ return t(($) => $.errors.class.agent);
+ case "other":
+ return t(($) => $.errors.class.other);
+ }
+ };
+}
+
+/**
+ * "What broke", as a full view rather than one compressed card at the bottom
+ * of the spend page.
+ *
+ * Reads top-down the way the question is actually asked: how bad is it (KPIs),
+ * when did it happen (trend), what kind of thing broke (mix), and who it broke
+ * for (offenders). Each of those used to be a subsection of a single card, or
+ * a fifth option on a toggle whose other four were spend metrics.
+ */
+export function ErrorsTab({
+ days,
+ allowedDims,
+ totals,
+ classRows,
+ reasonRows,
+ agentRows,
+ dailyErrors,
+ weeklyErrors,
+ agents,
+ locales,
+}: {
+ days: number;
+ allowedDims: readonly Dim[];
+ totals: FailureTotals;
+ classRows: FailureClassRow[];
+ reasonRows: FailureReasonRow[];
+ agentRows: AgentFailureRow[];
+ dailyErrors: ReturnType<typeof aggregateDailyErrors>;
+ weeklyErrors: ReturnType<typeof aggregateWeeklyErrors>;
+ agents: { id: string; name: string }[];
+ locales?: Intl.LocalesArgument;
+}) {
+ const { t } = useT("usage");
+ const classLabel = useFailureClassLabel();
+
+ // Agents affected counts the rows of the offender list below, so the tile and
+ // the list can never disagree. Agents this viewer cannot resolve are already
+ // folded into one anonymous row upstream, which makes this a lower bound when
+ // several hidden agents fail — the alternative, counting them individually,
+ // would leak how many private agents exist.
+ const affectedAgents = agentRows.length;
+ const worst = agentRows[0];
+ const worstName = worst
+ ? (agents.find((a) => a.id === worst.agentId)?.name ??
+ t(($) => $.errors.other_agents))
+ : null;
+
+ return (
+ <div className="space-y-5">
+ <div className="grid grid-cols-1 divide-y rounded-lg border bg-card sm:grid-cols-3 sm:divide-x sm:divide-y-0">
+ <KpiCard
+ label={t(($) => $.errors.kpi_failed_label, { days })}
+ value={
+ <NumberFlow
+ value={totals.failed}
+ locales={locales}
+ format={{ maximumFractionDigits: 0 }}
+ aria-label={String(totals.failed)}
+ />
+ }
+ hint={t(($) => $.errors.kpi_failed_hint, { total: totals.total })}
+ />
+ {/* The rate carries its denominator right below it. The Tasks tile on
+ the Usage tab quotes a different, smaller failure count — it only
+ counts tasks that actually started — and two bare percentages from
+ two denominators read as a contradiction unless each says what it
+ is counting. */}
+ <KpiCard
+ label={t(($) => $.errors.kpi_rate_label, { days })}
+ value={formatRate(totals.failed, totals.total)}
+ hint={t(($) => $.errors.summary, {
+ failed: totals.failed,
+ total: totals.total,
+ rate: formatRate(totals.failed, totals.total),
+ })}
+ />
+ <KpiCard
+ label={t(($) => $.errors.kpi_agents_label, { days })}
+ value={
+ <NumberFlow
+ value={affectedAgents}
+ locales={locales}
+ format={{ maximumFractionDigits: 0 }}
+ aria-label={String(affectedAgents)}
+ />
+ }
+ hint={
+ worst && worstName
+ ? t(($) => $.errors.kpi_agents_hint, {
+ name: worstName,
+ count: worst.failed,
+ })
+ : undefined
+ }
+ />
+ </div>
+
+ {totals.failed === 0 ? (
+ <div className="flex flex-col items-center rounded-lg border border-dashed py-12 text-center">
+ <BarChart3 className="h-6 w-6 text-faint-foreground" />
+ <p className="mt-3 text-caption text-muted-foreground">
+ {t(($) => $.errors.no_data)}
+ </p>
+ </div>
+ ) : (
+ <>
+ <ErrorTrendCard
+ allowedDims={allowedDims}
+ dailyErrors={dailyErrors}
+ weeklyErrors={weeklyErrors}
+ />
+ <FailureMixCard
+ totals={totals}
+ classRows={classRows}
+ reasonRows={reasonRows}
+ classLabel={classLabel}
+ />
+ <OffendersCard
+ agentRows={agentRows}
+ agents={agents}
+ classLabel={classLabel}
+ />
+ </>
+ )}
+ </div>
+ );
+}
+
+/** Failures over time, on the same x-axis the spend charts use. Promoted from
+ * the fifth option of the spend toggle, where seeing failures meant hiding
+ * spend. */
+function ErrorTrendCard({
+ allowedDims,
+ dailyErrors,
+ weeklyErrors,
+}: {
+ allowedDims: readonly Dim[];
+ dailyErrors: ReturnType<typeof aggregateDailyErrors>;
+ weeklyErrors: ReturnType<typeof aggregateWeeklyErrors>;
+}) {
+ const { t } = useT("usage");
+ const [dim, setDim] = useState<Dim>("daily");
+ const effectiveDim: Dim = allowedDims.includes(dim) ? dim : allowedDims[0]!;
+ const weekly = effectiveDim === "weekly";
+
+ return (
+ <div className="rounded-lg border bg-card p-4">
+ <div className="mb-3 flex flex-wrap items-center justify-between gap-3">
+ <h4 className="text-body font-semibold">
+ {weekly ? t(($) => $.weekly.title_errors) : t(($) => $.daily.title_errors)}
+ </h4>
+ <DimSegmented allowedDims={allowedDims} value={effectiveDim} onChange={setDim} />
+ </div>
+ <div className="min-h-[240px]">
+ {weekly ? (
+ <WeeklyErrorsChart data={weeklyErrors} />
+ ) : (
+ <DailyErrorsChart data={dailyErrors} />
+ )}
+ </div>
+ </div>
+ );
+}
+
+/** What kind of thing broke: the class mix, with the raw wire enums one click
+ * away. */
+function FailureMixCard({
+ totals,
+ classRows,
+ reasonRows,
+ classLabel,
+}: {
+ totals: FailureTotals;
+ classRows: FailureClassRow[];
+ reasonRows: FailureReasonRow[];
+ classLabel: (c: FailureClass) => string;
+}) {
+ const { t } = useT("usage");
+ const [showReasons, setShowReasons] = useState(false);
+
+ return (
+ <div className="rounded-lg border bg-card">
+ <div className="flex flex-wrap items-center justify-between gap-3 border-b px-4 pt-4 pb-3">
+ {/* Spells out its own denominator: the rate tile above quotes a rate
+ over every run, this section splits the failures alone. */}
+ <h4 className="text-body font-semibold">
+ {t(($) => $.errors.mix_title, { failed: totals.failed })}
+ </h4>
+ <button
+ type="button"
+ onClick={() => setShowReasons((v) => !v)}
+ className="text-caption text-muted-foreground underline-offset-2 hover:text-foreground hover:underline"
+ >
+ {showReasons
+ ? t(($) => $.errors.hide_reasons)
+ : t(($) => $.errors.show_reasons)}
+ </button>
+ </div>
+ <div className="p-4">
+ {showReasons ? (
+ <ReasonList rows={reasonRows} />
+ ) : (
+ <ClassComposition rows={classRows} classLabel={classLabel} />
+ )}
+ </div>
+ </div>
+ );
+}
+
+/** Who it broke for. */
+function OffendersCard({
+ agentRows,
+ agents,
+ classLabel,
+}: {
+ agentRows: AgentFailureRow[];
+ agents: { id: string; name: string }[];
+ classLabel: (c: FailureClass) => string;
+}) {
+ const { t } = useT("usage");
+ const [showAllAgents, setShowAllAgents] = useState(false);
+ const [sortBy, setSortBy] = useState<OffenderSort>("failed");
+
+ const sortOptions = useMemo(
+ () => [
+ { value: "failed" as const, label: t(($) => $.errors.sort_failed) },
+ { value: "rate" as const, label: t(($) => $.errors.sort_rate) },
+ ],
+ [t],
+ );
+
+ const sortedAgents = useMemo(
+ () => sortAgentFailures(agentRows, sortBy),
+ [agentRows, sortBy],
+ );
+
+ // The leader fills the track, measured over every row rather than the
+ // visible ones so a bar means the same thing collapsed and expanded. Reading
+ // it off the leader (instead of a max over the raw rows) also keeps the Rate
+ // scale usable: a demoted small-sample row can out-rate the leader, and
+ // scaling to it would squash every meaningful bar to a sliver.
+ const leader = sortedAgents[0];
+ const maxValue = leader ? OFFENDER_METRIC[sortBy](leader) : 0;
+
+ const visibleAgents = showAllAgents
+ ? sortedAgents
+ : sortedAgents.slice(0, TOP_OFFENDER_LIMIT);
+
+ return (
+ <div className="rounded-lg border bg-card">
+ <div className="flex flex-wrap items-center justify-between gap-3 border-b px-4 pt-4 pb-3">
+ <h4 className="text-body font-semibold">{t(($) => $.errors.by_agent)}</h4>
+ <div className="flex flex-wrap items-center justify-end gap-3">
+ <Segmented
+ label={t(($) => $.errors.sort_label)}
+ value={sortBy}
+ onChange={setSortBy}
+ options={sortOptions}
+ />
+ {sortedAgents.length > TOP_OFFENDER_LIMIT ? (
+ <button
+ type="button"
+ onClick={() => setShowAllAgents((v) => !v)}
+ className="text-caption text-muted-foreground underline-offset-2 hover:text-foreground hover:underline"
+ >
+ {showAllAgents
+ ? t(($) => $.errors.show_less, { count: TOP_OFFENDER_LIMIT })
+ : t(($) => $.errors.show_all, { count: sortedAgents.length })}
+ </button>
+ ) : null}
+ </div>
+ </div>
+ <div className="p-4 pt-0">
+ {/* Column headers, as on the leaderboard: `4 / 10 · 40%` was one
+ unlabelled blob and the reader had to guess which number was
+ which. The active metric's column is emphasised so it is
+ obvious what the ranking and the bars measure. */}
+ {sortedAgents.length > 0 ? (
+ <div
+ className={`${OFFENDER_GRID} border-b py-2 text-caption font-medium text-muted-foreground`}
+ >
+ <span>{t(($) => $.errors.header_agent)}</span>
+ <span />
+ <span
+ className={`text-right ${sortBy === "failed" ? "text-foreground" : ""}`}
+ >
+ {t(($) => $.errors.header_failed)}
+ </span>
+ <span className="text-right">{t(($) => $.errors.header_runs)}</span>
+ <span
+ className={`text-right ${sortBy === "rate" ? "text-foreground" : ""}`}
+ >
+ {t(($) => $.errors.header_rate)}
+ </span>
+ </div>
+ ) : null}
+ <ul aria-label={t(($) => $.errors.by_agent)} className="divide-y">
+ {visibleAgents.map((row) => (
+ <AgentFailureItem
+ key={row.agentId}
+ row={row}
+ name={agents.find((a) => a.id === row.agentId)?.name ?? null}
+ maxValue={maxValue}
+ sortBy={sortBy}
+ classLabel={classLabel}
+ />
+ ))}
+ </ul>
+ </div>
+ </div>
+ );
+}
+
+/**
+ * Class breakdown as one 100%-stacked bar plus a legend.
+ *
+ * The question this answers is "what is the mix", and a single bar shows
+ * share-of-total directly — with separate bars the reader has to compare
+ * lengths and mentally total them.
+ */
+function ClassComposition({
+ rows,
+ classLabel,
+}: {
+ rows: FailureClassRow[];
+ classLabel: (c: FailureClass) => string;
+}) {
+ const { t } = useT("usage");
+ const total = rows.reduce((sum, r) => sum + r.count, 0);
+ if (total === 0) return null;
+
+ return (
+ <div className="space-y-2.5">
+ {/* Segments are ordered by count desc (the aggregator's order), so the
+ bar reads heaviest-first left to right. */}
+ <div className="flex h-2 w-full overflow-hidden rounded-full bg-muted">
+ {rows.map((row) => (
+ <div
+ key={row.failureClass}
+ className="h-full transition-[width] duration-300 ease-out"
+ style={{
+ width: `${(row.count / total) * 100}%`,
+ backgroundColor: FAILURE_CLASS_COLOR[row.failureClass],
+ }}
+ />
+ ))}
+ </div>
+ <ul
+ aria-label={t(($) => $.errors.mix_label)}
+ className="flex flex-wrap items-center gap-x-4 gap-y-1.5"
+ >
+ {rows.map((row) => (
+ <li key={row.failureClass} className="flex items-center gap-1.5">
+ <span
+ aria-hidden
+ className="h-2 w-2 shrink-0 rounded-[2px]"
+ style={{ backgroundColor: FAILURE_CLASS_COLOR[row.failureClass] }}
+ />
+ <span className="text-caption">{classLabel(row.failureClass)}</span>
+ <span className="text-caption tabular-nums text-muted-foreground">
+ {row.count}
+ </span>
+ </li>
+ ))}
+ </ul>
+ </div>
+ );
+}
+
+/**
+ * Raw `failure_reason` values behind the class summary. Unlocalised on
+ * purpose: they are the backend's wire enum, and an operator pasting one into
+ * a log search or an issue needs the exact string.
+ */
+function ReasonList({ rows }: { rows: FailureReasonRow[] }) {
+ const { t } = useT("usage");
+ return (
+ <ul
+ aria-label={t(($) => $.errors.codes_label)}
+ className="grid grid-cols-1 gap-x-6 gap-y-1.5 sm:grid-cols-2"
+ >
+ {rows.map((row) => (
+ <li key={row.reason} className="flex items-center justify-between gap-2">
+ <span className="flex min-w-0 items-center gap-2">
+ <span
+ aria-hidden
+ className="h-2 w-2 shrink-0 rounded-[2px]"
+ style={{ backgroundColor: FAILURE_CLASS_COLOR[row.failureClass] }}
+ />
+ <code className="truncate text-caption text-muted-foreground">
+ {row.reason}
+ </code>
+ </span>
+ <span className="shrink-0 text-caption tabular-nums">{row.count}</span>
+ </li>
+ ))}
+ </ul>
+ );
+}
+
+/**
+ * One offender row, shaped like the leaderboard row on the Usage tab:
+ * identity, then a proportional bar, then one column per number.
+ *
+ * The bar measures whatever the list is currently sorted by, and the matching
+ * column is emphasised — the same lockstep the leaderboard keeps.
+ *
+ * The bar is stacked by failure class, which is also the only thing its colour
+ * means. A row that fails one way is a solid block; a row failing five ways is
+ * visibly striped — a distinction a single dominant-class badge erased.
+ */
+function AgentFailureItem({
+ row,
+ name,
+ maxValue,
+ sortBy,
+ classLabel,
+}: {
+ row: AgentFailureRow;
+ name: string | null;
+ maxValue: number;
+ sortBy: OffenderSort;
+ classLabel: (c: FailureClass) => string;
+}) {
+ const { t } = useT("usage");
+ const wsPaths = useWorkspacePaths();
+
+ const segments = FAILURE_CLASSES.filter((c) => row.classes[c] > 0);
+ // Text equivalent of the stacked bar. The bar is the only place the class
+ // split is rendered, so it has to carry a name for screen readers as well as
+ // a hover affordance for everyone else.
+ const composition = segments
+ .map((c) => `${classLabel(c)} ${row.classes[c]}`)
+ .join(" · ");
+
+ // Clamped, not just scaled: under the Rate ranking a small-sample row is
+ // demoted below the leader while still able to carry a higher rate, and an
+ // unclamped width would overflow the track.
+ const value = OFFENDER_METRIC[sortBy](row);
+ const pct = maxValue > 0 ? Math.min(100, (value / maxValue) * 100) : 0;
+
+ // Below MIN_RATE_SAMPLE runs the rate is arithmetic, not signal (1/1 is
+ // 100%). Those rows sort last under Rate and never take the emphasis that
+ // marks the active column, but they keep rendering and say why on hover.
+ const weakSample = !hasRateSample(row);
+
+ // The row links into the agent's Overview, whose ActivityTab lists recent
+ // runs with each failure's reason — the drill-down from "this agent is the
+ // problem" to the actual failed runs. NOT the Work tab: that one lists the
+ // issues assigned to the agent, which is a different question entirely.
+ //
+ // An agent with no resolvable name is either hard-deleted or private to
+ // someone else; either way there is no page to open and no name to show,
+ // so the row degrades to a neutral placeholder. Rendering `row.agentId`
+ // here would leak a bare UUID — and, for a private agent, leak its
+ // existence and failure profile to a member who cannot see it.
+ const label = (
+ <span
+ className={`block truncate text-caption${name ? "" : " italic text-muted-foreground"}`}
+ >
+ {name ?? t(($) => $.errors.other_agents)}
+ </span>
+ );
+
+ return (
+ <li className={`${OFFENDER_GRID} py-2`}>
+ {name ? (
+ <AppLink
+ href={`${wsPaths.agentDetail(row.agentId)}?view=overview`}
+ newTabTitle={name}
+ className="min-w-0 hover:underline"
+ >
+ {label}
+ </AppLink>
+ ) : (
+ label
+ )}
+ <div className="h-1.5 overflow-hidden rounded-full bg-muted">
+ <div
+ role="img"
+ aria-label={composition}
+ title={composition}
+ className="flex h-full overflow-hidden rounded-full transition-[width] duration-300 ease-out"
+ style={{ width: `${pct}%` }}
+ >
+ {segments.map((c) => (
+ <div
+ key={c}
+ className="h-full"
+ style={{
+ width: `${(row.classes[c] / row.failed) * 100}%`,
+ backgroundColor: FAILURE_CLASS_COLOR[c],
+ }}
+ />
+ ))}
+ </div>
+ </div>
+ <span
+ className={`text-right text-caption tabular-nums ${sortBy === "failed" ? "font-medium text-foreground" : "text-muted-foreground"}`}
+ >
+ {row.failed}
+ </span>
+ <span className="text-right text-caption tabular-nums text-muted-foreground">
+ {row.total}
+ </span>
+ <span
+ title={
+ weakSample
+ ? t(($) => $.errors.low_sample, { count: MIN_RATE_SAMPLE })
+ : undefined
+ }
+ className={`text-right text-caption tabular-nums ${
+ sortBy === "rate" && !weakSample
+ ? "font-medium text-foreground"
+ : "text-muted-foreground"
+ }`}
+ >
+ {formatRate(row.failed, row.total)}
+ </span>
+ </li>
+ );
+}
diff --git a/packages/views/dashboard/components/leaderboard.tsx b/packages/views/dashboard/components/leaderboard.tsx
new file mode 100644
index 0000000000..edcba285de
--- /dev/null
+++ b/packages/views/dashboard/components/leaderboard.tsx
@@ -0,0 +1,243 @@
+"use client";
+
+import { useMemo, useState } from "react";
+import { EyeOff, Trash2 } from "lucide-react";
+import { ActorAvatar } from "../../common/actor-avatar";
+import { formatTokens } from "../../runtimes/utils";
+import { useT } from "../../i18n";
+import {
+ DELETED_AGENTS_ROW_ID,
+ formatDuration,
+ isSyntheticAgentRow,
+ RESTRICTED_AGENTS_ROW_ID,
+ type AgentDashboardRow,
+} from "../utils";
+import { Segmented } from "./dashboard-shared";
+
+// Which metric ranks the leaderboard. Drives row order, progress bar
+// width, and which column header is emphasised — keeping the three in
+// lockstep so the user always sees what the ranking actually measures.
+type LeaderboardSort = "tokens" | "cost" | "time" | "tasks";
+
+const SORT_METRIC: Record<LeaderboardSort, (r: AgentDashboardRow) => number> = {
+ tokens: (r) => r.tokens,
+ cost: (r) => r.cost,
+ time: (r) => r.seconds,
+ tasks: (r) => r.taskCount,
+};
+
+// How many agents the leaderboard ranks before collapsing the tail behind a
+// toggle, mirroring the offender list's cap. A workspace with dozens of agents
+// rendered every one of them, which pushed everything below it a full screen or
+// more down the page (MUL-5388). Ten answers "who is spending the most" — the
+// tail is reachable via the toggle.
+const LEADERBOARD_LIMIT = 10;
+
+const LEADERBOARD_GRID =
+ "grid grid-cols-[minmax(0,1.6fr)_minmax(0,1fr)_5rem_5rem_5rem_4rem] items-center gap-3";
+
+export function Leaderboard({
+ rows,
+ agents,
+ deletedAgentCount,
+ lessThanMinuteLabel,
+}: {
+ rows: AgentDashboardRow[];
+ agents: { id: string; name: string }[];
+ deletedAgentCount: number;
+ lessThanMinuteLabel: string;
+}) {
+ const { t } = useT("usage");
+ const [sortBy, setSortBy] = useState<LeaderboardSort>("tokens");
+ const [showAll, setShowAll] = useState(false);
+
+ const sortOptions = useMemo(
+ () => [
+ { value: "tokens" as const, label: t(($) => $.leaderboard.header_tokens) },
+ { value: "cost" as const, label: t(($) => $.leaderboard.header_cost) },
+ { value: "time" as const, label: t(($) => $.leaderboard.header_time) },
+ { value: "tasks" as const, label: t(($) => $.leaderboard.header_tasks) },
+ ],
+ [t],
+ );
+
+ // Re-rank when the metric changes; keep the merged input untouched so
+ // upstream `mergeAgentDashboardRows`'s tiebreaker (run time desc) still
+ // applies inside an equal-bucket.
+ const sortedRows = useMemo(() => {
+ const metric = SORT_METRIC[sortBy];
+ return rows.toSorted((a, b) => metric(b) - metric(a));
+ }, [rows, sortBy]);
+
+ // Measured across every row, not just the visible ones, so a bar's width
+ // means the same thing collapsed and expanded — the leader always fills the
+ // track and nothing re-scales when the tail comes into view.
+ const maxValue = useMemo(() => {
+ const metric = SORT_METRIC[sortBy];
+ return sortedRows.reduce((m, r) => Math.max(m, metric(r)), 0);
+ }, [sortedRows, sortBy]);
+
+ const visibleRows = showAll
+ ? sortedRows
+ : sortedRows.slice(0, LEADERBOARD_LIMIT);
+
+ // "N agents" counts the rows that actually name an agent. Up to two of the
+ // rows are synthetic buckets (deleted, restricted), and subtracting a fixed 1
+ // reported one agent too many whenever both were present.
+ const namedAgentCount = useMemo(
+ () => rows.filter((r) => !isSyntheticAgentRow(r.agentId)).length,
+ [rows],
+ );
+
+ // Active column gets foreground text; others stay muted. Helps the user
+ // see "this is what the bar is measuring" at a glance.
+ const colClass = (key: LeaderboardSort) =>
+ `text-right ${sortBy === key ? "text-foreground" : "text-muted-foreground"}`;
+
+ return (
+ <div className="rounded-lg border bg-card">
+ <div className="flex flex-wrap items-center justify-between gap-3 border-b px-4 pt-4 pb-3">
+ <h4 className="text-body font-semibold">{t(($) => $.leaderboard.title)}</h4>
+ <div className="flex flex-wrap items-center justify-end gap-3">
+ <Segmented
+ label={t(($) => $.leaderboard.sort_label)}
+ value={sortBy}
+ onChange={setSortBy}
+ options={sortOptions}
+ />
+ <span className="text-caption text-muted-foreground">
+ {deletedAgentCount > 0
+ ? t(($) => $.leaderboard.caption_with_deleted, {
+ count: namedAgentCount,
+ deleted: deletedAgentCount,
+ })
+ : t(($) => $.leaderboard.caption, { count: namedAgentCount })}
+ </span>
+ {/* The caption right beside this already states how many agents the
+ window covers, so the toggle carries a count only when
+ collapsing — spelling the total out twice reads as two different
+ numbers once the deleted-agents bucket splits the caption. */}
+ {sortedRows.length > LEADERBOARD_LIMIT ? (
+ <button
+ type="button"
+ onClick={() => setShowAll((v) => !v)}
+ className="text-caption text-muted-foreground underline-offset-2 hover:text-foreground hover:underline"
+ >
+ {showAll
+ ? t(($) => $.leaderboard.show_less, { count: LEADERBOARD_LIMIT })
+ : t(($) => $.leaderboard.show_all)}
+ </button>
+ ) : null}
+ </div>
+ </div>
+ {sortedRows.length === 0 ? (
+ <p className="px-4 py-8 text-center text-caption text-muted-foreground">
+ {t(($) => $.leaderboard.no_data)}
+ </p>
+ ) : (
+ <>
+ <div
+ className={`${LEADERBOARD_GRID} border-b px-4 py-2 text-caption font-medium text-muted-foreground`}
+ >
+ <span>{t(($) => $.leaderboard.header_agent)}</span>
+ <span />
+ <span className={colClass("tokens")}>{t(($) => $.leaderboard.header_tokens)}</span>
+ <span className={colClass("cost")}>{t(($) => $.leaderboard.header_cost)}</span>
+ <span className={colClass("time")}>{t(($) => $.leaderboard.header_time)}</span>
+ <span className={colClass("tasks")}>{t(($) => $.leaderboard.header_tasks)}</span>
+ </div>
+ {/* A real list, like the offender list on the Errors tab: the rows are
+ a truncated ranking, so screen readers need the count and the
+ item boundaries rather than a bag of divs. */}
+ <ul aria-label={t(($) => $.leaderboard.title)} className="divide-y">
+ {visibleRows.map((row) => {
+ // Two synthetic rows, neither a real agent: both render a neutral
+ // placeholder (no avatar fetch / hover card / UUID) instead of
+ // looking the id up in the agent list.
+ //
+ // Only the deleted bucket dashes out Time/Tasks — it genuinely
+ // never carries them (see bucketUnknownAgentRows). The server's
+ // bucket does: those agents are alive and ran, the server just
+ // merged them (MUL-5409), so zeroing their columns would
+ // under-report the workspace's run time.
+ //
+ // Its copy is the neutral "Other agents" rather than anything
+ // about permissions, because it covers two populations: agents
+ // this viewer may not see, and the hidden system carriers behind
+ // agent-builder sessions, which nobody can name — including the
+ // admin who owns them.
+ const isDeletedBucket = row.agentId === DELETED_AGENTS_ROW_ID;
+ const isRestrictedBucket = row.agentId === RESTRICTED_AGENTS_ROW_ID;
+ const isBucket = isDeletedBucket || isRestrictedBucket;
+ const agent = agents.find((a) => a.id === row.agentId);
+ const value = SORT_METRIC[sortBy](row);
+ const pct = maxValue > 0 ? (value / maxValue) * 100 : 0;
+ return (
+ <li key={row.agentId} className={`${LEADERBOARD_GRID} px-4 py-2`}>
+ <div className="flex min-w-0 items-center gap-2">
+ {isBucket ? (
+ <>
+ <span className="flex h-[22px] w-[22px] shrink-0 items-center justify-center rounded-full bg-muted text-muted-foreground">
+ {isDeletedBucket ? (
+ <Trash2 className="h-3 w-3" />
+ ) : (
+ <EyeOff className="h-3 w-3" />
+ )}
+ </span>
+ <span className="truncate text-body font-medium italic text-muted-foreground">
+ {isDeletedBucket
+ ? t(($) => $.leaderboard.deleted_agents)
+ : t(($) => $.leaderboard.other_agents)}
+ </span>
+ </>
+ ) : (
+ <>
+ <ActorAvatar
+ actorType="agent"
+ actorId={row.agentId}
+ size="md"
+ enableHoverCard
+ />
+ <span className="cursor-pointer truncate text-body font-medium">
+ {agent?.name ?? row.agentId}
+ </span>
+ </>
+ )}
+ </div>
+ <div className="relative h-2 overflow-hidden rounded-full bg-muted">
+ <div
+ className="h-full rounded-full bg-chart-1 transition-[width] duration-300 ease-out"
+ style={{ width: `${pct}%` }}
+ />
+ </div>
+ <div
+ className={`text-right text-caption tabular-nums ${sortBy === "tokens" ? "font-medium text-foreground" : "text-muted-foreground"}`}
+ >
+ {formatTokens(row.tokens)}
+ </div>
+ <div
+ className={`text-right tabular-nums ${sortBy === "cost" ? "text-body font-medium" : "text-caption text-muted-foreground"}`}
+ >
+ ${row.cost.toFixed(2)}
+ </div>
+ <div
+ className={`text-right text-caption tabular-nums ${sortBy === "time" ? "font-medium text-foreground" : "text-muted-foreground"}`}
+ >
+ {isDeletedBucket
+ ? "—"
+ : formatDuration(row.seconds, lessThanMinuteLabel)}
+ </div>
+ <div
+ className={`text-right text-caption tabular-nums ${sortBy === "tasks" ? "font-medium text-foreground" : "text-muted-foreground"}`}
+ >
+ {isDeletedBucket ? "—" : row.taskCount}
+ </div>
+ </li>
+ );
+ })}
+ </ul>
+ </>
+ )}
+ </div>
+ );
+}
diff --git a/packages/views/dashboard/components/usage-trend-card.tsx b/packages/views/dashboard/components/usage-trend-card.tsx
new file mode 100644
index 0000000000..974bcf90ac
--- /dev/null
+++ b/packages/views/dashboard/components/usage-trend-card.tsx
@@ -0,0 +1,170 @@
+"use client";
+
+import { useState } from "react";
+import { BarChart3 } from "lucide-react";
+import {
+ DailyCostChart,
+ DailyTokensChart,
+ DailyTimeChart,
+ DailyTasksChart,
+ WeeklyCostChart,
+ WeeklyTokensChart,
+ WeeklyTimeChart,
+ WeeklyTasksChart,
+} from "../../runtimes/components/charts";
+import { aggregateByWeek } from "../../runtimes/utils";
+import { useT } from "../../i18n";
+import {
+ aggregateDailyCost,
+ aggregateDailyTasks,
+ aggregateDailyTime,
+ aggregateDailyTokens,
+ aggregateWeeklyTasks,
+ aggregateWeeklyTime,
+ formatDuration,
+} from "../utils";
+import { Segmented, type Dim } from "./dashboard-shared";
+import { DimSegmented } from "./dim-segmented";
+
+type UsageMetric = "tokens" | "cost" | "time" | "tasks";
+
+/**
+ * Spend over time: one x-axis, four metrics behind a toggle so the reader can
+ * mentally overlay them by flipping between them.
+ *
+ * Errors used to be the fifth metric here. It is a different question — "what
+ * broke" rather than "what did it cost" — and sharing a toggle with the spend
+ * metrics meant the only way to see failures was to hide spend. It now has its
+ * own chart on the Errors tab.
+ */
+export function UsageTrendCard({
+ allowedDims,
+ dailyCost,
+ dailyTokens,
+ dailyTime,
+ dailyTasks,
+ weeklyCost,
+ weeklyTokens,
+ weeklyTime,
+ weeklyTasks,
+ lessThanMinuteLabel,
+}: {
+ allowedDims: readonly Dim[];
+ dailyCost: ReturnType<typeof aggregateDailyCost>;
+ dailyTokens: ReturnType<typeof aggregateDailyTokens>;
+ dailyTime: ReturnType<typeof aggregateDailyTime>;
+ dailyTasks: ReturnType<typeof aggregateDailyTasks>;
+ weeklyCost: ReturnType<typeof aggregateByWeek>["weeklyCostStack"];
+ weeklyTokens: ReturnType<typeof aggregateByWeek>["weeklyTokens"];
+ weeklyTime: ReturnType<typeof aggregateWeeklyTime>;
+ weeklyTasks: ReturnType<typeof aggregateWeeklyTasks>;
+ lessThanMinuteLabel: string;
+}) {
+ const { t } = useT("usage");
+ const [metric, setMetric] = useState<UsageMetric>("tokens");
+ const [dim, setDim] = useState<Dim>("daily");
+ // Derived, never reset: when the range narrows to 1d the card simply draws
+ // the one dimension that range allows, and a later widening restores the
+ // reader's choice. Writing the correction back into state would make the
+ // card forget it.
+ const effectiveDim: Dim = allowedDims.includes(dim) ? dim : allowedDims[0]!;
+ const weekly = effectiveDim === "weekly";
+
+ // Empty-state is per-metric so each toggle option independently decides
+ // whether it has data — e.g. tokens recorded but no terminal runs yet
+ // should show Tokens normally while Time / Tasks fall through to empty.
+ const costData = weekly ? weeklyCost : dailyCost;
+ const tokensData = weekly ? weeklyTokens : dailyTokens;
+ const timeData = weekly ? weeklyTime : dailyTime;
+ const tasksData = weekly ? weeklyTasks : dailyTasks;
+
+ const totalCost = costData.reduce((sum, d) => sum + d.total, 0);
+ const totalTokens = tokensData.reduce(
+ (sum, d) => sum + d.input + d.output + d.cacheRead + d.cacheWrite,
+ 0,
+ );
+ const totalSeconds = timeData.reduce((sum, d) => sum + d.totalSeconds, 0);
+ const totalTasks = tasksData.reduce((sum, d) => sum + d.completed + d.failed, 0);
+ const isEmpty =
+ metric === "cost"
+ ? totalCost === 0
+ : metric === "tokens"
+ ? totalTokens === 0
+ : metric === "time"
+ ? totalSeconds === 0
+ : totalTasks === 0;
+
+ const title = weekly
+ ? metric === "cost"
+ ? t(($) => $.weekly.title_cost)
+ : metric === "tokens"
+ ? t(($) => $.weekly.title_tokens)
+ : metric === "time"
+ ? t(($) => $.weekly.title_time)
+ : t(($) => $.weekly.title_tasks)
+ : metric === "cost"
+ ? t(($) => $.daily.title_cost)
+ : metric === "tokens"
+ ? t(($) => $.daily.title_tokens)
+ : metric === "time"
+ ? t(($) => $.daily.title_time)
+ : t(($) => $.daily.title_tasks);
+
+ return (
+ <div className="rounded-lg border bg-card p-4">
+ <div className="mb-3 flex flex-wrap items-center justify-between gap-3">
+ <h4 className="text-body font-semibold">{title}</h4>
+ <div className="flex flex-wrap items-center gap-2">
+ <Segmented
+ label={t(($) => $.daily.metric_label)}
+ value={metric}
+ onChange={setMetric}
+ options={[
+ { label: t(($) => $.daily.metric_tokens), value: "tokens" as const },
+ { label: t(($) => $.daily.metric_cost), value: "cost" as const },
+ { label: t(($) => $.daily.metric_time), value: "time" as const },
+ { label: t(($) => $.daily.metric_tasks), value: "tasks" as const },
+ ]}
+ />
+ <DimSegmented allowedDims={allowedDims} value={effectiveDim} onChange={setDim} />
+ </div>
+ </div>
+ <div className="min-h-[240px]">
+ {isEmpty ? (
+ <div className="flex aspect-[3/1] flex-col items-center justify-center gap-2 rounded-md border border-dashed bg-muted/20 p-6 text-center">
+ <BarChart3 className="h-5 w-5 text-faint-foreground" />
+ <p className="text-caption text-muted-foreground">
+ {t(($) => $.daily.no_data)}
+ </p>
+ </div>
+ ) : weekly ? (
+ metric === "cost" ? (
+ <WeeklyCostChart data={weeklyCost} />
+ ) : metric === "tokens" ? (
+ <WeeklyTokensChart data={weeklyTokens} />
+ ) : metric === "time" ? (
+ <WeeklyTimeChart
+ data={weeklyTime}
+ formatY={(s) => formatDuration(s, lessThanMinuteLabel)}
+ formatTooltip={(s) => formatDuration(s, lessThanMinuteLabel)}
+ />
+ ) : (
+ <WeeklyTasksChart data={weeklyTasks} />
+ )
+ ) : metric === "cost" ? (
+ <DailyCostChart data={dailyCost} />
+ ) : metric === "tokens" ? (
+ <DailyTokensChart data={dailyTokens} />
+ ) : metric === "time" ? (
+ <DailyTimeChart
+ data={dailyTime}
+ formatY={(s) => formatDuration(s, lessThanMinuteLabel)}
+ formatTooltip={(s) => formatDuration(s, lessThanMinuteLabel)}
+ />
+ ) : (
+ <DailyTasksChart data={dailyTasks} />
+ )}
+ </div>
+ </div>
+ );
+}
diff --git a/packages/views/locales/en/layout.json b/packages/views/locales/en/layout.json
index a41f4fff26..c670a3dc7b 100644
--- a/packages/views/locales/en/layout.json
+++ b/packages/views/locales/en/layout.json
@@ -8,7 +8,7 @@
"autopilots": "Autopilot",
"agents": "Agents",
"squads": "Squads",
- "usage": "Usage",
+ "usage": "Analytics",
"runtimes": "Runtimes",
"skills": "Skills",
"settings": "Settings"
diff --git a/packages/views/locales/en/usage.json b/packages/views/locales/en/usage.json
index e2a5e6363f..2eadb2c9c5 100644
--- a/packages/views/locales/en/usage.json
+++ b/packages/views/locales/en/usage.json
@@ -1,6 +1,11 @@
{
- "title": "Usage",
+ "title": "Analytics",
+ "tab_usage": "Usage",
"subtitle": "Token spend and agent activity across this workspace.",
+ "header": {
+ "timezone_and_updated": "{{tz}} · updated {{time}}",
+ "refresh": "Refresh"
+ },
"filter": {
"project_label": "Project",
"all_projects": "All projects",
@@ -30,7 +35,6 @@
"metric_tokens": "Tokens",
"metric_time": "Time",
"metric_tasks": "Tasks",
- "metric_errors": "Errors",
"no_data": "No usage in this window.",
"metric_label": "Metric"
},
@@ -43,6 +47,11 @@
"partial_label": "{{range}} (partial · {{covered}} / 7 days)"
},
"errors": {
+ "kpi_failed_label": "Failed tasks · {{days}}D",
+ "kpi_failed_hint": "Of {{total}} runs",
+ "kpi_rate_label": "Failure rate · {{days}}D",
+ "kpi_agents_label": "Agents affected · {{days}}D",
+ "kpi_agents_hint": "Worst {{name}} · {{count}}",
"tooltip_rate": "Error rate",
"class": {
"auth": "Auth",
diff --git a/packages/views/locales/ja/layout.json b/packages/views/locales/ja/layout.json
index 82378c29eb..a03dfbbff0 100644
--- a/packages/views/locales/ja/layout.json
+++ b/packages/views/locales/ja/layout.json
@@ -8,7 +8,7 @@
"autopilots": "オートパイロット",
"agents": "エージェント",
"squads": "スクワッド",
- "usage": "使用量",
+ "usage": "分析",
"runtimes": "ランタイム",
"skills": "スキル",
"settings": "設定"
diff --git a/packages/views/locales/ja/usage.json b/packages/views/locales/ja/usage.json
index 5734c6da28..aaf9878ec1 100644
--- a/packages/views/locales/ja/usage.json
+++ b/packages/views/locales/ja/usage.json
@@ -1,6 +1,11 @@
{
- "title": "使用量",
+ "title": "分析",
+ "tab_usage": "使用量",
"subtitle": "このワークスペース全体のトークン消費とエージェントの活動です。",
+ "header": {
+ "timezone_and_updated": "{{tz}} · {{time}} 更新",
+ "refresh": "更新"
+ },
"filter": {
"project_label": "プロジェクト",
"all_projects": "すべてのプロジェクト",
@@ -30,7 +35,6 @@
"metric_tokens": "トークン",
"metric_time": "時間",
"metric_tasks": "作業",
- "metric_errors": "エラー",
"no_data": "この期間に使用量はありません。",
"metric_label": "指標"
},
@@ -43,6 +47,11 @@
"partial_label": "{{range}} (一部 · 7日中 {{covered}}日)"
},
"errors": {
+ "kpi_failed_label": "失敗した作業 · {{days}}日",
+ "kpi_failed_hint": "{{total}} 回の実行中",
+ "kpi_rate_label": "失敗率 · {{days}}日",
+ "kpi_agents_label": "影響を受けたエージェント · {{days}}日",
+ "kpi_agents_hint": "最多 {{name}} · {{count}} 回",
"tooltip_rate": "エラー率",
"class": {
"auth": "認証",
diff --git a/packages/views/locales/ko/layout.json b/packages/views/locales/ko/layout.json
index 8c4be4d347..c089411af3 100644
--- a/packages/views/locales/ko/layout.json
+++ b/packages/views/locales/ko/layout.json
@@ -8,7 +8,7 @@
"autopilots": "오토파일럿",
"agents": "에이전트",
"squads": "스쿼드",
- "usage": "사용량",
+ "usage": "분석",
"runtimes": "런타임",
"skills": "스킬",
"settings": "설정"
diff --git a/packages/views/locales/ko/usage.json b/packages/views/locales/ko/usage.json
index 0edc30f44e..386b5b1d95 100644
--- a/packages/views/locales/ko/usage.json
+++ b/packages/views/locales/ko/usage.json
@@ -1,6 +1,11 @@
{
- "title": "사용량",
+ "title": "분석",
+ "tab_usage": "사용량",
"subtitle": "이 워크스페이스의 토큰 비용과 에이전트 활동입니다.",
+ "header": {
+ "timezone_and_updated": "{{tz}} · {{time}} 업데이트",
+ "refresh": "새로고침"
+ },
"filter": {
"project_label": "프로젝트",
"all_projects": "모든 프로젝트",
@@ -30,7 +35,6 @@
"metric_tokens": "토큰",
"metric_time": "시간",
"metric_tasks": "작업",
- "metric_errors": "오류",
"no_data": "이 기간에는 사용량이 없습니다.",
"metric_label": "지표"
},
@@ -43,6 +47,11 @@
"partial_label": "{{range}} (부분 · 7일 중 {{covered}}일)"
},
"errors": {
+ "kpi_failed_label": "실패한 작업 · {{days}}일",
+ "kpi_failed_hint": "실행 {{total}}회 중",
+ "kpi_rate_label": "실패율 · {{days}}일",
+ "kpi_agents_label": "영향받은 에이전트 · {{days}}일",
+ "kpi_agents_hint": "최다 {{name}} · {{count}}회",
"tooltip_rate": "오류율",
"class": {
"auth": "인증",
diff --git a/packages/views/locales/zh-Hans/layout.json b/packages/views/locales/zh-Hans/layout.json
index d0dc44cabc..5aa737d1c9 100644
--- a/packages/views/locales/zh-Hans/layout.json
+++ b/packages/views/locales/zh-Hans/layout.json
@@ -8,7 +8,7 @@
"autopilots": "自动化",
"agents": "智能体",
"squads": "小队",
- "usage": "用量",
+ "usage": "统计",
"runtimes": "运行时",
"skills": "Skills",
"settings": "设置"
diff --git a/packages/views/locales/zh-Hans/usage.json b/packages/views/locales/zh-Hans/usage.json
index 0b7f29052b..d561567665 100644
--- a/packages/views/locales/zh-Hans/usage.json
+++ b/packages/views/locales/zh-Hans/usage.json
@@ -1,6 +1,11 @@
{
- "title": "用量",
+ "title": "统计",
+ "tab_usage": "用量",
"subtitle": "查看当前 Workspace 的 token 消耗和智能体运行情况。",
+ "header": {
+ "timezone_and_updated": "{{tz}} · 更新于 {{time}}",
+ "refresh": "刷新"
+ },
"filter": {
"project_label": "项目",
"all_projects": "全部项目",
@@ -30,7 +35,6 @@
"metric_tokens": "Token",
"metric_time": "运行时长",
"metric_tasks": "task 数",
- "metric_errors": "错误",
"no_data": "所选时间范围内暂无消耗。",
"metric_label": "指标"
},
@@ -43,6 +47,11 @@
"partial_label": "{{range}}(未满 · 已过 {{covered}} / 7 天)"
},
"errors": {
+ "kpi_failed_label": "失败 task · {{days}}天",
+ "kpi_failed_hint": "共 {{total}} 次运行",
+ "kpi_rate_label": "失败率 · {{days}}天",
+ "kpi_agents_label": "受影响智能体 · {{days}}天",
+ "kpi_agents_hint": "最多 {{name}} · {{count}} 次",
"tooltip_rate": "错误率",
"class": {
"auth": "认证",