Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-7685: fix(agents): paginate task history and aggregate duration (#8804)
Hugo815fe37b1faa
diff --git a/apps/docs/content/docs/cli.mdx b/apps/docs/content/docs/cli.mdxindex 918ed1ac8b..b9953b23f7 100644--- a/apps/docs/content/docs/cli.mdx+++ b/apps/docs/content/docs/cli.mdx@@ -141,6 +141,21 @@ multica skill import --url <skill-url> --on-conflict skip`overwrite` is only allowed for the skill's creator and preserves the original ID and agent bindings.+### Agent run history++`multica agent tasks <agent-id> --limit 200` returns the newest page of runs.+The default and maximum page size is 200. If more runs exist, stderr prints a+cursor; pass it unchanged as `--before '<cursor>'` to read the next page.+`--output json` keeps the array output and includes usage for that page only.++The corresponding `GET /api/agents/{id}/tasks` endpoint accepts `limit` and+`before`, and keeps its JSON array response. The `X-Agent-Tasks-Next-Cursor`+response header supplies the next cursor; its absence marks the final page.+Cursors preserve `(created_at, id)` order, including timestamp precision.+Invalid limits or cursors return HTTP 400; limits above 200 are capped.+Clients that do not follow the cursor receive only the newest 200 runs.++## Daemon and runtimes```bashdiff --git a/packages/core/agents/queries.test.ts b/packages/core/agents/queries.test.tsnew file mode 100644index 0000000000..a301db0b60--- /dev/null+++ b/packages/core/agents/queries.test.ts@@ -0,0 +1,114 @@+// @vitest-environment node+import { afterEach, describe, expect, it, vi } from "vitest";+import { InfiniteQueryObserver, QueryClient } from "@tanstack/react-query";+import { api } from "../api";+import type { AgentTask } from "../types";+import { agentTasksKeys, agentTasksOptions } from "./queries";++vi.mock("../api", () => ({ api: { listAgentTasksPage: vi.fn() } }));++const clients: QueryClient[] = [];+function client() {+ const result = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ clients.push(result);+ return result;+}+function page(ids: string[], nextCursor: string | null = null) {+ const tasks = ids.map((id): AgentTask => ({+ id, agent_id: "agent-1", runtime_id: "runtime-1", issue_id: "",+ status: "completed", priority: 0, dispatched_at: null, started_at: null,+ completed_at: "2026-09-24T00:00:00Z", created_at: "2026-09-24T00:00:00Z",+ result: null, error: null,+ }));+ return { tasks, nextCursor };+}++afterEach(() => {+ clients.splice(0).forEach((queryClient) => queryClient.clear());+ vi.resetAllMocks();+});++describe("agent history query lifecycle", () => {+ it("shares concurrent readers without eagerly fetching the next page", async () => {+ const queryClient = client();+ const fetchPage = vi.mocked(api.listAgentTasksPage);+ fetchPage.mockResolvedValue(page(["first"], "older"));+ const options = agentTasksOptions("workspace-1", "agent-1");+ const [first, second] = await Promise.all([+ queryClient.fetchInfiniteQuery(options),+ queryClient.fetchInfiniteQuery(options),+ ]);+ expect(fetchPage).toHaveBeenCalledTimes(1);+ expect(fetchPage).toHaveBeenCalledWith("agent-1", {+ limit: 200, before: undefined, signal: expect.any(AbortSignal),+ });+ expect(first).toEqual(second);+ expect(first.pages).toHaveLength(1);+ expect(first.pages[0]?.nextCursor).toBe("older");+ });++ it("isolates cached pages by workspace and agent", async () => {+ const queryClient = client();+ const fetchPage = vi.mocked(api.listAgentTasksPage);+ fetchPage.mockResolvedValueOnce(page(["workspace-1-agent-1"]))+ .mockResolvedValueOnce(page(["workspace-2-agent-1"]))+ .mockResolvedValueOnce(page(["workspace-1-agent-2"]));+ const first = await queryClient.fetchInfiniteQuery(agentTasksOptions("workspace-1", "agent-1"));+ const otherWorkspace = await queryClient.fetchInfiniteQuery(agentTasksOptions("workspace-2", "agent-1"));+ const otherAgent = await queryClient.fetchInfiniteQuery(agentTasksOptions("workspace-1", "agent-2"));+ const cached = await queryClient.fetchInfiniteQuery(agentTasksOptions("workspace-1", "agent-1"));+ expect(fetchPage).toHaveBeenCalledTimes(3);+ expect(cached).toEqual(first);+ expect(otherWorkspace.pages[0]?.tasks[0]?.id).toBe("workspace-2-agent-1");+ expect(otherAgent.pages[0]?.tasks[0]?.id).toBe("workspace-1-agent-2");+ });++ it("rebuilds subsequent cursors after a task event invalidates loaded pages", async () => {+ const queryClient = client();+ const fetchPage = vi.mocked(api.listAgentTasksPage);+ fetchPage.mockResolvedValueOnce(page(["first"], "old-boundary"))+ .mockResolvedValueOnce(page(["second"]))+ .mockResolvedValueOnce(page(["new"], "new-boundary"))+ .mockResolvedValueOnce(page(["first", "second"]));+ const options = agentTasksOptions("workspace-1", "agent-1");+ await queryClient.fetchInfiniteQuery(options);+ const observer = new InfiniteQueryObserver(queryClient, options);+ const unsubscribe = observer.subscribe(() => {});+ try {+ await observer.fetchNextPage();+ expect(fetchPage.mock.calls[1]?.[1]?.before).toBe("old-boundary");+ // This is the same prefix used by task lifecycle WebSocket events.+ await queryClient.invalidateQueries({ queryKey: agentTasksKeys.all("workspace-1") });+ expect(fetchPage).toHaveBeenCalledTimes(4);+ expect(fetchPage.mock.calls[2]?.[1]?.before).toBeUndefined();+ expect(fetchPage.mock.calls[3]?.[1]?.before).toBe("new-boundary");+ expect(observer.getCurrentResult().data?.pages.flatMap((p) => p.tasks.map((t) => t.id)))+ .toEqual(["new", "first", "second"]);+ expect(observer.getCurrentResult().hasNextPage).toBe(false);+ await observer.fetchNextPage();+ expect(fetchPage).toHaveBeenCalledTimes(4);+ } finally {+ unsubscribe();+ }+ });++ it("aborts a pending history request when its last reader leaves", async () => {+ const queryClient = client();+ let requestSignal: AbortSignal | undefined;+ vi.mocked(api.listAgentTasksPage).mockImplementation((_id, options) => {+ requestSignal = options?.signal;+ return new Promise((_resolve, reject) => {+ requestSignal?.addEventListener("abort", () => reject(new Error("aborted")), { once: true });+ });+ });+ const options = agentTasksOptions("workspace-1", "agent-1");+ const observer = new InfiniteQueryObserver(queryClient, options);+ const unsubscribe = observer.subscribe(() => {});+ await vi.waitFor(() => expect(requestSignal).toBeDefined());+ expect(requestSignal?.aborted).toBe(false);+ unsubscribe();+ expect(requestSignal?.aborted).toBe(true);+ expect(queryClient.getQueryState(options.queryKey)?.fetchStatus).toBe("idle");+ expect(queryClient.getQueryData(options.queryKey)).toBeUndefined();+ });+});diff --git a/packages/core/agents/queries.ts b/packages/core/agents/queries.tsindex a8f17654d0..dde47a015f 100644--- a/packages/core/agents/queries.ts+++ b/packages/core/agents/queries.ts@@ -1,4 +1,4 @@-import { queryOptions } from "@tanstack/react-query";+import { infiniteQueryOptions, queryOptions } from "@tanstack/react-query";import { api } from "../api";import type {WorkspaceWorkingAgentMineRelation,@@ -123,14 +123,15 @@ export const agentTasksKeys = {[...agentTasksKeys.all(wsId), agentId] as const,};-// All tasks for a single agent (the agent detail page consumer). Powers both-// the inspector's 7-day throughput stats and the Tasks tab list — shared so-// they don't fetch twice. WS task events invalidate this via the existing-// task-prefix invalidation in useRealtimeSync.+// History is fetched one bounded page at a time. Aggregate metrics use+// agentActivity30dOptions so they do not depend on how many pages were opened.export function agentTasksOptions(wsId: string, agentId: string) {- return queryOptions({- queryKey: agentTasksKeys.detail(wsId, agentId),- queryFn: () => api.listAgentTasks(agentId),+ return infiniteQueryOptions({+ queryKey: [...agentTasksKeys.detail(wsId, agentId), "pages"],+ initialPageParam: undefined as string | undefined,+ queryFn: ({ pageParam, signal }) =>+ api.listAgentTasksPage(agentId, { limit: 200, before: pageParam, signal }),+ getNextPageParam: (lastPage) => lastPage.nextCursor ?? undefined,staleTime: 30 * 1000,gcTime: 5 * 60 * 1000,refetchOnWindowFocus: true,diff --git a/packages/core/agents/use-agent-activity.test.ts b/packages/core/agents/use-agent-activity.test.tsindex 476eeec397..260aebef2d 100644--- a/packages/core/agents/use-agent-activity.test.ts+++ b/packages/core/agents/use-agent-activity.test.ts@@ -245,3 +245,34 @@ describe("buildActivityMap", () => {expect(summarizeActivityWindow(a, 30).totalRuns).toBe(0);});});+++describe("aggregate duration", () => {+ it("weights daily duration totals by measured runs, independent of task pages", () => {+ const result = deriveAgentActivity([+ { ...bucket("a", 0, 200), duration_ms: 12000000, duration_count: 200 },+ { ...bucket("a", 1, 1), duration_ms: 600000, duration_count: 1 },+ ], "2026-01-01", NOW);+ expect(result.avgDurationMs).toBe(Math.round(12600000 / 201));+ });++ // completed_at > now() - 30 days can span 31 calendar days. The chart keeps+ // 30 local-day slots, but the average must cover the whole server window.+ it("averages the full rolling window, including the oldest day the chart drops", () => {+ const now = Date.parse("2026-09-27T12:00:00Z");+ const run = (bucketAt: string, durationMs: number): AgentActivityBucket => ({+ agent_id: "a", bucket_at: bucketAt, task_count: 1, completed_count: 1,+ failed_count: 0, cancelled_count: 0, duration_ms: durationMs, duration_count: 1,+ });+ const result = deriveAgentActivity([+ run("2026-08-28T00:00:00Z", 61 * 60_000),+ run("2026-09-27T00:00:00Z", 60_000),+ ], "2026-01-01T00:00:00Z", now);+ expect(result.buckets.reduce((sum, b) => sum + b.total, 0)).toBe(1);+ expect(result.avgDurationMs).toBe(31 * 60_000);+ });++ it("does not estimate duration when the server omits aggregates", () => {+ expect(deriveAgentActivity([bucket("a", 0, 5)], "2026-01-01", NOW).avgDurationMs).toBe(0);+ });+});diff --git a/packages/core/agents/use-agent-activity.ts b/packages/core/agents/use-agent-activity.tsindex 3c62a5b20b..2a8cc0b666 100644--- a/packages/core/agents/use-agent-activity.ts+++ b/packages/core/agents/use-agent-activity.ts@@ -33,6 +33,7 @@ export interface AgentActivity {* zero days.*/daysSinceCreated: number;+ avgDurationMs?: number;}/**@@ -159,7 +160,14 @@ export function deriveAgentActivity(// slots so index 0 = oldest, index DAYS-1 = today.const today = startOfDay(now);+ let durationMs = 0;+ let durationCount = 0;for (const b of buckets) {+ // The server already bounds duration to its rolling 30-day window, which+ // can span 31 calendar days. Sum before the chart's local-day slotting so+ // the oldest partial day still counts toward the average.+ durationMs += b.duration_ms ?? 0;+ durationCount += b.duration_count ?? 0;const ts = new Date(b.bucket_at).getTime();if (Number.isNaN(ts)) continue;const daysAgo = Math.floor((today - startOfDay(ts)) / DAY_MS);@@ -182,6 +190,7 @@ export function deriveAgentActivity(return {buckets: series,daysSinceCreated,+ avgDurationMs: durationCount > 0 ? Math.round(durationMs / durationCount) : 0,};}diff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.tsindex c145c94d6e..390f6074dc 100644--- a/packages/core/api/client.test.ts+++ b/packages/core/api/client.test.ts@@ -1148,15 +1148,43 @@ describe("ApiClient", () => {vi.stubGlobal("fetch", fetchMock);const client = new ApiClient("https://api.example.test");- const tasks = await client.listAgentTasks("agent-1");+ const { tasks, nextCursor } = await client.listAgentTasksPage("agent-1");expect(tasks.map((task) => task.id)).toEqual(["task-1", "task-2"]);+ expect(nextCursor).toBeNull();expect(fetchMock).toHaveBeenCalledTimes(1);expect(fetchMock.mock.calls[0]?.[0]).toBe(- "https://api.example.test/api/agents/agent-1/tasks",+ "https://api.example.test/api/agents/agent-1/tasks?limit=200",);});+ it("reads a lossless task cursor and passes it to the next bounded request", async () => {+ const cursor = "2026-09-24T01:02:03.123456Z|00000000-0000-0000-0000-000000000001";+ const fetchMock = vi.fn().mockImplementation(() => Promise.resolve(new Response(+ JSON.stringify([{ id: "task-1", status: "completed" }]),+ { headers: { "X-Agent-Tasks-Next-Cursor": cursor } },+ )));+ vi.stubGlobal("fetch", fetchMock);+ const client = new ApiClient("https://api.example.test");+ const page = await client.listAgentTasksPage("agent-1", { limit: 7 });+ expect(page.nextCursor).toBe(cursor);+ const controller = new AbortController();+ await client.listAgentTasksPage("agent-1", { limit: 7, before: page.nextCursor!, signal: controller.signal });+ const request = new URL(fetchMock.mock.calls[1]![0]);+ expect(request.searchParams.get("limit")).toBe("7");+ expect(request.searchParams.get("before")).toBe(cursor);+ expect(fetchMock.mock.calls[1]![1].signal).toBe(controller.signal);+ });++ it("drops the continuation when the task page is malformed", async () => {+ vi.stubGlobal("fetch", vi.fn().mockResolvedValue(new Response(+ JSON.stringify({ tasks: "not-an-array" }),+ { headers: { "X-Agent-Tasks-Next-Cursor": "cursor" } },+ )));+ const client = new ApiClient("https://api.example.test");+ await expect(client.listAgentTasksPage("agent-1")).resolves.toEqual({ tasks: [], nextCursor: null });+ });+it("falls back to an empty agent task history for a malformed response", async () => {const fetchMock = vi.fn().mockResolvedValue(new Response(JSON.stringify({ tasks: "not-an-array" }), {@@ -1167,7 +1195,7 @@ describe("ApiClient", () => {vi.stubGlobal("fetch", fetchMock);const client = new ApiClient("https://api.example.test");- await expect(client.listAgentTasks("agent-1")).resolves.toEqual([]);+ await expect(client.listAgentTasksPage("agent-1")).resolves.toEqual({ tasks: [], nextCursor: null });expect(fetchMock).toHaveBeenCalledTimes(1);});diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex bfe821ea42..2440ec15e3 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -247,6 +247,7 @@ import {RuntimeProfileSchema,RuntimeProfileListSchema,AgentTaskListSchema,+ AgentTaskPageSchema,AgentActivityBucketListSchema,AttachmentResponseSchema,CancelTaskResponseSchema,@@ -2619,11 +2620,22 @@ export class ApiClient {return this.fetch(`/api/runtimes/${runtimeId}/local-skills/import/${requestId}`);}- async listAgentTasks(agentId: string): Promise<AgentTask[]> {- const raw = await this.fetch<unknown>(`/api/agents/${agentId}/tasks`);- return parseWithFallback<AgentTask[]>(raw, AgentTaskListSchema, [], {- endpoint: "GET /api/agents/:id/tasks",- });+ async listAgentTasksPage(+ agentId: string,+ options: { limit?: number; before?: string; signal?: AbortSignal } = {},+ ): Promise<{ tasks: AgentTask[]; nextCursor: string | null }> {+ const search = new URLSearchParams({ limit: String(options.limit ?? 200) });+ if (options.before) search.set("before", options.before);+ const response = await this.fetchRaw(`/api/agents/${agentId}/tasks?${search}`, {+ signal: options.signal,+ });+ const tasks: unknown = await response.json();+ return parseWithFallback(+ { tasks, nextCursor: response.headers.get("X-Agent-Tasks-Next-Cursor") },+ AgentTaskPageSchema,+ { tasks: [], nextCursor: null },+ { endpoint: "GET /api/agents/:id/tasks" },+ );}// Workspace-scoped agent task snapshot: every active taskdiff --git a/packages/core/api/schemas.test.ts b/packages/core/api/schemas.test.tsindex 5de48b3d65..2cfdd3536c 100644--- a/packages/core/api/schemas.test.ts+++ b/packages/core/api/schemas.test.ts@@ -14,6 +14,7 @@ import {EMPTY_LIST_TELEGRAM_INSTALLATIONS_RESPONSE,EMPTY_REDEEM_TELEGRAM_BINDING_TOKEN_RESPONSE,AgentTaskListSchema,+ AgentActivityBucketListSchema,TaskMessageListSchema,AutopilotQuotaUsageSchema,AutopilotRunSchema,@@ -2338,3 +2339,19 @@ describe("TaskMessageListSchema", () => {expect(parsed[0]?.type).toBe("text");});});+++describe("AgentActivityBucketListSchema duration", () => {+ const bucket = { agent_id: "a", bucket_at: "2026-09-24T00:00:00Z", task_count: 201,+ completed_count: 201, failed_count: 0, cancelled_count: 0 };+ it("accepts optional aggregate duration from new and old servers", () => {+ expect(AgentActivityBucketListSchema.parse([bucket])[0]?.duration_ms).toBeUndefined();+ expect(AgentActivityBucketListSchema.parse([{ ...bucket, duration_ms: 12600000, duration_count: 201 }])[0]?.duration_count).toBe(201);+ });+ it("does not discard activity counts when duration is malformed", () => {+ const parsed = AgentActivityBucketListSchema.parse([{ ...bucket, duration_ms: "slow", duration_count: -1 }]);+ expect(parsed[0]?.task_count).toBe(201);+ expect(parsed[0]?.duration_ms).toBeUndefined();+ expect(parsed[0]?.duration_count).toBeUndefined();+ });+});diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex 9258805540..cd62bd9c5b 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -1911,10 +1911,17 @@ export const AgentActivityBucketListSchema = z.array(z.object({failed_count: z.number().int().nonnegative(),completed_count: z.number().int().nonnegative(),cancelled_count: z.number().int().nonnegative(),+ duration_ms: z.number().nonnegative().optional().catch(undefined),+ duration_count: z.number().int().nonnegative().optional().catch(undefined),}).loose());export const AgentTaskListSchema = z.array(AgentTaskSchema);+export const AgentTaskPageSchema = z.object({+ tasks: AgentTaskListSchema,+ nextCursor: z.string().min(1).nullable(),+});+// One row of a run transcript. `output_truncated` gates a completeness claim// the UI makes about a tool's output, so it stays `.optional()` with no// default: a server that does not send it means "unknown", and defaulting itdiff --git a/packages/core/types/agent.ts b/packages/core/types/agent.tsindex 78c5a3f30b..ff3a3b0685 100644--- a/packages/core/types/agent.ts+++ b/packages/core/types/agent.ts@@ -216,6 +216,9 @@ export interface AgentActivityBucket {// back-end always reports all three.completed_count: number;cancelled_count: number;+ // Absent on older servers; do not estimate duration from a task page.+ duration_ms?: number;+ duration_count?: number;}// 30-day total run count per agent, drives the Agents-list RUNS column.diff --git a/packages/views/agents/components/tabs/activity-tab.render.test.tsx b/packages/views/agents/components/tabs/activity-tab.render.test.tsxindex 4dcbe11d0c..240f4c94d7 100644--- a/packages/views/agents/components/tabs/activity-tab.render.test.tsx+++ b/packages/views/agents/components/tabs/activity-tab.render.test.tsx@@ -1,9 +1,10 @@// @vitest-environment jsdomimport { describe, it, expect, vi, beforeEach } from "vitest";-import { render, screen } from "@testing-library/react";+import { render, screen, fireEvent, waitFor } from "@testing-library/react";import { QueryClient, QueryClientProvider } from "@tanstack/react-query";-import type { Agent, AgentActivityBucket } from "@multica/core/types";+import type { Agent, AgentActivityBucket, AgentTask } from "@multica/core/types";+import { WorkspaceSlugProvider } from "@multica/core/paths";import { I18nProvider } from "@multica/core/i18n/react";import enCommon from "../../../locales/en/common.json";import enAgents from "../../../locales/en/agents.json";@@ -18,12 +19,18 @@ vi.mock("@multica/core/hooks", () => ({useWorkspaceId: () => "ws-1",}));-// TaskRow never mounts in these aggregate/loading/empty-state tests.+// History fixtures have no issue links, so they need no issue-detail requests.vi.mock("@multica/core/api", () => ({ api: {} }));+// Keep transcript internals out of history pagination tests while exposing+// the identity of each rendered task row.+vi.mock("../../../common/task-transcript", () => ({+ TranscriptButton: ({ task }: { task: AgentTask }) => <span data-testid={`task-${task.id}`} />,+}));+// Keep "Now" empty while varying activity outcomes and task-list loading.const agentTasksRef = vi.hoisted(() => ({- current: () => new Promise<unknown>(() => {}),+ current: (_before?: string) => new Promise<unknown>(() => {}),}));const activityRef = vi.hoisted(() => ({ current: [] as AgentActivityBucket[] }));vi.mock("@multica/core/agents", async (importOriginal) => {@@ -36,7 +43,9 @@ vi.mock("@multica/core/agents", async (importOriginal) => {}),agentTasksOptions: () => ({queryKey: ["agent-tasks"],- queryFn: () => agentTasksRef.current(),+ initialPageParam: undefined,+ getNextPageParam: (page: { nextCursor: string | null }) => page.nextCursor ?? undefined,+ queryFn: ({ pageParam }: { pageParam?: string }) => agentTasksRef.current(pageParam),}),useWorkspaceActivityMap: () => ({byAgent: new Map([[@@ -73,8 +82,10 @@ function renderTab(performance = false) {<I18nProvider locale="en" resources={TEST_RESOURCES}><NavigationProvider value={navigation}><QueryClientProvider client={queryClient}>- {performance && <AgentPerformanceSummary agent={baseAgent} />}- <ActivityTab agent={baseAgent} showPerformance={performance} />+ <WorkspaceSlugProvider slug="acme">+ {performance && <AgentPerformanceSummary agent={baseAgent} />}+ <ActivityTab agent={baseAgent} showPerformance={performance} />+ </WorkspaceSlugProvider></QueryClientProvider></NavigationProvider></I18nProvider>,@@ -132,7 +143,7 @@ describe("ActivityTab Recent work loading state", () => {});it("shows the empty state once the task list resolves to no runs", async () => {- agentTasksRef.current = () => Promise.resolve([]);+ agentTasksRef.current = () => Promise.resolve({ tasks: [], nextCursor: null });renderTab();expect(await screen.findByText(EMPTY_RECENT)).toBeInTheDocument();expect(@@ -140,3 +151,147 @@ describe("ActivityTab Recent work loading state", () => {).toBe(0);});});+++describe("ActivityTab server pagination", () => {+ it("requests older history only on demand, disables duplicate fetches, and retries failures", async () => {+ let finish: (value: unknown) => void = () => {};+ const query = vi.fn()+ .mockResolvedValueOnce({ tasks: [], nextCursor: "older" })+ .mockImplementationOnce(() => new Promise((resolve) => { finish = resolve; }))+ .mockRejectedValueOnce(new Error("offline"))+ .mockResolvedValueOnce({ tasks: [], nextCursor: null });+ agentTasksRef.current = query;+ renderTab();+ const more = await screen.findByRole("button", { name: /Show more/ });+ expect(query).toHaveBeenCalledTimes(1);+ fireEvent.click(more);+ await waitFor(() => expect(more).toBeDisabled());+ fireEvent.click(more);+ expect(query).toHaveBeenCalledTimes(2);+ expect(query.mock.calls[1]?.[0]).toBe("older");+ finish({ tasks: [], nextCursor: "oldest" });+ await waitFor(() => expect(more).toBeEnabled());+ fireEvent.click(more);+ const retry = await screen.findByRole("button", { name: "Try again" });+ fireEvent.click(retry);+ await waitFor(() => expect(screen.queryByRole("button", { name: /Show more/ })).not.toBeInTheDocument());+ expect(query.mock.calls[3]?.[0]).toBe("oldest");+ });++ it("renders aggregate duration without fetching task history for the performance summary", () => {+ const query = vi.fn();+ agentTasksRef.current = query;+ activityRef.current = [{ agent_id: "agent-1", bucket_at: new Date().toISOString(), task_count: 201,+ completed_count: 201, failed_count: 0, cancelled_count: 0, duration_ms: 24120000, duration_count: 201 }];+ render(<I18nProvider locale="en" resources={TEST_RESOURCES}>+ <QueryClientProvider client={new QueryClient()}><AgentPerformanceSummary agent={baseAgent} /></QueryClientProvider>+ </I18nProvider>);+ expect(screen.getByText("2m 00s")).toBeInTheDocument();+ expect(query).not.toHaveBeenCalled();+ });+});+++function historyTask(index: number): AgentTask {+ return {+ id: String(index), agent_id: "agent-1", runtime_id: "runtime-1", issue_id: "",+ status: "completed", priority: 0, dispatched_at: null, started_at: null,+ completed_at: new Date(Date.now() - index * 60000).toISOString(),+ created_at: new Date(Date.now() - index * 60000).toISOString(),+ result: null, error: null,+ };+}++describe("ActivityTab loaded history rows", () => {+ it("reveals cached rows before requesting older history and deduplicates overlapping pages", async () => {+ const tasks = Array.from({ length: 31 }, (_, i) => historyTask(i));+ const query = vi.fn()+ .mockResolvedValueOnce({ tasks, nextCursor: "older" })+ .mockResolvedValueOnce({ tasks: [tasks[30], historyTask(31)], nextCursor: null });+ agentTasksRef.current = query;+ renderTab();+ await screen.findByTestId("task-0");+ expect(screen.getAllByTestId(/^task-/)).toHaveLength(10);+ expect(screen.queryByTestId("task-10")).not.toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: /Show more/ }));+ expect(screen.getAllByTestId(/^task-/)).toHaveLength(30);+ expect(query).toHaveBeenCalledTimes(1);+ fireEvent.click(screen.getByRole("button", { name: /Show more/ }));+ expect(screen.getAllByTestId(/^task-/)).toHaveLength(31);+ expect(query).toHaveBeenCalledTimes(1);+ fireEvent.click(screen.getByRole("button", { name: /Show more/ }));+ await screen.findByTestId("task-31");+ expect(query).toHaveBeenCalledTimes(2);+ expect(query.mock.calls[1]?.[0]).toBe("older");+ expect(screen.getAllByTestId(/^task-/)).toHaveLength(32);+ expect(screen.getAllByTestId("task-30")).toHaveLength(1);+ expect(screen.queryByRole("button", { name: /Show more/ })).not.toBeInTheDocument();+ });++ it("keeps loaded rows visible when an older page fails and retries the same cursor", async () => {+ const query = vi.fn()+ .mockResolvedValueOnce({ tasks: [historyTask(0)], nextCursor: "older" })+ .mockRejectedValueOnce(new Error("offline"))+ .mockResolvedValueOnce({ tasks: [historyTask(1)], nextCursor: null });+ agentTasksRef.current = query;+ renderTab();+ await screen.findByTestId("task-0");+ fireEvent.click(screen.getByRole("button", { name: /Show more/ }));+ const retry = await screen.findByRole("button", { name: "Try again" });+ expect(screen.getByTestId("task-0")).toBeInTheDocument();+ expect(screen.queryByText(EMPTY_RECENT)).not.toBeInTheDocument();+ fireEvent.click(retry);+ await screen.findByTestId("task-1");+ expect(screen.getAllByTestId(/^task-/)).toHaveLength(2);+ expect(query.mock.calls.slice(1).map(([before]) => before)).toEqual(["older", "older"]);+ });+});++// A loaded page is not the total history. Keep the denominator unknown until+// the server reports that the last page has been reached.+describe("ActivityTab history completeness", () => {+ it.each([+ { nextCursor: "older", subtitle: "10 latest runs" },+ { nextCursor: null, subtitle: "10 of 200 runs" },+ ])("shows '$subtitle' for a 200-row page with cursor $nextCursor", async ({ nextCursor, subtitle }) => {+ agentTasksRef.current = () => Promise.resolve({+ tasks: Array.from({ length: 200 }, (_, i) => historyTask(i)),+ nextCursor,+ });+ renderTab();+ expect(await screen.findByText(subtitle)).toBeInTheDocument();+ if (nextCursor) {+ expect(screen.queryByText("10 of 200 runs")).not.toBeInTheDocument();+ }+ expect(screen.getAllByTestId(/^task-/)).toHaveLength(10);+ });++ it.each([+ { nextCursor: "oldest", subtitle: "50 latest runs" },+ { nextCursor: null, subtitle: "50 of 220 runs" },+ ])("shows '$subtitle' after loading more history with cursor $nextCursor", async ({ nextCursor, subtitle }) => {+ const query = vi.fn()+ .mockResolvedValueOnce({+ tasks: Array.from({ length: 20 }, (_, i) => historyTask(i)),+ nextCursor: "older",+ })+ .mockResolvedValueOnce({+ tasks: Array.from({ length: 200 }, (_, i) => historyTask(i + 20)),+ nextCursor,+ });+ agentTasksRef.current = query;+ renderTab();+ expect(await screen.findByText("10 latest runs")).toBeInTheDocument();+ fireEvent.click(screen.getByRole("button", { name: /Show more/ }));+ expect(screen.getByText("20 latest runs")).toBeInTheDocument();+ expect(query).toHaveBeenCalledTimes(1);+ fireEvent.click(screen.getByRole("button", { name: /Show more/ }));+ expect(await screen.findByText(subtitle)).toBeInTheDocument();+ if (nextCursor) {+ expect(screen.queryByText(/of 220 runs/)).not.toBeInTheDocument();+ }+ expect(screen.getAllByTestId(/^task-/)).toHaveLength(50);+ expect(query.mock.calls[1]?.[0]).toBe("older");+ });+});diff --git a/packages/views/agents/components/tabs/activity-tab.test.ts b/packages/views/agents/components/tabs/activity-tab.test.tsindex 822678e63e..9dbff61868 100644--- a/packages/views/agents/components/tabs/activity-tab.test.ts+++ b/packages/views/agents/components/tabs/activity-tab.test.ts@@ -1,89 +1,6 @@+// @vitest-environment nodeimport { describe, expect, it } from "vitest";-import type { AgentTask } from "@multica/core/types";-import {- deriveAvgDurationLast30d,- formatDurationMs,-} from "./activity-tab";--const NOW = new Date("2026-04-28T12:00:00Z").getTime();-const HOUR = 60 * 60 * 1000;-const DAY = 24 * HOUR;--function task(overrides: Partial<AgentTask>): AgentTask {- return {- id: "t",- agent_id: "a",- runtime_id: "r",- issue_id: "",- status: "completed",- priority: 0,- dispatched_at: null,- started_at: null,- completed_at: null,- result: null,- error: null,- created_at: new Date(NOW - HOUR).toISOString(),- ...overrides,- };-}--describe("deriveAvgDurationLast30d", () => {- it("returns 0 when no tasks have both started_at and completed_at", () => {- const tasks = [- task({ started_at: null, completed_at: new Date(NOW).toISOString() }),- task({- started_at: new Date(NOW - HOUR).toISOString(),- completed_at: null,- }),- ];- expect(deriveAvgDurationLast30d(tasks, NOW)).toBe(0);- });-- it("averages durations across in-window tasks", () => {- const tasks = [- task({- started_at: new Date(NOW - 60_000).toISOString(),- completed_at: new Date(NOW).toISOString(),- }), // 60s- task({- started_at: new Date(NOW - 180_000).toISOString(),- completed_at: new Date(NOW).toISOString(),- }), // 180s- ];- expect(deriveAvgDurationLast30d(tasks, NOW)).toBe(120_000);- });-- it("excludes tasks completed more than 30 days ago", () => {- const tasks = [- task({- started_at: new Date(NOW - 60_000).toISOString(),- completed_at: new Date(NOW).toISOString(),- }), // in window, 60s- task({- started_at: new Date(NOW - 60 * DAY - 60_000).toISOString(),- completed_at: new Date(NOW - 60 * DAY).toISOString(),- }), // 60d ago, ignored- ];- expect(deriveAvgDurationLast30d(tasks, NOW)).toBe(60_000);- });-- it("ignores non-positive durations defensively", () => {- const tasks = [- task({- // Wall-clock anomaly: completed before it started. The aggregation- // should still produce a sensible average from the well-formed rows- // rather than poisoning the count with a zero-or-negative entry.- started_at: new Date(NOW).toISOString(),- completed_at: new Date(NOW - 1000).toISOString(),- }),- task({- started_at: new Date(NOW - 4000).toISOString(),- completed_at: new Date(NOW).toISOString(),- }), // 4s- ];- expect(deriveAvgDurationLast30d(tasks, NOW)).toBe(4000);- });-});+import { formatDurationMs } from "./activity-tab";describe("formatDurationMs", () => {it("renders sub-minute durations in seconds", () => {diff --git a/packages/views/agents/components/tabs/activity-tab.tsx b/packages/views/agents/components/tabs/activity-tab.tsxindex b1d8847cab..cb8774de9c 100644--- a/packages/views/agents/components/tabs/activity-tab.tsx+++ b/packages/views/agents/components/tabs/activity-tab.tsx@@ -16,9 +16,10 @@ import {TooltipContent,TooltipTrigger,} from "@multica/ui/components/ui/tooltip";+import { Button } from "@multica/ui/components/ui/button";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 { useInfiniteQuery, useQueries, useQuery } from "@tanstack/react-query";import type { Agent, AgentTask, Issue } from "@multica/core/types";import {type AgentActivity,@@ -39,11 +40,7 @@ import { cancellationActorLabel, cancelReasonLabel, failureReasonLabel } from ".import { Sparkline } from "../sparkline";import { useT, useTimeAgo } from "../../../i18n";-const THIRTY_DAYS_MS = 30 * 24 * 60 * 60 * 1000;-// Recent work pagination: small initial cohort to keep the section-// scannable, then "Show more" reveals 20 at a time. Tasks are already-// fully cached client-side (one listAgentTasks for the whole agent), so-// "more" is a pure state flip — zero extra fetches.+// Reveal cached rows in small batches and fetch another page only on demand.const RECENT_INITIAL = 10;const RECENT_PAGE = 20;// Placeholder rows shown while the lazily-loaded per-agent task list is@@ -61,13 +58,11 @@ interface ActivityTabProps {* around the user's three diagnostic questions, in scan order:** Now — what's it doing right this second?- * Last 7 days — how has it been doing in aggregate?+ * Last 30 days — how has it been doing in aggregate?* Recent work — what did it just finish?*- * All three read from caches the rest of the page already fills (the- * workspace task snapshot for "Now", per-agent task list for "Recent",- * the workspace 7d activity buckets for the trend), so opening this tab- * adds no extra fetches once the page is hydrated.+ * "Now" and performance reuse workspace projections. Recent work loads+ * bounded history pages on demand; opening the tab never fetches all runs.*/export function ActivityTab({ agent, showPerformance = true }: ActivityTabProps) {const wsId = useWorkspaceId();@@ -76,9 +71,21 @@ export function ActivityTab({ agent, showPerformance = true }: ActivityTabProps)// `isLoading` (pending + fetching, no cached data) is true only on the// very first fetch. Once the page has hydrated this cache elsewhere the// tab opens straight into data with no skeleton flash.- const { data: agentTasks = [], isLoading: isLoadingRecent } = useQuery(- agentTasksOptions(wsId, agent.id),- );+ const {+ data,+ isLoading: isLoadingRecent,+ hasNextPage,+ fetchNextPage,+ isFetchingNextPage,+ isFetchNextPageError,+ } = useInfiniteQuery(agentTasksOptions(wsId, agent.id));+ const agentTasks = useMemo(() => {+ const tasks = new Map<string, AgentTask>();+ for (const page of data?.pages ?? []) {+ for (const task of page.tasks) tasks.set(task.id, task);+ }+ return [...tasks.values()];+ }, [data]);const { byAgent: activityMap } = useWorkspaceActivityMap(wsId);const activity = activityMap.get(agent.id);@@ -138,12 +145,9 @@ export function ActivityTab({ agent, showPerformance = true }: ActivityTabProps)() => recentTasksAll.slice(0, recentDisplayLimit),[recentTasksAll, recentDisplayLimit],);- const hasMoreRecent = recentTasksAll.length > recentTasks.length;+ const hasMoreRecent = recentTasksAll.length > recentTasks.length || hasNextPage;- const avgDurationMs = useMemo(- () => deriveAvgDurationLast30d(agentTasks, Date.now()),- [agentTasks],- );+ const avgDurationMs = activity?.avgDurationMs ?? 0;// Resolve issue identifiers + titles for any task we'll render. Going// through `issueDetailOptions` is the same lookup the rest of the app@@ -179,12 +183,22 @@ export function ActivityTab({ agent, showPerformance = true }: ActivityTabProps))}<RecentWorkSectiontasks={recentTasks}- totalCount={recentTasksAll.length}+ totalCount={hasNextPage ? undefined : recentTasksAll.length}hasMore={hasMoreRecent}loading={isLoadingRecent}- onShowMore={() =>- setRecentDisplayLimit((n) => n + RECENT_PAGE)- }+ fetchingMore={isFetchingNextPage}+ fetchMoreFailed={isFetchNextPageError}+ onShowMore={() => {+ if (recentDisplayLimit < recentTasksAll.length) {+ setRecentDisplayLimit((n) => n + RECENT_PAGE);+ } else if (hasNextPage && !isFetchingNextPage) {+ void fetchNextPage({ cancelRefetch: false }).then((result) => {+ if (!result.isFetchNextPageError) {+ setRecentDisplayLimit((n) => n + RECENT_PAGE);+ }+ });+ }+ }}issueMap={issueMap}agent={agent}/>@@ -197,16 +211,10 @@ export function ActivityTab({ agent, showPerformance = true }: ActivityTabProps)export function AgentPerformanceSummary({ agent }: { agent: Agent }) {const { t } = useT("agents");const wsId = useWorkspaceId();- const { data: agentTasks = [] } = useQuery(- agentTasksOptions(wsId, agent.id),- );const { byAgent: activityMap } = useWorkspaceActivityMap(wsId);const activity = activityMap.get(agent.id);const summary = summarizeActivityWindow(activity, 30);- const avgDurationMs = useMemo(- () => deriveAvgDurationLast30d(agentTasks, Date.now()),- [agentTasks],- );+ const avgDurationMs = activity?.avgDurationMs ?? 0;return (<section className="mt-5 border-t pt-5">@@ -422,14 +430,19 @@ function RecentWorkSection({hasMore,loading,onShowMore,+ fetchingMore,+ fetchMoreFailed,issueMap,agent,}: {tasks: AgentTask[];- totalCount: number;+ // Only known after the server has returned the final history page.+ totalCount?: number;hasMore: boolean;loading: boolean;onShowMore: () => void;+ fetchingMore: boolean;+ fetchMoreFailed: boolean;issueMap: Map<string, Issue>;agent: Agent;}) {@@ -439,8 +452,10 @@ function RecentWorkSection({const subtitle = loading? "": tasks.length === 0- ? t(($) => $.tab_body.activity.subtitle_no_recent)- : totalCount > tasks.length+ ? hasMore+ ? ""+ : t(($) => $.tab_body.activity.subtitle_no_recent)+ : totalCount !== undefined && totalCount > tasks.length? t(($) => $.tab_body.activity.subtitle_recent_progress, { shown: tasks.length, total: totalCount }): t(($) => $.tab_body.activity.subtitle_recent_latest, { count: tasks.length });return (@@ -448,25 +463,27 @@ function RecentWorkSection({{loading ? (<RecentWorkSkeleton />) : tasks.length === 0 ? (- <EmptyText>{t(($) => $.tab_body.activity.empty_recent)}</EmptyText>+ hasMore ? null : <EmptyText>{t(($) => $.tab_body.activity.empty_recent)}</EmptyText>) : (- <>- <TaskList- tasks={tasks}- issueMap={issueMap}- timeMode="completed"- agent={agent}- />- {hasMore && (- <button- type="button"- onClick={onShowMore}- className="mt-2 self-start rounded-xs text-caption text-muted-foreground transition-colors hover:text-foreground"- >- {t(($) => $.tab_body.activity.show_more)}- </button>- )}- </>+ <TaskList+ tasks={tasks}+ issueMap={issueMap}+ timeMode="completed"+ agent={agent}+ />+ )}+ {!loading && hasMore && (+ <Button+ type="button"+ variant="ghost"+ size="sm"+ onClick={onShowMore}+ disabled={fetchingMore}+ aria-busy={fetchingMore}+ className="self-start"+ >+ {fetchMoreFailed ? t(($) => $.detail.try_again) : t(($) => $.tab_body.activity.show_more)}+ </Button>)}</Section>);@@ -858,32 +875,6 @@ function activeTaskTimeText(task: AgentTask, t: AgentsT, timeAgo: TimeAgoFn): streturn t(($) => $.tab_body.activity.queued_prefix, { when: timeAgo(task.created_at) });}-/**- * Average wall-clock duration of completed/failed tasks whose completion- * lands in the last 30 days. Pure function so callers can pass a- * deterministic `now` in tests.- */-export function deriveAvgDurationLast30d(- tasks: readonly AgentTask[],- now: number,-): number {- let sum = 0;- let count = 0;- for (const t of tasks) {- if (!t.completed_at || !t.started_at) continue;- const completedAt = new Date(t.completed_at).getTime();- if (Number.isNaN(completedAt)) continue;- if (now - completedAt > THIRTY_DAYS_MS) continue;- const startedAt = new Date(t.started_at).getTime();- const dur = completedAt - startedAt;- if (Number.isFinite(dur) && dur > 0) {- sum += dur;- count += 1;- }- }- return count > 0 ? Math.round(sum / count) : 0;-}-/*** Compact human-readable duration ("12s", "2m 04s", "1h 30m"). Pads the* seconds inside the minute formatter so the column stays visuallydiff --git a/server/cmd/migrate/main.go b/server/cmd/migrate/main.goindex 1ce9147ead..28369826f2 100644--- a/server/cmd/migrate/main.go+++ b/server/cmd/migrate/main.go@@ -140,6 +140,7 @@ var pgBigmOperatorClass = extensionOperatorClass{// they are still pending: a fresh self-hosted install, which is exactly where an// interrupted build would otherwise leave a permanently unusable index.var concurrentIndexCleanups = map[string]string{+ "552_agent_task_history_page_index": "idx_agent_task_queue_history_page","535_github_pr_address_index": "idx_github_pull_request_pr_owner_repo","539_task_supplement_request_index": "task_supplement_task_request_uidx","540_task_supplement_capability_index": "task_supplement_capability_task_uidx",diff --git a/server/cmd/migrate/migrate_agent_task_history_index_test.go b/server/cmd/migrate/migrate_agent_task_history_index_test.gonew file mode 100644index 0000000000..5d5b258c2c--- /dev/null+++ b/server/cmd/migrate/migrate_agent_task_history_index_test.go@@ -0,0 +1,91 @@+package main++import (+ "context"+ "math/rand/v2"+ "os"+ "path/filepath"+ "strings"+ "testing"+ "time"+)++func TestAgentTaskHistoryIndexMigrationAndPagePlans(t *testing.T) {+ adminPool := openTestPool(t)+ ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)+ defer cancel()+ schema := createScratchSchema(t, ctx, adminPool, "migrate_agent_history_")+ pool := openTestPoolWithSearchPath(t, schema)+ for _, statement := range []string{+ `CREATE TABLE agent_task_queue (+ id UUID PRIMARY KEY, agent_id UUID NOT NULL, created_at TIMESTAMPTZ NOT NULL,+ status TEXT NOT NULL, escalation_for_task_id UUID, started_at TIMESTAMPTZ,+ result TEXT+ )`,+ `INSERT INTO agent_task_queue (id, agent_id, created_at, status, result)+ SELECT md5('task-' || n)::uuid, md5('agent')::uuid,+ '2026-09-01T00:00:00Z'::timestamptz + n * interval '1 second',+ 'completed', repeat('x', 128)+ FROM generate_series(1, 18165) AS n`,+ `ANALYZE agent_task_queue`,+ } {+ if _, err := pool.Exec(ctx, statement); err != nil {+ t.Fatalf("fixture: %v", err)+ }+ }+ // Explain the actual sqlc source query, so a future predicate or ordering+ // change must still be served by this index without sorting all history.+ source, err := os.ReadFile(filepath.Join("..", "..", "pkg", "db", "queries", "agent.sql"))+ if err != nil {+ t.Fatal(err)+ }+ _, history, ok := strings.Cut(string(source), "-- name: ListAgentTasks :many\n")+ if !ok {+ t.Fatal("ListAgentTasks query missing")+ }+ history, _, ok = strings.Cut(history, ";")+ if !ok {+ t.Fatal("ListAgentTasks query terminator missing")+ }++ const version = "552_agent_task_history_page_index"+ const indexName = "idx_agent_task_queue_history_page"+ options := runOptions{+ Direction: "up", Files: realMigrationFiles(t, []string{version}, "up"),+ SchemaMigrationsTable: schema + ".schema_migrations",+ AdvisoryLockKey: int64(rand.Uint64()&0x7fffffffffffffff) | 1,+ Hooks: hooksForDirection("up"),+ }+ if err := runMigrations(ctx, pool, options); err != nil {+ t.Fatal(err)+ }+ assertIndexValidity(t, pool, schema, indexName, true)+ for _, before := range []string{"'infinity'", "'2026-09-01T02:00:00Z'"} {+ query := strings.NewReplacer(+ "@agent_id", "md5('agent')::uuid",+ "@before_created_at", before,+ "@before_id", "'ffffffff-ffff-ffff-ffff-ffffffffffff'",+ "@page_limit", "201",+ ).Replace(history)+ plan := explainAnalyze(t, ctx, pool, query)+ if !strings.Contains(plan, indexName) || strings.Contains(plan, "Sort") {+ t.Fatalf("page before %s must use the history index without sorting:\n%s", before, plan)+ }+ t.Logf("page before %s:\n%s", before, plan)+ }+ options.Direction = "down"+ options.Files = realMigrationFiles(t, []string{version}, "down")+ options.Hooks = hooksForDirection("down")+ if err := runMigrations(ctx, pool, options); err != nil {+ t.Fatal(err)+ }+ assertIndexExists(t, pool, schema, indexName, false)+ assertMigrationVersionRecorded(t, ctx, pool, schema, version, false)+ options.Direction = "up"+ options.Files = realMigrationFiles(t, []string{version}, "up")+ options.Hooks = hooksForDirection("up")+ if err := runMigrations(ctx, pool, options); err != nil {+ t.Fatal(err)+ }+ assertIndexValidity(t, pool, schema, indexName, true)+}diff --git a/server/cmd/multica/cmd_agent.go b/server/cmd/multica/cmd_agent.goindex 51cd6d5a07..99c6a51477 100644--- a/server/cmd/multica/cmd_agent.go+++ b/server/cmd/multica/cmd_agent.go@@ -219,6 +219,8 @@ func init() {// agent tasksagentTasksCmd.Flags().String("output", "table", "Output format: table or json")+ agentTasksCmd.Flags().Int("limit", 200, "Maximum runs per page (1-200)")+ agentTasksCmd.Flags().String("before", "", "Cursor from the previous page")// agent avataragentAvatarCmd.Flags().String("file", "", "Path to the avatar image file (required)")@@ -883,18 +885,32 @@ func runAgentTasks(cmd *cobra.Command, args []string) error {}output, _ := cmd.Flags().GetString("output")- path := "/api/agents/" + args[0] + "/tasks"+ params := url.Values{}+ limit, _ := cmd.Flags().GetInt("limit")+ if limit < 1 {+ return fmt.Errorf("limit must be a positive integer")+ }+ params.Set("limit", fmt.Sprint(limit))+ before, _ := cmd.Flags().GetString("before")+ if before != "" {+ params.Set("before", before)+ }if output == "json" {- path += "?include_usage=true"+ params.Set("include_usage", "true")}+ path := "/api/agents/" + args[0] + "/tasks?" + params.Encode()ctx, cancel := cli.APIContext(context.Background())defer cancel()var tasks []map[string]any- if err := client.GetJSON(ctx, path, &tasks); err != nil {+ responseHeaders, err := client.GetJSONWithHeaders(ctx, path, &tasks)+ if err != nil {return fmt.Errorf("list agent runs: %w", err)}+ if cursor := responseHeaders.Get("X-Agent-Tasks-Next-Cursor"); cursor != "" {+ fmt.Fprintf(cmd.ErrOrStderr(), "More runs available; use --before %q to fetch the next page.\n", cursor)+ }if output == "json" {return cli.PrintJSON(os.Stdout, tasks)diff --git a/server/cmd/multica/cmd_agent_test.go b/server/cmd/multica/cmd_agent_test.goindex 716e0a5ca2..00647c3493 100644--- a/server/cmd/multica/cmd_agent_test.go+++ b/server/cmd/multica/cmd_agent_test.go@@ -36,6 +36,8 @@ func freshAgentEnvSetCmd() *cobra.Command {func newAgentTasksTestCmd() *cobra.Command {cmd := &cobra.Command{Use: "tasks"}cmd.Flags().String("output", "json", "")+ cmd.Flags().Int("limit", 200, "")+ cmd.Flags().String("before", "", "")cmd.Flags().String("profile", "", "")return cmd}@@ -71,6 +73,38 @@ func TestRunAgentTasksRequestsUsageForJSON(t *testing.T) {}}+func TestRunAgentTasksPagination(t *testing.T) {+ t.Chdir(t.TempDir())+ t.Setenv("MULTICA_AGENT_ID", "")+ t.Setenv("MULTICA_TASK_ID", "")+ cursor := "2026-09-24T01:02:03.123456Z|00000000-0000-0000-0000-000000000001"+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {+ if r.URL.Query().Get("limit") != "7" || r.URL.Query().Get("before") != cursor {+ t.Errorf("pagination query = %s", r.URL.RawQuery)+ }+ w.Header().Set("X-Agent-Tasks-Next-Cursor", cursor)+ _, _ = w.Write([]byte(`[{"id":"task-1"}]`))+ }))+ defer srv.Close()+ setCLITestServerEnv(t, srv.URL)+ cmd := newAgentTasksTestCmd()+ _ = cmd.Flags().Set("limit", "7")+ _ = cmd.Flags().Set("before", cursor)+ var stderr bytes.Buffer+ cmd.SetErr(&stderr)+ output, err := captureStdout(t, func() error { return runAgentTasks(cmd, []string{"agent-123"}) })+ if err != nil {+ t.Fatal(err)+ }+ if !strings.Contains(stderr.String(), "--before") || !strings.Contains(stderr.String(), cursor) {+ t.Fatalf("missing continuation: %s", stderr.String())+ }+ var rows []map[string]any+ if err := json.Unmarshal([]byte(output), &rows); err != nil {+ t.Fatalf("stdout must remain JSON: %s", output)+ }+}+func TestRunAgentTasksKeepsTableRequestLightweight(t *testing.T) {t.Chdir(t.TempDir())t.Setenv("MULTICA_AGENT_ID", "")diff --git a/server/cmd/server/cors_headers_test.go b/server/cmd/server/cors_headers_test.goindex 22e4676da4..ffcf07cd9e 100644--- a/server/cmd/server/cors_headers_test.go+++ b/server/cmd/server/cors_headers_test.go@@ -48,6 +48,7 @@ func TestRouterCORSContract(t *testing.T) {handler.HeaderCommentsTruncated,handler.HeaderTimelineTruncated,handler.HeaderActiveRunsTruncated,+ handler.HeaderAgentTasksNextCursor,} {if !headerListContains(rec.Header().Get("Access-Control-Expose-Headers"), want) {t.Errorf("Access-Control-Expose-Headers = %q, missing %q", rec.Header().Get("Access-Control-Expose-Headers"), want)diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 00ca29e45d..ed44405c8c 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -97,6 +97,7 @@ var corsExposedHeaders = []string{handler.HeaderCommentsTruncated,handler.HeaderTimelineTruncated,handler.HeaderActiveRunsTruncated,+ handler.HeaderAgentTasksNextCursor,}func registerPluginActionRoutes(r chi.Router, h *handler.Handler) {diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.goindex c6ed3013ec..36532d19c7 100644--- a/server/internal/handler/agent.go+++ b/server/internal/handler/agent.go@@ -11,6 +11,7 @@ import ("net/http""regexp""slices"+ "strconv""strings""time""unicode/utf8"@@ -777,6 +778,7 @@ type TaskAgentData struct {// Dispatch only begins preparation, so a fallback cancelled before StartTask// is still unused. Keep started fallbacks and ordinary cancellations visible,// and retain the underlying scheduling records for audit.+// Keep this predicate in sync with ListAgentTasks in pkg/db/queries/agent.sql.func visibleTaskHistory(tasks []db.AgentTaskQueue) []db.AgentTaskQueue {return slices.DeleteFunc(tasks, func(task db.AgentTaskQueue) bool {return task.EscalationForTaskID.Valid &&@@ -2667,6 +2669,13 @@ func (h *Handler) CancelAgentTasks(w http.ResponseWriter, r *http.Request) {writeJSON(w, http.StatusOK, cancelAgentTasksResponse{Cancelled: len(cancelled)})}+// HeaderAgentTasksNextCursor preserves the array response used by installed clients.+// An absent header means this is the last page.+const HeaderAgentTasksNextCursor = "X-Agent-Tasks-Next-Cursor"++const defaultAgentTasksLimit = 200+const maxAgentTasksLimit = 200+func (h *Handler) ListAgentTasks(w http.ResponseWriter, r *http.Request) {id := chi.URLParam(r, "id")agent, ok := h.loadAgentForUser(w, r, id)@@ -2692,13 +2701,41 @@ func (h *Handler) ListAgentTasks(w http.ResponseWriter, r *http.Request) {return}- tasks, err := h.Queries.ListAgentTasks(r.Context(), agent.ID)+ limit := defaultAgentTasksLimit+ if raw := r.URL.Query().Get("limit"); raw != "" {+ n, err := strconv.Atoi(raw)+ if err != nil || n < 1 {+ writeError(w, http.StatusBadRequest, "limit must be a positive integer")+ return+ }+ limit = min(n, maxAgentTasksLimit)+ }+ // An infinite upper bound gives both first and subsequent pages an indexed+ // tuple comparison, without an optional-cursor OR in the query plan.+ beforeCreatedAt := pgtype.Timestamptz{InfinityModifier: pgtype.Infinity, Valid: true}+ beforeID := agent.ID+ if raw := r.URL.Query().Get("before"); raw != "" {+ beforeCreatedAt, beforeID = parseTranscriptCursor(raw)+ if !beforeCreatedAt.Valid || !beforeID.Valid {+ writeError(w, http.StatusBadRequest, "invalid before cursor")+ return+ }+ }+ tasks, err := h.Queries.ListAgentTasks(r.Context(), db.ListAgentTasksParams{+ AgentID: agent.ID, BeforeCreatedAt: beforeCreatedAt, BeforeID: beforeID,+ PageLimit: int32(limit + 1),+ })if err != nil {writeError(w, http.StatusInternalServerError, "failed to list agent tasks")return}- tasks = visibleTaskHistory(tasks)+ nextCursor := ""+ if len(tasks) > limit {+ tasks = tasks[:limit]+ last := tasks[len(tasks)-1]+ nextCursor = transcriptCursor(last.CreatedAt.Time, last.ID)+ }resp := make([]AgentTaskResponse, len(tasks))var taskIDs []pgtype.UUIDif includeUsage {@@ -2720,18 +2757,23 @@ func (h *Handler) ListAgentTasks(w http.ResponseWriter, r *http.Request) {}}+ if nextCursor != "" {+ w.Header().Set(HeaderAgentTasksNextCursor, nextCursor)+ }writeJSON(w, http.StatusOK, resp)}// 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"`- CompletedCount int32 `json:"completed_count"`- CancelledCount int32 `json:"cancelled_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"`+ DurationMs float64 `json:"duration_ms"`+ DurationCount int32 `json:"duration_count"`}// AgentRunCount is the trailing-30-day total task run count per agent,@@ -2953,6 +2995,8 @@ func (h *Handler) GetWorkspaceAgentActivity30d(w http.ResponseWriter, r *http.ReFailedCount: row.FailedCount,CompletedCount: row.CompletedCount,CancelledCount: row.CancelledCount,+ DurationMs: row.DurationMs,+ DurationCount: row.DurationCount,})}diff --git a/server/internal/handler/agent_tasks_pagination_test.go b/server/internal/handler/agent_tasks_pagination_test.gonew file mode 100644index 0000000000..34e35e68ff--- /dev/null+++ b/server/internal/handler/agent_tasks_pagination_test.go@@ -0,0 +1,273 @@+package handler++import (+ "context"+ "fmt"+ "net/http"+ "net/url"+ "testing"+ "time"++ "github.com/multica-ai/multica/server/internal/testutil"+)++func TestListAgentTasksPagination(t *testing.T) {+ runtimeID := dbfx.Runtime(t, "paged history runtime")+ agentID := dbfx.Agent(t, "paged history agent", runtimeID)+ otherAgentID := dbfx.Agent(t, "other history agent", runtimeID)+ // Equal, sub-second timestamps exercise the tie breaker and lossless cursor.+ createdAt := time.Now().UTC().Add(-time.Hour).Truncate(time.Microsecond)+ visible := map[string]bool{}+ for i := 0; i < 205; i++ {+ id := dbfx.Task(t, agentID, testutil.Cols{"runtime_id": runtimeID, "status": "completed", "created_at": createdAt})+ visible[id] = true+ }+ var parentID string+ for id := range visible {+ parentID = id+ break+ }+ dbfx.Task(t, otherAgentID, testutil.Cols{"runtime_id": runtimeID, "status": "completed", "created_at": createdAt})+ // These sort ahead of the visible history. Filtering after LIMIT would+ // produce an empty/short page and incorrectly make older work inaccessible.+ for _, status := range []string{"cancelled", "deferred"} {+ dbfx.Task(t, agentID, testutil.Cols{"runtime_id": runtimeID, "status": status, "created_at": createdAt.Add(time.Second), "escalation_for_task_id": parentID})+ }+ startedFallback := dbfx.Task(t, agentID, testutil.Cols{"runtime_id": runtimeID, "status": "cancelled", "created_at": createdAt, "started_at": createdAt, "escalation_for_task_id": parentID})+ visible[startedFallback] = true++ readPage := func(query string, wantStatus int) ([]AgentTaskResponse, string) {+ t.Helper()+ req := withURLParam(newRequest(http.MethodGet, "/api/agents/"+agentID+"/tasks"+query, nil), "id", agentID)+ var tasks []AgentTaskResponse+ response := testutil.Call(t, testHandler.ListAgentTasks, req).Want(wantStatus)+ if wantStatus == http.StatusOK {+ response.JSON(&tasks)+ }+ return tasks, response.Header().Get(HeaderAgentTasksNextCursor)+ }+ for _, query := range []string{"", "?limit=999999"} {+ tasks, cursor := readPage(query, http.StatusOK)+ if len(tasks) != 200 || cursor == "" {+ t.Fatalf("%s: got %d tasks, cursor %q", query, len(tasks), cursor)+ }+ }+ for _, query := range []string{"?limit=0", "?limit=-1", "?limit=abc", "?limit=999999999999999999999", "?before=bad", "?before=2026-01-01T00:00:00Z%7Cbad"} {+ readPage(query, http.StatusBadRequest)+ }++ seen := map[string]bool{}+ cursor := ""+ var previous AgentTaskResponse+ for page := 0; page < 100; page++ {+ tasks, next := readPage("?limit=7&before="+url.QueryEscape(cursor), http.StatusOK)+ if len(tasks) > 7 {+ t.Fatal("page exceeded limit")+ }+ for _, task := range tasks {+ if !visible[task.ID] || seen[task.ID] {+ t.Fatalf("unexpected or repeated task %s", task.ID)+ }+ if previous.ID != "" && previous.ID <= task.ID {+ t.Fatalf("tied timestamps not ordered by descending id: %s then %s", previous.ID, task.ID)+ }+ seen[task.ID] = true+ previous = task+ }+ if page == 0 {+ // Newer work must not shift subsequent pages or repeat old rows.+ dbfx.Task(t, agentID, testutil.Cols{"runtime_id": runtimeID, "status": "completed", "created_at": createdAt.Add(time.Minute)})+ }+ if next == "" {+ break+ }+ if next == cursor {+ t.Fatal("cursor did not advance")+ }+ cursor = next+ }+ if len(seen) != len(visible) {+ t.Fatalf("read %d of %d visible tasks", len(seen), len(visible))+ }++ // A cursor remains usable if its boundary row is deleted between requests.+ tasks, cursor := readPage("?limit=1", http.StatusOK)+ if _, err := testPool.Exec(context.Background(), "DELETE FROM agent_task_queue WHERE id = $1", tasks[0].ID); err != nil {+ t.Fatal(err)+ }+ tasks, _ = readPage("?limit=1&before="+url.QueryEscape(cursor), http.StatusOK)+ if len(tasks) != 1 {+ t.Fatal("deleted boundary lost the rest of history")+ }++ emptyID := dbfx.Agent(t, "empty history agent", runtimeID)+ req := withURLParam(newRequest(http.MethodGet, fmt.Sprintf("/api/agents/%s/tasks", emptyID), nil), "id", emptyID)+ response := testutil.Call(t, testHandler.ListAgentTasks, req).Want(http.StatusOK)+ if response.Body.String() != "[]\n" {+ t.Fatalf("empty history = %s", response.Body.String())+ }+}++func TestAgentActivityDurationUsesAllRuns(t *testing.T) {+ runtimeID := dbfx.Runtime(t, "duration runtime")+ agentID := dbfx.Agent(t, "duration agent", runtimeID)+ now := time.Now().UTC().Truncate(time.Second)+ // More than one history page: duration must never be calculated from the+ // newest 200 rows or change when another page is opened.+ for i := 0; i < 201; i++ {+ duration := time.Minute+ if i == 0 {+ duration = 10 * time.Minute+ }+ dbfx.Task(t, agentID, testutil.Cols{"runtime_id": runtimeID, "status": "completed", "started_at": now.Add(-duration), "completed_at": now})+ }+ for _, cols := range []testutil.Cols{+ {"status": "completed", "started_at": now.Add(-32 * 24 * time.Hour), "completed_at": now.Add(-31 * 24 * time.Hour)},+ {"status": "cancelled", "completed_at": now},+ {"status": "failed", "started_at": now.Add(time.Second), "completed_at": now},+ {"status": "running", "started_at": now},+ } {+ cols["runtime_id"] = runtimeID+ dbfx.Task(t, agentID, cols)+ }+ req := withChatTestWorkspaceCtx(t, newRequest(http.MethodGet, "/api/agent-activity-30d", nil))+ var buckets []AgentActivityBucket+ testutil.Call(t, testHandler.GetWorkspaceAgentActivity30d, req).Want(http.StatusOK).JSON(&buckets)+ var count int32+ var duration float64+ for _, bucket := range buckets {+ if bucket.AgentID == agentID {+ count += bucket.DurationCount+ duration += bucket.DurationMs+ }+ }+ if count != 201 || duration != 210*60000 {+ t.Fatalf("duration/count = %v/%d, want %d/201", duration, count, 210*60000)+ }+}++func TestListAgentTasksPageBoundaries(t *testing.T) {+ runtimeID := dbfx.Runtime(t, "history boundaries runtime")+ for _, count := range []int{0, 1, 2, 3, 4, 6} {+ t.Run(fmt.Sprintf("%d_tasks_limit_3", count), func(t *testing.T) {+ agentID := dbfx.Agent(t, "history boundary agent", runtimeID)+ now := time.Now().UTC().Truncate(time.Microsecond)+ // Deliberately reverse UUID and time order: created_at must be the+ // primary sort key, not UUID order or insertion order.+ expected := make([]string, count)+ for i := 0; i < count; i++ {+ expected[i] = dbfx.Task(t, agentID, testutil.Cols{+ "id": fmt.Sprintf("00000000-0000-0000-0000-%012d", i+1),+ "runtime_id": runtimeID, "status": "completed",+ "created_at": now.Add(-time.Duration(i) * time.Microsecond),+ })+ }+ var got []string+ before := ""+ for page := 0; page < 3; page++ {+ req := withURLParam(newRequest(http.MethodGet, "/api/agents/"+agentID+"/tasks?limit=3&before="+url.QueryEscape(before), nil), "id", agentID)+ var tasks []AgentTaskResponse+ response := testutil.Call(t, testHandler.ListAgentTasks, req).Want(http.StatusOK).JSON(&tasks)+ for _, task := range tasks {+ got = append(got, task.ID)+ }+ before = response.Header().Get(HeaderAgentTasksNextCursor)+ wantMore := len(got) < count+ if (before != "") != wantMore {+ t.Fatalf("after %d/%d tasks: cursor=%q", len(got), count, before)+ }+ if !wantMore {+ break+ }+ }+ if len(got) != len(expected) {+ t.Fatalf("got %v, want %v", got, expected)+ }+ for i := range got {+ if got[i] != expected[i] {+ t.Fatalf("got %v, want timestamp order %v", got, expected)+ }+ }+ // A valid cursor older than every row is an empty, terminal page.+ before = transcriptCursor(now.Add(-time.Hour), parseUUID(agentID))+ req := withURLParam(newRequest(http.MethodGet, "/api/agents/"+agentID+"/tasks?before="+url.QueryEscape(before), nil), "id", agentID)+ response := testutil.Call(t, testHandler.ListAgentTasks, req).Want(http.StatusOK)+ if response.Body.String() != "[]\n" || response.Header().Get(HeaderAgentTasksNextCursor) != "" {+ t.Fatalf("past the end: %s, cursor=%q", response.Body.String(), response.Header().Get(HeaderAgentTasksNextCursor))+ }+ })+ }+}++func TestListAgentTasksCursorDoesNotGrantPrivateAccess(t *testing.T) {+ agentID, ownerID, memberID := privateAgentTestFixture(t)+ now := time.Now().UTC()+ for i := 0; i < 2; i++ {+ dbfx.Task(t, agentID, testutil.Cols{"status": "completed", "completed_at": now, "created_at": now.Add(-time.Duration(i) * time.Minute)})+ }+ var first []AgentTaskResponse+ req := withURLParam(newRequestAs(ownerID, http.MethodGet, "/api/agents/"+agentID+"/tasks?limit=1", nil), "id", agentID)+ response := testutil.Call(t, testHandler.ListAgentTasks, req).Want(http.StatusOK).JSON(&first)+ cursor := response.Header().Get(HeaderAgentTasksNextCursor)+ if len(first) != 1 || cursor == "" {+ t.Fatal("expected a first page and cursor")+ }+ for _, userID := range []string{memberID, ownerID} {+ status := http.StatusForbidden+ if userID == ownerID {+ status = http.StatusOK+ }+ req := withURLParam(newRequestAs(userID, http.MethodGet, "/api/agents/"+agentID+"/tasks?limit=1&include_usage=true&before="+url.QueryEscape(cursor), nil), "id", agentID)+ response := testutil.Call(t, testHandler.ListAgentTasks, req).Want(status)+ if userID == memberID && response.Header().Get(HeaderAgentTasksNextCursor) != "" {+ t.Fatal("forbidden response leaked a continuation")+ }+ if userID == ownerID {+ var second []AgentTaskResponse+ response.JSON(&second)+ if len(second) != 1 || second[0].ID == first[0].ID {+ t.Fatalf("bad owner continuation: %+v", second)+ }+ }+ }+}++func TestListAgentTasksUsageAndAgentScopeAcrossPages(t *testing.T) {+ runtimeID := dbfx.Runtime(t, "paged usage runtime")+ agentID := dbfx.Agent(t, "paged usage agent", runtimeID)+ otherID := dbfx.Agent(t, "other paged usage agent", runtimeID)+ now := time.Now().UTC()+ ids := make([]string, 3)+ for i := range ids {+ ids[i] = dbfx.Task(t, agentID, testutil.Cols{"runtime_id": runtimeID, "status": "completed", "created_at": now.Add(-time.Duration(i) * time.Minute)})+ dbfx.Insert(t, "task_usage", testutil.Cols{"task_id": ids[i], "provider": "openai", "model": "test-model", "input_tokens": i + 10})+ }+ otherTask := dbfx.Task(t, otherID, testutil.Cols{"runtime_id": runtimeID, "created_at": now.Add(-time.Minute)})+ dbfx.Insert(t, "task_usage", testutil.Cols{"task_id": otherTask, "provider": "openai", "model": "private-other-model", "input_tokens": 999})+ cursor := ""+ for i, id := range ids {+ req := withURLParam(newRequest(http.MethodGet, "/api/agents/"+agentID+"/tasks?limit=1&include_usage=true&before="+url.QueryEscape(cursor), nil), "id", agentID)+ var tasks []AgentTaskResponse+ response := testutil.Call(t, testHandler.ListAgentTasks, req).Want(http.StatusOK).JSON(&tasks)+ if len(tasks) != 1 || tasks[0].ID != id {+ t.Fatalf("page %d: %+v", i, tasks)+ }+ usage := tasks[0].Usage+ if len(usage) != 1 || usage[0].InputTokens != int64(i+10) || usage[0].Model != "test-model" {+ t.Fatalf("page %d usage: %+v", i, usage)+ }+ cursor = response.Header().Get(HeaderAgentTasksNextCursor)+ }+ if cursor != "" {+ t.Fatal("last usage page still has continuation")+ }+ // A cursor minted for a different agent is only a position, never a way+ // to read that agent's rows or its usage.+ cursor = transcriptCursor(now, parseUUID(ids[0]))+ req := withURLParam(newRequest(http.MethodGet, "/api/agents/"+otherID+"/tasks?limit=1&include_usage=true&before="+url.QueryEscape(cursor), nil), "id", otherID)+ var tasks []AgentTaskResponse+ testutil.Call(t, testHandler.ListAgentTasks, req).Want(http.StatusOK).JSON(&tasks)+ if len(tasks) != 1 || tasks[0].ID != otherTask || len(tasks[0].Usage) != 1 || tasks[0].Usage[0].Model != "private-other-model" {+ t.Fatalf("cross-agent cursor changed ownership scope: %+v", tasks)+ }+}diff --git a/server/migrations/552_agent_task_history_page_index.down.sql b/server/migrations/552_agent_task_history_page_index.down.sqlnew file mode 100644index 0000000000..b225d97de4--- /dev/null+++ b/server/migrations/552_agent_task_history_page_index.down.sql@@ -0,0 +1 @@+DROP INDEX CONCURRENTLY IF EXISTS idx_agent_task_queue_history_page;diff --git a/server/migrations/552_agent_task_history_page_index.up.sql b/server/migrations/552_agent_task_history_page_index.up.sqlnew file mode 100644index 0000000000..e9abf58675--- /dev/null+++ b/server/migrations/552_agent_task_history_page_index.up.sql@@ -0,0 +1,5 @@+-- Match ListAgentTasks visibility and keyset order for bounded history reads.+CREATE INDEX CONCURRENTLY IF NOT EXISTS idx_agent_task_queue_history_page+ON agent_task_queue (agent_id, created_at DESC, id DESC)+WHERE NOT (escalation_for_task_id IS NOT NULL AND started_at IS NULL+ AND status IN ('deferred', 'cancelled'));diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.goindex 09f5bc4122..56289d1ef7 100644--- a/server/pkg/db/generated/agent.sql.go+++ b/server/pkg/db/generated/agent.sql.go@@ -4675,7 +4675,10 @@ SELECTCOUNT(*)::int AS task_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_count+ COUNT(*) FILTER (WHERE atq.status = 'cancelled')::int AS cancelled_count,+ COALESCE(SUM(EXTRACT(EPOCH FROM (atq.completed_at - atq.started_at)) * 1000)+ FILTER (WHERE atq.completed_at > atq.started_at), 0)::float8 AS duration_ms,+ COUNT(*) FILTER (WHERE atq.completed_at > atq.started_at)::int AS duration_countFROM agent_task_queue atqJOIN agent a ON a.id = atq.agent_idWHERE a.workspace_id = $1@@ -4692,6 +4695,8 @@ type GetWorkspaceAgentActivity30dRow struct {FailedCount int32 `json:"failed_count"`CompletedCount int32 `json:"completed_count"`CancelledCount int32 `json:"cancelled_count"`+ DurationMs float64 `json:"duration_ms"`+ DurationCount int32 `json:"duration_count"`}// Returns per-agent daily activity buckets for the last 30 days. Single@@ -4726,6 +4731,8 @@ func (q *Queries) GetWorkspaceAgentActivity30d(ctx context.Context, workspaceID&i.FailedCount,&i.CompletedCount,&i.CancelledCount,+ &i.DurationMs,+ &i.DurationCount,); err != nil {return nil, err}@@ -5430,11 +5437,29 @@ func (q *Queries) ListActiveTasksByIssueFamily(ctx context.Context, arg ListActiconst listAgentTasks = `-- name: ListAgentTasks :manySELECT id, agent_id, issue_id, status, priority, dispatched_at, started_at, completed_at, result, error, created_at, context, runtime_id, session_id, work_dir, trigger_comment_id, chat_session_id, autopilot_run_id, attempt, max_attempts, parent_task_id, failure_reason, trigger_summary, force_fresh_session, is_leader_task, wait_reason, initiator_user_id, handoff_note, prepare_lease_expires_at, squad_id, runtime_mcp_overlay, escalation_for_task_id, fire_at, originator_user_id, runtime_connected_apps, coalesced_comment_ids, delivered_comment_ids, chat_input_task_id, chat_finalize_deferred_at, originator_source, delegated_from_task_id, retry_of_task_id, rerun_of_task_id, rule_version_id, trigger_evidence_kind, trigger_evidence_ref_id, accountable_user_id, session_rollout_missing, retired_session_id, quick_actions_disabled, regenerate_quick_actions_for, branch_name, durable_work_dir, channel_context_revision, comment_thread_id, cancelled_by_type, cancelled_by_id, cancelled_by_name, issue_snapshot FROM agent_task_queueWHERE agent_id = $1-ORDER BY created_at DESC+ -- Apply visibility before LIMIT so hidden fallbacks cannot end a page early.+ -- Keep this predicate in sync with handler.visibleTaskHistory.+ AND NOT (escalation_for_task_id IS NOT NULL AND started_at IS NULL+ AND status IN ('deferred', 'cancelled'))+ AND (created_at, id) < ($2::timestamptz, $3::uuid)+ORDER BY created_at DESC, id DESC+LIMIT $4`-func (q *Queries) ListAgentTasks(ctx context.Context, agentID pgtype.UUID) ([]AgentTaskQueue, error) {- rows, err := q.db.Query(ctx, listAgentTasks, agentID)+type ListAgentTasksParams struct {+ AgentID pgtype.UUID `json:"agent_id"`+ BeforeCreatedAt pgtype.Timestamptz `json:"before_created_at"`+ BeforeID pgtype.UUID `json:"before_id"`+ PageLimit int32 `json:"page_limit"`+}++func (q *Queries) ListAgentTasks(ctx context.Context, arg ListAgentTasksParams) ([]AgentTaskQueue, error) {+ rows, err := q.db.Query(ctx, listAgentTasks,+ arg.AgentID,+ arg.BeforeCreatedAt,+ arg.BeforeID,+ arg.PageLimit,+ )if err != nil {return nil, err}diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sqlindex a86d28439e..0af074b364 100644--- a/server/pkg/db/queries/agent.sql+++ b/server/pkg/db/queries/agent.sql@@ -287,8 +287,14 @@ RETURNING *;-- name: ListAgentTasks :manySELECT * FROM agent_task_queue-WHERE agent_id = $1-ORDER BY created_at DESC;+WHERE agent_id = @agent_id+ -- Apply visibility before LIMIT so hidden fallbacks cannot end a page early.+ -- Keep this predicate in sync with handler.visibleTaskHistory.+ AND NOT (escalation_for_task_id IS NOT NULL AND started_at IS NULL+ AND status IN ('deferred', 'cancelled'))+ AND (created_at, id) < (@before_created_at::timestamptz, @before_id::uuid)+ORDER BY created_at DESC, id DESC+LIMIT @page_limit;-- name: CreateAgentTask :one-- Fenced against workspace teardown: lock_task_owner_rows (migration 284)@@ -2603,7 +2609,10 @@ SELECTCOUNT(*)::int AS task_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_count+ COUNT(*) FILTER (WHERE atq.status = 'cancelled')::int AS cancelled_count,+ COALESCE(SUM(EXTRACT(EPOCH FROM (atq.completed_at - atq.started_at)) * 1000)+ FILTER (WHERE atq.completed_at > atq.started_at), 0)::float8 AS duration_ms,+ COUNT(*) FILTER (WHERE atq.completed_at > atq.started_at)::int AS duration_countFROM agent_task_queue atqJOIN agent a ON a.id = atq.agent_idWHERE a.workspace_id = $1