Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.
Go
MUL-6891, MUL-7048: fix(agents): preserve presence for hidden private runtimes (#7830)
makesomethingshit2aad9842a9fe
diff --git a/apps/mobile/data/queries/agents.test.ts b/apps/mobile/data/queries/agents.test.tsnew file mode 100644index 0000000000..c827327927--- /dev/null+++ b/apps/mobile/data/queries/agents.test.ts@@ -0,0 +1,32 @@+import { describe, expect, it, vi } from "vitest";+import type { Agent } from "@multica/core/types";++import { agentListOptions } from "./agents";++vi.mock("@/data/api", () => ({ api: {} }));++describe("agentListOptions", () => {+ it("polls only while projected runtime availability can age offline", () => {+ const options = agentListOptions("ws-1");+ const interval = options.refetchInterval;+ expect(typeof interval).toBe("function");+ if (typeof interval !== "function") return;++ const queryState = (data: Agent[]) =>+ interval({ state: { status: "success", data } } as never);++ expect(queryState([{ runtime_availability: "online" } as Agent])).toBe(30_000);+ expect(queryState([{ runtime_availability: "unstable" } as Agent])).toBe(30_000);+ expect(queryState([{ runtime_availability: "offline" } as Agent])).toBe(false);+ expect(queryState([{ runtime_availability: undefined } as Agent])).toBe(false);+ expect(+ queryState([+ {+ archived_at: "2026-09-04T00:00:00Z",+ runtime_availability: "online",+ } as Agent,+ ]),+ ).toBe(false);+ expect(queryState([])).toBe(false);+ });+});diff --git a/apps/mobile/data/queries/agents.ts b/apps/mobile/data/queries/agents.tsindex 73f770a596..c402ea309e 100644--- a/apps/mobile/data/queries/agents.ts+++ b/apps/mobile/data/queries/agents.ts@@ -6,4 +6,15 @@ export const agentListOptions = (wsId: string | null) =>queryKey: ["agents", wsId] as const,queryFn: ({ signal }) => api.listAgents({ signal }),enabled: !!wsId,+ // Mirrors Web/Desktop: projected unstable ages offline without an event,+ // while offline recovery is covered by lifecycle events and reconnect.+ refetchInterval: (query) =>+ query.state.data?.some(+ (agent) =>+ !agent.archived_at &&+ (agent.runtime_availability === "online" ||+ agent.runtime_availability === "unstable"),+ )+ ? 30_000+ : false,});diff --git a/apps/mobile/data/realtime/use-presence-realtime.test.ts b/apps/mobile/data/realtime/use-presence-realtime.test.tsnew file mode 100644index 0000000000..8aceba3d94--- /dev/null+++ b/apps/mobile/data/realtime/use-presence-realtime.test.ts@@ -0,0 +1,77 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++const { invalidateQueries, subscriptionSetups } = vi.hoisted(() => ({+ invalidateQueries: vi.fn(),+ subscriptionSetups: [] as Array<+ (ws: MockWS, wsId: string) => Array<() => void>+ >,+}));++type EventHandler = (payload: unknown) => void;++interface MockWS {+ on: ReturnType<typeof vi.fn>;+ onReconnect: ReturnType<typeof vi.fn>;+}++vi.mock("@tanstack/react-query", () => ({+ useQueryClient: () => ({ invalidateQueries }),+}));++vi.mock("@/lib/use-ws-subscriptions", () => ({+ useWSSubscriptions: (+ setup: (ws: MockWS, wsId: string) => Array<() => void>,+ ) => {+ subscriptionSetups.push(setup);+ },+}));++import { usePresenceRealtime } from "./use-presence-realtime";++describe("usePresenceRealtime", () => {+ beforeEach(() => {+ invalidateQueries.mockReset();+ subscriptionSetups.length = 0;+ });++ it("refreshes hidden agent liveness on daemon register and reconnect", () => {+ usePresenceRealtime();+ expect(subscriptionSetups).toHaveLength(1);++ const handlers = new Map<string, EventHandler>();+ let reconnect: (() => void) | undefined;+ const ws: MockWS = {+ on: vi.fn((event: string, handler: EventHandler) => {+ handlers.set(event, handler);+ return () => {};+ }),+ onReconnect: vi.fn((handler: () => void) => {+ reconnect = handler;+ return () => {};+ }),+ };++ subscriptionSetups[0](ws, "workspace-1");+ handlers.get("daemon:register")?.({});++ const invalidatedKeys = () =>+ invalidateQueries.mock.calls.map(([query]) => query.queryKey);+ expect(invalidatedKeys()).toEqual(+ expect.arrayContaining([+ ["runtimes", "workspace-1"],+ ["agents", "workspace-1"],+ ]),+ );++ invalidateQueries.mockClear();+ reconnect?.();++ expect(invalidatedKeys()).toEqual(+ expect.arrayContaining([+ ["runtimes", "workspace-1"],+ ["agents", "workspace-1"],+ ["agent-task-snapshot", "workspace-1"],+ ]),+ );+ });+});diff --git a/apps/mobile/data/realtime/use-presence-realtime.ts b/apps/mobile/data/realtime/use-presence-realtime.tsindex 460f7493ce..1e27e1caba 100644--- a/apps/mobile/data/realtime/use-presence-realtime.ts+++ b/apps/mobile/data/realtime/use-presence-realtime.ts@@ -16,8 +16,7 @@* - task:progress / task:message — fire many times per active task. The* presence cache only needs lifecycle transitions, not per-step updates.*- * Reconnect: re-invalidate runtimes + snapshot (NOT agents — agent identity- * doesn't drift while we're offline; runtime status and task counts do).+ * Reconnect: re-invalidate runtimes + agents + snapshot after missed events.*/import { useQueryClient } from "@tanstack/react-query";import { useWSSubscriptions } from "@/lib/use-ws-subscriptions";@@ -39,12 +38,11 @@ export function usePresenceRealtime() {queryClient.invalidateQueries({ queryKey: snapshotKey });return [- // Daemon lifecycle — register events mean a runtime came online or- // re-registered; the sweeper's offline transitions are NOT pushed as- // a WS event, but the next agent:status / task:* event will pull a- // fresh runtime list anyway, and the 30s wall-clock tick masks the- // gap. Heartbeats deliberately omitted.- ws.on("daemon:register", invalidateRuntimes),+ // Daemon lifecycle; heartbeats deliberately omitted.+ ws.on("daemon:register", () => {+ invalidateRuntimes();+ invalidateAgents();+ }),// Agent identity churn — visible in pickers / chat header straight// away, so invalidate the cached list.@@ -61,12 +59,10 @@ export function usePresenceRealtime() {ws.on("task:failed", invalidateSnapshot),ws.on("task:cancelled", invalidateSnapshot),- // We may have missed sweeper-driven runtime offline transitions- // while disconnected — refetch runtimes + snapshot. Agents not- // re-invalidated because agent:created / archived are rare enough- // that the user can pull-to-refresh if needed.+ // Recover all presence inputs after missed sweeper transitions.ws.onReconnect(() => {invalidateRuntimes();+ invalidateAgents();invalidateSnapshot();}),];diff --git a/packages/core/agents/derive-presence.test.ts b/packages/core/agents/derive-presence.test.tsindex 8c21b122fd..ba2b5be035 100644--- a/packages/core/agents/derive-presence.test.ts+++ b/packages/core/agents/derive-presence.test.ts@@ -404,6 +404,39 @@ describe("buildPresenceMap", () => {expect(o?.workload).toBe("working");});+ it("uses an agent liveness projection when its private runtime is hidden", () => {+ const shared = makeAgent({+ id: "shared",+ runtime_id: "private-runtime",+ runtime_availability: "online",+ });+ const map = buildPresenceMap({+ agents: [shared],+ runtimes: [],+ snapshot: [makeTask({ agent_id: "shared", status: "running" })],+ now: NOW,+ });++ expect(map.get("shared")?.availability).toBe("online");+ expect(map.get("shared")?.workload).toBe("working");+ });++ it("keeps a recent loss unstable from a hidden runtime projection", () => {+ const shared = makeAgent({+ id: "shared",+ runtime_id: "private-runtime",+ runtime_availability: "unstable",+ });+ const map = buildPresenceMap({+ agents: [shared],+ runtimes: [],+ snapshot: [],+ now: NOW,+ });++ expect(map.get("shared")?.availability).toBe("unstable");+ });+it("threads the same `now` so every agent on a shared runtime gets the same availability", () => {// Multi-agent scenario: one local daemon backs N agents, daemon dies.// All dependent agents should report unstable together — the shareddiff --git a/packages/core/agents/derive-presence.ts b/packages/core/agents/derive-presence.tsindex a3427fc8f6..6b5f0a6873 100644--- a/packages/core/agents/derive-presence.ts+++ b/packages/core/agents/derive-presence.ts@@ -19,12 +19,26 @@ import type {Workload,} from "./types";+type RuntimeLiveness = Pick<AgentRuntime, "status" | "last_seen_at">;++function runtimeAvailabilityFromAgent(agent: Agent): AgentAvailability | null {+ const availability = agent.runtime_availability;+ if (+ availability !== "online" &&+ availability !== "unstable" &&+ availability !== "offline"+ ) {+ return null;+ }+ return availability;+}+// AgentAvailability mirrors RuntimeHealth's reachability buckets but folds// `long_offline` into `offline` — both mean "unreachable" from the agent// availability standpoint; the duration detail belongs to the runtime card,// not the agent dot.export function deriveAgentAvailability(- runtime: AgentRuntime | null,+ runtime: RuntimeLiveness | null,now: number,): AgentAvailability {if (!runtime) return "offline";@@ -84,7 +98,7 @@ export function deriveWorkloadDetail(tasks: readonly AgentTask[]): WorkloadDetaiinterface DerivePresenceInput {agent: Agent;- runtime: AgentRuntime | null;+ runtime: RuntimeLiveness | null;// Tasks for THIS agent only. Callers (buildPresenceMap, hooks) pre-filter// by agent_id — we don't re-check here.tasks: readonly AgentTask[];@@ -108,7 +122,9 @@ export function deriveAgentPresenceDetail(input: DerivePresenceInput): AgentPres};}- const availability = deriveAgentAvailability(input.runtime, input.now);+ const availability = input.runtime+ ? deriveAgentAvailability(input.runtime, input.now)+ : runtimeAvailabilityFromAgent(input.agent) ?? "offline";const detail = deriveWorkloadDetail(input.tasks);return {diff --git a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsxindex 9f31ed5a8f..4645c95789 100644--- a/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx+++ b/packages/core/realtime/use-realtime-sync-ws-instance.test.tsx@@ -9,6 +9,7 @@ import type { WSClient } from "../api/ws-client";import { defaultStorage } from "../platform/storage";import { issueKeys } from "../issues/queries";import { chatKeys } from "../chat/queries";+import { runtimeKeys } from "../runtimes/queries";import { workspaceWorkingAgentsKeys } from "../agents/queries";import { workspaceKeys } from "../workspace/queries";import { issueStatusKeys } from "../issue-statuses/queries";@@ -159,6 +160,31 @@ describe("useRealtimeSync — ws instance change", () => {expect(calls).toContainEqual(issueStatusKeys.all("ws-1"));});+ it("invalidates agent projections when a daemon changes liveness", () => {+ vi.useFakeTimers();+ try {+ const ws = createMockWs();+ renderHook(() => useRealtimeSync(ws, stores), {+ wrapper: createWrapper(qc),+ });+ const onAny = vi.mocked(ws.onAny).mock.calls[0]?.[0];+ expect(onAny).toBeDefined();++ invalidateSpy.mockClear();+ onAny!({ type: "daemon:register", payload: {} } as never);+ vi.advanceTimersByTime(100);++ expect(invalidateSpy).toHaveBeenCalledWith({+ queryKey: runtimeKeys.all("ws-1"),+ });+ expect(invalidateSpy).toHaveBeenCalledWith({+ queryKey: workspaceKeys.agents("ws-1"),+ });+ } finally {+ vi.useRealTimers();+ }+ });+it("invalidates per-issue caches (no wsId in key) on ws instance change", () => {// These keys are not under the ["issues", wsId] prefix, so they need// their own invalidation on recovery — otherwise events missed whilediff --git a/packages/core/realtime/use-realtime-sync.ts b/packages/core/realtime/use-realtime-sync.tsindex 6652c6cd9c..00d036da94 100644--- a/packages/core/realtime/use-realtime-sync.ts+++ b/packages/core/realtime/use-realtime-sync.ts@@ -838,6 +838,10 @@ export function useRealtimeSync(const wsId = getCurrentWsId();if (wsId) {qc.invalidateQueries({ queryKey: runtimeKeys.all(wsId) });+ // Shared agents may carry a redacted runtime liveness projection;+ // refetch it when a daemon changes state even if its private runtime+ // is absent from this member's runtime list.+ qc.invalidateQueries({ queryKey: workspaceKeys.agents(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.diff --git a/packages/core/runtimes/derive-health.ts b/packages/core/runtimes/derive-health.tsindex 44c8fa9c28..97457dbde7 100644--- a/packages/core/runtimes/derive-health.ts+++ b/packages/core/runtimes/derive-health.ts@@ -11,7 +11,10 @@ const FIVE_MINUTES_MS = 5 * 60 * 1000;// not promise when or whether server-side cleanup will happen.const LONG_OFFLINE_THRESHOLD_MS = 6 * 24 * 3600 * 1000; // 6 days-export function deriveRuntimeHealth(runtime: AgentRuntime, now: number): RuntimeHealth {+export function deriveRuntimeHealth(+ runtime: Pick<AgentRuntime, "status" | "last_seen_at">,+ now: number,+): RuntimeHealth {if (runtime.status === "online") return "online";// No last_seen timestamp ever recorded — treat as long-offline. This isdiff --git a/packages/core/types/agent.ts b/packages/core/types/agent.tsindex 4d28b5cd60..dad015fa9c 100644--- a/packages/core/types/agent.ts+++ b/packages/core/types/agent.ts@@ -466,6 +466,8 @@ export interface Agent {runtime_id: string;/** False exactly when the agent has no runtime. Older backends omit it. */runtime_bound?: boolean;+ /** Privacy-safe coarse liveness for a runtime hidden from the runtime list. */+ runtime_availability?: "online" | "unstable" | "offline";name: string;description: string;/** What this agent's owner wrote. For a system agent this holds only thediff --git a/packages/core/workspace/queries.test.ts b/packages/core/workspace/queries.test.tsindex 57f782317c..63bbc258fd 100644--- a/packages/core/workspace/queries.test.ts+++ b/packages/core/workspace/queries.test.ts@@ -1,6 +1,6 @@import { describe, expect, it } from "vitest";-import type { Workspace } from "../types";-import { workspaceBySlugOptions } from "./queries";+import type { Agent, Workspace } from "../types";+import { agentListOptions, workspaceBySlugOptions } from "./queries";function makeWorkspace(slug: string): Workspace {return {@@ -31,3 +31,37 @@ describe("workspaceBySlugOptions", () => {expect(workspaceBySlugOptions("missing").select?.(workspaces)).toBeNull();});});++describe("agentListOptions", () => {+ it("polls only while projected runtime availability can age offline", () => {+ const options = agentListOptions("ws-1");+ const interval = options.refetchInterval;+ expect(typeof interval).toBe("function");+ if (typeof interval !== "function") return;++ const queryState = (data: Agent[]) =>+ interval({ state: { status: "success", data } } as never);++ expect(+ queryState([{ runtime_availability: "online" } as Agent]),+ ).toBe(30_000);+ expect(+ queryState([{ runtime_availability: "unstable" } as Agent]),+ ).toBe(30_000);+ expect(+ queryState([{ runtime_availability: "offline" } as Agent]),+ ).toBe(false);+ expect(+ queryState([{ runtime_availability: undefined } as Agent]),+ ).toBe(false);+ expect(+ queryState([+ {+ archived_at: "2026-09-04T00:00:00Z",+ runtime_availability: "online",+ } as Agent,+ ]),+ ).toBe(false);+ expect(queryState([])).toBe(false);+ });+});diff --git a/packages/core/workspace/queries.ts b/packages/core/workspace/queries.tsindex 5d3013e808..fac21d06f8 100644--- a/packages/core/workspace/queries.ts+++ b/packages/core/workspace/queries.ts@@ -50,6 +50,17 @@ export function agentListOptions(wsId: string) {queryKey: workspaceKeys.agents(wsId),queryFn: () =>api.listAgents({ workspace_id: wsId, include_archived: true }),+ // Projected unstable can age offline without an event; polling online also+ // covers a missed demotion. Offline recovery is event/reconnect-driven.+ refetchInterval: (query) =>+ query.state.data?.some(+ (agent) =>+ !agent.archived_at &&+ (agent.runtime_availability === "online" ||+ agent.runtime_availability === "unstable"),+ )+ ? 30_000+ : false,});}diff --git a/packages/views/agents/components/agent-activity-hover-content.test.tsx b/packages/views/agents/components/agent-activity-hover-content.test.tsxindex cdeb65060c..a82fb09faf 100644--- a/packages/views/agents/components/agent-activity-hover-content.test.tsx+++ b/packages/views/agents/components/agent-activity-hover-content.test.tsx@@ -2,9 +2,14 @@import { cleanup, screen } from "@testing-library/react";import { afterEach, describe, expect, it, vi } from "vitest";-import type { AgentTask, Issue } from "@multica/core/types";+import type { Agent, AgentRuntime, AgentTask, Issue } from "@multica/core/types";import { renderWithI18n } from "../../test/i18n";+const activityQueryData = vi.hoisted(() => ({+ agents: [] as Agent[],+ runtimes: [] as AgentRuntime[],+}));+// The hover card renders one row per internal task record and counts product// runs, so its header must describe runs — not agents. A single agent can have// several runs at once (e.g. the workspace chip reads "2 working" for two@@ -37,10 +42,6 @@ vi.mock("@multica/core/workspace/queries", () => ({agentListOptions: () => ({ queryKey: ["agents"] }),}));-vi.mock("@multica/core/agents", () => ({- deriveAgentAvailability: () => "online",-}));-vi.mock("@multica/ui/components/common/actor-avatar", () => ({ActorAvatar: ({ name }: { name: string }) => (<span data-testid="actor-avatar">{name}</span>@@ -52,7 +53,15 @@ vi.mock("@tanstack/react-query", async () => {await vi.importActual<typeof import("@tanstack/react-query")>("@tanstack/react-query",);- return { ...actual, useQuery: () => ({ data: [] }) };+ return {+ ...actual,+ useQuery: (options: { queryKey?: readonly unknown[] }) => ({+ data:+ options.queryKey?.[0] === "agents"+ ? activityQueryData.agents+ : activityQueryData.runtimes,+ }),+ };});import {@@ -105,7 +114,11 @@ function makeTask(overrides: Partial<AgentTask>): AgentTask {};}-afterEach(cleanup);+afterEach(() => {+ cleanup();+ activityQueryData.agents = [];+ activityQueryData.runtimes = [];+});describe("AgentActivityHoverContent", () => {// Two agents, three active runs (Niko has two at once). The header must@@ -130,6 +143,27 @@ describe("AgentActivityHoverContent", () => {expect(screen.getByText("1 active run")).toBeInTheDocument();});+ it("uses an online agent projection when its runtime row is hidden", () => {+ activityQueryData.agents = [+ {+ id: "agent-1",+ runtime_id: "private-runtime",+ runtime_availability: "online",+ } as Agent,+ ];++ const { container } = renderWithI18n(+ <AgentActivityHoverContent tasks={[makeTask({ status: "queued" })]} />,+ );++ expect(+ container.querySelector('[class*="bg-muted-foreground/40"]'),+ ).toBeInTheDocument();+ expect(+ container.querySelector('[class*="bg-warning"]'),+ ).not.toBeInTheDocument();+ });+it("renders the Chinese run copy", () => {renderWithI18n(<AgentActivityHoverContent tasks={threeTasksTwoAgents} />, {locale: "zh-Hans",diff --git a/packages/views/agents/components/agent-activity-hover-content.tsx b/packages/views/agents/components/agent-activity-hover-content.tsxindex 96393f28b6..d8a53b358d 100644--- a/packages/views/agents/components/agent-activity-hover-content.tsx+++ b/packages/views/agents/components/agent-activity-hover-content.tsx@@ -7,7 +7,7 @@ import { useActorName } from "@multica/core/workspace/hooks";import { useWorkspaceId } from "@multica/core/hooks";import { runtimeListOptions } from "@multica/core/runtimes/queries";import { agentListOptions } from "@multica/core/workspace/queries";-import { deriveAgentAvailability } from "@multica/core/agents";+import { deriveAgentPresenceDetail } from "@multica/core/agents/derive-presence";import type { AgentTask, Issue } from "@multica/core/types";import { workloadConfig } from "../presence";import { useT } from "../../i18n";@@ -73,7 +73,10 @@ function AgentActivityTaskRow({const agent = agentById.get(task.agent_id);const runtime = runtimeFrom(agent?.runtime_id, runtimeById);- const availability = deriveAgentAvailability(runtime, now);+ const availability = agent+ ? deriveAgentPresenceDetail({ agent, runtime, tasks: [], now })+ .availability+ : "offline";const isRunning = task.status === "running";// queued/dispatched both read as "queued" in the user-facing copy —// `dispatched` is the daemon-acked sub-state of queued and notdiff --git a/packages/views/agents/components/agent-profile-card.test.tsx b/packages/views/agents/components/agent-profile-card.test.tsxindex 1a9f6fda52..981e761cc0 100644--- a/packages/views/agents/components/agent-profile-card.test.tsx+++ b/packages/views/agents/components/agent-profile-card.test.tsx@@ -139,6 +139,28 @@ beforeEach(() => {mockAgents.current = [makeAgent()];});+describe("AgentProfileCard — Runtime row", () => {+ it.each([+ ["online", "svg.lucide-wifi"],+ ["unstable", "svg.lucide-wifi-high"],+ ["offline", "svg.lucide-wifi-off"],+ ] as const)(+ "uses projected %s availability when the private runtime row is hidden",+ (runtimeAvailability, iconSelector) => {+ mockAgents.current = [+ makeAgent({+ runtime_mode: "local",+ runtime_availability: runtimeAvailability,+ }),+ ];++ const { container } = renderCard();++ expect(container.querySelector(iconSelector)).toBeInTheDocument();+ },+ );+});+describe("AgentProfileCard — Model row", () => {it("shows the pinned model id and the effort badge", () => {mockAgents.current = [makeAgent({ model: "claude-opus-4-8", thinking_level: "high" })];diff --git a/packages/views/agents/components/agent-profile-card.tsx b/packages/views/agents/components/agent-profile-card.tsxindex c20ac185cf..8732cb80b2 100644--- a/packages/views/agents/components/agent-profile-card.tsx+++ b/packages/views/agents/components/agent-profile-card.tsx@@ -158,8 +158,9 @@ function AgentAvailabilityLine({}// Compact runtime row — wifi-style health icon + runtime name. The icon-// shape (Wifi / WifiOff) plus colour reflects the live runtime health-// derived from runtime + clock; cloud runtimes always read as online.+// shape (Wifi / WifiOff) plus colour reflects the live runtime health derived+// from a visible runtime + clock, or the coarse projection when that row is+// private; cloud runtimes always read as online.// This is duplicate signal with the availability dot above by design —// the dot is the agent's effective availability (which mostly tracks// runtime health), and seeing the same wifi icon next to the runtime@@ -177,7 +178,11 @@ function RuntimeRow({? "online": runtime? deriveRuntimeHealth(runtime, Date.now())- : "offline";+ : agent.runtime_availability === "online"+ ? "online"+ : agent.runtime_availability === "unstable"+ ? "recently_lost"+ : "offline";const label = runtime? runtimeDisplayLabel(runtime): isClouddiff --git a/server/cmd/server/main.go b/server/cmd/server/main.goindex b6168fa281..8c7d054042 100644--- a/server/cmd/server/main.go+++ b/server/cmd/server/main.go@@ -647,6 +647,11 @@ func main() {// create a second wrapper around the same primary pool.h.ReadSelector = dbreader.New(h.Queries, replicaQueries, readRecorder)+ // Reconciled race recoveries in the batched scheduler reuse the same+ // daemon:register refresh the sync transition path publishes. Wired before+ // the scheduler's Run goroutine starts so the field write is race-free.+ heartbeatScheduler.RecoveryNotifier = h+srv := newMainHTTPServer(":"+port, r)profilingServer := profiling.NewServer()diff --git a/server/internal/handler/agent.go b/server/internal/handler/agent.goindex 2ba6865d0b..7d40248f36 100644--- a/server/internal/handler/agent.go+++ b/server/internal/handler/agent.go@@ -11,6 +11,7 @@ import ("net/http""regexp""strings"+ "time""unicode/utf8""github.com/go-chi/chi/v5"@@ -58,9 +59,14 @@ type AgentResponse struct {// branch on this rather than on RuntimeID being falsy, and must not confuse// it with a bound-but-offline runtime (a different user story: reconnect the// machine vs. pick a new one).- RuntimeBound bool `json:"runtime_bound"`- Name string `json:"name"`- Description string `json:"description"`+ RuntimeBound bool `json:"runtime_bound"`+ // RuntimeAvailability is the coarse liveness projection for a runtime that+ // may be hidden from the caller's runtime list. It deliberately carries no+ // timestamp, device, owner, configuration, or credential fields; clients+ // use it only when the full runtime row is unavailable.+ RuntimeAvailability string `json:"runtime_availability,omitempty"`+ Name string `json:"name"`+ Description string `json:"description"`// Instructions is what this agent's owner wrote. For a system agent it// holds only the workspace's own notes — the product half lives in// SystemInstructions and is never stored on the row.@@ -970,6 +976,58 @@ func computeTaskKind(t db.AgentTaskQueue) string {return "direct"}+// loadAgentRuntimeAvailability returns only a coarse liveness bucket for+// agent presence. Runtime rows are loaded internally even when the caller is+// not allowed to list or inspect the private runtime; no runtime fields are+// copied onto an agent response. The existing runtime-list visibility contract+// is mirrored so the bucket is only copied when the full row is hidden.+func (h *Handler) loadAgentRuntimeAvailability(ctx context.Context, agents []db.Agent, workspaceID, viewerID, viewerRole string, now time.Time) (map[string]string, error) {+ // Owner/admin runtime lists already contain every row, so their normal+ // client-side derivation is authoritative and no projection query is needed.+ if roleAllowed(viewerRole, "owner", "admin") {+ return map[string]string{}, nil+ }++ runtimeIDs := make([]pgtype.UUID, 0, len(agents))+ for _, agent := range agents {+ // Archived presence always resolves to "archived", so its runtime state+ // is neither user-visible nor a reason for clients to keep polling.+ if !agent.ArchivedAt.Valid && agent.RuntimeID.Valid {+ runtimeIDs = append(runtimeIDs, agent.RuntimeID)+ }+ }+ result := make(map[string]string, len(runtimeIDs))+ if len(runtimeIDs) == 0 {+ return result, nil+ }++ runtimes, err := h.Queries.GetAgentRuntimes(ctx, runtimeIDs)+ if err != nil {+ return nil, err+ }+ for _, runtime := range runtimes {+ // Agent/runtime workspace consistency is normally enforced at bind time;+ // keep the projection fail-closed if a legacy row violates it.+ if uuidToString(runtime.WorkspaceID) != workspaceID {+ continue+ }+ // ListAgentRuntimes exposes every row to workspace owner/admin and only+ // owner/public rows to regular members. Keep the coarse bridge for the+ // rows that the viewer's runtime list cannot carry.+ if runtime.Visibility == "public" ||+ (runtime.OwnerID.Valid && uuidToString(runtime.OwnerID) == viewerID) {+ continue+ }+ result[uuidToString(runtime.ID)] = deriveAgentRuntimeAvailability(runtime, now)+ }+ return result, nil+}++func deriveAgentRuntimeAvailability(runtime db.AgentRuntime, now time.Time) string {+ status := pgtype.Text{String: runtime.Status, Valid: runtime.Status != ""}+ return deriveRuntimeAvailability(status, runtime.LastSeenAt, now)+}+func (h *Handler) ListAgents(w http.ResponseWriter, r *http.Request) {workspaceID := h.resolveWorkspaceID(r)member, ok := h.workspaceMember(w, r, workspaceID)@@ -989,6 +1047,11 @@ func (h *Handler) ListAgents(w http.ResponseWriter, r *http.Request) {writeError(w, http.StatusInternalServerError, "failed to list agents")return}+ runtimeAvailabilityByID, err := h.loadAgentRuntimeAvailability(r.Context(), agents, workspaceID, userID, member.Role, time.Now())+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to load agent runtime availability")+ return+ }// Batch-load skills for all agents to avoid N+1.skillRows, err := h.Queries.ListAgentSkillsByWorkspace(r.Context(), parseUUID(workspaceID))@@ -1040,6 +1103,12 @@ func (h *Handler) ListAgents(w http.ResponseWriter, r *http.Request) {}}resp := h.agentToResponse(a)+ // The map is keyed by runtime, and active + archived agents may share one.+ // Keep the archived guard here as well as in the loader so an active sibling+ // cannot leak its projection onto an archived response.+ if availability, ok := runtimeAvailabilityByID[resp.RuntimeID]; ok && !a.ArchivedAt.Valid {+ resp.RuntimeAvailability = availability+ }applyInvocationTargetsToResponse(&resp, targets)if skills, ok := skillMap[resp.ID]; ok {resp.Skills = skills@@ -1083,12 +1152,25 @@ func (h *Handler) GetAgent(w http.ResponseWriter, r *http.Request) {// render an explicit "no access" placeholder instead of a 404 — see// agent-detail-page.tsx.workspaceID := uuidToString(agent.WorkspaceID)- actorType, actorID := h.resolveActor(r, requestUserID(r), workspaceID)+ userID := requestUserID(r)+ actorType, actorID := h.resolveActor(r, userID, workspaceID)if !h.canAccessPrivateAgent(r.Context(), agent, actorType, actorID, workspaceID) {writeError(w, http.StatusForbidden, "you do not have access to this agent")return}resp := h.agentToResponse(agent)+ viewerRole := ""+ if member, ok := ctxMember(r.Context()); ok {+ viewerRole = member.Role+ }+ runtimeAvailability, err := h.loadAgentRuntimeAvailability(r.Context(), []db.Agent{agent}, workspaceID, userID, viewerRole, time.Now())+ if err != nil {+ writeError(w, http.StatusInternalServerError, "failed to load agent runtime availability")+ return+ }+ if availability, ok := runtimeAvailability[resp.RuntimeID]; ok {+ resp.RuntimeAvailability = availability+ }if !h.enrichAgentResponseWithTargetsHTTP(w, r, &resp, agent.ID) {return}@@ -1103,7 +1185,6 @@ func (h *Handler) GetAgent(w http.ResponseWriter, r *http.Request) {// mcp_config redaction (custom_env was removed from this response shape// in MUL-2600; secrets are now fetched via GET /api/agents/{id}/env).- userID := requestUserID(r)ws, err := h.Queries.GetWorkspace(r.Context(), agent.WorkspaceID)if err != nil {slog.Warn("GetWorkspace failed for redact check", "workspace_id", uuidToString(agent.WorkspaceID), "error", err)diff --git a/server/internal/handler/agent_access_test.go b/server/internal/handler/agent_access_test.goindex 8c6d5f48d5..0d4edce29c 100644--- a/server/internal/handler/agent_access_test.go+++ b/server/internal/handler/agent_access_test.go@@ -5,13 +5,72 @@ import ("encoding/json""net/http""net/http/httptest"+ "strconv""testing"+ "time"+ "github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/middleware"+ "github.com/multica-ai/multica/server/internal/testutil""github.com/multica-ai/multica/server/internal/util"db "github.com/multica-ai/multica/server/pkg/db/generated")+func TestDeriveAgentRuntimeAvailability(t *testing.T) {+ now := time.Date(2026, time.April, 27, 12, 0, 0, 0, time.UTC)+ timestamp := func(at time.Time) pgtype.Timestamptz {+ return pgtype.Timestamptz{Time: at, Valid: true}+ }++ for _, tc := range []struct {+ name string+ status string+ seen pgtype.Timestamptz+ want string+ }{+ {name: "online", status: "online", want: "online"},+ {name: "recent loss", status: "offline", seen: timestamp(now.Add(-time.Minute)), want: "unstable"},+ {name: "offline", status: "offline", seen: timestamp(now.Add(-10 * time.Minute)), want: "offline"},+ {name: "missing heartbeat", status: "offline", want: "offline"},+ } {+ t.Run(tc.name, func(t *testing.T) {+ got := deriveAgentRuntimeAvailability(db.AgentRuntime{+ Status: tc.status,+ LastSeenAt: tc.seen,+ }, now)+ if got != tc.want {+ t.Fatalf("deriveAgentRuntimeAvailability = %q, want %q", got, tc.want)+ }+ })+ }+}++func TestLoadAgentRuntimeAvailability_PrivilegedViewerSkipsRuntimeQuery(t *testing.T) {+ h := &Handler{}+ agents := []db.Agent{{+ RuntimeID: util.MustParseUUID("11111111-1111-1111-1111-111111111111"),+ }}++ for _, role := range []string{"owner", "admin"} {+ t.Run(role, func(t *testing.T) {+ got, err := h.loadAgentRuntimeAvailability(+ context.Background(),+ agents,+ "22222222-2222-2222-2222-222222222222",+ "33333333-3333-3333-3333-333333333333",+ role,+ time.Now(),+ )+ if err != nil {+ t.Fatalf("loadAgentRuntimeAvailability: %v", err)+ }+ if len(got) != 0 {+ t.Fatalf("availability = %v, want empty for %s", got, role)+ }+ })+ }+}+// TestMemberAllowedToViewAgent_Pure exercises the pure predicate that drives// the private-agent VIEW gate. For a private agent it must allow:// - workspace owner / admin (regardless of agent ownership)@@ -142,6 +201,13 @@ func TestGetAgent_PrivateAgentForbidsPlainMember(t *testing.T) {if w.Code != http.StatusOK {t.Fatalf("GetAgent as workspace owner: expected 200, got %d: %s", w.Code, w.Body.String())}+ var ownerResponse map[string]json.RawMessage+ if err := json.Unmarshal(w.Body.Bytes(), &ownerResponse); err != nil {+ t.Fatalf("decode GetAgent owner response: %v", err)+ }+ if _, ok := ownerResponse["runtime_availability"]; ok {+ t.Fatal("runtime_availability should be omitted when the viewer owns the runtime")+ }// Agent owner (plain member who happens to own the agent): allowed.w = httptest.NewRecorder()@@ -190,6 +256,117 @@ func TestListAgents_FiltersPrivateForPlainMember(t *testing.T) {}}+// TestListAgents_SharedAgentCarriesPrivateRuntimeAvailability verifies the+// privacy-safe bridge used by presence derivation: a member may see a shared+// agent's coarse runtime availability even when that private runtime is absent+// from their runtime list, but no runtime detail fields are added to the agent+// response.+func TestListAgents_SharedAgentCarriesPrivateRuntimeAvailability(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }++ runtimeID, runtimeOwnerID, memberID := runtimeVisibilityFixture(t)+ agentID := dbfx.Agent(t, "shared-private-runtime-agent", runtimeID, testutil.Cols{+ "visibility": "workspace",+ "permission_mode": "public_to",+ "owner_id": runtimeOwnerID,+ })+ dbfx.Insert(t, "agent_invocation_target", testutil.Cols{+ "agent_id": agentID,+ "target_type": "workspace",+ "target_id": testWorkspaceID,+ })++ listResponse := testutil.Call(t, testHandler.ListAgents,+ newRequestAs(memberID, "GET", "/api/agents", nil)).Want(http.StatusOK)++ var responses []AgentResponse+ listResponse.JSON(&responses)+ var shared *AgentResponse+ for i := range responses {+ if responses[i].ID == agentID {+ shared = &responses[i]+ break+ }+ }+ if shared == nil {+ t.Fatalf("shared agent %s missing from member list", agentID)+ }+ if shared.RuntimeAvailability != "online" {+ t.Fatalf("runtime_availability = %q, want online", shared.RuntimeAvailability)+ }+ var wire []map[string]json.RawMessage+ listResponse.JSON(&wire)+ for _, item := range wire {+ if string(item["id"]) != strconv.Quote(agentID) {+ continue+ }+ for _, field := range []string{+ "device_info",+ "metadata",+ "daemon_id",+ "runtime_status",+ "runtime_last_seen_at",+ } {+ if _, ok := item[field]; ok {+ t.Errorf("agent response leaked runtime field %q", field)+ }+ }+ if string(item["runtime_availability"]) != strconv.Quote("online") {+ t.Errorf("runtime_availability = %s, want online", item["runtime_availability"])+ }+ }++ var detail AgentResponse+ testutil.Call(t, testHandler.GetAgent,+ withURLParam(newRequestAs(memberID, "GET", "/api/agents/"+agentID, nil), "id", agentID)).+ Want(http.StatusOK).JSON(&detail)+ if detail.RuntimeAvailability != "online" {+ t.Fatalf("GetAgent runtime_availability = %q, want online", detail.RuntimeAvailability)+ }++ // Archived agents short-circuit presence to "archived" and must not keep+ // every client polling for a projection it will never consume. Keep an+ // active sibling on the same runtime so this also catches accidentally+ // applying a runtime-keyed projection to the archived response.+ siblingID := dbfx.Agent(t, "active-shared-private-runtime-agent", runtimeID, testutil.Cols{+ "visibility": "workspace",+ "permission_mode": "public_to",+ "owner_id": runtimeOwnerID,+ })+ dbfx.Insert(t, "agent_invocation_target", testutil.Cols{+ "agent_id": siblingID,+ "target_type": "workspace",+ "target_id": testWorkspaceID,+ })+ dbfx.Exec(t, `UPDATE agent SET archived_at = now() WHERE id = $1`, agentID)++ archivedList := testutil.Call(t, testHandler.ListAgents,+ newRequestAs(memberID, "GET", "/api/agents?include_archived=true", nil)).Want(http.StatusOK)+ var archivedWire []map[string]json.RawMessage+ archivedList.JSON(&archivedWire)+ foundArchived := false+ foundActiveSibling := false+ for _, item := range archivedWire {+ switch string(item["id"]) {+ case strconv.Quote(agentID):+ foundArchived = true+ if _, ok := item["runtime_availability"]; ok {+ t.Fatal("archived agent should not carry runtime_availability")+ }+ case strconv.Quote(siblingID):+ foundActiveSibling = true+ if string(item["runtime_availability"]) != strconv.Quote("online") {+ t.Fatalf("active sibling runtime_availability = %s, want online", item["runtime_availability"])+ }+ }+ }+ if !foundArchived || !foundActiveSibling {+ t.Fatalf("include_archived list missing agents: archived=%t active_sibling=%t", foundArchived, foundActiveSibling)+ }+}+func listContainsAgent(t *testing.T, body []byte, agentID string) bool {t.Helper()var resp []AgentResponsediff --git a/server/internal/handler/daemon.go b/server/internal/handler/daemon.goindex 482cb3843a..93a92d0e3f 100644--- a/server/internal/handler/daemon.go+++ b/server/internal/handler/daemon.go@@ -1224,6 +1224,7 @@ func (h *Handler) recordHeartbeat(ctx context.Context, rt db.AgentRuntime) errorStatus: rt.Status,LastSeenAt: rt.LastSeenAt.Time,LastSeenAtValid: rt.LastSeenAt.Valid,+ WorkspaceID: rt.WorkspaceID,}, nil)}@@ -1233,10 +1234,14 @@ func (h *Handler) recordHeartbeatLease(ctx context.Context, runtimeID string, lereturn fmt.Errorf("invalid runtime_id: %w", err)}state := lease.Snapshot()+ // Lenient parse: the workspace ID only feeds the recovery refresh payload.+ // An invalid value suppresses the event instead of failing the heartbeat.+ wsUUID, _ := util.ParseUUID(state.WorkspaceID)return h.recordHeartbeatState(ctx, runtimeUUID, runtimeID, heartbeatLivenessState{Status: state.Status,LastSeenAt: state.LastSeenAt,LastSeenAtValid: state.LastSeenAtValid,+ WorkspaceID: wsUUID,}, lease.MarkDBWriteScheduled)}@@ -1244,6 +1249,9 @@ type heartbeatLivenessState struct {Status stringLastSeenAt time.TimeLastSeenAtValid bool+ // WorkspaceID feeds the recovery lifecycle refresh; it is already known+ // from the lease snapshot or the HTTP row and never re-read from the DB.+ WorkspaceID pgtype.UUID}func (h *Handler) recordHeartbeatState(@@ -1283,7 +1291,22 @@ func (h *Handler) recordHeartbeatState(// dependent work that expects an online row. The steady-state online bump// is ID-only and may be coalesced by the production scheduler.if state.Status != "online" || !state.LastSeenAtValid {- if _, err := h.Queries.MarkAgentRuntimeOnline(ctx, runtimeUUID); err != nil {+ // The conditional update reports whether this beat performed the+ // offline → online flip. Only an actual flip publishes the lifecycle+ // refresh; a beat that lost the race (or a never-seen row already+ // online) stays silent and keeps the unconditional update below so+ // last_seen_at is bumped and pgx.ErrNoRows is preserved for deletions.+ flipped, err := h.Queries.MarkAgentRuntimeOnlineIfOffline(ctx, runtimeUUID)+ if err != nil {+ return err+ }+ if flipped > 0 {+ // Reuse daemon:register so web and mobile invalidate both runtime and+ // agent projections. Ordinary online heartbeats stay silent.+ if state.WorkspaceID.Valid {+ h.PublishRuntimeRefresh(uuidToString(state.WorkspaceID), "system", "", "heartbeat_recovery")+ }+ } else if _, err := h.Queries.MarkAgentRuntimeOnline(ctx, runtimeUUID); err != nil {return err}if markDBWriteScheduled != nil {@@ -1291,7 +1314,7 @@ func (h *Handler) recordHeartbeatState(}return nil}- if err := h.HeartbeatScheduler.Schedule(ctx, runtimeUUID); err != nil {+ if err := h.HeartbeatScheduler.Schedule(ctx, runtimeUUID, state.WorkspaceID); err != nil {return err}if markDBWriteScheduled != nil {diff --git a/server/internal/handler/handler.go b/server/internal/handler/handler.goindex 56ff747495..07e638063a 100644--- a/server/internal/handler/handler.go+++ b/server/internal/handler/handler.go@@ -180,6 +180,14 @@ type RuntimeGoneNotifier interface {NotifyRuntimeGone(runtimeID string)}+// RuntimeRecoveryNotifier republishes the daemon:register lifecycle refresh+// after a heartbeat actually flipped an offline runtime row back online+// (sweeper-race fallback, batch-receipt reconciliation). Recovery paths already+// know the workspace, so publishing never needs a follow-up database lookup.+type RuntimeRecoveryNotifier interface {+ NotifyRuntimeRecovered(ctx context.Context, workspaceID string)+}+type Handler struct {Queries *db.QueriesReadSelector *dbreader.Selector@@ -493,6 +501,11 @@ func New(queries *db.Queries, txStarter txStarter, hub *realtime.Hub, bus *eventcfg: cfg,}h.WebhookDeliveryWorker = NewWebhookDeliveryWorker(h)+ // The default passthrough scheduler reports sweeper-race recoveries so the+ // daemon:register refresh fires even without the production batched wiring.+ if passthrough, ok := h.HeartbeatScheduler.(*PassthroughHeartbeatScheduler); ok {+ passthrough.RecoveryNotifier = h+ }// GitHub API snapshot pipeline for PR cards (MUL-5265). Built// unconditionally but inert (every trigger no-ops) when the App private key@@ -744,6 +757,16 @@ func (h *Handler) NotifyRuntimeGone(runtimeID string) {h.DaemonRuntimeGone.NotifyRuntimeGone(runtimeID)}+// NotifyRuntimeRecovered republishes the workspace-scoped daemon:register+// lifecycle event after a heartbeat restored a runtime from offline. Runtime+// details are intentionally omitted from the payload.+func (h *Handler) NotifyRuntimeRecovered(_ context.Context, workspaceID string) {+ if h == nil || workspaceID == "" {+ return+ }+ h.PublishRuntimeRefresh(workspaceID, "system", "", "heartbeat_recovery")+}+// publishTask is publish() plus a TaskID hint so the realtime layer can route// the event to the per-task scope rather than the whole workspace.func (h *Handler) publishTask(eventType, workspaceID, actorType, actorID, taskID string, payload any) {diff --git a/server/internal/handler/heartbeat_scheduler.go b/server/internal/handler/heartbeat_scheduler.goindex 3e46a46baa..c629aefb6c 100644--- a/server/internal/handler/heartbeat_scheduler.go+++ b/server/internal/handler/heartbeat_scheduler.go@@ -32,21 +32,30 @@ import (type HeartbeatScheduler interface {// Schedule is called from the heartbeat hot path after the per-row flush// window check has decided a DB write is warranted. Runtime ownership and- // status live in the connection lease, so only the ID enters this layer.- Schedule(ctx context.Context, runtimeID pgtype.UUID) error+ // status live in the connection lease. The workspace ID accompanies the+ // runtime ID so a rare passthrough recovery can publish without another read.+ //+ // When a Schedule/flush path itself flips an offline row back online+ // (sweeper-race fallback, batch-receipt reconciliation), it reports the+ // recovery through RecoveryNotifier so the workspace-scoped daemon:register+ // refresh fires exactly once per actual offline → online transition.+ Schedule(ctx context.Context, runtimeID, workspaceID pgtype.UUID) error}// PassthroughHeartbeatScheduler is the synchronous scheduler used as the// default in handler.New so tests observe DB writes immediately.type PassthroughHeartbeatScheduler struct {queries *db.Queries+ // RecoveryNotifier is optional; when nil, race recoveries stay silent+ // (plain last_seen_at bookkeeping).+ RecoveryNotifier RuntimeRecoveryNotifier}func NewPassthroughHeartbeatScheduler(queries *db.Queries) *PassthroughHeartbeatScheduler {return &PassthroughHeartbeatScheduler{queries: queries}}-func (p *PassthroughHeartbeatScheduler) Schedule(ctx context.Context, runtimeID pgtype.UUID) error {+func (p *PassthroughHeartbeatScheduler) Schedule(ctx context.Context, runtimeID, workspaceID pgtype.UUID) error {rows, err := p.queries.TouchAgentRuntimeLastSeen(ctx, runtimeID)if err != nil {return err@@ -54,12 +63,29 @@ func (p *PassthroughHeartbeatScheduler) Schedule(ctx context.Context, runtimeIDif rows > 0 {return nil}- // The row either raced offline or was deleted. MarkAgentRuntimeOnline- // restores the former and preserves pgx.ErrNoRows for the latter.+ // The row either raced offline or was deleted. The conditional update+ // reports an actual offline → online flip so the recovery refresh can fire;+ // if another heartbeat already won the race (or the row is gone), the+ // unconditional MarkAgentRuntimeOnline still bumps last_seen_at and+ // preserves pgx.ErrNoRows for the deleted case.+ flipped, err := p.queries.MarkAgentRuntimeOnlineIfOffline(ctx, runtimeID)+ if err != nil {+ return err+ }+ if flipped > 0 {+ p.notifyRuntimeRecovered(ctx, workspaceID)+ return nil+ }_, err = p.queries.MarkAgentRuntimeOnline(ctx, runtimeID)return err}+func (p *PassthroughHeartbeatScheduler) notifyRuntimeRecovered(ctx context.Context, workspaceID pgtype.UUID) {+ if p.RecoveryNotifier != nil && workspaceID.Valid {+ p.RecoveryNotifier.NotifyRuntimeRecovered(ctx, uuidToString(workspaceID))+ }+}+// BatchedHeartbeatScheduler coalesces same-id Schedule calls within a tick// window into a single bulk UPDATE.//@@ -79,6 +105,9 @@ type BatchedHeartbeatScheduler struct {queries *db.QueriesruntimeGone RuntimeGoneNotifiertickInterval time.Duration+ // RecoveryNotifier is optional; when nil, reconciled race recoveries stay+ // silent (plain last_seen_at bookkeeping).+ RecoveryNotifier RuntimeRecoveryNotifiermu sync.Mutexpending map[pgtype.UUID]struct{}@@ -116,7 +145,7 @@ func NewBatchedHeartbeatScheduler(queries *db.Queries, tickInterval time.Duratio}}-func (b *BatchedHeartbeatScheduler) Schedule(_ context.Context, runtimeID pgtype.UUID) error {+func (b *BatchedHeartbeatScheduler) Schedule(_ context.Context, runtimeID, _ pgtype.UUID) error {b.mu.Lock()b.pending[runtimeID] = struct{}{}b.mu.Unlock()@@ -251,6 +280,7 @@ func (b *BatchedHeartbeatScheduler) flushOnce(ctx context.Context) {continue}recovered+++ b.notifyRuntimeRecovered(ctx, state.WorkspaceID)}for _, id := range omitted {@@ -286,3 +316,9 @@ func (b *BatchedHeartbeatScheduler) notifyRuntimeGone(id pgtype.UUID) {b.runtimeGone.NotifyRuntimeGone(uuidToString(id))}}++func (b *BatchedHeartbeatScheduler) notifyRuntimeRecovered(ctx context.Context, workspaceID pgtype.UUID) {+ if b.RecoveryNotifier != nil && workspaceID.Valid {+ b.RecoveryNotifier.NotifyRuntimeRecovered(ctx, uuidToString(workspaceID))+ }+}diff --git a/server/internal/handler/heartbeat_scheduler_test.go b/server/internal/handler/heartbeat_scheduler_test.goindex 8019dd3444..4f5266520b 100644--- a/server/internal/handler/heartbeat_scheduler_test.go+++ b/server/internal/handler/heartbeat_scheduler_test.go@@ -35,7 +35,7 @@ func TestBatchedHeartbeatScheduler_CoalescesAndFlushes(t *testing.T) {for i := 0; i < callers; i++ {go func() {defer wg.Done()- if err := sched.Schedule(context.Background(), rt.ID); err != nil {+ if err := sched.Schedule(context.Background(), rt.ID, rt.WorkspaceID); err != nil {t.Errorf("Schedule: %v", err)}}()@@ -77,8 +77,10 @@ func TestBatchedHeartbeatScheduler_ExplicitDeregisterReceiptStaysOffline(t *testruntimeID := createRuntimeLocalSkillTestRuntime(t, testUserID)setRuntimeLastSeenAt(t, runtimeID, time.Now())rt := loadRuntime(t, runtimeID)+ recoveries := &recordingRecoveryNotifier{}sched := NewBatchedHeartbeatScheduler(testHandler.Queries, 0, nil)- if err := sched.Schedule(context.Background(), rt.ID); err != nil {+ sched.RecoveryNotifier = recoveries+ if err := sched.Schedule(context.Background(), rt.ID, rt.WorkspaceID); err != nil {t.Fatalf("Schedule: %v", err)}reason := []byte(`{"code":"provider_removed"}`)@@ -109,6 +111,10 @@ func TestBatchedHeartbeatScheduler_ExplicitDeregisterReceiptStaysOffline(t *testif got := sched.PendingCount(); got != 0 {t.Fatalf("preserved offline runtime remained pending: %d", got)}+ // A preserved explicit deregistration is not a recovery: no refresh event.+ if len(recoveries.workspaceIDs) != 0 {+ t.Fatalf("preserved offline runtime published recovery events: %v", recoveries.workspaceIDs)+ }}// TestBatchedHeartbeatScheduler_StopDrains confirms the shutdown contract:@@ -131,7 +137,7 @@ func TestBatchedHeartbeatScheduler_StopDrains(t *testing.T) {defer cancel()go sched.Run(ctx)- if err := sched.Schedule(context.Background(), rt.ID); err != nil {+ if err := sched.Schedule(context.Background(), rt.ID, rt.WorkspaceID); err != nil {t.Fatalf("Schedule: %v", err)}if got := sched.PendingCount(); got != 1 {@@ -179,7 +185,7 @@ func TestBatchedHeartbeatScheduler_StopFlushesLateSchedule(t *testing.T) {// Now Schedule a late heartbeat. Run is gone; only Stop's defensive// flush can persist this.- if err := sched.Schedule(context.Background(), rt.ID); err != nil {+ if err := sched.Schedule(context.Background(), rt.ID, rt.WorkspaceID); err != nil {t.Fatalf("Schedule: %v", err)}if got := sched.PendingCount(); got != 1 {@@ -197,6 +203,48 @@ func TestBatchedHeartbeatScheduler_StopFlushesLateSchedule(t *testing.T) {}}+// TestBatchedHeartbeatScheduler_StopRecoveryUsesBoundedContextAndKnownWorkspace+// verifies that the Stop drain keeps its deadline and avoids another lookup.+func TestBatchedHeartbeatScheduler_StopRecoveryUsesBoundedContextAndKnownWorkspace(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ runtimeID := createRuntimeLocalSkillTestRuntime(t, testUserID)+ setRuntimeLastSeenAt(t, runtimeID, time.Now().Add(-2*heartbeatReceiptRecoveryThreshold))+ rt := loadRuntime(t, runtimeID)++ recoveries := &recordingRecoveryNotifier{}+ sched := NewBatchedHeartbeatScheduler(testHandler.Queries, time.Hour, nil)+ sched.RecoveryNotifier = recoveries+ go sched.Run(context.Background())+ if err := sched.Schedule(context.Background(), rt.ID, rt.WorkspaceID); err != nil {+ t.Fatalf("Schedule: %v", err)+ }+ rows, err := testHandler.Queries.MarkRuntimesOfflineByIDs(context.Background(), db.MarkRuntimesOfflineByIDsParams{+ Ids: []pgtype.UUID{rt.ID},+ StaleSeconds: service.RuntimeClaimFreshnessSeconds,+ })+ if err != nil {+ t.Fatalf("MarkRuntimesOfflineByIDs: %v", err)+ }+ if len(rows) != 1 {+ t.Fatalf("sweeper rows = %d, want 1", len(rows))+ }++ sched.Stop()++ if len(recoveries.workspaceIDs) != 1 || recoveries.workspaceIDs[0] != testWorkspaceID {+ t.Fatalf("recovery workspaces = %v, want [%s]", recoveries.workspaceIDs, testWorkspaceID)+ }+ deadline, ok := recoveries.contexts[0].Deadline()+ if !ok {+ t.Fatal("Stop recovery context has no deadline")+ }+ if remaining := time.Until(deadline); remaining <= 0 || remaining > 10*time.Second {+ t.Fatalf("Stop recovery deadline remaining = %s, want within (0s, 10s]", remaining)+ }+}+// TestBatchedHeartbeatScheduler_FlushIgnoresEmpty exercises the empty-pending// fast path: a tick with nothing queued must not issue a DB call.func TestBatchedHeartbeatScheduler_FlushIgnoresEmpty(t *testing.T) {@@ -214,6 +262,18 @@ func TestBatchedHeartbeatScheduler_FlushIgnoresEmpty(t *testing.T) {// TestBatchedHeartbeatScheduler_RaceToOfflineSelfHeals confirms that if the// sweeper flips a row offline between Schedule and FlushNow, receipt// reconciliation restores it without a new heartbeat lookup.+// recordingRecoveryNotifier captures RuntimeRecoveryNotifier calls so tests+// can assert a lifecycle refresh fires for the already-known workspace.+type recordingRecoveryNotifier struct {+ workspaceIDs []string+ contexts []context.Context+}++func (r *recordingRecoveryNotifier) NotifyRuntimeRecovered(ctx context.Context, workspaceID string) {+ r.workspaceIDs = append(r.workspaceIDs, workspaceID)+ r.contexts = append(r.contexts, ctx)+}+func TestBatchedHeartbeatScheduler_RaceToOfflineSelfHeals(t *testing.T) {if testHandler == nil {t.Skip("database not available")@@ -222,8 +282,10 @@ func TestBatchedHeartbeatScheduler_RaceToOfflineSelfHeals(t *testing.T) {setRuntimeLastSeenAt(t, runtimeID, time.Now().Add(-2*heartbeatReceiptRecoveryThreshold))rt := loadRuntime(t, runtimeID)+ recoveries := &recordingRecoveryNotifier{}sched := NewBatchedHeartbeatScheduler(testHandler.Queries, 0, nil)- if err := sched.Schedule(context.Background(), rt.ID); err != nil {+ sched.RecoveryNotifier = recoveries+ if err := sched.Schedule(context.Background(), rt.ID, rt.WorkspaceID); err != nil {t.Fatalf("Schedule: %v", err)}@@ -240,7 +302,8 @@ func TestBatchedHeartbeatScheduler_RaceToOfflineSelfHeals(t *testing.T) {t.Fatalf("sweeper rows = %d, want 1", len(rows))}- sched.FlushNow(context.Background())+ flushCtx := context.WithValue(context.Background(), recoveryContextKey{}, "batch")+ sched.FlushNow(flushCtx)// The bulk UPDATE omits the offline row, and receipt reconciliation flips// it back online without waiting for another heartbeat.@@ -248,6 +311,14 @@ func TestBatchedHeartbeatScheduler_RaceToOfflineSelfHeals(t *testing.T) {if status != "online" {t.Fatalf("expected receipt reconciliation to recover online, got %q", status)}+ // The reconciled flip is a real offline → online recovery: one lifecycle+ // refresh, no more.+ if len(recoveries.workspaceIDs) != 1 || recoveries.workspaceIDs[0] != testWorkspaceID {+ t.Fatalf("recovery workspaces = %v, want [%s]", recoveries.workspaceIDs, testWorkspaceID)+ }+ if got := recoveries.contexts[0].Value(recoveryContextKey{}); got != "batch" {+ t.Fatalf("recovery context value = %v, want batch", got)+ }}func TestBatchedHeartbeatScheduler_DeletedReceiptInvalidatesRuntime(t *testing.T) {@@ -258,7 +329,7 @@ func TestBatchedHeartbeatScheduler_DeletedReceiptInvalidatesRuntime(t *testing.Trt := loadRuntime(t, runtimeID)notifier := &recordingRuntimeGoneNotifier{}sched := NewBatchedHeartbeatScheduler(testHandler.Queries, 0, notifier)- if err := sched.Schedule(context.Background(), rt.ID); err != nil {+ if err := sched.Schedule(context.Background(), rt.ID, rt.WorkspaceID); err != nil {t.Fatalf("Schedule: %v", err)}if _, err := testPool.Exec(context.Background(), `DELETE FROM agent_runtime WHERE id = $1`, runtimeID); err != nil {@@ -288,11 +359,17 @@ func TestPassthroughHeartbeatScheduler_TouchAndRaceRecovery(t *testing.T) {setRuntimeLastSeenAt(t, runtimeID, stale)rt := loadRuntime(t, runtimeID)+ recoveries := &recordingRecoveryNotifier{}sched := NewPassthroughHeartbeatScheduler(testHandler.Queries)+ sched.RecoveryNotifier = recoveries- if err := sched.Schedule(context.Background(), rt.ID); err != nil {+ if err := sched.Schedule(context.Background(), rt.ID, rt.WorkspaceID); err != nil {t.Fatalf("Schedule: %v", err)}+ // Ordinary online bump: no recovery refresh.+ if len(recoveries.workspaceIDs) != 0 {+ t.Fatalf("online heartbeat published recovery events: %v", recoveries.workspaceIDs)+ }_, lastSeen, _ := readRuntimeRow(t, runtimeID)if !lastSeen.After(stale.Add(time.Minute)) {t.Fatalf("passthrough did not bump last_seen_at: stale=%s after=%s", stale, lastSeen)@@ -301,15 +378,25 @@ func TestPassthroughHeartbeatScheduler_TouchAndRaceRecovery(t *testing.T) {// Race: snapshot still says online but DB is now offline.rt2 := loadRuntime(t, runtimeID)setRuntimeStatus(t, runtimeID, "offline")- if err := sched.Schedule(context.Background(), rt2.ID); err != nil {+ scheduleCtx := context.WithValue(context.Background(), recoveryContextKey{}, "passthrough")+ if err := sched.Schedule(scheduleCtx, rt2.ID, rt2.WorkspaceID); err != nil {t.Fatalf("Schedule under race: %v", err)}status, _, _ := readRuntimeRow(t, runtimeID)if status != "online" {t.Fatalf("expected race recovery via MarkAgentRuntimeOnline, got %q", status)}+ // The race flip is a real recovery: exactly one lifecycle refresh.+ if len(recoveries.workspaceIDs) != 1 || recoveries.workspaceIDs[0] != testWorkspaceID {+ t.Fatalf("recovery workspaces = %v, want [%s]", recoveries.workspaceIDs, testWorkspaceID)+ }+ if got := recoveries.contexts[0].Value(recoveryContextKey{}); got != "passthrough" {+ t.Fatalf("recovery context value = %v, want passthrough", got)+ }}+type recoveryContextKey struct{}+// silenceUnusedPgUUID ensures the package compiles even if no other test// happens to reference pgtype after future edits trim imports.var _ = pgtype.UUID{}diff --git a/server/internal/handler/heartbeat_test.go b/server/internal/handler/heartbeat_test.goindex 18413a7cc9..6dbedd0eff 100644--- a/server/internal/handler/heartbeat_test.go+++ b/server/internal/handler/heartbeat_test.go@@ -10,7 +10,9 @@ import ("github.com/google/uuid""github.com/jackc/pgx/v5/pgtype""github.com/multica-ai/multica/server/internal/daemonws"+ "github.com/multica-ai/multica/server/internal/events"db "github.com/multica-ai/multica/server/pkg/db/generated"+ "github.com/multica-ai/multica/server/pkg/protocol")// fakeLivenessStore lets tests drive every Available / Touch / IsAliveBatch@@ -69,7 +71,7 @@ type recordingHeartbeatScheduler struct {err error}-func (s *recordingHeartbeatScheduler) Schedule(_ context.Context, id pgtype.UUID) error {+func (s *recordingHeartbeatScheduler) Schedule(_ context.Context, id, _ pgtype.UUID) error {s.ids = append(s.ids, id)return s.err}@@ -323,6 +325,67 @@ func TestRecordHeartbeat_OfflineToOnlineForcesDBWrite(t *testing.T) {}}+// TestRecordHeartbeat_RecoveryPublishesOnce verifies that a heartbeat-only+// offline -> online recovery wakes presence clients, while the next ordinary+// online heartbeat stays silent.+func TestRecordHeartbeat_RecoveryPublishesOnce(t *testing.T) {+ if testHandler == nil {+ t.Skip("database not available")+ }+ runtimeID := createRuntimeLocalSkillTestRuntime(t, testUserID)+ setRuntimeStatus(t, runtimeID, "offline")+ setRuntimeLastSeenAt(t, runtimeID, time.Now())++ h := *testHandler+ h.Bus = events.New()+ h.LivenessStore = NewNoopLivenessStore()+ h.HeartbeatScheduler = NewPassthroughHeartbeatScheduler(h.Queries)+ var refreshes []events.Event+ h.Bus.Subscribe(protocol.EventDaemonRegister, func(event events.Event) {+ refreshes = append(refreshes, event)+ })++ if err := h.recordHeartbeat(context.Background(), loadRuntime(t, runtimeID)); err != nil {+ t.Fatalf("recovery recordHeartbeat: %v", err)+ }+ if len(refreshes) != 1 {+ t.Fatalf("recovery should publish one daemon refresh, got %d", len(refreshes))+ }+ if refreshes[0].WorkspaceID != testWorkspaceID {+ t.Fatalf("refresh workspace_id = %q, want %q", refreshes[0].WorkspaceID, testWorkspaceID)+ }+ if payload, ok := refreshes[0].Payload.(map[string]any); !ok || payload["action"] != "heartbeat_recovery" {+ t.Fatalf("refresh payload = %#v, want heartbeat_recovery", refreshes[0].Payload)+ }++ if err := h.recordHeartbeat(context.Background(), loadRuntime(t, runtimeID)); err != nil {+ t.Fatalf("ordinary recordHeartbeat: %v", err)+ }+ if len(refreshes) != 1 {+ t.Fatalf("ordinary online heartbeat published %d refreshes, want 1 total", len(refreshes))+ }+}++// TestNotifyRuntimeRecovered_PublishesKnownWorkspaceWithoutLookup pins the+// no-query contract: a handler with no Queries can still publish the refresh.+func TestNotifyRuntimeRecovered_PublishesKnownWorkspaceWithoutLookup(t *testing.T) {+ const workspaceID = "11111111-1111-1111-1111-111111111111"+ h := Handler{Bus: events.New()}+ var refreshes []events.Event+ h.Bus.Subscribe(protocol.EventDaemonRegister, func(event events.Event) {+ refreshes = append(refreshes, event)+ })++ h.NotifyRuntimeRecovered(context.Background(), workspaceID)++ if len(refreshes) != 1 {+ t.Fatalf("recovery refreshes = %d, want 1", len(refreshes))+ }+ if refreshes[0].WorkspaceID != workspaceID {+ t.Fatalf("refresh workspace_id = %q, want %q", refreshes[0].WorkspaceID, workspaceID)+ }+}+// TestRecordHeartbeat_TouchErrorFallsBackToDB confirms graceful degradation:// if Redis Touch errors, the heartbeat still writes the DB so the sweeper's// DB-only fallback path observes a fresh last_seen_at.diff --git a/server/internal/handler/squad.go b/server/internal/handler/squad.goindex 4ca3c46720..aa2f21acf6 100644--- a/server/internal/handler/squad.go+++ b/server/internal/handler/squad.go@@ -585,6 +585,29 @@ type SquadMemberStatusListResponse struct {Members []SquadMemberStatusResponse `json:"members"`}+// deriveRuntimeAvailability owns the shared three-state runtime reachability+// policy. Agent projections use these values directly; squad presence maps an+// online runtime to its user-facing "idle" bucket after workload precedence.+func deriveRuntimeAvailability(+ runtimeStatus pgtype.Text,+ lastSeen pgtype.Timestamptz,+ now time.Time,+) string {+ if !runtimeStatus.Valid {+ return "offline"+ }+ if runtimeStatus.String == "online" {+ return "online"+ }+ if !lastSeen.Valid {+ return "offline"+ }+ if now.Sub(lastSeen.Time) < 5*time.Minute {+ return "unstable"+ }+ return "offline"+}+// deriveSquadMemberStatus collapses runtime + task signals into the five// status buckets used by the squad UI. Mirrors the workload+availability// split in packages/core/agents/derive-presence.ts: working wins over@@ -616,19 +639,11 @@ func deriveSquadMemberStatus(if hasWorkingTask {return "working"}- if !runtimeStatus.Valid {- return "offline"- }- if runtimeStatus.String == "online" {+ availability := deriveRuntimeAvailability(runtimeStatus, lastSeen, now)+ if availability == "online" {return "idle"}- if !lastSeen.Valid {- return "offline"- }- if now.Sub(lastSeen.Time) < 5*time.Minute {- return "unstable"- }- return "offline"+ return availability}// ListSquadMemberStatus returns one entry per squad member with deriveddiff --git a/server/pkg/db/generated/runtime.sql.go b/server/pkg/db/generated/runtime.sql.goindex 574dcacbdb..bb53cd9d75 100644--- a/server/pkg/db/generated/runtime.sql.go+++ b/server/pkg/db/generated/runtime.sql.go@@ -1009,6 +1009,24 @@ func (q *Queries) MarkAgentRuntimeOnline(ctx context.Context, id pgtype.UUID) (Areturn i, err}+const markAgentRuntimeOnlineIfOffline = `-- name: MarkAgentRuntimeOnlineIfOffline :execrows+UPDATE agent_runtime+SET status = 'online', last_seen_at = now(), updated_at = now()+WHERE id = $1 AND status <> 'online'+`++// Reports whether this heartbeat performed an offline -> online transition.+// The conditional update prevents concurrent stale heartbeat snapshots from+// publishing duplicate lifecycle refresh events after another beat already+// recovered the runtime.+func (q *Queries) MarkAgentRuntimeOnlineIfOffline(ctx context.Context, id pgtype.UUID) (int64, error) {+ result, err := q.db.Exec(ctx, markAgentRuntimeOnlineIfOffline, id)+ if err != nil {+ return 0, err+ }+ return result.RowsAffected(), nil+}+const markRuntimesOfflineByIDs = `-- name: MarkRuntimesOfflineByIDs :manyUPDATE agent_runtimeSET status = 'offline', updated_at = now()diff --git a/server/pkg/db/queries/runtime.sql b/server/pkg/db/queries/runtime.sqlindex e404d8a5b2..5d7ff96612 100644--- a/server/pkg/db/queries/runtime.sql+++ b/server/pkg/db/queries/runtime.sql@@ -216,6 +216,15 @@ SET status = 'online', last_seen_at = now(), updated_at = now()WHERE id = $1RETURNING *;+-- name: MarkAgentRuntimeOnlineIfOffline :execrows+-- Reports whether this heartbeat performed an offline -> online transition.+-- The conditional update prevents concurrent stale heartbeat snapshots from+-- publishing duplicate lifecycle refresh events after another beat already+-- recovered the runtime.+UPDATE agent_runtime+SET status = 'online', last_seen_at = now(), updated_at = now()+WHERE id = $1 AND status <> 'online';+-- name: SetAgentRuntimeOffline :execUPDATE agent_runtimeSET status = 'offline', updated_at = now()