Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(usage): error/failure charts on the Usage page (MUL-5352) (#5991)
Bohan Jiang4d0475ce89c0
diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 77ea590d9b..e358e73b9c 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -71,6 +71,8 @@ import type {DashboardUsageByAgent,DashboardAgentRunTime,DashboardRunTimeDaily,+ DashboardFailureDaily,+ DashboardFailureByAgent,RuntimeUpdate,RuntimeModelListRequest,RuntimeLocalSkillListRequest,@@ -192,6 +194,8 @@ import {agentBuilderRuntimeSwitchFallback,DashboardAgentRunTimeListSchema,DashboardRunTimeDailyListSchema,+ DashboardFailureDailyListSchema,+ DashboardFailureByAgentListSchema,DashboardUsageByAgentListSchema,DashboardUsageDailyListSchema,EMPTY_AGENT_TEMPLATE_DETAIL,@@ -1618,6 +1622,40 @@ export class ApiClient {);}+ async getDashboardFailuresDaily(+ params: { days?: number; project_id?: string | null; tz?: string },+ ): Promise<DashboardFailureDaily[]> {+ const search = new URLSearchParams();+ if (params.days) search.set("days", String(params.days));+ if (params.project_id) search.set("project_id", params.project_id);+ // `tz` cuts the day buckets in the viewer's calendar so the Errors chart+ // shares an x-axis with the other four metrics.+ if (params.tz) search.set("tz", params.tz);+ const raw = await this.fetch<unknown>(`/api/dashboard/failures/daily?${search}`);+ return parseWithFallback<DashboardFailureDaily[]>(+ raw,+ DashboardFailureDailyListSchema,+ [],+ { endpoint: "GET /api/dashboard/failures/daily" },+ );+ }++ async getDashboardFailuresByAgent(+ params: { days?: number; project_id?: string | null; tz?: string },+ ): Promise<DashboardFailureByAgent[]> {+ const search = new URLSearchParams();+ if (params.days) search.set("days", String(params.days));+ if (params.project_id) search.set("project_id", params.project_id);+ if (params.tz) search.set("tz", params.tz);+ const raw = await this.fetch<unknown>(`/api/dashboard/failures/by-agent?${search}`);+ return parseWithFallback<DashboardFailureByAgent[]>(+ raw,+ DashboardFailureByAgentListSchema,+ [],+ { endpoint: "GET /api/dashboard/failures/by-agent" },+ );+ }+async initiateUpdate(runtimeId: string,targetVersion: string,diff --git a/packages/core/api/schemas.test.ts b/packages/core/api/schemas.test.tsindex 712e2aaf2e..c22dc9b2a3 100644--- a/packages/core/api/schemas.test.ts+++ b/packages/core/api/schemas.test.ts@@ -6,6 +6,8 @@ import {FALLBACK_AUTOPILOT_RUN,CommentTriggerPreviewSchema,DashboardAgentRunTimeListSchema,+ DashboardFailureByAgentListSchema,+ DashboardFailureDailyListSchema,DashboardUsageByAgentListSchema,DashboardUsageDailyListSchema,ChatDraftRestoresResponseSchema,@@ -638,9 +640,48 @@ describe("dashboard + runtime usage schema drift", () => {it("rejects a non-array body so parseWithFallback can return its fallback", () => {expect(DashboardUsageDailyListSchema.safeParse(null).success).toBe(false);+ expect(DashboardFailureDailyListSchema.safeParse(null).success).toBe(false);+ expect(DashboardFailureByAgentListSchema.safeParse({ rows: [] }).success).toBe(+ false,+ );expect(RuntimeUsageListSchema.safeParse({ rows: [] }).success).toBe(false);});+ it("keeps a failure_reason the client build has never heard of", () => {+ // failure_reason is an open string, not an enum: the backend taxonomy+ // grows, and an installed desktop client must still count a reason its+ // build predates rather than dropping the row (and with it the day's+ // error total).+ const parsed = DashboardFailureDailyListSchema.parse([+ { date: "2026-05-19", failure_reason: "agent_error.brand_new", task_count: 3 },+ ]);+ expect(parsed).toHaveLength(1);+ expect(parsed[0]?.failure_reason).toBe("agent_error.brand_new");+ expect(parsed[0]?.task_count).toBe(3);+ });++ it("coerces a missing failure row field without dropping the array", () => {+ const daily = DashboardFailureDailyListSchema.parse([{ date: "2026-05-19" }]);+ expect(daily).toHaveLength(1);+ // "" is the succeeded bucket, so a reason-less row lands in the+ // denominator instead of inventing a failure that never happened.+ //+ // Defaulting to a failure bucket instead was considered and rejected: the+ // realistic drift here is someone adding `omitempty` to the Go struct+ // tag, which would strip the field from exactly the SUCCESS rows and turn+ // every window into a 100% error rate. Deflating a rate under drift is+ // the milder failure. TestDashboardFailureWireContractKeepsEmptyReason+ // (server/internal/handler/dashboard_test.go) guards the other side by+ // pinning that the server always emits the field.+ expect(daily[0]?.failure_reason).toBe("");+ expect(daily[0]?.task_count).toBe(0);++ const byAgent = DashboardFailureByAgentListSchema.parse([+ { failure_reason: "timeout", task_count: 2 },+ ]);+ expect(byAgent[0]?.agent_id).toBe("");+ });+it("keeps unknown server-side fields via .loose()", () => {const parsed = RuntimeUsageListSchema.parse([{ date: "2026-05-19", region: "us-east" },diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex 471ab39e77..a1c8750d41 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -859,6 +859,32 @@ const DashboardRunTimeDailySchema = z.object({export const DashboardRunTimeDailyListSchema = z.array(DashboardRunTimeDailySchema);+// Failure rollups. `failure_reason` is an open string on purpose — it carries+// the backend's canonical taxonomy, which grows as new classifier rules land+// (server/pkg/taskfailure). Pinning it to a z.enum would make an installed+// desktop client drop rows for a reason its build predates; the client folds+// unrecognised reasons into an "other" display class instead. The empty+// string is the succeeded bucket, so `.default("")` is a meaningful default+// only for a row that already lost its reason — such a row lands in the+// denominator rather than inventing a failure that never happened.+const DashboardFailureDailySchema = z.object({+ date: z.string().default(""),+ failure_reason: z.string().default(""),+ task_count: z.number().default(0),+}).loose();++export const DashboardFailureDailyListSchema = z.array(DashboardFailureDailySchema);++const DashboardFailureByAgentSchema = z.object({+ agent_id: z.string().default(""),+ failure_reason: z.string().default(""),+ task_count: z.number().default(0),+}).loose();++export const DashboardFailureByAgentListSchema = z.array(+ DashboardFailureByAgentSchema,+);+// ---------------------------------------------------------------------------// Runtime usage schemas — the runtime-detail page's four usage endpoints// (`/api/runtimes/:id/usage*`). Same leniency rules as the dashboarddiff --git a/packages/core/dashboard/failure-class.test.ts b/packages/core/dashboard/failure-class.test.tsnew file mode 100644index 0000000000..9b71e8f1e5--- /dev/null+++ b/packages/core/dashboard/failure-class.test.ts@@ -0,0 +1,54 @@+import { describe, expect, it } from "vitest";++import { FAILURE_CLASSES, failureClassOf } from "./failure-class";++describe("failureClassOf", () => {+ it("maps the reasons an operator acts on to distinct classes", () => {+ expect(failureClassOf("agent_error.provider_auth_or_access")).toBe("auth");+ expect(failureClassOf("agent_error.provider_capacity_or_rate_limit")).toBe(+ "rate_limit",+ );+ // Billing quota shares the rate-limit class: same operator response.+ expect(failureClassOf("agent_error.provider_quota_limit")).toBe("rate_limit");+ expect(failureClassOf("timeout")).toBe("timeout");+ expect(failureClassOf("agent_error.agent_timeout")).toBe("timeout");+ expect(failureClassOf("agent_error.provider_server_error")).toBe("provider");+ expect(failureClassOf("runtime_offline")).toBe("runtime");+ expect(failureClassOf("queued_expired")).toBe("runtime");+ expect(failureClassOf("agent_error.process_failure")).toBe("agent");+ });++ it("keeps pre-MUL-1949 coarse reasons countable", () => {+ // Historical rows still carry the old coarse taxonomy; they must land in+ // a bucket rather than vanish from the class totals.+ expect(failureClassOf("agent_error")).toBe("other");+ expect(failureClassOf("codex_semantic_inactivity")).toBe("timeout");+ expect(failureClassOf("runtime_recovery")).toBe("runtime");+ expect(failureClassOf("manual")).toBe("other");+ });++ it("files a reason from a newer backend under 'other' instead of dropping it", () => {+ // The wire value is an open string on purpose. A client build older than+ // the backend must still count the failure, or the class totals stop+ // reconciling with the headline failure count.+ expect(failureClassOf("agent_error.some_future_reason")).toBe("other");+ expect(failureClassOf("unclassified")).toBe("other");+ });++ it("returns a class every FAILURE_CLASSES member can be produced for", () => {+ // Guards against a class being declared but unreachable — a colour and a+ // translated label with no reason behind it.+ const reachable = new Set(+ [+ "agent_error.provider_auth_or_access",+ "agent_error.provider_quota_limit",+ "timeout",+ "agent_error.provider_network",+ "runtime_offline",+ "agent_error.process_failure",+ "agent_error.unknown",+ ].map(failureClassOf),+ );+ expect([...reachable].toSorted()).toEqual([...FAILURE_CLASSES].toSorted());+ });+});diff --git a/packages/core/dashboard/failure-class.ts b/packages/core/dashboard/failure-class.tsnew file mode 100644index 0000000000..ba30ec2f37--- /dev/null+++ b/packages/core/dashboard/failure-class.ts@@ -0,0 +1,92 @@+// Display grouping for `agent_task_queue.failure_reason`.+//+// The backend taxonomy (server/pkg/taskfailure) has 21 reasons, which is far+// too many series for a stacked chart or a scannable breakdown list. These+// seven classes are the granularity an operator actually acts on: an auth+// spike means "go re-auth", a rate-limit spike means "back off or raise the+// cap", a runtime spike means "a daemon is down". The raw reason stays on the+// wire and is still shown in the breakdown, so nothing is lost.+//+// Ordering below is the render order everywhere (stack segments, legend,+// breakdown rows): most-actionable first, catchall last, so the chart's+// colour ramp reads consistently regardless of which classes a workspace+// actually hits.+export const FAILURE_CLASSES = [+ "auth",+ "rate_limit",+ "timeout",+ "provider",+ "runtime",+ "agent",+ "other",+] as const;++export type FailureClass = (typeof FAILURE_CLASSES)[number];++// Reason → class. Keys are the wire values written by the backend: the 21+// canonical `taskfailure.Reason` strings, the `"unclassified"` sentinel the+// failure rollups substitute for a failed row with an empty column, and the+// pre-MUL-1949 coarse values that still sit in historical rows.+//+// Anything absent from this map falls through to "other" — including a new+// reason from a backend newer than this client, which is the case that makes+// a total-coverage exhaustive `Record<Reason, …>` the wrong shape here.+const REASON_CLASS: Record<string, FailureClass> = {+ // Credentials / access.+ "agent_error.provider_auth_or_access": "auth",+ "agent_error.missing_config": "auth",++ // Capacity the account ran out of — rate limits and billing quota share a+ // class because the operator response is the same: wait, or raise a cap.+ "agent_error.provider_capacity_or_rate_limit": "rate_limit",+ "agent_error.provider_quota_limit": "rate_limit",++ // Ran too long. Platform-side sweeper timeout and the agent's own hard+ // timeout land together — from the dashboard both read as "this run hung".+ timeout: "timeout",+ "agent_error.agent_timeout": "timeout",+ codex_semantic_inactivity: "timeout",++ // The upstream model API misbehaved or was asked for something it rejected.+ "agent_error.provider_server_error": "provider",+ "agent_error.provider_network": "provider",+ "agent_error.model_not_found_or_unavailable": "provider",+ api_invalid_request: "provider",++ // Multica-side execution substrate: daemon offline / restarted, task never+ // got picked up, runner binary missing or too old.+ runtime_offline: "runtime",+ runtime_recovery: "runtime",+ queued_expired: "runtime",+ "agent_error.runtime_missing_executable": "runtime",+ "agent_error.runtime_version_unsupported": "runtime",++ // The agent process itself produced the failure.+ "agent_error.process_failure": "agent",+ "agent_error.empty_or_unparseable_output": "agent",+ "agent_error.context_overflow": "agent",+ iteration_limit: "agent",+ agent_blocked: "agent",++ // Catchall + legacy coarse values.+ "agent_error.unknown": "other",+ agent_error: "other",+ manual: "other",+ unclassified: "other",+};++/**+ * Fold a raw `failure_reason` into its display class.+ *+ * Unknown reasons — including ones a newer backend introduced — resolve to+ * "other" rather than being dropped, so the class totals always reconcile+ * with the raw failure count.+ *+ * Callers must not pass the empty string: in the dashboard failure rollups+ * that value is the *succeeded* bucket, not a failure. It resolves to "other"+ * here so a caller that leaks one in inflates a visible bucket instead of+ * silently corrupting the error rate.+ */+export function failureClassOf(reason: string): FailureClass {+ return REASON_CLASS[reason] ?? "other";+}diff --git a/packages/core/dashboard/index.ts b/packages/core/dashboard/index.tsindex b69c251208..a9646e3da5 100644--- a/packages/core/dashboard/index.ts+++ b/packages/core/dashboard/index.ts@@ -1 +1,2 @@export * from "./queries";+export * from "./failure-class";diff --git a/packages/core/dashboard/queries.test.ts b/packages/core/dashboard/queries.test.tsindex 79df6815bd..5b8ff56a9d 100644--- a/packages/core/dashboard/queries.test.ts+++ b/packages/core/dashboard/queries.test.ts@@ -2,6 +2,8 @@ import { describe, expect, it } from "vitest";import {dashboardAgentRunTimeOptions,+ dashboardFailuresByAgentOptions,+ dashboardFailuresDailyOptions,dashboardRunTimeDailyOptions,dashboardUsageByAgentOptions,dashboardUsageDailyOptions,@@ -34,6 +36,8 @@ const optionBuilders = [dashboardUsageByAgentOptions,dashboardAgentRunTimeOptions,dashboardRunTimeDailyOptions,+ dashboardFailuresDailyOptions,+ dashboardFailuresByAgentOptions,] as const;describe("dashboard range placeholders", () => {diff --git a/packages/core/dashboard/queries.ts b/packages/core/dashboard/queries.tsindex 1417f58a74..fc95723a60 100644--- a/packages/core/dashboard/queries.ts+++ b/packages/core/dashboard/queries.ts@@ -27,6 +27,19 @@ export const dashboardKeys = {projectId: string | null,tz: string,) => [...dashboardKeys.all(wsId), "runtime-daily", days, projectId, tz] as const,+ failuresDaily: (+ wsId: string,+ days: number,+ projectId: string | null,+ tz: string,+ ) => [...dashboardKeys.all(wsId), "failures-daily", days, projectId, tz] as const,+ failuresByAgent: (+ wsId: string,+ days: number,+ projectId: string | null,+ tz: string,+ ) =>+ [...dashboardKeys.all(wsId), "failures-by-agent", days, projectId, tz] as const,};// 5-min rollup cadence on the server, 60s background refetch on the client.@@ -47,9 +60,9 @@ function isSameDashboardScope(}// `tz` participates in every dashboard key so a Preferences change-// repoints the cache. All four series — token rollups and the-// atq.completed_at-based run-time series — slice their day boundary in-// the viewer's tz, so the four dashboard tabs always agree.+// repoints the cache. Every series — token rollups and the+// atq.completed_at-based run-time / failure series — slices its day boundary+// in the viewer's tz, so all the dashboard tabs always agree.export function dashboardUsageDailyOptions(wsId: string,days: number,@@ -145,3 +158,51 @@ export function dashboardRunTimeDailyOptions(: undefined,});}++export function dashboardFailuresDailyOptions(+ wsId: string,+ days: number,+ projectId: string | null,+ tz: string,+) {+ const queryKey = dashboardKeys.failuresDaily(wsId, days, projectId, tz);+ return queryOptions({+ queryKey,+ queryFn: () =>+ api.getDashboardFailuresDaily({+ days,+ project_id: projectId ?? undefined,+ tz,+ }),+ enabled: !!wsId,+ staleTime: STALE_TIME,+ placeholderData: (previousData, previousQuery) =>+ isSameDashboardScope(previousQuery?.queryKey, queryKey)+ ? keepPreviousData(previousData)+ : undefined,+ });+}++export function dashboardFailuresByAgentOptions(+ wsId: string,+ days: number,+ projectId: string | null,+ tz: string,+) {+ const queryKey = dashboardKeys.failuresByAgent(wsId, days, projectId, tz);+ return queryOptions({+ queryKey,+ queryFn: () =>+ api.getDashboardFailuresByAgent({+ days,+ project_id: projectId ?? undefined,+ tz,+ }),+ enabled: !!wsId,+ staleTime: STALE_TIME,+ placeholderData: (previousData, previousQuery) =>+ isSameDashboardScope(previousQuery?.queryKey, queryKey)+ ? keepPreviousData(previousData)+ : undefined,+ });+}diff --git a/packages/core/types/agent.ts b/packages/core/types/agent.tsindex 41200b7a16..6fe333b160 100644--- a/packages/core/types/agent.ts+++ b/packages/core/types/agent.ts@@ -935,6 +935,32 @@ export interface DashboardRunTimeDaily {failed_count: number;}+// One (date, failure_reason) bucket of terminal-task counts for the workspace+// dashboard's Errors metric.+//+// `failure_reason` carries the backend's canonical failure taxonomy (the 21+// `taskfailure.Reason` values, plus `"unclassified"` for failed rows with an+// empty column) — EXCEPT for the empty string, which is the *succeeded*+// bucket. Shipping successes in the same series is deliberate: the error rate+// then has a denominator built on exactly the same filters as its numerator.+// `DashboardRunTimeDaily.task_count` is NOT a safe denominator here, because+// it only counts tasks that actually started and a queue-expired task never+// does.+export interface DashboardFailureDaily {+ date: string;+ failure_reason: string;+ task_count: number;+}++// Per-(agent, failure_reason) terminal-task counts. Same succeeded-bucket+// convention as DashboardFailureDaily, so the client can rank agents by+// failure rate rather than by raw failure count.+export interface DashboardFailureByAgent {+ agent_id: string;+ failure_reason: string;+ task_count: number;+}+export type RuntimeUpdateStatus =| "pending"| "running"diff --git a/packages/core/types/index.ts b/packages/core/types/index.tsindex 0b5e122d23..b10a46e262 100644--- a/packages/core/types/index.ts+++ b/packages/core/types/index.ts@@ -53,6 +53,8 @@ export type {DashboardUsageByAgent,DashboardAgentRunTime,DashboardRunTimeDaily,+ DashboardFailureDaily,+ DashboardFailureByAgent,RuntimeUpdate,RuntimeUpdateStatus,RuntimeModel,diff --git a/packages/views/agents/components/tabs/activity-tab.tsx b/packages/views/agents/components/tabs/activity-tab.tsxindex a670782739..6cb27c943d 100644--- a/packages/views/agents/components/tabs/activity-tab.tsx+++ b/packages/views/agents/components/tabs/activity-tab.tsx@@ -19,12 +19,7 @@ import {import { NumberFlow } from "@multica/ui/components/ui/number-flow";import { Skeleton } from "@multica/ui/components/ui/skeleton";import { useQueries, useQuery } from "@tanstack/react-query";-import type {- Agent,- AgentTask,- Issue,- TaskFailureReason,-} from "@multica/core/types";+import type { Agent, AgentTask, Issue } from "@multica/core/types";import {type AgentActivity,agentTaskSnapshotOptions,@@ -589,12 +584,11 @@ function TaskRow({: "—";// Failure reason. The back-end emits "" on non-failed tasks (omitempty- // strips it on the wire) so the truthy guard is the right shape; the- // cast is safe because the back-end only emits one of the enum values.+ // strips it on the wire) so the truthy guard is the right shape.+ // failureReasonLabel takes the raw open string — the taxonomy has 21+ // values and grows, so there is no enum to cast to.const failureLabel =- task.status === "failed" && task.failure_reason- ? failureReasonLabel[task.failure_reason as TaskFailureReason]- : null;+ task.status === "failed" ? failureReasonLabel(task.failure_reason) : null;// Only show duration for terminal rows. An active row's duration is// inferred from the timeText already ("Started 2m ago") and adding adiff --git a/packages/views/agents/components/tabs/task-failure.test.ts b/packages/views/agents/components/tabs/task-failure.test.tsnew file mode 100644index 0000000000..ac8099ec52--- /dev/null+++ b/packages/views/agents/components/tabs/task-failure.test.ts@@ -0,0 +1,44 @@+import { describe, expect, it } from "vitest";++import { failureReasonLabel } from "./task-failure";++// This is the copy the Usage page's Errors breakdown drills into: a top+// offender is only actionable if the runs it links to actually say why they+// failed.+describe("failureReasonLabel", () => {+ it("labels the refined agent_error.* reasons the backend has written since MUL-1949", () => {+ // Regression: this used to be a Record indexed with a cast to the old+ // 6-value coarse enum, so every one of these resolved to `undefined` and+ // the row rendered no reason at all.+ expect(failureReasonLabel("agent_error.provider_auth_or_access")).toBe(+ "Provider auth failed",+ );+ expect(failureReasonLabel("agent_error.provider_capacity_or_rate_limit")).toBe(+ "Rate limited by provider",+ );+ expect(failureReasonLabel("agent_error.context_overflow")).toBe(+ "Context window exceeded",+ );+ expect(failureReasonLabel("queued_expired")).toBe("Expired in queue");+ });++ it("still labels the pre-MUL-1949 coarse reasons on historical rows", () => {+ expect(failureReasonLabel("agent_error")).toBe("Agent execution error");+ expect(failureReasonLabel("runtime_offline")).toBe("Daemon offline");+ expect(failureReasonLabel("manual")).toBe("Cancelled by user");+ });++ it("falls back to the raw wire value for a reason this build predates", () => {+ // Truthful and searchable beats blank — the operator can paste it into a+ // log search.+ expect(failureReasonLabel("agent_error.from_a_newer_backend")).toBe(+ "agent_error.from_a_newer_backend",+ );+ });++ it("returns null when there is no reason to show", () => {+ expect(failureReasonLabel("")).toBeNull();+ expect(failureReasonLabel(null)).toBeNull();+ expect(failureReasonLabel(undefined)).toBeNull();+ });+});diff --git a/packages/views/agents/components/tabs/task-failure.ts b/packages/views/agents/components/tabs/task-failure.tsindex 6572bac2be..1cac1723b7 100644--- a/packages/views/agents/components/tabs/task-failure.ts+++ b/packages/views/agents/components/tabs/task-failure.ts@@ -1,17 +1,65 @@-import type { TaskFailureReason } from "@multica/core/types";--// Human-readable copy for the back-end task failure reason enum. Surfaced-// in the agent detail Recent Work tab when a task ended in failure — the-// only place the front-end exposes failure_reason directly to the user.+// Human-readable copy for the back-end task failure reason. Surfaced in the+// agent detail Recent Work list and the issue execution log — the two places+// the front-end exposes failure_reason directly to the user, and the+// destination the Usage page's Errors breakdown drills into.//// Lives next to the consuming tab (rather than in agents/presence) because// failed tasks no longer have a top-level workload state; failure context// is purely a detail-page concern now.-export const failureReasonLabel: Record<TaskFailureReason, string> = {- agent_error: "Agent execution error",- timeout: "Task timed out",- codex_semantic_inactivity: "Codex semantic inactivity timeout",+//+// Covers the canonical taxonomy in server/pkg/taskfailure — 7 platform-side+// reasons plus 14 `agent_error.*` sub-reasons — and the pre-MUL-1949 coarse+// values still present on historical rows. This used to be a+// `Record<TaskFailureReason, string>` indexed with a cast, which silently+// resolved to `undefined` for every refined reason the backend has written+// since MUL-1949: a task that failed on a provider 401 rendered no reason+// at all.+const REASON_LABEL: Record<string, string> = {+ // Platform / scheduler side.+ queued_expired: "Expired in queue",runtime_offline: "Daemon offline",runtime_recovery: "Daemon restarted",+ timeout: "Task timed out",+ iteration_limit: "Hit the iteration limit",+ agent_blocked: "Waiting on human input",+ api_invalid_request: "Rejected by the model API",++ // Agent process side — provider.+ "agent_error.provider_auth_or_access": "Provider auth failed",+ "agent_error.provider_quota_limit": "Provider quota exhausted",+ "agent_error.provider_capacity_or_rate_limit": "Rate limited by provider",+ "agent_error.provider_server_error": "Provider server error",+ "agent_error.provider_network": "Network error reaching provider",++ // Agent process side — agent / runner.+ "agent_error.process_failure": "Agent process crashed",+ "agent_error.empty_or_unparseable_output": "Agent returned no usable output",+ "agent_error.agent_timeout": "Agent timed out",+ "agent_error.context_overflow": "Context window exceeded",+ "agent_error.missing_config": "Missing API key or configuration",+ "agent_error.model_not_found_or_unavailable": "Model unavailable",+ "agent_error.runtime_version_unsupported": "Runner CLI version unsupported",+ "agent_error.runtime_missing_executable": "Runner CLI not installed",+ "agent_error.unknown": "Agent execution error",++ // Pre-MUL-1949 coarse values, still present on historical rows.+ agent_error: "Agent execution error",+ codex_semantic_inactivity: "Codex semantic inactivity timeout",manual: "Cancelled by user",};++/**+ * Label for a `failure_reason`, or `null` when there is nothing to show.+ *+ * `failure_reason` is an open string, not a closed enum: the taxonomy grows+ * as classifier rules land, and an installed desktop client will meet+ * reasons its build predates. Those fall back to the raw wire value rather+ * than to nothing — machine-y, but truthful, and it is the exact string an+ * operator would paste into a log search.+ */+export function failureReasonLabel(+ reason: string | null | undefined,+): string | null {+ if (!reason) return null;+ return REASON_LABEL[reason] ?? reason;+}diff --git a/packages/views/dashboard/components/dashboard-page.test.tsx b/packages/views/dashboard/components/dashboard-page.test.tsxindex 0073813d63..f2360a856f 100644--- a/packages/views/dashboard/components/dashboard-page.test.tsx+++ b/packages/views/dashboard/components/dashboard-page.test.tsx@@ -1,6 +1,9 @@import { describe, it, expect, beforeEach, vi } from "vitest";-import { cleanup } from "@testing-library/react";+import { cleanup, screen, within } from "@testing-library/react";+import userEvent from "@testing-library/user-event";import { renderWithI18n } from "../../test/i18n";+import { NavigationProvider } from "../../navigation";+import type { NavigationAdapter } from "../../navigation";// The viewing timezone flows: auth store `user.timezone` → useViewingTimezone()// → every dashboard query key. This test pins that chain: when the stored@@ -26,6 +29,15 @@ vi.mock("@tanstack/react-query", async () => {useQuery: (opts: { queryKey: unknown[] }) => {queryKeys.push(opts.queryKey);if (dashboardDataRef.current) {+ // ["workspaces", wsId, "agents"] — needed so the Errors breakdown can+ // resolve agent-1 to a name and render its drill-down link.+ if (opts.queryKey[0] === "workspaces" && opts.queryKey[2] === "agents") {+ return {+ data: [{ id: "agent-1", name: "Agent One" }],+ isLoading: false,+ isSuccess: true,+ };+ }const kind = opts.queryKey[2];const data =kind === "daily"@@ -59,7 +71,41 @@ vi.mock("@tanstack/react-query", async () => {failed_count: 1,},]- : [];+ : // `failure_reason: ""` is the succeeded bucket — the+ // denominator behind every rate the Errors surface shows.+ kind === "failures-daily"+ ? [+ { date: todayIso(), failure_reason: "", task_count: 6 },+ {+ date: todayIso(),+ failure_reason: "agent_error.provider_auth_or_access",+ task_count: 3,+ },+ { date: todayIso(), failure_reason: "timeout", task_count: 1 },+ ]+ : kind === "failures-by-agent"+ ? [+ { agent_id: "agent-1", failure_reason: "", task_count: 6 },+ {+ agent_id: "agent-1",+ failure_reason: "agent_error.provider_auth_or_access",+ task_count: 3,+ },+ {+ agent_id: "agent-1",+ failure_reason: "timeout",+ task_count: 1,+ },+ // Not in the agent list below — a private agent this+ // member cannot see, or a deleted one. The rollup+ // still returns it.+ {+ agent_id: "0f9d1c2e-private-agent-uuid",+ failure_reason: "agent_error.provider_auth_or_access",+ task_count: 2,+ },+ ]+ : [];return { data, isLoading: false, isSuccess: true };}return { data: undefined, isLoading: true };@@ -71,6 +117,18 @@ vi.mock("@multica/core/hooks", () => ({useWorkspaceId: () => "ws-1",}));+// The leaderboard renders ActorAvatar, which resolves avatar URLs through+// the api singleton. Only the base-URL read is exercised here.+vi.mock("@multica/core/api", () => ({+ api: { getBaseUrl: () => "https://example.test" },+}));++vi.mock("@multica/core/paths", () => ({+ useWorkspacePaths: () => ({+ agentDetail: (id: string) => `/acme/agents/${id}`,+ }),+}));+const tzRef = vi.hoisted(() => ({ current: "UTC" as string | null }));vi.mock("@multica/core/auth", () => {@@ -95,6 +153,28 @@ 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}>+ <DashboardPage />+ </NavigationProvider>,+ );+}+describe("DashboardPage — viewing timezone drives the query key", () => {beforeEach(() => {queryKeys.length = 0;@@ -145,7 +225,7 @@ describe("DashboardPage — viewing timezone drives the query key", () => {dashboardDataRef.current = true;tzRef.current = "UTC";- const { container } = renderWithI18n(<DashboardPage />);+ const { container } = renderDashboard();const flows = Array.from(container.querySelectorAll("number-flow-react"),);@@ -164,3 +244,98 @@ describe("DashboardPage — viewing timezone drives the query key", () => {).toBe(true);});});++describe("DashboardPage — failure visibility", () => {+ beforeEach(() => {+ queryKeys.length = 0;+ dashboardDataRef.current = true;+ tzRef.current = "UTC";+ 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.+ renderDashboard();++ expect(screen.getByText("4 of 10 runs failed · 40%")).toBeInTheDocument();+ // The Tasks tile keeps its own started-tasks-only figure.+ expect(screen.getByText("1 failed")).toBeInTheDocument();+ });++ it("breaks failures down by class and links the offending agent to its runs", () => {+ renderDashboard();++ // 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" }));+ expect(byClass.getAllByRole("listitem").map((li) => li.textContent)).toEqual([+ "Auth3",+ "Timeout1",+ ]);++ const byAgent = within(screen.getByRole("list", { name: "Top offenders" }));+ const link = byAgent.getByRole("link", { name: /Agent One/ });+ // Overview, NOT ?view=work: Work lists the issues assigned to the agent,+ // 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();+ });++ it("reveals the raw failure_reason values behind the class summary", async () => {+ const user = userEvent.setup();+ renderDashboard();++ expect(+ screen.queryByText("agent_error.provider_auth_or_access"),+ ).not.toBeInTheDocument();++ await user.click(screen.getByRole("button", { name: "Show error codes" }));++ // Raw and unlocalised: an operator pastes this exact string into a log+ // search, so it must not be translated or prettified.+ expect(+ screen.getByText("agent_error.provider_auth_or_access"),+ ).toBeInTheDocument();+ });++ it("adds Errors to the trend toggle without disturbing the other metrics", async () => {+ const user = userEvent.setup();+ const { container } = renderDashboard();++ await user.click(screen.getByRole("button", { name: "Errors" }));++ expect(container).toHaveTextContent("Daily errors");+ });+});++describe("DashboardPage — the Errors list never exposes an agent the viewer can't see", () => {+ beforeEach(() => {+ queryKeys.length = 0;+ dashboardDataRef.current = true;+ tzRef.current = "UTC";+ cleanup();+ });++ it("folds an unresolvable agent into an anonymous row instead of printing its UUID", () => {+ // 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 { container } = renderDashboard();++ expect(container).not.toHaveTextContent("0f9d1c2e-private-agent-uuid");++ const byAgent = within(screen.getByRole("list", { name: "Top offenders" }));+ expect(byAgent.getByText("Other agents")).toBeInTheDocument();+ // Anonymous, and therefore not a link — there is no page to open.+ expect(+ byAgent.queryByRole("link", { name: /Other agents/ }),+ ).not.toBeInTheDocument();+ });+});diff --git a/packages/views/dashboard/components/dashboard-page.tsx b/packages/views/dashboard/components/dashboard-page.tsxindex 036e1ad683..d0928dd73c 100644--- a/packages/views/dashboard/components/dashboard-page.tsx+++ b/packages/views/dashboard/components/dashboard-page.tsx@@ -26,7 +26,11 @@ import {dashboardUsageByAgentOptions,dashboardAgentRunTimeOptions,dashboardRunTimeDailyOptions,+ dashboardFailuresDailyOptions,+ dashboardFailuresByAgentOptions,+ 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";@@ -36,13 +40,18 @@ import {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 {addDaysIso,aggregateByWeek,@@ -51,19 +60,30 @@ import {} from "../../runtimes/utils";import { useT } from "../../i18n";import {+ aggregateAgentFailures,aggregateAgentTokens,aggregateDailyCost,+ aggregateDailyErrors,aggregateDailyTasks,aggregateDailyTime,aggregateDailyTokens,+ aggregateFailureClasses,+ aggregateFailureReasons,+ aggregateWeeklyErrors,aggregateWeeklyTasks,aggregateWeeklyTime,bucketUnknownAgentRows,+ anonymizeUnresolvedAgentRows,computeDailyTotals,+ computeFailureTotals,DELETED_AGENTS_ROW_ID,formatDuration,mergeAgentDashboardRows,type AgentDashboardRow,+ type AgentFailureRow,+ type FailureClassRow,+ type FailureReasonRow,+ type FailureTotals,} from "../utils";// Period selector — mirrors the runtime detail page so users see the same@@ -107,6 +127,9 @@ const EMPTY_DAILY: import("@multica/core/types").DashboardUsageDaily[] = [];const EMPTY_BY_AGENT: import("@multica/core/types").DashboardUsageByAgent[] = [];const EMPTY_RUNTIME: import("@multica/core/types").DashboardAgentRunTime[] = [];const EMPTY_RUNTIME_DAILY: import("@multica/core/types").DashboardRunTimeDaily[] = [];+const EMPTY_FAILURE_DAILY: import("@multica/core/types").DashboardFailureDaily[] = [];+const EMPTY_FAILURE_BY_AGENT: import("@multica/core/types").DashboardFailureByAgent[] =+ [];const EMPTY_AGENTS: Agent[] = [];// Local segmented control — same visual language the runtime usage section@@ -247,11 +270,19 @@ export function DashboardPage() {const runTimeDailyQuery = useQuery(dashboardRunTimeDailyOptions(wsId, chartFetchDays, projectId, viewTZ),);+ const failuresDailyQuery = useQuery(+ dashboardFailuresDailyOptions(wsId, chartFetchDays, projectId, viewTZ),+ );+ const failuresByAgentQuery = useQuery(+ dashboardFailuresByAgentOptions(wsId, days, projectId, viewTZ),+ );const dailyUsage = dailyQuery.data ?? EMPTY_DAILY;const byAgentUsage = byAgentQuery.data ?? EMPTY_BY_AGENT;const runTimeRows = runTimeQuery.data ?? EMPTY_RUNTIME;const runTimeDailyRows = runTimeDailyQuery.data ?? EMPTY_RUNTIME_DAILY;+ 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@@ -272,14 +303,20 @@ export function DashboardPage() {() => runTimeDailyRows.filter((r) => r.date >= dailyCutoffIso),[runTimeDailyRows, dailyCutoffIso],);+ const failureDailyInWindow = useMemo(+ () => failureDailyRows.filter((r) => r.date >= dailyCutoffIso),+ [failureDailyRows, dailyCutoffIso],+ );const isLoading =dailyQuery.isLoading ||byAgentQuery.isLoading ||runTimeQuery.isLoading ||- runTimeDailyQuery.isLoading;+ runTimeDailyQuery.isLoading ||+ failuresDailyQuery.isLoading ||+ failuresByAgentQuery.isLoading;- // Four independent rollups, but the empty-state is one decision — only+ // 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 =@@ -287,7 +324,9 @@ export function DashboardPage() {dailyUsage.length === 0 &&byAgentUsage.length === 0 &&runTimeRows.length === 0 &&- runTimeDailyRows.length === 0;+ runTimeDailyRows.length === 0 &&+ failureDailyRows.length === 0 &&+ failureByAgentRows.length === 0;// Cost / token math — re-derived when usage, days, or pricings change.const totals = useMemo(@@ -310,6 +349,56 @@ export function DashboardPage() {() => aggregateDailyTasks(runTimeDailyInWindow),[runTimeDailyInWindow],);+ const dailyErrors = useMemo(+ () => aggregateDailyErrors(failureDailyInWindow),+ [failureDailyInWindow],+ );++ // Failure summaries for the Errors breakdown card.+ //+ // 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.+ const failureTotals = useMemo(+ () => computeFailureTotals(failureDailyInWindow),+ [failureDailyInWindow],+ );+ const failureClassRows = useMemo(+ () => aggregateFailureClasses(failureDailyInWindow),+ [failureDailyInWindow],+ );+ const failureReasonRows = useMemo(+ () => aggregateFailureReasons(failureDailyInWindow),+ [failureDailyInWindow],+ );+ // Which agent ids this viewer can actually resolve to a name. Declared here+ // rather than next to the leaderboard because the Errors aggregation below+ // needs it too — see anonymizeUnresolvedAgentRows.+ const knownAgentIds = useMemo(+ () => (agentsQuery.isSuccess ? new Set(agents.map((a) => a.id)) : null),+ [agentsQuery.isSuccess, agents],+ );++ // The per-agent split has no date to trim on, so its window is closed+ // server-side instead — GetDashboardFailuresByAgent uses the exact N-day+ // cutoff rather than the N+1 one.+ //+ // Anonymize BEFORE aggregating: the sentinel then behaves like any other+ // agent id, so the bucket's failure classes are summed from real+ // per-(agent, reason) rows instead of being reconstructed from rows that+ // have already collapsed to a single dominant class.+ const agentFailureRows = useMemo(+ () =>+ aggregateAgentFailures(+ anonymizeUnresolvedAgentRows(failureByAgentRows, knownAgentIds),+ ),+ [failureByAgentRows, knownAgentIds],+ );// Weekly aggregates — built from the over-fetched per-date queries so the// leftmost trailing week always has data even when the user-selected `days`@@ -331,6 +420,10 @@ export function DashboardPage() {() => aggregateWeeklyTasks(runTimeDailyRows, viewTZ, weekCount),[runTimeDailyRows, viewTZ, weekCount],);+ const weeklyErrors = useMemo(+ () => aggregateWeeklyErrors(failureDailyRows, viewTZ, weekCount),+ [failureDailyRows, viewTZ, weekCount],+ );const agentTokenRows = useMemo(() => aggregateAgentTokens(byAgentUsage),[byAgentUsage],@@ -362,10 +455,6 @@ export function DashboardPage() {// archived included); only truly-removed agents collapse into the bucket.// Skip bucketing until the agent list has loaded so a slow agents fetch// doesn't transiently merge every row.- const knownAgentIds = useMemo(- () => (agentsQuery.isSuccess ? new Set(agents.map((a) => a.id)) : null),- [agentsQuery.isSuccess, agents],- );const visibleAgentRows = useMemo(() => bucketUnknownAgentRows(agentRows, knownAgentIds),[agentRows, knownAgentIds],@@ -473,6 +562,12 @@ export function DashboardPage() {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,})}@@ -480,24 +575,38 @@ export function DashboardPage() {/></div>- {/* Trend chart — toggle picks Tokens / Cost / Time / Tasks- and the parent's dim selector decides whether the bars are- per-day or per-calendar-week. All four metrics share the- same x-axis so the user can mentally overlay them by- flipping the toggle. */}+ {/* 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. */}<TrendBlockdim={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)}/>+ {/* 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+ totals={failureTotals}+ classRows={failureClassRows}+ reasonRows={failureReasonRows}+ agentRows={agentFailureRows}+ agents={agents}+ />+{/* Per-agent leaderboard — user picks the ranking metric;the progress bar and column emphasis follow the metric. */}<Leaderboard@@ -576,7 +685,7 @@ function ProjectFilter({);}-type DailyMetric = "tokens" | "cost" | "time" | "tasks";+type DailyMetric = "tokens" | "cost" | "time" | "tasks" | "errors";function TrendBlock({dim,@@ -584,10 +693,12 @@ function TrendBlock({dailyTokens,dailyTime,dailyTasks,+ dailyErrors,weeklyCost,weeklyTokens,weeklyTime,weeklyTasks,+ weeklyErrors,lessThanMinuteLabel,}: {dim: Dim;@@ -595,10 +706,12 @@ function TrendBlock({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");@@ -611,6 +724,7 @@ function TrendBlock({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(@@ -622,6 +736,10 @@ function TrendBlock({(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@@ -629,7 +747,9 @@ function TrendBlock({? totalTokens === 0: metric === "time"? totalSeconds === 0- : totalTasks === 0;+ : metric === "tasks"+ ? totalTasks === 0+ : totalFailed === 0;const title =dim === "weekly"@@ -639,14 +759,18 @@ function TrendBlock({? t(($) => $.weekly.title_tokens): metric === "time"? t(($) => $.weekly.title_time)- : t(($) => $.weekly.title_tasks)+ : 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)- : t(($) => $.daily.title_tasks);+ : metric === "tasks"+ ? t(($) => $.daily.title_tasks)+ : t(($) => $.daily.title_errors);return (<div className="rounded-lg border bg-card p-4">@@ -660,6 +784,7 @@ function TrendBlock({{ 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>@@ -668,7 +793,9 @@ function TrendBlock({<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-muted-foreground/50" /><p className="text-xs text-muted-foreground">- {t(($) => $.daily.no_data)}+ {metric === "errors"+ ? t(($) => $.errors.no_data)+ : t(($) => $.daily.no_data)}</p></div>) : dim === "weekly" ? (@@ -682,8 +809,10 @@ function TrendBlock({formatY={(s) => formatDuration(s, lessThanMinuteLabel)}formatTooltip={(s) => formatDuration(s, lessThanMinuteLabel)}/>- ) : (+ ) : metric === "tasks" ? (<WeeklyTasksChart data={weeklyTasks} />+ ) : (+ <WeeklyErrorsChart data={weeklyErrors} />)) : metric === "cost" ? (<DailyCostChart data={dailyCost} />@@ -695,14 +824,252 @@ function TrendBlock({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);+ }+ };+}++/**+ * Failure breakdown for the selected window: what class of thing broke, and+ * which agents it broke for.+ *+ * Two ranked lists rather than a second chart — with seven classes and an+ * unbounded agent list, bar length plus an exact number is easier to read+ * than more stacked colour, and it leaves room for the raw error codes+ * behind a disclosure.+ */+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 maxClass = classRows.reduce((m, r) => Math.max(m, r.count), 0);+ const maxAgent = agentRows.reduce((m, r) => Math.max(m, r.failed), 0);++ 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-sm font-semibold">{t(($) => $.errors.title)}</h4>+ <span className="text-xs 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="grid grid-cols-1 divide-y md:grid-cols-2 md:divide-x md:divide-y-0">+ <div className="min-w-0 p-4">+ <div className="mb-2 flex items-center justify-between gap-2">+ <h5 className="text-xs font-medium text-muted-foreground">+ {t(($) => $.errors.by_class)}+ </h5>+ <button+ type="button"+ onClick={() => setShowReasons((v) => !v)}+ className="text-xs text-muted-foreground underline-offset-2 hover:text-foreground hover:underline"+ >+ {showReasons+ ? t(($) => $.errors.hide_reasons)+ : t(($) => $.errors.show_reasons)}+ </button>+ </div>+ {showReasons ? (+ // Raw failure_reason values, 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.+ <ul aria-label={t(($) => $.errors.by_class)} className="space-y-1.5">+ {reasonRows.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-xs text-muted-foreground">+ {row.reason}+ </code>+ </span>+ <span className="shrink-0 text-xs tabular-nums">+ {row.count}+ </span>+ </li>+ ))}+ </ul>+ ) : (+ <ul aria-label={t(($) => $.errors.by_class)} className="space-y-2">+ {classRows.map((row) => (+ <li key={row.failureClass} className="space-y-1">+ <div className="flex items-center justify-between gap-2 text-xs">+ <span className="truncate">{classLabel(row.failureClass)}</span>+ <span className="shrink-0 tabular-nums text-muted-foreground">+ {row.count}+ </span>+ </div>+ <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: `${maxClass > 0 ? (row.count / maxClass) * 100 : 0}%`,+ backgroundColor: FAILURE_CLASS_COLOR[row.failureClass],+ }}+ />+ </div>+ </li>+ ))}+ </ul>+ )}+ </div>++ <div className="min-w-0 p-4">+ <h5 className="mb-2 text-xs font-medium text-muted-foreground">+ {t(($) => $.errors.by_agent)}+ </h5>+ <ul aria-label={t(($) => $.errors.by_agent)} className="space-y-2">+ {agentRows.map((row) => (+ <AgentFailureItem+ key={row.agentId}+ row={row}+ name={agents.find((a) => a.id === row.agentId)?.name ?? null}+ maxFailed={maxAgent}+ classLabel={classLabel}+ />+ ))}+ </ul>+ </div>+ </div>+ )}+ </div>+ );+}++function AgentFailureItem({+ row,+ name,+ maxFailed,+ classLabel,+}: {+ row: AgentFailureRow;+ name: string | null;+ maxFailed: number;+ classLabel: (c: FailureClass) => string;+}) {+ const { t } = useT("usage");+ const wsPaths = useWorkspacePaths();+ const barColor = FAILURE_CLASS_COLOR[row.topClass ?? "other"];++ // 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="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>+ );++ return (+ <li className="space-y-1">+ <div className="flex items-center justify-between gap-2">+ {name ? (+ <AppLink+ href={`${wsPaths.agentDetail(row.agentId)}?view=overview`}+ newTabTitle={name}+ className="min-w-0 hover:underline"+ >+ {label}+ </AppLink>+ ) : (+ label+ )}+ <span className="shrink-0 text-xs tabular-nums text-muted-foreground">+ {t(($) => $.errors.agent_rate, {+ failed: row.failed,+ total: row.total,+ rate: formatRate(row.failed, row.total),+ })}+ </span>+ </div>+ <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,+ }}+ />+ </div>+ </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.diff --git a/packages/views/dashboard/utils.test.ts b/packages/views/dashboard/utils.test.tsindex 58f273b126..0608477d2f 100644--- a/packages/views/dashboard/utils.test.ts+++ b/packages/views/dashboard/utils.test.ts@@ -1,11 +1,19 @@import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";import {+ aggregateAgentFailures,+ anonymizeUnresolvedAgentRows,+ UNRESOLVED_AGENTS_ROW_ID,aggregateAgentTokens,aggregateDailyCost,+ aggregateDailyErrors,+ aggregateFailureClasses,+ aggregateFailureReasons,+ aggregateWeeklyErrors,aggregateWeeklyTasks,aggregateWeeklyTime,bucketUnknownAgentRows,computeDailyTotals,+ computeFailureTotals,DELETED_AGENTS_ROW_ID,formatDuration,mergeAgentDashboardRows,@@ -393,3 +401,212 @@ describe("aggregateWeeklyTasks", () => {});});});++// ---------------------------------------------------------------------------+// Failure aggregations+//+// The rollups ship succeeded rows too, marked by `failure_reason: ""`. Every+// test below leans on that: the succeeded row is what makes an error *rate*+// possible, and mishandling it is the failure mode with the worst blast+// radius — a rate that reads 100% when nothing is wrong.+// ---------------------------------------------------------------------------++describe("aggregateDailyErrors", () => {+ it("stacks failures by class and keeps the succeeded rows as the denominator", () => {+ const result = aggregateDailyErrors([+ { date: "2026-05-10", failure_reason: "", task_count: 8 },+ {+ date: "2026-05-10",+ failure_reason: "agent_error.provider_auth_or_access",+ task_count: 2,+ },+ { date: "2026-05-10", failure_reason: "timeout", task_count: 1 },+ { date: "2026-05-09", failure_reason: "", task_count: 4 },+ ]);++ expect(result.map((r) => r.date)).toEqual(["2026-05-09", "2026-05-10"]);+ expect(result[1]).toMatchObject({+ auth: 2,+ timeout: 1,+ rate_limit: 0,+ failed: 3,+ total: 11,+ });+ // A day with only successes still renders a bar slot, at zero height.+ expect(result[0]).toMatchObject({ failed: 0, total: 4 });+ });++ it("folds a reason this build has never seen into 'other' rather than dropping it", () => {+ const [row] = aggregateDailyErrors([+ { date: "2026-05-10", failure_reason: "agent_error.from_the_future", task_count: 5 },+ ]);+ expect(row).toMatchObject({ other: 5, failed: 5, total: 5 });+ });+});++describe("aggregateWeeklyErrors", () => {+ beforeEach(() => {+ vi.useFakeTimers();+ });+ afterEach(() => {+ vi.useRealTimers();+ });++ it("buckets per calendar week and pre-zeroes weeks with no terminal tasks", () => {+ vi.setSystemTime(new Date("2026-05-19T12:00:00Z"));+ const result = aggregateWeeklyErrors(+ [+ { date: "2026-05-12", failure_reason: "runtime_offline", task_count: 2 },+ { date: "2026-05-12", failure_reason: "", task_count: 6 },+ ],+ "UTC",+ 2,+ );++ expect(result[0]).toMatchObject({+ weekStart: "2026-05-11",+ runtime: 2,+ failed: 2,+ total: 8,+ });+ expect(result[1]).toMatchObject({+ weekStart: "2026-05-18",+ failed: 0,+ total: 0,+ partial: true,+ });+ });+});++describe("computeFailureTotals", () => {+ it("excludes the succeeded bucket from the numerator but not the denominator", () => {+ expect(+ computeFailureTotals([+ { failure_reason: "", task_count: 9 },+ { failure_reason: "timeout", task_count: 1 },+ ]),+ ).toEqual({ failed: 1, total: 10, rate: 0.1 });+ });++ it("reports rate 0 rather than dividing by zero on an empty window", () => {+ expect(computeFailureTotals([])).toEqual({ failed: 0, total: 0, rate: 0 });+ });+});++describe("aggregateFailureClasses / aggregateFailureReasons", () => {+ const rows = [+ { failure_reason: "", task_count: 20 },+ { failure_reason: "agent_error.provider_quota_limit", task_count: 3 },+ { failure_reason: "agent_error.provider_capacity_or_rate_limit", task_count: 4 },+ { failure_reason: "timeout", task_count: 5 },+ ];++ it("merges reasons that share a class and ranks by count desc", () => {+ expect(aggregateFailureClasses(rows)).toEqual([+ { failureClass: "rate_limit", count: 7 },+ { failureClass: "timeout", count: 5 },+ ]);+ });++ it("keeps raw reasons separate so an operator can search the exact string", () => {+ expect(aggregateFailureReasons(rows)).toEqual([+ { reason: "timeout", failureClass: "timeout", count: 5 },+ {+ reason: "agent_error.provider_capacity_or_rate_limit",+ failureClass: "rate_limit",+ count: 4,+ },+ {+ reason: "agent_error.provider_quota_limit",+ failureClass: "rate_limit",+ count: 3,+ },+ ]);+ });+});++describe("aggregateAgentFailures", () => {+ it("ranks by failure count, carries the rate, and names the dominant class", () => {+ const result = aggregateAgentFailures([+ { agent_id: "a", failure_reason: "", task_count: 90 },+ { agent_id: "a", failure_reason: "timeout", task_count: 10 },+ { agent_id: "b", failure_reason: "", task_count: 1 },+ { agent_id: "b", failure_reason: "runtime_offline", task_count: 3 },+ { agent_id: "b", failure_reason: "timeout", task_count: 1 },+ ]);++ // `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" },+ ]);+ });++ it("drops agents with no failures — the list is triage, not a census", () => {+ expect(+ aggregateAgentFailures([{ agent_id: "clean", failure_reason: "", task_count: 42 }]),+ ).toEqual([]);+ });+});++describe("anonymizeUnresolvedAgentRows", () => {+ // Raw per-(agent, reason) rows, which is the shape this operates on. Two+ // agents the viewer cannot resolve, with deliberately conflicting dominant+ // classes — see the counterexample test below.+ const rows = [+ { agent_id: "visible", failure_reason: "", task_count: 5 },+ { agent_id: "visible", failure_reason: "timeout", task_count: 5 },+ {+ agent_id: "private-a",+ failure_reason: "agent_error.provider_auth_or_access",+ task_count: 6,+ },+ { agent_id: "private-a", failure_reason: "timeout", task_count: 5 },+ { agent_id: "private-b", failure_reason: "timeout", task_count: 10 },+ ];++ it("rewrites unresolvable ids to the sentinel and leaves resolvable ones alone", () => {+ const result = anonymizeUnresolvedAgentRows(rows, new Set(["visible"]));++ expect(result.map((r) => r.agent_id)).toEqual([+ "visible",+ "visible",+ UNRESOLVED_AGENTS_ROW_ID,+ UNRESOLVED_AGENTS_ROW_ID,+ UNRESOLVED_AGENTS_ROW_ID,+ ]);+ // Counts are untouched — only identity is erased.+ expect(result.map((r) => r.task_count)).toEqual([5, 5, 6, 5, 10]);+ });++ it("keeps the bucket's dominant class 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.+ 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" });+ });++ it("anonymizes everything while the agent list is still loading", () => {+ // Deliberately stricter than bucketUnknownAgentRows, which passes rows+ // through on null: a transient flash of raw UUIDs is precisely the leak+ // this function exists to prevent.+ const result = anonymizeUnresolvedAgentRows(rows, null);++ expect(new Set(result.map((r) => r.agent_id))).toEqual(+ new Set([UNRESOLVED_AGENTS_ROW_ID]),+ );+ });++ it("returns the input untouched when every agent resolves", () => {+ const known = new Set(["visible", "private-a", "private-b"]);+ // Same reference, not just equal — nothing needed rewriting.+ expect(anonymizeUnresolvedAgentRows(rows, known)).toBe(rows);+ });+});diff --git a/packages/views/dashboard/utils.ts b/packages/views/dashboard/utils.tsindex 16c9b1f15c..1efbd9500a 100644--- a/packages/views/dashboard/utils.ts+++ b/packages/views/dashboard/utils.ts@@ -3,7 +3,14 @@ import type {DashboardUsageByAgent,DashboardAgentRunTime,DashboardRunTimeDaily,+ DashboardFailureDaily,+ DashboardFailureByAgent,} from "@multica/core/types";+import {+ FAILURE_CLASSES,+ failureClassOf,+ type FailureClass,+} from "@multica/core/dashboard";import {addDaysIso,estimateCost,@@ -18,6 +25,10 @@ import type {DailyTasksData,WeeklyTimeData,WeeklyTasksData,+ DailyErrorsData,+ WeeklyErrorsData,+ FailureBucketTotals,+ FailureClassCounts,} from "../runtimes/components/charts";// ---------------------------------------------------------------------------@@ -427,3 +438,258 @@ export function formatDuration(seconds: number, lessThanMinuteLabel: string): st}return mins > 0 ? `${hours}h ${mins}m` : `${hours}h`;}++// ---------------------------------------------------------------------------+// Failure aggregations+//+// The two failure rollups ship every terminal task, with `failure_reason: ""`+// marking the succeeded bucket. Keeping successes in the same payload is what+// lets these helpers produce an error *rate* whose numerator and denominator+// come from identical filters — the run-time rollups can't serve as the+// denominator because they require `started_at IS NOT NULL` and a task that+// expired in the queue never started.+//+// Everything here folds raw reasons into the seven display classes from+// `@multica/core/dashboard`; the raw reason survives only in+// `aggregateFailureReasons`, which powers the detail rows under the class+// summary.+// ---------------------------------------------------------------------------++function emptyClassCounts(): FailureClassCounts {+ return Object.fromEntries(+ FAILURE_CLASSES.map((c) => [c, 0]),+ ) as FailureClassCounts;+}++// Fold one rollup row into a mutable accumulator. `failure_reason: ""` is the+// succeeded bucket: it moves `total` only, never `failed` or a class.+function foldFailureRow(+ acc: FailureClassCounts & FailureBucketTotals,+ reason: string,+ count: number,+): void {+ acc.total += count;+ if (reason === "") return;+ acc.failed += count;+ acc[failureClassOf(reason)] += count;+}++// Per-(date, reason) rows → one row per date with per-class failure counts+// and the day's failed / total totals. Sorted date asc to match the other+// daily aggregators.+export function aggregateDailyErrors(+ rows: DashboardFailureDaily[],+): DailyErrorsData[] {+ const map = new Map<string, FailureClassCounts & FailureBucketTotals>();+ for (const r of rows) {+ let entry = map.get(r.date);+ if (!entry) {+ entry = { ...emptyClassCounts(), failed: 0, total: 0 };+ map.set(r.date, entry);+ }+ foldFailureRow(entry, r.failure_reason, r.task_count);+ }+ return Array.from(map.entries())+ .toSorted(([a], [b]) => a.localeCompare(b))+ .map(([date, counts]) => ({+ ...counts,+ date,+ label: formatDateLabel(date),+ }));+}++// Weekly counterpart. Buckets are pre-zeroed from the same week shells the+// time / tasks weekly aggregators use, so a week with no terminal tasks+// renders as an empty bar instead of collapsing the x-axis.+export function aggregateWeeklyErrors(+ rows: DashboardFailureDaily[],+ tz: string,+ weekCount: number,+): WeeklyErrorsData[] {+ const shells = buildWeekShells(tz, weekCount);+ const buckets = new Map<string, FailureClassCounts & FailureBucketTotals>();+ for (const shell of shells) {+ buckets.set(shell.weekStart, { ...emptyClassCounts(), failed: 0, total: 0 });+ }+ for (const r of rows) {+ const bucket = buckets.get(weekStartIso(r.date));+ if (!bucket) continue;+ foldFailureRow(bucket, r.failure_reason, r.task_count);+ }+ return shells.map((s) => ({+ ...(buckets.get(s.weekStart) ?? { ...emptyClassCounts(), failed: 0, total: 0 }),+ ...s,+ }));+}++// Whole-window failure totals for the Errors KPI hint and the breakdown+// header. `rate` is a fraction in [0, 1]; 0 when the window has no terminal+// tasks at all.+export interface FailureTotals {+ failed: number;+ total: number;+ rate: number;+}++export function computeFailureTotals(+ rows: { failure_reason: string; task_count: number }[],+): FailureTotals {+ let failed = 0;+ let total = 0;+ for (const r of rows) {+ total += r.task_count;+ if (r.failure_reason !== "") failed += r.task_count;+ }+ return { failed, total, rate: total > 0 ? failed / total : 0 };+}++export interface FailureClassRow {+ failureClass: FailureClass;+ count: number;+}++// Per-class window totals, heaviest first, zero-count classes dropped. Ties+// break on FAILURE_CLASSES order so the list doesn't reshuffle between+// renders when two classes sit at the same count.+export function aggregateFailureClasses(+ rows: { failure_reason: string; task_count: number }[],+): FailureClassRow[] {+ const counts = emptyClassCounts();+ for (const r of rows) {+ if (r.failure_reason === "") continue;+ counts[failureClassOf(r.failure_reason)] += r.task_count;+ }+ return FAILURE_CLASSES.map((failureClass) => ({+ failureClass,+ count: counts[failureClass],+ }))+ .filter((r) => r.count > 0)+ .toSorted((a, b) => b.count - a.count);+}++export interface FailureReasonRow {+ reason: string;+ failureClass: FailureClass;+ count: number;+}++// Per-raw-reason window totals, heaviest first. This is the row set that+// answers "which specific error", under the coarser class summary.+export function aggregateFailureReasons(+ rows: { failure_reason: string; task_count: number }[],+): FailureReasonRow[] {+ const counts = new Map<string, number>();+ for (const r of rows) {+ if (r.failure_reason === "") continue;+ counts.set(r.failure_reason, (counts.get(r.failure_reason) ?? 0) + r.task_count);+ }+ return Array.from(counts.entries())+ .map(([reason, count]) => ({+ reason,+ failureClass: failureClassOf(reason),+ count,+ }))+ .toSorted((a, b) => b.count - a.count || a.reason.localeCompare(b.reason));+}++// Synthetic agentId for the row aggregating every agent the viewer can't+// resolve to a name. Distinct from DELETED_AGENTS_ROW_ID because this bucket+// covers two populations at once: hard-deleted agents, and agents that are+// private to someone else. The failure rollups are workspace-scoped and do+// NOT apply per-agent visibility (see the access-control note on+// server/internal/handler/dashboard.go), while the agent list the client+// joins against DOES — members only see a private agent when they own it or+// are workspace owner/admin. Naming the bucket after deletion would be a lie+// for the second group.+export const UNRESOLVED_AGENTS_ROW_ID = "__unresolved_agents__";++export interface AgentFailureRow {+ agentId: string;+ 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.+//+// Agents with zero failures are dropped — this list is a triage aid, not a+// census; the leaderboard above it already shows every agent.+export function aggregateAgentFailures(+ rows: DashboardFailureByAgent[],+): AgentFailureRow[] {+ const map = new Map<+ string,+ { failed: number; total: number; classes: FailureClassCounts }+ >();+ for (const r of rows) {+ let entry = map.get(r.agent_id);+ if (!entry) {+ entry = { failed: 0, total: 0, classes: emptyClassCounts() };+ map.set(r.agent_id, entry);+ }+ entry.total += r.task_count;+ if (r.failure_reason === "") continue;+ 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 {+ 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);+}++// Fold rows whose agent the viewer cannot resolve into one aggregated bucket+// so the Errors list never renders a bare agent UUID.+//+// This is a privacy boundary, not just a cosmetic one. The failure rollups+// return every agent in the workspace — deliberately, since failure volume is+// a workspace-level operational metric — but the agent list is filtered by+// per-agent visibility. Rendering `agentId` for the difference would tell a+// member that a private agent exists, how often it runs, how often it fails,+// and what it fails on.+//+// `knownAgentIds` is null while the agent list is still loading. Unlike+// `bucketUnknownAgentRows`, which passes rows through in that window, this+// one anonymizes them: a transient flash of UUIDs is exactly the leak the+// function exists to prevent, and one merged row for a few hundred+// milliseconds is the cheaper failure.+//+// 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.+export function anonymizeUnresolvedAgentRows(+ rows: DashboardFailureByAgent[],+ knownAgentIds: ReadonlySet<string> | null,+): DashboardFailureByAgent[] {+ if (!rows.some((r) => !knownAgentIds?.has(r.agent_id))) return rows;+ return rows.map((r) =>+ knownAgentIds?.has(r.agent_id)+ ? r+ : { ...r, agent_id: UNRESOLVED_AGENTS_ROW_ID },+ );+}diff --git a/packages/views/issues/components/execution-log-section.tsx b/packages/views/issues/components/execution-log-section.tsxindex d2121d1019..1a62acbf7a 100644--- a/packages/views/issues/components/execution-log-section.tsx+++ b/packages/views/issues/components/execution-log-section.tsx@@ -6,7 +6,7 @@ import { Ban, CheckCircle2, ChevronRight, Loader2, RotateCcw, Square, XCircle }import { toast } from "sonner";import { api, dispatchReasonCode } from "@multica/core/api";import { issueKeys } from "@multica/core/issues/queries";-import type { AgentTask, TaskFailureReason } from "@multica/core/types";+import type { AgentTask } from "@multica/core/types";import { useTimeAgo } from "../../i18n";import {Tooltip,@@ -370,9 +370,7 @@ function PastRow({ task, issueId }: { task: AgentTask; issueId: string }) {const trigger = useTriggerText(task);const time = task.completed_at ? timeAgo(task.completed_at) : "—";const failureLabel =- task.status === "failed" && task.failure_reason- ? failureReasonLabel[task.failure_reason as TaskFailureReason]- : null;+ task.status === "failed" ? failureReasonLabel(task.failure_reason) : null;// Retry only makes sense for terminal-but-not-success rows. Passing// task.id targets this specific row's agent — without it, the rerundiff --git a/packages/views/locales/en/usage.json b/packages/views/locales/en/usage.jsonindex 379b870d8f..3af467dc3f 100644--- a/packages/views/locales/en/usage.json+++ b/packages/views/locales/en/usage.json@@ -25,10 +25,12 @@"title_tokens": "Daily tokens","title_time": "Daily run time","title_tasks": "Daily tasks",+ "title_errors": "Daily errors","metric_cost": "Cost","metric_tokens": "Tokens","metric_time": "Time","metric_tasks": "Tasks",+ "metric_errors": "Errors","no_data": "No usage in this window."},"weekly": {@@ -36,8 +38,30 @@"title_tokens": "Weekly tokens","title_time": "Weekly run time","title_tasks": "Weekly tasks",+ "title_errors": "Weekly errors","partial_label": "{{range}} (partial · {{covered}} / 7 days)"},+ "errors": {+ "tooltip_rate": "Error rate",+ "class": {+ "auth": "Auth",+ "rate_limit": "Rate limit",+ "timeout": "Timeout",+ "provider": "Provider",+ "runtime": "Runtime",+ "agent": "Agent",+ "other": "Other"+ },+ "title": "Errors",+ "summary": "{{failed}} of {{total}} runs failed · {{rate}}",+ "by_class": "By class",+ "by_agent": "Top offenders",+ "other_agents": "Other agents",+ "agent_rate": "{{failed}} / {{total}} · {{rate}}",+ "no_data": "No failed runs in this window.",+ "show_reasons": "Show error codes",+ "hide_reasons": "Hide error codes"+ },"leaderboard": {"title": "Leaderboard","caption": "{{count}} agents",diff --git a/packages/views/locales/ja/usage.json b/packages/views/locales/ja/usage.jsonindex 453f3536ae..ee4187b022 100644--- a/packages/views/locales/ja/usage.json+++ b/packages/views/locales/ja/usage.json@@ -25,10 +25,12 @@"title_tokens": "日別トークン","title_time": "日別実行時間","title_tasks": "日別タスク",+ "title_errors": "日別エラー","metric_cost": "コスト","metric_tokens": "トークン","metric_time": "時間","metric_tasks": "タスク",+ "metric_errors": "エラー","no_data": "この期間に使用量はありません。"},"weekly": {@@ -36,8 +38,30 @@"title_tokens": "週別トークン","title_time": "週別実行時間","title_tasks": "週別タスク",+ "title_errors": "週別エラー","partial_label": "{{range}} (一部 · 7日中 {{covered}}日)"},+ "errors": {+ "tooltip_rate": "エラー率",+ "class": {+ "auth": "認証",+ "rate_limit": "レート制限",+ "timeout": "タイムアウト",+ "provider": "プロバイダー",+ "runtime": "ランタイム",+ "agent": "エージェント",+ "other": "その他"+ },+ "title": "エラー",+ "summary": "{{total}} 回中 {{failed}} 回が失敗 · {{rate}}",+ "by_class": "種類別",+ "by_agent": "失敗の多いエージェント",+ "other_agents": "その他のエージェント",+ "agent_rate": "{{failed}} / {{total}} · {{rate}}",+ "no_data": "この期間に失敗した実行はありません。",+ "show_reasons": "エラーコードを表示",+ "hide_reasons": "エラーコードを隠す"+ },"leaderboard": {"title": "リーダーボード","caption": "{{count}} 件のエージェント",diff --git a/packages/views/locales/ko/usage.json b/packages/views/locales/ko/usage.jsonindex 2470faedbc..7534c93bd1 100644--- a/packages/views/locales/ko/usage.json+++ b/packages/views/locales/ko/usage.json@@ -25,10 +25,12 @@"title_tokens": "일별 토큰","title_time": "일별 실행 시간","title_tasks": "일별 작업",+ "title_errors": "일별 오류","metric_cost": "비용","metric_tokens": "토큰","metric_time": "시간","metric_tasks": "작업",+ "metric_errors": "오류","no_data": "이 기간에는 사용량이 없습니다."},"weekly": {@@ -36,8 +38,30 @@"title_tokens": "주별 토큰","title_time": "주별 실행 시간","title_tasks": "주별 작업",+ "title_errors": "주별 오류","partial_label": "{{range}} (부분 · 7일 중 {{covered}}일)"},+ "errors": {+ "tooltip_rate": "오류율",+ "class": {+ "auth": "인증",+ "rate_limit": "속도 제한",+ "timeout": "시간 초과",+ "provider": "프로바이더",+ "runtime": "런타임",+ "agent": "에이전트",+ "other": "기타"+ },+ "title": "오류",+ "summary": "실행 {{total}}회 중 {{failed}}회 실패 · {{rate}}",+ "by_class": "유형별",+ "by_agent": "실패가 많은 에이전트",+ "other_agents": "기타 에이전트",+ "agent_rate": "{{failed}} / {{total}} · {{rate}}",+ "no_data": "이 기간에는 실패한 실행이 없습니다.",+ "show_reasons": "오류 코드 표시",+ "hide_reasons": "오류 코드 숨기기"+ },"leaderboard": {"title": "리더보드","caption": "에이전트 {{count}}개",diff --git a/packages/views/locales/zh-Hans/usage.json b/packages/views/locales/zh-Hans/usage.jsonindex 2c79c0dbb6..165e4eb115 100644--- a/packages/views/locales/zh-Hans/usage.json+++ b/packages/views/locales/zh-Hans/usage.json@@ -25,10 +25,12 @@"title_tokens": "每日 Token","title_time": "每日运行时长","title_tasks": "每日任务数",+ "title_errors": "每日错误","metric_cost": "费用","metric_tokens": "Token","metric_time": "运行时长","metric_tasks": "任务数",+ "metric_errors": "错误","no_data": "所选时间范围内暂无消耗。"},"weekly": {@@ -36,8 +38,30 @@"title_tokens": "每周 Token","title_time": "每周运行时长","title_tasks": "每周任务数",+ "title_errors": "每周错误","partial_label": "{{range}}(未满 · 已过 {{covered}} / 7 天)"},+ "errors": {+ "tooltip_rate": "错误率",+ "class": {+ "auth": "认证",+ "rate_limit": "限流",+ "timeout": "超时",+ "provider": "模型服务",+ "runtime": "运行时",+ "agent": "智能体",+ "other": "其他"+ },+ "title": "错误",+ "summary": "{{total}} 次运行中有 {{failed}} 次失败 · {{rate}}",+ "by_class": "按类型",+ "by_agent": "问题最多的智能体",+ "other_agents": "其他智能体",+ "agent_rate": "{{failed}} / {{total}} · {{rate}}",+ "no_data": "所选时间范围内没有失败的运行。",+ "show_reasons": "展开错误码",+ "hide_reasons": "收起错误码"+ },"leaderboard": {"title": "排行榜","caption": "{{count}} 个智能体",diff --git a/packages/views/runtimes/components/charts/daily-errors-chart.tsx b/packages/views/runtimes/components/charts/daily-errors-chart.tsxnew file mode 100644index 0000000000..9d6518315f--- /dev/null+++ b/packages/views/runtimes/components/charts/daily-errors-chart.tsx@@ -0,0 +1,89 @@+import { BarChart, Bar, XAxis, YAxis, CartesianGrid } from "recharts";+import {+ ChartContainer,+ ChartTooltip,+ ChartTooltipContent,+} from "@multica/ui/components/ui/chart";+import { useT } from "../../../i18n";+import {+ activeFailureClasses,+ formatRate,+ labelOf,+ useFailureClassConfig,+ type FailureBucketTotals,+ type FailureClassCounts,+} from "./failure-class-visuals";++export interface DailyErrorsData extends FailureClassCounts, FailureBucketTotals {+ date: string;+ label: string;+}++/**+ * Failed tasks per day, stacked by failure class.+ *+ * Bar height is the absolute failure count — a spike is what an operator+ * scans for. The rate lives in the tooltip instead of on the y-axis: as a+ * chart series it would be dominated by low-volume days, where a single+ * failure out of one task reads as a 100% outage.+ */+export function DailyErrorsChart({ data }: { data: DailyErrorsData[] }) {+ const { t } = useT("usage");+ const config = useFailureClassConfig();+ const classes = activeFailureClasses(data);++ return (+ <ChartContainer config={config} className="aspect-[3/1] w-full">+ <BarChart data={data} margin={{ left: 0, right: 0, top: 4, bottom: 0 }}>+ <CartesianGrid vertical={false} />+ <XAxis+ dataKey="label"+ tickLine={false}+ axisLine={false}+ tickMargin={8}+ interval="preserveStartEnd"+ />+ <YAxis+ tickLine={false}+ axisLine={false}+ tickMargin={8}+ allowDecimals={false}+ width={40}+ />+ <ChartTooltip+ content={+ <ChartTooltipContent+ // `name` is the Recharts dataKey — the raw class id+ // ("rate_limit"). Resolve it through the chart config so the+ // tooltip shows the translated label the legend already uses.+ formatter={(value, name) => `${value} ${labelOf(config, name)}`}+ footer={(payload) => {+ const row = payload[0]?.payload as DailyErrorsData | undefined;+ if (!row) return null;+ return (+ <div className="flex items-center justify-between gap-2 font-medium">+ <span>{t(($) => $.errors.tooltip_rate)}</span>+ <span className="font-mono tabular-nums">+ {formatRate(row.failed, row.total)}+ </span>+ </div>+ );+ }}+ />+ }+ />+ {classes.map((c, i) => (+ <Bar+ key={c}+ dataKey={c}+ stackId="errors"+ fill={`var(--color-${c})`}+ // Only the topmost segment gets rounded corners, so the stack+ // reads as one bar rather than a pile of pills.+ radius={i === classes.length - 1 ? [3, 3, 0, 0] : [0, 0, 0, 0]}+ />+ ))}+ </BarChart>+ </ChartContainer>+ );+}diff --git a/packages/views/runtimes/components/charts/failure-class-visuals.ts b/packages/views/runtimes/components/charts/failure-class-visuals.tsnew file mode 100644index 0000000000..0315924206--- /dev/null+++ b/packages/views/runtimes/components/charts/failure-class-visuals.ts@@ -0,0 +1,110 @@+import { FAILURE_CLASSES, type FailureClass } from "@multica/core/dashboard";+import type { ChartConfig } from "@multica/ui/components/ui/chart";+import { useT } from "../../../i18n";++// The design system ships five `--chart-*` tokens and they are a single-hue+// blue ramp, so there is no seven-hue categorical palette to borrow here —+// and borrowing the blue one would make failures read like token spend.+// Instead every class is a step down a `--destructive` ramp mixed toward+// `--card`: the whole stack reads as "errors" at a glance, and the steps stay+// distinguishable side by side. Mixing toward `--card` rather than a fixed+// white keeps the ramp legible in dark mode too.+//+// The ramp bottoms out at 30% rather than fading to nothing so the least+// prominent class is still visible against the card it sits on. Order follows+// FAILURE_CLASSES (most-actionable first), so the darkest segment is always+// the one worth looking at first.+// One bucket's failure counts, keyed by display class. Every class is always+// present (0 when unused) so a bucket can be read without existence checks;+// which of them actually get drawn is `activeFailureClasses`' call.+export type FailureClassCounts = Record<FailureClass, number>;++// Bucket-level totals that ride alongside the per-class counts. `total`+// counts every terminal task in the bucket, not just failures, so the+// tooltip can report a rate.+export interface FailureBucketTotals {+ failed: number;+ total: number;+}++export const FAILURE_CLASS_COLOR: Record<FailureClass, string> = {+ auth: "var(--destructive)",+ rate_limit: "color-mix(in oklch, var(--destructive) 86%, var(--card))",+ timeout: "color-mix(in oklch, var(--destructive) 72%, var(--card))",+ provider: "color-mix(in oklch, var(--destructive) 60%, var(--card))",+ runtime: "color-mix(in oklch, var(--destructive) 48%, var(--card))",+ agent: "color-mix(in oklch, var(--destructive) 38%, var(--card))",+ other: "color-mix(in oklch, var(--destructive) 30%, var(--card))",+};++/**+ * Which classes to draw, in canonical order.+ *+ * Rendering all seven unconditionally would put five permanently-zero rows in+ * every tooltip. Restricting to the classes the window actually contains+ * keeps the legend and tooltip proportional to what happened, and the+ * canonical order keeps a class pinned to the same colour whether or not its+ * neighbours are present.+ */+export function activeFailureClasses(+ data: readonly Partial<Record<FailureClass, number>>[],+): FailureClass[] {+ return FAILURE_CLASSES.filter((c) => data.some((d) => (d[c] ?? 0) > 0));+}++/**+ * Failure rate as a percentage of terminal tasks — "12.5%", "40%".+ *+ * Sub-10% rates keep one decimal because that is the band where a regression+ * shows up first and rounding 1.4% to 1% hides half the movement. A bucket+ * with no terminal tasks at all has no rate to report, so it renders a dash+ * rather than a 0% that reads as "healthy".+ */+export function formatRate(failed: number, total: number): string {+ if (total <= 0) return "—";+ const pct = (failed / total) * 100;+ return `${pct >= 10 || pct === 0 ? Math.round(pct) : pct.toFixed(1)}%`;+}++/**+ * Translated label for a Recharts series name.+ *+ * Recharts passes the `dataKey` through as the tooltip item's `name`, so a+ * formatter that echoes it renders the raw class id ("rate_limit"). Look it+ * up in the same config that drives the legend, and fall back to the key+ * itself if the config ever loses an entry.+ */+export function labelOf(+ config: ChartConfig,+ name: string | number | undefined,+): string {+ const key = String(name ?? "");+ const label = config[key]?.label;+ return typeof label === "string" ? label : key;+}++/** Translated Recharts config for the failure-class series. */+export function useFailureClassConfig(): ChartConfig {+ const { t } = useT("usage");+ return {+ auth: { label: t(($) => $.errors.class.auth), color: FAILURE_CLASS_COLOR.auth },+ rate_limit: {+ label: t(($) => $.errors.class.rate_limit),+ color: FAILURE_CLASS_COLOR.rate_limit,+ },+ timeout: {+ label: t(($) => $.errors.class.timeout),+ color: FAILURE_CLASS_COLOR.timeout,+ },+ provider: {+ label: t(($) => $.errors.class.provider),+ color: FAILURE_CLASS_COLOR.provider,+ },+ runtime: {+ label: t(($) => $.errors.class.runtime),+ color: FAILURE_CLASS_COLOR.runtime,+ },+ agent: { label: t(($) => $.errors.class.agent), color: FAILURE_CLASS_COLOR.agent },+ other: { label: t(($) => $.errors.class.other), color: FAILURE_CLASS_COLOR.other },+ } satisfies ChartConfig;+}diff --git a/packages/views/runtimes/components/charts/index.ts b/packages/views/runtimes/components/charts/index.tsindex cce5a345e8..27ea16ac38 100644--- a/packages/views/runtimes/components/charts/index.ts+++ b/packages/views/runtimes/components/charts/index.ts@@ -6,4 +6,15 @@ export { DailyTimeChart, type DailyTimeData } from "./daily-time-chart";export { DailyTasksChart, type DailyTasksData } from "./daily-tasks-chart";export { WeeklyTimeChart, type WeeklyTimeData } from "./weekly-time-chart";export { WeeklyTasksChart, type WeeklyTasksData } from "./weekly-tasks-chart";+export { DailyErrorsChart, type DailyErrorsData } from "./daily-errors-chart";+export { WeeklyErrorsChart, type WeeklyErrorsData } from "./weekly-errors-chart";+export {+ FAILURE_CLASS_COLOR,+ activeFailureClasses,+ formatRate,+ labelOf,+ useFailureClassConfig,+ type FailureBucketTotals,+ type FailureClassCounts,+} from "./failure-class-visuals";export { ActivityHeatmap } from "./activity-heatmap";diff --git a/packages/views/runtimes/components/charts/weekly-errors-chart.tsx b/packages/views/runtimes/components/charts/weekly-errors-chart.tsxnew file mode 100644index 0000000000..305bde62a1--- /dev/null+++ b/packages/views/runtimes/components/charts/weekly-errors-chart.tsx@@ -0,0 +1,103 @@+import { BarChart, Bar, XAxis, YAxis, CartesianGrid, Cell } from "recharts";+import {+ ChartContainer,+ ChartTooltip,+ ChartTooltipContent,+} from "@multica/ui/components/ui/chart";+import { useT } from "../../../i18n";+import {+ activeFailureClasses,+ formatRate,+ labelOf,+ useFailureClassConfig,+ type FailureBucketTotals,+ type FailureClassCounts,+} from "./failure-class-visuals";++export interface WeeklyErrorsData extends FailureClassCounts, FailureBucketTotals {+ weekStart: string;+ weekEnd: string;+ label: string;+ rangeLabel: string;+ partial: boolean;+ daysCovered: number;+}++/**+ * Weekly counterpart of DailyErrorsChart — same class stack, each bar a+ * Mon–Sun calendar week. Partial-week bars render at half opacity, matching+ * every other weekly chart so the in-progress week reads as subordinate.+ */+export function WeeklyErrorsChart({ data }: { data: WeeklyErrorsData[] }) {+ const { t } = useT("usage");+ const config = useFailureClassConfig();+ const classes = activeFailureClasses(data);++ return (+ <ChartContainer config={config} className="aspect-[3/1] w-full">+ <BarChart data={data} margin={{ left: 0, right: 0, top: 4, bottom: 0 }}>+ <CartesianGrid vertical={false} />+ <XAxis+ dataKey="label"+ tickLine={false}+ axisLine={false}+ tickMargin={8}+ interval="preserveStartEnd"+ />+ <YAxis+ tickLine={false}+ axisLine={false}+ tickMargin={8}+ allowDecimals={false}+ width={40}+ />+ <ChartTooltip+ content={+ <ChartTooltipContent+ labelKey="rangeLabel"+ labelFormatter={(_label, payload) => {+ const row = payload[0]?.payload as WeeklyErrorsData | undefined;+ if (!row) return "";+ return row.partial+ ? t(($) => $.weekly.partial_label, {+ range: row.rangeLabel,+ covered: row.daysCovered,+ })+ : row.rangeLabel;+ }}+ // `name` is the Recharts dataKey — the raw class id+ // ("rate_limit"). Resolve it through the chart config so the+ // tooltip shows the translated label the legend already uses.+ formatter={(value, name) => `${value} ${labelOf(config, name)}`}+ footer={(payload) => {+ const row = payload[0]?.payload as WeeklyErrorsData | undefined;+ if (!row) return null;+ return (+ <div className="flex items-center justify-between gap-2 font-medium">+ <span>{t(($) => $.errors.tooltip_rate)}</span>+ <span className="font-mono tabular-nums">+ {formatRate(row.failed, row.total)}+ </span>+ </div>+ );+ }}+ />+ }+ />+ {classes.map((c, i) => (+ <Bar+ key={c}+ dataKey={c}+ stackId="errors"+ fill={`var(--color-${c})`}+ radius={i === classes.length - 1 ? [3, 3, 0, 0] : [0, 0, 0, 0]}+ >+ {data.map((d) => (+ <Cell key={`${d.weekStart}-${c}`} fillOpacity={d.partial ? 0.5 : 1} />+ ))}+ </Bar>+ ))}+ </BarChart>+ </ChartContainer>+ );+}diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 3c30a89b25..af7ef91fa5 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -1316,6 +1316,8 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Get("/usage/by-agent", h.GetDashboardUsageByAgent)r.Get("/agent-runtime", h.GetDashboardAgentRunTime)r.Get("/runtime/daily", h.GetDashboardRunTimeDaily)+ r.Get("/failures/daily", h.GetDashboardFailuresDaily)+ r.Get("/failures/by-agent", h.GetDashboardFailuresByAgent)})// Runtimesdiff --git a/server/internal/handler/dashboard.go b/server/internal/handler/dashboard.goindex d25f474849..fe063c14a9 100644--- a/server/internal/handler/dashboard.go+++ b/server/internal/handler/dashboard.go@@ -12,14 +12,16 @@ import (// ---------------------------------------------------------------------------// Workspace / Project dashboard//-// Three read endpoints power the workspace dashboard:+// Six read endpoints power the workspace dashboard://-// GET /api/dashboard/usage/daily per-(date, model) token rows-// GET /api/dashboard/usage/by-agent per-(agent, model) token rows-// GET /api/dashboard/agent-runtime per-agent run-time + task counts-// GET /api/dashboard/runtime/daily per-date run-time + task counts+// GET /api/dashboard/usage/daily per-(date, model) token rows+// GET /api/dashboard/usage/by-agent per-(agent, model) token rows+// GET /api/dashboard/agent-runtime per-agent run-time + task counts+// GET /api/dashboard/runtime/daily per-date run-time + task counts+// GET /api/dashboard/failures/daily per-(date, failure_reason) counts+// GET /api/dashboard/failures/by-agent per-(agent, failure_reason) counts//-// All three accept ?days=N (defaults to 30, capped at 365) and an optional+// All of them accept ?days=N (defaults to 30, capped at 365) and an optional// ?project_id=<uuid> to scope the rollup to a single project. With no// project_id the data spans the whole workspace.//@@ -322,3 +324,118 @@ func (h *Handler) GetDashboardRunTimeDaily(w http.ResponseWriter, r *http.Reques}writeJSON(w, http.StatusOK, resp)}++// ---------------------------------------------------------------------------+// Failure rollups+//+// Both endpoints return EVERY terminal task, not just the failed ones: the+// row whose FailureReason is "" carries that bucket's succeeded count. The+// client needs that denominator to render an error *rate*, and shipping it+// in the same payload keeps numerator and denominator on identical filters —+// deriving the denominator from the run-time endpoints instead would silently+// disagree, because those require started_at IS NOT NULL and a task that+// expired in the queue never started.+//+// FailureReason values are the canonical taxonomy from server/pkg/taskfailure+// (21 reasons), plus "unclassified" for failed rows with a NULL / empty+// column. The client folds them into a handful of display classes; the raw+// reason stays on the wire so that mapping can change without a backend+// deploy.+// ---------------------------------------------------------------------------++// DashboardFailureDailyResponse is one (date, failure_reason) bucket of+// terminal-task counts. FailureReason == "" is the succeeded bucket.+type DashboardFailureDailyResponse struct {+ Date string `json:"date"`+ FailureReason string `json:"failure_reason"`+ TaskCount int32 `json:"task_count"`+}++// GetDashboardFailuresDaily returns per-(date, failure_reason) terminal-task+// counts for the workspace, optionally scoped to a project. Powers the Usage+// page's Errors trend and errors-by-class breakdown.+func (h *Handler) GetDashboardFailuresDaily(w http.ResponseWriter, r *http.Request) {+ workspaceID := h.resolveWorkspaceID(r)+ if _, ok := h.workspaceMember(w, r, workspaceID); !ok {+ return+ }+ projectID, ok := parseProjectIDParam(w, r)+ if !ok {+ return+ }+ // Same viewer-tz day boundary as every other daily series so the Errors+ // tab lines up with Cost / Tokens / Time / Tasks.+ tz := h.resolveViewingTZ(r)+ since := parseSinceParamInTZ(r, 30, tz)++ rows, err := h.Queries.ListDashboardFailuresDaily(r.Context(), db.ListDashboardFailuresDailyParams{+ WorkspaceID: parseUUID(workspaceID),+ Tz: tz,+ Since: since,+ ProjectID: projectID,+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list daily failures")+ return+ }++ resp := make([]DashboardFailureDailyResponse, len(rows))+ for i, row := range rows {+ resp[i] = DashboardFailureDailyResponse{+ Date: row.Date.Time.Format("2006-01-02"),+ FailureReason: row.FailureReason,+ TaskCount: row.TaskCount,+ }+ }+ writeJSON(w, http.StatusOK, resp)+}++// DashboardFailureByAgentResponse is one (agent, failure_reason) bucket of+// terminal-task counts. FailureReason == "" is the succeeded bucket.+type DashboardFailureByAgentResponse struct {+ AgentID string `json:"agent_id"`+ FailureReason string `json:"failure_reason"`+ TaskCount int32 `json:"task_count"`+}++// GetDashboardFailuresByAgent returns per-(agent, failure_reason)+// terminal-task counts for the workspace, optionally scoped to a project.+// Powers the Usage page's "top offenders" list.+func (h *Handler) GetDashboardFailuresByAgent(w http.ResponseWriter, r *http.Request) {+ workspaceID := h.resolveWorkspaceID(r)+ if _, ok := h.workspaceMember(w, r, workspaceID); !ok {+ return+ }+ projectID, ok := parseProjectIDParam(w, r)+ if !ok {+ return+ }+ // No date grouping in the SQL, so the client cannot trim this response the+ // way it trims the date-bucketed series. Close the window server-side to+ // exactly `days` calendar buckets — the same span the Errors chart renders+ // after its `-(days-1)` filter. With the default N+1 cutoff this list+ // covered one extra day, so at days=1 the card could report yesterday's+ // failures next to a chart showing none.+ tz := h.resolveViewingTZ(r)+ since := parseExactSinceParamInTZ(r, 30, tz)++ rows, err := h.Queries.ListDashboardFailuresByAgent(r.Context(), db.ListDashboardFailuresByAgentParams{+ WorkspaceID: parseUUID(workspaceID),+ Since: since,+ ProjectID: projectID,+ })+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list failures by agent")+ return+ }++ resp := make([]DashboardFailureByAgentResponse, len(rows))+ for i, row := range rows {+ resp[i] = DashboardFailureByAgentResponse{+ AgentID: uuidToString(row.AgentID),+ FailureReason: row.FailureReason,+ TaskCount: row.TaskCount,+ }+ }+ writeJSON(w, http.StatusOK, resp)+}diff --git a/server/internal/handler/dashboard_test.go b/server/internal/handler/dashboard_test.goindex 9a3d7218db..fec9be0245 100644--- a/server/internal/handler/dashboard_test.go+++ b/server/internal/handler/dashboard_test.go@@ -1407,3 +1407,247 @@ func TestRollupTaskUsageHourlyConvergesOnTaskUsageDelete(t *testing.T) {t.Errorf("after delete: expected bucket recomputed to 0, got %d", got)}}++// TestDashboardFailuresCountNeverStartedTasks pins the reason the failure+// rollups exist as their own queries rather than reusing the run-time ones:+// ListDashboardRunTimeDaily / ListDashboardAgentRunTime require+// `started_at IS NOT NULL`, so a task that expired in the queue — the exact+// signature of a runtime outage — contributes nothing to their failed_count.+// The failure endpoints must count it, and must report the succeeded tasks in+// the same payload so the client's error rate has a matching denominator.+func TestDashboardFailuresCountNeverStartedTasks(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()++ var runtimeID, agentID string+ if err := testPool.QueryRow(ctx, `SELECT id FROM agent_runtime WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&runtimeID); err != nil {+ t.Fatalf("fetch runtime: %v", err)+ }+ if err := testPool.QueryRow(ctx, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID); err != nil {+ t.Fatalf("fetch agent: %v", err)+ }++ var issueID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO issue (workspace_id, title, creator_id, creator_type, number)+ VALUES ($1, 'failures rollup test', $2, 'member',+ (SELECT COALESCE(MAX(number), 0) + 1 FROM issue WHERE workspace_id = $1))+ RETURNING id+ `, testWorkspaceID, testUserID).Scan(&issueID); err != nil {+ t.Fatalf("create issue: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID) })++ now := time.Now().UTC()+ started := now.Add(-30 * time.Minute)+ completed := started.Add(10 * time.Minute)++ // startedAt is nullable so the queue-expiry case can be modelled exactly:+ // completed_at set, started_at absent.+ mkTask := func(status string, failureReason any, startedAt any) {+ var taskID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent_task_queue (agent_id, issue_id, runtime_id, status, started_at, completed_at, failure_reason, created_at)+ VALUES ($1, $2, $3, $4, $5, $6, $7, now())+ RETURNING id+ `, agentID, issueID, runtimeID, status, startedAt, completed, failureReason).Scan(&taskID); err != nil {+ t.Fatalf("insert task: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })+ }++ mkTask("completed", nil, started)+ mkTask("failed", "agent_error.provider_auth_or_access", started)+ mkTask("failed", "queued_expired", nil) // never started+ mkTask("failed", nil, started) // unclassified: empty reason column++ type failureRow struct {+ Date string `json:"date"`+ AgentID string `json:"agent_id"`+ FailureReason string `json:"failure_reason"`+ TaskCount int32 `json:"task_count"`+ }++ // The fixture workspace is shared, so other tests' rows may be in the+ // window too. Assert on the buckets this test wrote rather than on the+ // whole payload.+ collect := func(rows []failureRow) map[string]int32 {+ byReason := map[string]int32{}+ for _, r := range rows {+ byReason[r.FailureReason] += r.TaskCount+ }+ return byReason+ }++ for _, tc := range []struct {+ name string+ call func(w *httptest.ResponseRecorder)+ }{+ {"daily", func(w *httptest.ResponseRecorder) {+ testHandler.GetDashboardFailuresDaily(w, newRequest("GET", "/api/dashboard/failures/daily?days=1", nil))+ }},+ {"by-agent", func(w *httptest.ResponseRecorder) {+ testHandler.GetDashboardFailuresByAgent(w, newRequest("GET", "/api/dashboard/failures/by-agent?days=1", nil))+ }},+ } {+ t.Run(tc.name, func(t *testing.T) {+ w := httptest.NewRecorder()+ tc.call(w)+ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }+ var rows []failureRow+ if err := json.NewDecoder(w.Body).Decode(&rows); err != nil {+ t.Fatalf("decode: %v", err)+ }+ byReason := collect(rows)++ if byReason["agent_error.provider_auth_or_access"] < 1 {+ t.Errorf("expected the classified failure to be counted, got %v", byReason)+ }+ // The point of the whole endpoint: a failure with no started_at+ // still lands in a bucket.+ if byReason["queued_expired"] < 1 {+ t.Errorf("expected the never-started failure to be counted, got %v", byReason)+ }+ // A failed row with an empty failure_reason must not be mistaken+ // for a success — that would deflate the error rate.+ if byReason["unclassified"] < 1 {+ t.Errorf("expected the reason-less failure to be counted as unclassified, got %v", byReason)+ }+ // Succeeded tasks ride along under the empty-string key so the+ // client can compute a rate from one payload.+ if byReason[""] < 1 {+ t.Errorf("expected succeeded tasks in the denominator bucket, got %v", byReason)+ }+ })+ }+}++// TestDashboardFailuresByAgentUsesExactWindow pins the cutoff difference+// between the two failure endpoints.+//+// parseSinceParamInTZ deliberately returns N+1 calendar days of headroom, and+// the workspace dashboard trims the surplus client-side with `-(days-1)`. The+// by-agent rollup carries no date column, so it cannot be trimmed that way —+// it must close its own window server-side. Before that fix, `days=1` served+// the Errors card yesterday's failures while the chart beside it, correctly+// trimmed, showed none.+func TestDashboardFailuresByAgentUsesExactWindow(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ ctx := context.Background()++ var runtimeID, agentID string+ if err := testPool.QueryRow(ctx, `SELECT id FROM agent_runtime WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&runtimeID); err != nil {+ t.Fatalf("fetch runtime: %v", err)+ }+ if err := testPool.QueryRow(ctx, `SELECT id FROM agent WHERE workspace_id = $1 LIMIT 1`, testWorkspaceID).Scan(&agentID); err != nil {+ t.Fatalf("fetch agent: %v", err)+ }++ var issueID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO issue (workspace_id, title, creator_id, creator_type, number)+ VALUES ($1, 'failures window test', $2, 'member',+ (SELECT COALESCE(MAX(number), 0) + 1 FROM issue WHERE workspace_id = $1))+ RETURNING id+ `, testWorkspaceID, testUserID).Scan(&issueID); err != nil {+ t.Fatalf("create issue: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID) })++ // One failure at noon YESTERDAY (UTC). days=1 means "today", so neither+ // endpoint may count it. Noon avoids the midnight edge in either+ // direction.+ var taskID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent_task_queue (agent_id, issue_id, runtime_id, status, started_at, completed_at, failure_reason, created_at)+ VALUES (+ $1, $2, $3, 'failed',+ ((CURRENT_DATE - 1)::timestamp + interval '11 hours') AT TIME ZONE 'UTC',+ ((CURRENT_DATE - 1)::timestamp + interval '12 hours') AT TIME ZONE 'UTC',+ 'timeout', now()+ )+ RETURNING id+ `, agentID, issueID, runtimeID).Scan(&taskID); err != nil {+ t.Fatalf("insert task: %v", err)+ }+ t.Cleanup(func() { testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID) })++ type failureRow struct {+ FailureReason string `json:"failure_reason"`+ TaskCount int32 `json:"task_count"`+ }+ countTimeouts := func(body []byte) int32 {+ var rows []failureRow+ if err := json.Unmarshal(body, &rows); err != nil {+ t.Fatalf("decode: %v", err)+ }+ var n int32+ for _, r := range rows {+ if r.FailureReason == "timeout" {+ n += r.TaskCount+ }+ }+ return n+ }++ w := httptest.NewRecorder()+ testHandler.GetDashboardFailuresByAgent(w, newRequest("GET", "/api/dashboard/failures/by-agent?days=1&tz=UTC", nil))+ if w.Code != http.StatusOK {+ t.Fatalf("by-agent: expected 200, got %d: %s", w.Code, w.Body.String())+ }+ if got := countTimeouts(w.Body.Bytes()); got != 0 {+ t.Errorf("days=1 must not reach yesterday's failure, but by-agent counted %d", got)+ }++ // days=2 covers today + yesterday, so the same row must now appear —+ // proving the window was closed, not that the fixture is unreachable.+ w = httptest.NewRecorder()+ testHandler.GetDashboardFailuresByAgent(w, newRequest("GET", "/api/dashboard/failures/by-agent?days=2&tz=UTC", nil))+ if w.Code != http.StatusOK {+ t.Fatalf("by-agent days=2: expected 200, got %d: %s", w.Code, w.Body.String())+ }+ if got := countTimeouts(w.Body.Bytes()); got < 1 {+ t.Errorf("days=2 must include yesterday's failure, got %d", got)+ }+}++// TestDashboardFailureWireContractKeepsEmptyReason pins the success bucket's+// wire form. The client's zod schema defaults a missing `failure_reason` to+// "" — the succeeded bucket — which is only safe while the server always+// emits the field. Adding `omitempty` to the struct tag would strip it from+// exactly the success rows and silently turn every window into a 100% error+// rate, so that regression is caught here rather than in a dashboard.+func TestDashboardFailureWireContractKeepsEmptyReason(t *testing.T) {+ // Each case decodes into its OWN map. json.Unmarshal merges into a+ // non-nil map rather than resetting it, so sharing one across cases would+ // leave the first payload's failure_reason in place and let a later+ // omitempty regression pass unnoticed — the exact failure this test+ // exists to catch.+ for _, tc := range []struct {+ name string+ row any+ }{+ {"daily", DashboardFailureDailyResponse{Date: "2026-05-19", TaskCount: 3}},+ {"by-agent", DashboardFailureByAgentResponse{AgentID: "a", TaskCount: 3}},+ } {+ t.Run(tc.name, func(t *testing.T) {+ body, err := json.Marshal(tc.row)+ if err != nil {+ t.Fatalf("marshal: %v", err)+ }+ decoded := map[string]any{}+ if err := json.Unmarshal(body, &decoded); err != nil {+ t.Fatalf("unmarshal: %v", err)+ }+ if _, present := decoded["failure_reason"]; !present {+ t.Errorf("succeeded rows must serialize an explicit empty failure_reason, got %s", body)+ }+ })+ }+}diff --git a/server/internal/handler/runtime.go b/server/internal/handler/runtime.goindex 709932714f..3020da95eb 100644--- a/server/internal/handler/runtime.go+++ b/server/internal/handler/runtime.go@@ -399,6 +399,33 @@ func sinceFromDays(now time.Time, days int, loc *time.Location) time.Time {// bucket + N prior full days). If tzName is empty or unparseable, falls back// to UTC — never returns an error so handlers stay simple.func parseSinceParamInTZ(r *http.Request, defaultDays int, tzName string) pgtype.Timestamptz {+ return parseDaysCutoff(r, defaultDays, tzName, 0)+}++// parseExactSinceParamInTZ is parseSinceParamInTZ without the extra day of+// headroom: `days=N` yields exactly N calendar buckets (today's partial+// bucket + N-1 prior full days), which is the window the workspace dashboard+// actually displays.+//+// The N+1 cutoff exists so date-bucketed series can reach one bucket further+// back than they render (runtime detail's prior-window delta needs it), and+// the dashboard trims the surplus client-side with `-(days-1)`. A response+// with NO date dimension cannot be trimmed that way, so an aggregate served+// off the N+1 cutoff silently covers one more day than the chart beside it.+// Endpoints whose rows carry no date use this variant instead.+func parseExactSinceParamInTZ(r *http.Request, defaultDays int, tzName string) pgtype.Timestamptz {+ return parseDaysCutoff(r, defaultDays, tzName, 1)+}++// parseDaysCutoff is the shared body of the two cutoff parsers. `trimDays`+// pulls the cutoff forward, so 0 keeps the N+1 headroom and 1 closes the+// window to exactly N calendar days.+func parseDaysCutoff(+ r *http.Request,+ defaultDays int,+ tzName string,+ trimDays int,+) pgtype.Timestamptz {days := defaultDaysif d := r.URL.Query().Get("days"); d != "" {if parsed, err := strconv.Atoi(d); err == nil && parsed > 0 && parsed <= 365 {@@ -409,7 +436,13 @@ func parseSinceParamInTZ(r *http.Request, defaultDays int, tzName string) pgtypeif err != nil || loc == nil {loc = time.UTC}- return pgtype.Timestamptz{Time: sinceFromDays(time.Now(), days, loc), Valid: true}+ // Guard the floor: days is already >= 1 here, and trimming a 1-day+ // window by one would put the cutoff at start-of-today+0 — still correct+ // ("today only"), which is exactly what days=1 means.+ return pgtype.Timestamptz{+ Time: sinceFromDays(time.Now(), days-trimDays, loc),+ Valid: true,+ }}// resolveViewingTZ resolves the IANA tz to render the response in:diff --git a/server/migrations/231_agent_task_queue_terminal_completed_at_index.down.sql b/server/migrations/231_agent_task_queue_terminal_completed_at_index.down.sqlnew file mode 100644index 0000000000..6b0fb08e31--- /dev/null+++ b/server/migrations/231_agent_task_queue_terminal_completed_at_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_agent_task_queue_terminal_completed_at;diff --git a/server/migrations/231_agent_task_queue_terminal_completed_at_index.up.sql b/server/migrations/231_agent_task_queue_terminal_completed_at_index.up.sqlnew file mode 100644index 0000000000..df164c99bf--- /dev/null+++ b/server/migrations/231_agent_task_queue_terminal_completed_at_index.up.sql@@ -0,0 +1,18 @@+-- Single statement: CREATE INDEX CONCURRENTLY cannot run inside a transaction+-- or share a multi-command migration file.+--+-- Every Usage-page dashboard rollup that reads agent_task_queue filters on+-- `status IN ('completed','failed') AND completed_at >= <cutoff>` and then+-- joins `agent` for the workspace scope — ListDashboardRunTimeDaily,+-- ListDashboardAgentRunTime, and the two failure rollups added for the+-- errors charts. agent_task_queue had no index on completed_at at all, so+-- each of those was a full scan of a table whose lifetime row count is+-- dominated by rows outside any 30-day window.+--+-- The partial predicate matches those queries' status filter verbatim so the+-- planner can prove index applicability, and it keeps the index off the+-- queued / dispatched / running rows that the hot dispatch path churns —+-- a row only enters this index once, when it reaches a terminal state.+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_agent_task_queue_terminal_completed_at+ ON agent_task_queue (completed_at)+ WHERE status IN ('completed', 'failed');diff --git a/server/pkg/db/generated/task_usage.sql.go b/server/pkg/db/generated/task_usage.sql.goindex fe08dce770..00f31d65ee 100644--- a/server/pkg/db/generated/task_usage.sql.go+++ b/server/pkg/db/generated/task_usage.sql.go@@ -166,6 +166,146 @@ func (q *Queries) ListDashboardAgentRunTime(ctx context.Context, arg ListDashboareturn items, nil}+const listDashboardFailuresByAgent = `-- name: ListDashboardFailuresByAgent :many+SELECT+ atq.agent_id,+ CASE+ WHEN atq.status = 'failed'+ THEN COALESCE(NULLIF(atq.failure_reason, ''), 'unclassified')+ ELSE ''+ END AS failure_reason,+ COUNT(*)::int AS task_count+FROM agent_task_queue atq+JOIN agent a ON a.id = atq.agent_id+LEFT JOIN issue i ON i.id = atq.issue_id+WHERE a.workspace_id = $1+ AND atq.status IN ('completed', 'failed')+ AND atq.completed_at IS NOT NULL+ AND atq.completed_at >= $2::timestamptz+ AND ($3::uuid IS NULL OR i.project_id = $3)+GROUP BY atq.agent_id, 2+ORDER BY atq.agent_id, 2+`++type ListDashboardFailuresByAgentParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ Since pgtype.Timestamptz `json:"since"`+ ProjectID pgtype.UUID `json:"project_id"`+}++type ListDashboardFailuresByAgentRow struct {+ AgentID pgtype.UUID `json:"agent_id"`+ FailureReason string `json:"failure_reason"`+ TaskCount int32 `json:"task_count"`+}++// Per-(agent, failure_reason) terminal-task counts — the "top offenders"+// half of the dashboard's errors breakdown. Same `failure_reason = ”`+// succeeded-bucket convention as ListDashboardFailuresDaily, so the client+// can rank agents by failure rate rather than raw count.+//+// No date bucketing, so no @tz — @since is the viewer's local+// start-of-day-(N) so the window lines up with the per-agent run-time card.+func (q *Queries) ListDashboardFailuresByAgent(ctx context.Context, arg ListDashboardFailuresByAgentParams) ([]ListDashboardFailuresByAgentRow, error) {+ rows, err := q.db.Query(ctx, listDashboardFailuresByAgent, arg.WorkspaceID, arg.Since, arg.ProjectID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ListDashboardFailuresByAgentRow{}+ for rows.Next() {+ var i ListDashboardFailuresByAgentRow+ if err := rows.Scan(&i.AgentID, &i.FailureReason, &i.TaskCount); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}++const listDashboardFailuresDaily = `-- name: ListDashboardFailuresDaily :many+SELECT+ DATE(atq.completed_at AT TIME ZONE $2::text) AS date,+ CASE+ WHEN atq.status = 'failed'+ THEN COALESCE(NULLIF(atq.failure_reason, ''), 'unclassified')+ ELSE ''+ END AS failure_reason,+ COUNT(*)::int AS task_count+FROM agent_task_queue atq+JOIN agent a ON a.id = atq.agent_id+LEFT JOIN issue i ON i.id = atq.issue_id+WHERE a.workspace_id = $1+ AND atq.status IN ('completed', 'failed')+ AND atq.completed_at IS NOT NULL+ AND atq.completed_at >= $3::timestamptz+ AND ($4::uuid IS NULL OR i.project_id = $4)+GROUP BY 1, 2+ORDER BY 1 DESC, 2+`++type ListDashboardFailuresDailyParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ Tz string `json:"tz"`+ Since pgtype.Timestamptz `json:"since"`+ ProjectID pgtype.UUID `json:"project_id"`+}++type ListDashboardFailuresDailyRow struct {+ Date pgtype.Date `json:"date"`+ FailureReason string `json:"failure_reason"`+ TaskCount int32 `json:"task_count"`+}++// Daily per-(date, failure_reason) terminal-task counts for the workspace,+// optionally scoped to a single project. Powers the workspace dashboard's+// "Errors" trend and the errors-by-class breakdown.+//+// Shape note: this returns EVERY terminal task, not just the failures. The+// `failure_reason = ”` row of each date carries that date's succeeded+// count, which is the denominator the client needs for an error rate. A+// failed row whose failure_reason column is NULL or empty (pre-MUL-1949+// rows, or a failure path that forgot to classify) collapses into the+// 'unclassified' bucket so it stays countable instead of masquerading as a+// success. Cardinality is bounded by days x (21 reasons + 2), so the whole+// window fits in one small payload.+//+// Unlike ListDashboardRunTimeDaily this does NOT require started_at — a task+// that expired in the queue (failure_reason='queued_expired') never started+// but is unambiguously a failure, and dropping it would under-report exactly+// the outage the Errors chart exists to surface. Every failure path sets+// completed_at, so bucketing on it covers all of them.+//+// @since is already the viewer's local start-of-day-(N) (parseSinceParamInTZ)+// — passed straight through, NOT re-truncated; see ListDashboardUsageDaily.+func (q *Queries) ListDashboardFailuresDaily(ctx context.Context, arg ListDashboardFailuresDailyParams) ([]ListDashboardFailuresDailyRow, error) {+ rows, err := q.db.Query(ctx, listDashboardFailuresDaily,+ arg.WorkspaceID,+ arg.Tz,+ arg.Since,+ arg.ProjectID,+ )+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ListDashboardFailuresDailyRow{}+ for rows.Next() {+ var i ListDashboardFailuresDailyRow+ if err := rows.Scan(&i.Date, &i.FailureReason, &i.TaskCount); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const listDashboardRunTimeDaily = `-- name: ListDashboardRunTimeDaily :manySELECTDATE(atq.completed_at AT TIME ZONE $2::text) AS date,diff --git a/server/pkg/db/queries/task_usage.sql b/server/pkg/db/queries/task_usage.sqlindex 8e86a02627..8973094410 100644--- a/server/pkg/db/queries/task_usage.sql+++ b/server/pkg/db/queries/task_usage.sql@@ -175,3 +175,71 @@ WHERE a.workspace_id = $1AND (sqlc.narg('project_id')::uuid IS NULL OR i.project_id = sqlc.narg('project_id'))GROUP BY atq.agent_idORDER BY total_seconds DESC;++-- name: ListDashboardFailuresDaily :many+-- Daily per-(date, failure_reason) terminal-task counts for the workspace,+-- optionally scoped to a single project. Powers the workspace dashboard's+-- "Errors" trend and the errors-by-class breakdown.+--+-- Shape note: this returns EVERY terminal task, not just the failures. The+-- `failure_reason = ''` row of each date carries that date's succeeded+-- count, which is the denominator the client needs for an error rate. A+-- failed row whose failure_reason column is NULL or empty (pre-MUL-1949+-- rows, or a failure path that forgot to classify) collapses into the+-- 'unclassified' bucket so it stays countable instead of masquerading as a+-- success. Cardinality is bounded by days x (21 reasons + 2), so the whole+-- window fits in one small payload.+--+-- Unlike ListDashboardRunTimeDaily this does NOT require started_at — a task+-- that expired in the queue (failure_reason='queued_expired') never started+-- but is unambiguously a failure, and dropping it would under-report exactly+-- the outage the Errors chart exists to surface. Every failure path sets+-- completed_at, so bucketing on it covers all of them.+--+-- @since is already the viewer's local start-of-day-(N) (parseSinceParamInTZ)+-- — passed straight through, NOT re-truncated; see ListDashboardUsageDaily.+SELECT+ DATE(atq.completed_at AT TIME ZONE sqlc.arg('tz')::text) AS date,+ CASE+ WHEN atq.status = 'failed'+ THEN COALESCE(NULLIF(atq.failure_reason, ''), 'unclassified')+ ELSE ''+ END AS failure_reason,+ COUNT(*)::int AS task_count+FROM agent_task_queue atq+JOIN agent a ON a.id = atq.agent_id+LEFT JOIN issue i ON i.id = atq.issue_id+WHERE a.workspace_id = $1+ AND atq.status IN ('completed', 'failed')+ AND atq.completed_at IS NOT NULL+ AND atq.completed_at >= sqlc.arg('since')::timestamptz+ AND (sqlc.narg('project_id')::uuid IS NULL OR i.project_id = sqlc.narg('project_id'))+GROUP BY 1, 2+ORDER BY 1 DESC, 2;++-- name: ListDashboardFailuresByAgent :many+-- Per-(agent, failure_reason) terminal-task counts — the "top offenders"+-- half of the dashboard's errors breakdown. Same `failure_reason = ''`+-- succeeded-bucket convention as ListDashboardFailuresDaily, so the client+-- can rank agents by failure rate rather than raw count.+--+-- No date bucketing, so no @tz — @since is the viewer's local+-- start-of-day-(N) so the window lines up with the per-agent run-time card.+SELECT+ atq.agent_id,+ CASE+ WHEN atq.status = 'failed'+ THEN COALESCE(NULLIF(atq.failure_reason, ''), 'unclassified')+ ELSE ''+ END AS failure_reason,+ COUNT(*)::int AS task_count+FROM agent_task_queue atq+JOIN agent a ON a.id = atq.agent_id+LEFT JOIN issue i ON i.id = atq.issue_id+WHERE a.workspace_id = $1+ AND atq.status IN ('completed', 'failed')+ AND atq.completed_at IS NOT NULL+ AND atq.completed_at >= @since::timestamptz+ AND (sqlc.narg('project_id')::uuid IS NULL OR i.project_id = sqlc.narg('project_id'))+GROUP BY atq.agent_id, 2+ORDER BY atq.agent_id, 2;