Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(usage): rank the Errors offender list by failures or rate (MUL-5389) (#6023)
Bohan Jiangce45b8d35310
diff --git a/packages/views/dashboard/components/dashboard-page.test.tsx b/packages/views/dashboard/components/dashboard-page.test.tsxindex a08cc4aa20..b5962478df 100644--- a/packages/views/dashboard/components/dashboard-page.test.tsx+++ b/packages/views/dashboard/components/dashboard-page.test.tsx@@ -227,6 +227,23 @@ function renderDashboard() {);}+// 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;+}++// The filled part of one offender row's bar. `role="img"` is on the fill (it+// carries the class-split label), and its inline width is the metric the list+// is currently ranked by.+function offenderBar(index: number): HTMLElement {+ const rows = within(+ screen.getByRole("list", { name: "Top offenders" }),+ ).getAllByRole("listitem");+ return within(rows[index] as HTMLElement).getByRole("img");+}+describe("DashboardPage — viewing timezone drives the query key", () => {beforeEach(() => {queryKeys.length = 0;@@ -323,11 +340,14 @@ describe("DashboardPage — failure visibility", () => {// Auth (3) outranks Timeout (1), and both are named by class rather than// by the raw failure_reason enum.- const byClass = within(screen.getByRole("list", { name: "By class" }));+ const byClass = within(screen.getByRole("list", { name: "Failure mix" }));expect(byClass.getAllByRole("listitem").map((li) => li.textContent)).toEqual(["Auth3","Timeout1",]);+ // The section names its own denominator: the header above it quotes a+ // rate over all 10 runs, this one splits the 4 failures.+ expect(screen.getByText("Failure mix · 4")).toBeInTheDocument();const byAgent = within(screen.getByRole("list", { name: "Top offenders" }));const link = byAgent.getByRole("link", { name: /Agent One/ });@@ -335,8 +355,70 @@ describe("DashboardPage — failure visibility", () => {// while its recent runs (and each failure's reason) live in the Overview// pane's ActivityTab.expect(link).toHaveAttribute("href", "/acme/agents/agent-1?view=overview");- // 4 of that agent's 10 terminal runs failed, and Auth is what dominates.- expect(byAgent.getByText("4 / 10 · 40%")).toBeInTheDocument();+ // One labelled column per number instead of the old unlabelled+ // `4 / 10 · 40%` blob.+ const row = byAgent.getAllByRole("listitem")[0] as HTMLElement;+ expect(within(row).getByText("4")).toBeInTheDocument();+ expect(within(row).getByText("10")).toBeInTheDocument();+ expect(within(row).getByText("40%")).toBeInTheDocument();+ // The bar is the only place the class split lives now that the dominant-+ // class badge is gone, so it has to name that split for screen readers.+ expect(within(row).getByRole("img")).toHaveAccessibleName("Auth 3 · Timeout 1");+ });++ it("moves the bar onto whichever metric the list is ranked by", async () => {+ const user = userEvent.setup();+ renderDashboard();++ // 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% —+ // a bar that stayed on the failure count while the row shouted "100%" is+ // exactly the mismatch this control exists to remove.+ expect(offenderBar(1).style.width).toBe("50%");++ await user.click(within(offenderCard()).getByRole("button", { name: "Rate" }));++ expect(offenderBar(1).style.width).toBe("100%");+ });++ it("says which metric the list is ranked by without relying on colour", async () => {+ const user = userEvent.setup();+ renderDashboard();++ // 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" });+ expect(+ within(group).getByRole("button", { name: "Failures" }),+ ).toHaveAttribute("aria-pressed", "true");+ expect(within(group).getByRole("button", { name: "Rate" })).toHaveAttribute(+ "aria-pressed",+ "false",+ );++ await user.click(within(group).getByRole("button", { name: "Rate" }));++ expect(within(group).getByRole("button", { name: "Rate" })).toHaveAttribute(+ "aria-pressed",+ "true",+ );+ });++ it("keeps a two-run agent from hijacking the rate ranking", async () => {+ const user = userEvent.setup();+ renderDashboard();++ await user.click(within(offenderCard()).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+ // reconcile with the workspace failure count above it.+ const rows = within(screen.getByRole("list", { name: "Top offenders" }))+ .getAllByRole("listitem")+ .map((li) => li.textContent);+ expect(rows[0]).toMatch(/Agent One/);+ expect(rows[1]).toMatch(/Other agents/);});it("reveals the raw failure_reason values behind the class summary", async () => {diff --git a/packages/views/dashboard/components/dashboard-page.tsx b/packages/views/dashboard/components/dashboard-page.tsxindex 18f1c718c0..526df82207 100644--- a/packages/views/dashboard/components/dashboard-page.tsx+++ b/packages/views/dashboard/components/dashboard-page.tsx@@ -28,6 +28,7 @@ import {dashboardRunTimeDailyOptions,dashboardFailuresDailyOptions,dashboardFailuresByAgentOptions,+ FAILURE_CLASSES,type FailureClass,} from "@multica/core/dashboard";import { useWorkspacePaths } from "@multica/core/paths";@@ -78,12 +79,17 @@ import {computeFailureTotals,DELETED_AGENTS_ROW_ID,formatDuration,+ hasRateSample,mergeAgentDashboardRows,+ MIN_RATE_SAMPLE,+ OFFENDER_METRIC,+ 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@@ -135,21 +141,36 @@ 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 className="inline-flex items-center gap-0.5 rounded-md bg-muted p-0.5">+ <div+ role="group"+ aria-label={label}+ className="inline-flex items-center gap-0.5 rounded-md bg-muted p-0.5"+ >{options.map((o) => (<buttonkey={String(o.value)}type="button"+ aria-pressed={o.value === value}onClick={() => onChange(o.value)}className={`rounded-sm px-2.5 py-1 text-xs font-medium transition-colors ${o.value === value@@ -487,6 +508,7 @@ export function DashboardPage() {onChange={setProjectValue}/><Segmented+ label={t(($) => $.dim.label)}value={dim}onChange={handleDimChange}options={[@@ -495,6 +517,7 @@ export function DashboardPage() {]}/><Segmented+ label={t(($) => $.filter.period_label)}value={days}onChange={setDays}options={allowedRanges.map((r) => ({ label: r.label, value: r.days }))}@@ -777,6 +800,7 @@ function TrendBlock({<div className="mb-3 flex flex-wrap items-center justify-between gap-3"><h4 className="text-sm font-semibold">{title}</h4><Segmented+ label={t(($) => $.daily.metric_label)}value={metric}onChange={setMetric}options={[@@ -866,6 +890,11 @@ function useFailureClassLabel(): (c: FailureClass) => string {// 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.@@ -895,11 +924,32 @@ function ErrorsBreakdown({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 maxAgent = agentRows.reduce((m, r) => Math.max(m, r.failed), 0);const visibleAgents = showAllAgents- ? agentRows- : agentRows.slice(0, TOP_OFFENDER_LIMIT);+ ? sortedAgents+ : sortedAgents.slice(0, TOP_OFFENDER_LIMIT);return (<div className="rounded-lg border bg-card">@@ -920,8 +970,13 @@ function ErrorsBreakdown({<><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-xs font-medium text-muted-foreground">- {t(($) => $.errors.by_class)}+ {t(($) => $.errors.mix_title, { failed: totals.failed })}</h5><buttontype="button"@@ -941,29 +996,67 @@ function ErrorsBreakdown({</div><div className="p-4">- <div className="mb-2 flex items-center justify-between gap-2">+ <div className="mb-2 flex flex-wrap items-center justify-between gap-2"><h5 className="text-xs font-medium text-muted-foreground">{t(($) => $.errors.by_agent)}</h5>- {agentRows.length > TOP_OFFENDER_LIMIT ? (- <button- type="button"- onClick={() => setShowAllAgents((v) => !v)}- className="text-xs 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: agentRows.length })}- </button>- ) : null}+ <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-xs 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-xs 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) => (<AgentFailureItemkey={row.agentId}row={row}name={agents.find((a) => a.id === row.agentId)?.name ?? null}- maxFailed={maxAgent}+ maxValue={maxValue}+ sortBy={sortBy}classLabel={classLabel}/>))}@@ -1012,7 +1105,7 @@ function ClassComposition({))}</div><ul- aria-label={t(($) => $.errors.by_class)}+ aria-label={t(($) => $.errors.mix_label)}className="flex flex-wrap items-center gap-x-4 gap-y-1.5">{rows.map((row) => (@@ -1045,7 +1138,7 @@ function ReasonList({ rows }: { rows: FailureReasonRow[] }) {const { t } = useT("usage");return (<ul- aria-label={t(($) => $.errors.by_class)}+ 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) => (@@ -1069,27 +1162,52 @@ function ReasonList({ rows }: { rows: FailureReasonRow[] }) {/*** One offender row, shaped like the leaderboard row directly above this card:- * identity, then a proportional bar, then the numbers.+ * identity, then a proportional bar, then one column per number.*- * Was two lines (name+stats over a full-width bar), which at 30 agents made- * the card taller than the rest of the page combined. Folding the bar into- * its own grid column halves the height and lines the numbers up into a- * scannable column.+ * 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,- maxFailed,+ maxValue,+ sortBy,classLabel,}: {row: AgentFailureRow;name: string | null;- maxFailed: number;+ maxValue: number;+ sortBy: OffenderSort;classLabel: (c: FailureClass) => string;}) {const { t } = useT("usage");const wsPaths = useWorkspacePaths();- const barColor = FAILURE_CLASS_COLOR[row.topClass ?? "other"];++ 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@@ -1102,22 +1220,15 @@ function AgentFailureItem({// 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="flex min-w-0 items-center gap-2">- <span- className={`truncate text-xs${name ? "" : " italic text-muted-foreground"}`}- >- {name ?? t(($) => $.errors.other_agents)}- </span>- {row.topClass ? (- <span className="shrink-0 rounded-sm bg-muted px-1 py-px text-[10px] text-muted-foreground">- {classLabel(row.topClass)}- </span>- ) : null}+ <span+ className={`block truncate text-xs${name ? "" : " italic text-muted-foreground"}`}+ >+ {name ?? t(($) => $.errors.other_agents)}</span>);return (- <li className="grid grid-cols-[minmax(0,1.4fr)_minmax(0,1fr)_auto] items-center gap-3 py-2">+ <li className={`${OFFENDER_GRID} py-2`}>{name ? (<AppLinkhref={`${wsPaths.agentDetail(row.agentId)}?view=overview`}@@ -1131,19 +1242,45 @@ function AgentFailureItem({)}<div className="h-1.5 overflow-hidden rounded-full bg-muted"><div- className="h-full rounded-full transition-[width] duration-300 ease-out"- style={{- width: `${maxFailed > 0 ? (row.failed / maxFailed) * 100 : 0}%`,- backgroundColor: barColor,- }}- />+ 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="whitespace-nowrap text-right text-xs tabular-nums text-muted-foreground">- {t(($) => $.errors.agent_rate, {- failed: row.failed,- total: row.total,- rate: formatRate(row.failed, row.total),- })}+ <span+ className={`text-right text-xs tabular-nums ${sortBy === "failed" ? "font-medium text-foreground" : "text-muted-foreground"}`}+ >+ {row.failed}+ </span>+ <span className="text-right text-xs tabular-nums text-muted-foreground">+ {row.total}+ </span>+ <span+ title={+ weakSample+ ? t(($) => $.errors.low_sample, { count: MIN_RATE_SAMPLE })+ : undefined+ }+ className={`text-right text-xs tabular-nums ${+ sortBy === "rate" && !weakSample+ ? "font-medium text-foreground"+ : "text-muted-foreground"+ }`}+ >+ {formatRate(row.failed, row.total)}</span></li>);@@ -1223,7 +1360,12 @@ function Leaderboard({<div className="flex flex-wrap items-center justify-between gap-3 border-b px-4 pt-4 pb-3"><h4 className="text-sm font-semibold">{t(($) => $.leaderboard.title)}</h4><div className="flex flex-wrap items-center justify-end gap-3">- <Segmented value={sortBy} onChange={setSortBy} options={sortOptions} />+ <Segmented+ label={t(($) => $.leaderboard.sort_label)}+ value={sortBy}+ onChange={setSortBy}+ options={sortOptions}+ /><span className="text-xs text-muted-foreground">{deletedAgentCount > 0? t(($) => $.leaderboard.caption_with_deleted, {diff --git a/packages/views/dashboard/utils.test.ts b/packages/views/dashboard/utils.test.tsindex 0608477d2f..34471b9591 100644--- a/packages/views/dashboard/utils.test.ts+++ b/packages/views/dashboard/utils.test.ts@@ -16,7 +16,9 @@ import {computeFailureTotals,DELETED_AGENTS_ROW_ID,formatDuration,+ hasRateSample,mergeAgentDashboardRows,+ sortAgentFailures,} from "./utils";describe("aggregateDailyCost", () => {@@ -526,7 +528,7 @@ describe("aggregateFailureClasses / aggregateFailureReasons", () => {});describe("aggregateAgentFailures", () => {- it("ranks by failure count, carries the rate, and names the dominant class", () => {+ it("ranks by failure count, carries the rate, and splits failures by class", () => {const result = aggregateAgentFailures([{ agent_id: "a", failure_reason: "", task_count: 90 },{ agent_id: "a", failure_reason: "timeout", task_count: 10 },@@ -537,10 +539,14 @@ describe("aggregateAgentFailures", () => {// `a` fails 10% of the time, `b` fails 80% — but `a` is the bigger// absolute problem, so it ranks first and the rate rides along.- expect(result).toEqual([- { agentId: "a", failed: 10, total: 100, rate: 0.1, topClass: "timeout" },- { agentId: "b", failed: 4, total: 5, rate: 0.8, topClass: "runtime" },+ expect(result.map((r) => [r.agentId, r.failed, r.total, r.rate])).toEqual([+ ["a", 10, 100, 0.1],+ ["b", 4, 5, 0.8],]);+ // The whole composition, not just the heaviest class: `b` failing two+ // ways is the thing that decides whether to look at the agent or at the+ // platform, and a single dominant-class label hid it.+ expect(result[1]?.classes).toMatchObject({ runtime: 3, timeout: 1, auth: 0 });});it("drops agents with no failures — the list is triage, not a census", () => {@@ -550,6 +556,48 @@ describe("aggregateAgentFailures", () => {});});+describe("sortAgentFailures", () => {+ // `busy` is the workspace's biggest absolute problem; `flaky` is the least+ // healthy per run; `once` is the small-sample trap — a single failed run is+ // a 100% rate and would win the Rate ranking outright.+ const rows = aggregateAgentFailures([+ { agent_id: "busy", failure_reason: "", task_count: 900 },+ { agent_id: "busy", failure_reason: "timeout", task_count: 100 },+ { agent_id: "flaky", failure_reason: "", task_count: 80 },+ { agent_id: "flaky", failure_reason: "runtime_offline", task_count: 20 },+ { agent_id: "once", failure_reason: "timeout", task_count: 1 },+ ]);++ it("ranks by absolute failures by default", () => {+ expect(sortAgentFailures(rows, "failed").map((r) => r.agentId)).toEqual([+ "busy",+ "flaky",+ "once",+ ]);+ });++ it("ranks by rate, with too-small samples demoted rather than dropped", () => {+ // `once` is 100% and `flaky` only 20%, but one run is not evidence. The+ // row still renders — the list has to reconcile with the workspace+ // failure count above it.+ expect(sortAgentFailures(rows, "rate").map((r) => r.agentId)).toEqual([+ "flaky",+ "busy",+ "once",+ ]);+ });++ it("marks which rows have enough runs for their rate to mean anything", () => {+ expect(rows.map((r) => hasRateSample(r))).toEqual([true, true, false]);+ });++ it("leaves the input array untouched", () => {+ const before = rows.map((r) => r.agentId);+ sortAgentFailures(rows, "rate");+ expect(rows.map((r) => r.agentId)).toEqual(before);+ });+});+describe("anonymizeUnresolvedAgentRows", () => {// Raw per-(agent, reason) rows, which is the shape this operates on. Two// agents the viewer cannot resolve, with deliberately conflicting dominant@@ -580,17 +628,17 @@ describe("anonymizeUnresolvedAgentRows", () => {expect(result.map((r) => r.task_count)).toEqual([5, 5, 6, 5, 10]);});- it("keeps the bucket's dominant class honest across merged agents", () => {+ it("keeps the bucket's class split honest across merged agents", () => {// This is why the rewrite happens on RAW rows. private-a is auth-dominant// (6 vs 5) and private-b is timeout-only (10). Merging AFTER aggregation- // would see only each agent's top class and its total failure count —- // auth 11, timeout 10 — and label the bucket Auth. The true composition- // is timeout 15 / auth 6, so it must read Timeout.+ // would see only each agent's dominant class and its total failure count —+ // auth 11, timeout 10 — while the true composition is timeout 15 / auth 6.const bucket = aggregateAgentFailures(anonymizeUnresolvedAgentRows(rows, new Set(["visible"])),).find((r) => r.agentId === UNRESOLVED_AGENTS_ROW_ID);- expect(bucket).toMatchObject({ failed: 21, total: 21, topClass: "timeout" });+ expect(bucket).toMatchObject({ failed: 21, total: 21 });+ expect(bucket?.classes).toMatchObject({ timeout: 15, auth: 6 });});it("anonymizes everything while the agent list is still loading", () => {diff --git a/packages/views/dashboard/utils.ts b/packages/views/dashboard/utils.tsindex 1efbd9500a..e585da3ec2 100644--- a/packages/views/dashboard/utils.ts+++ b/packages/views/dashboard/utils.ts@@ -608,15 +608,19 @@ export interface AgentFailureRow {failed: number;total: number;rate: number;- // Heaviest class for this agent — the "what kind of broken" hint on the- // top-offenders row. null when the agent has no failures at all.- topClass: FailureClass | null;-}--// Per-agent failure totals, worst first. Ranked by absolute failure count-// rather than rate: an agent with 1/1 failed is a 100% rate but is rarely the-// thing an operator should look at before the agent that failed 40 times.-// The rate rides along on the row so the reader can still see it.+ // Full per-class split of this agent's failures, which the offender row+ // draws as a stacked bar. Carries the whole composition rather than just+ // the heaviest class: "fails one way" and "fails five ways" are different+ // problems, and a single dominant-class label collapsed them into the same+ // row. Every class is present (0 when unused) so the bar can be built+ // without existence checks.+ classes: FailureClassCounts;+}++// Per-agent failure totals, worst first. Default order is absolute failure+// count: an agent with 1/1 failed is a 100% rate but is rarely the thing an+// operator should look at before the agent that failed 40 times. The rate+// rides along on the row, and `sortAgentFailures` can re-rank on it.//// Agents with zero failures are dropped — this list is a triage aid, not a// census; the leaderboard above it already shows every agent.@@ -638,24 +642,62 @@ export function aggregateAgentFailures(entry.failed += r.task_count;entry.classes[failureClassOf(r.failure_reason)] += r.task_count;}- return Array.from(map.entries())- .filter(([, v]) => v.failed > 0)- .map(([agentId, v]) => {- let topClass: FailureClass | null = null;- for (const c of FAILURE_CLASSES) {- if (v.classes[c] > 0 && (topClass === null || v.classes[c] > v.classes[topClass])) {- topClass = c;- }- }- return {+ return sortAgentFailures(+ Array.from(map.entries())+ .filter(([, v]) => v.failed > 0)+ .map(([agentId, v]) => ({agentId,failed: v.failed,total: v.total,rate: v.total > 0 ? v.failed / v.total : 0,- topClass,- };- })- .toSorted((a, b) => b.failed - a.failed || b.rate - a.rate);+ classes: v.classes,+ })),+ "failed",+ );+}++// Which metric ranks the offender list, and therefore how long its bars are.+// The two used to disagree: the list ranked on absolute failures while the+// most prominent number on the row was the rate, so the bar looked like it+// measured a percentage it had nothing to do with. Mirrors LeaderboardSort's+// contract — sort metric, bar length and the emphasised column move together.+export type OffenderSort = "failed" | "rate";++export const OFFENDER_METRIC: Record<+ OffenderSort,+ (r: AgentFailureRow) => number+> = {+ failed: (r) => r.failed,+ rate: (r) => r.rate,+};++// Minimum terminal runs before an agent's failure rate is allowed to compete+// on the Rate ranking. One run that failed is a 100% rate, and without a floor+// that row wins outright and buries every agent worth looking at.+//+// Small-sample rows are demoted, NOT hidden: this list has to keep reconciling+// with the workspace failure count above it, and an agent that failed its only+// two runs is still a real thing an operator may want to see.+export const MIN_RATE_SAMPLE = 10;++export function hasRateSample(row: AgentFailureRow): boolean {+ return row.total >= MIN_RATE_SAMPLE;+}++// Re-rank the offender rows for the selected metric. Ties break on the other+// metric so an equal-valued bucket keeps a stable, meaningful order instead of+// reshuffling on every render.+export function sortAgentFailures(+ rows: AgentFailureRow[],+ sortBy: OffenderSort,+): AgentFailureRow[] {+ if (sortBy === "failed") {+ return rows.toSorted((a, b) => b.failed - a.failed || b.rate - a.rate);+ }+ const sample = (r: AgentFailureRow) => (hasRateSample(r) ? 0 : 1);+ return rows.toSorted(+ (a, b) => sample(a) - sample(b) || b.rate - a.rate || b.failed - a.failed,+ );}// Fold rows whose agent the viewer cannot resolve into one aggregated bucket@@ -676,12 +718,10 @@ export function aggregateAgentFailures(//// This rewrites the RAW per-(agent, reason) rows rather than merging the// aggregated ones, so the bucket is just another agent_id by the time-// `aggregateAgentFailures` runs and its per-class counts stay exact. Merging-// after aggregation loses the class breakdown: each row carries only its own-// dominant class, so folding two agents would attribute each one's ENTIRE-// failure count to that single class. An agent failing auth 6 / timeout 5-// would contribute 11 to auth and nothing to timeout, and a bucket whose real-// composition was timeout 15 / auth 6 would announce itself as Auth.+// `aggregateAgentFailures` runs: its totals, rate, class split and rank all+// come out of the same code path as every other row. Merging aggregated rows+// would mean re-deriving `total` and `rate` by hand at the merge site — a+// second, easily-skewed copy of arithmetic that already exists once.export function anonymizeUnresolvedAgentRows(rows: DashboardFailureByAgent[],knownAgentIds: ReadonlySet<string> | null,diff --git a/packages/views/locales/en/usage.json b/packages/views/locales/en/usage.jsonindex 06b9fe9206..b0fe1daec4 100644--- a/packages/views/locales/en/usage.json+++ b/packages/views/locales/en/usage.json@@ -31,7 +31,8 @@"metric_time": "Time","metric_tasks": "Tasks","metric_errors": "Errors",- "no_data": "No usage in this window."+ "no_data": "No usage in this window.",+ "metric_label": "Metric"},"weekly": {"title_cost": "Weekly cost",@@ -54,10 +55,19 @@},"title": "Errors","summary": "{{failed}} of {{total}} runs failed · {{rate}}",- "by_class": "By class",+ "mix_title": "Failure mix · {{failed}}",+ "mix_label": "Failure mix",+ "codes_label": "Error codes","by_agent": "Top offenders",+ "sort_label": "Rank offenders by",+ "sort_failed": "Failures",+ "sort_rate": "Rate",+ "header_agent": "Agent",+ "header_failed": "Failed",+ "header_runs": "Runs",+ "header_rate": "Rate","other_agents": "Other agents",- "agent_rate": "{{failed}} / {{total}} · {{rate}}",+ "low_sample": "Fewer than {{count}} runs in this window — this rate is not meaningful.","no_data": "No failed runs in this window.","show_reasons": "Show error codes","hide_reasons": "Hide error codes",@@ -68,6 +78,7 @@"title": "Leaderboard","caption": "{{count}} agents","caption_with_deleted": "{{count}} agents · {{deleted}} deleted",+ "sort_label": "Rank agents by","deleted_agents": "Deleted agents","header_agent": "Agent","header_tokens": "Tokens",diff --git a/packages/views/locales/ja/usage.json b/packages/views/locales/ja/usage.jsonindex bbd11fa5f8..6277d33959 100644--- a/packages/views/locales/ja/usage.json+++ b/packages/views/locales/ja/usage.json@@ -31,7 +31,8 @@"metric_time": "時間","metric_tasks": "タスク","metric_errors": "エラー",- "no_data": "この期間に使用量はありません。"+ "no_data": "この期間に使用量はありません。",+ "metric_label": "指標"},"weekly": {"title_cost": "週別コスト",@@ -54,10 +55,19 @@},"title": "エラー","summary": "{{total}} 回中 {{failed}} 回が失敗 · {{rate}}",- "by_class": "種類別",+ "mix_title": "失敗の内訳 · {{failed}}",+ "mix_label": "失敗の内訳",+ "codes_label": "エラーコード","by_agent": "失敗の多いエージェント",+ "sort_label": "失敗の多いエージェントの並び順",+ "sort_failed": "失敗数",+ "sort_rate": "失敗率",+ "header_agent": "エージェント",+ "header_failed": "失敗",+ "header_runs": "実行",+ "header_rate": "失敗率","other_agents": "その他のエージェント",- "agent_rate": "{{failed}} / {{total}} · {{rate}}",+ "low_sample": "この期間の実行が {{count}} 回未満のため、この失敗率は参考になりません。","no_data": "この期間に失敗した実行はありません。","show_reasons": "エラーコードを表示","hide_reasons": "エラーコードを隠す",@@ -68,6 +78,7 @@"title": "リーダーボード","caption": "{{count}} 件のエージェント","caption_with_deleted": "{{count}} 件のエージェント · 削除済み {{deleted}} 件",+ "sort_label": "エージェントの並び順","deleted_agents": "削除済みエージェント","header_agent": "エージェント","header_tokens": "トークン",diff --git a/packages/views/locales/ko/usage.json b/packages/views/locales/ko/usage.jsonindex b9044a0713..4c4b4e4bf1 100644--- a/packages/views/locales/ko/usage.json+++ b/packages/views/locales/ko/usage.json@@ -31,7 +31,8 @@"metric_time": "시간","metric_tasks": "작업","metric_errors": "오류",- "no_data": "이 기간에는 사용량이 없습니다."+ "no_data": "이 기간에는 사용량이 없습니다.",+ "metric_label": "지표"},"weekly": {"title_cost": "주별 비용",@@ -54,10 +55,19 @@},"title": "오류","summary": "실행 {{total}}회 중 {{failed}}회 실패 · {{rate}}",- "by_class": "유형별",+ "mix_title": "실패 구성 · {{failed}}",+ "mix_label": "실패 구성",+ "codes_label": "오류 코드","by_agent": "실패가 많은 에이전트",+ "sort_label": "오류 순위 기준",+ "sort_failed": "실패 수",+ "sort_rate": "실패율",+ "header_agent": "에이전트",+ "header_failed": "실패",+ "header_runs": "실행",+ "header_rate": "실패율","other_agents": "기타 에이전트",- "agent_rate": "{{failed}} / {{total}} · {{rate}}",+ "low_sample": "이 기간의 실행이 {{count}}회 미만이어서 이 실패율은 의미가 크지 않습니다.","no_data": "이 기간에는 실패한 실행이 없습니다.","show_reasons": "오류 코드 표시","hide_reasons": "오류 코드 숨기기",@@ -68,6 +78,7 @@"title": "리더보드","caption": "에이전트 {{count}}개","caption_with_deleted": "에이전트 {{count}}개 · 삭제됨 {{deleted}}개",+ "sort_label": "에이전트 순위 기준","deleted_agents": "삭제된 에이전트","header_agent": "에이전트","header_tokens": "토큰",diff --git a/packages/views/locales/zh-Hans/usage.json b/packages/views/locales/zh-Hans/usage.jsonindex 0383c4fec8..a8da72ffec 100644--- a/packages/views/locales/zh-Hans/usage.json+++ b/packages/views/locales/zh-Hans/usage.json@@ -31,7 +31,8 @@"metric_time": "运行时长","metric_tasks": "任务数","metric_errors": "错误",- "no_data": "所选时间范围内暂无消耗。"+ "no_data": "所选时间范围内暂无消耗。",+ "metric_label": "指标"},"weekly": {"title_cost": "每周费用",@@ -54,10 +55,19 @@},"title": "错误","summary": "{{total}} 次运行中有 {{failed}} 次失败 · {{rate}}",- "by_class": "按类型",+ "mix_title": "失败构成 · {{failed}}",+ "mix_label": "失败构成",+ "codes_label": "错误码","by_agent": "问题最多的智能体",+ "sort_label": "错误榜排序依据",+ "sort_failed": "失败数",+ "sort_rate": "失败率",+ "header_agent": "智能体",+ "header_failed": "失败数",+ "header_runs": "运行数",+ "header_rate": "失败率","other_agents": "其他智能体",- "agent_rate": "{{failed}} / {{total}} · {{rate}}",+ "low_sample": "所选时间范围内运行不足 {{count}} 次,失败率参考价值有限。","no_data": "所选时间范围内没有失败的运行。","show_reasons": "展开错误码","hide_reasons": "收起错误码",@@ -68,6 +78,7 @@"title": "排行榜","caption": "{{count}} 个智能体","caption_with_deleted": "{{count}} 个智能体 · {{deleted}} 个已删除",+ "sort_label": "智能体排序依据","deleted_agents": "已删除的智能体","header_agent": "智能体","header_tokens": "Token",