Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(issues): agents-working chip on the sub-issues header (#5825) (#5834)
Jiayuan Zhang2274f521dc95
diff --git a/packages/core/agents/queries.ts b/packages/core/agents/queries.tsindex c63f4b4fc0..da24146194 100644--- a/packages/core/agents/queries.ts+++ b/packages/core/agents/queries.ts@@ -16,12 +16,17 @@ export const workspaceWorkingAgentsKeys = {wsId: string,type?: WorkspaceWorkingAgentType,mineRelation?: WorkspaceWorkingAgentMineRelation,+ parentIssueId?: string,) =>[...workspaceWorkingAgentsKeys.all(wsId),"list",type ?? "all",- mineRelation ? `mine:${mineRelation}` : "workspace",+ mineRelation+ ? `mine:${mineRelation}`+ : parentIssueId+ ? `parent:${parentIssueId}`+ : "workspace",] as const,};@@ -54,17 +59,25 @@ 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.+// Working-agent summaries, optionally narrowed to a My Issues relation or to+// one issue's direct children. Task lifecycle WebSocket events invalidate+// every narrowing immediately; the short stale time is the reconnect /+// missed-event safety net.export function workspaceWorkingAgentsOptions(wsId: string,type?: WorkspaceWorkingAgentType,mineRelation?: WorkspaceWorkingAgentMineRelation,+ parentIssueId?: string,) {return queryOptions({- queryKey: workspaceWorkingAgentsKeys.list(wsId, type, mineRelation),- queryFn: () => api.getWorkspaceWorkingAgents(type, mineRelation),+ queryKey: workspaceWorkingAgentsKeys.list(+ wsId,+ type,+ mineRelation,+ parentIssueId,+ ),+ queryFn: () =>+ api.getWorkspaceWorkingAgents(type, mineRelation, parentIssueId),staleTime: 30 * 1000,gcTime: 5 * 60 * 1000,refetchOnWindowFocus: true,diff --git a/packages/core/api/client.test.ts b/packages/core/api/client.test.tsindex 0a0d545766..8987bebc60 100644--- a/packages/core/api/client.test.ts+++ b/packages/core/api/client.test.ts@@ -424,10 +424,20 @@ describe("ApiClient workspace working agents", () => {client.getWorkspaceWorkingAgents("issue"),).resolves.toEqual(payload);await expect(client.getWorkspaceWorkingAgents()).resolves.toEqual(payload);+ await expect(+ client.getWorkspaceWorkingAgents("issue", undefined, "parent-1"),+ ).resolves.toEqual(payload);+ // The server rejects parent alongside scope, so a My Issues relation wins+ // and the parent is dropped rather than sent into a 400.+ await expect(+ client.getWorkspaceWorkingAgents("issue", "assigned", "parent-1"),+ ).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",+ "https://api.example.test/api/working-agents?type=issue&parent=parent-1",+ "https://api.example.test/api/working-agents?type=issue&scope=mine&relation=assigned",]);});});diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 21d24667d1..63ca4c9ea2 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -1733,15 +1733,22 @@ export class ApiClient {// 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.+ // `parentIssueId` narrows the projection to that issue's direct children,+ // which is how the sub-issue header on issue detail reads the same source+ // as the Issues list header. The server rejects combining it with `scope`,+ // so callers pass one or the other.async getWorkspaceWorkingAgents(type?: WorkspaceWorkingAgentType,mineRelation?: WorkspaceWorkingAgentMineRelation,+ parentIssueId?: string,): Promise<WorkspaceWorkingAgent[]> {const search = new URLSearchParams();if (type) search.set("type", type);if (mineRelation) {search.set("scope", "mine");search.set("relation", mineRelation);+ } else if (parentIssueId) {+ search.set("parent", parentIssueId);}const query = search.toString();return this.fetch(`/api/working-agents${query ? `?${query}` : ""}`);diff --git a/packages/views/issues/components/issue-detail.test.tsx b/packages/views/issues/components/issue-detail.test.tsxindex c11de11a67..1eafd82462 100644--- a/packages/views/issues/components/issue-detail.test.tsx+++ b/packages/views/issues/components/issue-detail.test.tsx@@ -274,6 +274,8 @@ const mockApiObj = vi.hoisted(() => ({listChildIssues: vi.fn().mockResolvedValue({ issues: [] }),getChildIssueProgress: vi.fn().mockResolvedValue({ progress: [] }),getAgentTaskSnapshot: vi.fn().mockResolvedValue([]),+ // The sub-issues header chip reads this narrowed to the parent issue.+ getWorkspaceWorkingAgents: vi.fn().mockResolvedValue([]),listProperties: vi.fn().mockResolvedValue({ properties: [], total: 0 }),listIssues: vi.fn().mockResolvedValue({ issues: [], total: 0 }),uploadFile: vi.fn(),@@ -626,6 +628,7 @@ describe("IssueDetail (shared)", () => {mockApiObj.listChildIssues.mockResolvedValue({ issues: [] });mockApiObj.getChildIssueProgress.mockResolvedValue({ progress: [] });mockApiObj.getAgentTaskSnapshot.mockResolvedValue([]);+ mockApiObj.getWorkspaceWorkingAgents.mockResolvedValue([]);mockApiObj.listProperties.mockResolvedValue({ properties: [], total: 0 });mockApiObj.listIssues.mockResolvedValue({ issues: [], total: 0 });mockApiObj.getActiveTasksForIssue.mockResolvedValue({ tasks: [] });diff --git a/packages/views/issues/components/issue-detail.tsx b/packages/views/issues/components/issue-detail.tsxindex b276810a91..0325de883f 100644--- a/packages/views/issues/components/issue-detail.tsx+++ b/packages/views/issues/components/issue-detail.tsx@@ -58,6 +58,7 @@ import { Switch } from "@multica/ui/components/ui/switch";import { IssueActionsDropdown, useIssueActions, IssueActionsContextMenu, IssueContextMenuProvider } from "../actions";import { LabelChip } from "../../labels/label-chip";import { IssueAgentActivityIndicator } from "./issue-agent-activity-indicator";+import { SubIssuesAgentWorkingChip } from "./sub-issues-agent-working-chip";import { ProjectPicker } from "../../projects/components/project-picker";import { LocalDirectoryHint } from "../../projects/components/local-directory-hint";import { CommentCard } from "./comment-card";@@ -2478,6 +2479,9 @@ export function IssueDetail({ issueId, onDelete, onDone, defaultSidebarOpen = tr{doneCount}/{childIssues.length}</span></div>+ {/* issue.id, not the route param — the endpoint takes a+ UUID and the route may carry a human-readable id. */}+ <SubIssuesAgentWorkingChip parentIssueId={issue.id} /><inputtype="checkbox"checked={allChildrenSelected}diff --git a/packages/views/issues/components/sub-issues-agent-working-chip.test.tsx b/packages/views/issues/components/sub-issues-agent-working-chip.test.tsxnew file mode 100644index 0000000000..ff3ddd7afb--- /dev/null+++ b/packages/views/issues/components/sub-issues-agent-working-chip.test.tsx@@ -0,0 +1,152 @@+import { cleanup, render, screen } from "@testing-library/react";+import { beforeEach, describe, expect, it, vi } from "vitest";+import type { WorkspaceWorkingAgent } from "@multica/core/types";++const mockState = vi.hoisted(() => ({+ agents: [] as WorkspaceWorkingAgent[],+ optionsCalls: [] as unknown[][],+}));++vi.mock("@multica/core/hooks", () => ({+ useWorkspaceId: () => "ws-1",+}));++vi.mock("@multica/core/agents", () => ({+ workspaceWorkingAgentsOptions: (...args: unknown[]) => {+ mockState.optionsCalls.push(args);+ return { queryKey: ["working-agents", ...args] };+ },+}));++vi.mock("../../agents/components/agent-avatar-stack", () => ({+ AgentAvatarStack: ({ agentIds }: { agentIds: string[] }) => (+ <div data-testid="agent-avatar-stack">{agentIds.join(",")}</div>+ ),+}));++vi.mock("./workspace-agent-working-chip", () => ({+ WorkingAgentsHoverContent: ({+ agents,+ }: {+ agents: readonly WorkspaceWorkingAgent[];+ }) => <div data-testid="hover-body">{agents.length}</div>,+}));++vi.mock("../../i18n", () => ({+ useT: () => ({+ t: (+ selector: (keys: Record<string, Record<string, string>>) => string,+ options?: { count?: number },+ ) => {+ const key = selector(+ new Proxy(+ {},+ {+ get: (_t, ns: string) =>+ new Proxy({}, { get: (_n, k: string) => `${ns}.${k}` }),+ },+ ) as Record<string, Record<string, string>>,+ );+ return options?.count !== undefined ? `${key}:${options.count}` : key;+ },+ }),+}));++// The hover card only portals its content once open, so absence of the body+// cannot distinguish "closed" from "not wired up". Mock the primitive and+// assert on the wrapper itself (same approach as the row indicator's test).+vi.mock("@multica/ui/components/ui/hover-card", () => ({+ HoverCard: ({ children }: { children: React.ReactNode }) => (+ <div data-testid="hover-card">{children}</div>+ ),+ HoverCardTrigger: ({ children }: { children: React.ReactNode }) => (+ <span data-testid="hover-card-trigger">{children}</span>+ ),+ HoverCardContent: ({ children }: { children: React.ReactNode }) => (+ <div>{children}</div>+ ),+}));++vi.mock("@tanstack/react-query", async () => {+ const actual =+ await vi.importActual<typeof import("@tanstack/react-query")>(+ "@tanstack/react-query",+ );+ return { ...actual, useQuery: () => ({ data: mockState.agents }) };+});++import { SubIssuesAgentWorkingChip } from "./sub-issues-agent-working-chip";++function makeAgent(+ overrides: Partial<WorkspaceWorkingAgent> = {},+): WorkspaceWorkingAgent {+ return {+ id: "agent-1",+ name: "Agent One",+ avatar_url: null,+ running_task_count: 1,+ issue_ids: ["child-1"],+ ...overrides,+ };+}++beforeEach(() => {+ cleanup();+ mockState.agents = [];+ mockState.optionsCalls = [];+});++describe("SubIssuesAgentWorkingChip", () => {+ it("asks the server to narrow the projection to the parent's children", () => {+ mockState.agents = [makeAgent()];++ render(<SubIssuesAgentWorkingChip parentIssueId="parent-1" />);++ // type=issue plus the parent id, and no My Issues relation. Getting this+ // wrong silently widens the chip to the whole workspace.+ expect(mockState.optionsCalls).toEqual([+ ["ws-1", "issue", undefined, "parent-1"],+ ]);+ });++ it("counts the agents the server returned", () => {+ mockState.agents = [+ makeAgent({ id: "agent-1", issue_ids: ["child-1"] }),+ makeAgent({ id: "agent-2", issue_ids: ["child-2"] }),+ ];++ render(<SubIssuesAgentWorkingChip parentIssueId="parent-1" />);++ expect(+ screen.getByText("agent_activity.chip_agents_working:2"),+ ).not.toBeNull();+ expect(screen.getByTestId("agent-avatar-stack").textContent).toBe(+ "agent-1,agent-2",+ );+ });++ it("hands the same agents to the hover body as it counted", () => {+ mockState.agents = [+ makeAgent({ id: "agent-1" }),+ makeAgent({ id: "agent-2" }),+ makeAgent({ id: "agent-3" }),+ ];++ render(<SubIssuesAgentWorkingChip parentIssueId="parent-1" />);++ // The number and the hover body must never disagree — they are the same+ // list, not two derivations of one snapshot.+ expect(+ screen.getByText("agent_activity.chip_agents_working:3"),+ ).not.toBeNull();+ expect(screen.getByTestId("hover-body").textContent).toBe("3");+ });++ it("renders nothing when no agent is working on a sub-issue", () => {+ const { container } = render(+ <SubIssuesAgentWorkingChip parentIssueId="parent-1" />,+ );++ expect(container.firstChild).toBeNull();+ });+});diff --git a/packages/views/issues/components/sub-issues-agent-working-chip.tsx b/packages/views/issues/components/sub-issues-agent-working-chip.tsxnew file mode 100644index 0000000000..92b56bbd04--- /dev/null+++ b/packages/views/issues/components/sub-issues-agent-working-chip.tsx@@ -0,0 +1,73 @@+"use client";++import { memo } from "react";+import { useQuery } from "@tanstack/react-query";+import {+ HoverCard,+ HoverCardTrigger,+ HoverCardContent,+} from "@multica/ui/components/ui/hover-card";+import { useWorkspaceId } from "@multica/core/hooks";+import { workspaceWorkingAgentsOptions } from "@multica/core/agents";+import { AgentAvatarStack } from "../../agents/components/agent-avatar-stack";+import { WorkingAgentsHoverContent } from "./workspace-agent-working-chip";+import { useT } from "../../i18n";++interface SubIssuesAgentWorkingChipProps {+ /** Parent issue whose direct children this chip aggregates over. */+ parentIssueId: string;+}++/**+ * Aggregate "N agents working" chip for the sub-issues header in issue+ * detail (multica#5825). The per-row IssueAgentActivityIndicator answers+ * "which sub-issue is being worked on"; this chip answers "how many agents+ * are on this parent's children right now" without scanning the rows — and+ * keeps that signal visible while the list is collapsed.+ *+ * It reads the same /api/working-agents projection as the Issues list header,+ * narrowed with `parent`. That is deliberate: a header count is a claim about+ * a scope, so the server owns both the scope and the arithmetic, exactly as+ * it does for the Issues list. Deriving it here from the workspace task+ * snapshot would put a second definition of "working" in the client, and the+ * count and the hover body would each have to re-derive it.+ *+ * Row indicators keep reading the snapshot — one shared query sliced per row+ * is the right shape for a per-row cue, and a stale row decoration costs+ * nothing. A header number is the opposite: it has to be authoritative.+ */+export const SubIssuesAgentWorkingChip = memo(+ function SubIssuesAgentWorkingChip({+ parentIssueId,+ }: SubIssuesAgentWorkingChipProps) {+ const { t } = useT("issues");+ const wsId = useWorkspaceId();+ const { data: agents = [] } = useQuery(+ workspaceWorkingAgentsOptions(wsId, "issue", undefined, parentIssueId),+ );++ if (agents.length === 0) return null;++ const agentIds = agents.map((agent) => agent.id);++ return (+ <HoverCard>+ <HoverCardTrigger+ render={+ <span className="inline-flex shrink-0 items-center gap-1.5 rounded-full bg-muted/60 px-2 py-0.5" />+ }+ >+ <AgentAvatarStack agentIds={agentIds} size="xs" max={3} />+ <span className="animate-chat-text-shimmer text-[11px] font-medium leading-none tabular-nums">+ {t(($) => $.agent_activity.chip_agents_working, {+ count: agentIds.length,+ })}+ </span>+ </HoverCardTrigger>+ <HoverCardContent align="start" className="w-72">+ <WorkingAgentsHoverContent agents={agents} />+ </HoverCardContent>+ </HoverCard>+ );+ },+);diff --git a/packages/views/issues/components/workspace-agent-working-chip.tsx b/packages/views/issues/components/workspace-agent-working-chip.tsxindex e38fd8953d..e37a57a3c1 100644--- a/packages/views/issues/components/workspace-agent-working-chip.tsx+++ b/packages/views/issues/components/workspace-agent-working-chip.tsx@@ -38,7 +38,13 @@ export function chipAppearance(return { variant: "outline", className: `${layout} text-muted-foreground` };}-function WorkingAgentsHoverContent({+/**+ * Hover body for every surface that reads the working-agents projection —+ * the workspace filter chip here and the sub-issues header chip on issue+ * detail. Shared so a narrowed read and an unnarrowed one describe activity+ * the same way; the only difference between the two is the query's scope.+ */+export function WorkingAgentsHoverContent({agents,}: {agents: readonly WorkspaceWorkingAgent[];diff --git a/packages/views/issues/surface/use-issue-surface-controller.test.tsx b/packages/views/issues/surface/use-issue-surface-controller.test.tsxindex 6b2f096cea..b005ee7d39 100644--- a/packages/views/issues/surface/use-issue-surface-controller.test.tsx+++ b/packages/views/issues/surface/use-issue-surface-controller.test.tsx@@ -858,7 +858,7 @@ describe("useIssueSurfaceController", () => {);expect(result.current.tableQuerySpec.filters.assignees).toBeUndefined();expect(result.current.tableQuerySpec.filters.working_only).toBeUndefined();- expect(getWorkspaceWorkingAgents).toHaveBeenCalledWith("issue", undefined);+ expect(getWorkspaceWorkingAgents).toHaveBeenCalledWith("issue", undefined, undefined);expect(listIssues).not.toHaveBeenCalled();});@@ -891,6 +891,7 @@ describe("useIssueSurfaceController", () => {expect(getWorkspaceWorkingAgents).toHaveBeenCalledWith("issue","assigned",+ undefined,),);expect(result.current.tableQuerySpec.filters.working_issue_ids).toEqual([]);@@ -927,7 +928,7 @@ describe("useIssueSurfaceController", () => {);expect(result.current.tableQuerySpec.filters.assignees).toBeUndefined();expect(result.current.tableQuerySpec.filters.working_only).toBeUndefined();- expect(getWorkspaceWorkingAgents).toHaveBeenCalledWith("issue", undefined);+ expect(getWorkspaceWorkingAgents).toHaveBeenCalledWith("issue", undefined, undefined);expect(getAgentTaskSnapshot).not.toHaveBeenCalled();},);@@ -1336,7 +1337,7 @@ describe("useIssueSurfaceController", () => {await waitFor(() => expect(result.current.isLoading).toBe(false));expect(result.current.workingScopeIssues).toEqual([]);- expect(getWorkspaceWorkingAgents).toHaveBeenCalledWith("issue", undefined);+ expect(getWorkspaceWorkingAgents).toHaveBeenCalledWith("issue", undefined, undefined);expect(getAgentTaskSnapshot).not.toHaveBeenCalled();});@@ -1509,6 +1510,7 @@ describe("useIssueSurfaceController", () => {expect(getWorkspaceWorkingAgents).toHaveBeenCalledWith("issue",undefined,+ undefined,),);diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.goindex 1f5fd2d3a8..47feadb8df 100644--- a/server/internal/handler/agent.go+++ b/server/internal/handler/agent.go@@ -2188,13 +2188,36 @@ func (h *Handler) ListWorkspaceWorkingAgents(w http.ResponseWriter, r *http.Requreturn}+ // Narrows the projection to one issue's direct children, so an issue+ // detail's sub-issue header reads this endpoint instead of deriving a+ // count client-side. Left zero when absent, which the query treats as+ // NULL and therefore as "no narrowing" — an older client that never+ // sends it keeps the exact workspace-wide behaviour.+ var parentIssueID pgtype.UUID+ if raw := strings.TrimSpace(r.URL.Query().Get("parent")); raw != "" {+ if workType != "issue" {+ writeError(w, http.StatusBadRequest, "parent requires type=issue")+ return+ }+ if scope != "" {+ writeError(w, http.StatusBadRequest, "parent cannot be combined with scope")+ return+ }+ var ok bool+ parentIssueID, ok = parseUUIDOrBadRequest(w, raw, "parent")+ if !ok {+ return+ }+ }+rows, err := h.Queries.ListWorkspaceWorkingAgents(r.Context(),db.ListWorkspaceWorkingAgentsParams{- WorkspaceID: parseUUID(workspaceID),- WorkType: workType,- MineRelation: mineRelation,- MemberID: memberID,+ WorkspaceID: parseUUID(workspaceID),+ WorkType: workType,+ MineRelation: mineRelation,+ MemberID: memberID,+ ParentIssueID: parentIssueID,},)if err != nil {diff --git a/server/internal/handler/agent_test.go b/server/internal/handler/agent_test.goindex e8b0b944f5..c70b98b1d0 100644--- a/server/internal/handler/agent_test.go+++ b/server/internal/handler/agent_test.go@@ -527,6 +527,9 @@ func TestListWorkspaceWorkingAgentsRejectsInvalidFilters(t *testing.T) {"/api/working-agents?type=issue&scope=workspace","/api/working-agents?type=issue&relation=assigned","/api/working-agents?type=issue&scope=mine&relation=watching",+ "/api/working-agents?type=issue&parent=not-a-uuid",+ "/api/working-agents?type=chat&parent=00000000-0000-0000-0000-000000000000",+ "/api/working-agents?type=issue&scope=mine&parent=00000000-0000-0000-0000-000000000000",} {t.Run(path, func(t *testing.T) {w := httptest.NewRecorder()@@ -541,6 +544,151 @@ func TestListWorkspaceWorkingAgentsRejectsInvalidFilters(t *testing.T) {}}+// The sub-issue header on issue detail reads this endpoint with ?parent=, so+// the projection must cover exactly one issue's direct children. The final+// sub-test is the compatibility guard: dropping the parameter has to return+// the unnarrowed workspace projection, which is what an older installed+// client keeps sending.+func TestListWorkspaceWorkingAgentsParentScope(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }++ ctx := context.Background()+ childAgentID := createHandlerTestAgent(t, "working-agents-parent-child", []byte(`{}`))+ siblingAgentID := createHandlerTestAgent(t, "working-agents-parent-sibling", []byte(`{}`))++ insertedIssueIDs := make([]string, 0, 4)+ insertIssue := func(title string, parentIssueID any) string {+ t.Helper()+ var issueID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO issue (+ workspace_id, number, title, status, priority,+ creator_type, creator_id, parent_issue_id+ )+ SELECT $1, COALESCE(MIN(number), 0) - 1, $2, 'todo', 'none',+ 'member', $3, $4+ FROM issue+ WHERE workspace_id = $1+ RETURNING id+ `, testWorkspaceID, title, testUserID, parentIssueID).Scan(&issueID); err != nil {+ t.Fatalf("insert issue %q: %v", title, err)+ }+ insertedIssueIDs = append(insertedIssueIDs, issueID)+ return issueID+ }+ parentIssueID := insertIssue("working-agents-parent", nil)+ firstChildID := insertIssue("working-agents-parent-first-child", parentIssueID)+ secondChildID := insertIssue("working-agents-parent-second-child", parentIssueID)+ // Same workspace, no parent — must never leak into the narrowed read even+ // though the same agent is running on it.+ unrelatedIssueID := insertIssue("working-agents-parent-unrelated", nil)+ t.Cleanup(func() {+ for _, issueID := range insertedIssueIDs {+ testPool.Exec(ctx, `DELETE FROM issue WHERE id = $1`, issueID)+ }+ })++ insertedTaskIDs := make([]string, 0, 3)+ for _, fixture := range []struct {+ agentID string+ issueID string+ }{+ {childAgentID, firstChildID},+ {siblingAgentID, secondChildID},+ {childAgentID, unrelatedIssueID},+ } {+ var taskID string+ if err := testPool.QueryRow(ctx, `+ INSERT INTO agent_task_queue (+ agent_id, runtime_id, status, priority, issue_id, started_at+ )+ VALUES ($1, $2, 'running', 0, $3, now())+ RETURNING id+ `, fixture.agentID, testRuntimeID, fixture.issueID).Scan(&taskID); err != nil {+ t.Fatalf("insert running task: %v", err)+ }+ insertedTaskIDs = append(insertedTaskIDs, taskID)+ }+ t.Cleanup(func() {+ for _, taskID := range insertedTaskIDs {+ testPool.Exec(ctx, `DELETE FROM agent_task_queue WHERE id = $1`, taskID)+ }+ })++ read := func(t *testing.T, query string) map[string]WorkspaceWorkingAgent {+ t.Helper()+ w := httptest.NewRecorder()+ testHandler.ListWorkspaceWorkingAgents(+ w,+ newRequest(http.MethodGet, "/api/working-agents"+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)+ }+ byID := make(map[string]WorkspaceWorkingAgent, len(agents))+ for _, agent := range agents {+ byID[agent.ID] = agent+ }+ return byID+ }++ t.Run("narrows to the parent's direct children", func(t *testing.T) {+ byID := read(t, "?type=issue&parent="+parentIssueID)++ child, ok := byID[childAgentID]+ if !ok {+ t.Fatalf("agent running on a child issue was not returned")+ }+ if child.RunningTaskCount != 1 {+ t.Errorf("running_task_count = %d, want 1", child.RunningTaskCount)+ }+ if len(child.IssueIDs) != 1 || child.IssueIDs[0] != firstChildID {+ t.Errorf("issue_ids = %v, want [%s]", child.IssueIDs, firstChildID)+ }+ if _, ok := byID[siblingAgentID]; !ok {+ t.Errorf("agent running on the second child was not returned")+ }+ })++ t.Run("an unrelated issue's parent yields nothing", func(t *testing.T) {+ byID := read(t, "?type=issue&parent="+unrelatedIssueID)++ if _, ok := byID[childAgentID]; ok {+ t.Errorf("childless issue must not return the child agent")+ }+ if _, ok := byID[siblingAgentID]; ok {+ t.Errorf("childless issue must not return the sibling agent")+ }+ })++ t.Run("omitting parent keeps the workspace projection", func(t *testing.T) {+ byID := read(t, "?type=issue")++ child, ok := byID[childAgentID]+ if !ok {+ t.Fatalf("agent was not returned by the unnarrowed read")+ }+ if child.RunningTaskCount != 2 {+ t.Errorf("running_task_count = %d, want 2", child.RunningTaskCount)+ }+ seen := make(map[string]struct{}, len(child.IssueIDs))+ for _, issueID := range child.IssueIDs {+ seen[issueID] = struct{}{}+ }+ for _, want := range []string{firstChildID, unrelatedIssueID} {+ if _, ok := seen[want]; !ok {+ t.Errorf("issue_ids = %v, missing %s", child.IssueIDs, want)+ }+ }+ })+}+func TestCreateAgent_RejectsDuplicateName(t *testing.T) {if testHandler == nil {t.Skip("database not available")diff --git a/server/pkg/db/generated/agent.sql.go b/server/pkg/db/generated/agent.sql.goindex 561455db9e..f2549ab8f8 100644--- a/server/pkg/db/generated/agent.sql.go+++ b/server/pkg/db/generated/agent.sql.go@@ -4229,15 +4229,26 @@ WHERE a.workspace_id = $1)))+ AND (+ $5::uuid IS NULL+ OR EXISTS (+ SELECT 1+ FROM issue child+ WHERE child.id = atq.issue_id+ AND child.workspace_id = a.workspace_id+ AND child.parent_issue_id = $5::uuid+ )+ )GROUP BY a.id, a.name, a.avatar_url, a.created_atORDER 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"`+ WorkspaceID pgtype.UUID `json:"workspace_id"`+ WorkType string `json:"work_type"`+ MineRelation string `json:"mine_relation"`+ MemberID pgtype.UUID `json:"member_id"`+ ParentIssueID pgtype.UUID `json:"parent_issue_id"`}type ListWorkspaceWorkingAgentsRow struct {@@ -4256,13 +4267,17 @@ type ListWorkspaceWorkingAgentsRow struct {// 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.+// authenticated member's My Issues relation. parent_issue_id is optional+// (NULL = workspace); when set it narrows issue work to the direct children+// of that issue, so an issue detail's sub-issue header reads the same+// projection as the Issues list header instead of deriving its own count.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,+ arg.ParentIssueID,)if err != nil {return nil, errdiff --git a/server/pkg/db/queries/agent.sql b/server/pkg/db/queries/agent.sqlindex 48f70e7004..7eef734700 100644--- a/server/pkg/db/queries/agent.sql+++ b/server/pkg/db/queries/agent.sql@@ -1369,7 +1369,10 @@ SELECT t.* FROM (-- 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.+-- authenticated member's My Issues relation. parent_issue_id is optional+-- (NULL = workspace); when set it narrows issue work to the direct children+-- of that issue, so an issue detail's sub-issue header reads the same+-- projection as the Issues list header instead of deriving its own count.SELECTa.id,a.name,@@ -1471,6 +1474,16 @@ WHERE a.workspace_id = $1)))+ AND (+ @parent_issue_id::uuid IS NULL+ OR EXISTS (+ SELECT 1+ FROM issue child+ WHERE child.id = atq.issue_id+ AND child.workspace_id = a.workspace_id+ AND child.parent_issue_id = @parent_issue_id::uuid+ )+ )GROUP BY a.id, a.name, a.avatar_url, a.created_atORDER BY a.created_at ASC;