Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(agents): MUL-7383 exclude cancelled runs from success metrics (#8424)
importcppf639d35f44ee
diff --git a/packages/core/agents/use-agent-activity.test.ts b/packages/core/agents/use-agent-activity.test.tsindex acacaf3867..476eeec397 100644--- a/packages/core/agents/use-agent-activity.test.ts+++ b/packages/core/agents/use-agent-activity.test.ts@@ -1,3 +1,4 @@+// @vitest-environment nodeimport { describe, expect, it } from "vitest";import type { Agent, AgentActivityBucket } from "../types";import {@@ -17,6 +18,7 @@ function bucket(daysAgo: number,taskCount: number,failedCount = 0,+ cancelledCount = 0,): AgentActivityBucket {const t = new Date(NOW);t.setHours(0, 0, 0, 0);@@ -25,6 +27,8 @@ function bucket(bucket_at: new Date(t.getTime() - daysAgo * DAY).toISOString(),task_count: taskCount,failed_count: failedCount,+ completed_count: taskCount - failedCount - cancelledCount,+ cancelled_count: cancelledCount,};}@@ -66,8 +70,8 @@ describe("deriveAgentActivity", () => {NOW,);expect(result.buckets).toHaveLength(30);- expect(result.buckets[0]).toEqual({ total: 1, failed: 0 });- expect(result.buckets[29]).toEqual({ total: 5, failed: 0 });+ expect(result.buckets[0]).toMatchObject({ total: 1, failed: 0 });+ expect(result.buckets[29]).toMatchObject({ total: 5, failed: 0 });expect(result.daysSinceCreated).toBe(30);});@@ -83,7 +87,7 @@ describe("deriveAgentActivity", () => {expect(result.daysSinceCreated).toBe(0);// Today's bucket still records — pre-life days simply look like zero// days, which is on purpose.- expect(result.buckets[29]).toEqual({ total: 1, failed: 0 });+ expect(result.buckets[29]).toMatchObject({ total: 1, failed: 0 });});it("ignores buckets older than the 30-day window", () => {@@ -111,6 +115,57 @@ describe("deriveAgentActivity", () => {});describe("summarizeActivityWindow", () => {+ it.each<[number, number, number, number | null]>([+ [1, 1, 8, 50],+ [0, 0, 8, null],+ [0, 2, 1, 0],+ [2, 0, 1, 100],+ [0, 0, 0, null],+ ])("counts completed=%s, failed=%s, cancelled=%s independently", (completed, failed, cancelled, rate) => {+ const total = completed + failed + cancelled;+ const result = deriveAgentActivity([+ {+ ...bucket("a1", 0, total, failed),+ completed_count: completed,+ cancelled_count: cancelled,+ },+ ], fullHistoryAgent.created_at, NOW);+ expect(summarizeActivityWindow(result, 30)).toMatchObject({+ totalRuns: total,+ totalCompleted: completed,+ totalFailed: failed,+ totalCancelled: cancelled,+ successRate: rate,+ });+ });++ it("rolls outcome counts up over the requested window only", () => {+ // 5 clean runs 20 days back, then 1/1/8 today. The 7-day window sees+ // only the recent day, so the older successes must not lift its rate.+ const result = deriveAgentActivity(+ [bucket("a1", 20, 5), bucket("a1", 0, 10, 1, 8)],+ fullHistoryAgent.created_at,+ NOW,+ );+ expect(summarizeActivityWindow(result, 30)).toMatchObject({+ totalRuns: 15, totalCompleted: 6, totalCancelled: 8, successRate: 86,+ });+ expect(summarizeActivityWindow(result, 7)).toMatchObject({+ totalRuns: 10, totalCompleted: 1, totalCancelled: 8, successRate: 50,+ });+ });++ it("sums outcomes from several buckets landing on the same day", () => {+ const result = deriveAgentActivity(+ [bucket("a1", 0, 5), bucket("a1", 0, 2, 1)],+ fullHistoryAgent.created_at,+ NOW,+ );+ expect(summarizeActivityWindow(result, 30)).toMatchObject({+ totalRuns: 7, totalCompleted: 6, totalFailed: 1, successRate: 86,+ });+ });+it("rolls up totals across the trailing N buckets", () => {// 5 runs total over the 30-day series.const result = deriveAgentActivity(diff --git a/packages/core/agents/use-agent-activity.ts b/packages/core/agents/use-agent-activity.tsindex e6965fc028..3c62a5b20b 100644--- a/packages/core/agents/use-agent-activity.ts+++ b/packages/core/agents/use-agent-activity.ts@@ -13,6 +13,8 @@ const DAY_MS = 24 * 60 * 60 * 1000;export interface ActivityBucket {total: number;failed: number;+ completed: number;+ cancelled: number;}export interface AgentActivity {@@ -46,12 +48,27 @@ export interface ActivityWindowSummary {totalRuns: number;/** Sum of `bucket.failed` across the window. */totalFailed: number;+ /** Sum of `bucket.completed` across the window. */+ totalCompleted: number;+ /** Sum of `bucket.cancelled` across the window. */+ totalCancelled: number;+ /**+ * Completed / (completed + failed). Null when the window has no+ * completed or failed run to divide by — a window of nothing but+ * cancellations has no success rate, and must not claim 100%.+ */+ successRate: number | null;/** Echo of the input window — the renderer uses it for copy. */windowDays: number;}const EMPTY: AgentActivity = {- buckets: Array.from({ length: DAYS }, () => ({ total: 0, failed: 0 })),+ buckets: Array.from({ length: DAYS }, () => ({+ total: 0,+ failed: 0,+ completed: 0,+ cancelled: 0,+ })),daysSinceCreated: DAYS,};@@ -59,6 +76,9 @@ const EMPTY_SUMMARY: ActivityWindowSummary = {buckets: [],totalRuns: 0,totalFailed: 0,+ totalCompleted: 0,+ totalCancelled: 0,+ successRate: null,windowDays: 0,};@@ -131,6 +151,8 @@ export function deriveAgentActivity(const series: ActivityBucket[] = Array.from({ length: DAYS }, () => ({total: 0,failed: 0,+ completed: 0,+ cancelled: 0,}));// Newest slot is the start of "today" in local time; we walk back DAYS@@ -143,8 +165,11 @@ export function deriveAgentActivity(const daysAgo = Math.floor((today - startOfDay(ts)) / DAY_MS);if (daysAgo < 0 || daysAgo >= DAYS) continue;const slot = DAYS - 1 - daysAgo;- series[slot]!.total += b.task_count;- series[slot]!.failed += b.failed_count;+ const target = series[slot]!;+ target.total += b.task_count;+ target.failed += b.failed_count;+ target.completed += b.completed_count;+ target.cancelled += b.cancelled_count;}const createdAt = new Date(agentCreatedAt).getTime();@@ -184,11 +209,26 @@ export function summarizeActivityWindow(safeWindow === 0 ? [] : activity.buckets.slice(-safeWindow);let totalRuns = 0;let totalFailed = 0;+ let totalCompleted = 0;+ let totalCancelled = 0;for (const b of slice) {totalRuns += b.total;totalFailed += b.failed;+ totalCompleted += b.completed;+ totalCancelled += b.cancelled;}- return { buckets: slice, totalRuns, totalFailed, windowDays };+ const outcomes = totalCompleted + totalFailed;+ const successRate =+ outcomes > 0 ? Math.round((totalCompleted / outcomes) * 100) : null;+ return {+ buckets: slice,+ totalRuns,+ totalFailed,+ totalCompleted,+ totalCancelled,+ successRate,+ windowDays,+ };}function startOfDay(ts: number): number {diff --git a/packages/core/api/agent-activity.test.ts b/packages/core/api/agent-activity.test.tsnew file mode 100644index 0000000000..84fc7ab2a1--- /dev/null+++ b/packages/core/api/agent-activity.test.ts@@ -0,0 +1,45 @@+// @vitest-environment node+import { afterEach, describe, expect, it, vi } from "vitest";+import { ApiClient } from "./client";++const bucket = {+ agent_id: "a",+ bucket_at: "2026-09-15T00:00:00Z",+ task_count: 10,+ failed_count: 1,+};++afterEach(() => vi.unstubAllGlobals());++async function read(body: unknown) {+ vi.stubGlobal(+ "fetch",+ vi.fn().mockResolvedValue(new Response(JSON.stringify(body), { status: 200 })),+ );+ return new ApiClient("https://api.example.test").getWorkspaceAgentActivity30d();+}++describe("agent activity API outcomes", () => {+ it("preserves explicit outcome counts, including zero", async () => {+ expect(await read([{ ...bucket, completed_count: 0, cancelled_count: 9 }])).toEqual([+ { ...bucket, completed_count: 0, cancelled_count: 9 },+ ]);+ });++ // Outcome counts are part of the contract, so a bucket without usable+ // ones is drift, not an older peer to accommodate. Degrading the whole+ // response is the intended failure mode: an empty activity panel is+ // honest, a half-populated one silently misreports success.+ it.each([undefined, null, "1", -1, 1.5])(+ "drops the response when an outcome count is %s",+ async (bad) => {+ expect(+ await read([{ ...bucket, completed_count: bad, cancelled_count: bad }]),+ ).toEqual([]);+ },+ );++ it("falls back for a malformed list", async () => {+ expect(await read({ buckets: [] })).toEqual([]);+ });+});diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 7373e9274b..2779c8d5bd 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -239,6 +239,7 @@ import { getCurrentSlug } from "../platform/workspace-storage";import { parseWithFallback } from "./schema";import {AgentTaskListSchema,+ AgentActivityBucketListSchema,AttachmentResponseSchema,CancelTaskResponseSchema,ChatDraftRestoresResponseSchema,@@ -2393,7 +2394,10 @@ export class ApiClient {// sparkline (uses trailing 7 buckets) and the agent detail "Last 30// days" panel (uses all 30).async getWorkspaceAgentActivity30d(): Promise<AgentActivityBucket[]> {- return this.fetch(`/api/agent-activity-30d`);+ const raw = await this.fetch<unknown>(`/api/agent-activity-30d`);+ return parseWithFallback<AgentActivityBucket[]>(raw, AgentActivityBucketListSchema, [], {+ endpoint: "GET /api/agent-activity-30d",+ });}// Per-agent 30-day total run count for the Agents-list RUNS column.diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex 0463b071a8..90cdae195f 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -1802,6 +1802,19 @@ export const AgentTaskSchema = z.object({usage: z.array(TaskUsageSchema).optional().catch(undefined),}).loose();+// Outcome counts are required: every backend that serves this endpoint+// reports them, so a response missing them is a contract drift, not an+// older peer. `parseWithFallback` then degrades the whole list to `[]`+// rather than letting a partial window masquerade as measured outcomes.+export const AgentActivityBucketListSchema = z.array(z.object({+ agent_id: z.string(),+ bucket_at: z.string(),+ task_count: z.number().int().nonnegative(),+ failed_count: z.number().int().nonnegative(),+ completed_count: z.number().int().nonnegative(),+ cancelled_count: z.number().int().nonnegative(),+}).loose());+export const AgentTaskListSchema = z.array(AgentTaskSchema);// One row of a run transcript. `output_truncated` gates a completeness claimdiff --git a/packages/core/issues/ws-updaters.test.ts b/packages/core/issues/ws-updaters.test.tsindex fc7ae2eb73..37c2d10507 100644--- a/packages/core/issues/ws-updaters.test.ts+++ b/packages/core/issues/ws-updaters.test.ts@@ -1069,6 +1069,8 @@ describe("onIssueDeleted", () => {bucket_at: "2025-01-01T00:00:00Z",task_count: 1,failed_count: 0,+ completed_count: 1,+ cancelled_count: 0,},],);diff --git a/packages/core/types/agent.ts b/packages/core/types/agent.tsindex 4a597ded7c..5c20cdeea1 100644--- a/packages/core/types/agent.ts+++ b/packages/core/types/agent.ts@@ -202,6 +202,10 @@ export interface AgentActivityBucket {bucket_at: string;task_count: number;failed_count: number;+ // task_count = completed_count + failed_count + cancelled_count; the+ // back-end always reports all three.+ completed_count: number;+ cancelled_count: number;}// 30-day total run count per agent, drives the Agents-list RUNS column.diff --git a/packages/views/agents/components/agents-page.test.tsx b/packages/views/agents/components/agents-page.test.tsxindex 987e22ac8a..79a64f71eb 100644--- a/packages/views/agents/components/agents-page.test.tsx+++ b/packages/views/agents/components/agents-page.test.tsx@@ -196,8 +196,8 @@ function makeAgent(over: Partial<Agent>): Agent {// Build a 30-bucket activity series whose most-recent bucket with runs is// `daysAgo` days back — `lastActiveDaysAgo` reads exactly this.function activityLastActive(daysAgo: number): AgentActivity {- const buckets = Array.from({ length: 30 }, () => ({ total: 0, failed: 0 }));- buckets[29 - daysAgo] = { total: 1, failed: 0 };+ const buckets = Array.from({ length: 30 }, () => ({ total: 0, failed: 0, completed: 0, cancelled: 0 }));+ buckets[29 - daysAgo] = { total: 1, failed: 0, completed: 1, cancelled: 0 };return { buckets, daysSinceCreated: 30 };}diff --git a/packages/views/agents/components/sparkline.test.tsx b/packages/views/agents/components/sparkline.test.tsxnew file mode 100644index 0000000000..4c43026cff--- /dev/null+++ b/packages/views/agents/components/sparkline.test.tsx@@ -0,0 +1,22 @@+import { render } from "@testing-library/react";+import { describe, expect, it } from "vitest";+import { Sparkline } from "./sparkline";++describe("activity sparkline outcomes", () => {+ it("keeps cancellations neutral while preserving total height", () => {+ const { container } = render(+ <Sparkline+ buckets={[{ total: 10, failed: 1, completed: 1 }]}+ width={20}+ height={101}+ />,+ );+ const group = container.querySelector("g")!;+ const bars = [...group.querySelectorAll("rect")];+ expect(bars).toHaveLength(3);+ expect(group.querySelector('rect[fill="var(--color-brand)"]')).toHaveAttribute("height", "10");+ expect(group.querySelector('rect[fill="var(--color-destructive)"]')).toHaveAttribute("height", "10");+ expect(group.querySelector('rect[fill="var(--color-muted-foreground)"]')).toHaveAttribute("height", "80");+ expect(bars.reduce((sum, bar) => sum + Number(bar.getAttribute("height")), 0)).toBe(100);+ });+});diff --git a/packages/views/agents/components/sparkline.tsx b/packages/views/agents/components/sparkline.tsxindex 579a10e511..10152c948f 100644--- a/packages/views/agents/components/sparkline.tsx+++ b/packages/views/agents/components/sparkline.tsx@@ -3,6 +3,7 @@interface ActivityBucketLike {total: number;failed: number;+ completed: number;}interface SparklineProps {@@ -21,17 +22,18 @@ interface SparklineProps {const SUCCESS_FILL = "var(--color-brand)";const SUCCESS_OPACITY = 0.6;const FAILED_FILL = "var(--color-destructive)";+const NEUTRAL_FILL = "var(--color-muted-foreground)";const BASELINE_FILL = "var(--color-muted-foreground)";const BASELINE_OPACITY = 0.25;/**- * Stacked bar sparkline — success bottom, failure top. One row, one shape,- * two dimensions:+ * Stacked bar sparkline — completed bottom, failed top, cancelled neutral.+ * Two dimensions:** - **Column height** = total throughput that day (per-component scaled* so a quiet agent reads "its own shape", not flattened by a noisy* neighbour).- * - **Red share** = failure rate. A 100-runs-1-failed agent and a+ * - **Red share** = failed runs / all activity. A 100-runs-1-failed agent and a* 100-runs-99-failed agent must be told apart at scan speed; the only* way to do that with a single column is to encode the second* dimension *inside* the column.@@ -118,20 +120,40 @@ export function Sparkline({Math.max(1, Math.round((usableH * b.failed) / scaleDenominator)),): 0;- const successH = totalH - failedH;+ // Only completed runs earn a success segment. Whatever is left over+ // — cancellations — is neither success nor failure, so it reads+ // neutral rather than inflating the brand-coloured share.+ const completedH =+ b.completed > 0+ ? Math.min(+ totalH - failedH,+ Math.max(1, Math.round((usableH * b.completed) / scaleDenominator)),+ )+ : 0;+ const neutralH = totalH - failedH - completedH;const colTop = baselineY - totalH;return (<g key={i}>- {successH > 0 && (+ {completedH > 0 && (<rectx={x}- y={colTop + failedH}+ y={colTop + failedH + neutralH}width={colWidth}- height={successH}+ height={completedH}fill={SUCCESS_FILL}fillOpacity={SUCCESS_OPACITY}/>)}+ {neutralH > 0 && (+ <rect+ x={x}+ y={colTop + failedH}+ width={colWidth}+ height={neutralH}+ fill={NEUTRAL_FILL}+ fillOpacity={SUCCESS_OPACITY}+ />+ )}{failedH > 0 && (<rectx={x}diff --git a/packages/views/agents/components/tabs/activity-tab.render.test.tsx b/packages/views/agents/components/tabs/activity-tab.render.test.tsxindex 6bc896f083..4dcbe11d0c 100644--- a/packages/views/agents/components/tabs/activity-tab.render.test.tsx+++ b/packages/views/agents/components/tabs/activity-tab.render.test.tsx@@ -3,7 +3,7 @@import { describe, it, expect, vi, beforeEach } from "vitest";import { render, screen } from "@testing-library/react";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";-import type { Agent } from "@multica/core/types";+import type { Agent, AgentActivityBucket } from "@multica/core/types";import { I18nProvider } from "@multica/core/i18n/react";import enCommon from "../../../locales/en/common.json";import enAgents from "../../../locales/en/agents.json";@@ -18,35 +18,36 @@ vi.mock("@multica/core/hooks", () => ({useWorkspaceId: () => "ws-1",}));-// api / paths are only reached from a rendered TaskRow, which never mounts in-// the loading and empty states under test — stub them so the module graph-// resolves without dragging in platform wiring.+// TaskRow never mounts in these aggregate/loading/empty-state tests.vi.mock("@multica/core/api", () => ({ api: {} }));-// The tab reads three data sources. Snapshot ("Now") and the activity map-// ("Last 30 days") stay empty; the per-agent task list is the one under test,-// its queryFn swapped per test to stay pending or resolve.+// Keep "Now" empty while varying activity outcomes and task-list loading.const agentTasksRef = vi.hoisted(() => ({current: () => new Promise<unknown>(() => {}),}));-vi.mock("@multica/core/agents", () => ({- agentTaskSnapshotOptions: () => ({- queryKey: ["snapshot"],- queryFn: () => Promise.resolve([]),- }),- agentTasksOptions: () => ({- queryKey: ["agent-tasks"],- queryFn: () => agentTasksRef.current(),- }),- useWorkspaceActivityMap: () => ({ byAgent: new Map() }),- summarizeActivityWindow: () => ({- totalRuns: 0,- totalFailed: 0,- buckets: [],- }),-}));+const activityRef = vi.hoisted(() => ({ current: [] as AgentActivityBucket[] }));+vi.mock("@multica/core/agents", async (importOriginal) => {+ const actual = await importOriginal<typeof import("@multica/core/agents")>();+ return {+ ...actual,+ agentTaskSnapshotOptions: () => ({+ queryKey: ["snapshot"],+ queryFn: () => Promise.resolve([]),+ }),+ agentTasksOptions: () => ({+ queryKey: ["agent-tasks"],+ queryFn: () => agentTasksRef.current(),+ }),+ useWorkspaceActivityMap: () => ({+ byAgent: new Map([[+ "agent-1",+ actual.deriveAgentActivity(activityRef.current, "2026-01-01", Date.now()),+ ]]),+ }),+ };+});-import { ActivityTab } from "./activity-tab";+import { ActivityTab, AgentPerformanceSummary } from "./activity-tab";const baseAgent = {id: "agent-1",@@ -55,7 +56,7 @@ const baseAgent = {const EMPTY_RECENT = "This agent hasn't completed anything yet.";-function renderTab() {+function renderTab(performance = false) {const queryClient = new QueryClient({defaultOptions: { queries: { retry: false } },});@@ -72,7 +73,8 @@ function renderTab() {<I18nProvider locale="en" resources={TEST_RESOURCES}><NavigationProvider value={navigation}><QueryClientProvider client={queryClient}>- <ActivityTab agent={baseAgent} showPerformance={false} />+ {performance && <AgentPerformanceSummary agent={baseAgent} />}+ <ActivityTab agent={baseAgent} showPerformance={performance} /></QueryClientProvider></NavigationProvider></I18nProvider>,@@ -81,6 +83,41 @@ function renderTab() {beforeEach(() => {agentTasksRef.current = () => new Promise<unknown>(() => {});+ activityRef.current = [];+});++describe("agent outcome presentation", () => {+ it("uses completed and failed outcomes in both summaries and shows cancellations separately", () => {+ activityRef.current = [{+ agent_id: "agent-1",+ bucket_at: new Date().toISOString(),+ task_count: 10,+ failed_count: 1,+ completed_count: 1,+ cancelled_count: 8,+ }];+ renderTab(true);+ expect(screen.getByText("50%")).toBeInTheDocument();+ expect(screen.getByText("50% success")).toBeInTheDocument();+ expect(screen.getAllByText("8 cancelled")).toHaveLength(2);+ expect(screen.queryByText("90%")).not.toBeInTheDocument();+ });++ it("does not claim success for cancelled-only data", () => {+ activityRef.current = [{+ agent_id: "agent-1",+ bucket_at: new Date().toISOString(),+ task_count: 8,+ failed_count: 0,+ completed_count: 0,+ cancelled_count: 8,+ }];+ const { container } = renderTab(true);+ expect(screen.queryByText("100%")).not.toBeInTheDocument();+ expect(screen.queryByText("100% success")).not.toBeInTheDocument();+ expect(container.querySelectorAll('rect[fill="var(--color-brand)"]')).toHaveLength(0);+ expect(screen.getByText("success rate").parentElement).toHaveTextContent("—");+ });});describe("ActivityTab Recent work loading state", () => {diff --git a/packages/views/agents/components/tabs/activity-tab.tsx b/packages/views/agents/components/tabs/activity-tab.tsxindex 2273bf34d1..d618898edf 100644--- a/packages/views/agents/components/tabs/activity-tab.tsx+++ b/packages/views/agents/components/tabs/activity-tab.tsx@@ -207,13 +207,6 @@ export function AgentPerformanceSummary({ agent }: { agent: Agent }) {() => deriveAvgDurationLast30d(agentTasks, Date.now()),[agentTasks],);- const successPct =- summary.totalRuns > 0- ? Math.round(- ((summary.totalRuns - summary.totalFailed) / summary.totalRuns) *- 100,- )- : 100;return (<section className="mt-5 border-t pt-5">@@ -234,7 +227,7 @@ export function AgentPerformanceSummary({ agent }: { agent: Agent }) {})}/><Metric- value={`${successPct}%`}+ value={<SuccessRate rate={summary.successRate} />}label={t(($) => $.tab_body.activity.success_label)}/><Metric@@ -247,6 +240,13 @@ export function AgentPerformanceSummary({ agent }: { agent: Agent }) {destructive={summary.totalFailed > 0}/></div>+ {summary.totalCancelled > 0 && (+ <p className="mt-2 text-caption text-muted-foreground">+ {t(($) => $.tab_body.activity.cancelled_count, {+ count: summary.totalCancelled,+ })}+ </p>+ )}<Sparklinebuckets={summary.buckets}width={250}@@ -264,7 +264,7 @@ function Metric({label,destructive = false,}: {- value: string;+ value: ReactNode;label: string;destructive?: boolean;}) {@@ -282,6 +282,32 @@ function Metric({);}+function SuccessRate({+ rate,+ labelled = false,+}: {+ rate: number | null;+ labelled?: boolean;+}) {+ const { t } = useT("agents");+ return (+ <Tooltip>+ <TooltipTrigger render={<span tabIndex={0} />}>+ {rate === null+ ? "—"+ : labelled+ ? t(($) => $.tab_body.activity.success_pct, { percent: rate })+ : `${rate}%`}+ </TooltipTrigger>+ <TooltipContent>+ {rate === null+ ? t(($) => $.tab_body.activity.success_unavailable)+ : t(($) => $.tab_body.activity.success_hint)}+ </TooltipContent>+ </Tooltip>+ );+}+function NowSection({tasks,issueMap,@@ -326,10 +352,6 @@ function Last30dSection({const summary = summarizeActivityWindow(activity, 30);const { totalRuns, totalFailed } = summary;const locales = i18n.resolvedLanguage ?? i18n.language;- const successPct =- totalRuns > 0- ? Math.round(((totalRuns - totalFailed) / totalRuns) * 100)- : 100;return (<Section title={t(($) => $.tab_body.activity.section_last_30d)} subtitle={t(($) => $.tab_body.activity.subtitle_performance)}>@@ -351,7 +373,7 @@ function Last30dSection({</span></div><div className="text-caption text-muted-foreground">- {t(($) => $.tab_body.activity.success_pct, { percent: successPct })}+ <SuccessRate rate={summary.successRate} labelled />{avgDurationMs > 0 && (<><Sep />@@ -366,6 +388,16 @@ function Last30dSection({</span></>)}+ {summary.totalCancelled > 0 && (+ <>+ <Sep />+ <span>+ {t(($) => $.tab_body.activity.cancelled_count, {+ count: summary.totalCancelled,+ })}+ </span>+ </>+ )}</div></div>{/* Garnish, not hero — small enough that a sparse 30-day seriesdiff --git a/packages/views/locales/en/agents.json b/packages/views/locales/en/agents.jsonindex 319b0df76c..3fb294456a 100644--- a/packages/views/locales/en/agents.json+++ b/packages/views/locales/en/agents.json@@ -747,7 +747,10 @@"runs_one": "run","runs_other": "runs","success_pct": "{{percent}}% success",- "success_label": "succeeded",+ "success_label": "success rate",+ "success_hint": "Completed runs divided by completed and failed runs. Cancelled runs are excluded.",+ "success_unavailable": "No completed or failed runs in this period, so there is no success rate to show.",+ "cancelled_count": "{{count}} cancelled","avg_duration": "avg {{value}}","avg_duration_label": "average duration","failed_count": "{{count}} failed",diff --git a/packages/views/locales/ja/agents.json b/packages/views/locales/ja/agents.jsonindex ab34d763ae..32e692a399 100644--- a/packages/views/locales/ja/agents.json+++ b/packages/views/locales/ja/agents.json@@ -625,7 +625,10 @@"show_more": "もっと見る →","runs_other": "回実行","success_pct": "成功率 {{percent}}%",- "success_label": "成功",+ "success_label": "成功率",+ "success_hint": "完了した実行数を、完了と失敗の実行数の合計で割った割合です。キャンセルした実行は含みません。",+ "success_unavailable": "この期間に完了または失敗した実行がないため、成功率を計算できません。",+ "cancelled_count": "{{count}} 件キャンセル","avg_duration": "平均 {{value}}","avg_duration_label": "平均時間","failed_count": "{{count}} 回失敗",diff --git a/packages/views/locales/ko/agents.json b/packages/views/locales/ko/agents.jsonindex 2585e84f68..da6c69ebb0 100644--- a/packages/views/locales/ko/agents.json+++ b/packages/views/locales/ko/agents.json@@ -633,7 +633,10 @@"show_more": "더 보기 →","runs_other": "회 실행","success_pct": "성공률 {{percent}}%",- "success_label": "성공",+ "success_label": "성공률",+ "success_hint": "완료 및 실패한 실행 수 중 완료한 실행의 비율입니다. 취소한 실행은 제외됩니다.",+ "success_unavailable": "이 기간에 완료하거나 실패한 실행이 없어 성공률을 계산할 수 없습니다.",+ "cancelled_count": "{{count}}개 취소됨","avg_duration": "평균 {{value}}","avg_duration_label": "평균 소요 시간","failed_count": "{{count}}회 실패",diff --git a/packages/views/locales/zh-Hans/agents.json b/packages/views/locales/zh-Hans/agents.jsonindex f55c1505ec..bf59d9f7ca 100644--- a/packages/views/locales/zh-Hans/agents.json+++ b/packages/views/locales/zh-Hans/agents.json@@ -732,7 +732,10 @@"show_more": "查看更多 →","runs_other": "次运行","success_pct": "{{percent}}% 成功",- "success_label": "成功",+ "success_label": "成功率",+ "success_hint": "成功率按已完成和失败的运行计算,不包含已取消的运行。",+ "success_unavailable": "本期间没有已完成或失败的运行,无法计算成功率。",+ "cancelled_count": "{{count}} 次已取消","avg_duration": "平均 {{value}}","avg_duration_label": "平均耗时","failed_count": "{{count}} 次失败",diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.goindex e666a753c0..a2426a8cce 100644--- a/server/internal/handler/agent.go+++ b/server/internal/handler/agent.go@@ -2641,10 +2641,12 @@ func (h *Handler) ListAgentTasks(w http.ResponseWriter, r *http.Request) {// AgentActivityBucket is one day-bucketed throughput sample for the// Agents-list ACTIVITY sparkline. bucket_at is midnight UTC of the day.type AgentActivityBucket struct {- AgentID string `json:"agent_id"`- BucketAt string `json:"bucket_at"`- TaskCount int32 `json:"task_count"`- FailedCount int32 `json:"failed_count"`+ AgentID string `json:"agent_id"`+ BucketAt string `json:"bucket_at"`+ TaskCount int32 `json:"task_count"`+ FailedCount int32 `json:"failed_count"`+ CompletedCount int32 `json:"completed_count"`+ CancelledCount int32 `json:"cancelled_count"`}// AgentRunCount is the trailing-30-day total task run count per agent,@@ -2860,10 +2862,12 @@ func (h *Handler) GetWorkspaceAgentActivity30d(w http.ResponseWriter, r *http.Recontinue}resp = append(resp, AgentActivityBucket{- AgentID: agentID,- BucketAt: timestampToString(row.Bucket),- TaskCount: row.TaskCount,- FailedCount: row.FailedCount,+ AgentID: agentID,+ BucketAt: timestampToString(row.Bucket),+ TaskCount: row.TaskCount,+ FailedCount: row.FailedCount,+ CompletedCount: row.CompletedCount,+ CancelledCount: row.CancelledCount,})}diff --git a/server/internal/handler/agent_activity_outcomes_test.go b/server/internal/handler/agent_activity_outcomes_test.gonew file mode 100644index 0000000000..74f91aceb7--- /dev/null+++ b/server/internal/handler/agent_activity_outcomes_test.go@@ -0,0 +1,83 @@+package handler++import (+ "net/http"+ "testing"++ "github.com/multica-ai/multica/server/internal/testutil"+)++func TestAgentActivityOutcomes(t *testing.T) {+ runtimeID := dbfx.Runtime(t, "activity outcomes runtime")+ agentID := dbfx.Agent(t, "activity outcomes agent", runtimeID)+ issueID := dbfx.Issue(t, "activity outcomes issue")++ // Exercise the cancellation handler, including a run stopped after starting.+ for i := 0; i < 8; i++ {+ cols := testutil.Cols{"runtime_id": runtimeID, "issue_id": issueID}+ if i == 7 {+ cols["status"] = "running"+ cols["started_at"] = testutil.Raw("now() - interval '1 minute'")+ }+ taskID := dbfx.Task(t, agentID, cols)+ testutil.Call(t, testHandler.CancelTaskByUser, cancelTaskByUserRequest(t, testUserID, taskID)).Want(http.StatusOK)+ if got := taskStatus(t, taskID); got != "cancelled" {+ t.Fatalf("cancel handler left task %s in %s", taskID, got)+ }+ }++ readCounts := func(t *testing.T, wantTotal, wantCompleted, wantFailed, wantCancelled int) {+ t.Helper()+ var rows []struct {+ AgentID string `json:"agent_id"`+ TaskCount int `json:"task_count"`+ CompletedCount *int `json:"completed_count"`+ FailedCount int `json:"failed_count"`+ CancelledCount *int `json:"cancelled_count"`+ }+ req := withChatTestWorkspaceCtx(t, newRequest(http.MethodGet, "/api/agent-activity-30d", nil))+ testutil.Call(t, testHandler.GetWorkspaceAgentActivity30d, req).Want(http.StatusOK).JSON(&rows)+ var total, completed, failed, cancelled int+ for _, row := range rows {+ if row.AgentID != agentID {+ continue+ }+ if row.CompletedCount == nil || row.CancelledCount == nil {+ t.Fatalf("activity response must distinguish completed/cancelled counts: %+v", row)+ }+ total += row.TaskCount+ completed += *row.CompletedCount+ failed += row.FailedCount+ cancelled += *row.CancelledCount+ }+ if total != wantTotal || completed != wantCompleted || failed != wantFailed || cancelled != wantCancelled {+ t.Fatalf("total/completed/failed/cancelled = %d/%d/%d/%d, want %d/%d/%d/%d", total, completed, failed, cancelled, wantTotal, wantCompleted, wantFailed, wantCancelled)+ }+ }++ t.Run("only_cancelled", func(t *testing.T) { readCounts(t, 8, 0, 0, 8) })+ for _, status := range []string{"completed", "failed"} {+ dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID,+ "issue_id": issueID,+ "status": status,+ "started_at": testutil.Raw("now() - interval '1 minute'"),+ "completed_at": testutil.Raw("now()"),+ })+ }+ t.Run("mixed_outcomes", func(t *testing.T) { readCounts(t, 10, 1, 1, 8) })++ // Neither old outcomes nor a still-running attempt belongs in the window.+ for _, status := range []string{"completed", "failed", "cancelled"} {+ dbfx.Task(t, agentID, testutil.Cols{+ "status": status,+ "completed_at": testutil.Raw("now() - interval '31 days'"),+ })+ }+ dbfx.Task(t, agentID, testutil.Cols{+ "runtime_id": runtimeID,+ "status": "running",+ "started_at": testutil.Raw("now()"),+ })+ t.Run("window_and_active_runs", func(t *testing.T) { readCounts(t, 10, 1, 1, 8) })+}diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.goindex 75a94fc05e..dbc543ecd4 100644--- a/server/pkg/db/generated/agent.sql.go+++ b/server/pkg/db/generated/agent.sql.go@@ -4613,7 +4613,9 @@ SELECTatq.agent_id,DATE_TRUNC('day', atq.completed_at)::timestamptz AS bucket,COUNT(*)::int AS task_count,- COUNT(*) FILTER (WHERE atq.status = 'failed')::int AS failed_count+ COUNT(*) FILTER (WHERE atq.status = 'failed')::int AS failed_count,+ COUNT(*) FILTER (WHERE atq.status = 'completed')::int AS completed_count,+ COUNT(*) FILTER (WHERE atq.status = 'cancelled')::int AS cancelled_countFROM agent_task_queue atqJOIN agent a ON a.id = atq.agent_idWHERE a.workspace_id = $1@@ -4624,10 +4626,12 @@ ORDER BY atq.agent_id, bucket`type GetWorkspaceAgentActivity30dRow struct {- AgentID pgtype.UUID `json:"agent_id"`- Bucket pgtype.Timestamptz `json:"bucket"`- TaskCount int32 `json:"task_count"`- FailedCount int32 `json:"failed_count"`+ AgentID pgtype.UUID `json:"agent_id"`+ Bucket pgtype.Timestamptz `json:"bucket"`+ TaskCount int32 `json:"task_count"`+ FailedCount int32 `json:"failed_count"`+ CompletedCount int32 `json:"completed_count"`+ CancelledCount int32 `json:"cancelled_count"`}// Returns per-agent daily activity buckets for the last 30 days. Single@@ -4644,6 +4648,8 @@ type GetWorkspaceAgentActivity30dRow struct {// still in flight has no completed_at and contributes nothing here — that's// correct: in-flight tasks are surfaced via the live presence indicator,// not the historical trend.+// Keep total activity separate from outcomes: cancelled runs belong in the+// history, but success rate is completed / (completed + failed).func (q *Queries) GetWorkspaceAgentActivity30d(ctx context.Context, workspaceID pgtype.UUID) ([]GetWorkspaceAgentActivity30dRow, error) {rows, err := q.db.Query(ctx, getWorkspaceAgentActivity30d, workspaceID)if err != nil {@@ -4658,6 +4664,8 @@ func (q *Queries) GetWorkspaceAgentActivity30d(ctx context.Context, workspaceID&i.Bucket,&i.TaskCount,&i.FailedCount,+ &i.CompletedCount,+ &i.CancelledCount,); err != nil {return nil, err}diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sqlindex 8d40bf41e7..6010553289 100644--- a/server/pkg/db/queries/agent.sql+++ b/server/pkg/db/queries/agent.sql@@ -2539,11 +2539,15 @@ GROUP BY atq.agent_id;-- still in flight has no completed_at and contributes nothing here — that's-- correct: in-flight tasks are surfaced via the live presence indicator,-- not the historical trend.+-- Keep total activity separate from outcomes: cancelled runs belong in the+-- history, but success rate is completed / (completed + failed).SELECTatq.agent_id,DATE_TRUNC('day', atq.completed_at)::timestamptz AS bucket,COUNT(*)::int AS task_count,- COUNT(*) FILTER (WHERE atq.status = 'failed')::int AS failed_count+ COUNT(*) FILTER (WHERE atq.status = 'failed')::int AS failed_count,+ COUNT(*) FILTER (WHERE atq.status = 'completed')::int AS completed_count,+ COUNT(*) FILTER (WHERE atq.status = 'cancelled')::int AS cancelled_countFROM agent_task_queue atqJOIN agent a ON a.id = atq.agent_idWHERE a.workspace_id = $1