Skip to content

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

Go

fix(dashboard): stop leaking private agents from the per-agent rollups (MUL-5409) (#6051)

Bohan Jiang2e9a3d01193a
diff --git a/packages/views/dashboard/components/dashboard-page.test.tsx b/packages/views/dashboard/components/dashboard-page.test.tsx
index b5962478df..4ce28a5b59 100644
--- a/packages/views/dashboard/components/dashboard-page.test.tsx
+++ b/packages/views/dashboard/components/dashboard-page.test.tsx
@@ -1,4 +1,4 @@
-import { describe, it, expect, beforeEach, vi } from "vitest";
+import { describe, it, expect, afterEach, beforeEach, vi } from "vitest";
import { cleanup, screen, within } from "@testing-library/react";
import userEvent from "@testing-library/user-event";
import { renderWithI18n } from "../../test/i18n";
@@ -18,6 +18,39 @@ const dashboardDataRef = vi.hoisted(() => ({ current: false }));
// top-offenders and leaderboard caps. Kept off by default so the other tests
// keep their exact 4-of-10 arithmetic.
const manyAgentsRef = vi.hoisted(() => ({ current: false }));
+// Appends the server's `__restricted_agents__` bucket to the per-agent rollups
+// — what a plain member actually receives once the backend folds the agents
+// they may not view (MUL-5409).
+const restrictedBucketRef = vi.hoisted(() => ({ current: false }));
+
+// Kept out of the fixture ternary so the sentinel's shape reads at a glance.
+// Unlike the deleted-agents bucket this one carries real seconds / tasks: the
+// agents behind it are alive and ran.
+const RESTRICTED_BUCKET_ROWS = vi.hoisted(
+ () =>
+ ({
+ "by-agent": [
+ {
+ agent_id: "__restricted_agents__",
+ provider: "anthropic",
+ model: "claude-sonnet-4-6",
+ input_tokens: 500,
+ output_tokens: 500,
+ cache_read_tokens: 0,
+ cache_write_tokens: 0,
+ task_count: 4,
+ },
+ ],
+ "agent-runtime": [
+ {
+ agent_id: "__restricted_agents__",
+ total_seconds: 2 * 3_600,
+ task_count: 4,
+ failed_count: 2,
+ },
+ ],
+ }) as Record<string, unknown[]>,
+);
function todayIso() {
return new Date().toISOString().slice(0, 10);
@@ -158,7 +191,13 @@ vi.mock("@tanstack/react-query", async () => {
},
]
: [];
- return { data, isLoading: false, isSuccess: true };
+ return {
+ data: restrictedBucketRef.current
+ ? [...data, ...(RESTRICTED_BUCKET_ROWS[kind as string] ?? [])]
+ : data,
+ isLoading: false,
+ isSuccess: true,
+ };
}
return { data: undefined, isLoading: true };
},
@@ -526,6 +565,60 @@ describe("DashboardPage — Errors card placement and density", () => {
});
});
+// MUL-5409. The server folds every agent it won't name — those the viewer may
+// not see, plus the hidden system carriers behind agent-builder sessions — onto
+// one sentinel row. The leaderboard used to have a single synthetic row,
+// labelled "Deleted agents" with a bin icon and dashed-out Time/Tasks, so the
+// user was told "N agents were deleted" about agents that are alive and running.
+describe("DashboardPage — the leaderboard tells the truth about the server's bucket", () => {
+ beforeEach(() => {
+ queryKeys.length = 0;
+ dashboardDataRef.current = true;
+ manyAgentsRef.current = false;
+ restrictedBucketRef.current = true;
+ tzRef.current = "UTC";
+ cleanup();
+ });
+
+ afterEach(() => {
+ restrictedBucketRef.current = false;
+ });
+
+ it("labels the bucket neutrally, never as deleted", () => {
+ const { container } = renderDashboard();
+
+ const list = within(screen.getByRole("list", { name: "Leaderboard" }));
+ expect(list.getByText("Other agents")).toBeInTheDocument();
+ expect(list.queryByText("Deleted agents")).not.toBeInTheDocument();
+ // The sentinel is a placeholder, not an id to render.
+ expect(container).not.toHaveTextContent("__restricted_agents__");
+ });
+
+ it("counts it as neither an agent nor a deletion in the caption", () => {
+ const { container } = renderDashboard();
+
+ // One real agent in the fixture. The bucket is a row, not an agent, and
+ // nothing here was deleted — so no "· N deleted" suffix.
+ expect(container).toHaveTextContent("1 agents");
+ expect(container).not.toHaveTextContent("deleted");
+ });
+
+ it("keeps the bucket's run time and task count instead of dashing them out", () => {
+ // Those agents really ran; the server merely merged them. Blanking these
+ // columns (which is right for a hard-deleted agent) would under-report the
+ // workspace's run time against the Time / Tasks KPIs above.
+ renderDashboard();
+
+ const rows = within(
+ screen.getByRole("list", { name: "Leaderboard" }),
+ ).getAllByRole("listitem");
+ const bucket = rows.find((r) => r.textContent?.includes("Other agents"));
+ expect(bucket).toBeDefined();
+ expect(bucket).toHaveTextContent("2h");
+ expect(bucket).toHaveTextContent("4");
+ });
+});
+
describe("DashboardPage — leaderboard density", () => {
beforeEach(() => {
queryKeys.length = 0;
diff --git a/packages/views/dashboard/components/dashboard-page.tsx b/packages/views/dashboard/components/dashboard-page.tsx
index 526df82207..95db91f0c2 100644
--- a/packages/views/dashboard/components/dashboard-page.tsx
+++ b/packages/views/dashboard/components/dashboard-page.tsx
@@ -1,7 +1,7 @@
"use client";
import { useMemo, useState } from "react";
-import { BarChart3, FolderKanban, Trash2 } from "lucide-react";
+import { BarChart3, EyeOff, FolderKanban, Trash2 } from "lucide-react";
import { useQuery } from "@tanstack/react-query";
import { Skeleton } from "@multica/ui/components/ui/skeleton";
import {
@@ -80,9 +80,11 @@ import {
DELETED_AGENTS_ROW_ID,
formatDuration,
hasRateSample,
+ isSyntheticAgentRow,
mergeAgentDashboardRows,
MIN_RATE_SAMPLE,
OFFENDER_METRIC,
+ RESTRICTED_AGENTS_ROW_ID,
sortAgentFailures,
type AgentDashboardRow,
type AgentFailureRow,
@@ -481,11 +483,16 @@ export function DashboardPage() {
[agentRows, knownAgentIds],
);
// Distinct hard-deleted agents folded into the bucket — drives the caption's
- // "· N deleted" suffix (the bucket itself is a single row).
+ // "· N deleted" suffix (the bucket itself is a single row). The server's
+ // restricted bucket is not in `knownAgentIds` either but is not a deletion,
+ // so it must not inflate this count — that mislabelling is exactly the bug
+ // MUL-5409 came with.
const deletedAgentCount = useMemo(
() =>
knownAgentIds
- ? agentRows.filter((r) => !knownAgentIds.has(r.agentId)).length
+ ? agentRows.filter(
+ (r) => !knownAgentIds.has(r.agentId) && !isSyntheticAgentRow(r.agentId),
+ ).length
: 0,
[agentRows, knownAgentIds],
);
@@ -1350,6 +1357,14 @@ function Leaderboard({
? sortedRows
: sortedRows.slice(0, LEADERBOARD_LIMIT);
+ // "N agents" counts the rows that actually name an agent. Up to two of the
+ // rows are synthetic buckets (deleted, restricted), and subtracting a fixed 1
+ // reported one agent too many whenever both were present.
+ const namedAgentCount = useMemo(
+ () => rows.filter((r) => !isSyntheticAgentRow(r.agentId)).length,
+ [rows],
+ );
+
// Active column gets foreground text; others stay muted. Helps the user
// see "this is what the bar is measuring" at a glance.
const colClass = (key: LeaderboardSort) =>
@@ -1369,10 +1384,10 @@ function Leaderboard({
<span className="text-xs text-muted-foreground">
{deletedAgentCount > 0
? t(($) => $.leaderboard.caption_with_deleted, {
- count: rows.length - 1,
+ count: namedAgentCount,
deleted: deletedAgentCount,
})
- : t(($) => $.leaderboard.caption, { count: rows.length })}
+ : t(($) => $.leaderboard.caption, { count: namedAgentCount })}
</span>
{/* The caption right beside this already states how many agents the
window covers, so the toggle carries a count only when
@@ -1410,11 +1425,24 @@ function Leaderboard({
item boundaries rather than a bag of divs. */}
<ul aria-label={t(($) => $.leaderboard.title)} className="divide-y">
{visibleRows.map((row) => {
- // The deleted-agents bucket is a synthetic row, not a real agent:
- // render a neutral placeholder (no avatar fetch / hover card / UUID)
- // and dash out Time/Tasks, which it never carries (see
- // bucketUnknownAgentRows).
+ // Two synthetic rows, neither a real agent: both render a neutral
+ // placeholder (no avatar fetch / hover card / UUID) instead of
+ // looking the id up in the agent list.
+ //
+ // Only the deleted bucket dashes out Time/Tasks — it genuinely
+ // never carries them (see bucketUnknownAgentRows). The server's
+ // bucket does: those agents are alive and ran, the server just
+ // merged them (MUL-5409), so zeroing their columns would
+ // under-report the workspace's run time.
+ //
+ // Its copy is the neutral "Other agents" rather than anything
+ // about permissions, because it covers two populations: agents
+ // this viewer may not see, and the hidden system carriers behind
+ // agent-builder sessions, which nobody can name — including the
+ // admin who owns them.
const isDeletedBucket = row.agentId === DELETED_AGENTS_ROW_ID;
+ const isRestrictedBucket = row.agentId === RESTRICTED_AGENTS_ROW_ID;
+ const isBucket = isDeletedBucket || isRestrictedBucket;
const agent = agents.find((a) => a.id === row.agentId);
const value = SORT_METRIC[sortBy](row);
const pct = maxValue > 0 ? (value / maxValue) * 100 : 0;
@@ -1424,13 +1452,19 @@ function Leaderboard({
className="grid grid-cols-[minmax(0,1.6fr)_minmax(0,1fr)_5rem_5rem_5rem_4rem] items-center gap-3 px-4 py-2"
>
<div className="flex min-w-0 items-center gap-2">
- {isDeletedBucket ? (
+ {isBucket ? (
<>
<span className="flex h-[22px] w-[22px] shrink-0 items-center justify-center rounded-full bg-muted text-muted-foreground">
- <Trash2 className="h-3 w-3" />
+ {isDeletedBucket ? (
+ <Trash2 className="h-3 w-3" />
+ ) : (
+ <EyeOff className="h-3 w-3" />
+ )}
</span>
<span className="truncate text-sm font-medium italic text-muted-foreground">
- {t(($) => $.leaderboard.deleted_agents)}
+ {isDeletedBucket
+ ? t(($) => $.leaderboard.deleted_agents)
+ : t(($) => $.leaderboard.other_agents)}
</span>
</>
) : (
diff --git a/packages/views/dashboard/utils.test.ts b/packages/views/dashboard/utils.test.ts
index 34471b9591..7d7c02d58e 100644
--- a/packages/views/dashboard/utils.test.ts
+++ b/packages/views/dashboard/utils.test.ts
@@ -17,7 +17,9 @@ import {
DELETED_AGENTS_ROW_ID,
formatDuration,
hasRateSample,
+ isSyntheticAgentRow,
mergeAgentDashboardRows,
+ RESTRICTED_AGENTS_ROW_ID,
sortAgentFailures,
} from "./utils";
@@ -289,6 +291,40 @@ describe("bucketUnknownAgentRows", () => {
const out = bucketUnknownAgentRows([live, deletedA], null);
expect(out.map((r) => r.agentId)).toEqual(["live", "deleted-a"]);
});
+
+ // MUL-5409: the server folds agents the viewer may not see onto its own
+ // sentinel. That row is not in `knownAgentIds` either, and sweeping it into
+ // the "Deleted agents" bucket is exactly the lie the issue was filed for —
+ // those agents are alive.
+ it("keeps the server's restricted bucket out of the deleted bucket", () => {
+ const restricted = {
+ agentId: RESTRICTED_AGENTS_ROW_ID,
+ tokens: 70,
+ cost: 0.7,
+ seconds: 42,
+ taskCount: 3,
+ };
+ const out = bucketUnknownAgentRows(
+ [live, restricted, deletedA],
+ new Set(["live"]),
+ );
+ expect(out.map((r) => r.agentId)).toEqual([
+ "live",
+ RESTRICTED_AGENTS_ROW_ID,
+ DELETED_AGENTS_ROW_ID,
+ ]);
+ // It passes through whole: unlike a deleted agent it really ran, so its
+ // Time / Tasks columns carry real numbers.
+ expect(out.find((r) => r.agentId === RESTRICTED_AGENTS_ROW_ID)).toEqual(
+ restricted,
+ );
+ });
+
+ it("classifies both bucket ids as synthetic and real agents as not", () => {
+ expect(isSyntheticAgentRow(DELETED_AGENTS_ROW_ID)).toBe(true);
+ expect(isSyntheticAgentRow(RESTRICTED_AGENTS_ROW_ID)).toBe(true);
+ expect(isSyntheticAgentRow("live")).toBe(false);
+ });
});
describe("formatDuration", () => {
diff --git a/packages/views/dashboard/utils.ts b/packages/views/dashboard/utils.ts
index e585da3ec2..392c8677df 100644
--- a/packages/views/dashboard/utils.ts
+++ b/packages/views/dashboard/utils.ts
@@ -243,6 +243,17 @@ export function mergeAgentDashboardRows(
// placeholder instead of looking the id up in the agent list.
export const DELETED_AGENTS_ROW_ID = "__deleted_agents__";
+// Synthetic agentId the SERVER sends for the bucket aggregating every agent it
+// refuses to name (MUL-5409): agents the viewer may not see, plus the hidden
+// system carriers behind agent-builder sessions, which no client can resolve to
+// a name for anyone. Mirrors `restrictedAgentsRowID` in
+// server/internal/handler/dashboard.go — the two strings must stay in sync.
+//
+// Distinct from DELETED_AGENTS_ROW_ID on purpose: those agents are gone, these
+// are alive and still running. Labelling them "Deleted agents" told the user
+// something false, which is why the bucket renders as a neutral "Other agents".
+export const RESTRICTED_AGENTS_ROW_ID = "__restricted_agents__";
+
// Fold usage rows whose agent no longer exists in the workspace into a single
// aggregated "Deleted agents" row instead of dropping them. The agent list is
// fetched with `include_archived: true`, so archived agents keep their names
@@ -262,6 +273,11 @@ export const DELETED_AGENTS_ROW_ID = "__deleted_agents__";
// `knownAgentIds` is `null` while the agent list is still loading; callers
// pass `null` in that case so the rows pass through untouched instead of the
// whole leaderboard collapsing into one bucket on a slow fetch.
+//
+// The server's restricted bucket is NOT in `knownAgentIds` either (it is not an
+// agent), so it is passed through explicitly rather than swept into the deleted
+// bucket. It also keeps its seconds / taskCount: unlike a hard-deleted agent it
+// really did run, and the run-time rollup folds those numbers into it.
export function bucketUnknownAgentRows(
rows: AgentDashboardRow[],
knownAgentIds: ReadonlySet<string> | null,
@@ -277,7 +293,7 @@ export function bucketUnknownAgentRows(
};
let hasDeleted = false;
for (const r of rows) {
- if (knownAgentIds.has(r.agentId)) {
+ if (knownAgentIds.has(r.agentId) || r.agentId === RESTRICTED_AGENTS_ROW_ID) {
known.push(r);
continue;
}
@@ -288,6 +304,13 @@ export function bucketUnknownAgentRows(
return hasDeleted ? [...known, bucket] : known;
}
+// Rows the leaderboard renders as a synthetic bucket rather than an agent.
+// `deletedAgentCount` and the caption's agent count both have to exclude these,
+// or the card claims more agents (or more deletions) than it is showing.
+export function isSyntheticAgentRow(agentId: string): boolean {
+ return agentId === DELETED_AGENTS_ROW_ID || agentId === RESTRICTED_AGENTS_ROW_ID;
+}
+
// ---------------------------------------------------------------------------
// Weekly fold for run-time + tasks. Mirrors `aggregateByWeek` in
// `runtimes/utils.ts` which already covers cost / tokens — same calendar
@@ -594,13 +617,10 @@ export function aggregateFailureReasons(
// Synthetic agentId for the row aggregating every agent the viewer can't
// resolve to a name. Distinct from DELETED_AGENTS_ROW_ID because this bucket
-// covers two populations at once: hard-deleted agents, and agents that are
-// private to someone else. The failure rollups are workspace-scoped and do
-// NOT apply per-agent visibility (see the access-control note on
-// server/internal/handler/dashboard.go), while the agent list the client
-// joins against DOES — members only see a private agent when they own it or
-// are workspace owner/admin. Naming the bucket after deletion would be a lie
-// for the second group.
+// covers two populations at once: hard-deleted agents, and the server's
+// already-anonymized restricted bucket. Naming it after deletion would be a
+// lie for the second group, so the Errors card labels it neutrally
+// ("Other agents"), which is honest for both.
export const UNRESOLVED_AGENTS_ROW_ID = "__unresolved_agents__";
export interface AgentFailureRow {
@@ -703,12 +723,13 @@ export function sortAgentFailures(
// Fold rows whose agent the viewer cannot resolve into one aggregated bucket
// so the Errors list never renders a bare agent UUID.
//
-// This is a privacy boundary, not just a cosmetic one. The failure rollups
-// return every agent in the workspace — deliberately, since failure volume is
-// a workspace-level operational metric — but the agent list is filtered by
-// per-agent visibility. Rendering `agentId` for the difference would tell a
-// member that a private agent exists, how often it runs, how often it fails,
-// and what it fails on.
+// The privacy boundary itself now lives on the server: GetDashboardFailuresByAgent
+// folds agents the caller may not view onto RESTRICTED_AGENTS_ROW_ID before
+// serializing (MUL-5409), because client-side filtering is decoration — one
+// curl bypasses it. This function stays as the display-side backstop: it still
+// owns hard-deleted agents, whose ids the server has no reason to hide but
+// which resolve to no name, and it re-anonymizes the server's bucket into the
+// same neutral row so the card has one "not an agent you can open" case.
//
// `knownAgentIds` is null while the agent list is still loading. Unlike
// `bucketUnknownAgentRows`, which passes rows through in that window, this
diff --git a/packages/views/locales/en/usage.json b/packages/views/locales/en/usage.json
index b0fe1daec4..e2a5e6363f 100644
--- a/packages/views/locales/en/usage.json
+++ b/packages/views/locales/en/usage.json
@@ -80,6 +80,7 @@
"caption_with_deleted": "{{count}} agents · {{deleted}} deleted",
"sort_label": "Rank agents by",
"deleted_agents": "Deleted agents",
+ "other_agents": "Other agents",
"header_agent": "Agent",
"header_tokens": "Tokens",
"header_cost": "Cost",
diff --git a/packages/views/locales/ja/usage.json b/packages/views/locales/ja/usage.json
index 6277d33959..b1aaa3792c 100644
--- a/packages/views/locales/ja/usage.json
+++ b/packages/views/locales/ja/usage.json
@@ -80,6 +80,7 @@
"caption_with_deleted": "{{count}} 件のエージェント · 削除済み {{deleted}} 件",
"sort_label": "エージェントの並び順",
"deleted_agents": "削除済みエージェント",
+ "other_agents": "その他のエージェント",
"header_agent": "エージェント",
"header_tokens": "トークン",
"header_cost": "コスト",
diff --git a/packages/views/locales/ko/usage.json b/packages/views/locales/ko/usage.json
index 4c4b4e4bf1..0edc30f44e 100644
--- a/packages/views/locales/ko/usage.json
+++ b/packages/views/locales/ko/usage.json
@@ -80,6 +80,7 @@
"caption_with_deleted": "에이전트 {{count}}개 · 삭제됨 {{deleted}}개",
"sort_label": "에이전트 순위 기준",
"deleted_agents": "삭제된 에이전트",
+ "other_agents": "기타 에이전트",
"header_agent": "에이전트",
"header_tokens": "토큰",
"header_cost": "비용",
diff --git a/packages/views/locales/zh-Hans/usage.json b/packages/views/locales/zh-Hans/usage.json
index a8da72ffec..65b1fea294 100644
--- a/packages/views/locales/zh-Hans/usage.json
+++ b/packages/views/locales/zh-Hans/usage.json
@@ -80,6 +80,7 @@
"caption_with_deleted": "{{count}} 个智能体 · {{deleted}} 个已删除",
"sort_label": "智能体排序依据",
"deleted_agents": "已删除的智能体",
+ "other_agents": "其他智能体",
"header_agent": "智能体",
"header_tokens": "Token",
"header_cost": "费用",
diff --git a/server/internal/handler/agent_access.go b/server/internal/handler/agent_access.go
index fd1706834e..de18f45443 100644
--- a/server/internal/handler/agent_access.go
+++ b/server/internal/handler/agent_access.go
@@ -362,6 +362,65 @@ func (h *Handler) accessibleAgentIDs(ctx context.Context, workspaceID, actorType
return allowed, true
}
+// restrictedAgentIDs returns the ids of agents that EXIST in the workspace but
+// must not be named to this actor. Aggregation endpoints that cannot simply drop
+// a row (the dashboard rollups, whose per-agent totals have to keep reconciling
+// with the workspace-level series rendered beside them) use it to fold those
+// agents onto a single sentinel instead.
+//
+// Two populations land in the set, for two different reasons:
+//
+// 1. Every `kind != "user"` agent — the hidden execution carriers behind agent
+// builder sessions. These are restricted for EVERYONE, owner and admin
+// included: no list endpoint returns them (ListAgents / ListAllAgents filter
+// on kind), so no client can ever resolve one to a name, yet they run real
+// tasks and book real usage that the rollups aggregate all the same. Left
+// alone they surface as a bare UUID whose spend and failure profile belong
+// to whoever opened that builder session.
+// 2. For a plain member only, the user agents they may not view.
+//
+// Hard-deleted agents are deliberately NOT in the set: they are already absent
+// from the agent table, have no visibility left to protect, and the dashboard
+// renders them as their own "deleted agents" bucket — folding them in here
+// would relabel a real deletion as a permission boundary.
+//
+// Because of (1) this always reads the agent table, but the per-agent
+// invocation-target lookup is skipped for actors who see every user agent
+// (agent actors, workspace owner/admin) since nothing there can change their
+// answer.
+func (h *Handler) restrictedAgentIDs(ctx context.Context, workspaceID, actorType, actorID, role string) (map[string]struct{}, bool) {
+ wsUUID, err := util.ParseUUID(workspaceID)
+ if err != nil {
+ return nil, false
+ }
+ agents, err := h.Queries.ListAllAgentsAnyKind(ctx, wsUUID)
+ if err != nil {
+ return nil, false
+ }
+
+ // Whether per-agent visibility can restrict anything for this actor at all.
+ judgeUserAgents := actorType == "member" && !roleAllowed(role, "owner", "admin")
+ var targetsByAgent map[string][]db.AgentInvocationTarget
+ if judgeUserAgents {
+ var ok bool
+ if targetsByAgent, ok = h.loadInvocationTargetsByAgent(ctx, agents); !ok {
+ return nil, false
+ }
+ }
+
+ restricted := make(map[string]struct{})
+ for _, a := range agents {
+ if a.Kind == "user" {
+ if !judgeUserAgents ||
+ memberAllowedToViewAgent(a, targetsByAgent[uuidToString(a.ID)], actorID, role) {
+ continue
+ }
+ }
+ restricted[uuidToString(a.ID)] = struct{}{}
+ }
+ return restricted, true
+}
+
// loadInvocationTargetsByAgent batch-loads invocation targets for a set of
// agents and buckets them by agent id string. Avoids the per-agent query the
// list / aggregation paths would otherwise incur.
diff --git a/server/internal/handler/dashboard.go b/server/internal/handler/dashboard.go
index fe063c14a9..05f45c11e4 100644
--- a/server/internal/handler/dashboard.go
+++ b/server/internal/handler/dashboard.go
@@ -29,12 +29,97 @@ import (
// dimension is intentionally preserved on the wire (same convention as the
// per-runtime usage endpoints).
//
-// Access control: workspace membership only — we don't filter by per-agent
-// visibility on the dashboard because token spend / run time are workspace-
-// level operational metrics. Agent-detail pages still gate on per-agent
-// access (see GetWorkspaceAgentRunCounts).
+// Access control: the workspace-wide series (usage/daily, runtime/daily,
+// failures/daily) carry no agent dimension and need workspace membership only —
+// token spend / run time / failure volume are workspace-level operational
+// metrics. The three per-AGENT rollups additionally apply per-agent visibility:
+// see foldRestrictedAgents.
// ---------------------------------------------------------------------------
+// restrictedAgentsRowID is the synthetic agent_id that every row this response
+// refuses to name is folded onto. Deliberately not a UUID, so it can never
+// collide with a real agent id, and distinct from the client's "deleted agents"
+// bucket: those agents are gone, these are alive and still running.
+const restrictedAgentsRowID = "__restricted_agents__"
+
+// foldRestrictedAgents rewrites every row named by `restricted` (see
+// restrictedAgentIDs) onto restrictedAgentsRowID, merging the rewritten rows
+// that then collide on whatever dimensions the row has left (provider+model,
+// failure_reason, or nothing at all).
+//
+// "Private" is a promise the rest of the codebase keeps — agent detail 403s,
+// ListAgents filters, even an admin cannot invoke someone else's private agent.
+// These three endpoints used to break it by returning bare agent UUIDs for the
+// whole workspace, which told a plain member that a private agent exists, how
+// much it runs, and what it fails on. The client already collapsed those rows,
+// but client-side filtering is decoration: one curl bypasses it.
+//
+// The same fold covers the hidden `kind = 'system'` builder carriers, which no
+// list endpoint returns to anyone: aggregating over agent_task_queue /
+// task_usage picks them up regardless of kind, so without this they arrive as a
+// bare UUID no client can name.
+//
+// Folding rather than dropping: each of these responses is the per-agent half
+// of a pair whose other half (usage/daily, runtime/daily, failures/daily) is
+// workspace-scoped and unfiltered, so dropping rows would make the per-agent
+// breakdown stop adding up to the totals rendered directly beside it. One
+// merged bucket keeps every sum intact while carrying no real agent id and no
+// per-agent split.
+//
+// The retained dimensions leak nothing new: the workspace-level series already
+// exposes each (provider, model) / failure_reason total for the whole
+// workspace, and every visible agent's rows are returned in full, so the
+// restricted remainder was always one subtraction away.
+//
+// `rewrite` stamps the sentinel id and returns the merge key for what remains;
+// `merge` accumulates a later row onto the one already emitted. Row order is
+// otherwise preserved, with the bucket sitting where its first member was — the
+// client re-ranks all of these anyway.
+func foldRestrictedAgents[T any, K comparable](
+ rows []T,
+ restricted map[string]struct{},
+ agentIDOf func(T) string,
+ rewrite func(T) (T, K),
+ merge func(dst, src T) T,
+) []T {
+ if len(restricted) == 0 {
+ return rows
+ }
+ out := make([]T, 0, len(rows))
+ bucketAt := make(map[K]int)
+ for _, row := range rows {
+ if _, hidden := restricted[agentIDOf(row)]; !hidden {
+ out = append(out, row)
+ continue
+ }
+ folded, key := rewrite(row)
+ if i, ok := bucketAt[key]; ok {
+ out[i] = merge(out[i], folded)
+ continue
+ }
+ bucketAt[key] = len(out)
+ out = append(out, folded)
+ }
+ return out
+}
+
+// dashboardRestrictedAgents resolves the agents this request may not see. On
+// failure it writes a 500 and returns ok=false: an unfiltered rollup is the one
+// outcome this must never degrade to.
+func (h *Handler) dashboardRestrictedAgents(
+ w http.ResponseWriter,
+ r *http.Request,
+ workspaceID, role string,
+) (map[string]struct{}, bool) {
+ actorType, actorID := h.resolveActor(r, requestUserID(r), workspaceID)
+ restricted, ok := h.restrictedAgentIDs(r.Context(), workspaceID, actorType, actorID, role)
+ if !ok {
+ writeError(w, http.StatusInternalServerError, "failed to resolve agent access")
+ return nil, false
+ }
+ return restricted, true
+}
+
// parseProjectIDParam reads ?project_id=<uuid> off the URL. Returns a
// pgtype.UUID with Valid=false when the param is absent so sqlc's nullable
// argument resolves to SQL NULL and the WHERE clause degrades to "no
@@ -167,13 +252,18 @@ type DashboardUsageByAgentResponse struct {
// task_usage_hourly with the viewer's tz applied to the `?days=` cutoff.
func (h *Handler) GetDashboardUsageByAgent(w http.ResponseWriter, r *http.Request) {
workspaceID := h.resolveWorkspaceID(r)
- if _, ok := h.workspaceMember(w, r, workspaceID); !ok {
+ member, ok := h.workspaceMember(w, r, workspaceID)
+ if !ok {
return
}
projectID, ok := parseProjectIDParam(w, r)
if !ok {
return
}
+ restricted, ok := h.dashboardRestrictedAgents(w, r, workspaceID, member.Role)
+ if !ok {
+ return
+ }
// "By agent" has no date grouping in the SQL — tz only determines
// the cutoff boundary, not the bucket axis.
tz := h.resolveViewingTZ(r)
@@ -184,7 +274,42 @@ func (h *Handler) GetDashboardUsageByAgent(w http.ResponseWriter, r *http.Reques
writeError(w, http.StatusInternalServerError, "failed to list usage by agent")
return
}
- writeJSON(w, http.StatusOK, resp)
+ writeJSON(w, http.StatusOK, foldRestrictedUsageByAgent(resp, restricted))
+}
+
+// providerModelKey keeps the restricted bucket split by (provider, model) so
+// the client can still price it from its per-model table — without that the
+// bucket's cost is uncomputable and the leaderboard stops summing to the Cost
+// KPI, which is the whole reason these rows are folded rather than dropped.
+type providerModelKey struct{ provider, model string }
+
+func foldRestrictedUsageByAgent(
+ rows []DashboardUsageByAgentResponse,
+ restricted map[string]struct{},
+) []DashboardUsageByAgentResponse {
+ return foldRestrictedAgents(
+ rows,
+ restricted,
+ func(row DashboardUsageByAgentResponse) string { return row.AgentID },
+ func(row DashboardUsageByAgentResponse) (DashboardUsageByAgentResponse, providerModelKey) {
+ key := providerModelKey{provider: row.Provider, model: row.Model}
+ row.AgentID = restrictedAgentsRowID
+ return row, key
+ },
+ func(dst, src DashboardUsageByAgentResponse) DashboardUsageByAgentResponse {
+ dst.InputTokens += src.InputTokens
+ dst.OutputTokens += src.OutputTokens
+ dst.CacheReadTokens += src.CacheReadTokens
+ dst.CacheWriteTokens += src.CacheWriteTokens
+ dst.CostUSDTicks += src.CostUSDTicks
+ dst.UncostedInputTokens += src.UncostedInputTokens
+ dst.UncostedOutputTokens += src.UncostedOutputTokens
+ dst.UncostedCacheReadTokens += src.UncostedCacheReadTokens
+ dst.UncostedCacheWriteTokens += src.UncostedCacheWriteTokens
+ dst.TaskCount += src.TaskCount
+ return dst
+ },
+ )
}
func (h *Handler) listDashboardUsageByAgent(
@@ -239,13 +364,18 @@ type DashboardAgentRunTimeResponse struct {
// finite duration.
func (h *Handler) GetDashboardAgentRunTime(w http.ResponseWriter, r *http.Request) {
workspaceID := h.resolveWorkspaceID(r)
- if _, ok := h.workspaceMember(w, r, workspaceID); !ok {
+ member, ok := h.workspaceMember(w, r, workspaceID)
+ if !ok {
return
}
projectID, ok := parseProjectIDParam(w, r)
if !ok {
return
}
+ restricted, ok := h.dashboardRestrictedAgents(w, r, workspaceID, member.Role)
+ if !ok {
+ return
+ }
// Cutoff in the viewer's tz so the "last N days" window matches the
// per-agent cost card (GetDashboardUsageByAgent).
tz := h.resolveViewingTZ(r)
@@ -270,7 +400,30 @@ func (h *Handler) GetDashboardAgentRunTime(w http.ResponseWriter, r *http.Reques
FailedCount: row.FailedCount,
}
}
- writeJSON(w, http.StatusOK, resp)
+ writeJSON(w, http.StatusOK, foldRestrictedAgentRunTime(resp, restricted))
+}
+
+// The run-time row carries no dimension besides the agent, so every restricted
+// row merges into a single bucket — hence the empty merge key.
+func foldRestrictedAgentRunTime(
+ rows []DashboardAgentRunTimeResponse,
+ restricted map[string]struct{},
+) []DashboardAgentRunTimeResponse {
+ return foldRestrictedAgents(
+ rows,
+ restricted,
+ func(row DashboardAgentRunTimeResponse) string { return row.AgentID },
+ func(row DashboardAgentRunTimeResponse) (DashboardAgentRunTimeResponse, struct{}) {
+ row.AgentID = restrictedAgentsRowID
+ return row, struct{}{}
+ },
+ func(dst, src DashboardAgentRunTimeResponse) DashboardAgentRunTimeResponse {
+ dst.TotalSeconds += src.TotalSeconds
+ dst.TaskCount += src.TaskCount
+ dst.FailedCount += src.FailedCount
+ return dst
+ },
+ )
}
// DashboardRunTimeDailyResponse is one (date) bucket of terminal-task run
@@ -403,13 +556,18 @@ type DashboardFailureByAgentResponse struct {
// Powers the Usage page's "top offenders" list.
func (h *Handler) GetDashboardFailuresByAgent(w http.ResponseWriter, r *http.Request) {
workspaceID := h.resolveWorkspaceID(r)
- if _, ok := h.workspaceMember(w, r, workspaceID); !ok {
+ member, ok := h.workspaceMember(w, r, workspaceID)
+ if !ok {
return
}
projectID, ok := parseProjectIDParam(w, r)
if !ok {
return
}
+ restricted, ok := h.dashboardRestrictedAgents(w, r, workspaceID, member.Role)
+ if !ok {
+ return
+ }
// No date grouping in the SQL, so the client cannot trim this response the
// way it trims the date-bucketed series. Close the window server-side to
// exactly `days` calendar buckets — the same span the Errors chart renders
@@ -437,5 +595,30 @@ func (h *Handler) GetDashboardFailuresByAgent(w http.ResponseWriter, r *http.Req
TaskCount: row.TaskCount,
}
}
- writeJSON(w, http.StatusOK, resp)
+ writeJSON(w, http.StatusOK, foldRestrictedFailuresByAgent(resp, restricted))
+}
+
+// The restricted bucket keeps its failure_reason split: the client derives the
+// bucket's failure rate and class mix from these raw rows exactly like any
+// other agent's, and the succeeded rows (failure_reason == "") are the
+// denominator that keeps the offender list reconciling with the workspace
+// failure total above it.
+func foldRestrictedFailuresByAgent(
+ rows []DashboardFailureByAgentResponse,
+ restricted map[string]struct{},
+) []DashboardFailureByAgentResponse {
+ return foldRestrictedAgents(
+ rows,
+ restricted,
+ func(row DashboardFailureByAgentResponse) string { return row.AgentID },
+ func(row DashboardFailureByAgentResponse) (DashboardFailureByAgentResponse, string) {
+ reason := row.FailureReason
+ row.AgentID = restrictedAgentsRowID
+ return row, reason
+ },
+ func(dst, src DashboardFailureByAgentResponse) DashboardFailureByAgentResponse {
+ dst.TaskCount += src.TaskCount
+ return dst
+ },
+ )
}
diff --git a/server/internal/handler/dashboard_agent_visibility_test.go b/server/internal/handler/dashboard_agent_visibility_test.go
new file mode 100644
index 0000000000..404ecbf4d5
--- /dev/null
+++ b/server/internal/handler/dashboard_agent_visibility_test.go
@@ -0,0 +1,523 @@
+package handler
+
+import (
+ "context"
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+)
+
+// dashboardAgentPresence is the expected membership of the three agent ids that
+// matter in a per-agent dashboard response.
+type dashboardAgentPresence struct {
+ privateAgent bool
+ publicAgent bool
+ sentinel bool
+}
+
+// TestDashboardPerAgentRollupsFoldRestrictedAgents is the regression guard for
+// MUL-5409: the three per-agent dashboard rollups used to authorize on
+// workspace membership alone and return a bare agent_id for EVERY agent in the
+// workspace, telling a plain member that someone else's private agent exists,
+// how much it spends, how long it runs, and what it fails on.
+//
+// The contract now: rows for agents the caller may not view are folded onto the
+// `__restricted_agents__` sentinel — never dropped — so
+//
+// - no private agent's UUID appears in a plain member's response, and
+// - every aggregate still sums to exactly what the privileged view sums to,
+// which is what keeps the per-agent breakdown reconciling with the
+// workspace-level KPIs rendered beside it.
+//
+// A public_to agent is seeded alongside the private one so the test also proves
+// the fold is selective rather than "the member sees nothing".
+func TestDashboardPerAgentRollupsFoldRestrictedAgents(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ privateAgentID, _, memberID := privateAgentTestFixture(t)
+ runtimeID := handlerTestRuntimeID(t)
+
+ // Second agent, public_to the whole workspace: the plain member CAN see
+ // this one, so its rows must survive with their real UUID.
+ var publicAgentID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent (
+ workspace_id, name, description, runtime_mode, runtime_config,
+ runtime_id, visibility, permission_mode, max_concurrent_tasks, owner_id,
+ instructions, custom_env, custom_args
+ )
+ VALUES ($1, 'dashboard-visibility-public-agent', '', 'cloud', '{}'::jsonb,
+ $2, 'workspace', 'public_to', 1, $3, '', '{}'::jsonb, '[]'::jsonb)
+ RETURNING id
+ `, testWorkspaceID, runtimeID, testUserID).Scan(&publicAgentID); err != nil {
+ t.Fatalf("create public agent: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM agent WHERE id = $1`, publicAgentID)
+ })
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO agent_invocation_target (agent_id, target_type, target_id)
+ VALUES ($1, 'workspace', $2)
+ `, publicAgentID, testWorkspaceID); err != nil {
+ t.Fatalf("grant workspace invocation target: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(),
+ `DELETE FROM agent_invocation_target WHERE agent_id = $1`, publicAgentID)
+ })
+
+ var issueID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO issue (workspace_id, title, creator_id, creator_type, number)
+ VALUES ($1, 'dashboard agent visibility', $2, 'member',
+ (SELECT COALESCE(MAX(number), 0) + 1 FROM issue WHERE workspace_id = $1))
+ RETURNING id
+ `, testWorkspaceID, testUserID).Scan(&issueID); err != nil {
+ t.Fatalf("create issue: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID) })
+
+ started := time.Now().UTC().Add(-30 * time.Minute)
+ completed := started.Add(10 * time.Minute) // 600s run
+
+ // One completed + one failed run per agent, each with usage, so all three
+ // endpoints have something to fold: tokens/cost, run time, and a failure
+ // reason alongside its succeeded denominator.
+ seedRun := func(agentID, status, failureReason string, tokens int64) {
+ var taskID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_task_queue (
+ agent_id, issue_id, runtime_id, status, failure_reason,
+ started_at, completed_at, created_at
+ )
+ VALUES ($1, $2, $3, $4, NULLIF($5, ''), $6, $7, now())
+ RETURNING id
+ `, agentID, issueID, runtimeID, status, failureReason, started, completed).Scan(&taskID); err != nil {
+ t.Fatalf("insert %s task: %v", status, err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, taskID)
+ })
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO task_usage (task_id, provider, model, input_tokens, output_tokens, created_at)
+ VALUES ($1, 'claude', 'agent-visibility-model', $2, 0, now())
+ `, taskID, tokens); err != nil {
+ t.Fatalf("insert task_usage: %v", err)
+ }
+ }
+ seedRun(privateAgentID, "completed", "", 1000)
+ seedRun(privateAgentID, "failed", "runtime_offline", 200)
+ seedRun(publicAgentID, "completed", "", 300)
+ seedRun(publicAgentID, "failed", "timeout", 50)
+
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(),
+ `DELETE FROM task_usage_hourly WHERE model = 'agent-visibility-model'`)
+ })
+ if _, err := testPool.Exec(ctx, `
+ SELECT rollup_task_usage_hourly_window('1970-01-01'::timestamptz, now() + interval '1 hour')
+ `); err != nil {
+ t.Fatalf("rollup window: %v", err)
+ }
+
+ // `days=7` rather than 1: failures/by-agent closes its window at exactly N
+ // calendar days in the viewer tz, and a run seeded 20 minutes ago falls
+ // outside that when the suite happens to run just after local midnight.
+ // The assertions below compare the two views of the same data, so a wider
+ // window costs nothing.
+ read := func(
+ name string,
+ handler func(http.ResponseWriter, *http.Request),
+ path, userID string,
+ out any,
+ ) string {
+ t.Helper()
+ w := httptest.NewRecorder()
+ handler(w, newRequestAs(userID, "GET", path, nil))
+ if w.Code != http.StatusOK {
+ t.Fatalf("%s as %s: expected 200, got %d: %s", name, userID, w.Code, w.Body.String())
+ }
+ body := w.Body.String()
+ if err := json.Unmarshal([]byte(body), out); err != nil {
+ t.Fatalf("%s: decode response: %v", name, err)
+ }
+ // Structural assertions only cover the fields this test knows about; a
+ // substring scan also catches an agent id smuggled in by a field added
+ // later.
+ if userID == memberID && strings.Contains(body, privateAgentID) {
+ t.Errorf("%s: member response leaked private agent id %s: %s", name, privateAgentID, body)
+ }
+ return body
+ }
+
+ // ---- usage/by-agent ----------------------------------------------------
+
+ type usageRow struct {
+ AgentID string `json:"agent_id"`
+ Model string `json:"model"`
+ InputTokens int64 `json:"input_tokens"`
+ CostUSDTicks int64 `json:"cost_usd_ticks"`
+ }
+ var ownerUsage, memberUsage []usageRow
+ const usagePath = "/api/dashboard/usage/by-agent?days=7"
+ read("usage/by-agent", testHandler.GetDashboardUsageByAgent, usagePath, testUserID, &ownerUsage)
+ read("usage/by-agent", testHandler.GetDashboardUsageByAgent, usagePath, memberID, &memberUsage)
+
+ usageID := func(r usageRow) string { return r.AgentID }
+ assertDashboardAgentPresence(t, "usage/by-agent (owner)", dashboardAgentIDSet(ownerUsage, usageID),
+ dashboardAgentPresence{privateAgent: true, publicAgent: true, sentinel: false}, privateAgentID, publicAgentID)
+ assertDashboardAgentPresence(t, "usage/by-agent (member)", dashboardAgentIDSet(memberUsage, usageID),
+ dashboardAgentPresence{privateAgent: false, publicAgent: true, sentinel: true}, privateAgentID, publicAgentID)
+
+ sumUsage := func(rows []usageRow) (tokens, ticks int64) {
+ for _, r := range rows {
+ tokens += r.InputTokens
+ ticks += r.CostUSDTicks
+ }
+ return
+ }
+ ownerTokens, ownerTicks := sumUsage(ownerUsage)
+ memberTokens, memberTicks := sumUsage(memberUsage)
+ if ownerTokens != memberTokens || ownerTicks != memberTicks {
+ t.Errorf("usage/by-agent: folding changed the totals — owner (%d tokens, %d ticks), member (%d tokens, %d ticks)",
+ ownerTokens, ownerTicks, memberTokens, memberTicks)
+ }
+ // The restricted bucket must stay split by (provider, model) or the client
+ // cannot price it, and the leaderboard stops summing to the Cost KPI.
+ for _, r := range memberUsage {
+ if r.AgentID == restrictedAgentsRowID && r.Model == "" {
+ t.Errorf("usage/by-agent: restricted bucket lost its model dimension: %+v", r)
+ }
+ }
+
+ // ---- agent-runtime -----------------------------------------------------
+
+ type runTimeRow struct {
+ AgentID string `json:"agent_id"`
+ TotalSeconds int64 `json:"total_seconds"`
+ TaskCount int32 `json:"task_count"`
+ FailedCount int32 `json:"failed_count"`
+ }
+ var ownerRunTime, memberRunTime []runTimeRow
+ const runTimePath = "/api/dashboard/agent-runtime?days=7"
+ read("agent-runtime", testHandler.GetDashboardAgentRunTime, runTimePath, testUserID, &ownerRunTime)
+ read("agent-runtime", testHandler.GetDashboardAgentRunTime, runTimePath, memberID, &memberRunTime)
+
+ runTimeID := func(r runTimeRow) string { return r.AgentID }
+ assertDashboardAgentPresence(t, "agent-runtime (owner)", dashboardAgentIDSet(ownerRunTime, runTimeID),
+ dashboardAgentPresence{privateAgent: true, publicAgent: true, sentinel: false}, privateAgentID, publicAgentID)
+ assertDashboardAgentPresence(t, "agent-runtime (member)", dashboardAgentIDSet(memberRunTime, runTimeID),
+ dashboardAgentPresence{privateAgent: false, publicAgent: true, sentinel: true}, privateAgentID, publicAgentID)
+
+ sumRunTime := func(rows []runTimeRow) (secs int64, tasks, failed int32) {
+ for _, r := range rows {
+ secs += r.TotalSeconds
+ tasks += r.TaskCount
+ failed += r.FailedCount
+ }
+ return
+ }
+ ownerSecs, ownerTasks, ownerFailed := sumRunTime(ownerRunTime)
+ memberSecs, memberTasks, memberFailed := sumRunTime(memberRunTime)
+ if ownerSecs != memberSecs || ownerTasks != memberTasks || ownerFailed != memberFailed {
+ t.Errorf("agent-runtime: folding changed the totals — owner (%ds, %d tasks, %d failed), member (%ds, %d tasks, %d failed)",
+ ownerSecs, ownerTasks, ownerFailed, memberSecs, memberTasks, memberFailed)
+ }
+ // One bucket, not one row per hidden agent: how MANY private agents exist
+ // is itself part of what "private" hides.
+ restrictedRows := 0
+ for _, r := range memberRunTime {
+ if r.AgentID == restrictedAgentsRowID {
+ restrictedRows++
+ }
+ }
+ if restrictedRows != 1 {
+ t.Errorf("agent-runtime: expected exactly 1 restricted bucket row, got %d", restrictedRows)
+ }
+
+ // ---- failures/by-agent -------------------------------------------------
+
+ type failureRow struct {
+ AgentID string `json:"agent_id"`
+ FailureReason string `json:"failure_reason"`
+ TaskCount int32 `json:"task_count"`
+ }
+ var ownerFailures, memberFailures []failureRow
+ const failuresPath = "/api/dashboard/failures/by-agent?days=7"
+ read("failures/by-agent", testHandler.GetDashboardFailuresByAgent, failuresPath, testUserID, &ownerFailures)
+ read("failures/by-agent", testHandler.GetDashboardFailuresByAgent, failuresPath, memberID, &memberFailures)
+
+ failureID := func(r failureRow) string { return r.AgentID }
+ assertDashboardAgentPresence(t, "failures/by-agent (owner)", dashboardAgentIDSet(ownerFailures, failureID),
+ dashboardAgentPresence{privateAgent: true, publicAgent: true, sentinel: false}, privateAgentID, publicAgentID)
+ assertDashboardAgentPresence(t, "failures/by-agent (member)", dashboardAgentIDSet(memberFailures, failureID),
+ dashboardAgentPresence{privateAgent: false, publicAgent: true, sentinel: true}, privateAgentID, publicAgentID)
+
+ // Per-reason totals must be identical across the two views: the Errors card
+ // derives the workspace failure rate from these rows, and a fold that lost
+ // or double-counted a bucket would silently skew it.
+ byReason := func(rows []failureRow) map[string]int32 {
+ out := map[string]int32{}
+ for _, r := range rows {
+ out[r.FailureReason] += r.TaskCount
+ }
+ return out
+ }
+ ownerByReason, memberByReason := byReason(ownerFailures), byReason(memberFailures)
+ if len(ownerByReason) != len(memberByReason) {
+ t.Errorf("failures/by-agent: reason set changed — owner %v, member %v", ownerByReason, memberByReason)
+ }
+ for reason, count := range ownerByReason {
+ if memberByReason[reason] != count {
+ t.Errorf("failures/by-agent: reason %q total changed — owner %d, member %d",
+ reason, count, memberByReason[reason])
+ }
+ }
+ // The private agent's failure still has to be COUNTED — it rides inside the
+ // bucket — just not be attributable to it.
+ if ownerByReason["runtime_offline"] < 1 {
+ t.Fatalf("test setup: expected the private agent's runtime_offline failure in the owner view, got %v", ownerByReason)
+ }
+}
+
+// TestDashboardPerAgentRollupsFoldSystemAgentCarriers covers the population the
+// first version of the MUL-5409 fix missed. `kind = 'system'` agents — the
+// hidden execution carriers behind agent-builder sessions — run real tasks and
+// book real usage, and the three rollup queries aggregate over
+// agent_task_queue / task_usage without any kind filter. But NO list endpoint
+// returns them (ListAgents / ListAllAgents both filter `kind = 'user'`), so no
+// client can resolve one to a name.
+//
+// That makes them the sharpest form of both bugs at once: a bare UUID that
+// leaks one member's builder session to every other member, and — once the
+// agent list loads — a live agent folded into the client's "Deleted agents"
+// row. They are therefore restricted for EVERYONE, workspace owner included,
+// which is what this test pins: the carrier's own owner must not get its UUID
+// either, and the totals must survive the fold.
+func TestDashboardPerAgentRollupsFoldSystemAgentCarriers(t *testing.T) {
+ if testHandler == nil {
+ t.Skip("database not available")
+ }
+ ctx := context.Background()
+
+ _, _, memberID := privateAgentTestFixture(t)
+ runtimeID := handlerTestRuntimeID(t)
+
+ var issueID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO issue (workspace_id, title, creator_id, creator_type, number)
+ VALUES ($1, 'system carrier visibility', $2, 'member',
+ (SELECT COALESCE(MAX(number), 0) + 1 FROM issue WHERE workspace_id = $1))
+ RETURNING id
+ `, testWorkspaceID, testUserID).Scan(&issueID); err != nil {
+ t.Fatalf("create issue: %v", err)
+ }
+ t.Cleanup(func() { testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID) })
+
+ rollup := func(label string) {
+ t.Helper()
+ if _, err := testPool.Exec(ctx, `
+ SELECT rollup_task_usage_hourly_window('1970-01-01'::timestamptz, now() + interval '1 hour')
+ `); err != nil {
+ t.Fatalf("rollup (%s): %v", label, err)
+ }
+ }
+
+ type totals struct {
+ tokens int64
+ secs int64
+ tasks int32
+ failed int32
+ runs int32
+ }
+ // Sums the whole response rather than one row: the point is that the
+ // carrier's numbers are still IN there, just not attributable.
+ readTotals := func(userID string) (totals, []string) {
+ t.Helper()
+ var out totals
+ var bodies []string
+ read := func(name string, handler func(http.ResponseWriter, *http.Request), path string, decode func([]byte)) {
+ w := httptest.NewRecorder()
+ handler(w, newRequestAs(userID, "GET", path, nil))
+ if w.Code != http.StatusOK {
+ t.Fatalf("%s as %s: expected 200, got %d: %s", name, userID, w.Code, w.Body.String())
+ }
+ bodies = append(bodies, w.Body.String())
+ decode(w.Body.Bytes())
+ }
+ read("usage/by-agent", testHandler.GetDashboardUsageByAgent,
+ "/api/dashboard/usage/by-agent?days=7", func(b []byte) {
+ var rows []struct {
+ InputTokens int64 `json:"input_tokens"`
+ }
+ if err := json.Unmarshal(b, &rows); err != nil {
+ t.Fatalf("decode usage/by-agent: %v", err)
+ }
+ for _, r := range rows {
+ out.tokens += r.InputTokens
+ }
+ })
+ read("agent-runtime", testHandler.GetDashboardAgentRunTime,
+ "/api/dashboard/agent-runtime?days=7", func(b []byte) {
+ var rows []struct {
+ TotalSeconds int64 `json:"total_seconds"`
+ TaskCount int32 `json:"task_count"`
+ FailedCount int32 `json:"failed_count"`
+ }
+ if err := json.Unmarshal(b, &rows); err != nil {
+ t.Fatalf("decode agent-runtime: %v", err)
+ }
+ for _, r := range rows {
+ out.secs += r.TotalSeconds
+ out.tasks += r.TaskCount
+ out.failed += r.FailedCount
+ }
+ })
+ read("failures/by-agent", testHandler.GetDashboardFailuresByAgent,
+ "/api/dashboard/failures/by-agent?days=7", func(b []byte) {
+ var rows []struct {
+ TaskCount int32 `json:"task_count"`
+ }
+ if err := json.Unmarshal(b, &rows); err != nil {
+ t.Fatalf("decode failures/by-agent: %v", err)
+ }
+ for _, r := range rows {
+ out.runs += r.TaskCount
+ }
+ })
+ return out, bodies
+ }
+
+ rollup("baseline")
+ ownerBefore, _ := readTotals(testUserID)
+ memberBefore, _ := readTotals(memberID)
+
+ // A builder carrier, shaped exactly like CreateAgentBuilder writes one:
+ // kind=system, permission_mode=private, owned by the workspace owner.
+ var carrierID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent (
+ workspace_id, name, description, runtime_mode, runtime_config, runtime_id,
+ visibility, permission_mode, max_concurrent_tasks, owner_id, instructions,
+ custom_env, custom_args, kind, system_key
+ )
+ VALUES ($1, 'agent-builder-carrier', '', 'cloud', '{}'::jsonb, $2,
+ 'private', 'private', 1, $3, '', '{}'::jsonb, '[]'::jsonb,
+ 'system', 'agent_builder:' || gen_random_uuid()::text)
+ RETURNING id
+ `, testWorkspaceID, runtimeID, testUserID).Scan(&carrierID); err != nil {
+ t.Fatalf("create builder carrier: %v", err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM agent WHERE id = $1`, carrierID)
+ })
+
+ started := time.Now().UTC().Add(-30 * time.Minute)
+ completed := started.Add(10 * time.Minute) // 600s per run
+ for _, run := range []struct {
+ status, failureReason string
+ tokens int64
+ }{
+ {"completed", "", 900},
+ {"failed", "agent_error.provider_quota_limit", 100},
+ } {
+ var taskID string
+ if err := testPool.QueryRow(ctx, `
+ INSERT INTO agent_task_queue (
+ agent_id, issue_id, runtime_id, status, failure_reason,
+ started_at, completed_at, created_at
+ )
+ VALUES ($1, $2, $3, $4, NULLIF($5, ''), $6, $7, now())
+ RETURNING id
+ `, carrierID, issueID, runtimeID, run.status, run.failureReason, started, completed).Scan(&taskID); err != nil {
+ t.Fatalf("insert carrier %s task: %v", run.status, err)
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(), `DELETE FROM agent_task_queue WHERE id = $1`, taskID)
+ })
+ if _, err := testPool.Exec(ctx, `
+ INSERT INTO task_usage (task_id, provider, model, input_tokens, output_tokens, created_at)
+ VALUES ($1, 'claude', 'system-carrier-model', $2, 0, now())
+ `, taskID, run.tokens); err != nil {
+ t.Fatalf("insert carrier task_usage: %v", err)
+ }
+ }
+ t.Cleanup(func() {
+ testPool.Exec(context.Background(),
+ `DELETE FROM task_usage_hourly WHERE model = 'system-carrier-model'`)
+ })
+ rollup("after carrier")
+
+ for _, viewer := range []struct {
+ label string
+ userID string
+ before totals
+ }{
+ {"workspace owner (the carrier's own owner)", testUserID, ownerBefore},
+ {"plain member", memberID, memberBefore},
+ } {
+ after, bodies := readTotals(viewer.userID)
+
+ for i, body := range bodies {
+ if strings.Contains(body, carrierID) {
+ t.Errorf("%s: endpoint #%d leaked system carrier id %s: %s",
+ viewer.label, i, carrierID, body)
+ }
+ if !strings.Contains(body, restrictedAgentsRowID) {
+ t.Errorf("%s: endpoint #%d has no restricted bucket to carry the carrier's rows: %s",
+ viewer.label, i, body)
+ }
+ }
+
+ // Folded, not dropped: every metric must have moved by exactly the
+ // carrier's contribution.
+ if got := after.tokens - viewer.before.tokens; got != 1000 {
+ t.Errorf("%s: usage/by-agent token delta = %d, want 1000 (900 + 100)", viewer.label, got)
+ }
+ if got := after.secs - viewer.before.secs; got != 1200 {
+ t.Errorf("%s: agent-runtime seconds delta = %d, want 1200 (two 600s runs)", viewer.label, got)
+ }
+ if got := after.tasks - viewer.before.tasks; got != 2 {
+ t.Errorf("%s: agent-runtime task delta = %d, want 2", viewer.label, got)
+ }
+ if got := after.failed - viewer.before.failed; got != 1 {
+ t.Errorf("%s: agent-runtime failed delta = %d, want 1", viewer.label, got)
+ }
+ if got := after.runs - viewer.before.runs; got != 2 {
+ t.Errorf("%s: failures/by-agent run delta = %d, want 2", viewer.label, got)
+ }
+ }
+}
+
+func dashboardAgentIDSet[T any](rows []T, idOf func(T) string) map[string]struct{} {
+ out := make(map[string]struct{}, len(rows))
+ for _, r := range rows {
+ out[idOf(r)] = struct{}{}
+ }
+ return out
+}
+
+func assertDashboardAgentPresence(
+ t *testing.T,
+ label string,
+ ids map[string]struct{},
+ want dashboardAgentPresence,
+ privateAgentID, publicAgentID string,
+) {
+ t.Helper()
+ check := func(what, id string, expected bool) {
+ _, got := ids[id]
+ if got != expected {
+ t.Errorf("%s: %s (%s) present=%v, want %v", label, what, id, got, expected)
+ }
+ }
+ check("private agent", privateAgentID, want.privateAgent)
+ check("public agent", publicAgentID, want.publicAgent)
+ check("restricted bucket", restrictedAgentsRowID, want.sentinel)
+}
diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.go
index f2549ab8f8..daa7f76e4a 100644
--- a/server/pkg/db/generated/agent.sql.go
+++ b/server/pkg/db/generated/agent.sql.go
@@ -3619,6 +3619,71 @@ func (q *Queries) ListAllAgents(ctx context.Context, workspaceID pgtype.UUID) ([
return items, nil
}
+const listAllAgentsAnyKind = `-- name: ListAllAgentsAnyKind :many
+SELECT id, workspace_id, name, avatar_url, runtime_mode, runtime_config, visibility, status, max_concurrent_tasks, owner_id, created_at, updated_at, description, runtime_id, instructions, archived_at, archived_by, custom_env, custom_args, mcp_config, model, thinking_level, composio_toolkit_allowlist, permission_mode, kind, system_key, disabled_runtime_skills, service_tier FROM agent
+WHERE workspace_id = $1
+ORDER BY created_at ASC
+`
+
+// Every agent row in the workspace, INCLUDING `kind = 'system'` execution
+// carriers (agent builder sessions) that ListAllAgents deliberately hides.
+//
+// Only for surfaces that aggregate over raw `agent_task_queue` / task_usage
+// rows, which carry no kind filter of their own: a system carrier runs real
+// tasks and books real usage, so a per-agent rollup returns it whether or not
+// any list endpoint will ever name it. Those surfaces need the full population
+// to decide what to hide (MUL-5409). Do NOT use this to build a user-facing
+// agent list — `kind = 'system'` must stay out of every picker and assignee
+// surface.
+func (q *Queries) ListAllAgentsAnyKind(ctx context.Context, workspaceID pgtype.UUID) ([]Agent, error) {
+ rows, err := q.db.Query(ctx, listAllAgentsAnyKind, workspaceID)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []Agent{}
+ for rows.Next() {
+ var i Agent
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Name,
+ &i.AvatarUrl,
+ &i.RuntimeMode,
+ &i.RuntimeConfig,
+ &i.Visibility,
+ &i.Status,
+ &i.MaxConcurrentTasks,
+ &i.OwnerID,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.Description,
+ &i.RuntimeID,
+ &i.Instructions,
+ &i.ArchivedAt,
+ &i.ArchivedBy,
+ &i.CustomEnv,
+ &i.CustomArgs,
+ &i.McpConfig,
+ &i.Model,
+ &i.ThinkingLevel,
+ &i.ComposioToolkitAllowlist,
+ &i.PermissionMode,
+ &i.Kind,
+ &i.SystemKey,
+ &i.DisabledRuntimeSkills,
+ &i.ServiceTier,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const listChatFinalizeDeferredExpired = `-- name: ListChatFinalizeDeferredExpired :many
SELECT 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 FROM agent_task_queue
WHERE chat_finalize_deferred_at IS NOT NULL
diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sql
index 7eef734700..e464cb335a 100644
--- a/server/pkg/db/queries/agent.sql
+++ b/server/pkg/db/queries/agent.sql
@@ -8,6 +8,21 @@ SELECT * FROM agent
WHERE workspace_id = $1 AND kind = 'user'
ORDER BY created_at ASC;
+-- name: ListAllAgentsAnyKind :many
+-- Every agent row in the workspace, INCLUDING `kind = 'system'` execution
+-- carriers (agent builder sessions) that ListAllAgents deliberately hides.
+--
+-- Only for surfaces that aggregate over raw `agent_task_queue` / task_usage
+-- rows, which carry no kind filter of their own: a system carrier runs real
+-- tasks and books real usage, so a per-agent rollup returns it whether or not
+-- any list endpoint will ever name it. Those surfaces need the full population
+-- to decide what to hide (MUL-5409). Do NOT use this to build a user-facing
+-- agent list — `kind = 'system'` must stay out of every picker and assignee
+-- surface.
+SELECT * FROM agent
+WHERE workspace_id = $1
+ORDER BY created_at ASC;
+
-- name: GetAgent :one
SELECT * FROM agent
WHERE id = $1;