Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-5200: unify working-agent filters across issue views (#5819)
Multica Eve423a5c59cb51
diff --git a/packages/core/agents/queries.ts b/packages/core/agents/queries.tsindex 882282c704..c63f4b4fc0 100644--- a/packages/core/agents/queries.ts+++ b/packages/core/agents/queries.ts@@ -1,11 +1,30 @@import { queryOptions } from "@tanstack/react-query";import { api } from "../api";+import type {+ WorkspaceWorkingAgentMineRelation,+ WorkspaceWorkingAgentType,+} from "../types";export const agentTaskSnapshotKeys = {all: (wsId: string) => ["workspaces", wsId, "agent-task-snapshot"] as const,list: (wsId: string) => [...agentTaskSnapshotKeys.all(wsId), "list"] as const,};+export const workspaceWorkingAgentsKeys = {+ all: (wsId: string) => ["workspaces", wsId, "working-agents"] as const,+ list: (+ wsId: string,+ type?: WorkspaceWorkingAgentType,+ mineRelation?: WorkspaceWorkingAgentMineRelation,+ ) =>+ [+ ...workspaceWorkingAgentsKeys.all(wsId),+ "list",+ type ?? "all",+ mineRelation ? `mine:${mineRelation}` : "workspace",+ ] as const,+};+export const agentActivityKeys = {all: (wsId: string) => ["workspaces", wsId, "agent-activity"] as const,last30d: (wsId: string) => [...agentActivityKeys.all(wsId), "30d"] as const,@@ -35,6 +54,23 @@ export function agentTaskSnapshotOptions(wsId: string) {});}+// Working-agent summaries, optionally narrowed to a My Issues relation. Task+// lifecycle WebSocket events invalidate every relation immediately; the short+// stale time is the reconnect / missed-event safety net.+export function workspaceWorkingAgentsOptions(+ wsId: string,+ type?: WorkspaceWorkingAgentType,+ mineRelation?: WorkspaceWorkingAgentMineRelation,+) {+ return queryOptions({+ queryKey: workspaceWorkingAgentsKeys.list(wsId, type, mineRelation),+ queryFn: () => api.getWorkspaceWorkingAgents(type, mineRelation),+ staleTime: 30 * 1000,+ gcTime: 5 * 60 * 1000,+ refetchOnWindowFocus: true,+ });+}+// Workspace-wide daily task activity for the last 30 days, anchored on// completed_at. One fetch backs both the Agents-list sparkline (which// only uses the trailing 7 buckets via `summarizeActivityWindow`) anddiff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.tsindex 0c8ed40fcb..bedec73f87 100644--- a/packages/core/api/client.test.ts+++ b/packages/core/api/client.test.ts@@ -331,6 +331,42 @@ describe("ApiClient issue move intent", () => {});});+describe("ApiClient workspace working agents", () => {+ it("supports an optional source-type filter", async () => {+ const payload = [+ {+ id: "agent-1",+ name: "Agent 1",+ avatar_url: null,+ running_task_count: 2,+ },+ ];+ const fetchMock = vi.fn().mockImplementation(() =>+ Promise.resolve(+ new Response(JSON.stringify(payload), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ }),+ ),+ );+ vi.stubGlobal("fetch", fetchMock);++ const client = new ApiClient("https://api.example.test");+ await expect(+ client.getWorkspaceWorkingAgents("issue", "assigned"),+ ).resolves.toEqual(payload);+ await expect(+ client.getWorkspaceWorkingAgents("issue"),+ ).resolves.toEqual(payload);+ await expect(client.getWorkspaceWorkingAgents()).resolves.toEqual(payload);+ expect(fetchMock.mock.calls.map(([url]) => url)).toEqual([+ "https://api.example.test/api/working-agents?type=issue&scope=mine&relation=assigned",+ "https://api.example.test/api/working-agents?type=issue",+ "https://api.example.test/api/working-agents",+ ]);+ });+});+describe("ApiClient label response schemas", () => {it("falls back safely for malformed label catalog, label, and resource responses", async () => {const fetchMock = vi.fn().mockImplementation(() =>diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex aa601e9527..9673a2fe28 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -33,6 +33,9 @@ import type {AgentTask,AgentActivityBucket,AgentRunCount,+ WorkspaceWorkingAgent,+ WorkspaceWorkingAgentMineRelation,+ WorkspaceWorkingAgentType,AgentRuntime,RuntimeProfile,CreateRuntimeProfileRequest,@@ -1683,6 +1686,24 @@ export class ApiClient {return this.fetch(`/api/agent-task-snapshot`);}+ // Independent workspace-level projection. Unlike the task snapshot, this+ // already deduplicates running agents and returns only the display fields+ // consumers need. Callers may narrow the projection by task source and, for+ // issue work, the authenticated member's My Issues relation.+ async getWorkspaceWorkingAgents(+ type?: WorkspaceWorkingAgentType,+ mineRelation?: WorkspaceWorkingAgentMineRelation,+ ): Promise<WorkspaceWorkingAgent[]> {+ const search = new URLSearchParams();+ if (type) search.set("type", type);+ if (mineRelation) {+ search.set("scope", "mine");+ search.set("relation", mineRelation);+ }+ const query = search.toString();+ return this.fetch(`/api/working-agents${query ? `?${query}` : ""}`);+ }+// Per-agent daily activity for the last 30 days, anchored on// completed_at. One workspace-wide fetch backs both the Agents-list// sparkline (uses trailing 7 buckets) and the agent detail "Last 30diff --git a/packages/core/issues/stores/my-issues-view-store.test.ts b/packages/core/issues/stores/my-issues-view-store.test.tsnew file mode 100644index 0000000000..21f2714b79--- /dev/null+++ b/packages/core/issues/stores/my-issues-view-store.test.ts@@ -0,0 +1,21 @@+// @vitest-environment jsdom++import { describe, expect, it } from "vitest";+import {+ myIssuesRelationFromScope,+ type MyIssuesScope,+} from "./my-issues-view-store";++describe("myIssuesRelationFromScope", () => {+ it.each([+ ["all", "all"],+ ["assigned", "assigned"],+ ["created", "created"],+ ["agents", "involved"],+ ] satisfies Array<[MyIssuesScope, string]>)(+ "maps %s to the surface relation %s",+ (scope, relation) => {+ expect(myIssuesRelationFromScope(scope)).toBe(relation);+ },+ );+});diff --git a/packages/core/issues/stores/my-issues-view-store.ts b/packages/core/issues/stores/my-issues-view-store.tsindex e197af79da..a95976bbbb 100644--- a/packages/core/issues/stores/my-issues-view-store.ts+++ b/packages/core/issues/stores/my-issues-view-store.ts@@ -11,6 +11,16 @@ import {import { registerForWorkspaceRehydration } from "../../platform/workspace-storage";export type MyIssuesScope = "all" | "assigned" | "created" | "agents";+export type MyIssuesRelation = "all" | "assigned" | "created" | "involved";++// "agents" is the user-facing scope label; the issue APIs call the same+// ownership/squad-membership relation "involved".+export function myIssuesRelationFromScope(+ scope: MyIssuesScope,+): MyIssuesRelation {+ if (scope === "agents") return "involved";+ return scope;+}export interface MyIssuesViewState extends IssueViewState {scope: MyIssuesScope;diff --git a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsxindex dbf5b3e1fa..27b1beb9ce 100644--- a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx+++ b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx@@ -8,6 +8,7 @@ import { describe, expect, it, vi, beforeEach, afterEach } from "vitest";import type { WSClient } from "../api/ws-client";import { defaultStorage } from "../platform/storage";import { issueKeys } from "../issues/queries";+import { workspaceWorkingAgentsKeys } from "../agents/queries";import { workspaceKeys } from "../workspace/queries";import {markWorkspaceDeletePending,@@ -110,9 +111,10 @@ describe("useRealtimeSync — ws instance change", () => {// Should have called invalidateQueries for all workspace-scoped keys// (16 workspace-scoped [incl. property definitions] + 6 per-issue- // prefixes + 5 per-chat prefixes + 1 workspaceKeys.list() + 1- // cross-workspace inbox unread summary = 29 calls)- expect(invalidateSpy).toHaveBeenCalledTimes(29);+ // prefixes + the workspace working-agents projection + 5 per-chat+ // prefixes + 1 workspaceKeys.list() + 1 cross-workspace inbox unread+ // summary = 30 calls)+ expect(invalidateSpy).toHaveBeenCalledTimes(30);});it("does not re-invalidate when rerendered with the same ws instance", () => {@@ -225,6 +227,9 @@ describe("useRealtimeSync — Table server membership invalidation", () => {expect(invalidate).toHaveBeenCalledWith({queryKey: issueKeys.tableAll("ws-1"),});+ expect(invalidate).toHaveBeenCalledWith({+ queryKey: workspaceWorkingAgentsKeys.all("ws-1"),+ });});it("invalidates Table queries after a property definition changes", () => {diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.tsindex a40533c416..b360872b0a 100644--- a/packages/core/realtime/use-realtime-sync.ts+++ b/packages/core/realtime/use-realtime-sync.ts@@ -18,6 +18,7 @@ import { labelKeys } from "../labels/queries";import { propertyKeys } from "../properties/queries";import {agentTaskSnapshotKeys,+ workspaceWorkingAgentsKeys,agentActivityKeys,agentRunCountsKeys,agentTasksKeys,@@ -494,6 +495,7 @@ function invalidateWorkspaceScopedQueries(qc: QueryClient): void {qc.invalidateQueries({ queryKey: runtimeKeys.all(wsId) });qc.invalidateQueries({ queryKey: autopilotKeys.all(wsId) });qc.invalidateQueries({ queryKey: agentTaskSnapshotKeys.all(wsId) });+ qc.invalidateQueries({ queryKey: workspaceWorkingAgentsKeys.all(wsId) });qc.invalidateQueries({ queryKey: agentActivityKeys.all(wsId) });qc.invalidateQueries({ queryKey: agentRunCountsKeys.all(wsId) });qc.invalidateQueries({ queryKey: chatKeys.all(wsId) });@@ -601,6 +603,7 @@ export function useRealtimeSync(const wsId = getCurrentWsId();if (wsId) {qc.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) });+ qc.invalidateQueries({ queryKey: workspaceWorkingAgentsKeys.all(wsId) });// Squad members status is derived per agent, so any agent// change (status flip, archive, runtime swap) needs to refresh the// per-squad members-status cache without refetching the static squad@@ -695,10 +698,11 @@ export function useRealtimeSync(const wsId = getCurrentWsId();if (!wsId) return;qc.invalidateQueries({ queryKey: agentTaskSnapshotKeys.list(wsId) });- // Table's working_only predicate is evaluated from task lifecycle- // state on the server. Without invalidating its server-owned graph,- // rows/groups/facets can remain permanently stale (global staleTime- // is Infinity) after a task starts or reaches a terminal state.+ qc.invalidateQueries({ queryKey: workspaceWorkingAgentsKeys.all(wsId) });+ // The Table working-agent shortcut derives an assignee set from the+ // projection above. Refresh its server-owned graph alongside that set+ // so rows/groups/facets cannot remain on an old task transition while+ // the projection refetches (global staleTime is Infinity).qc.invalidateQueries({ queryKey: issueKeys.tableAll(wsId) });// 30d activity series shares the same lifecycle signal — any task// completion / failure shifts the histogram. (Dispatch alonediff --git a/packages/core/types/agent.ts b/packages/core/types/agent.tsindex 5ada701a04..3aac724ac0 100644--- a/packages/core/types/agent.ts+++ b/packages/core/types/agent.ts@@ -198,6 +198,24 @@ export interface AgentRunCount {run_count: number;}+// Privacy-safe display summary returned by GET /api/working-agents. The+// endpoint is workspace-scoped and includes each user-authored agent with at+// least one running task exactly once.+export interface WorkspaceWorkingAgent {+ id: string;+ name: string;+ avatar_url: string | null;+ running_task_count: number;+}++export type WorkspaceWorkingAgentType = "issue" | "autopilot" | "chat";++export type WorkspaceWorkingAgentMineRelation =+ | "assigned"+ | "created"+ | "involved"+ | "any";+/*** A departed-member-safe user ref resolved from the global user table. `name` /* `email` / `avatar_url` are absent until the server hydrates them (present ondiff --git a/packages/core/types/index.ts b/packages/core/types/index.tsindex 7c1dd86015..21dd7edd4b 100644--- a/packages/core/types/index.ts+++ b/packages/core/types/index.ts@@ -13,6 +13,9 @@ export type {TaskEvidence,AgentActivityBucket,AgentRunCount,+ WorkspaceWorkingAgent,+ WorkspaceWorkingAgentType,+ WorkspaceWorkingAgentMineRelation,TaskFailureReason,AgentRuntime,RuntimeDevice,diff --git a/packages/views/issues/components/issues-header.tsx b/packages/views/issues/components/issues-header.tsxindex f0eb461ece..b35c7fe4d4 100644--- a/packages/views/issues/components/issues-header.tsx+++ b/packages/views/issues/components/issues-header.tsx@@ -794,7 +794,6 @@ export function ViewRefreshIndicator({ active }: { active: boolean }) {export function IssuesHeader({scopedIssues,- workingIssues,allowGantt = false,dateFilter = null,onDateFilterChange,@@ -804,10 +803,6 @@ export function IssuesHeader({onTableFacetChange,}: {scopedIssues: Issue[];- /** The rows the agents-working filter would leave on screen — undefined- * when the set is unknown (chip renders indeterminate). Scopes the chip:- * it counts the agents working on these rows. */- workingIssues: Issue[] | undefined;allowGantt?: boolean;dateFilter?: IssueDateFilter | null;onDateFilterChange?: (filter: IssueDateFilter | null) => void;@@ -902,7 +897,6 @@ export function IssuesHeader({<WorkspaceAgentWorkingChipvalue={agentRunningFilter}onToggle={toggleAgentRunningFilter}- workingIssues={workingIssues}/><IssueDisplayControlsscopedIssues={scopedIssues}diff --git a/packages/views/issues/components/issues-page.tsx b/packages/views/issues/components/issues-page.tsxindex 8c16f40023..137eccb7f0 100644--- a/packages/views/issues/components/issues-page.tsx+++ b/packages/views/issues/components/issues-page.tsx@@ -15,14 +15,12 @@ import { IssuesHeader } from "./issues-header";function IssuesSurfaceHeader({issues,- workingIssues,isRefreshing,facetCountsExact,tableFacetCounts,onTableFacetChange,}: {issues: Issue[];- workingIssues: Issue[] | undefined;isRefreshing: boolean;facetCountsExact: boolean;tableFacetCounts?: IssueTableFacetsResponse;@@ -34,7 +32,6 @@ function IssuesSurfaceHeader({return (<IssuesHeaderscopedIssues={issues}- workingIssues={workingIssues}dateFilter={dateFilter}onDateFilterChange={setDateFilter}isRefreshing={isRefreshing}@@ -60,10 +57,9 @@ export function IssuesPage() {scope={{ type: "workspace", actorKind: scope }}modes={["board", "list", "table", "swimlane"]}batchToolbar="list"- renderHeader={({ controller, workingIssues }) => (+ renderHeader={({ controller }) => (<IssuesSurfaceHeaderissues={controller.surfaceIssues}- workingIssues={workingIssues}isRefreshing={controller.isRefreshing}facetCountsExact={controller.facetCountsExact}tableFacetCounts={controller.tableFacetCounts}diff --git a/packages/views/issues/components/swimlane-view.test.tsx b/packages/views/issues/components/swimlane-view.test.tsxindex 12d355e4a7..7265af8e23 100644--- a/packages/views/issues/components/swimlane-view.test.tsx+++ b/packages/views/issues/components/swimlane-view.test.tsx@@ -1775,7 +1775,6 @@ describe("SwimLaneView", () => {projectFilters: [],includeNoProject: false,labelFilters: [],- agentRunningFilter: false,}}childProgressMap={childProgressMap}onMoveIssue={vi.fn()}@@ -1792,7 +1791,7 @@ describe("SwimLaneView", () => {});});- it("filters batch-fetched children using working filter", async () => {+ it("filters batch-fetched children using API-derived working assignees", async () => {mockViewState.swimlaneGrouping = "parent";const grandparent: Issue = {@@ -1835,6 +1834,8 @@ describe("SwimLaneView", () => {identifier: "PROJ-32",title: "Running Child",status: "in_progress",+ assignee_type: "agent",+ assignee_id: "working-agent",parent_issue_id: "p-3",position: 12,};@@ -1845,14 +1846,12 @@ describe("SwimLaneView", () => {identifier: "PROJ-33",title: "Non-running Child",status: "in_progress",+ assignee_type: "agent",+ assignee_id: "idle-agent",parent_issue_id: "p-3",position: 13,};- mockGetAgentTaskSnapshot.mockResolvedValueOnce([- { id: "task-1", status: "running", issue_id: "gc-running" },- ]);-mockListChildrenByParents.mockResolvedValueOnce({issues: [runningGrandchild, nonRunningGrandchild],});@@ -1866,13 +1865,12 @@ describe("SwimLaneView", () => {issues={[grandparent, parent]}activeFilters={{priorityFilters: [],- assigneeFilters: [],+ assigneeFilters: [{ type: "agent", id: "working-agent" }],includeNoAssignee: false,creatorFilters: [],projectFilters: [],includeNoProject: false,labelFilters: [],- agentRunningFilter: true,}}childProgressMap={childProgressMap}onMoveIssue={vi.fn()}@@ -1889,6 +1887,47 @@ describe("SwimLaneView", () => {});});+ it("hides batch-fetched children for an explicitly empty working-assignee predicate", async () => {+ mockViewState.swimlaneGrouping = "parent";+ const parent = mockIssues[0]!;+ const batchOnlyChild: Issue = {+ ...mockIssues[1]!,+ id: "working-empty-child",+ identifier: "PROJ-34",+ title: "Working Empty Child",+ parent_issue_id: parent.id,+ };+ mockListChildrenByParents.mockResolvedValueOnce({+ issues: [batchOnlyChild],+ });++ renderWithI18n(+ <SwimLaneView+ issues={[parent]}+ activeFilters={{+ priorityFilters: [],+ assigneeFilters: [],+ includeNoAssignee: false,+ assigneeFilterActive: true,+ creatorFilters: [],+ projectFilters: [],+ includeNoProject: false,+ labelFilters: [],+ }}+ childProgressMap={+ new Map([[parent.id, { done: 0, total: 1 }]])+ }+ onMoveIssue={vi.fn()}+ />,+ );++ await waitFor(() => {+ expect(mockListChildrenByParents).toHaveBeenCalled();+ });+ await act(async () => {});+ expect(screen.queryByText("Working Empty Child")).toBeNull();+ });+it("hides batch-fetched children when 'Show sub-issues' is off", async () => {mockViewState.swimlaneGrouping = "parent";@@ -1955,7 +1994,6 @@ describe("SwimLaneView", () => {projectFilters: [],includeNoProject: false,labelFilters: [],- agentRunningFilter: false,showSubIssues: false,}}childProgressMap={childProgressMap}diff --git a/packages/views/issues/components/swimlane-view.tsx b/packages/views/issues/components/swimlane-view.tsxindex a269b486b1..27f7afeece 100644--- a/packages/views/issues/components/swimlane-view.tsx+++ b/packages/views/issues/components/swimlane-view.tsx@@ -29,7 +29,6 @@ import type {UpdateIssueRequest,} from "@multica/core/types";import { useViewStore, useViewStoreApi } from "@multica/core/issues/stores/view-store-context";-import { agentTaskSnapshotOptions } from "@multica/core/agents";import { filterIssues, type IssueFilters } from "../utils/filter";import { getMoveAnchors } from "../utils/drag-utils";import type { SwimlaneGrouping } from "@multica/core/issues/stores/view-store";@@ -62,7 +61,6 @@ import { useRestoredScrollOffset, useRestoredScrollRef } from "../../platform";import { DeferredTooltip } from "../../common/deferred-tooltip";import type { ChildProgress } from "./list-row";import { useT } from "../../i18n";-import type { IssueActivityState } from "../surface/activity";import type { IssueCreateDefaults } from "../surface/types";import type {IssueGroupBranches,@@ -614,7 +612,6 @@ function SwimLaneViewImpl({myIssuesFilter,sort,projectId,- activityByIssueId,onCreateIssue,groupBranches,}: {@@ -628,7 +625,10 @@ function SwimLaneViewImpl({* a parent in a hidden status still surfaces its label correctly.*/unfilteredIssues?: Issue[];- activeFilters?: Omit<IssueFilters, "statusFilters" | "runningIssueIds">;+ activeFilters?: Omit<+ IssueFilters,+ "statusFilters" | "agentRunningFilter" | "runningIssueIds"+ >;visibleStatuses?: IssueStatus[];hiddenStatuses?: IssueStatus[];onMoveIssue: (@@ -644,7 +644,6 @@ function SwimLaneViewImpl({sort?: IssueSortParam;/** Pre-fills `project_id` on the create form for the in-cell "+" button. */projectId?: string;- activityByIssueId?: ReadonlyMap<string, IssueActivityState>;onCreateIssue?: (defaults: IssueCreateDefaults) => void;groupBranches?: IssueGroupBranches;}) {@@ -659,42 +658,24 @@ function SwimLaneViewImpl({const wsId = useWorkspaceId();- const { data: snapshot = [] } = useQuery({- ...agentTaskSnapshotOptions(wsId),- enabled: !activityByIssueId,- });- const runningIssueIds = useMemo(() => {- if (activityByIssueId) {- const ids = new Set<string>();- for (const [issueId, activity] of activityByIssueId) {- if (activity.isWorking) ids.add(issueId);- }- return ids;- }- const ids = new Set<string>();- for (const t of snapshot) {- if (t.status === "running" && t.issue_id) ids.add(t.issue_id);- }- return ids;- }, [activityByIssueId, snapshot]);-const activeFilters = useMemo(() => ({// Status is enforced by visible-column rendering, not by filterIssuesstatusFilters: [],priorityFilters: activeFiltersProp?.priorityFilters ?? [],+ // The controller has already projected `/api/working-agents` into this+ // assignee list, so extra children use the same membership as Table.assigneeFilters: activeFiltersProp?.assigneeFilters ?? [],includeNoAssignee: activeFiltersProp?.includeNoAssignee ?? false,+ assigneeFilterActive: activeFiltersProp?.assigneeFilterActive ?? false,creatorFilters: activeFiltersProp?.creatorFilters ?? [],projectFilters: activeFiltersProp?.projectFilters ?? [],includeNoProject: activeFiltersProp?.includeNoProject ?? false,labelFilters: activeFiltersProp?.labelFilters ?? [],- agentRunningFilter: activeFiltersProp?.agentRunningFilter ?? false,- runningIssueIds,// Carry the "Show sub-issues" toggle through to the extra-children merge// path (see `filterIssues(extra, activeFilters)` below); otherwise batch /// per-parent loaded sub-issues get re-added even when the toggle is off.showSubIssues: activeFiltersProp?.showSubIssues ?? true,- }), [activeFiltersProp, runningIssueIds]);+ }), [activeFiltersProp]);const projects = useMemo(() =>swimlaneGrouping === "project" && projectMapdiff --git a/packages/views/issues/components/workspace-agent-working-chip.test.tsx b/packages/views/issues/components/workspace-agent-working-chip.test.tsxindex d32ddf5c56..09ee5d4d1e 100644--- a/packages/views/issues/components/workspace-agent-working-chip.test.tsx+++ b/packages/views/issues/components/workspace-agent-working-chip.test.tsx@@ -2,20 +2,15 @@import { cleanup, screen } from "@testing-library/react";import { beforeEach, describe, expect, it, vi } from "vitest";-import type { AgentTask, Issue } from "@multica/core/types";+import type { WorkspaceWorkingAgent } from "@multica/core/types";import { renderWithI18n } from "../../test/i18n";const mockState = vi.hoisted(() => ({- snapshot: [] as unknown[],- // Captures what the chip hands its children so a test can assert the- // avatar stack, the hover card and the colour tier without reaching into- // their internals.- avatarAgentIds: undefined as string[] | undefined,- avatarOverflow: undefined as string | undefined,+ agents: [] as WorkspaceWorkingAgent[],+ requestedType: undefined as string | undefined,+ requestedMineRelation: undefined as string | undefined,+ avatarAgentIds: undefined as readonly string[] | undefined,buttonVariant: undefined as string | undefined,- hoverProps: undefined as- | { issues: readonly Issue[]; taskCount: number }- | undefined,}));vi.mock("@multica/core/hooks", () => ({@@ -23,63 +18,54 @@ vi.mock("@multica/core/hooks", () => ({}));vi.mock("@multica/core/agents", () => ({- agentTaskSnapshotOptions: (wsId: string) => ({- queryKey: ["agents", "task-snapshot", wsId],- }),+ 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("../../agents/components/agent-avatar-stack", () => ({- AgentAvatarStack: ({- agentIds,- overflow,- }: {- agentIds: string[];- overflow?: string;- }) => {+ AgentAvatarStack: ({ agentIds }: { agentIds: readonly string[] }) => {mockState.avatarAgentIds = agentIds;- mockState.avatarOverflow = overflow;return <div data-testid="agent-avatar-stack">{agentIds.length}</div>;},}));-vi.mock("../../agents/components/agent-activity-hover-content", () => ({- WorkspaceAgentActivityHoverContent: (props: {- issues: readonly Issue[];- taskCount: number;- }) => {- mockState.hoverProps = props;- return <div data-testid="activity-hover">{props.taskCount}</div>;- },-}));--// Record the variant the chip picks. The colour tier lives entirely in the-// Button variant now, so this is the assertable surface.-vi.mock("@multica/ui/components/ui/button", async () => {+vi.mock("@tanstack/react-query", async () => {const actual =- await vi.importActual<typeof import("@multica/ui/components/ui/button")>(- "@multica/ui/components/ui/button",+ await vi.importActual<typeof import("@tanstack/react-query")>(+ "@tanstack/react-query",);return {...actual,- Button: (props: React.ComponentProps<typeof actual.Button>) => {- mockState.buttonVariant = props.variant ?? undefined;- return <actual.Button {...props} />;- },+ useQuery: () => ({ data: mockState.agents }),};});-vi.mock("@tanstack/react-query", async () => {+vi.mock("@multica/ui/components/ui/button", async () => {const actual =- await vi.importActual<typeof import("@tanstack/react-query")>(- "@tanstack/react-query",+ await vi.importActual<typeof import("@multica/ui/components/ui/button")>(+ "@multica/ui/components/ui/button",);return {...actual,- useQuery: (opts: { queryKey?: readonly unknown[] }) => {- if (opts.queryKey?.[1] === "task-snapshot") {- return { data: mockState.snapshot };- }- return { data: undefined };+ Button: (props: React.ComponentProps<typeof actual.Button>) => {+ mockState.buttonVariant = props.variant ?? undefined;+ return <actual.Button {...props} />;},};});@@ -87,282 +73,89 @@ vi.mock("@tanstack/react-query", async () => {import {WorkspaceAgentWorkingChip,chipAppearance,- deriveWorkingChipView,} from "./workspace-agent-working-chip";-function makeTask(overrides: Partial<AgentTask>): AgentTask {- return {- id: "task-1",- agent_id: "agent-1",- runtime_id: "runtime-1",- issue_id: "issue-1",- status: "running",- priority: 0,- dispatched_at: null,- started_at: "2026-06-08T08:00:00Z",- completed_at: null,- result: null,- error: null,- created_at: "2026-06-08T08:00:00Z",- ...overrides,- };-}--function makeIssue(id: string): Issue {+function makeAgent(+ id: string,+ runningTaskCount = 1,+): WorkspaceWorkingAgent {return {id,- workspace_id: "ws-1",- number: 1,- identifier: `MUL-${id}`,- title: `Issue ${id}`,- description: null,- status: "in_progress",- priority: "none",- assignee_type: null,- assignee_id: null,- creator_type: "member",- creator_id: "user-1",- parent_issue_id: null,- project_id: null,- position: 1,- stage: null,- start_date: null,- due_date: null,- metadata: {},- properties: {},- created_at: "2026-06-08T08:00:00Z",- updated_at: "2026-06-08T08:00:00Z",+ name: `Agent ${id}`,+ avatar_url: null,+ running_task_count: runningTaskCount,};}beforeEach(() => {cleanup();vi.clearAllMocks();- mockState.snapshot = [];+ mockState.agents = [];+ mockState.requestedType = undefined;+ mockState.requestedMineRelation = undefined;mockState.avatarAgentIds = undefined;- mockState.avatarOverflow = undefined;mockState.buttonVariant = undefined;- mockState.hoverProps = undefined;});describe("WorkspaceAgentWorkingChip", () => {- it("counts agents — the same list the avatar stack shows", () => {- // The screenshot case from MUL-4884: 4 running tasks, 4 distinct agents,- // 3 issues on screen. The chip counts the agents, so its number and the- // heads beside it are one unit and cannot contradict each other.- mockState.snapshot = [- makeTask({ id: "t-1", agent_id: "agent-1", issue_id: "issue-1" }),- makeTask({ id: "t-2", agent_id: "agent-2", issue_id: "issue-2" }),- makeTask({ id: "t-3", agent_id: "agent-3", issue_id: "issue-3" }),- makeTask({ id: "t-4", agent_id: "agent-4", issue_id: "issue-3" }),+ it("shows every agent returned by the independent workspace API", () => {+ mockState.agents = [+ makeAgent("agent-1"),+ makeAgent("agent-2", 3),+ makeAgent("agent-3"),];renderWithI18n(- <WorkspaceAgentWorkingChip- value={false}- onToggle={() => {}}- workingIssues={["issue-1", "issue-2", "issue-3"].map(makeIssue)}- />,+ <WorkspaceAgentWorkingChip value={false} onToggle={() => {}} />,);expect(- screen.getByRole("button", { name: "4 agents working" }),+ screen.getByRole("button", { name: "3 agents working" }),).toBeTruthy();expect(mockState.avatarAgentIds).toEqual(["agent-1","agent-2","agent-3",- "agent-4",]);- // Overflow is the component's standard +N badge again: with an- // agent-anchored number, "3 shown + 1 = 4" corroborates the text instead- // of competing with it.- expect(mockState.avatarOverflow).toBeUndefined();- });-- it("counts one agent once, however many issues it is working", () => {- // The accepted trade-off: the number no longer predicts the row count.- // One agent across two issues reads "1 agent working" and opens 2 rows —- // WHO vs WHERE, different questions.- mockState.snapshot = [- makeTask({ id: "t-1", agent_id: "agent-1", issue_id: "issue-1" }),- makeTask({ id: "t-2", agent_id: "agent-1", issue_id: "issue-2" }),- ];-- renderWithI18n(- <WorkspaceAgentWorkingChip- value- onToggle={() => {}}- workingIssues={["issue-1", "issue-2"].map(makeIssue)}- />,- );-- expect(- screen.getByRole("button", { name: "1 agent working" }),- ).toBeTruthy();+ expect(mockState.requestedType).toBe("issue");+ expect(mockState.requestedMineRelation).toBeUndefined();+ expect(mockState.buttonVariant).toBe("brandSubtle");});- it("renders an indeterminate state when the scope is unknown, never a number", () => {- // 3 agents ARE running workspace-wide, but the surface could not resolve- // which of them belong to the current window (table window resolving /- // failed / too large). Publishing any count here — 0 from an empty- // fallback or 3 from the workspace — would be a precise-looking wrong- // answer (round-5 review P2). The chip must say "unknown" instead.- mockState.snapshot = [- makeTask({ id: "t-1", agent_id: "agent-1", issue_id: "issue-1" }),- makeTask({ id: "t-2", agent_id: "agent-2", issue_id: "issue-2" }),- makeTask({ id: "t-3", agent_id: "agent-3", issue_id: "issue-3" }),- ];-+ it("requests the selected My Issues relation when the header is scoped", () => {renderWithI18n(<WorkspaceAgentWorkingChipvalue={false}onToggle={() => {}}- workingIssues={undefined}+ mineRelation="involved"/>,);- expect(- screen.getByRole("button", { name: "Agents working: —" }),- ).toBeTruthy();- // No avatar stack: heads next to an unknown label would still read as a- // claim about who is in scope.- expect(mockState.avatarAgentIds).toBeUndefined();+ expect(mockState.requestedType).toBe("issue");+ expect(mockState.requestedMineRelation).toBe("involved");});- it("shows 0 when nothing is running", () => {- mockState.snapshot = [];-+ it("shows a known zero instead of an indeterminate Table value", () => {renderWithI18n(- <WorkspaceAgentWorkingChip- value={false}- onToggle={() => {}}- workingIssues={[]}- />,+ <WorkspaceAgentWorkingChip value={false} onToggle={() => {}} />,);expect(screen.getByRole("button", { name: "0 agents working" }),).toBeTruthy();expect(screen.queryByTestId("agent-avatar-stack")).toBeNull();- });-- // Colour is carried by three self-contained Button variants. The tier- // rules are unit-tested against `chipAppearance` below; these two cover- // the wiring.- it("uses the filled brand variant only while the filter is on", () => {- mockState.snapshot = [makeTask({ id: "t-1", issue_id: "issue-1" })];-- const { rerender } = renderWithI18n(- <WorkspaceAgentWorkingChip- value={false}- onToggle={() => {}}- workingIssues={[makeIssue("issue-1")]}- />,- );-- // Activity, filter off → the tint variant.- expect(mockState.buttonVariant).toBe("brandSubtle");-- rerender(- <WorkspaceAgentWorkingChip- value- onToggle={() => {}}- workingIssues={[makeIssue("issue-1")]}- />,- );-- expect(mockState.buttonVariant).toBe("brand");- });-- it("stays a plain control when nothing is running", () => {- mockState.snapshot = [];-- renderWithI18n(- <WorkspaceAgentWorkingChip- value={false}- onToggle={() => {}}- workingIssues={[]}- />,- );-expect(mockState.buttonVariant).toBe("outline");});- it("keeps issue-less tasks out of the agent count", () => {- // Chat / autopilot tasks carry issue_id === "" (core/types/agent.ts).- // Their agents are not working on any issue, so they must not join the- // count or the stack.- mockState.snapshot = [- makeTask({ id: "t-1", agent_id: "agent-1", issue_id: "issue-1" }),- makeTask({ id: "t-2", agent_id: "agent-2", issue_id: "" }),- makeTask({ id: "t-3", agent_id: "agent-3", issue_id: "" }),- ];-+ it("keeps the active filter visually selected after the final agent stops", () => {renderWithI18n(- <WorkspaceAgentWorkingChip- value={false}- onToggle={() => {}}- workingIssues={[makeIssue("issue-1")]}- />,- );-- expect(- screen.getByRole("button", { name: "1 agent working" }),- ).toBeTruthy();- expect(mockState.avatarAgentIds).toEqual(["agent-1"]);- });-});--describe("deriveWorkingChipView", () => {- it("counts only running tasks whose issue is on screen", () => {- const view = deriveWorkingChipView(- [- makeTask({ id: "t-1", agent_id: "a1", issue_id: "issue-1" }),- makeTask({ id: "t-2", agent_id: "a2", issue_id: "issue-1" }),- // chat/autopilot run — no linked issue- makeTask({ id: "t-3", agent_id: "a3", issue_id: "" }),- // running, but its issue is filtered out / past the loaded page- makeTask({ id: "t-4", agent_id: "a4", issue_id: "issue-offscreen" }),- makeTask({- id: "t-5",- agent_id: "a5",- issue_id: "issue-1",- status: "queued",- }),- ],- [makeIssue("issue-1")],+ <WorkspaceAgentWorkingChip value onToggle={() => {}} />,);- expect(view.agentIds).toEqual(["a1", "a2"]);- expect(view.taskCount).toBe(2);- expect(view.tasksByIssueId.get("issue-1")?.map((t) => t.id)).toEqual([- "t-1",- "t-2",- ]);- });-- it("dedupes agents that run several tasks at once", () => {- const view = deriveWorkingChipView(- [- makeTask({ id: "t-1", agent_id: "a1", issue_id: "issue-1" }),- makeTask({ id: "t-2", agent_id: "a1", issue_id: "issue-2" }),- ],- [makeIssue("issue-1"), makeIssue("issue-2")],- );-- // Two issues, two tasks, but one agent — this is the number the chip- // shows.- expect(view.agentIds).toEqual(["a1"]);- expect(view.taskCount).toBe(2);+ expect(mockState.buttonVariant).toBe("brand");});});-// The chip's colour must come from its Button variant and nothing else. A-// colour class in `className` is appended AFTER the variant, so-// tailwind-merge keeps it and it beats the variant — the opposite of what-// "the variant owns the colour" implies. These pin the tier rules including-// the state that already got this wrong.describe("chipAppearance", () => {it("wears the filled brand tier while the filter is on", () => {expect(chipAppearance(true, true).variant).toBe("brand");@@ -373,25 +166,14 @@ describe("chipAppearance", () => {});it("wears the plain tier with muted text when nothing is running", () => {- const a = chipAppearance(false, false);- expect(a.variant).toBe("outline");- // `outline` sets no text colour, so this tier supplies its own.- expect(a.className).toContain("text-muted-foreground");- });-- it("does not mute the text when the filter is on with 0 agents", () => {- // Real state: the filter stays on after the last agent finishes. The- // variant is `brand` here, so appending `text-muted-foreground` would- // WIN over the variant's `text-brand-foreground` and paint grey text on- // a brand-blue fill.- const a = chipAppearance(true, false);- expect(a.variant).toBe("brand");- expect(a.className).not.toContain("text-muted-foreground");+ const appearance = chipAppearance(false, false);+ expect(appearance.variant).toBe("outline");+ expect(appearance.className).toContain("text-muted-foreground");});- it("never carries a colour class for either brand tier", () => {- for (const a of [chipAppearance(true, true), chipAppearance(false, true)]) {- expect(a.className).not.toMatch(/(^|\s)(text|bg|border)-/);- }+ it("does not mute the active zero state", () => {+ const appearance = chipAppearance(true, false);+ 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 e88347620c..e38fd8953d 100644--- a/packages/views/issues/components/workspace-agent-working-chip.tsx+++ b/packages/views/issues/components/workspace-agent-working-chip.tsx@@ -1,110 +1,32 @@"use client";-import { useMemo } from "react";import { useQuery } from "@tanstack/react-query";+import { ActorAvatar } from "@multica/ui/components/common/actor-avatar";import { Button } from "@multica/ui/components/ui/button";import {HoverCard,- HoverCardTrigger,HoverCardContent,+ HoverCardTrigger,} from "@multica/ui/components/ui/hover-card";+import { workspaceWorkingAgentsOptions } from "@multica/core/agents";import { useWorkspaceId } from "@multica/core/hooks";-import { agentTaskSnapshotOptions } from "@multica/core/agents";-import type { AgentTask, Issue } from "@multica/core/types";+import type {+ WorkspaceWorkingAgent,+ WorkspaceWorkingAgentMineRelation,+} from "@multica/core/types";import { AgentAvatarStack } from "../../agents/components/agent-avatar-stack";-import { WorkspaceAgentActivityHoverContent } from "../../agents/components/agent-activity-hover-content";import { useT } from "../../i18n";interface WorkspaceAgentWorkingChipProps {- // Controlled toggle binding. Different surfaces (Issues page singleton- // hook, My Issues vanilla store) own the underlying state, so the chip- // stays presentational and accepts both forms via plain props.value: boolean;onToggle: () => void;- // The rows this filter leaves on screen, computed by the surface from the- // same pipeline that renders them (see `workingScopeIssues`).- //- // The chip does not count these — it counts the agents working ON them. The- // list decides WHICH agents count: an agent whose only running task sits on- // an issue this filter would hide is not part of the number. Taking scope- // from the render pipeline instead of re-deriving it from the task snapshot- // is what keeps that judgement in step with the list (MUL-4884).- //- // `undefined` means the scope is UNKNOWN. Table deliberately does not- // materialize all cursor branches just to derive this decoration, so the- // chip shows an indeterminate "—" while the toggle remains available.- workingIssues: readonly Issue[] | undefined;-}--export interface WorkingChipView {- /** Running tasks on `workingIssues`, keyed by issue id. */- tasksByIssueId: Map<string, AgentTask[]>;- /** Distinct agents behind the counted work. This IS the chip's number,- * and the avatar stack renders the same list. */- agentIds: string[];- /** Total running tasks across the counted issues — the hover card's- * second figure. */- taskCount: number;-}--/**- * Bucket the workspace task snapshot against the issues the filter would- * show. Exported for tests: the counting rule is the entire point of this- * component, so it is a pure function rather than a hook-bound useMemo.- *- * A running task only counts when its issue is on screen. Two kinds are- * skipped, both silently — they have no visual presence on this page, so- * announcing them would explain an absence the user never noticed:- * - no `issue_id` — chat/autopilot runs, which are not issue work at all- * - issue not on screen — filtered out, or past the page the list loaded- *- * `issue_id` is an EMPTY STRING for chat/autopilot tasks, not null — see- * packages/core/types/agent.ts. The guard is data correctness, not- * presentation: without it those tasks collapse into one `""` bucket and- * their agents would join the count for work that isn't on any issue- * (MUL-4884). Mirrors `deriveIssueSurfaceActivity`.- */-export function deriveWorkingChipView(- snapshot: readonly AgentTask[],- workingIssues: readonly Issue[],-): WorkingChipView {- const onScreen = new Set(workingIssues.map((issue) => issue.id));- const tasksByIssueId = new Map<string, AgentTask[]>();- const agentIds: string[] = [];- const seenAgents = new Set<string>();- let taskCount = 0;-- for (const task of snapshot) {- if (task.status !== "running") continue;- if (!task.issue_id) continue;- if (!onScreen.has(task.issue_id)) continue;- const bucket = tasksByIssueId.get(task.issue_id);- if (bucket) bucket.push(task);- else tasksByIssueId.set(task.issue_id, [task]);- taskCount += 1;- if (!seenAgents.has(task.agent_id)) {- seenAgents.add(task.agent_id);- agentIds.push(task.agent_id);- }- }-- return { tasksByIssueId, agentIds, taskCount };+ mineRelation?: WorkspaceWorkingAgentMineRelation;}/*** Which colour tier the chip wears, and the only classes allowed alongside- * it. Exported so the tier rules are testable without a DOM.- *- * The tier lives entirely in the Button variant. `className` carries layout- * only — with ONE exception: the idle tier needs muted text, which `outline`- * does not set. That exception is gated on `!value`, and the gate matters:- * `filter ON + 0 agents` is a real state (the filter stays on after the last- * agent finishes), and there the variant is `brand`. Appending- * `text-muted-foreground` there does not lose to the variant — it WINS, because- * tailwind-merge keeps the last class in a group and `className` is appended- * after the variant. The result would be muted grey text on a brand-blue- * fill. Colour classes in `className` are how this component keeps breaking;- * the safe rule is that a tier's colours only ever come from its variant.+ * it. Activity uses a tint, the active filter uses the filled brand tier,+ * and an idle workspace stays neutral.*/export function chipAppearance(value: boolean,@@ -116,59 +38,77 @@ export function chipAppearance(return { variant: "outline", className: `${layout} text-muted-foreground` };}+function WorkingAgentsHoverContent({+ agents,+}: {+ agents: readonly WorkspaceWorkingAgent[];+}) {+ const { t } = useT("issues");++ if (agents.length === 0) {+ return (+ <p className="text-xs text-muted-foreground">+ {t(($) => $.agent_activity.empty_hover)}+ </p>+ );+ }++ return (+ <div className="flex flex-col gap-2">+ <div className="text-xs font-medium text-muted-foreground">+ {t(($) => $.agent_activity.hover_header, { count: agents.length })}+ </div>+ <div className="flex flex-col gap-1.5">+ {agents.map((agent) => (+ <div key={agent.id} className="flex items-center gap-2 text-xs">+ <ActorAvatar+ name={agent.name}+ initials={agent.name.trim().slice(0, 2).toUpperCase()}+ avatarUrl={agent.avatar_url ?? undefined}+ isAgent+ size="sm"+ />+ <span className="min-w-0 flex-1 truncate font-medium">+ {agent.name}+ </span>+ <span className="shrink-0 tabular-nums text-muted-foreground">+ {t(($) => $.agent_activity.tasks_count, {+ count: agent.running_task_count,+ })}+ </span>+ </div>+ ))}+ </div>+ </div>+ );+}+/**- * Filter chip on the issues / my-issues header, sitting to the left of the- * Filter button. Always rendered so the filter toggle never disappears- * mid-flight (a previous design hid the chip when no agents were running,- * which trapped users in an active-but-invisible filter state).- *- * It says one thing: "N agents working". The number counts agents, which is- * exactly what the avatar stack next to it shows — one control, one unit.- * Earlier versions counted issues (or tasks) beside a stack of agent heads,- * and two units sitting side by side is what made the chip read as broken- * no matter which one was "right" (MUL-4884).+ * Workspace-wide agents-working filter chip.*- * Counting agents also settles the subject: only agents produce a runtime- * signal, so "N agents working" cannot be misread as "N issues someone is- * working on" — human work has no signal here and is not being claimed.- *- * Accepted trade-off: the number no longer predicts the row count of the- * click. One agent on two issues reads "1 agent working" and opens two- * rows. The chip answers WHO, the list answers WHERE — different questions,- * so the two numbers do not compete; the hover card's issue grouping shows- * the mapping on the spot.- *- * Colour is three-tier and each tier is its own Button variant rather than- * classes layered over `outline` — see the `brand` / `brandSubtle` variants- * for why layering silently loses in dark mode.+ * 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.*/export function WorkspaceAgentWorkingChip({value,onToggle,- workingIssues,+ mineRelation,}: WorkspaceAgentWorkingChipProps) {const { t } = useT("issues");const wsId = useWorkspaceId();- const { data: snapshot = [] } = useQuery(agentTaskSnapshotOptions(wsId));-- const scopeKnown = workingIssues !== undefined;- const view = useMemo(- () => deriveWorkingChipView(snapshot, workingIssues ?? []),- [snapshot, workingIssues],+ const { data: agents = [] } = useQuery(+ workspaceWorkingAgentsOptions(wsId, "issue", mineRelation),);-- // The number and the avatar stack are the same list, so they cannot- // disagree.- const agentCount = view.agentIds.length;- const hasAgents = scopeKnown && agentCount > 0;-- const label = scopeKnown- ? t(($) => $.agent_activity.chip_agents_working, { count: agentCount })- : t(($) => $.agent_activity.chip_agents_working_unknown);-- // Three tiers: filter ON is the loud filled state, activity without the- // filter is a tint, nothing running is a plain control. An unknown scope- // uses the plain tier — it makes no activity claim to colour by.+ 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 trigger = (@@ -178,34 +118,19 @@ export function WorkspaceAgentWorkingChip({className={appearance.className}onClick={onToggle}aria-pressed={value}- // The narrow layout shows the bare number, so pin the full- // sentence as the accessible name in every layout.aria-label={label}>- {hasAgents && (- <AgentAvatarStack agentIds={view.agentIds} size="sm" max={3} />- )}- <span className="tabular-nums md:hidden">- {scopeKnown ? agentCount : "—"}- </span>+ {hasAgents && <AgentAvatarStack agentIds={agentIds} size="sm" max={3} />}+ <span className="tabular-nums md:hidden">{agentCount}</span><span className="hidden tabular-nums md:inline">{label}</span></Button>);- // No hover card while the scope is unknown: there is no issue list to- // show, and an empty card would read as "nothing running" — the exact- // claim the unknown state exists to avoid.- if (!scopeKnown) return trigger;-return (<HoverCard><HoverCardTrigger render={trigger} />- <HoverCardContent align="end" className="w-80">- <WorkspaceAgentActivityHoverContent- issues={workingIssues}- tasksByIssueId={view.tasksByIssueId}- taskCount={view.taskCount}- />+ <HoverCardContent align="end" className="w-72">+ <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 e9be43cc36..f0ac80c152 100644--- a/packages/views/issues/surface/issue-surface.test.tsx+++ b/packages/views/issues/surface/issue-surface.test.tsx@@ -335,6 +335,16 @@ describe("IssueSurface — table pagination ownership", () => {})) as unknown as AgentTask[],),),+ getWorkspaceWorkingAgents: vi.fn(() =>+ Promise.resolve(+ runningIssues.map((_, index) => ({+ id: `agent-${index}`,+ name: `Agent ${index}`,+ avatar_url: null,+ running_task_count: 1,+ })),+ ),+ ),getChildIssueProgress: vi.fn(() => never()),listProperties: vi.fn(() => never()),listMembers: vi.fn(() => never()),@@ -354,14 +364,23 @@ describe("IssueSurface — table pagination ownership", () => {</QueryClientProvider>,);- await waitFor(() => expect(listIssueTableRows).toHaveBeenCalledTimes(1));- expect(listIssueTableRows).toHaveBeenCalledWith(+ // The first render has not received the independent working-agents query+ // yet and therefore requests the explicit match-none form. Once that+ // query resolves, the Table owns a new query key containing the agent id+ // list and starts the real branch.+ await waitFor(() => expect(listIssueTableRows).toHaveBeenCalledTimes(2));+ expect(listIssueTableRows).toHaveBeenLastCalledWith(expect.objectContaining({group: { kind: "none" },group_key: null,parent_id: null,query: expect.objectContaining({- filters: expect.objectContaining({ working_only: true }),+ filters: expect.objectContaining({+ assignees: runningIssues.map((_, index) => ({+ type: "agent",+ id: `agent-${index}`,+ })),+ }),}),}),);diff --git a/packages/views/issues/surface/issue-surface.tsx b/packages/views/issues/surface/issue-surface.tsxindex 7f99daa87c..7133ab015e 100644--- a/packages/views/issues/surface/issue-surface.tsx+++ b/packages/views/issues/surface/issue-surface.tsx@@ -211,7 +211,6 @@ function IssueSurfaceContent({) : (<IssuesHeaderscopedIssues={controller.surfaceIssues}- workingIssues={workingIssues}allowGantt={controller.allowGantt}isRefreshing={controller.isRefreshing}facetCountsExact={@@ -309,7 +308,6 @@ function IssueSurfaceContent({myIssuesFilter={controller.loadMoreFilter}sort={controller.sort}projectId={controller.projectId}- activityByIssueId={controller.activity.activityByIssueId}onCreateIssue={openCreateIssue}groupBranches={controller.groupBranches}/>diff --git a/packages/views/issues/surface/use-issue-surface-controller.test.tsx b/packages/views/issues/surface/use-issue-surface-controller.test.tsxindex 65d1cfd170..f774038f16 100644--- a/packages/views/issues/surface/use-issue-surface-controller.test.tsx+++ b/packages/views/issues/surface/use-issue-surface-controller.test.tsx@@ -7,7 +7,6 @@ import { QueryClient, QueryClientProvider } from "@tanstack/react-query";import type { ReactNode } from "react";import { setApiInstance } from "@multica/core/api";import type { ApiClient } from "@multica/core/api/client";-import { agentTaskSnapshotOptions } from "@multica/core/agents";import {getIssueSurfaceViewStore,pruneIssueSurfaceViewStates,@@ -19,6 +18,7 @@ import type {IssueStatus,ListIssuesParams,ListIssuesResponse,+ WorkspaceWorkingAgent,} from "@multica/core/types";import { useIssueSurfaceController } from "./use-issue-surface-controller";import { IssueTableExportIntegrityError } from "../components/table-view-model";@@ -115,6 +115,18 @@ function makeRunningTask(id: string, agentId: string, issueId: string): AgentTas};}+function makeWorkingAgent(+ id: string,+ runningTaskCount = 1,+): WorkspaceWorkingAgent {+ return {+ id,+ name: id,+ avatar_url: null,+ running_task_count: runningTaskCount,+ };+}+describe("useIssueSurfaceController", () => {let qc: QueryClient;let listIssues: ReturnType<@@ -123,6 +135,9 @@ describe("useIssueSurfaceController", () => {let getAgentTaskSnapshot: ReturnType<typeof vi.fn<() => Promise<AgentTask[]>>>;+ let getWorkspaceWorkingAgents: ReturnType<+ typeof vi.fn<() => Promise<WorkspaceWorkingAgent[]>>+ >;let listIssueTableRows: ReturnType<typeof vi.fn>;let listIssueTableFacets: ReturnType<typeof vi.fn>;@@ -130,6 +145,9 @@ describe("useIssueSurfaceController", () => {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);listIssueTableRows = vi.fn(tableMethods.listIssueTableRows);listIssueTableFacets = vi.fn(tableMethods.listIssueTableFacets);@@ -141,6 +159,7 @@ describe("useIssueSurfaceController", () => {listGroupedIssues: vi.fn(() => never()),listProjects: vi.fn(() => never()),getAgentTaskSnapshot,+ getWorkspaceWorkingAgents,getChildIssueProgress: vi.fn(() => never()),} as unknown as ApiClient);pruneIssueSurfaceViewStates([]);@@ -784,11 +803,27 @@ describe("useIssueSurfaceController", () => {);});- it("sends the agents-working filter as a backend predicate without sending running ids", async () => {+ it("sends workspace working-agent ids through the Table assignee filter", async () => {const store = getIssueSurfaceViewStore("project:p1");store.getState().setViewMode("table");store.getState().toggleAgentRunningFilter();listIssues.mockResolvedValue({ issues: [], total: 0 });+ const getWorkspaceWorkingAgents = vi.fn(() =>+ Promise.resolve([+ {+ id: "agent-1",+ name: "Agent 1",+ avatar_url: null,+ running_task_count: 1,+ },+ {+ id: "agent-2",+ name: "Agent 2",+ avatar_url: null,+ running_task_count: 2,+ },+ ] satisfies WorkspaceWorkingAgent[]),+ );setApiInstance({listIssues,listGroupedIssues: vi.fn(() => never()),@@ -798,6 +833,7 @@ describe("useIssueSurfaceController", () => {{ id: "task-1", issue_id: "issue-running", status: "running" },] as unknown as AgentTask[]),),+ getWorkspaceWorkingAgents,getChildIssueProgress: vi.fn(() => never()),} as unknown as ApiClient);@@ -810,217 +846,137 @@ describe("useIssueSurfaceController", () => {{ wrapper: makeWrapper(qc, "project:p1") },);- expect(result.current.tableQuerySpec.filters.working_only).toBe(true);+ await waitFor(() =>+ expect(result.current.tableQuerySpec.filters.assignees).toEqual([+ { type: "agent", id: "agent-1" },+ { type: "agent", id: "agent-2" },+ ]),+ );+ expect(result.current.tableQuerySpec.filters.working_only).toBeUndefined();+ expect(getWorkspaceWorkingAgents).toHaveBeenCalledWith("issue", undefined);expect(listIssues).not.toHaveBeenCalled();});- it("keeps the table working-chip scope unknown without materializing a second issue window", async () => {- const store = getIssueSurfaceViewStore("project:p1");+ it("uses the active My Issues relation for the Table working-agent filter", async () => {+ const store = getIssueSurfaceViewStore("my:user-1:assigned");store.getState().setViewMode("table");- const running = makeIssue({ id: "issue-running", status: "in_progress" });- // A running issue may live in an unopened cursor branch. The header must- // stay unknown instead of deriving a false zero from visible rows.- listIssues.mockImplementation((params?: ListIssuesParams) =>- Promise.resolve(- params?.ids- ? { issues: [running], total: 1 }- : { issues: [], total: 0 },- ),+ store.getState().toggleAgentRunningFilter();+ const getWorkspaceWorkingAgents = vi.fn(() =>+ Promise.resolve([] satisfies WorkspaceWorkingAgent[]),);setApiInstance({listIssues,listGroupedIssues: vi.fn(() => never()),listProjects: vi.fn(() => never()),- getAgentTaskSnapshot: vi.fn(() =>- Promise.resolve([- { id: "task-1", issue_id: "issue-running", status: "running" },- ] as unknown as AgentTask[]),- ),+ getAgentTaskSnapshot: vi.fn(() => Promise.resolve([])),+ getWorkspaceWorkingAgents,getChildIssueProgress: vi.fn(() => never()),} as unknown as ApiClient);const { result } = renderHook(() =>useIssueSurfaceController({- scope: { type: "project", projectId: "p1" },+ scope: { type: "my", relation: "assigned", userId: "user-1" },modes: ["table"],}),- { wrapper: makeWrapper(qc, "project:p1") },+ { wrapper: makeWrapper(qc, "my:user-1:assigned") },);- await waitFor(() => expect(result.current.workingScopeIssues).toBeUndefined());- expect(listIssues).not.toHaveBeenCalled();- });-- it("does not subscribe Table to the legacy offset window", async () => {- const store = getIssueSurfaceViewStore("project:p1");- store.getState().setViewMode("table");- // page 1 claims a small window (under the ceiling); by page 2 the real- // window has grown far beyond it. The ceiling check must see the fresh- // total — pagination itself already advances on it.- listIssues.mockImplementation((params?: ListIssuesParams) =>- Promise.resolve(- (params?.offset ?? 0) === 0- ? {- issues: [- makeIssue({ id: "i-1", status: "todo" }),- makeIssue({ id: "i-2", status: "todo" }),- ],- total: 900,- }- : { issues: [makeIssue({ id: "i-3", status: "todo" })], total: 50_000 },+ await waitFor(() =>+ expect(getWorkspaceWorkingAgents).toHaveBeenCalledWith(+ "issue",+ "assigned",),);-- const { result } = renderHook(- () =>- useIssueSurfaceController({- scope: { type: "project", projectId: "p1" },- modes: ["table"],- }),- { wrapper: makeWrapper(qc, "project:p1") },- );-- expect(result.current.isLoading).toBe(false);- expect(result.current.isEmpty).toBe(false);- expect(listIssues).not.toHaveBeenCalled();+ expect(result.current.tableQuerySpec.filters.assignees).toEqual([]);});- it("does not materialize a multi-page working window for Table chrome", async () => {- const store = getIssueSurfaceViewStore("project:p1");- store.getState().setViewMode("table");- // 101 running issues spread over two pages: presenting page 1 alone as- // the authoritative scope makes the chip under-count until the filter is- // toggled (round-4 review P2#3) — the bounded loop must fetch page 2 by- // itself, and only a COMPLETE window is treated as authoritative.- const runningIssues = Array.from({ length: 101 }, (_, index) =>- makeIssue({ id: `run-${index}`, status: "in_progress" }),- );- listIssues.mockImplementation((params?: ListIssuesParams) => {- if (params?.ids) {- const offset = params.offset ?? 0;- return Promise.resolve({- issues: runningIssues.slice(offset, offset + 100),- total: runningIssues.length,- });- }- return Promise.resolve({ issues: [], total: 0 });- });- setApiInstance({- listIssues,- listGroupedIssues: vi.fn(() => never()),- listProjects: vi.fn(() => never()),- getAgentTaskSnapshot: vi.fn(() =>- Promise.resolve(- runningIssues.map((issue, index) => ({- id: `task-${index}`,- issue_id: issue.id,- status: "running",- })) as unknown as AgentTask[],- ),- ),- getChildIssueProgress: vi.fn(() => never()),- } as unknown as ApiClient);+ it.each(["board", "list", "swimlane"] as const)(+ "uses working-agent assignees for the %s server query without reading the task snapshot",+ async (viewMode) => {+ const store = getIssueSurfaceViewStore("project:p1");+ store.getState().setViewMode(viewMode);+ store.getState().toggleAgentRunningFilter();+ getWorkspaceWorkingAgents.mockResolvedValue([+ makeWorkingAgent("agent-from-working-api"),+ ]);+ // Deliberately contradictory legacy data. It must neither be fetched nor+ // influence membership after the quick filter moved to working-agents.+ getAgentTaskSnapshot.mockResolvedValue([+ makeRunningTask("legacy-task", "legacy-agent", "legacy-issue"),+ ]);- const { result } = renderHook(- () =>- useIssueSurfaceController({- scope: { type: "project", projectId: "p1" },- modes: ["table"],- }),- { wrapper: makeWrapper(qc, "project:p1") },- );+ const { result } = renderHook(+ () =>+ useIssueSurfaceController({+ scope: { type: "project", projectId: "p1" },+ modes: ["board", "list", "swimlane"],+ }),+ { wrapper: makeWrapper(qc, "project:p1") },+ );- await waitFor(() => expect(result.current.workingScopeIssues).toBeUndefined());- expect(listIssues).not.toHaveBeenCalled();- });+ await waitFor(() =>+ expect(result.current.tableQuerySpec.filters.assignees).toEqual([+ { type: "agent", id: "agent-from-working-api" },+ ]),+ );+ expect(result.current.tableQuerySpec.filters.working_only).toBeUndefined();+ expect(getWorkspaceWorkingAgents).toHaveBeenCalledWith("issue", undefined);+ expect(getAgentTaskSnapshot).not.toHaveBeenCalled();+ },+ );- it("never starts a legacy working-window request, regardless of result size", async () => {+ it("intersects regular assignees with working agents and excludes unassigned rows", async () => {const store = getIssueSurfaceViewStore("project:p1");- store.getState().setViewMode("table");- // The working window shares the MAIN table cache key while the filter is- // on, so an uncapped chip-driven loop would re-open the very ceiling the- // structure loop enforces (round-5 review P1). An over-ceiling window- // must stop after page 1 — and the chip must see UNKNOWN, not a number- // built from one page.- const runningIssues = Array.from({ length: 100 }, (_, index) =>- makeIssue({ id: `run-${index}`, status: "in_progress" }),- );- const idsCalls: Array<number | undefined> = [];- listIssues.mockImplementation((params?: ListIssuesParams) => {- if (params?.ids) {- idsCalls.push(params.offset);- return Promise.resolve({ issues: runningIssues, total: 5_000 });- }- return Promise.resolve({ issues: [], total: 0 });- });- setApiInstance({- listIssues,- listGroupedIssues: vi.fn(() => never()),- listProjects: vi.fn(() => never()),- getAgentTaskSnapshot: vi.fn(() =>- Promise.resolve(- runningIssues.map((issue, index) => ({- id: `task-${index}`,- issue_id: issue.id,- status: "running",- })) as unknown as AgentTask[],- ),- ),- getChildIssueProgress: vi.fn(() => never()),- } as unknown as ApiClient);+ store.getState().setViewMode("list");+ store.getState().toggleAssigneeFilter({ type: "agent", id: "agent-1" });+ store.getState().toggleAssigneeFilter({ type: "agent", id: "agent-2" });+ store.getState().toggleAssigneeFilter({ type: "member", id: "member-1" });+ store.getState().toggleNoAssignee();+ store.getState().toggleAgentRunningFilter();+ getWorkspaceWorkingAgents.mockResolvedValue([+ makeWorkingAgent("agent-2"),+ makeWorkingAgent("agent-3"),+ ]);const { result } = renderHook(() =>useIssueSurfaceController({scope: { type: "project", projectId: "p1" },- modes: ["table"],+ modes: ["list"],}),{ wrapper: makeWrapper(qc, "project:p1") },);- // Give any accidental auto-loop a chance to fire before asserting.- await act(async () => {- await new Promise((resolve) => setTimeout(resolve, 50));- });- expect(idsCalls).toEqual([]);await waitFor(() =>- expect(result.current.workingScopeIssues).toBeUndefined(),+ expect(result.current.tableQuerySpec.filters.assignees).toEqual([+ { type: "agent", id: "agent-2" },+ ]),);+ expect(+ result.current.tableQuerySpec.filters.include_no_assignee,+ ).toBeUndefined();});- it("keeps the Table activity scope unknown across task-snapshot rekeys", async () => {+ it("does not subscribe Table to the legacy offset window", async () => {const store = getIssueSurfaceViewStore("project:p1");store.getState().setViewMode("table");- // Running set A resolves to a complete window; then the set changes to B- // and B's request stays pending. keepPreviousData leaves A's rows as- // PLACEHOLDER under the new key — publishing them (paired with the new- // snapshot) would be a precise-looking number for a scope nobody fetched- // (round-6 review P2#1). Until B resolves, the scope must be unknown.- const issueA = makeIssue({ id: "run-A", status: "in_progress" });- let snapshotIssueId = "run-A";- listIssues.mockImplementation((params?: ListIssuesParams) => {- if (params?.ids?.includes("run-A")) {- return Promise.resolve({ issues: [issueA], total: 1 });- }- if (params?.ids) return never<ListIssuesResponse>();- return Promise.resolve({ issues: [], total: 0 });- });- setApiInstance({- listIssues,- listGroupedIssues: vi.fn(() => never()),- listProjects: vi.fn(() => never()),- getAgentTaskSnapshot: vi.fn(() =>- Promise.resolve([- {- id: "task-1",- issue_id: snapshotIssueId,- status: "running",- },- ] as unknown as AgentTask[]),+ // page 1 claims a small window (under the ceiling); by page 2 the real+ // window has grown far beyond it. The ceiling check must see the fresh+ // total — pagination itself already advances on it.+ listIssues.mockImplementation((params?: ListIssuesParams) =>+ Promise.resolve(+ (params?.offset ?? 0) === 0+ ? {+ issues: [+ makeIssue({ id: "i-1", status: "todo" }),+ makeIssue({ id: "i-2", status: "todo" }),+ ],+ total: 900,+ }+ : { issues: [makeIssue({ id: "i-3", status: "todo" })], total: 50_000 },),- getChildIssueProgress: vi.fn(() => never()),- } as unknown as ApiClient);+ );const { result } = renderHook(() =>@@ -1031,22 +987,9 @@ describe("useIssueSurfaceController", () => {{ wrapper: makeWrapper(qc, "project:p1") },);- await waitFor(() =>- expect(result.current.workingScopeIssues).toBeUndefined(),- );+ expect(result.current.isLoading).toBe(false);+ expect(result.current.isEmpty).toBe(false);expect(listIssues).not.toHaveBeenCalled();-- // The running set moves to B; B's ids window never resolves in this test.- snapshotIssueId = "run-B";- await act(async () => {- await qc.invalidateQueries({- queryKey: agentTaskSnapshotOptions("ws-1").queryKey,- });- });-- await waitFor(() => {- expect(result.current.workingScopeIssues).toBeUndefined();- });});it("leaves Table empty/error ownership to the server-backed renderer", async () => {@@ -1232,12 +1175,10 @@ 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. That only holds if the count comes out of the- // same filter pipeline the rows do. It used to be re-derived from the task- // snapshot against the PRE-filter issue set, so any active filter made the- // chip disagree with the list it was filtering.+ // rows clicking it leaves. The working-agents endpoint is projected into+ // the same assignee predicate used by every view's canonical query.- it("sends the working filter to the server without reconstructing a local scope", async () => {+ it("sends working-agent assignees to the server without reconstructing a local scope", async () => {mockListByStatus({todo: [makeIssue({ id: "todo-1", status: "todo" }),@@ -1245,10 +1186,9 @@ describe("useIssueSurfaceController", () => {],in_progress: [makeIssue({ id: "prog-1", status: "in_progress" })],});- // Running work on todo-1 and prog-1; todo-2 is idle.- getAgentTaskSnapshot.mockResolvedValue([- makeRunningTask("t-1", "agent-1", "todo-1"),- makeRunningTask("t-2", "agent-2", "prog-1"),+ getWorkspaceWorkingAgents.mockResolvedValue([+ makeWorkingAgent("agent-1"),+ makeWorkingAgent("agent-2"),]);const store = getIssueSurfaceViewStore("project:p1");@@ -1264,7 +1204,12 @@ describe("useIssueSurfaceController", () => {);await waitFor(() => expect(result.current.isLoading).toBe(false));- expect(result.current.tableQuerySpec.filters.working_only).toBe(true);+ expect(result.current.tableQuerySpec.filters.assignees).toEqual([+ { type: "agent", id: "agent-1" },+ { type: "agent", id: "agent-2" },+ ]);+ 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();@@ -1277,9 +1222,7 @@ describe("useIssueSurfaceController", () => {makeIssue({ id: "todo-2", status: "todo" }),],});- getAgentTaskSnapshot.mockResolvedValue([- makeRunningTask("t-1", "agent-1", "todo-1"),- ]);+ getWorkspaceWorkingAgents.mockResolvedValue([makeWorkingAgent("agent-1")]);const { result } = renderHook(() =>@@ -1303,10 +1246,9 @@ describe("useIssueSurfaceController", () => {todo: [makeIssue({ id: "todo-1", status: "todo" })],in_progress: [makeIssue({ id: "prog-1", status: "in_progress" })],});- // Both issues have running agents...- getAgentTaskSnapshot.mockResolvedValue([- makeRunningTask("t-1", "agent-1", "todo-1"),- makeRunningTask("t-2", "agent-2", "prog-1"),+ getWorkspaceWorkingAgents.mockResolvedValue([+ makeWorkingAgent("agent-1"),+ makeWorkingAgent("agent-2"),]);// ...but the user is only looking at `todo`.@@ -1328,7 +1270,11 @@ describe("useIssueSurfaceController", () => {await waitFor(() => expect(result.current.isLoading).toBe(false));expect(result.current.tableQuerySpec.filters.statuses).toEqual(["todo"]);- expect(result.current.tableQuerySpec.filters.working_only).toBe(true);+ expect(result.current.tableQuerySpec.filters.assignees).toEqual([+ { type: "agent", id: "agent-1" },+ { type: "agent", id: "agent-2" },+ ]);+ expect(result.current.tableQuerySpec.filters.working_only).toBeUndefined();expect(result.current.workingScopeIssues).toBeUndefined();});@@ -1339,9 +1285,7 @@ describe("useIssueSurfaceController", () => {makeIssue({ id: "child-1", status: "todo", parent_issue_id: "parent-1" }),],});- getAgentTaskSnapshot.mockResolvedValue([- makeRunningTask("t-1", "agent-1", "child-1"),- ]);+ getWorkspaceWorkingAgents.mockResolvedValue([makeWorkingAgent("agent-1")]);const store = getIssueSurfaceViewStore("project:p1");act(() => store.getState().toggleShowSubIssues());@@ -1361,17 +1305,10 @@ describe("useIssueSurfaceController", () => {expect(result.current.workingScopeIssues).toBeUndefined();});- it("keeps issue-less chat/autopilot tasks out of the working scope", async () => {+ it("requests issue working agents so chat/autopilot work stays out of scope", async () => {mockListByStatus({todo: [makeIssue({ id: "todo-1", status: "todo" })],});- // issue_id "" is how the API models a chat/autopilot task — it must not- // become a phantom row (it used to inflate the count by exactly 1).- getAgentTaskSnapshot.mockResolvedValue([- makeRunningTask("t-2", "agent-2", ""),- makeRunningTask("t-3", "agent-3", ""),- ]);-const { result } = renderHook(() =>useIssueSurfaceController({@@ -1383,6 +1320,8 @@ describe("useIssueSurfaceController", () => {await waitFor(() => expect(result.current.isLoading).toBe(false));expect(result.current.workingScopeIssues).toEqual([]);+ expect(getWorkspaceWorkingAgents).toHaveBeenCalledWith("issue", undefined);+ expect(getAgentTaskSnapshot).not.toHaveBeenCalled();});it("keeps swimlane chrome bounded while descriptors retain hidden-status counts", async () => {@@ -1390,9 +1329,9 @@ describe("useIssueSurfaceController", () => {todo: [makeIssue({ id: "todo-1", status: "todo" })],in_progress: [makeIssue({ id: "prog-1", status: "in_progress" })],});- getAgentTaskSnapshot.mockResolvedValue([- makeRunningTask("t-1", "agent-1", "todo-1"),- makeRunningTask("t-2", "agent-2", "prog-1"),+ getWorkspaceWorkingAgents.mockResolvedValue([+ makeWorkingAgent("agent-1"),+ makeWorkingAgent("agent-2"),]);const store = getIssueSurfaceViewStore("project:p1");@@ -1445,31 +1384,43 @@ describe("useIssueSurfaceController", () => {makeIssue({id: "gantt-open",status: "in_progress",+ assignee_type: "agent",+ assignee_id: "agent-1",start_date: "2026-01-01",due_date: "2026-01-05",}),makeIssue({id: "gantt-done",status: "done",+ assignee_type: "agent",+ assignee_id: "agent-2",start_date: "2026-01-01",due_date: "2026-01-05",}),// Scheduled server-side but momentarily dateless (e.g. a WS patch that// just cleared both dates) — the canvas cannot place it.- makeIssue({ id: "gantt-undated", status: "in_progress" }),+ makeIssue({+ id: "gantt-undated",+ status: "in_progress",+ assignee_type: "agent",+ assignee_id: "agent-3",+ }),];- it("keeps rows the gantt canvas hides out of the working scope", async () => {+ it("filters Gantt by working-agent assignees without reading the task snapshot", async () => {mockGanttIssues(ganttFixture);- // Every one of them has a running agent.+ getWorkspaceWorkingAgents.mockResolvedValue([makeWorkingAgent("agent-1")]);+ // Contradictory legacy membership must not affect the canvas.getAgentTaskSnapshot.mockResolvedValue([- makeRunningTask("t-1", "agent-1", "gantt-open"),makeRunningTask("t-2", "agent-2", "gantt-done"),makeRunningTask("t-3", "agent-3", "gantt-undated"),]);const store = getIssueSurfaceViewStore("project:p1");- act(() => store.getState().setViewMode("gantt"));+ act(() => {+ store.getState().setViewMode("gantt");+ store.getState().toggleAgentRunningFilter();+ });const { result } = renderHook(() =>@@ -1492,19 +1443,72 @@ describe("useIssueSurfaceController", () => {expect(result.current.workingScopeIssues?.map((i) => i.id)).toEqual(result.current.filteredGanttIssues.map((i) => i.id),);+ expect(getAgentTaskSnapshot).not.toHaveBeenCalled();+ });++ it.each([+ {+ name: "the working-agent API returns no agents",+ workingAgents: [] as WorkspaceWorkingAgent[],+ selectedAssigneeId: null,+ },+ {+ name: "the selected assignee has no working-agent intersection",+ workingAgents: [makeWorkingAgent("agent-1")],+ selectedAssigneeId: "agent-2",+ },+ ])("keeps Gantt empty when $name", async ({+ workingAgents,+ selectedAssigneeId,+ }) => {+ mockGanttIssues(ganttFixture);+ getWorkspaceWorkingAgents.mockResolvedValue(workingAgents);++ const store = getIssueSurfaceViewStore("project:p1");+ act(() => {+ store.getState().setViewMode("gantt");+ if (selectedAssigneeId) {+ store.getState().toggleAssigneeFilter({+ type: "agent",+ id: selectedAssigneeId,+ });+ }+ store.getState().toggleAgentRunningFilter();+ });++ const { result } = renderHook(+ () =>+ useIssueSurfaceController({+ scope: { type: "project", projectId: "p1" },+ modes: ["board", "list", "swimlane", "gantt"],+ }),+ { wrapper: makeWrapper(qc, "project:p1") },+ );++ await waitFor(() => expect(result.current.ganttIssues).toHaveLength(3));+ await waitFor(() =>+ expect(getWorkspaceWorkingAgents).toHaveBeenCalledWith(+ "issue",+ undefined,+ ),+ );++ expect(result.current.tableQuerySpec.filters.assignees).toEqual([]);+ expect(result.current.filteredGanttIssues).toEqual([]);+ expect(result.current.workingScopeIssues).toEqual([]);});it("widens the gantt working scope when show-completed is turned on", async () => {mockGanttIssues(ganttFixture);- getAgentTaskSnapshot.mockResolvedValue([- makeRunningTask("t-1", "agent-1", "gantt-open"),- makeRunningTask("t-2", "agent-2", "gantt-done"),- makeRunningTask("t-3", "agent-3", "gantt-undated"),+ getWorkspaceWorkingAgents.mockResolvedValue([+ makeWorkingAgent("agent-1"),+ makeWorkingAgent("agent-2"),]);const store = getIssueSurfaceViewStore("project:p1");act(() => {store.getState().setViewMode("gantt");+ store.getState().toggleAgentRunningFilter();store.getState().toggleGanttShowCompleted();});@@ -1530,5 +1534,6 @@ describe("useIssueSurfaceController", () => {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 ea86f7c091..1bc7329139 100644--- a/packages/views/issues/surface/use-issue-surface-controller.ts+++ b/packages/views/issues/surface/use-issue-surface-controller.ts@@ -14,6 +14,7 @@ import type {IssueTableQuerySpec,Project,} from "@multica/core/types";+import { workspaceWorkingAgentsOptions } from "@multica/core/agents";import { useWorkspaceId } from "@multica/core/hooks";import { ALL_STATUSES } from "@multica/core/issues/config";import { dateOnlyToLocalDate } from "@multica/core/issues/date";@@ -36,7 +37,6 @@ import type { IssueFilters } from "../utils/filter";import type { ChildProgress } from "../components/list-row";import { IssueTableExportIntegrityError } from "../components/table-view-model";import type { IssueSurfaceMode } from "./types";-import { useIssueSurfaceActivity, type IssueSurfaceActivity } from "./activity";import type { IssueSurfaceActions } from "./actions-context";import {type IssueSurfaceSelection,@@ -94,8 +94,10 @@ export interface IssueSurfaceController {/** Exact group catalog plus independent row cursors for Assignee/Property* Board and compound Swimlane cells. */groupBranches?: IssueGroupBranches;- activeFilters: Omit<IssueFilters, "statusFilters" | "runningIssueIds">;- activity: IssueSurfaceActivity;+ activeFilters: Omit<+ IssueFilters,+ "statusFilters" | "agentRunningFilter" | "runningIssueIds"+ >;actions: IssueSurfaceActions;selection: IssueSurfaceSelection;childProgressMap: Map<string, ChildProgress>;@@ -319,7 +321,39 @@ export function useIssueSurfaceController({const { projectFilters: viewProjectFilters, includeNoProject: viewIncludeNoProject } =projectFilterState;- const activity = useIssueSurfaceActivity();+ const workingAgentMineRelation =+ scope.type === "my"+ ? scope.relation === "all"+ ? "any"+ : scope.relation+ : undefined;+ const { data: workspaceWorkingAgents = [] } = useQuery(+ workspaceWorkingAgentsOptions(wsId, "issue", workingAgentMineRelation),+ );+ const workingAssigneeFilters = useMemo(() => {+ const workingAgentIds = new Set(+ workspaceWorkingAgents.map((agent) => agent.id),+ );+ if (assigneeFilters.length === 0) {+ return workspaceWorkingAgents.map((agent) => ({+ type: "agent" as const,+ id: agent.id,+ }));+ }++ // The quick filter and the regular assignee picker are both predicates+ // on the same field, so compose them with intersection (AND semantics).+ return assigneeFilters.filter(+ (assignee) =>+ assignee.type === "agent" && workingAgentIds.has(assignee.id),+ );+ }, [assigneeFilters, workspaceWorkingAgents]);+ const effectiveAssigneeFilters = agentRunningFilter+ ? workingAssigneeFilters+ : assigneeFilters;+ const effectiveIncludeNoAssignee = agentRunningFilter+ ? false+ : includeNoAssignee;const tableQuerySpec = useMemo<IssueTableQuerySpec>(() => {let queryScope: IssueTableQuerySpec["scope"];@@ -366,8 +400,14 @@ export function useIssueSurfaceController({filters: {...(statusFilters.length > 0 ? { statuses: statusFilters } : {}),...(priorityFilters.length > 0 ? { priorities: priorityFilters } : {}),- ...(assigneeFilters.length > 0 ? { assignees: assigneeFilters } : {}),- ...(includeNoAssignee ? { include_no_assignee: true } : {}),+ ...(agentRunningFilter+ ? { assignees: effectiveAssigneeFilters }+ : assigneeFilters.length > 0+ ? { assignees: assigneeFilters }+ : {}),+ ...(effectiveIncludeNoAssignee+ ? { include_no_assignee: true }+ : {}),...(creatorFilters.length > 0 ? { creators: creatorFilters } : {}),...(viewProjectFilters.length > 0? { project_ids: viewProjectFilters }@@ -378,7 +418,6 @@ export function useIssueSurfaceController({? { properties: effectivePropertyFilters }: {}),...(date ? { date } : {}),- ...(agentRunningFilter ? { working_only: true } : {}),include_sub_issues: showSubIssues,},...(debouncedActiveSearch ? { search: debouncedActiveSearch } : {}),@@ -393,8 +432,9 @@ export function useIssueSurfaceController({creatorFilters,dateParams,debouncedActiveSearch,+ effectiveAssigneeFilters,+ effectiveIncludeNoAssignee,effectivePropertyFilters,- includeNoAssignee,labelFilters,priorityFilters,scope,@@ -562,17 +602,17 @@ export function useIssueSurfaceController({serverGroupBranches,ganttShowCompleted,sort,- activity,statusFilters,priorityFilters,- assigneeFilters,- includeNoAssignee,+ assigneeFilters: effectiveAssigneeFilters,+ includeNoAssignee: effectiveIncludeNoAssignee,+ assigneeFilterActive: agentRunningFilter,creatorFilters,projectFilters: viewProjectFilters,includeNoProject: viewIncludeNoProject,labelFilters,propertyFilters: effectivePropertyFilters,- agentRunningFilter,+ workingAssigneeFilters,showSubIssues,loadProjects:cardProperties.project ||diff --git a/packages/views/issues/surface/use-issue-surface-data.ts b/packages/views/issues/surface/use-issue-surface-data.tsindex b4da5fb85e..dd276cd7b8 100644--- a/packages/views/issues/surface/use-issue-surface-data.ts+++ b/packages/views/issues/surface/use-issue-surface-data.ts@@ -28,7 +28,6 @@ import {type IssueFilters,} from "../utils/filter";import type { ChildProgress } from "../components/list-row";-import type { IssueSurfaceActivity } from "./activity";import type {IssueStatusBranches,IssueStatusPagination,@@ -82,8 +81,10 @@ export interface IssueSurfaceData {visibleStatuses: IssueStatus[];hiddenStatuses: IssueStatus[];statusPagination: IssueStatusPagination;- activeFilters: Omit<IssueFilters, "statusFilters" | "runningIssueIds">;- activity: IssueSurfaceActivity;+ activeFilters: Omit<+ IssueFilters,+ "statusFilters" | "agentRunningFilter" | "runningIssueIds"+ >;childProgressMap: Map<string, ChildProgress>;projectMap: Map<string, Project>;resolveTableExportLookups: (needs: {@@ -113,17 +114,17 @@ export function useIssueSurfaceData({serverGroupBranches,ganttShowCompleted,sort,- activity,statusFilters,priorityFilters,assigneeFilters,includeNoAssignee,+ assigneeFilterActive,creatorFilters,projectFilters,includeNoProject,labelFilters,propertyFilters,- agentRunningFilter,+ workingAssigneeFilters,showSubIssues,loadProjects,}: {@@ -139,27 +140,24 @@ export function useIssueSurfaceData({* rows without it, so the working scope has to honour it too. */ganttShowCompleted: boolean;sort: IssueSortParam;- /** Owned by the controller so the agents-working facet and the client- * display filters read the same task snapshot. */- activity: IssueSurfaceActivity;statusFilters: IssueStatus[];priorityFilters: IssueFilterState["priorityFilters"];assigneeFilters: IssueFilterState["assigneeFilters"];includeNoAssignee: boolean;+ /** True when the working-agent quick filter owns the assignee predicate,+ * including when its API-derived intersection is explicitly empty. */+ assigneeFilterActive: boolean;creatorFilters: IssueFilterState["creatorFilters"];projectFilters: string[];includeNoProject: boolean;labelFilters: string[];propertyFilters: Record<string, string[]>;- agentRunningFilter: boolean;+ /** The working-agent API projected into the same typed assignee predicate+ * used by the canonical Table query. */+ workingAssigneeFilters: IssueFilterState["assigneeFilters"];showSubIssues: boolean;loadProjects: boolean;}): IssueSurfaceData {- const filterContext = useMemo(- () => ({ activityByIssueId: activity.activityByIssueId }),- [activity.activityByIssueId],- );-const assigneeGroupFilter = useMemo<AssigneeGroupedIssuesFilter>(() => ({...queryPlan.groupedScopeFilter,@@ -209,7 +207,7 @@ export function useIssueSurfaceData({...issueSurfaceGanttOptions(wsId, projectId ?? ""),enabled: usesGantt,});- const hasRunningIssues = activity.runningIssueIds.size > 0;+ const hasWorkingAssignees = workingAssigneeFilters.length > 0;const bucketedIssues = useMemo(() => {return serverStatusBranches.enabled? serverStatusBranches.issues@@ -246,17 +244,18 @@ export function useIssueSurfaceData({priorityFilters,assigneeFilters,includeNoAssignee,+ assigneeFilterActive,creatorFilters,projectFilters,includeNoProject,labelFilters,propertyFilters,- workingOnly: agentRunningFilter,+ workingOnly: false,showSubIssues,}),[- agentRunningFilter,assigneeFilters,+ assigneeFilterActive,creatorFilters,includeNoAssignee,includeNoProject,@@ -273,10 +272,9 @@ export function useIssueSurfaceData({() =>serverStatusBranches.enabled? surfaceIssues- : applyIssueFilters(surfaceIssues, baseFilterState, filterContext),+ : applyIssueFilters(surfaceIssues, baseFilterState),[baseFilterState,- filterContext,serverStatusBranches.enabled,surfaceIssues,],@@ -291,48 +289,54 @@ export function useIssueSurfaceData({);const swimlaneIssues = useMemo(- () => applyIssueFilters(surfaceIssues, statuslessFilterState, filterContext),- [filterContext, statuslessFilterState, surfaceIssues],+ () => applyIssueFilters(surfaceIssues, statuslessFilterState),+ [statuslessFilterState, surfaceIssues],);const filteredGanttIssues = useMemo(() =>ganttCanvasRows(- applyIssueFilters(ganttIssues, baseFilterState, filterContext),+ applyIssueFilters(ganttIssues, baseFilterState),ganttShowCompleted,),- [baseFilterState, filterContext, ganttIssues, ganttShowCompleted],+ [baseFilterState, ganttIssues, ganttShowCompleted],);// The assignee-grouped board renders straight from `groups`, bypassing the- // flat applyIssueFilters output — re-apply the client-only display filters- // (Show sub-issues + agents-working) per group.+ // flat applyIssueFilters output — re-apply the remaining client-only+ // display filters per group. Working-agent membership is already encoded+ // in the assignee predicate sent to the server.const filteredAssigneeGroups = useMemo(() =>filterAssigneeGroups(assigneeGroupsQuery.data?.groups, {showSubIssues,- agentRunningFilter,- runningIssueIds: activity.runningIssueIds,propertyFilters,}),[- activity.runningIssueIds,- agentRunningFilter,assigneeGroupsQuery.data?.groups,propertyFilters,showSubIssues,],);+ const workingFilterState = useMemo<IssueFilterState>(+ () => ({+ ...baseFilterState,+ assigneeFilters: workingAssigneeFilters,+ includeNoAssignee: false,+ assigneeFilterActive: true,+ workingOnly: false,+ }),+ [baseFilterState, workingAssigneeFilters],+ );+// The rows the agents-working filter leaves on screen — i.e. exactly what// you get when you click the header chip.//- // This is deliberately a PROJECTION OF THE RENDER PIPELINE, not a second- // pass over the task snapshot: it reuses the same predicates, the same- // filter state and the same per-mode source as the rows below, with- // `workingOnly` forced on. Turning the filter on only adds `workingOnly` to- // this same pipeline, so the set is the post-click list whether the filter- // is currently on or off.+ // This is deliberately a projection of the render pipeline. The controller+ // translates `/api/working-agents` into a typed assignee predicate once;+ // both the canonical server query and client-only Gantt/extra-child paths+ // reuse that predicate, so there is no task-snapshot membership fallback.//// 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@@ -359,45 +363,36 @@ export function useIssueSurfaceData({return ganttCanvasRows(applyIssueFilters(ganttIssues,- { ...baseFilterState, workingOnly: true },- filterContext,+ workingFilterState,),ganttShowCompleted,);}if (usesAssigneeBoard && !serverGroupBranches.enabled) {- return (+ const groupedIssues = (filterAssigneeGroups(assigneeGroupsQuery.data?.groups, {showSubIssues,- agentRunningFilter: true,- runningIssueIds: activity.runningIssueIds,propertyFilters,}) ?? []).flatMap((group) => group.issues);+ return applyIssueFilters(groupedIssues, workingFilterState);}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 task set is trivially known; otherwise- // keep the chip indeterminate until a bounded server facet supplies- // the matching task/issue projection.- if (!hasRunningIssues) return EMPTY_ISSUES;+ // 1,000-row ceiling. An empty working-assignee intersection is trivially+ // known; otherwise keep the chip indeterminate until a bounded server+ // facet supplies the matching task/issue projection.+ if (!hasWorkingAssignees) return EMPTY_ISSUES;return undefined;}- return applyIssueFilters(- surfaceIssues,- { ...baseFilterState, workingOnly: true },- filterContext,- );+ return applyIssueFilters(surfaceIssues, workingFilterState);}, [- activity.runningIssueIds,assigneeGroupsQuery.data?.groups,- baseFilterState,- filterContext,ganttIssues,ganttShowCompleted,- hasRunningIssues,+ hasWorkingAssignees,propertyFilters,showSubIssues,surfaceIssues,@@ -406,6 +401,7 @@ export function useIssueSurfaceData({usesTable,serverStatusBranches.enabled,serverGroupBranches.enabled,+ workingFilterState,]);const {@@ -480,17 +476,17 @@ export function useIssueSurfaceData({priorityFilters,assigneeFilters,includeNoAssignee,+ assigneeFilterActive,creatorFilters,projectFilters,includeNoProject,labelFilters,propertyFilters,- agentRunningFilter,showSubIssues,}),[- agentRunningFilter,assigneeFilters,+ assigneeFilterActive,creatorFilters,includeNoAssignee,includeNoProject,@@ -549,7 +545,6 @@ export function useIssueSurfaceData({hiddenStatuses,statusPagination: serverStatusBranches.pagination,activeFilters,- activity,childProgressMap,projectMap,resolveTableExportLookups,diff --git a/packages/views/issues/utils/filter.test.ts b/packages/views/issues/utils/filter.test.tsindex 34cb60a29f..08a1eb93c0 100644--- a/packages/views/issues/utils/filter.test.ts+++ b/packages/views/issues/utils/filter.test.ts@@ -93,6 +93,14 @@ describe("filterIssues", () => {expect(result.map((i) => i.id)).toEqual(["2", "3"]);});+ it("treats an explicitly active empty assignee predicate as match-none", () => {+ const result = filterIssues(issues, {+ ...NO_FILTER,+ assigneeFilterActive: true,+ });+ expect(result).toEqual([]);+ });+it("hides assigned issues when only 'No assignee' is selected", () => {const result = filterIssues(issues, { ...NO_FILTER, includeNoAssignee: true });expect(result.every((i) => !i.assignee_id)).toBe(true);diff --git a/packages/views/issues/utils/filter.ts b/packages/views/issues/utils/filter.tsindex 1a43b53570..c517eba146 100644--- a/packages/views/issues/utils/filter.ts+++ b/packages/views/issues/utils/filter.ts@@ -7,6 +7,10 @@ export interface IssueFilters {priorityFilters: IssuePriority[];assigneeFilters: ActorFilterValue[];includeNoAssignee: boolean;+ /** Keeps an explicitly active assignee predicate distinct from the normal+ * empty-array = no-filter state. When true with no selected assignees and+ * includeNoAssignee=false, the predicate intentionally matches nothing. */+ assigneeFilterActive?: boolean;creatorFilters: ActorFilterValue[];projectFilters: string[];includeNoProject: boolean;@@ -32,6 +36,8 @@ export interface IssueFilterState {priorityFilters: IssuePriority[];assigneeFilters: ActorFilterValue[];includeNoAssignee: boolean;+ /** See IssueFilters.assigneeFilterActive. */+ assigneeFilterActive?: boolean;creatorFilters: ActorFilterValue[];projectFilters: string[];includeNoProject: boolean;@@ -97,7 +103,10 @@ export function applyIssueFilters(context: IssueFilterContext = {},): Issue[] {const { statusFilters, priorityFilters, assigneeFilters, includeNoAssignee, creatorFilters, projectFilters, includeNoProject, labelFilters, workingOnly } = filters;- const hasAssigneeFilter = assigneeFilters.length > 0 || includeNoAssignee;+ const hasAssigneeFilter =+ filters.assigneeFilterActive === true ||+ assigneeFilters.length > 0 ||+ includeNoAssignee;const hasProjectFilter = projectFilters.length > 0 || includeNoProject;// Empty set passed without `agentRunningFilter` is a no-op. When the// filter is on but the set is missing/empty, hide everything — the@@ -174,6 +183,7 @@ export function filterIssues(issues: Issue[], filters: IssueFilters): Issue[] {priorityFilters: filters.priorityFilters,assigneeFilters: filters.assigneeFilters,includeNoAssignee: filters.includeNoAssignee,+ assigneeFilterActive: filters.assigneeFilterActive,creatorFilters: filters.creatorFilters,projectFilters: filters.projectFilters,includeNoProject: filters.includeNoProject,diff --git a/packages/views/my-issues/components/my-issues-header.tsx b/packages/views/my-issues/components/my-issues-header.tsxindex 77cc4b631d..16b9eb6343 100644--- a/packages/views/my-issues/components/my-issues-header.tsx+++ b/packages/views/my-issues/components/my-issues-header.tsx@@ -15,7 +15,10 @@ import type {IssueTableFacetSpec,IssueTableFacetsResponse,} from "@multica/core/types";-import type { MyIssuesScope } from "@multica/core/issues/stores/my-issues-view-store";+import {+ myIssuesRelationFromScope,+ 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";@@ -26,7 +29,6 @@ import {export function MyIssuesHeader({allIssues,- workingIssues,scope,onScopeChange,isRefreshing = false,@@ -35,10 +37,6 @@ export function MyIssuesHeader({onTableFacetChange,}: {allIssues: Issue[];- /** The rows the agents-working filter would leave on screen — undefined- * when the set is unknown (chip renders indeterminate). Scopes the chip:- * it counts the agents working on these rows. */- workingIssues: Issue[] | undefined;scope: MyIssuesScope;onScopeChange: (scope: MyIssuesScope) => void;isRefreshing?: boolean;@@ -49,6 +47,7 @@ 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) },@@ -124,7 +123,7 @@ export function MyIssuesHeader({<WorkspaceAgentWorkingChipvalue={agentRunningFilter}onToggle={toggleAgentRunningFilter}- workingIssues={workingIssues}+ mineRelation={mineRelation === "all" ? "any" : mineRelation}/><IssueDisplayControlsscopedIssues={allIssues}diff --git a/packages/views/my-issues/components/my-issues-page.tsx b/packages/views/my-issues/components/my-issues-page.tsxindex f384144724..37ad4bde47 100644--- a/packages/views/my-issues/components/my-issues-page.tsx+++ b/packages/views/my-issues/components/my-issues-page.tsx@@ -4,18 +4,14 @@ import { useStore } from "zustand";import { ListTodo } from "lucide-react";import { useAuthStore } from "@multica/core/auth";import {+ myIssuesRelationFromScope,myIssuesViewStore,- type MyIssuesScope,} from "@multica/core/issues/stores/my-issues-view-store";import { PageHeader } from "../../layout/page-header";import { IssueSurface } from "../../issues/surface/issue-surface";import { useT } from "../../i18n";import { MyIssuesHeader } from "./my-issues-header";-function relationFromScope(scope: MyIssuesScope) {- return scope === "agents" ? "involved" : scope;-}-export function MyIssuesPage() {const { t } = useT("my-issues");const user = useAuthStore((s) => s.user);@@ -34,14 +30,13 @@ export function MyIssuesPage() {scope={{type: "my",userId: user.id,- relation: relationFromScope(scope),+ relation: myIssuesRelationFromScope(scope),}}modes={["board", "list", "table", "swimlane"]}batchToolbar="list"- renderHeader={({ controller, workingIssues }) => (+ renderHeader={({ controller }) => (<MyIssuesHeaderallIssues={controller.surfaceIssues}- workingIssues={workingIssues}scope={scope}onScopeChange={setScope}isRefreshing={controller.isRefreshing}diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex 1c0f8d1f8a..14e53e3595 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -1323,6 +1323,10 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus// every active task + each agent's most recent terminal task.r.Get("/api/agent-task-snapshot", h.ListWorkspaceAgentTaskSnapshot)+ // Independent workspace-level list backing the issues-header+ // "agents working" chip and its assignee-id Table filter.+ r.Get("/api/working-agents", h.ListWorkspaceWorkingAgents)+// Workspace-wide daily agent activity (last 30d, anchored on// completed_at). Backs the Agents-list sparkline (trailing 7d// slice) AND the agent detail "Last 30 days" panel.diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.goindex 5b5a8e9650..a1daa09558 100644--- a/server/internal/handler/agent.go+++ b/server/internal/handler/agent.go@@ -2094,6 +2094,115 @@ type AgentRunCount struct {RunCount int32 `json:"run_count"`}+// WorkspaceWorkingAgent is the privacy-safe agent summary returned by the+// workspace working-agents endpoint. It deliberately carries only display+// information plus the current running-task count; full AgentResponse fields+// include runtime and integration configuration that this chip does not need.+type WorkspaceWorkingAgent struct {+ ID string `json:"id"`+ Name string `json:"name"`+ AvatarURL *string `json:"avatar_url"`+ RunningTaskCount int32 `json:"running_task_count"`+}++// ListWorkspaceWorkingAgents returns currently working user-authored agents in+// the workspace, independent of issue filters or Table pagination. The+// optional type query selects issue, autopilot, or chat work; omitting it keeps+// the all-sources projection. scope=mine narrows issue work to the authenticated+// member's selected My Issues relation. Access filtering mirrors the other+// workspace-wide agent aggregations so a private/non-allow-listed agent is+// never exposed by its name, avatar, count, or even presence.+func (h *Handler) ListWorkspaceWorkingAgents(w http.ResponseWriter, r *http.Request) {+ workspaceID := h.resolveWorkspaceID(r)+ member, ok := h.workspaceMember(w, r, workspaceID)+ if !ok {+ return+ }++ workType := strings.TrimSpace(r.URL.Query().Get("type"))+ switch workType {+ case "", "issue", "autopilot", "chat":+ default:+ writeError(w, http.StatusBadRequest, "invalid type: must be issue, autopilot, or chat")+ return+ }++ scope := strings.TrimSpace(r.URL.Query().Get("scope"))+ mineRelation := strings.TrimSpace(r.URL.Query().Get("relation"))+ var memberID pgtype.UUID+ switch scope {+ case "":+ if mineRelation != "" {+ writeError(w, http.StatusBadRequest, "relation requires scope=mine")+ return+ }+ case "mine":+ if workType != "issue" {+ writeError(w, http.StatusBadRequest, "scope=mine requires type=issue")+ return+ }+ if mineRelation == "" {+ mineRelation = "any"+ }+ switch mineRelation {+ case "assigned", "created", "involved", "any":+ default:+ writeError(w, http.StatusBadRequest, "invalid relation: must be assigned, created, involved, or any")+ return+ }+ userID, ok := requireUserID(w, r)+ if !ok {+ return+ }+ var err error+ memberID, err = util.ParseUUID(userID)+ if err != nil {+ writeError(w, http.StatusUnauthorized, "user not authenticated")+ return+ }+ default:+ writeError(w, http.StatusBadRequest, "invalid scope: must be mine")+ return+ }++ rows, err := h.Queries.ListWorkspaceWorkingAgents(+ r.Context(),+ db.ListWorkspaceWorkingAgentsParams{+ WorkspaceID: parseUUID(workspaceID),+ WorkType: workType,+ MineRelation: mineRelation,+ MemberID: memberID,+ },+ )+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list workspace working agents")+ return+ }++ actorType, actorID := h.resolveActor(r, requestUserID(r), workspaceID)+ allowed, ok := h.accessibleAgentIDs(r.Context(), workspaceID, actorType, actorID, member.Role)+ if !ok {+ writeError(w, http.StatusInternalServerError, "failed to resolve agent access")+ return+ }++ resp := make([]WorkspaceWorkingAgent, 0, len(rows))+ for _, row := range rows {+ agentID := uuidToString(row.ID)+ if _, ok := allowed[agentID]; !ok {+ continue+ }+ resp = append(resp, WorkspaceWorkingAgent{+ ID: agentID,+ Name: row.Name,+ AvatarURL: textToPtr(row.AvatarUrl),+ RunningTaskCount: row.RunningTaskCount,+ })+ }++ writeJSON(w, http.StatusOK, resp)+}+// GetWorkspaceAgentRunCounts returns 30-day total run counts for every// agent in the workspace. Same single-fetch pattern as live-tasks /// activity to keep the Agents list cheap regardless of agent count.diff --git a/server/internal/handler/agent_test.go b/server/internal/handler/agent_test.goindex 7dbff397f1..a1aa3d5763 100644--- a/server/internal/handler/agent_test.go+++ b/server/internal/handler/agent_test.go@@ -144,6 +144,320 @@ func TestListWorkspaceAgentTaskSnapshot(t *testing.T) {}}+func TestListWorkspaceWorkingAgents(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }++ ctx := context.Background()+ workingAgentID := createHandlerTestAgent(t, "working-agents-running", []byte(`{}`))+ queuedAgentID := createHandlerTestAgent(t, "working-agents-queued", []byte(`{}`))++ // An agent owned by someone else keeps the squad fixtures mutually+ // exclusive: it can lead a squad without accidentally satisfying the+ // "leader owned by me" branch.+ var outsiderUserID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO "user" (name, email)+ VALUES ('Working Agents Outsider', 'working-agents-outsider-' || gen_random_uuid()::text || '@multica.test')+ RETURNING id+ `).Scan(&outsiderUserID); err != nil {+ t.Fatalf("insert outsider user: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(ctx, `DELETE FROM "user" WHERE id = $1`, outsiderUserID)+ })++ var outsiderAgentID 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, mcp_config+ )+ VALUES (+ $1, 'working-agents-outsider', '', 'cloud', '{}'::jsonb,+ $2, 'workspace', 'private', 1, $3,+ '', '{}'::jsonb, '[]'::jsonb, '{}'::jsonb+ )+ RETURNING id+ `, testWorkspaceID, testRuntimeID, outsiderUserID).Scan(&outsiderAgentID); err != nil {+ t.Fatalf("insert outsider agent: %v", err)+ }+ t.Cleanup(func() {+ testPool.Exec(ctx, `DELETE FROM agent WHERE id = $1`, outsiderAgentID)+ })++ insertedSquadIDs := make([]string, 0, 3)+ insertSquad := func(name, leaderID string) string {+ t.Helper()+ var squadID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO squad (+ workspace_id, name, description, leader_id, creator_id+ )+ VALUES ($1, $2, '', $3, $4)+ RETURNING id+ `,+ testWorkspaceID,+ name,+ leaderID,+ testUserID,+ ).Scan(&squadID); err != nil {+ t.Fatalf("insert squad %q: %v", name, err)+ }+ insertedSquadIDs = append(insertedSquadIDs, squadID)+ return squadID+ }+ directMemberSquadID := insertSquad(+ "working-agents-direct-member-squad",+ outsiderAgentID,+ )+ ownedLeaderSquadID := insertSquad(+ "working-agents-owned-leader-squad",+ workingAgentID,+ )+ ownedMemberSquadID := insertSquad(+ "working-agents-owned-member-squad",+ outsiderAgentID,+ )+ if _, err := testPool.Exec(ctx, `+ INSERT INTO squad_member (squad_id, member_type, member_id)+ VALUES+ ($1, 'member', $2),+ ($3, 'agent', $4)+ `,+ directMemberSquadID,+ testUserID,+ ownedMemberSquadID,+ workingAgentID,+ ); err != nil {+ t.Fatalf("insert squad involvement fixtures: %v", err)+ }+ t.Cleanup(func() {+ for _, squadID := range insertedSquadIDs {+ testPool.Exec(ctx, `DELETE FROM squad WHERE id = $1`, squadID)+ }+ })++ // Insert source issues directly: this test is about the working-agent+ // projection, so it must not inherit unrelated CreateIssue validation or+ // side effects. The fixtures cover every direct My Issues relation plus+ // all three squad-involvement branches.+ insertedIssueIDs := make([]string, 0, 6)+ insertIssue := func(+ title, creatorType, creatorID string,+ assigneeType, assigneeID any,+ ) string {+ t.Helper()+ var issueID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO issue (+ workspace_id, number, title, status, priority,+ assignee_type, assignee_id, creator_type, creator_id+ )+ SELECT $1, COALESCE(MIN(number), 0) - 1, $2, 'todo', 'none',+ $3, $4, $5, $6+ FROM issue+ WHERE workspace_id = $1+ RETURNING id+ `,+ testWorkspaceID,+ title,+ assigneeType,+ assigneeID,+ creatorType,+ creatorID,+ ).Scan(&issueID); err != nil {+ t.Fatalf("insert source issue %q: %v", title, err)+ }+ insertedIssueIDs = append(insertedIssueIDs, issueID)+ return issueID+ }+ assignedIssueID := insertIssue(+ "working-agent-assigned-to-me",+ "member",+ testUserID,+ "member",+ testUserID,+ )+ ownedAgentIssueID := insertIssue(+ "working-agent-owned-agent",+ "agent",+ outsiderAgentID,+ "agent",+ workingAgentID,+ )+ outsideIssueID := insertIssue(+ "working-agent-outside-mine",+ "agent",+ outsiderAgentID,+ nil,+ nil,+ )+ directMemberSquadIssueID := insertIssue(+ "working-agent-direct-member-squad",+ "agent",+ outsiderAgentID,+ "squad",+ directMemberSquadID,+ )+ ownedLeaderSquadIssueID := insertIssue(+ "working-agent-owned-leader-squad",+ "agent",+ outsiderAgentID,+ "squad",+ ownedLeaderSquadID,+ )+ ownedMemberSquadIssueID := insertIssue(+ "working-agent-owned-member-squad",+ "agent",+ outsiderAgentID,+ "squad",+ ownedMemberSquadID,+ )+ t.Cleanup(func() {+ for _, issueID := range insertedIssueIDs {+ testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID)+ }+ })+ chatSessionID := createHandlerTestChatSession(t, workingAgentID)+ autopilotID := insertListTestAutopilot(t, workingAgentID, "working-agent-source-filter")+ var autopilotRunID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO autopilot_run (autopilot_id, source, status)+ VALUES ($1, 'manual', 'running')+ RETURNING id+ `, autopilotID).Scan(&autopilotRunID); err != nil {+ t.Fatalf("insert autopilot run: %v", err)+ }++ // Nine running tasks on one agent: six issue relations, chat, autopilot,+ // and quick-create (no source FK). The autopilot task also carries issue_id+ // to prove source precedence keeps it out of type=issue.+ insertedTaskIDs := make([]string, 0, 10)+ for _, fixture := range []struct {+ agentID string+ status string+ issueID any+ chatSessionID any+ autopilotRunID any+ }{+ {workingAgentID, "running", assignedIssueID, nil, nil},+ {workingAgentID, "running", ownedAgentIssueID, nil, nil},+ {workingAgentID, "running", outsideIssueID, nil, nil},+ {workingAgentID, "running", directMemberSquadIssueID, nil, nil},+ {workingAgentID, "running", ownedLeaderSquadIssueID, nil, nil},+ {workingAgentID, "running", ownedMemberSquadIssueID, nil, nil},+ {workingAgentID, "running", nil, chatSessionID, nil},+ {workingAgentID, "running", assignedIssueID, nil, autopilotRunID},+ {workingAgentID, "running", nil, nil, nil},+ {queuedAgentID, "queued", nil, nil, nil},+ } {+ var taskID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent_task_queue (+ agent_id, runtime_id, status, priority, issue_id,+ chat_session_id, autopilot_run_id, started_at+ )+ VALUES ($1, $2, $3, 0, $4, $5, $6, now())+ RETURNING id+ `,+ fixture.agentID,+ testRuntimeID,+ fixture.status,+ fixture.issueID,+ fixture.chatSessionID,+ fixture.autopilotRunID,+ ).Scan(&taskID); err != nil {+ t.Fatalf("insert %s task: %v", fixture.status, err)+ }+ insertedTaskIDs = append(insertedTaskIDs, taskID)+ }+ t.Cleanup(func() {+ for _, taskID := range insertedTaskIDs {+ testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID)+ }+ })++ for _, tc := range []struct {+ name string+ query string+ wantCount int32+ }{+ {name: "all sources", wantCount: 9},+ {name: "issue", query: "?type=issue", wantCount: 6},+ {name: "autopilot", query: "?type=autopilot", wantCount: 1},+ {name: "chat", query: "?type=chat", wantCount: 1},+ {name: "mine defaults to any", query: "?type=issue&scope=mine", wantCount: 5},+ {name: "mine any", query: "?type=issue&scope=mine&relation=any", wantCount: 5},+ {name: "mine assigned", query: "?type=issue&scope=mine&relation=assigned", wantCount: 1},+ {name: "mine created", query: "?type=issue&scope=mine&relation=created", wantCount: 1},+ {name: "mine involved", query: "?type=issue&scope=mine&relation=involved", wantCount: 4},+ } {+ t.Run(tc.name, func(t *testing.T) {+ w := httptest.NewRecorder()+ testHandler.ListWorkspaceWorkingAgents(+ w,+ newRequest(http.MethodGet, "/api/working-agents"+tc.query, nil),+ )+ if w.Code != http.StatusOK {+ t.Fatalf("expected 200, got %d: %s", w.Code, w.Body.String())+ }++ var agents []WorkspaceWorkingAgent+ if err := json.NewDecoder(w.Body).Decode(&agents); err != nil {+ t.Fatalf("decode response: %v", err)+ }++ var working *WorkspaceWorkingAgent+ for i := range agents {+ switch agents[i].ID {+ case workingAgentID:+ working = &agents[i]+ case queuedAgentID:+ t.Errorf("queued-only agent must not be returned")+ }+ }+ if working == nil {+ t.Fatalf("running agent %s was not returned", workingAgentID)+ }+ if working.Name != "working-agents-running" {+ t.Errorf("name = %q, want %q", working.Name, "working-agents-running")+ }+ if working.RunningTaskCount != tc.wantCount {+ t.Errorf("running_task_count = %d, want %d", working.RunningTaskCount, tc.wantCount)+ }+ })+ }+}++func TestListWorkspaceWorkingAgentsRejectsInvalidFilters(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }++ for _, path := range []string{+ "/api/working-agents?type=quick_create",+ "/api/working-agents?scope=mine",+ "/api/working-agents?type=chat&scope=mine",+ "/api/working-agents?type=issue&scope=workspace",+ "/api/working-agents?type=issue&relation=assigned",+ "/api/working-agents?type=issue&scope=mine&relation=watching",+ } {+ t.Run(path, func(t *testing.T) {+ w := httptest.NewRecorder()+ testHandler.ListWorkspaceWorkingAgents(+ w,+ newRequest(http.MethodGet, path, nil),+ )+ if w.Code != http.StatusBadRequest {+ t.Fatalf("expected 400, got %d: %s", w.Code, w.Body.String())+ }+ })+ }+}+func TestCreateAgent_RejectsDuplicateName(t *testing.T) {if testHandler == nil {t.Skip("database not available")diff --git a/server/internal/handler/issue_table_query.go b/server/internal/handler/issue_table_query.goindex 8003eb3b88..d72757b791 100644--- a/server/internal/handler/issue_table_query.go+++ b/server/internal/handler/issue_table_query.go@@ -243,6 +243,8 @@ func equalOptionalString(a, b *string) bool {}func canonicalIssueTableFingerprint(workspaceID string, spec issueTableQuerySpec) (string, error) {+ explicitEmptyAssignees :=+ spec.Filters.Assignees != nil && len(spec.Filters.Assignees) == 0normalized := specnormalized.Search = strings.TrimSpace(normalized.Search)normalized.Scope.AssigneeTypes = sortedUniqueStrings(normalized.Scope.AssigneeTypes)@@ -256,11 +258,13 @@ func canonicalIssueTableFingerprint(workspaceID string, spec issueTableQuerySpecnormalized.Filters.Properties[key] = sortedUniqueStrings(values)}encoded, err := json.Marshal(struct {- WorkspaceID string `json:"workspace_id"`- Query issueTableQuerySpec `json:"query"`+ WorkspaceID string `json:"workspace_id"`+ Query issueTableQuerySpec `json:"query"`+ ExplicitEmptyAssignees bool `json:"explicit_empty_assignees,omitempty"`}{- WorkspaceID: workspaceID,- Query: normalized,+ WorkspaceID: workspaceID,+ Query: normalized,+ ExplicitEmptyAssignees: explicitEmptyAssignees,})if err != nil {return "", err@@ -495,7 +499,7 @@ func (h *Handler) compileIssueTableQuery(w http.ResponseWriter, r *http.Request,return issueTableSQL{}, false}- if len(spec.Filters.Assignees) > 0 || spec.Filters.IncludeNoAssignee {+ if spec.Filters.Assignees != nil || spec.Filters.IncludeNoAssignee {ors := make([]string, 0, len(spec.Filters.Assignees)+1)for _, value := range spec.Filters.Assignees {actor, ok := parseIssueTableActor(w, value, "filters.assignees")@@ -507,7 +511,16 @@ func (h *Handler) compileIssueTableQuery(w http.ResponseWriter, r *http.Request,if spec.Filters.IncludeNoAssignee {ors = append(ors, "(i.assignee_type IS NULL AND i.assignee_id IS NULL)")}- where = append(where, "("+strings.Join(ors, " OR ")+")")+ if len(ors) == 0 {+ // Omitted assignees means "no assignee filter"; an explicitly+ // empty list means "match none". The workspace working-agent+ // quick filter relies on this distinction when the final agent+ // finishes (or when an explicit assignee selection intersects the+ // working set to empty).+ where = append(where, "FALSE")+ } else {+ where = append(where, "("+strings.Join(ors, " OR ")+")")+ }}if len(spec.Filters.Creators) > 0 {diff --git a/server/internal/handler/issue_table_query_test.go b/server/internal/handler/issue_table_query_test.goindex b521dbfd45..f035428539 100644--- a/server/internal/handler/issue_table_query_test.go+++ b/server/internal/handler/issue_table_query_test.go@@ -130,6 +130,44 @@ func TestCanonicalIssueTableFingerprintBindsWorkspace(t *testing.T) {}}+func TestIssueTableExplicitEmptyAssigneesMatchesNone(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }++ base := issueTableQuerySpec{+ Scope: issueTableScope{Kind: "workspace"},+ Sort: issueTableSortRequest{Field: "position", Direction: "asc"},+ }+ withEmpty := base+ withEmpty.Filters.Assignees = []issueTableActorRef{}++ unfilteredFingerprint, err := canonicalIssueTableFingerprint(testWorkspaceID, base)+ if err != nil {+ t.Fatal(err)+ }+ emptyFingerprint, err := canonicalIssueTableFingerprint(testWorkspaceID, withEmpty)+ if err != nil {+ t.Fatal(err)+ }+ if unfilteredFingerprint == emptyFingerprint {+ t.Fatal("explicit empty assignees must not share the unfiltered cursor fingerprint")+ }++ w := httptest.NewRecorder()+ compiled, ok := testHandler.compileIssueTableQuery(+ w,+ newRequest(http.MethodPost, "/api/issues/table/rows", nil),+ withEmpty,+ )+ if !ok {+ t.Fatalf("compile failed: %d %s", w.Code, w.Body.String())+ }+ if !strings.Contains(compiled.where, "FALSE") {+ t.Fatalf("explicit empty assignees predicate = %q, want FALSE", compiled.where)+ }+}+func TestIssueTableCursorRejectsAnotherQuery(t *testing.T) {groupKey := "status:todo"cursor := issueTableCursor{diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.goindex 3186f75841..b61f72aa48 100644--- a/server/pkg/db/generated/agent.sql.go+++ b/server/pkg/db/generated/agent.sql.go@@ -3997,6 +3997,160 @@ func (q *Queries) ListWorkspaceAgentTaskSnapshot(ctx context.Context, workspaceIreturn items, nil}+const listWorkspaceWorkingAgents = `-- name: ListWorkspaceWorkingAgents :many+SELECT+ a.id,+ a.name,+ a.avatar_url,+ COUNT(*)::int AS running_task_count+FROM agent a+JOIN agent_task_queue atq ON atq.agent_id = a.id+WHERE a.workspace_id = $1+ AND a.kind = 'user'+ AND a.archived_at IS NULL+ AND atq.status = 'running'+ AND (+ $2::text = ''+ OR ($2::text = 'chat' AND atq.chat_session_id IS NOT NULL)+ OR (+ $2::text = 'autopilot'+ AND atq.chat_session_id IS NULL+ AND atq.autopilot_run_id IS NOT NULL+ )+ OR (+ $2::text = 'issue'+ AND atq.chat_session_id IS NULL+ AND atq.autopilot_run_id IS NULL+ AND atq.issue_id IS NOT NULL+ )+ )+ AND (+ $3::text = ''+ OR EXISTS (+ SELECT 1+ FROM issue i+ WHERE i.id = atq.issue_id+ AND i.workspace_id = a.workspace_id+ AND (+ (+ $3::text IN ('assigned', 'any')+ AND i.assignee_type = 'member'+ AND i.assignee_id = $4::uuid+ )+ OR (+ $3::text IN ('created', 'any')+ AND i.creator_type = 'member'+ AND i.creator_id = $4::uuid+ )+ OR (+ $3::text IN ('involved', 'any')+ AND (+ (+ i.assignee_type = 'agent'+ AND EXISTS (+ SELECT 1+ FROM agent owned_agent+ WHERE owned_agent.id = i.assignee_id+ AND owned_agent.workspace_id = a.workspace_id+ AND owned_agent.owner_id = $4::uuid+ )+ )+ OR (+ i.assignee_type = 'squad'+ AND EXISTS (+ SELECT 1+ FROM squad s+ WHERE s.id = i.assignee_id+ AND s.workspace_id = a.workspace_id+ AND (+ EXISTS (+ SELECT 1+ FROM squad_member sm+ WHERE sm.squad_id = s.id+ AND sm.member_type = 'member'+ AND sm.member_id = $4::uuid+ )+ OR EXISTS (+ SELECT 1+ FROM agent leader+ WHERE leader.id = s.leader_id+ AND leader.workspace_id = a.workspace_id+ AND leader.owner_id = $4::uuid+ )+ OR EXISTS (+ SELECT 1+ FROM squad_member sm+ JOIN agent owned_member ON owned_member.id = sm.member_id+ WHERE sm.squad_id = s.id+ AND sm.member_type = 'agent'+ AND owned_member.workspace_id = a.workspace_id+ AND owned_member.owner_id = $4::uuid+ )+ )+ )+ )+ )+ )+ )+ )+ )+GROUP BY a.id, a.name, a.avatar_url, a.created_at+ORDER BY a.created_at ASC+`++type ListWorkspaceWorkingAgentsParams struct {+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ WorkType string `json:"work_type"`+ MineRelation string `json:"mine_relation"`+ MemberID pgtype.UUID `json:"member_id"`+}++type ListWorkspaceWorkingAgentsRow struct {+ ID pgtype.UUID `json:"id"`+ Name string `json:"name"`+ AvatarUrl pgtype.Text `json:"avatar_url"`+ RunningTaskCount int32 `json:"running_task_count"`+}++// Workspace-level source for consumers that show currently working agents.+// One row per visible, user-authored agent with at least one task that has+// actually started running. work_type is optional (empty = every source);+// source-specific reads use the same precedence as computeTaskKind:+// chat > autopilot > issue. "issue" intentionally groups direct and+// comment-triggered issue work. Quick-create work is present only in the+// unfiltered projection because it has no source FK yet. mine_relation is+// optional (empty = workspace); when set it narrows issue work to the+// authenticated member's My Issues relation.+func (q *Queries) ListWorkspaceWorkingAgents(ctx context.Context, arg ListWorkspaceWorkingAgentsParams) ([]ListWorkspaceWorkingAgentsRow, error) {+ rows, err := q.db.Query(ctx, listWorkspaceWorkingAgents,+ arg.WorkspaceID,+ arg.WorkType,+ arg.MineRelation,+ arg.MemberID,+ )+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ListWorkspaceWorkingAgentsRow{}+ for rows.Next() {+ var i ListWorkspaceWorkingAgentsRow+ if err := rows.Scan(+ &i.ID,+ &i.Name,+ &i.AvatarUrl,+ &i.RunningTaskCount,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const markAgentTaskWaitingLocalDirectory = `-- name: MarkAgentTaskWaitingLocalDirectory :oneUPDATE agent_task_queueSET status = 'waiting_local_directory',diff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sqlindex 0ad0e27721..b03c95d8a5 100644--- a/server/pkg/db/queries/agent.sql+++ b/server/pkg/db/queries/agent.sql@@ -1232,6 +1232,115 @@ SELECT t.* FROM (ORDER BY atq.agent_id, atq.completed_at DESC NULLS LAST) t;+-- name: ListWorkspaceWorkingAgents :many+-- Workspace-level source for consumers that show currently working agents.+-- One row per visible, user-authored agent with at least one task that has+-- actually started running. work_type is optional (empty = every source);+-- source-specific reads use the same precedence as computeTaskKind:+-- chat > autopilot > issue. "issue" intentionally groups direct and+-- comment-triggered issue work. Quick-create work is present only in the+-- unfiltered projection because it has no source FK yet. mine_relation is+-- optional (empty = workspace); when set it narrows issue work to the+-- authenticated member's My Issues relation.+SELECT+ a.id,+ a.name,+ a.avatar_url,+ COUNT(*)::int AS running_task_count+FROM agent a+JOIN agent_task_queue atq ON atq.agent_id = a.id+WHERE a.workspace_id = $1+ AND a.kind = 'user'+ AND a.archived_at IS NULL+ AND atq.status = 'running'+ AND (+ @work_type::text = ''+ OR (@work_type::text = 'chat' AND atq.chat_session_id IS NOT NULL)+ OR (+ @work_type::text = 'autopilot'+ AND atq.chat_session_id IS NULL+ AND atq.autopilot_run_id IS NOT NULL+ )+ OR (+ @work_type::text = 'issue'+ AND atq.chat_session_id IS NULL+ AND atq.autopilot_run_id IS NULL+ AND atq.issue_id IS NOT NULL+ )+ )+ AND (+ @mine_relation::text = ''+ OR EXISTS (+ SELECT 1+ FROM issue i+ WHERE i.id = atq.issue_id+ AND i.workspace_id = a.workspace_id+ AND (+ (+ @mine_relation::text IN ('assigned', 'any')+ AND i.assignee_type = 'member'+ AND i.assignee_id = @member_id::uuid+ )+ OR (+ @mine_relation::text IN ('created', 'any')+ AND i.creator_type = 'member'+ AND i.creator_id = @member_id::uuid+ )+ OR (+ @mine_relation::text IN ('involved', 'any')+ AND (+ (+ i.assignee_type = 'agent'+ AND EXISTS (+ SELECT 1+ FROM agent owned_agent+ WHERE owned_agent.id = i.assignee_id+ AND owned_agent.workspace_id = a.workspace_id+ AND owned_agent.owner_id = @member_id::uuid+ )+ )+ OR (+ i.assignee_type = 'squad'+ AND EXISTS (+ SELECT 1+ FROM squad s+ WHERE s.id = i.assignee_id+ AND s.workspace_id = a.workspace_id+ AND (+ EXISTS (+ SELECT 1+ FROM squad_member sm+ WHERE sm.squad_id = s.id+ AND sm.member_type = 'member'+ AND sm.member_id = @member_id::uuid+ )+ OR EXISTS (+ SELECT 1+ FROM agent leader+ WHERE leader.id = s.leader_id+ AND leader.workspace_id = a.workspace_id+ AND leader.owner_id = @member_id::uuid+ )+ OR EXISTS (+ SELECT 1+ FROM squad_member sm+ JOIN agent owned_member ON owned_member.id = sm.member_id+ WHERE sm.squad_id = s.id+ AND sm.member_type = 'agent'+ AND owned_member.workspace_id = a.workspace_id+ AND owned_member.owner_id = @member_id::uuid+ )+ )+ )+ )+ )+ )+ )+ )+ )+GROUP BY a.id, a.name, a.avatar_url, a.created_at+ORDER BY a.created_at ASC;+-- name: ListTasksByIssue :manySELECT * FROM agent_task_queueWHERE issue_id = $1