Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
fix(issues): count agents working in the surface, not the workspace (MUL-5525) (#6191)
Naiyuan Qing13b06f038e04
diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex 47c9f74fc1..61d344bbdf 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -894,7 +894,7 @@ const IssueTableFacetValueSchema = z.object({}).loose();const IssueTableFacetSchema = z.object({- kind: z.enum(["status", "priority", "assignee", "creator", "project", "label", "property"]),+ kind: z.enum(["status", "priority", "assignee", "creator", "project", "label", "property", "working_agents"]),property_id: z.string().optional(),values: z.array(IssueTableFacetValueSchema).default([]),}).loose();diff --git a/packages/core/types/api.ts b/packages/core/types/api.tsindex 427221122f..8ac5151690 100644--- a/packages/core/types/api.ts+++ b/packages/core/types/api.ts@@ -397,7 +397,11 @@ export type IssueTableFacetSpec =| { kind: "creator" }| { kind: "project" }| { kind: "label" }- | { kind: "property"; property_id: string };+ | { kind: "property"; property_id: string }+ /** Agents running issue work inside this surface. `key` is the agent id,+ * `count` its running-task count. Evaluated against the surface's own scope+ * and filters, so the header chip counts the same rows the list shows. */+ | { kind: "working_agents" };export interface IssueTableFacetsRequest {query: IssueTableQuerySpec;@@ -423,6 +427,15 @@ export interface IssueTableFacetsResponse {facets: IssueTableFacet[];}+/** One agent running issue work inside a single issue surface. Projected from+ * the `working_agents` facet, so the count is already narrowed by that+ * surface's scope and every active filter. Name/avatar are resolved from the+ * workspace agent directory, not carried here. */+export interface WorkingAgentSummary {+ id: string;+ running_task_count: number;+}+/** Per-status bucket in the paginated issue cache. `total` is the server count (all pages), not the length of `issues`. */export interface IssueStatusBucket {issues: Issue[];diff --git a/packages/views/issues/components/issues-header.tsx b/packages/views/issues/components/issues-header.tsxindex d844e6d2be..4ce3c32036 100644--- a/packages/views/issues/components/issues-header.tsx+++ b/packages/views/issues/components/issues-header.tsx@@ -65,6 +65,7 @@ import type {IssueProperty,IssueTableFacetSpec,IssueTableFacetsResponse,+ WorkingAgentSummary,} from "@multica/core/types";import { ProjectIcon } from "../../projects/components/project-icon";import { ActorAvatar } from "../../common/actor-avatar";@@ -794,6 +795,7 @@ export function ViewRefreshIndicator({ active }: { active: boolean }) {export function IssuesHeader({scopedIssues,+ workingAgents,allowGantt = false,dateFilter = null,onDateFilterChange,@@ -803,6 +805,9 @@ export function IssuesHeader({onTableFacetChange,}: {scopedIssues: Issue[];+ /** See IssueSurfaceController.workingAgents — the surface-scoped projection+ * behind the agents-working chip. */+ workingAgents: WorkingAgentSummary[] | undefined;allowGantt?: boolean;dateFilter?: IssueDateFilter | null;onDateFilterChange?: (filter: IssueDateFilter | null) => void;@@ -897,6 +902,7 @@ export function IssuesHeader({<WorkspaceAgentWorkingChipvalue={agentRunningFilter}onToggle={toggleAgentRunningFilter}+ agents={workingAgents}/><IssueDisplayControlsscopedIssues={scopedIssues}diff --git a/packages/views/issues/components/issues-page.test.tsx b/packages/views/issues/components/issues-page.test.tsxindex b2c0030397..61abb67c2f 100644--- a/packages/views/issues/components/issues-page.test.tsx+++ b/packages/views/issues/components/issues-page.test.tsx@@ -149,19 +149,27 @@ const mockListIssueTableFacets = vi.hoisted(() =>"blocked","cancelled",];- const groups = await Promise.all(- statuses.map(async (status) => ({- status,- response: await mockListIssues({- status,- limit: 50,- offset: 0,- ...(request.query.scope.assignee_types- ? { assignee_types: request.query.scope.assignee_types }- : {}),- }),- })),+ // Only sweep the legacy endpoint for a status facet. Every surface also+ // requests an always-on `working_agents` facet to label its activity chip,+ // and that must not look like the legacy status sweep these tests forbid.+ const wantsStatus = request.facets.some(+ (facet: any) => facet.kind === "status",);+ const groups = wantsStatus+ ? await Promise.all(+ statuses.map(async (status) => ({+ status,+ response: await mockListIssues({+ status,+ limit: 50,+ offset: 0,+ ...(request.query.scope.assignee_types+ ? { assignee_types: request.query.scope.assignee_types }+ : {}),+ }),+ })),+ )+ : [];return {query_fingerprint: "test",total: groups.reduce((sum, group) => sum + group.response.issues.length, 0),diff --git a/packages/views/issues/components/issues-page.tsx b/packages/views/issues/components/issues-page.tsxindex c5b48b3309..26d94b4168 100644--- a/packages/views/issues/components/issues-page.tsx+++ b/packages/views/issues/components/issues-page.tsx@@ -5,6 +5,7 @@ import type {Issue,IssueTableFacetSpec,IssueTableFacetsResponse,+ WorkingAgentSummary,} from "@multica/core/types";import { useIssuesScopeStore } from "@multica/core/issues/stores/issues-scope-store";import { useViewStore } from "@multica/core/issues/stores/view-store-context";@@ -15,12 +16,14 @@ import { IssuesHeader } from "./issues-header";function IssuesSurfaceHeader({issues,+ workingAgents,isRefreshing,facetCountsExact,tableFacetCounts,onTableFacetChange,}: {issues: Issue[];+ workingAgents: WorkingAgentSummary[] | undefined;isRefreshing: boolean;facetCountsExact: boolean;tableFacetCounts?: IssueTableFacetsResponse;@@ -32,6 +35,7 @@ function IssuesSurfaceHeader({return (<IssuesHeaderscopedIssues={issues}+ workingAgents={workingAgents}dateFilter={dateFilter}onDateFilterChange={setDateFilter}isRefreshing={isRefreshing}@@ -60,6 +64,7 @@ export function IssuesPage() {renderHeader={({ controller }) => (<IssuesSurfaceHeaderissues={controller.surfaceIssues}+ workingAgents={controller.workingAgents}isRefreshing={controller.isRefreshing}facetCountsExact={controller.facetCountsExact}tableFacetCounts={controller.tableFacetCounts}diff --git a/packages/views/issues/components/workspace-agent-working-chip.test.tsx b/packages/views/issues/components/workspace-agent-working-chip.test.tsxindex 1778404080..654f393120 100644--- a/packages/views/issues/components/workspace-agent-working-chip.test.tsx+++ b/packages/views/issues/components/workspace-agent-working-chip.test.tsx@@ -2,40 +2,20 @@import { cleanup, screen } from "@testing-library/react";import { beforeEach, describe, expect, it, vi } from "vitest";-import type { WorkspaceWorkingAgent } from "@multica/core/types";+import type { WorkingAgentSummary } from "@multica/core/types";import { renderWithI18n } from "../../test/i18n";const mockState = vi.hoisted(() => ({- agents: [] as WorkspaceWorkingAgent[],- requestedType: undefined as string | undefined,- requestedMineRelation: undefined as string | undefined,avatarAgentIds: undefined as readonly string[] | undefined,buttonVariant: undefined as string | undefined,}));-vi.mock("@multica/core/hooks", () => ({- useWorkspaceId: () => "ws-1",-}));--vi.mock("@multica/core/agents", () => ({- workspaceWorkingAgentsOptions: (- wsId: string,- type?: string,- mineRelation?: string,- ) => {- mockState.requestedType = type;- mockState.requestedMineRelation = mineRelation;- return {- queryKey: [- "workspaces",- wsId,- "working-agents",- "list",- type ?? "all",- mineRelation ? `mine:${mineRelation}` : "workspace",- ],- };- },+vi.mock("@multica/core/workspace/hooks", () => ({+ useActorName: () => ({+ getActorName: (_type: string, id: string) => `Agent ${id}`,+ getActorInitials: () => "AG",+ getActorAvatarUrl: () => null,+ }),}));vi.mock("../../agents/components/agent-avatar-stack", () => ({@@ -45,16 +25,16 @@ vi.mock("../../agents/components/agent-avatar-stack", () => ({},}));-vi.mock("@tanstack/react-query", async () => {- const actual =- await vi.importActual<typeof import("@tanstack/react-query")>(- "@tanstack/react-query",- );- return {- ...actual,- useQuery: () => ({ data: mockState.agents }),- };-});+// The real hover card renders its body only while open. Render it inline so the+// chip's own wiring to the hover body is observable: the MUL-5525 follow-up bug+// was in that wiring (`agents ?? []`), not in the body's rendering.+vi.mock("@multica/ui/components/ui/hover-card", () => ({+ HoverCard: ({ children }: { children: React.ReactNode }) => <div>{children}</div>,+ HoverCardTrigger: ({ render }: { render: React.ReactElement }) => render,+ HoverCardContent: ({ children }: { children: React.ReactNode }) => (+ <div data-testid="hover-content">{children}</div>+ ),+}));vi.mock("@multica/ui/components/ui/button", async () => {const actual =@@ -71,43 +51,34 @@ vi.mock("@multica/ui/components/ui/button", async () => {});import {+ WorkingAgentsHoverContent,WorkspaceAgentWorkingChip,+ chipActivity,chipAppearance,} from "./workspace-agent-working-chip";-function makeAgent(- id: string,- runningTaskCount = 1,-): WorkspaceWorkingAgent {- return {- id,- name: `Agent ${id}`,- avatar_url: null,- running_task_count: runningTaskCount,- issue_ids: [],- };+function makeAgent(id: string, runningTaskCount = 1): WorkingAgentSummary {+ return { id, running_task_count: runningTaskCount };}+const UNKNOWN_HOVER = "Agents working: not loaded yet";+const EMPTY_HOVER = "No agents working right now";+beforeEach(() => {cleanup();vi.clearAllMocks();- mockState.agents = [];- mockState.requestedType = undefined;- mockState.requestedMineRelation = undefined;mockState.avatarAgentIds = undefined;mockState.buttonVariant = undefined;});describe("WorkspaceAgentWorkingChip", () => {- it("shows every agent returned by the independent workspace API", () => {- mockState.agents = [- makeAgent("agent-1"),- makeAgent("agent-2", 3),- makeAgent("agent-3"),- ];-+ it("counts exactly the agents the surface projection supplies", () => {renderWithI18n(- <WorkspaceAgentWorkingChip value={false} onToggle={() => {}} />,+ <WorkspaceAgentWorkingChip+ value={false}+ onToggle={() => {}}+ agents={[makeAgent("agent-1"), makeAgent("agent-2", 3), makeAgent("agent-3")]}+ />,);expect(@@ -118,62 +89,144 @@ describe("WorkspaceAgentWorkingChip", () => {"agent-2","agent-3",]);- expect(mockState.requestedType).toBe("issue");- expect(mockState.requestedMineRelation).toBeUndefined();expect(mockState.buttonVariant).toBe("brandSubtle");});- it("requests the selected My Issues relation when the header is scoped", () => {+ // The whole point of MUL-5525: the chip must not invent a count of its own.+ // A surface whose filters leave no working rows has to read zero even while+ // other agents are busy elsewhere in the workspace.+ it("shows a known zero for a surface with no working rows", () => {+ renderWithI18n(+ <WorkspaceAgentWorkingChip value={false} onToggle={() => {}} agents={[]} />,+ );++ expect(+ screen.getByRole("button", { name: "0 agents working" }),+ ).toBeTruthy();+ expect(screen.queryByTestId("agent-avatar-stack")).toBeNull();+ expect(mockState.buttonVariant).toBe("outline");+ expect(screen.getByText(EMPTY_HOVER)).toBeTruthy();+ });++ it("renders an indeterminate label while the projection is unresolved", () => {+ renderWithI18n(+ <WorkspaceAgentWorkingChip+ value={false}+ onToggle={() => {}}+ agents={undefined}+ />,+ );++ expect(+ screen.getByRole("button", { name: "Agents working: —" }),+ ).toBeTruthy();+ expect(screen.queryByTestId("agent-avatar-stack")).toBeNull();+ });++ // Regression: the chip passed `agents ?? []` to the hover body, so an+ // unresolved projection rendered "No agents working right now" — an assertion+ // of zero on no evidence, from the one surface with room to say otherwise.+ it("does not let the hover body downgrade an unresolved projection to zero", () => {renderWithI18n(<WorkspaceAgentWorkingChipvalue={false}onToggle={() => {}}- mineRelation="involved"+ agents={undefined}/>,);- expect(mockState.requestedType).toBe("issue");- expect(mockState.requestedMineRelation).toBe("involved");+ expect(screen.getByTestId("hover-content").textContent).toBe(UNKNOWN_HOVER);+ expect(screen.queryByText(EMPTY_HOVER)).toBeNull();});- it("shows a known zero instead of an indeterminate Table value", () => {+ // The neutral tier's muted text is what reads as "idle", so it must not be+ // worn while the answer is still unknown.+ it("does not dim the chip while the projection is unresolved", () => {renderWithI18n(- <WorkspaceAgentWorkingChip value={false} onToggle={() => {}} />,+ <WorkspaceAgentWorkingChip+ value={false}+ onToggle={() => {}}+ agents={undefined}+ />,);- expect(- screen.getByRole("button", { name: "0 agents working" }),- ).toBeTruthy();- expect(screen.queryByTestId("agent-avatar-stack")).toBeNull();+ const button = screen.getByRole("button", { name: "Agents working: —" });expect(mockState.buttonVariant).toBe("outline");+ expect(button.className).not.toContain("text-muted-foreground");});it("keeps the active filter visually selected after the final agent stops", () => {renderWithI18n(- <WorkspaceAgentWorkingChip value onToggle={() => {}} />,+ <WorkspaceAgentWorkingChip value onToggle={() => {}} agents={[]} />,);expect(mockState.buttonVariant).toBe("brand");});});+describe("WorkingAgentsHoverContent", () => {+ it("says the answer is not loaded yet when the projection is unresolved", () => {+ renderWithI18n(<WorkingAgentsHoverContent agents={undefined} />);++ expect(screen.getByText(UNKNOWN_HOVER)).toBeTruthy();+ expect(screen.queryByText(EMPTY_HOVER)).toBeNull();+ });++ it("says nobody is working only for a resolved empty projection", () => {+ renderWithI18n(<WorkingAgentsHoverContent agents={[]} />);++ expect(screen.getByText(EMPTY_HOVER)).toBeTruthy();+ expect(screen.queryByText(UNKNOWN_HOVER)).toBeNull();+ });++ it("lists the roster with each agent's running task count", () => {+ renderWithI18n(+ <WorkingAgentsHoverContent+ agents={[makeAgent("a1"), makeAgent("a2", 3)]}+ />,+ );++ expect(screen.getByText("2 agents working")).toBeTruthy();+ expect(screen.getByText("Agent a1")).toBeTruthy();+ expect(screen.getByText("1 task")).toBeTruthy();+ expect(screen.getByText("Agent a2")).toBeTruthy();+ expect(screen.getByText("3 tasks")).toBeTruthy();+ expect(screen.queryByText(UNKNOWN_HOVER)).toBeNull();+ expect(screen.queryByText(EMPTY_HOVER)).toBeNull();+ });+});++describe("chipActivity", () => {+ it("keeps unresolved, resolved-empty and non-empty strictly apart", () => {+ expect(chipActivity(undefined)).toBe("unknown");+ expect(chipActivity([])).toBe("none");+ expect(chipActivity([makeAgent("a1")])).toBe("some");+ });+});+describe("chipAppearance", () => {it("wears the filled brand tier while the filter is on", () => {- expect(chipAppearance(true, true).variant).toBe("brand");+ expect(chipAppearance(true, "some").variant).toBe("brand");});it("wears the tint tier for activity without the filter", () => {- expect(chipAppearance(false, true).variant).toBe("brandSubtle");+ expect(chipAppearance(false, "some").variant).toBe("brandSubtle");});it("wears the plain tier with muted text when nothing is running", () => {- const appearance = chipAppearance(false, false);+ const appearance = chipAppearance(false, "none");expect(appearance.variant).toBe("outline");expect(appearance.className).toContain("text-muted-foreground");});+ it("stays neutral but undimmed while the projection is unknown", () => {+ const appearance = chipAppearance(false, "unknown");+ expect(appearance.variant).toBe("outline");+ expect(appearance.className).not.toContain("text-muted-foreground");+ });+it("does not mute the active zero state", () => {- const appearance = chipAppearance(true, false);+ const appearance = chipAppearance(true, "none");expect(appearance.variant).toBe("brand");expect(appearance.className).not.toContain("text-muted-foreground");});diff --git a/packages/views/issues/components/workspace-agent-working-chip.tsx b/packages/views/issues/components/workspace-agent-working-chip.tsxindex 87be711ab9..436ed6dc41 100644--- a/packages/views/issues/components/workspace-agent-working-chip.tsx+++ b/packages/views/issues/components/workspace-agent-working-chip.tsx@@ -1,6 +1,5 @@"use client";-import { useQuery } from "@tanstack/react-query";import { ActorAvatar } from "@multica/ui/components/common/actor-avatar";import { Button } from "@multica/ui/components/ui/button";import {@@ -8,48 +7,82 @@ import {HoverCardContent,HoverCardTrigger,} from "@multica/ui/components/ui/hover-card";-import { workspaceWorkingAgentsOptions } from "@multica/core/agents";-import { useWorkspaceId } from "@multica/core/hooks";-import type {- WorkspaceWorkingAgent,- WorkspaceWorkingAgentMineRelation,-} from "@multica/core/types";+import { useActorName } from "@multica/core/workspace/hooks";+import type { WorkingAgentSummary } from "@multica/core/types";import { AgentAvatarStack } from "../../agents/components/agent-avatar-stack";import { useT } from "../../i18n";interface WorkspaceAgentWorkingChipProps {value: boolean;onToggle: () => void;- mineRelation?: WorkspaceWorkingAgentMineRelation;+ /** Agents working inside the surface this header belongs to, already narrowed+ * by its scope and every active filter. `undefined` = not resolved yet. */+ agents: readonly WorkingAgentSummary[] | undefined;+}++/** What the projection says about activity in this surface. `unknown` is a+ * first-class case, not a synonym for `none`. */+export type ChipActivity = "unknown" | "none" | "some";++export function chipActivity(+ agents: readonly WorkingAgentSummary[] | undefined,+): ChipActivity {+ if (agents === undefined) return "unknown";+ return agents.length > 0 ? "some" : "none";}/*** Which colour tier the chip wears, and the only classes allowed alongside* it. Activity uses a tint, the active filter uses the filled brand tier,- * and an idle workspace stays neutral.+ * and an idle surface stays neutral.+ *+ * The muted text on the neutral tier is what reads as "nothing is happening+ * here", so an unresolved projection gets the neutral tier WITHOUT it: we do+ * not yet know whether the surface is idle, and dimming it would claim so.*/export function chipAppearance(value: boolean,- hasAgents: boolean,+ activity: ChipActivity,): { variant: "brand" | "brandSubtle" | "outline"; className: string } {const layout = "h-8 px-2 md:h-7 md:px-2.5";if (value) return { variant: "brand", className: layout };- if (hasAgents) return { variant: "brandSubtle", className: layout };+ if (activity === "some") return { variant: "brandSubtle", className: layout };+ if (activity === "unknown") return { variant: "outline", className: layout };return { variant: "outline", className: `${layout} text-muted-foreground` };}/**- * Hover body for every surface that reads the working-agents projection —- * the workspace filter chip here and the sub-issues header chip on issue- * detail. Shared so a narrowed read and an unnarrowed one describe activity- * the same way; the only difference between the two is the query's scope.+ * Hover body for every surface that reads a working-agents projection — the+ * surface filter chip here and the sub-issues header chip on issue detail.+ * Shared so a narrowed read and an unnarrowed one describe activity the same+ * way; the only difference between the two is the projection's scope.+ *+ * Identity comes from the workspace agent directory rather than the payload:+ * the surface projection is a facet of ids and counts, and resolving names+ * here keeps one definition of an agent's name/avatar across both callers.+ *+ * Three distinct states, and the first two must never collapse into each other:+ * `undefined` = the projection has not resolved, `[]` = it resolved and this+ * surface really has nobody working, a non-empty list = the roster. Rendering+ * the empty sentence for an unresolved projection would assert "no agents+ * working right now" on no evidence — the same class of unearned claim the chip+ * count itself had (MUL-5525).*/export function WorkingAgentsHoverContent({agents,}: {- agents: readonly WorkspaceWorkingAgent[];+ agents: readonly WorkingAgentSummary[] | undefined;}) {const { t } = useT("issues");+ const { getActorName, getActorInitials, getActorAvatarUrl } = useActorName();++ if (agents === undefined) {+ return (+ <p className="text-caption text-muted-foreground">+ {t(($) => $.agent_activity.unknown_hover)}+ </p>+ );+ }if (agents.length === 0) {return (@@ -68,14 +101,14 @@ export function WorkingAgentsHoverContent({{agents.map((agent) => (<div key={agent.id} className="flex items-center gap-2 text-caption"><ActorAvatar- name={agent.name}- initials={agent.name.trim().slice(0, 2).toUpperCase()}- avatarUrl={agent.avatar_url ?? undefined}+ name={getActorName("agent", agent.id)}+ initials={getActorInitials("agent", agent.id)}+ avatarUrl={getActorAvatarUrl("agent", agent.id) ?? undefined}isAgentsize="sm"/><span className="min-w-0 flex-1 truncate font-medium">- {agent.name}+ {getActorName("agent", agent.id)}</span><span className="shrink-0 tabular-nums text-muted-foreground">{t(($) => $.agent_activity.tasks_count, {@@ -90,32 +123,36 @@ export function WorkingAgentsHoverContent({}/**- * Workspace-wide agents-working filter chip.+ * Agents-working filter chip for an issue surface header.*- * Its data comes from the independent GET /api/working-agents projection, so- * Table pagination and locally loaded rows can never turn a known count into- * an indeterminate "—". Issues uses the workspace issue projection; My Issues- * passes its authenticated relation so the server scopes the count. Clicking- * the control only toggles view state; the Table controller translates these- * same returned ids into assignee filters.+ * The number IS the post-click row count's authority: it counts the agents+ * working on rows this surface's scope AND active filters would show, resolved+ * by the surface controller from the server-side `working_agents` facet — the+ * same compiled query the rows come from. Before MUL-5525 it ran its own+ * workspace-wide `/api/working-agents` read, so on a project page it could+ * advertise agents working nowhere near that project and open an empty list.+ *+ * `agents === undefined` means the projection has not resolved. Every surface of+ * the chip then stays indeterminate — label, compact number, colour tier and+ * hover body alike — because "0" and "not known yet" are different claims and+ * the reader cannot tell them apart once one of them is rendered as the other.+ *+ * Clicking only toggles view state; the controller turns the running-issue set+ * into the query's `working_issue_ids` filter.*/export function WorkspaceAgentWorkingChip({value,onToggle,- mineRelation,+ agents,}: WorkspaceAgentWorkingChipProps) {const { t } = useT("issues");- const wsId = useWorkspaceId();- const { data: agents = [] } = useQuery(- workspaceWorkingAgentsOptions(wsId, "issue", mineRelation),- );- const agentIds = agents.map((agent) => agent.id);- const agentCount = agents.length;- const hasAgents = agentCount > 0;- const label = t(($) => $.agent_activity.chip_agents_working, {- count: agentCount,- });- const appearance = chipAppearance(value, hasAgents);+ const activity = chipActivity(agents);+ const agentIds = agents?.map((agent) => agent.id) ?? [];+ const label =+ activity === "unknown"+ ? t(($) => $.agent_activity.chip_agents_working_unknown)+ : t(($) => $.agent_activity.chip_agents_working, { count: agentIds.length });+ const appearance = chipAppearance(value, activity);const trigger = (<Button@@ -126,8 +163,12 @@ export function WorkspaceAgentWorkingChip({aria-pressed={value}aria-label={label}>- {hasAgents && <AgentAvatarStack agentIds={agentIds} size="sm" max={3} />}- <span className="tabular-nums md:hidden">{agentCount}</span>+ {activity === "some" && (+ <AgentAvatarStack agentIds={agentIds} size="sm" max={3} />+ )}+ <span className="tabular-nums md:hidden">+ {activity === "unknown" ? "—" : agentIds.length}+ </span><span className="hidden tabular-nums md:inline">{label}</span></Button>);@@ -136,6 +177,9 @@ export function WorkspaceAgentWorkingChip({<HoverCard><HoverCardTrigger render={trigger} /><HoverCardContent align="end" className="w-72">+ {/* Pass the projection through untouched. Defaulting to [] here would+ hand the hover card a definite "nobody is working" for a state we+ have not resolved. */}<WorkingAgentsHoverContent agents={agents} /></HoverCardContent></HoverCard>diff --git a/packages/views/issues/surface/issue-surface.test.tsx b/packages/views/issues/surface/issue-surface.test.tsxindex 18340abfa7..61a69b3f97 100644--- a/packages/views/issues/surface/issue-surface.test.tsx+++ b/packages/views/issues/surface/issue-surface.test.tsx@@ -13,7 +13,10 @@ import {import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import { setApiInstance } from "@multica/core/api";import type { ApiClient } from "@multica/core/api/client";-import { pruneIssueSurfaceViewStates } from "@multica/core/issues/stores/surface-view-store";+import {+ getIssueSurfaceViewStore,+ pruneIssueSurfaceViewStates,+} from "@multica/core/issues/stores/surface-view-store";import type {AgentTask,Issue,@@ -682,3 +685,98 @@ describe("IssueSurface — table pagination ownership", () => {expect(container.querySelector(".fixed.bottom-6")).not.toBeNull();});});++// MUL-5525. A surface whose filters match nothing is not an empty surface.+// Every caller's own empty copy ("No issues linked — create one") describes the+// UNFILTERED case, so the shared filtered state has to win before `renderEmpty`+// runs. The agents-working chip is the most common way into this state.+describe("IssueSurface — filtered empty state", () => {+ let qc: QueryClient;++ beforeEach(() => {+ mockWsId.current = "ws-1";+ qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });+ // Resolve `t(($) => $.a.b)` to "a.b" so copy can be asserted by key+ // without loading the locale bundles into this suite.+ mockTranslate.mockImplementation(((...args: unknown[]) => {+ const path: string[] = [];+ const probe: unknown = new Proxy(() => {}, {+ get: (_target, property) => {+ path.push(String(property));+ return probe;+ },+ });+ (args[0] as (value: unknown) => unknown)(probe);+ return path.join(".");+ }) as unknown as () => string);+ const listIssues = vi.fn(() =>+ Promise.resolve({ issues: [], total: 0 } satisfies ListIssuesResponse),+ );+ setApiInstance({+ listIssues,+ ...statusTableMethodsFromLegacy(listIssues),+ listGroupedIssues: vi.fn(() => never()),+ listProjects: vi.fn(() => never()),+ getAgentTaskSnapshot: vi.fn(() => never<AgentTask[]>()),+ getWorkspaceWorkingAgents: vi.fn(() => Promise.resolve([])),+ getChildIssueProgress: vi.fn(() => never()),+ } as unknown as ApiClient);+ pruneIssueSurfaceViewStates([]);+ });++ afterEach(() => {+ cleanup();+ qc.clear();+ pruneIssueSurfaceViewStates([]);+ mockTranslate.mockImplementation(() => "translated");+ vi.restoreAllMocks();+ });++ function filteredSurface() {+ return (+ <QueryClientProvider client={qc}>+ <IssueSurface+ scope={{ type: "project", projectId: "pf" }}+ modes={["list"]}+ renderHeader={() => null}+ batchToolbar="never"+ />+ </QueryClientProvider>+ );+ }++ it("says the filters hid everything instead of offering to create the first issue", async () => {+ const store = getIssueSurfaceViewStore("project:pf");+ act(() => store.getState().toggleAgentRunningFilter());++ render(filteredSurface());++ await screen.findByText("filtered_empty.title");+ expect(screen.getByText("filtered_empty.hint")).toBeInTheDocument();+ // The project's own "nothing linked yet" copy would be a lie here.+ expect(screen.queryByText("detail.empty_issues_title")).toBeNull();+ });++ it("clears exactly the filters it blamed, then hands the surface back", async () => {+ const store = getIssueSurfaceViewStore("project:pf");+ act(() => store.getState().toggleAgentRunningFilter());++ render(filteredSurface());++ await screen.findByText("filtered_empty.title");+ fireEvent.click(+ screen.getByRole("button", { name: "filtered_empty.clear_button" }),+ );++ expect(store.getState().agentRunningFilter).toBe(false);+ await screen.findByText("detail.empty_issues_title");+ expect(screen.queryByText("filtered_empty.title")).toBeNull();+ });++ it("keeps the unfiltered empty state when no filter is active", async () => {+ render(filteredSurface());++ await screen.findByText("detail.empty_issues_title");+ expect(screen.queryByText("filtered_empty.title")).toBeNull();+ });+});diff --git a/packages/views/issues/surface/issue-surface.tsx b/packages/views/issues/surface/issue-surface.tsxindex 3a076d0c54..bbd38e690a 100644--- a/packages/views/issues/surface/issue-surface.tsx+++ b/packages/views/issues/surface/issue-surface.tsx@@ -1,12 +1,15 @@"use client";import { useCallback, useEffect, useMemo, useState, type ReactNode } from "react";-import { ListTodo, Plus } from "lucide-react";+import { FilterX, ListTodo, Plus } from "lucide-react";import { Button } from "@multica/ui/components/ui/button";import { Skeleton } from "@multica/ui/components/ui/skeleton";import { cn } from "@multica/ui/lib/utils";import { useWorkspaceId } from "@multica/core/hooks";-import { ViewStoreProvider } from "@multica/core/issues/stores/view-store-context";+import {+ useViewStore,+ ViewStoreProvider,+} from "@multica/core/issues/stores/view-store-context";import { getIssueSurfaceViewStore } from "@multica/core/issues/stores/surface-view-store";import { issueScopeKey } from "@multica/core/issues/surface/scope";import type { Issue } from "@multica/core/types";@@ -30,12 +33,6 @@ import {export interface IssueSurfaceRenderContext {controller: IssueSurfaceController;issues: Issue[];- /** The rows the agents-working filter would leave on screen, with this- * surface's `clientFilter` applied — headers feed it to the working chip- * so the chip's count is the post-click row count (MUL-4884). Undefined- * means the set is UNKNOWN (not materialized by the server-backed Table);- * the chip renders an indeterminate state instead of a number. */- workingIssues: Issue[] | undefined;}interface IssueSurfaceComponentProps extends IssueSurfaceProps {@@ -158,20 +155,9 @@ function IssueSurfaceContent({: controller.swimlaneIssues,[clientFilter, controller.swimlaneIssues],);- // Same clientFilter the rendered rows go through, so the chip's promise- // survives on surfaces that narrow the list locally (e.g. a search box).- // An UNKNOWN scope (undefined) passes through untouched — there is nothing- // to filter and the chip must see it as unknown.- const workingIssues = useMemo(- () =>- clientFilter && controller.workingScopeIssues- ? controller.workingScopeIssues.filter((issue) => clientFilter(issue))- : controller.workingScopeIssues,- [clientFilter, controller.workingScopeIssues],- );const renderContext = useMemo(- () => ({ controller, issues, workingIssues }),- [controller, issues, workingIssues],+ () => ({ controller, issues }),+ [controller, issues],);const openCreateIssue = useCallback((defaults?: IssueCreateDefaults) => {@@ -211,6 +197,7 @@ function IssueSurfaceContent({) : (<IssuesHeaderscopedIssues={controller.surfaceIssues}+ workingAgents={controller.workingAgents}allowGantt={controller.allowGantt}isRefreshing={controller.isRefreshing}facetCountsExact={@@ -227,7 +214,15 @@ function IssueSurfaceContent({<IssueSurfaceSkeleton mode={controller.viewMode} />)) : controller.isEmpty || shouldShowClientEmpty ? (- renderEmpty ? (+ // A filtered-empty surface is NOT an empty surface. Claiming "no+ // issues here yet" and offering to create one is wrong when the rows+ // exist and a filter is hiding them — and it is the state the+ // agents-working chip drops you into most often (MUL-5525). This+ // branch precedes `renderEmpty` on purpose: every surface's own empty+ // copy describes the unfiltered case.+ controller.hasActiveFilters ? (+ <FilteredEmptyState />+ ) : renderEmpty ? (renderEmpty(renderContext)) : (<div className="flex flex-1 min-h-0 flex-col items-center justify-center gap-3 text-muted-foreground">@@ -327,6 +322,28 @@ function IssueSurfaceContent({);}+/**+ * Shown when the surface has rows but the active filters match none of them.+ * Shared by every surface, so no caller has to remember that its own empty+ * copy only describes the unfiltered case. The action clears exactly the+ * filters this state tests for, so it always restores content.+ */+function FilteredEmptyState() {+ const { t } = useT("issues");+ const clearFilters = useViewStore((s) => s.clearFilters);++ return (+ <div className="flex flex-1 min-h-0 flex-col items-center justify-center gap-3 text-muted-foreground">+ <FilterX className="h-10 w-10 text-muted-foreground/40" />+ <p className="text-body">{t(($) => $.filtered_empty.title)}</p>+ <p className="text-caption">{t(($) => $.filtered_empty.hint)}</p>+ <Button variant="outline" size="sm" className="mt-1" onClick={clearFilters}>+ {t(($) => $.filtered_empty.clear_button)}+ </Button>+ </div>+ );+}+// Table is deliberately absent. It owns its own placeholders, drawn as rows// inside its real grid so the header, column widths and toolbar are up before// any data is — a surface-level stand-in would replace all of that with barsdiff --git a/packages/views/issues/surface/status-table-test-api.ts b/packages/views/issues/surface/status-table-test-api.tsindex 7baf5601a5..46435af6eb 100644--- a/packages/views/issues/surface/status-table-test-api.ts+++ b/packages/views/issues/surface/status-table-test-api.ts@@ -15,6 +15,25 @@ type LegacyListIssues = (params?: ListIssuesParams,) => Promise<ListIssuesResponse>;+/** One agent holding running issue tasks, as the working-agents projection+ * reports it. `issue_ids` may name issues outside the queried surface — the+ * facet is expected to drop those, which is the whole point of MUL-5525. */+export interface WorkingTaskFixture {+ id: string;+ issue_ids: readonly string[];+}++/**+ * Data for the `working_agents` facet. `rows` is read directly rather than+ * through the legacy list endpoint: several tests assert that a Table surface+ * never touches that endpoint, and a facet stand-in that called it would make+ * them pass or fail for the wrong reason.+ */+export interface WorkingAgentsFixture {+ rows: () => readonly Issue[];+ agents: () => readonly WorkingTaskFixture[];+}+function legacyParamsForStatus(query: IssueTableQuerySpec,status: IssueStatus,@@ -80,6 +99,30 @@ async function allRows(return rows.flat();}+// The working-agents facet drops only ITS dimension, so every other filter in+// the spec still applies. Mirrors the two predicates `rowsForStatus` enforces.+function workingAgentFacetValues(+ query: IssueTableQuerySpec,+ fixture: WorkingAgentsFixture,+) {+ const statuses = query.filters.statuses;+ const visible = new Set(+ fixture+ .rows()+ .filter((issue) => !statuses || statuses.includes(issue.status))+ .filter(+ (issue) =>+ query.filters.include_sub_issues !== false ||+ issue.parent_issue_id === null,+ )+ .map((issue) => issue.id),+ );+ return fixture.agents().flatMap((agent) => {+ const count = agent.issue_ids.filter((id) => visible.has(id)).length;+ return count > 0 ? [{ key: agent.id, count }] : [];+ });+}+function primaryDescriptor(issue: Issue,primary: "assignee" | "project" | "parent",@@ -136,7 +179,13 @@ function primaryDescriptor(* imports this module; it lets existing surface tests keep their small* per-status in-memory data source while asserting the new request contract.*/-export function statusTableMethodsFromLegacy(listIssues: LegacyListIssues) {+export function statusTableMethodsFromLegacy(+ listIssues: LegacyListIssues,+ // Stand-in for the server's issue↔running-task join. Supply it to exercise+ // the `working_agents` facet; without it the facet answers empty, matching a+ // workspace where nothing is running.+ workingAgents: WorkingAgentsFixture = { rows: () => [], agents: () => [] },+) {return {listIssueTableGroups: async (request: IssueTableGroupsRequest) => {if (request.group.kind === "compound") {@@ -254,22 +303,27 @@ export function statusTableMethodsFromLegacy(listIssues: LegacyListIssues) {};},listIssueTableFacets: async (request: IssueTableFacetsRequest) => {- const groups = await Promise.all(- ALL_STATUSES.map(async (status) => ({- status,- issues: await rowsForStatus(- listIssues,- {- ...request.query,- filters: {- ...request.query.filters,- statuses: undefined,- },- },- status,- ),- })),- );+ // Only touch the legacy list endpoint when a status facet is actually+ // asked for: Table surfaces request other facets while asserting that+ // endpoint is never called.+ const groups = request.facets.some((facet) => facet.kind === "status")+ ? await Promise.all(+ ALL_STATUSES.map(async (status) => ({+ status,+ issues: await rowsForStatus(+ listIssues,+ {+ ...request.query,+ filters: {+ ...request.query.filters,+ statuses: undefined,+ },+ },+ status,+ ),+ })),+ )+ : [];return {query_fingerprint: "test",total: groups.reduce((sum, group) => sum + group.issues.length, 0),@@ -283,7 +337,9 @@ export function statusTableMethodsFromLegacy(listIssues: LegacyListIssues) {key: status,count: issues.length,}))- : [],+ : facet.kind === "working_agents"+ ? workingAgentFacetValues(request.query, workingAgents)+ : [],})),};},diff --git a/packages/views/issues/surface/use-issue-surface-controller.test.tsx b/packages/views/issues/surface/use-issue-surface-controller.test.tsxindex 8c2a9fef95..f5e1e7aff6 100644--- a/packages/views/issues/surface/use-issue-surface-controller.test.tsx+++ b/packages/views/issues/surface/use-issue-surface-controller.test.tsx@@ -98,6 +98,18 @@ function never<T>() {return new Promise<T>(() => {});}+/**+ * Facet requests that are NOT the always-on working-agents count. Every+ * surface issues that one on mount to label its activity chip; the lazy+ * submenu-facet contract these tests guard is about everything else.+ */+function submenuFacetCalls(mock: { mock: { calls: unknown[][] } }) {+ return mock.mock.calls.filter(([request]) => {+ const facets = (request as { facets?: { kind: string }[] } | undefined)?.facets;+ return !facets?.some((facet) => facet.kind === "working_agents");+ });+}+function makeRunningTask(id: string, agentId: string, issueId: string): AgentTask {return {id,@@ -142,15 +154,28 @@ describe("useIssueSurfaceController", () => {>;let listIssueTableRows: ReturnType<typeof vi.fn>;let listIssueTableFacets: ReturnType<typeof vi.fn>;+ // Every row the current fixture holds, kept outside the mocked list endpoint+ // so the working-agents facet stand-in can read it without registering a+ // call that Table-isolation tests assert never happens.+ let fixtureRows: Issue[];+ let workingAgentFixture: WorkspaceWorkingAgent[];beforeEach(() => {+ fixtureRows = [];+ workingAgentFixture = [];qc = new QueryClient({ defaultOptions: { queries: { retry: false } } });listIssues = vi.fn(() => never<ListIssuesResponse>());getAgentTaskSnapshot = vi.fn(() => never<AgentTask[]>());getWorkspaceWorkingAgents = vi.fn(() =>Promise.resolve([] satisfies WorkspaceWorkingAgent[]),);- const tableMethods = statusTableMethodsFromLegacy(listIssues);+ // The working-agents facet is server-side in production; here it reads the+ // same fixture the working-agents endpoint serves, so a test that moves one+ // moves both.+ const tableMethods = statusTableMethodsFromLegacy(listIssues, {+ rows: () => fixtureRows,+ agents: () => workingAgentFixture,+ });listIssueTableRows = vi.fn(tableMethods.listIssueTableRows);listIssueTableFacets = vi.fn(tableMethods.listIssueTableFacets);setApiInstance({@@ -652,10 +677,12 @@ describe("useIssueSurfaceController", () => {{ wrapper: makeWrapper(qc, "project:p1") },);- expect(listIssueTableFacets).not.toHaveBeenCalled();+ expect(submenuFacetCalls(listIssueTableFacets)).toHaveLength(0);act(() => result.current.setActiveTableFacet({ kind: "status" }));- await waitFor(() => expect(listIssueTableFacets).toHaveBeenCalledTimes(1));- expect(listIssueTableFacets).toHaveBeenCalledWith(+ await waitFor(() =>+ expect(submenuFacetCalls(listIssueTableFacets)).toHaveLength(1),+ );+ expect(submenuFacetCalls(listIssueTableFacets)[0]?.[0]).toEqual(expect.objectContaining({facets: [{ kind: "status" }],include_total: false,@@ -739,12 +766,14 @@ describe("useIssueSurfaceController", () => {);expect(result.current.facetCountsExact).toBe(false);- expect(listIssueTableFacets).not.toHaveBeenCalled();+ expect(submenuFacetCalls(listIssueTableFacets)).toHaveLength(0);act(() => result.current.setActiveTableFacet({ kind: "priority" }));- await waitFor(() => expect(listIssueTableFacets).toHaveBeenCalledTimes(1));- expect(listIssueTableFacets).toHaveBeenCalledWith(+ await waitFor(() =>+ expect(submenuFacetCalls(listIssueTableFacets)).toHaveLength(1),+ );+ expect(submenuFacetCalls(listIssueTableFacets)[0]?.[0]).toEqual(expect.objectContaining({facets: [{ kind: "priority" }],include_total: false,@@ -953,7 +982,7 @@ describe("useIssueSurfaceController", () => {const store = getIssueSurfaceViewStore("project:p1");store.getState().setViewMode(viewMode);store.getState().toggleAgentRunningFilter();- getWorkspaceWorkingAgents.mockResolvedValue([+ mockWorkingAgents([makeWorkingAgent("agent-from-working-api", ["issue-from-working-api"]),]);// Deliberately contradictory legacy data. It must neither be fetched nor@@ -991,7 +1020,7 @@ describe("useIssueSurfaceController", () => {store.getState().toggleAssigneeFilter({ type: "member", id: "member-1" });store.getState().toggleNoAssignee();store.getState().toggleAgentRunningFilter();- getWorkspaceWorkingAgents.mockResolvedValue([+ mockWorkingAgents([makeWorkingAgent("agent-2", ["member-assigned-running-issue"]),makeWorkingAgent("agent-3", ["unassigned-running-issue"]),]);@@ -1125,6 +1154,7 @@ describe("useIssueSurfaceController", () => {// and hideable like any other status.function mockListByStatus(byStatus: Partial<Record<IssueStatus, Issue[]>>) {+ fixtureRows = Object.values(byStatus).flatMap((issues) => issues ?? []);listIssues.mockImplementation((params?: ListIssuesParams) => {const status = params?.status as IssueStatus | undefined;const issues = (status && byStatus[status]) ?? [];@@ -1132,6 +1162,14 @@ describe("useIssueSurfaceController", () => {});}+ /** Feeds both the working-agents endpoint and the `working_agents` facet+ * stand-in, so a fixture can never say one thing to the filter and another+ * to the count. */+ function mockWorkingAgents(agents: WorkspaceWorkingAgent[]) {+ workingAgentFixture = agents;+ getWorkspaceWorkingAgents.mockResolvedValue(agents);+ }+it("fetches and surfaces the cancelled bucket as a default status", async () => {const { result } = renderHook(() =>@@ -1234,10 +1272,12 @@ describe("useIssueSurfaceController", () => {);});- // --- working-chip scope (MUL-4884) ------------------------------------- // The header chip promises "N issues in progress" where N is the number of- // rows clicking it leaves. The working-agents endpoint identifies both the- // running agents and the issues referenced by those agents' running tasks.+ // --- working-chip scope (MUL-4884, MUL-5525) ---------------------------+ // The header chip promises "N agents working" where N is the number of agents+ // holding rows that clicking it leaves. The running-issue ids still come from+ // the working-agents endpoint and go to the server as a filter; the COUNT+ // comes from the `working_agents` facet over the surface's own compiled+ // query, so scope and filters can never diverge from the list again.it("sends working issue ids to the server without reconstructing a local scope", async () => {mockListByStatus({@@ -1247,7 +1287,7 @@ describe("useIssueSurfaceController", () => {],in_progress: [makeIssue({ id: "prog-1", status: "in_progress" })],});- getWorkspaceWorkingAgents.mockResolvedValue([+ mockWorkingAgents([makeWorkingAgent("agent-1", ["todo-1"]),makeWorkingAgent("agent-2", ["prog-1"]),]);@@ -1272,20 +1312,29 @@ describe("useIssueSurfaceController", () => {expect(result.current.tableQuerySpec.filters.assignees).toBeUndefined();expect(result.current.tableQuerySpec.filters.working_only).toBeUndefined();expect(getAgentTaskSnapshot).not.toHaveBeenCalled();- // Membership is cursor-paged and server-owned. A partial page cannot- // produce the exact activity-chip scope, so it stays explicitly unknown.- expect(result.current.workingScopeIssues).toBeUndefined();+ // Cursor-paged server membership no longer forces an unknown count: the+ // facet answers over the same compiled query the branches use.+ await waitFor(() =>+ expect(result.current.workingAgents).toEqual([+ { id: "agent-1", running_task_count: 1 },+ { id: "agent-2", running_task_count: 1 },+ ]),+ );});- it("keeps the activity-chip scope unknown before the server filter is enabled", async () => {+ it("counts the agents a click would leave before the filter is even on", async () => {mockListByStatus({todo: [makeIssue({ id: "todo-1", status: "todo" }),makeIssue({ id: "todo-2", status: "todo" }),],});- getWorkspaceWorkingAgents.mockResolvedValue([+ mockWorkingAgents([makeWorkingAgent("agent-1", ["todo-1"]),+ // Working on an issue this project does not contain. The old+ // workspace-wide chip counted it here and then opened an empty list+ // (MUL-5525).+ makeWorkingAgent("agent-elsewhere", ["other-project-1"]),]);const { result } = renderHook(@@ -1299,10 +1348,14 @@ describe("useIssueSurfaceController", () => {await waitFor(() => expect(result.current.isLoading).toBe(false));- // Filter off: the list still shows both loaded rows, while the exact- // post-click membership remains unknown until the backend predicate runs.+ // Filter off: the list still shows both loaded rows, and the chip already+ // reports the post-click answer — one agent, not two.expect(result.current.issues).toHaveLength(2);- expect(result.current.workingScopeIssues).toBeUndefined();+ await waitFor(() =>+ expect(result.current.workingAgents).toEqual([+ { id: "agent-1", running_task_count: 1 },+ ]),+ );});it("combines the status and working predicates in the canonical server query", async () => {@@ -1310,7 +1363,7 @@ describe("useIssueSurfaceController", () => {todo: [makeIssue({ id: "todo-1", status: "todo" })],in_progress: [makeIssue({ id: "prog-1", status: "in_progress" })],});- getWorkspaceWorkingAgents.mockResolvedValue([+ mockWorkingAgents([makeWorkingAgent("agent-1", ["todo-1"]),makeWorkingAgent("agent-2", ["prog-1"]),]);@@ -1340,7 +1393,13 @@ describe("useIssueSurfaceController", () => {]);expect(result.current.tableQuerySpec.filters.assignees).toBeUndefined();expect(result.current.tableQuerySpec.filters.working_only).toBeUndefined();- expect(result.current.workingScopeIssues).toBeUndefined();+ // agent-2 works only on `prog-1`, which the active status filter hides. The+ // chip must not count an agent whose rows the list will not show.+ await waitFor(() =>+ expect(result.current.workingAgents).toEqual([+ { id: "agent-1", running_task_count: 1 },+ ]),+ );});it("sends the sub-issue display rule to the same server query", async () => {@@ -1350,7 +1409,7 @@ describe("useIssueSurfaceController", () => {makeIssue({ id: "child-1", status: "todo", parent_issue_id: "parent-1" }),],});- getWorkspaceWorkingAgents.mockResolvedValue([+ mockWorkingAgents([makeWorkingAgent("agent-1", ["parent-1"]),]);@@ -1369,7 +1428,40 @@ describe("useIssueSurfaceController", () => {await waitFor(() => expect(result.current.isLoading).toBe(false));expect(result.current.tableQuerySpec.filters.include_sub_issues).toBe(false);- expect(result.current.workingScopeIssues).toBeUndefined();+ await waitFor(() =>+ expect(result.current.workingAgents).toEqual([+ { id: "agent-1", running_task_count: 1 },+ ]),+ );+ });++ it("drops an agent whose only working row is a hidden sub-issue", async () => {+ mockListByStatus({+ todo: [+ makeIssue({ id: "parent-1", status: "todo" }),+ makeIssue({ id: "child-1", status: "todo", parent_issue_id: "parent-1" }),+ ],+ });+ mockWorkingAgents([+ makeWorkingAgent("agent-child", ["child-1"]),+ ]);++ const store = getIssueSurfaceViewStore("project:p1");+ act(() => store.getState().toggleShowSubIssues());++ const { result } = renderHook(+ () =>+ useIssueSurfaceController({+ scope: { type: "project", projectId: "p1" },+ modes: ["list"],+ }),+ { wrapper: makeWrapper(qc, "project:p1") },+ );++ await waitFor(() => expect(result.current.isLoading).toBe(false));++ expect(result.current.tableQuerySpec.filters.include_sub_issues).toBe(false);+ await waitFor(() => expect(result.current.workingAgents).toEqual([]));});it("requests issue working agents so chat/autopilot work stays out of scope", async () => {@@ -1386,7 +1478,7 @@ describe("useIssueSurfaceController", () => {);await waitFor(() => expect(result.current.isLoading).toBe(false));- expect(result.current.workingScopeIssues).toEqual([]);+ await waitFor(() => expect(result.current.workingAgents).toEqual([]));expect(getWorkspaceWorkingAgents).toHaveBeenCalledWith("issue", undefined, undefined);expect(getAgentTaskSnapshot).not.toHaveBeenCalled();});@@ -1396,7 +1488,7 @@ describe("useIssueSurfaceController", () => {todo: [makeIssue({ id: "todo-1", status: "todo" })],in_progress: [makeIssue({ id: "prog-1", status: "in_progress" })],});- getWorkspaceWorkingAgents.mockResolvedValue([+ mockWorkingAgents([makeWorkingAgent("agent-1", ["todo-1"]),makeWorkingAgent("agent-2", ["prog-1"]),]);@@ -1417,9 +1509,14 @@ describe("useIssueSurfaceController", () => {);await waitFor(() => expect(result.current.isLoading).toBe(false));- // Like Table/List, the migrated Swimlane owns cursor branches and does- // not materialize another complete working-only window for the chip.- expect(result.current.workingScopeIssues).toBeUndefined();+ // Like Table/List, the migrated Swimlane owns cursor branches and never+ // materializes a second working-only window — the chip's count comes from+ // the facet, and the active `todo` filter keeps agent-2 out of it.+ await waitFor(() =>+ expect(result.current.workingAgents).toEqual([+ { id: "agent-1", running_task_count: 1 },+ ]),+ );// Controller-only tests do not mount lane cells, so no row branch should// activate merely because its descriptor exists.expect(result.current.issues).toEqual([]);@@ -1476,7 +1573,7 @@ describe("useIssueSurfaceController", () => {it("filters Gantt by running-task issue ids rather than issue assignees", async () => {mockGanttIssues(ganttFixture);- getWorkspaceWorkingAgents.mockResolvedValue([+ mockWorkingAgents([// The editing agent deliberately differs from the issue assignee.makeWorkingAgent("agent-editor", ["gantt-open"]),]);@@ -1506,13 +1603,15 @@ describe("useIssueSurfaceController", () => {);// ganttShowCompleted defaults to false, so the done row and the undated- // row are not drawn — the chip must not count them either.- expect(result.current.workingScopeIssues?.map((i) => i.id)).toEqual([+ // row are not drawn — the chip must not count their agents either. Gantt+ // keeps a client-side count because its canvas projection is not+ // expressible as a Table query spec.+ expect(result.current.workingAgents).toEqual([+ { id: "agent-editor", running_task_count: 1 },+ ]);+ expect(result.current.filteredGanttIssues.map((i) => i.id)).toEqual(["gantt-open",]);- expect(result.current.workingScopeIssues?.map((i) => i.id)).toEqual(- result.current.filteredGanttIssues.map((i) => i.id),- );expect(getAgentTaskSnapshot).not.toHaveBeenCalled();});@@ -1532,7 +1631,7 @@ describe("useIssueSurfaceController", () => {selectedAssigneeId,}) => {mockGanttIssues(ganttFixture);- getWorkspaceWorkingAgents.mockResolvedValue(workingAgents);+ mockWorkingAgents(workingAgents);const store = getIssueSurfaceViewStore("project:p1");act(() => {@@ -1573,12 +1672,12 @@ describe("useIssueSurfaceController", () => {: undefined,);expect(result.current.filteredGanttIssues).toEqual([]);- expect(result.current.workingScopeIssues).toEqual([]);+ expect(result.current.workingAgents).toEqual([]);});it("widens the gantt working scope when show-completed is turned on", async () => {mockGanttIssues(ganttFixture);- getWorkspaceWorkingAgents.mockResolvedValue([+ mockWorkingAgents([makeWorkingAgent("agent-editor", ["gantt-open", "gantt-done"]),]);@@ -1602,15 +1701,15 @@ describe("useIssueSurfaceController", () => {expect(result.current.filteredGanttIssues.length).toBe(2),);- // The done row is drawn now, so it counts. The undated one still cannot- // be placed, so it still does not.- expect(result.current.workingScopeIssues?.map((i) => i.id).sort()).toEqual([+ // The done row is drawn now, so its task counts. The undated one still+ // cannot be placed, so it still does not — two rows, one agent, two tasks.+ expect(result.current.workingAgents).toEqual([+ { id: "agent-editor", running_task_count: 2 },+ ]);+ expect(result.current.filteredGanttIssues.map((i) => i.id).sort()).toEqual(["gantt-done","gantt-open",]);- expect(result.current.workingScopeIssues?.map((i) => i.id)).toEqual(- result.current.filteredGanttIssues.map((i) => i.id),- );expect(getAgentTaskSnapshot).not.toHaveBeenCalled();});});diff --git a/packages/views/issues/surface/use-issue-surface-controller.ts b/packages/views/issues/surface/use-issue-surface-controller.tsindex 642b9349e2..0634bfb567 100644--- a/packages/views/issues/surface/use-issue-surface-controller.ts+++ b/packages/views/issues/surface/use-issue-surface-controller.ts@@ -13,6 +13,7 @@ import type {IssueTableGroupsRequest,IssueTableQuerySpec,Project,+ WorkingAgentSummary,} from "@multica/core/types";import { workspaceWorkingAgentsOptions } from "@multica/core/agents";import { useWorkspaceId } from "@multica/core/hooks";@@ -74,10 +75,12 @@ export interface IssueSurfaceController {projectIssues: Issue[];issues: Issue[];swimlaneIssues: Issue[];- /** The rows the agents-working filter would leave on screen. Feeds the- * header chip so its count IS the post-click row count (MUL-4884). */- /** See IssueSurfaceData.workingScopeIssues — undefined means UNKNOWN. */- workingScopeIssues: Issue[] | undefined;+ /** Agents currently working inside THIS surface, under the surface's active+ * filters — the header chip's count, so clicking it leaves exactly these+ * agents' rows (MUL-4884, MUL-5525). `undefined` means the projection has+ * not resolved yet; the chip renders an indeterminate state rather than a+ * number it cannot stand behind. */+ workingAgents: WorkingAgentSummary[] | undefined;filteredGanttIssues: Issue[];assigneeGroups?: IssueAssigneeGroup[];assigneeGroupQueryKey?: QueryKey;@@ -95,6 +98,9 @@ export interface IssueSurfaceController {* Board and compound Swimlane cells. */groupBranches?: IssueGroupBranches;activeFilters: Omit<IssueFilters, "statusFilters">;+ /** Any filter that `clearFilters()` would reset is on. Lets an empty surface+ * say "your filters hid everything" instead of "there is nothing here". */+ hasActiveFilters: boolean;actions: IssueSurfaceActions;selection: IssueSurfaceSelection;childProgressMap: Map<string, ChildProgress>;@@ -347,6 +353,24 @@ export function useIssueSurfaceController({const { projectFilters: viewProjectFilters, includeNoProject: viewIncludeNoProject } =projectFilterState;+ // Exactly the filters `clearFilters()` resets, so an empty surface that+ // reports "filters hid everything" can always offer a button that fixes it.+ // Display toggles (show sub-issues) and per-surface search are deliberately+ // out: they have their own affordances and clearing filters would not undo+ // them.+ const hasActiveFilters =+ statusFilters.length > 0 ||+ priorityFilters.length > 0 ||+ assigneeFilters.length > 0 ||+ includeNoAssignee ||+ creatorFilters.length > 0 ||+ viewProjectFilters.length > 0 ||+ viewIncludeNoProject ||+ labelFilters.length > 0 ||+ Object.keys(effectivePropertyFilters).length > 0 ||+ dateFilter != null ||+ agentRunningFilter === true;+const workingAgentMineRelation =scope.type === "my"? scope.relation === "all"@@ -497,6 +521,50 @@ export function useIssueSurfaceController({usesServerStatusSurface ||((usesTable || usesServerGroupSurface) && activeTableFacet !== null),});+ // The header chip's count, kept on its own query rather than folded into the+ // submenu facet request above. Two reasons: that request is deliberately+ // lazy (an always-on facet would re-enable it for Table/grouped surfaces on+ // mount), and this spec drops `working_issue_ids` so toggling the filter+ // does not change the query identity — the number must not flicker when you+ // click the very chip it labels.+ const workingAgentsQuerySpec = useMemo<IssueTableQuerySpec>(() => {+ if (!agentRunningFilter) return tableQuerySpec;+ const { working_issue_ids: _working, ...filters } = tableQuerySpec.filters;+ return { ...tableQuerySpec, filters };+ }, [agentRunningFilter, tableQuerySpec]);+ const workingAgentsFacetRequest = useMemo(+ () => ({+ query: workingAgentsQuerySpec,+ facets: [{ kind: "working_agents" } as const],+ include_total: false,+ }),+ [workingAgentsQuerySpec],+ );+ const workingAgentsFacetQuery = useQuery({+ ...issueTableFacetsOptions(wsId, workingAgentsFacetRequest),+ placeholderData: keepPreviousData,+ // Gantt owns its own count: its canvas projection is client-side and not+ // expressible as a Table query spec, so a facet answer would over-count.+ //+ // The actor panel (member / agent detail) renders no agents-working chip at+ // all, so nothing would read the answer — and with no control to toggle it,+ // `agentRunningFilter` is unreachable there. Skip the aggregation rather+ // than pay for it on every panel mount. Adding the chip to that header+ // means dropping this clause.+ enabled: !usesGantt && scope.type !== "actor",+ });+ const facetWorkingAgents = useMemo<WorkingAgentSummary[] | undefined>(() => {+ const facet = workingAgentsFacetQuery.data?.facets.find(+ (candidate) => candidate.kind === "working_agents",+ );+ // A backend without this facet (older deploy) answers with an error or a+ // response that omits it. Stay indeterminate instead of claiming zero.+ if (!facet) return undefined;+ return facet.values.map((value) => ({+ id: value.key,+ running_task_count: value.count,+ }));+ }, [workingAgentsFacetQuery.data]);useEffect(() => {if (!usesServerFacets) setActiveTableFacet(null);}, [usesServerFacets]);@@ -631,6 +699,28 @@ export function useIssueSurfaceController({(effectiveViewMode === "swimlane" && swimlaneGrouping === "project"),});+ // Gantt draws a client-materialized canvas, so its chip counts the agents+ // holding those canvas rows. Every other view mode takes the server facet.+ const workingAgents = useMemo<WorkingAgentSummary[] | undefined>(() => {+ if (!usesGantt) return facetWorkingAgents;+ const rows = data.ganttWorkingScopeIssues;+ if (!rows) return undefined;+ const visible = new Set(rows.map((issue) => issue.id));+ const summaries: WorkingAgentSummary[] = [];+ for (const agent of workspaceWorkingAgents) {+ const running = agent.issue_ids.filter((id) => visible.has(id)).length;+ if (running > 0) {+ summaries.push({ id: agent.id, running_task_count: running });+ }+ }+ return summaries;+ }, [+ data.ganttWorkingScopeIssues,+ facetWorkingAgents,+ usesGantt,+ workspaceWorkingAgents,+ ]);+const exportTableIssues = useCallback(async () => {const issues: Issue[] = [];const seenIssueIds = new Set<string>();@@ -684,13 +774,17 @@ export function useIssueSurfaceController({createDefaults: resolvedCreateDefaults,});+ const { ganttWorkingScopeIssues: _ganttWorkingScope, ...surfaceData } = data;+return {scopeKey,projectId,createDefaults: resolvedCreateDefaults,viewMode: effectiveViewMode,allowGantt: allowedModes.has("gantt") && !!projectId,- ...data,+ ...surfaceData,+ workingAgents,+ hasActiveFilters,statusPagination: usesServerStatusSurface? data.statusPagination: undefined,diff --git a/packages/views/issues/surface/use-issue-surface-data.ts b/packages/views/issues/surface/use-issue-surface-data.tsindex 8fce7323cd..1dfee2f1f9 100644--- a/packages/views/issues/surface/use-issue-surface-data.ts+++ b/packages/views/issues/surface/use-issue-surface-data.ts@@ -65,11 +65,10 @@ export interface IssueSurfaceData {projectIssues: Issue[];issues: Issue[];swimlaneIssues: Issue[];- /** The rows the agents-working filter would leave on screen. `undefined`- * means the set is genuinely unknown: Table membership is server-owned,- * and the activity chip must not reconstruct a complete issue window just- * to decorate the header. */- workingScopeIssues: Issue[] | undefined;+ /** Gantt only: the canvas rows the agents-working filter would leave on+ * screen. `undefined` on every other view mode, where the header chip+ * sources its count from the `working_agents` server facet instead. */+ ganttWorkingScopeIssues: Issue[] | undefined;filteredGanttIssues: Issue[];assigneeGroups?: IssueAssigneeGroup[];assigneeGroupQueryKey?: QueryKey;@@ -201,7 +200,6 @@ export function useIssueSurfaceData({...issueSurfaceGanttOptions(wsId, projectId ?? ""),enabled: usesGantt,});- const hasWorkingIssues = workingIssueIDs.size > 0;const workingFilterContext = useMemo(() => ({ runningIssueIds: workingIssueIDs }),[workingIssueIDs],@@ -343,91 +341,31 @@ export function useIssueSurfaceData({[baseFilterState],);- // The rows the agents-working filter leaves on screen — i.e. exactly what- // you get when you click the header chip.+ // The Gantt canvas rows the agents-working filter would leave on screen —+ // i.e. exactly what you get when you click the header chip in Gantt.//- // This is deliberately a projection of the render pipeline. The controller- // translates `/api/working-agents` into running issue ids once; both the- // canonical server query and client-only Gantt/extra-child paths reuse that- // returned issue-id set.+ // Gantt is the one surface whose membership is NOT server-owned: it draws+ // from a fully materialized scheduled-issue window, and its canvas+ // projection (scheduled + dated + showCompleted) cannot be expressed in the+ // Table query spec. So the header chip cannot source its count from the+ // `working_agents` server facet here, and derives it from this set instead.//- // The chip counts AGENTS, not this list's length, so these are not equal- // (one agent can hold two of these rows). What this set does decide is- // WHICH agents the chip counts — only those working on rows that survive- // the filters. Re-deriving that scope from the snapshot instead is what- // made the chip disagree with the list it was filtering: any active- // status/assignee/label filter, or a sub-issue hidden by the display- // toggle, moved the list but not the chip (MUL-4884).- //- // Each branch below must take the SAME source the matching branch of- // IssueSurface renders:- // - gantt → the canvas set (scheduled + dated + showCompleted)- // - assignee board → the grouped response, not the flat list- // - table → unknown unless the running set is empty; Table uses- // server cursor branches and never materializes a second full window- // - board / list / swimlane → the flat filtered list- //- // Swimlane deliberately has no branch: SwimLaneView draws its cards from- // `issues` (status filter applied) and only uses the statusless- // `swimlaneIssues` for LANE DISCOVERY, so scoping the chip to the- // statusless set would count rows the canvas never draws.- const workingScopeIssues = useMemo(() => {- if (usesGantt) {- return ganttCanvasRows(- applyIssueFilters(- ganttIssues,- workingFilterState,- workingFilterContext,- ),- ganttShowCompleted,- );- }- if (usesAssigneeBoard && !serverGroupBranches.enabled) {- const groupedIssues = (- filterAssigneeGroups(assigneeGroupsQuery.data?.groups, {- agentRunningFilter: true,- runningIssueIds: workingIssueIDs,- showSubIssues,- propertyFilters,- }) ?? []- ).flatMap((group) => group.issues);- return applyIssueFilters(- groupedIssues,- workingFilterState,- workingFilterContext,- );- }- if (usesTable || serverStatusBranches.enabled || serverGroupBranches.enabled) {- // Table membership is server-owned and cursor paged. Do not rebuild a- // second complete issue window merely to decorate the activity chip:- // that was the final hidden auto-materialization loop behind the old- // 1,000-row ceiling. An empty running-issue set is trivially- // known; otherwise keep the chip indeterminate until a bounded server- // facet supplies the matching task/issue projection.- if (!hasWorkingIssues) return EMPTY_ISSUES;- return undefined;- }- return applyIssueFilters(- surfaceIssues,- workingFilterState,- workingFilterContext,+ // Every other view mode (list / board / swimlane / table) resolves the same+ // question through that facet, against the identical scope + filters the+ // rows come from. Rebuilding a second complete issue window client-side to+ // decorate the chip is what the server facet exists to avoid.+ const ganttWorkingScopeIssues = useMemo(() => {+ if (!usesGantt) return undefined;+ return ganttCanvasRows(+ applyIssueFilters(ganttIssues, workingFilterState, workingFilterContext),+ ganttShowCompleted,);}, [- assigneeGroupsQuery.data?.groups,ganttIssues,ganttShowCompleted,- hasWorkingIssues,- propertyFilters,- showSubIssues,- surfaceIssues,- usesAssigneeBoard,usesGantt,- usesTable,- serverStatusBranches.enabled,- serverGroupBranches.enabled,workingFilterState,workingFilterContext,- workingIssueIDs,]);const {@@ -558,7 +496,7 @@ export function useIssueSurfaceData({projectIssues: surfaceIssues,issues,swimlaneIssues,- workingScopeIssues,+ ganttWorkingScopeIssues,filteredGanttIssues,assigneeGroups: usesAssigneeBoard ? filteredAssigneeGroups : undefined,assigneeGroupQueryKey: usesAssigneeBoarddiff --git a/packages/views/locales/en/issues.json b/packages/views/locales/en/issues.jsonindex 59ae4f1138..3219855bbd 100644--- a/packages/views/locales/en/issues.json+++ b/packages/views/locales/en/issues.json@@ -445,6 +445,7 @@"status_running": "Working","status_queued": "Queued","empty_hover": "No agents working right now",+ "unknown_hover": "Agents working: not loaded yet","filter_active_label": "Viewing issues with agents working","tasks_count_one": "{{count}} task","tasks_count_other": "{{count}} tasks",@@ -454,6 +455,11 @@"issues_count_other": "{{count}} issues","chip_agents_working_unknown": "Agents working: —"},+ "filtered_empty": {+ "title": "No issues match these filters",+ "hint": "Adjust or clear the filters to see the issues in this view.",+ "clear_button": "Clear filters"+ },"agent_live": {"is_working": "{{name}} is working","is_queued": "{{name}} is queued",diff --git a/packages/views/locales/ja/issues.json b/packages/views/locales/ja/issues.jsonindex 818838eb9b..be2f6241b7 100644--- a/packages/views/locales/ja/issues.json+++ b/packages/views/locales/ja/issues.json@@ -429,12 +429,18 @@"status_running": "作業中","status_queued": "待機中","empty_hover": "現在作業中のエージェントはありません",+ "unknown_hover": "作業中のエージェント: まだ読み込まれていません","filter_active_label": "エージェントが作業中の issue を表示中","tasks_count_other": "task {{count}} 件","chip_agents_working_other": "作業中のエージェント {{count}} 件","issues_count_other": "issue {{count}} 件","chip_agents_working_unknown": "作業中のエージェント: —"},+ "filtered_empty": {+ "title": "フィルター条件に一致する issue がありません",+ "hint": "フィルターを変更または解除すると、このビューの issue が表示されます。",+ "clear_button": "フィルターを解除"+ },"agent_live": {"is_working": "{{name}} が作業中","is_queued": "{{name}} が待機中",diff --git a/packages/views/locales/ko/issues.json b/packages/views/locales/ko/issues.jsonindex 853e28faef..48ae3896d2 100644--- a/packages/views/locales/ko/issues.json+++ b/packages/views/locales/ko/issues.json@@ -429,12 +429,18 @@"status_running": "작업 중","status_queued": "대기 중","empty_hover": "현재 작업 중인 에이전트가 없습니다",+ "unknown_hover": "작업 중인 에이전트: 아직 불러오지 않았습니다","filter_active_label": "에이전트가 작업 중인 issue만 보는 중","tasks_count_other": "task {{count}}개","chip_agents_working_other": "작업 중인 에이전트 {{count}}개","issues_count_other": "issue {{count}}개","chip_agents_working_unknown": "작업 중인 에이전트: —"},+ "filtered_empty": {+ "title": "필터 조건에 맞는 issue가 없습니다",+ "hint": "필터를 조정하거나 해제하면 이 보기의 issue가 표시됩니다.",+ "clear_button": "필터 해제"+ },"agent_live": {"is_working": "{{name}} 작업 중","is_queued": "{{name}} 대기 중",diff --git a/packages/views/locales/zh-Hans/issues.json b/packages/views/locales/zh-Hans/issues.jsonindex 2bd865e880..cf353de8b3 100644--- a/packages/views/locales/zh-Hans/issues.json+++ b/packages/views/locales/zh-Hans/issues.json@@ -429,12 +429,18 @@"status_running": "正在工作","status_queued": "排队中","empty_hover": "当前没有智能体在工作",+ "unknown_hover": "工作中的智能体:尚未加载","filter_active_label": "正在查看有智能体在工作的 issue","tasks_count_other": "{{count}} 个 task","chip_agents_working_other": "{{count}} 个智能体工作中","issues_count_other": "{{count}} 个 issue","chip_agents_working_unknown": "工作中的智能体:—"},+ "filtered_empty": {+ "title": "没有符合筛选条件的 issue",+ "hint": "调整或清除筛选条件,就能看到这个视图里的 issue。",+ "clear_button": "清除筛选"+ },"agent_live": {"is_working": "{{name}} 在工作","is_queued": "{{name}} 排队中",diff --git a/packages/views/my-issues/components/my-issues-header.tsx b/packages/views/my-issues/components/my-issues-header.tsxindex 5b0b385f6f..a7f0c16101 100644--- a/packages/views/my-issues/components/my-issues-header.tsx+++ b/packages/views/my-issues/components/my-issues-header.tsx@@ -14,11 +14,9 @@ import type {Issue,IssueTableFacetSpec,IssueTableFacetsResponse,+ WorkingAgentSummary,} from "@multica/core/types";-import {- myIssuesRelationFromScope,- type MyIssuesScope,-} from "@multica/core/issues/stores/my-issues-view-store";+import { type MyIssuesScope } from "@multica/core/issues/stores/my-issues-view-store";import { useViewStore } from "@multica/core/issues/stores/view-store-context";import { useT } from "../../i18n";import { WorkspaceAgentWorkingChip } from "../../issues/components/workspace-agent-working-chip";@@ -29,6 +27,7 @@ import {export function MyIssuesHeader({allIssues,+ workingAgents,scope,onScopeChange,isRefreshing = false,@@ -37,6 +36,10 @@ export function MyIssuesHeader({onTableFacetChange,}: {allIssues: Issue[];+ /** See IssueSurfaceController.workingAgents. My Issues used to ask the+ * working-agents endpoint for its own relation-scoped count; the surface+ * projection now covers the relation AND every active filter. */+ workingAgents: WorkingAgentSummary[] | undefined;scope: MyIssuesScope;onScopeChange: (scope: MyIssuesScope) => void;isRefreshing?: boolean;@@ -47,7 +50,6 @@ export function MyIssuesHeader({}) {const { t } = useT("my-issues");const { t: tIssues } = useT("issues");- const mineRelation = myIssuesRelationFromScope(scope);const SCOPES: { value: MyIssuesScope; label: string; description: string }[] = [{ value: "all", label: t(($) => $.header.scope.all_label), description: t(($) => $.header.scope.all_description) },{ value: "assigned", label: t(($) => $.header.scope.assigned_label), description: t(($) => $.header.scope.assigned_description) },@@ -123,7 +125,7 @@ export function MyIssuesHeader({<WorkspaceAgentWorkingChipvalue={agentRunningFilter}onToggle={toggleAgentRunningFilter}- mineRelation={mineRelation === "all" ? "any" : mineRelation}+ agents={workingAgents}/><IssueDisplayControlsscopedIssues={allIssues}diff --git a/packages/views/my-issues/components/my-issues-page.tsx b/packages/views/my-issues/components/my-issues-page.tsxindex 9069949ea5..4ef86ddc94 100644--- a/packages/views/my-issues/components/my-issues-page.tsx+++ b/packages/views/my-issues/components/my-issues-page.tsx@@ -37,6 +37,7 @@ export function MyIssuesPage() {renderHeader={({ controller }) => (<MyIssuesHeaderallIssues={controller.surfaceIssues}+ workingAgents={controller.workingAgents}scope={scope}onScopeChange={setScope}isRefreshing={controller.isRefreshing}diff --git a/server/internal/handler/issue_table_facets.go b/server/internal/handler/issue_table_facets.goindex 8023e7fee1..3a860a6ca4 100644--- a/server/internal/handler/issue_table_facets.go+++ b/server/internal/handler/issue_table_facets.go@@ -10,6 +10,7 @@ import ("strings""github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/logger""github.com/multica-ai/multica/server/internal/util"db "github.com/multica-ai/multica/server/pkg/db/generated"@@ -65,6 +66,13 @@ func issueTableQueryWithoutFacet(input issueTableQuerySpec, facet issueTableFaceoutput.Filters.LabelIDs = nilcase "property":delete(output.Filters.Properties, facet.PropertyID)+ case "working_agents":+ // Disjunctive like every other facet: drop this facet's own dimension so+ // the answer is "who would you see if you turned the agents-working+ // filter ON", which is also the answer while it is already on. That+ // makes the header chip's count stable across the toggle.+ output.Filters.WorkingIssueIDs = nil+ output.Filters.WorkingOnly = false}return output}@@ -194,6 +202,25 @@ func (h *Handler) issueTableFacetQuery(w http.ResponseWriter, r *http.Request, rquery = fmt.Sprintf(`SELECT COALESCE(i.project_id::text, '__none__'), COUNT(*)::bigint FROM issue i WHERE %s GROUP BY 1`, compiled.where)case "label":query = fmt.Sprintf(`SELECT itl.label_id::text, COUNT(DISTINCT i.id)::bigint FROM issue i JOIN issue_to_label itl ON itl.issue_id = i.id WHERE %s GROUP BY itl.label_id`, compiled.where)+ case "working_agents":+ // One row per agent currently running issue work inside THIS surface,+ // with its running-task count. Same predicate as+ // ListWorkspaceWorkingAgents with type=issue (chat > autopilot > issue+ // precedence, user-authored non-archived agents only), but the issue set+ // comes from the surface's own compiled scope + filters instead of a+ // second, independent workspace-wide definition. That is what keeps the+ // header chip's count equal to the rows clicking it leaves (MUL-5525).+ query = fmt.Sprintf(`SELECT a.id::text, COUNT(*)::bigint+FROM issue i+JOIN agent_task_queue atq ON atq.issue_id = i.id+JOIN agent a ON a.id = atq.agent_id AND a.workspace_id = i.workspace_id+WHERE %s+ AND a.kind = 'user'+ AND a.archived_at IS NULL+ AND atq.status = 'running'+ AND atq.chat_session_id IS NULL+ AND atq.autopilot_run_id IS NULL+GROUP BY a.id`, compiled.where)case "property":propertyID, err := util.ParseUUID(facet.PropertyID)if err != nil {@@ -254,12 +281,52 @@ func (h *Handler) issueTableFacetQuery(w http.ResponseWriter, r *http.Request, rwriteIssueTableQueryFailure(w, r, "failed to list table facets")return response, false}+ if facet.Kind == "working_agents" {+ values, ok := h.filterAccessibleAgentFacetValues(w, r, compiled.workspaceID, response.Values)+ if !ok {+ return response, false+ }+ response.Values = values+ }sort.Slice(response.Values, func(i, j int) bool {return strings.Compare(response.Values[i].Key, response.Values[j].Key) < 0})return response, true}+// The working-agents facet keys are agent ids, so it discloses agent identity+// and must pass the same visibility gate as every other workspace-wide agent+// aggregation: a private or non-allow-listed agent is never exposed by its id,+// its count, or even its presence.+func (h *Handler) filterAccessibleAgentFacetValues(+ w http.ResponseWriter,+ r *http.Request,+ workspaceUUID pgtype.UUID,+ values []issueTableFacetValueResponse,+) ([]issueTableFacetValueResponse, bool) {+ if len(values) == 0 {+ return values, true+ }+ workspaceID := util.UUIDToString(workspaceUUID)+ member, ok := h.workspaceMember(w, r, workspaceID)+ if !ok {+ return nil, false+ }+ actorType, actorID := h.resolveActor(r, requestUserID(r), workspaceID)+ allowed, ok := h.accessibleAgentIDs(r.Context(), workspaceID, actorType, actorID, member.Role)+ if !ok {+ writeIssueTableQueryFailure(w, r, "failed to resolve agent access")+ return nil, false+ }+ filtered := make([]issueTableFacetValueResponse, 0, len(values))+ for _, value := range values {+ if _, permitted := allowed[value.Key]; permitted {+ filtered = append(filtered, value)+ }+ }+ return filtered, true+}+func (h *Handler) ListIssueTableFacets(w http.ResponseWriter, r *http.Request) {if h.DB == nil {writeError(w, http.StatusInternalServerError, "database is unavailable")diff --git a/server/internal/handler/issue_table_working_agents_facet_test.go b/server/internal/handler/issue_table_working_agents_facet_test.gonew file mode 100644index 0000000000..738bc55701--- /dev/null+++ b/server/internal/handler/issue_table_working_agents_facet_test.go@@ -0,0 +1,258 @@+package handler++import (+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "testing"+)++// workingAgentsFacetCounts posts one facets request and returns the+// working-agents facet as agent id -> running task count.+func workingAgentsFacetCounts(+ t *testing.T,+ request *http.Request,+) map[string]int64 {+ t.Helper()++ recorder := httptest.NewRecorder()+ testHandler.ListIssueTableFacets(recorder, request)+ if recorder.Code != http.StatusOK {+ t.Fatalf("facets status = %d: %s", recorder.Code, recorder.Body.String())+ }+ var response issueTableFacetsResponse+ if err := json.NewDecoder(recorder.Body).Decode(&response); err != nil {+ t.Fatalf("decode facets: %v", err)+ }+ counts := map[string]int64{}+ for _, facet := range response.Facets {+ if facet.Kind != "working_agents" {+ continue+ }+ for _, value := range facet.Values {+ counts[value.Key] = value.Count+ }+ }+ return counts+}++func workingAgentsFacetRequest(scope, filters map[string]any) *http.Request {+ if filters == nil {+ filters = map[string]any{}+ }+ return newRequest(http.MethodPost, "/api/issues/table/facets", map[string]any{+ "query": map[string]any{+ "scope": scope,+ "filters": filters,+ "sort": map[string]any{"field": "position", "direction": "asc"},+ },+ "facets": []map[string]any{{"kind": "working_agents"}},+ "include_total": false,+ })+}++// MUL-5525. The header chip's count used to come from a workspace-wide+// projection while the list came from the surface's own compiled query, so a+// project page could advertise "2 agents working" and then open an empty list.+// The `working_agents` facet answers the same question against the same scope+// and filters the rows come from.+func TestIssueTableWorkingAgentsFacetFollowsSurfaceScopeAndFilters(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }++ ctx := context.Background()+ insideAgentID := createHandlerTestAgent(t, "facet-working-inside", []byte(`{}`))+ outsideAgentID := createHandlerTestAgent(t, "facet-working-outside", []byte(`{}`))+ idleAgentID := createHandlerTestAgent(t, "facet-working-idle", []byte(`{}`))++ var projectID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO project (workspace_id, title)+ VALUES ($1, 'Working Agents Facet Project')+ RETURNING id+ `, testWorkspaceID).Scan(&projectID); err != nil {+ t.Fatalf("create project: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM project WHERE id = $1`, projectID)+ })++ var finalNumber int+ if err := testPool.QueryRow(ctx, `+ UPDATE workspace+ SET issue_counter = GREATEST(+ issue_counter,+ (SELECT COALESCE(MAX(number), 0) FROM issue WHERE workspace_id = $1)+ ) + 4+ WHERE id = $1+ RETURNING issue_counter+ `, testWorkspaceID).Scan(&finalNumber); err != nil {+ t.Fatalf("reserve issue numbers: %v", err)+ }++ insertIssue := func(title, status string, number int, project any, parent any) string {+ t.Helper()+ var issueID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO issue (+ workspace_id, title, status, priority, creator_type, creator_id,+ project_id, parent_issue_id, position, number+ )+ VALUES ($1, $2, $3, 'none', 'member', $4, $5, $6, $7, $8)+ RETURNING id+ `,+ testWorkspaceID, title, status, testUserID, project, parent, number, number,+ ).Scan(&issueID); err != nil {+ t.Fatalf("insert issue %q: %v", title, err)+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID)+ })+ return issueID+ }++ inProjectTodoID := insertIssue("in project, todo", "todo", finalNumber-3, projectID, nil)+ inProjectDoneID := insertIssue("in project, done", "done", finalNumber-2, projectID, nil)+ outsideProjectID := insertIssue("outside the project", "todo", finalNumber-1, nil, nil)+ subIssueID := insertIssue("in project, sub-issue", "todo", finalNumber, projectID, inProjectTodoID)++ // insideAgent holds two running tasks inside the project (one on each+ // status) plus one on the sub-issue; outsideAgent works only outside it;+ // idleAgent has no running task at all.+ createHandlerTestTaskForAgentOnIssue(t, insideAgentID, inProjectTodoID)+ createHandlerTestTaskForAgentOnIssue(t, insideAgentID, inProjectDoneID)+ createHandlerTestTaskForAgentOnIssue(t, insideAgentID, subIssueID)+ createHandlerTestTaskForAgentOnIssue(t, outsideAgentID, outsideProjectID)++ projectScope := map[string]any{"kind": "project", "project_id": projectID}++ t.Run("project scope excludes agents working elsewhere", func(t *testing.T) {+ counts := workingAgentsFacetCounts(t, workingAgentsFacetRequest(projectScope, nil))+ if counts[insideAgentID] != 3 {+ t.Errorf("inside agent count = %d, want 3", counts[insideAgentID])+ }+ if _, present := counts[outsideAgentID]; present {+ t.Errorf("agent working outside the project was counted: %s", outsideAgentID)+ }+ if _, present := counts[idleAgentID]; present {+ t.Errorf("agent with no running task was counted: %s", idleAgentID)+ }+ })++ t.Run("a status filter narrows the count like it narrows the rows", func(t *testing.T) {+ counts := workingAgentsFacetCounts(t, workingAgentsFacetRequest(projectScope, map[string]any{+ "statuses": []string{"done"},+ }))+ if counts[insideAgentID] != 1 {+ t.Errorf("inside agent count under status=done = %d, want 1", counts[insideAgentID])+ }+ })++ t.Run("hiding sub-issues drops their tasks from the count", func(t *testing.T) {+ counts := workingAgentsFacetCounts(t, workingAgentsFacetRequest(projectScope, map[string]any{+ "include_sub_issues": false,+ }))+ if counts[insideAgentID] != 2 {+ t.Errorf("inside agent count without sub-issues = %d, want 2", counts[insideAgentID])+ }+ })++ t.Run("a filter that matches nothing reports a real zero", func(t *testing.T) {+ counts := workingAgentsFacetCounts(t, workingAgentsFacetRequest(projectScope, map[string]any{+ "statuses": []string{"cancelled"},+ }))+ if len(counts) != 0 {+ t.Errorf("counts = %v, want empty", counts)+ }+ })++ // The facet drops only its OWN dimension, so the answer is identical whether+ // the agents-working filter is on or off. That is what lets the chip's number+ // stay put when you click it.+ t.Run("the working filter itself does not change the answer", func(t *testing.T) {+ off := workingAgentsFacetCounts(t, workingAgentsFacetRequest(projectScope, nil))+ on := workingAgentsFacetCounts(t, workingAgentsFacetRequest(projectScope, map[string]any{+ "working_issue_ids": []string{inProjectTodoID},+ }))+ if off[insideAgentID] != on[insideAgentID] {+ t.Errorf("count moved with the filter: off=%d on=%d", off[insideAgentID], on[insideAgentID])+ }+ matchNone := workingAgentsFacetCounts(t, workingAgentsFacetRequest(projectScope, map[string]any{+ "working_issue_ids": []string{},+ }))+ if matchNone[insideAgentID] != off[insideAgentID] {+ t.Errorf(+ "an explicit match-none working filter changed the count: %d vs %d",+ matchNone[insideAgentID], off[insideAgentID],+ )+ }+ })++ t.Run("workspace scope still sees both agents", func(t *testing.T) {+ counts := workingAgentsFacetCounts(t, workingAgentsFacetRequest(+ map[string]any{"kind": "workspace"}, nil,+ ))+ if counts[insideAgentID] != 3 || counts[outsideAgentID] != 1 {+ t.Errorf(+ "workspace counts inside=%d outside=%d, want 3 and 1",+ counts[insideAgentID], counts[outsideAgentID],+ )+ }+ })+}++// The facet keys are agent ids, so it discloses agent identity and has to pass+// the same visibility gate as /api/working-agents: a plain member must not learn+// that someone else's private agent exists, not even as a count.+func TestIssueTableWorkingAgentsFacetHidesInaccessibleAgents(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }++ ctx := context.Background()+ privateAgentID, ownerID, plainMemberID := privateAgentTestFixture(t)++ var finalNumber int+ if err := testPool.QueryRow(ctx, `+ UPDATE workspace+ SET issue_counter = GREATEST(+ issue_counter,+ (SELECT COALESCE(MAX(number), 0) FROM issue WHERE workspace_id = $1)+ ) + 1+ WHERE id = $1+ RETURNING issue_counter+ `, testWorkspaceID).Scan(&finalNumber); err != nil {+ t.Fatalf("reserve issue numbers: %v", err)+ }++ var issueID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO issue (+ workspace_id, title, status, priority, creator_type, creator_id,+ position, number+ )+ VALUES ($1, 'worked on by a private agent', 'todo', 'none', 'member', $2, $3, $4)+ RETURNING id+ `, testWorkspaceID, testUserID, finalNumber, finalNumber).Scan(&issueID); err != nil {+ t.Fatalf("insert issue: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(context.Background(), `DELETE FROM issue WHERE id = $1`, issueID)+ })+ createHandlerTestTaskForAgentOnIssue(t, privateAgentID, issueID)++ facetRequest := func(userID string) *http.Request {+ request := workingAgentsFacetRequest(map[string]any{"kind": "workspace"}, nil)+ request.Header.Set("X-User-ID", userID)+ return request+ }++ if counts := workingAgentsFacetCounts(t, facetRequest(plainMemberID)); len(counts) != 0 {+ t.Errorf("plain member saw inaccessible agents: %v", counts)+ }+ if counts := workingAgentsFacetCounts(t, facetRequest(ownerID)); counts[privateAgentID] != 1 {+ t.Errorf("agent owner count = %d, want 1", counts[privateAgentID])+ }+}