Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
feat(squads): show member working status on squad detail page (#2768)
Jiayuan Zhang46c1e2c889a0
diff --git a/packages/core/api/client.ts b/packages/core/api/client.tsindex 30bbeddb8b..bab49472d7 100644--- a/packages/core/api/client.ts+++ b/packages/core/api/client.ts@@ -98,6 +98,7 @@ import type {GitHubConnectResponse,Squad,SquadMember,+ SquadMemberStatusListResponse,} from "../types";import type { OnboardingCompletionPath } from "../onboarding/types";import { type Logger, noopLogger } from "../logger";@@ -121,12 +122,14 @@ import {EMPTY_CREATE_AGENT_FROM_TEMPLATE_RESPONSE,EMPTY_GROUPED_ISSUES_RESPONSE,EMPTY_LIST_ISSUES_RESPONSE,+ EMPTY_SQUAD_MEMBER_STATUS_LIST,EMPTY_TIMELINE_ENTRIES,EMPTY_LIST_WEBHOOK_DELIVERIES_RESPONSE,EMPTY_WEBHOOK_DELIVERY,GroupedIssuesResponseSchema,ListIssuesResponseSchema,ListWebhookDeliveriesResponseSchema,+ SquadMemberStatusListResponseSchema,SubscribersListSchema,TimelineEntriesSchema,WebhookDeliveryResponseSchema,@@ -1544,6 +1547,17 @@ export class ApiClient {return this.fetch(`/api/squads/${squadId}/members/role`, { method: "PATCH", body: JSON.stringify(data) });}+ // Per-squad members status snapshot: one row per member with derived+ // working/idle/offline/unstable plus the issues each agent is currently+ // running. Parsed with a lenient schema so a new server-side status+ // value or extra field can't white-screen the Squad page (#2143).+ async getSquadMemberStatus(squadId: string): Promise<SquadMemberStatusListResponse> {+ const raw = await this.fetch<unknown>(`/api/squads/${squadId}/members/status`);+ return parseWithFallback(raw, SquadMemberStatusListResponseSchema, EMPTY_SQUAD_MEMBER_STATUS_LIST, {+ endpoint: "GET /api/squads/:id/members/status",+ }) as SquadMemberStatusListResponse;+ }+// Autopilotsasync listAutopilots(params?: { status?: string }): Promise<ListAutopilotsResponse> {const search = new URLSearchParams();diff --git a/packages/core/api/schemas.ts b/packages/core/api/schemas.tsindex 77a66d65a1..dc6a9210a4 100644--- a/packages/core/api/schemas.ts+++ b/packages/core/api/schemas.ts@@ -336,6 +336,31 @@ export const EMPTY_CREATE_AGENT_FROM_TEMPLATE_RESPONSE: CreateAgentFromTemplateRreused_skill_ids: [],};+// Squad member status — backs the Squad detail page's Members tab. status+// is `string | null` (not the narrow `SquadMemberStatusValue` union) so a+// new server-side status doesn't fail the parse; the UI defaults to a+// neutral pill for unknown values.+const SquadActiveIssueBriefSchema = z.object({+ issue_id: z.string(),+ identifier: z.string(),+ title: z.string(),+ issue_status: z.string(),+}).loose();++const SquadMemberStatusSchema = z.object({+ member_type: z.string(),+ member_id: z.string(),+ status: z.string().nullable().optional().transform((v) => v ?? null),+ active_issues: z.array(SquadActiveIssueBriefSchema).default([]),+ last_active_at: z.string().nullable().optional().transform((v) => v ?? null),+}).loose();++export const SquadMemberStatusListResponseSchema = z.object({+ members: z.array(SquadMemberStatusSchema).default([]),+}).loose();++export const EMPTY_SQUAD_MEMBER_STATUS_LIST = { members: [] };+// ---------------------------------------------------------------------------// Structured error body — POST /api/workspaces/:wsId/issues 409 conflict.//diff --git a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsxindex dc9ccaf318..58ae33d647 100644--- a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx+++ b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx@@ -102,8 +102,8 @@ describe("useRealtimeSync — ws instance change", () => {rerender({ ws: ws2 });// Should have called invalidateQueries for all workspace-scoped keys- // (11 workspace-scoped + 1 workspaceKeys.list() = 12 calls)- expect(invalidateSpy).toHaveBeenCalledTimes(12);+ // (12 workspace-scoped + 1 workspaceKeys.list() = 13 calls)+ expect(invalidateSpy).toHaveBeenCalledTimes(13);});it("does not re-invalidate when rerendered with the same ws instance", () => {diff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.tsindex 85fc8702ed..03843ae1f2 100644--- a/packages/core/realtime/use-realtime-sync.ts+++ b/packages/core/realtime/use-realtime-sync.ts@@ -119,6 +119,7 @@ function invalidateWorkspaceScopedQueries(qc: QueryClient): void {qc.invalidateQueries({ queryKey: inboxKeys.all(wsId) });qc.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) });qc.invalidateQueries({ queryKey: workspaceKeys.members(wsId) });+ qc.invalidateQueries({ queryKey: workspaceKeys.squads(wsId) });qc.invalidateQueries({ queryKey: workspaceKeys.skills(wsId) });qc.invalidateQueries({ queryKey: projectKeys.all(wsId) });qc.invalidateQueries({ queryKey: runtimeKeys.all(wsId) });@@ -177,7 +178,14 @@ export function useRealtimeSync(},agent: () => {const wsId = getCurrentWsId();- if (wsId) qc.invalidateQueries({ queryKey: workspaceKeys.agents(wsId) });+ if (wsId) {+ qc.invalidateQueries({ queryKey: workspaceKeys.agents(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. Prefix-matches both the+ // squad list and every squadMemberStatus query.+ qc.invalidateQueries({ queryKey: workspaceKeys.squads(wsId) });+ }},member: () => {const wsId = getCurrentWsId();@@ -220,7 +228,14 @@ export function useRealtimeSync(},daemon: () => {const wsId = getCurrentWsId();- if (wsId) qc.invalidateQueries({ queryKey: runtimeKeys.all(wsId) });+ if (wsId) {+ qc.invalidateQueries({ queryKey: runtimeKeys.all(wsId) });+ // Runtime online/offline transitions move the derived status+ // for every agent that hosts on this runtime, which shifts the+ // working/idle/offline pill on the squad page. Same prefix+ // invalidation pattern as the agent handler above.+ qc.invalidateQueries({ queryKey: workspaceKeys.squads(wsId) });+ }},autopilot: () => {const wsId = getCurrentWsId();@@ -266,6 +281,10 @@ export function useRealtimeSync(// shape as the tasks invalidation above — any task lifecycle// event shifts the aggregated usage numbers.qc.invalidateQueries({ queryKey: ["issues", "usage"] });+ // Squad members-status reads the same task lifecycle to flip+ // working ↔ idle for each agent member. Prefix-matches every+ // mounted squad-page's members-status query in O(1).+ qc.invalidateQueries({ queryKey: workspaceKeys.squads(wsId) });},};diff --git a/packages/core/types/index.ts b/packages/core/types/index.tsindex 92990aa751..c8dbb3e67e 100644--- a/packages/core/types/index.ts+++ b/packages/core/types/index.ts@@ -119,4 +119,8 @@ export type {RemoveSquadMemberRequest,UpdateSquadMemberRoleRequest,CreateSquadActivityLogRequest,+ SquadMemberStatusValue,+ SquadActiveIssueBrief,+ SquadMemberStatus,+ SquadMemberStatusListResponse,} from "./squad";diff --git a/packages/core/types/squad.ts b/packages/core/types/squad.tsindex 63ed4b43a8..55103da0c3 100644--- a/packages/core/types/squad.ts+++ b/packages/core/types/squad.ts@@ -76,3 +76,32 @@ export interface CreateSquadActivityLogRequest {outcome: SquadActivityOutcome;details?: unknown;}++// SquadMemberStatus mirrors the four-way bucket the back-end derives in+// handler/squad.go::deriveSquadMemberStatus. Kept as a string union here+// (rather than re-derived from snapshot data) so the squad page can render+// the freshest server-side judgement without re-fetching the agent+// snapshot / runtime list.+export type SquadMemberStatusValue = "working" | "idle" | "offline" | "unstable";++export interface SquadActiveIssueBrief {+ issue_id: string;+ identifier: string;+ title: string;+ issue_status: string;+}++export interface SquadMemberStatus {+ member_type: SquadMemberType;+ member_id: string;+ // Human members are returned with status === null so the UI can render+ // them in the same list without showing a status pill (v1 has no+ // presence signal for humans).+ status: SquadMemberStatusValue | null;+ active_issues: SquadActiveIssueBrief[];+ last_active_at: string | null;+}++export interface SquadMemberStatusListResponse {+ members: SquadMemberStatus[];+}diff --git a/packages/core/workspace/queries.ts b/packages/core/workspace/queries.tsindex 58c066eeba..795d9e464c 100644--- a/packages/core/workspace/queries.ts+++ b/packages/core/workspace/queries.ts@@ -10,6 +10,11 @@ export const workspaceKeys = {myInvitations: () => ["invitations", "mine"] as const,agents: (wsId: string) => ["workspaces", wsId, "agents"] as const,squads: (wsId: string) => ["workspaces", wsId, "squads"] as const,+ // Per-squad member status. Lives under the workspace key tree so+ // workspace switches naturally drop the cache, and so a broad+ // `["workspaces", wsId, "squads"]` invalidation covers it.+ squadMemberStatus: (wsId: string, squadId: string) =>+ ["workspaces", wsId, "squads", squadId, "members-status"] as const,skills: (wsId: string) => ["workspaces", wsId, "skills"] as const,assigneeFrequency: (wsId: string) => ["workspaces", wsId, "assignee-frequency"] as const,};@@ -52,6 +57,20 @@ export function squadListOptions(wsId: string) {});}+// Per-squad members status snapshot. The freshness signal is the WS task /+// agent / runtime invalidation wired in use-realtime-sync (which broadly+// invalidates `["workspaces", wsId, "squads"]`); the staleTime is a+// tab-focus safety net.+export function squadMemberStatusOptions(wsId: string, squadId: string) {+ return queryOptions({+ queryKey: workspaceKeys.squadMemberStatus(wsId, squadId),+ queryFn: () => api.getSquadMemberStatus(squadId),+ enabled: !!wsId && !!squadId,+ staleTime: 30 * 1000,+ refetchOnWindowFocus: true,+ });+}+export function skillListOptions(wsId: string) {return queryOptions({queryKey: workspaceKeys.skills(wsId),diff --git a/packages/views/locales/en/squads.json b/packages/views/locales/en/squads.jsonindex 2c215e1ddd..6ce0696274 100644--- a/packages/views/locales/en/squads.json+++ b/packages/views/locales/en/squads.json@@ -41,7 +41,14 @@"leader_chip": "Leader","view_agent_tooltip": "Open agent detail","make_leader_tooltip": "Make squad leader",- "remove_member_tooltip": "Remove from squad"+ "remove_member_tooltip": "Remove from squad",+ "status_working": "Working",+ "status_idle": "Idle",+ "status_offline": "Offline",+ "status_unstable": "Unstable",+ "issue_status_blocked": "blocked",+ "active_issue_more": "and {{count}} more",+ "last_active_label": "last active {{time}}"},"instructions_tab": {"description": "Squad instructions are injected into the leader agent's prompt whenever it works on an issue assigned to this squad. Use them to give the leader squad-wide guidance, working agreements, or context the leader should follow on every task.",diff --git a/packages/views/locales/zh-Hans/squads.json b/packages/views/locales/zh-Hans/squads.jsonindex f98ee0d4c1..c4b0c0c4c5 100644--- a/packages/views/locales/zh-Hans/squads.json+++ b/packages/views/locales/zh-Hans/squads.json@@ -41,7 +41,14 @@"leader_chip": "负责人","view_agent_tooltip": "打开智能体详情","make_leader_tooltip": "设为小队负责人",- "remove_member_tooltip": "从小队移除"+ "remove_member_tooltip": "从小队移除",+ "status_working": "工作中",+ "status_idle": "空闲",+ "status_offline": "离线",+ "status_unstable": "不稳定",+ "issue_status_blocked": "已阻塞",+ "active_issue_more": "还有 {{count}} 个",+ "last_active_label": "最近活动 {{time}}"},"instructions_tab": {"description": "小队指引会在 Leader 智能体处理分配给该小队的 issue 时注入到它的 prompt 中。可用来给 Leader 提供贯穿全队的指导、协作规范,或每次任务都应遵循的上下文。",diff --git a/packages/views/squads/components/squad-detail-page.tsx b/packages/views/squads/components/squad-detail-page.tsxindex 3fe3391a58..0150e102e2 100644--- a/packages/views/squads/components/squad-detail-page.tsx+++ b/packages/views/squads/components/squad-detail-page.tsx@@ -8,7 +8,7 @@ import { useCurrentWorkspace, useWorkspacePaths } from "@multica/core/paths";import { useWorkspaceId } from "@multica/core/hooks";import { useFileUpload } from "@multica/core/hooks/use-file-upload";import { isImeComposing, timeAgo } from "@multica/core/utils";-import { agentListOptions, memberListOptions, workspaceKeys } from "@multica/core/workspace/queries";+import { agentListOptions, memberListOptions, squadMemberStatusOptions, workspaceKeys } from "@multica/core/workspace/queries";import { runtimeListOptions } from "@multica/core/runtimes";import { CreateAgentDialog } from "../../agents/components/create-agent-dialog";import { useNavigation } from "../../navigation";@@ -56,7 +56,7 @@ import {} from "../../issues/components/pickers/property-picker";import { ChevronDown, UserPlus } from "lucide-react";import { toast } from "sonner";-import type { Squad, SquadMember, Agent, CreateAgentRequest, MemberWithUser } from "@multica/core/types";+import type { Squad, SquadMember, SquadMemberStatus, Agent, CreateAgentRequest, MemberWithUser } from "@multica/core/types";import { useT } from "../../i18n";import { matchesPinyin } from "../../editor/extensions/pinyin-match";@@ -81,6 +81,20 @@ export function SquadDetailPage() {enabled: !!workspace?.id && !!squadId,});+ // Per-squad working/idle/offline + active-issue snapshot. WS task / agent /+ // daemon events invalidate this via use-realtime-sync; the staleTime is a+ // tab-focus safety net. Indexed by member_id so SquadMembersTab can look up+ // its row in O(1).+ const { data: memberStatusResp } = useQuery({+ ...squadMemberStatusOptions(wsId, squadId),+ enabled: !!workspace?.id && !!squadId,+ });+ const memberStatusById = useMemo(() => {+ const map = new Map<string, SquadMemberStatus>();+ for (const s of memberStatusResp?.members ?? []) map.set(s.member_id, s);+ return map;+ }, [memberStatusResp]);+const { data: agents = [] } = useQuery(agentListOptions(wsId));const { data: wsMembers = [] } = useQuery(memberListOptions(wsId));@@ -235,6 +249,7 @@ export function SquadDetailPage() {<SquadOverviewPanesquad={squad}members={members}+ memberStatusById={memberStatusById}isLeader={isLeader}getEntityName={getEntityName}onAddMemberClick={() => setShowAddMember(true)}@@ -912,6 +927,7 @@ const squadDetailTabs: { id: SquadDetailTab; label: string; icon: typeof FileTexfunction SquadOverviewPane({squad,members,+ memberStatusById,isLeader,getEntityName,onAddMemberClick,@@ -924,6 +940,7 @@ function SquadOverviewPane({}: {squad: Squad;members: SquadMember[];+ memberStatusById: Map<string, SquadMemberStatus>;isLeader: (m: SquadMember) => boolean;getEntityName: (type: string, id: string) => string;onAddMemberClick: () => void;@@ -981,6 +998,7 @@ function SquadOverviewPane({<div className="flex h-full flex-col p-4 md:p-6"><SquadMembersTabmembers={members}+ memberStatusById={memberStatusById}isLeader={isLeader}getEntityName={getEntityName}onAddMemberClick={onAddMemberClick}@@ -1025,9 +1043,23 @@ function SquadOverviewPane({);}+// Visual config for the four squad member status buckets. Mirrors+// availabilityConfig + workloadConfig in packages/views/agents/presence.ts —+// same semantic tokens so a status dot here matches the agent page's dot.+// Unknown / null statuses (human members, server-side enum drift) render as+// a neutral muted pill; this is the "downgrade, don't crash" defense from+// CLAUDE.md > API Response Compatibility.+const SQUAD_STATUS_DOT_CLASS: Record<"working" | "idle" | "offline" | "unstable", string> = {+ working: "bg-success",+ idle: "bg-muted-foreground/40",+ offline: "bg-muted-foreground/40",+ unstable: "bg-warning",+};+// Members tab body — re-uses the existing list/role editing patterns.function SquadMembersTab({members,+ memberStatusById,isLeader,getEntityName,onAddMemberClick,@@ -1038,6 +1070,7 @@ function SquadMembersTab({setLeaderPending,}: {members: SquadMember[];+ memberStatusById: Map<string, SquadMemberStatus>;isLeader: (m: SquadMember) => boolean;getEntityName: (type: string, id: string) => string;onAddMemberClick: () => void;@@ -1074,32 +1107,87 @@ function SquadMembersTab({</div><div className="space-y-2">- {members.map((m) => (- <div key={m.id} className="group flex items-start gap-3 rounded-lg border p-3">- <ActorAvatar- actorType={m.member_type}- actorId={m.member_id}- size={32}- showStatusDot- enableHoverCard={m.member_type === "agent"}- hoverCardVariant="live"- />- <div className="flex-1 min-w-0">- <div className="flex items-center gap-2">- <span className="text-sm font-medium">{getEntityName(m.member_type, m.member_id)}</span>- <span className="text-xs text-muted-foreground capitalize">{m.member_type}</span>- {isLeader(m) && (- <span className="inline-flex items-center gap-0.5 text-xs bg-amber-100 dark:bg-amber-900/30 text-amber-700 dark:text-amber-400 px-1.5 py-0.5 rounded">- <Crown className="size-3" />- {t(($) => $.members_tab.leader_chip)}- </span>+ {members.map((m) => {+ const status = memberStatusById.get(m.member_id);+ const statusValue = status?.status ?? null;+ const dotClass =+ statusValue && statusValue in SQUAD_STATUS_DOT_CLASS+ ? SQUAD_STATUS_DOT_CLASS[statusValue as keyof typeof SQUAD_STATUS_DOT_CLASS]+ : null;+ const statusLabel =+ statusValue === "working" ? t(($) => $.members_tab.status_working)+ : statusValue === "idle" ? t(($) => $.members_tab.status_idle)+ : statusValue === "offline" ? t(($) => $.members_tab.status_offline)+ : statusValue === "unstable" ? t(($) => $.members_tab.status_unstable)+ : null;+ const activeIssues = status?.active_issues ?? [];+ const primaryIssue = activeIssues[0];+ const extraIssueCount = Math.max(0, activeIssues.length - 1);+ // Show last_active only when the agent isn't currently working —+ // a "working" pill already implies the agent is live, and a+ // "last active 2s ago" line next to it is just noise.+ const showLastActive =+ m.member_type === "agent" && statusValue && statusValue !== "working" && status?.last_active_at;+ return (+ <div key={m.id} className="group flex items-start gap-3 rounded-lg border p-3">+ <ActorAvatar+ actorType={m.member_type}+ actorId={m.member_id}+ size={32}+ showStatusDot+ enableHoverCard={m.member_type === "agent"}+ hoverCardVariant="live"+ />+ <div className="flex-1 min-w-0">+ <div className="flex items-center gap-2">+ <span className="text-sm font-medium">{getEntityName(m.member_type, m.member_id)}</span>+ <span className="text-xs text-muted-foreground capitalize">{m.member_type}</span>+ {isLeader(m) && (+ <span className="inline-flex items-center gap-0.5 text-xs bg-amber-100 dark:bg-amber-900/30 text-amber-700 dark:text-amber-400 px-1.5 py-0.5 rounded">+ <Crown className="size-3" />+ {t(($) => $.members_tab.leader_chip)}+ </span>+ )}+ {m.member_type === "agent" && statusLabel && (+ <span className="inline-flex items-center gap-1 text-xs text-muted-foreground">+ <span className={`h-1.5 w-1.5 rounded-full ${dotClass ?? "bg-muted-foreground/40"}`} />+ {statusLabel}+ </span>+ )}+ </div>+ <RoleEditor+ value={m.role ?? ""}+ onSave={async (next) => { await onUpdateRole(m, next); }}+ />+ {primaryIssue && (+ <div className="mt-1 flex items-center gap-1 text-xs text-muted-foreground min-w-0">+ <AppLink+ href={p.issueDetail(primaryIssue.issue_id)}+ className="inline-flex items-center gap-1 min-w-0 hover:text-foreground transition-colors"+ >+ <span className="font-mono text-[10px] uppercase shrink-0">{primaryIssue.identifier}</span>+ <span className="truncate">{primaryIssue.title}</span>+ {primaryIssue.issue_status === "blocked" && (+ <span className="shrink-0 inline-flex items-center text-[10px] uppercase tracking-wide text-warning">+ {t(($) => $.members_tab.issue_status_blocked)}+ </span>+ )}+ </AppLink>+ {extraIssueCount > 0 && (+ <span className="shrink-0">+ · {t(($) => $.members_tab.active_issue_more, { count: extraIssueCount })}+ </span>+ )}+ </div>+ )}+ {showLastActive && (+ <div className="mt-0.5 text-xs text-muted-foreground">+ {t(($) => $.members_tab.last_active_label, {+ time: timeAgo(status!.last_active_at!),+ })}+ </div>)}</div>- <RoleEditor- value={m.role ?? ""}- onSave={async (next) => { await onUpdateRole(m, next); }}- />- </div><div className="flex items-center gap-1 opacity-0 group-hover:opacity-100 group-focus-within:opacity-100 transition-opacity">{m.member_type === "agent" && (<Tooltip>@@ -1162,7 +1250,8 @@ function SquadMembersTab({)}</div></div>- ))}+ );+ })}</div></div>);diff --git a/server/cmd/server/router.go b/server/cmd/server/router.goindex cbd1660036..cac40c6d0c 100644--- a/server/cmd/server/router.go+++ b/server/cmd/server/router.go@@ -446,6 +446,7 @@ func NewRouterWithOptions(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Busr.Put("/", h.UpdateSquad)r.Delete("/", h.DeleteSquad)r.Get("/members", h.ListSquadMembers)+ r.Get("/members/status", h.ListSquadMemberStatus)r.Post("/members", h.AddSquadMember)r.Delete("/members", h.RemoveSquadMember)r.Patch("/members/role", h.UpdateSquadMemberRole)diff --git a/server/internal/handler/squad.go b/server/internal/handler/squad.goindex 66fd45dd49..2ed8a4e66f 100644--- a/server/internal/handler/squad.go+++ b/server/internal/handler/squad.go@@ -5,6 +5,8 @@ import ("encoding/json""log/slog""net/http"+ "strconv"+ "time""github.com/go-chi/chi/v5""github.com/jackc/pgx/v5/pgtype"@@ -334,6 +336,192 @@ func (h *Handler) ListSquadMembers(w http.ResponseWriter, r *http.Request) {writeJSON(w, http.StatusOK, resp)}+// ── Squad Member Status ────────────────────────────────────────────────────++// SquadMemberStatus is the per-member entry in the squad member status+// response. Agent members carry a derived working/idle/offline/unstable+// status plus any active issues; human members are returned with member_type+// only so the front-end can render them in the same list without+// reordering.+type SquadMemberStatusResponse struct {+ MemberType string `json:"member_type"`+ MemberID string `json:"member_id"`+ Status *string `json:"status"`+ ActiveIssues []SquadActiveIssueBrief `json:"active_issues"`+ LastActiveAt *string `json:"last_active_at"`+}++type SquadActiveIssueBrief struct {+ IssueID string `json:"issue_id"`+ Identifier string `json:"identifier"`+ Title string `json:"title"`+ IssueStatus string `json:"issue_status"`+}++type SquadMemberStatusListResponse struct {+ Members []SquadMemberStatusResponse `json:"members"`+}++// deriveSquadMemberStatus collapses runtime + task signals into the four+// status buckets used by the squad UI. Mirrors the workload+availability+// split in packages/core/agents/derive-presence.ts: working wins over+// runtime health (an agent that is in the middle of dispatched/running+// work counts as working even if the runtime briefly drops), then+// availability buckets decide between idle / unstable / offline.+//+// Thresholds match deriveRuntimeHealth: any offline runtime whose+// last_seen_at is within the last 5 minutes is reported as "unstable" so+// the squad UI surfaces transient drops the same way the agent dot does.+//+// Archived agents always report `offline` regardless of any leftover+// runtime row or task — they should appear in the list but never look+// like they're still working. Per the RFC decision (see MUL-2319), we+// surface archived agents in this endpoint rather than filtering them+// out in the SQL.+func deriveSquadMemberStatus(+ archived bool,+ runtimeStatus pgtype.Text,+ lastSeen pgtype.Timestamptz,+ hasActiveTask bool,+ now time.Time,+) string {+ if archived {+ return "offline"+ }+ if hasActiveTask {+ return "working"+ }+ if !runtimeStatus.Valid {+ return "offline"+ }+ if runtimeStatus.String == "online" {+ return "idle"+ }+ if !lastSeen.Valid {+ return "offline"+ }+ if now.Sub(lastSeen.Time) < 5*time.Minute {+ return "unstable"+ }+ return "offline"+}++// ListSquadMemberStatus returns one entry per squad member with derived+// status, the issues each agent member is currently running, and the last+// observed runtime activity. The endpoint is read-only and inherits the+// workspace-membership guard from the route middleware — any member of the+// workspace can read it.+func (h *Handler) ListSquadMemberStatus(w http.ResponseWriter, r *http.Request) {+ squad, _, ok := h.loadSquadInWorkspace(w, r)+ if !ok {+ return+ }++ rows, err := h.Queries.ListSquadMemberStatusRows(r.Context(), squad.ID)+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to list squad member status")+ return+ }++ prefix := h.getIssuePrefix(r.Context(), squad.WorkspaceID)+ now := time.Now()++ // Group rows by member_id while preserving the SQL ORDER BY (squad_member+ // insertion order). One member may appear in multiple rows when they have+ // more than one active task.+ type memberAcc struct {+ response SquadMemberStatusResponse+ archived bool+ hasActiveTask bool+ runtimeStatus pgtype.Text+ runtimeSeenAt pgtype.Timestamptz+ latestActiveAt pgtype.Timestamptz+ }+ order := make([]string, 0, len(rows))+ acc := make(map[string]*memberAcc, len(rows))++ for _, row := range rows {+ memberID := uuidToString(row.MemberID)+ entry, exists := acc[memberID]+ if !exists {+ entry = &memberAcc{+ response: SquadMemberStatusResponse{+ MemberType: row.MemberType,+ MemberID: memberID,+ ActiveIssues: []SquadActiveIssueBrief{},+ },+ archived: row.AgentArchivedAt.Valid,+ runtimeStatus: row.RuntimeStatus,+ runtimeSeenAt: row.RuntimeLastSeenAt,+ }+ acc[memberID] = entry+ order = append(order, memberID)+ }++ if row.MemberType != "agent" {+ continue+ }++ // A dispatched/running task occupies an agent slot even when it+ // has no associated issue (chat / quick-create tasks set+ // agent_task_queue.issue_id = NULL). The `working` bucket is+ // defined by task presence, not by whether we can render an+ // issue link, so flag the agent here regardless of issue_id.+ if row.TaskID.Valid {+ entry.hasActiveTask = true++ if row.TaskIssueID.Valid {+ brief := SquadActiveIssueBrief{+ IssueID: uuidToString(row.TaskIssueID),+ Identifier: prefix + "-" + strconv.Itoa(int(row.IssueNumber.Int32)),+ Title: row.IssueTitle.String,+ IssueStatus: func() string {+ if row.IssueStatus.Valid {+ return row.IssueStatus.String+ }+ return ""+ }(),+ }+ entry.response.ActiveIssues = append(entry.response.ActiveIssues, brief)+ }++ if row.TaskDispatchedAt.Valid && (!entry.latestActiveAt.Valid ||+ row.TaskDispatchedAt.Time.After(entry.latestActiveAt.Time)) {+ entry.latestActiveAt = row.TaskDispatchedAt+ }+ }+ }++ resp := SquadMemberStatusListResponse{+ Members: make([]SquadMemberStatusResponse, 0, len(order)),+ }+ for _, id := range order {+ entry := acc[id]+ if entry.response.MemberType == "agent" {+ status := deriveSquadMemberStatus(+ entry.archived,+ entry.runtimeStatus,+ entry.runtimeSeenAt,+ entry.hasActiveTask,+ now,+ )+ entry.response.Status = &status+ // last_active_at prefers the freshest active-task dispatch+ // over the runtime heartbeat: a working agent should not+ // look stale because the runtime heartbeat is a few seconds+ // behind. Falls back to runtime last_seen_at otherwise.+ if entry.latestActiveAt.Valid {+ entry.response.LastActiveAt = timestampToPtr(entry.latestActiveAt)+ } else if entry.runtimeSeenAt.Valid {+ entry.response.LastActiveAt = timestampToPtr(entry.runtimeSeenAt)+ }+ }+ resp.Members = append(resp.Members, entry.response)+ }++ writeJSON(w, http.StatusOK, resp)+}+func (h *Handler) AddSquadMember(w http.ResponseWriter, r *http.Request) {workspaceID := workspaceIDFromURL(r, "workspaceId")if _, ok := h.requireWorkspaceRole(w, r, workspaceID, "workspace not found", "owner", "admin"); !ok {diff --git a/server/internal/handler/squad_member_status_test.go b/server/internal/handler/squad_member_status_test.gonew file mode 100644index 0000000000..3d0483b08b--- /dev/null+++ b/server/internal/handler/squad_member_status_test.go@@ -0,0 +1,52 @@+package handler++import (+ "testing"+ "time"++ "github.com/jackc/pgx/v5/pgtype"+)++func TestDeriveSquadMemberStatus(t *testing.T) {+ now := time.Date(2026, 5, 18, 12, 0, 0, 0, time.UTC)+ online := pgtype.Text{String: "online", Valid: true}+ offline := pgtype.Text{String: "offline", Valid: true}+ missing := pgtype.Text{}++ tsAgo := func(d time.Duration) pgtype.Timestamptz {+ return pgtype.Timestamptz{Time: now.Add(-d), Valid: true}+ }+ tsNone := pgtype.Timestamptz{}++ cases := []struct {+ name string+ archived bool+ runtimeStatus pgtype.Text+ lastSeen pgtype.Timestamptz+ hasActiveTask bool+ want string+ }{+ {"active wins over offline runtime", false, offline, tsAgo(time.Hour), true, "working"},+ {"active wins over missing runtime", false, missing, tsNone, true, "working"},+ {"online runtime, no task", false, online, tsAgo(2 * time.Second), false, "idle"},+ {"offline runtime, recent heartbeat", false, offline, tsAgo(2 * time.Minute), false, "unstable"},+ {"offline runtime, stale heartbeat", false, offline, tsAgo(2 * time.Hour), false, "offline"},+ {"offline runtime, no heartbeat", false, offline, tsNone, false, "offline"},+ {"no runtime row", false, missing, tsNone, false, "offline"},+ // Archived agents always report offline regardless of any leftover+ // runtime row or task — they should appear in the squad listing+ // but never look like they're still working.+ {"archived agent with active task", true, online, tsAgo(time.Second), true, "offline"},+ {"archived agent with online runtime", true, online, tsAgo(time.Second), false, "offline"},+ {"archived agent already offline", true, offline, tsAgo(time.Hour), false, "offline"},+ }++ for _, tc := range cases {+ t.Run(tc.name, func(t *testing.T) {+ got := deriveSquadMemberStatus(tc.archived, tc.runtimeStatus, tc.lastSeen, tc.hasActiveTask, now)+ if got != tc.want {+ t.Fatalf("deriveSquadMemberStatus = %q, want %q", got, tc.want)+ }+ })+ }+}diff --git a/server/pkg/db/generated/squad.sql.go b/server/pkg/db/generated/squad.sql.goindex 7981b4c39f..8412ef6409 100644--- a/server/pkg/db/generated/squad.sql.go+++ b/server/pkg/db/generated/squad.sql.go@@ -267,6 +267,91 @@ func (q *Queries) ListAllSquads(ctx context.Context, workspaceID pgtype.UUID) ([return items, nil}+const listSquadMemberStatusRows = `-- name: ListSquadMemberStatusRows :many+SELECT+ sm.id AS squad_member_id,+ sm.member_type AS member_type,+ sm.member_id AS member_id,+ a.archived_at AS agent_archived_at,+ ar.status AS runtime_status,+ ar.last_seen_at AS runtime_last_seen_at,+ atq.id AS task_id,+ atq.status AS task_status,+ atq.issue_id AS task_issue_id,+ atq.dispatched_at AS task_dispatched_at,+ i.number AS issue_number,+ i.title AS issue_title,+ i.status AS issue_status+FROM squad_member sm+LEFT JOIN agent a+ ON sm.member_type = 'agent' AND a.id = sm.member_id+LEFT JOIN agent_runtime ar+ ON ar.id = a.runtime_id+LEFT JOIN agent_task_queue atq+ ON sm.member_type = 'agent'+ AND atq.agent_id = sm.member_id+ AND atq.status IN ('dispatched', 'running')+LEFT JOIN issue i+ ON i.id = atq.issue_id+WHERE sm.squad_id = $1+ORDER BY sm.created_at ASC, atq.dispatched_at DESC NULLS LAST+`++type ListSquadMemberStatusRowsRow struct {+ SquadMemberID pgtype.UUID `json:"squad_member_id"`+ MemberType string `json:"member_type"`+ MemberID pgtype.UUID `json:"member_id"`+ AgentArchivedAt pgtype.Timestamptz `json:"agent_archived_at"`+ RuntimeStatus pgtype.Text `json:"runtime_status"`+ RuntimeLastSeenAt pgtype.Timestamptz `json:"runtime_last_seen_at"`+ TaskID pgtype.UUID `json:"task_id"`+ TaskStatus pgtype.Text `json:"task_status"`+ TaskIssueID pgtype.UUID `json:"task_issue_id"`+ TaskDispatchedAt pgtype.Timestamptz `json:"task_dispatched_at"`+ IssueNumber pgtype.Int4 `json:"issue_number"`+ IssueTitle pgtype.Text `json:"issue_title"`+ IssueStatus pgtype.Text `json:"issue_status"`+}++// Per-row join used to build the squad-members status view. One row per+// (squad_member × active_task); members with no active task return a+// single row with NULL task_* columns. Human members and agent members+// with no agent row also return one row with NULL agent_/runtime_ columns.+// The handler aggregates rows by member_id.+func (q *Queries) ListSquadMemberStatusRows(ctx context.Context, squadID pgtype.UUID) ([]ListSquadMemberStatusRowsRow, error) {+ rows, err := q.db.Query(ctx, listSquadMemberStatusRows, squadID)+ if err != nil {+ return nil, err+ }+ defer rows.Close()+ items := []ListSquadMemberStatusRowsRow{}+ for rows.Next() {+ var i ListSquadMemberStatusRowsRow+ if err := rows.Scan(+ &i.SquadMemberID,+ &i.MemberType,+ &i.MemberID,+ &i.AgentArchivedAt,+ &i.RuntimeStatus,+ &i.RuntimeLastSeenAt,+ &i.TaskID,+ &i.TaskStatus,+ &i.TaskIssueID,+ &i.TaskDispatchedAt,+ &i.IssueNumber,+ &i.IssueTitle,+ &i.IssueStatus,+ ); err != nil {+ return nil, err+ }+ items = append(items, i)+ }+ if err := rows.Err(); err != nil {+ return nil, err+ }+ return items, nil+}+const listSquadMembers = `-- name: ListSquadMembers :manySELECT id, squad_id, member_type, member_id, role, created_at FROM squad_member WHERE squad_id = $1 ORDER BY created_at ASC`diff --git a/server/pkg/db/queries/squad.sql b/server/pkg/db/queries/squad.sqlindex 348bc61d0f..5f958cd5bb 100644--- a/server/pkg/db/queries/squad.sql+++ b/server/pkg/db/queries/squad.sql@@ -72,3 +72,37 @@ ORDER BY s.created_at ASC;-- Transfer all issues assigned to a squad to the squad's leader agent.UPDATE issue SET assignee_type = 'agent', assignee_id = $2, updated_at = now()WHERE assignee_type = 'squad' AND assignee_id = $1;++-- name: ListSquadMemberStatusRows :many+-- Per-row join used to build the squad-members status view. One row per+-- (squad_member × active_task); members with no active task return a+-- single row with NULL task_* columns. Human members and agent members+-- with no agent row also return one row with NULL agent_/runtime_ columns.+-- The handler aggregates rows by member_id.+SELECT+ sm.id AS squad_member_id,+ sm.member_type AS member_type,+ sm.member_id AS member_id,+ a.archived_at AS agent_archived_at,+ ar.status AS runtime_status,+ ar.last_seen_at AS runtime_last_seen_at,+ atq.id AS task_id,+ atq.status AS task_status,+ atq.issue_id AS task_issue_id,+ atq.dispatched_at AS task_dispatched_at,+ i.number AS issue_number,+ i.title AS issue_title,+ i.status AS issue_status+FROM squad_member sm+LEFT JOIN agent a+ ON sm.member_type = 'agent' AND a.id = sm.member_id+LEFT JOIN agent_runtime ar+ ON ar.id = a.runtime_id+LEFT JOIN agent_task_queue atq+ ON sm.member_type = 'agent'+ AND atq.agent_id = sm.member_id+ AND atq.status IN ('dispatched', 'running')+LEFT JOIN issue i+ ON i.id = atq.issue_id+WHERE sm.squad_id = $1+ORDER BY sm.created_at ASC, atq.dispatched_at DESC NULLS LAST;