Real-time monitoring dashboard for Proxmox VE, PBS, Docker, Kubernetes, TrueNAS and vSphere. Self-hosted, with alerts for failed backups, full disks, unhealthy containers and offline nodes.
Go aialertsdashboarddockerdocker-monitoringgohomelabinfrastructure-monitoringkubernetesmonitoringmspproxmoxproxmox-backup-serverproxmox-mail-gatewayproxmox-veself-hostedtruenastypescriptvspherewebhooks
Keep agent heartbeats stream local
rcourtmanc6d5c4590a6c
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex 97024ffc6f..84b18dcbaa 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -946,10 +946,13 @@ prefixes preserved verbatim; successful dispatches carry abroker's read-after-write probe — so agents close the"did it actually work?" loop without polling /api/actions/{id}),and a 15-second heartbeat keepalive.-The broadcaster drops events for slow subscribers rather than-blocking publishers, so the patrol-finding runtime, the approval-store's post-create callback, and the executor's post-completion-callback can publish without ever stalling on consumer slowness.+The broadcaster drops real published events for slow subscribers+rather than blocking publishers, so the patrol-finding runtime, the+approval store's post-create callback, and the executor's+post-completion callback can publish without ever stalling on+consumer slowness. Heartbeats are stream-local keepalives written+to each connected response; one subscriber's heartbeat ticker must+not publish heartbeat events to every other subscriber.The agent runtime keeps the broadcaster wired across restarts, andthe capabilities manifest declares the stream under`subscribe_events` so the surface stays self-describing.diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex 69e6fc1676..ec80441dda 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -1388,14 +1388,17 @@ raw action and verification commands follow the same `ai:execute`redaction rule on the stream;refused dispatches omit `verification` because the probe neverruns) — and `heartbeat` every 15 seconds so an idle connection-can confirm the stream is alive. Each event carries a monotonic ID so agents-can dedupe and reason about ordering. The broadcaster drops events-for slow subscribers rather than blocking the publish path —-publishers (the patrol findings runtime, the approval store's-post-create callback, the executor's post-completion callback)-cannot stall on consumer slowness. The stream sits behind-`monitoring:read` and runs through the same auth path as the rest-of the agent surface; the capabilities manifest declares the stream+can confirm the stream is alive. Each event carries a monotonic ID+so agents can dedupe and reason about ordering. Heartbeats are+stream-local keepalives written directly to the connected response,+not global broadcaster publishes, so concurrent subscribers do not+multiply heartbeat fan-out for one another. The broadcaster drops+real published events for slow subscribers rather than blocking the+publish path — publishers (the patrol findings runtime, the+approval store's post-create callback, the executor's+post-completion callback) cannot stall on consumer slowness. The+stream sits behind `monitoring:read` and runs through the same auth+path as the rest of the agent surface; the capabilities manifest declares the streamunder `subscribe_events` so external agents discover it withoutout-of-band documentation.diff --git a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md b/docs/release-control/v6/internal/subsystems/performance-and-scalability.mdindex ea540790db..6a0edf946a 100644--- a/docs/release-control/v6/internal/subsystems/performance-and-scalability.md+++ b/docs/release-control/v6/internal/subsystems/performance-and-scalability.md@@ -529,7 +529,10 @@ callback on its own goroutine after the approval is persisted, andpost-completion callback on its own goroutine after the auditrecord is persisted. Goroutine dispatch keeps the approval anddispatch hot paths independent of consumer drain rate; per-event-cost is one channel send per subscriber.+cost is one channel send per subscriber. Heartbeats are the+exception: each SSE handler writes its own keepalive directly to+its response, so concurrent subscribers do not turn one+connection's heartbeat ticker into a global N-subscriber fan-out.The `action.completed` payload's `verification` block is a smallfixed-shape projection (5 fields, no embedded output) so addingdiff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex 6bacf2ec00..3a2fc20b53 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -970,7 +970,9 @@ list) for replay — those are the durable surfaces. Thecanonical record (approval row or action-audit row) has alreadybeen persisted, so a missed event is recoverable by reading thebacking endpoint; the stream is a doorbell for recent activity,-not the source of truth. The verification projection on+not the source of truth. Heartbeat events are stream-local+keepalives and do not create recovery records, action-audit rows,+or storage/recovery freshness evidence. The verification projection on`action.completed` reads from the same persisted`ActionAuditRecord.Result.Verification` field that agents wouldrecover from /api/actions/{id} after a reconnect — the eventdiff --git a/internal/api/agent_capabilities.go b/internal/api/agent_capabilities.goindex 78f14aedce..cc6c82c2be 100644--- a/internal/api/agent_capabilities.go+++ b/internal/api/agent_capabilities.go@@ -141,7 +141,7 @@ var agentCapabilitiesManifest = AgentCapabilitiesManifest{},{Name: "subscribe_events",- Description: "Subscribe to the SSE event stream for real-time notifications: finding.created when a new finding is raised, approval.pending when a remediation request enters StatusPending and waits on operator decision, action.completed when an action audit reaches a terminal state (Completed or Failed, including refused-before-dispatch failures with stable error-token prefixes; carries a verification block with the read-after-write probe outcome so agents close the certainty loop without polling /api/actions/{id}), heartbeat every 15s. Command fields are redacted for monitoring-read API tokens unless the token also has ai:execute. Long-lived connection; agents listen instead of polling.",+ Description: "Subscribe to the SSE event stream for real-time notifications: finding.created when a new finding is raised, approval.pending when a remediation request enters StatusPending and waits on operator decision, action.completed when an action audit reaches a terminal state (Completed or Failed, including refused-before-dispatch failures with stable error-token prefixes; carries a verification block with the read-after-write probe outcome so agents close the certainty loop without polling /api/actions/{id}), stream-local heartbeat every 15s. Command fields are redacted for monitoring-read API tokens unless the token also has ai:execute. Long-lived connection; agents listen instead of polling.",Category: "context",Method: http.MethodGet,Path: "/api/agent/events",diff --git a/internal/api/agent_events.go b/internal/api/agent_events.goindex 7ff58d5838..9a6a3593c6 100644--- a/internal/api/agent_events.go+++ b/internal/api/agent_events.go@@ -135,11 +135,12 @@ type AgentEventActionCompletedPayload struct {// fills, the broadcaster drops events for that subscriber rather// than blocking the global publish path.type AgentEventBroadcaster struct {- mu sync.RWMutex- subscribers map[uint64]chan AgentEvent- nextSubID uint64- nextEventID uint64- bufSize int+ mu sync.RWMutex+ subscribers map[uint64]chan AgentEvent+ nextSubID uint64+ nextEventID uint64+ bufSize int+ heartbeatInterval time.Duration}// NewAgentEventBroadcaster creates a broadcaster with a per-subscriber@@ -149,8 +150,9 @@ type AgentEventBroadcaster struct {// per subscriber.func NewAgentEventBroadcaster() *AgentEventBroadcaster {return &AgentEventBroadcaster{- subscribers: make(map[uint64]chan AgentEvent),- bufSize: 64,+ subscribers: make(map[uint64]chan AgentEvent),+ bufSize: 64,+ heartbeatInterval: 15 * time.Second,}}@@ -185,10 +187,7 @@ func (b *AgentEventBroadcaster) Subscribe() (<-chan AgentEvent, func()) {// path — agents that need replay must use a different mechanism// (none currently exposed; future event log can layer on top).func (b *AgentEventBroadcaster) Publish(event AgentEvent) {- if event.At.IsZero() {- event.At = time.Now().UTC()- }- event.ID = atomic.AddUint64(&b.nextEventID, 1)+ event = b.stampEvent(event)b.mu.RLock()defer b.mu.RUnlock()@@ -208,6 +207,21 @@ func (b *AgentEventBroadcaster) Publish(event AgentEvent) {}}+func (b *AgentEventBroadcaster) stampEvent(event AgentEvent) AgentEvent {+ if event.At.IsZero() {+ event.At = time.Now().UTC()+ }+ event.ID = atomic.AddUint64(&b.nextEventID, 1)+ return event+}++func (b *AgentEventBroadcaster) currentHeartbeatInterval() time.Duration {+ if b.heartbeatInterval <= 0 {+ return 15 * time.Second+ }+ return b.heartbeatInterval+}+// SubscriberCount returns the number of current subscribers. Used by// tests; not exposed on the wire.func (b *AgentEventBroadcaster) SubscriberCount() int {@@ -258,7 +272,7 @@ func (b *AgentEventBroadcaster) HandleAgentEvents(w http.ResponseWriter, r *http})flusher.Flush()- heartbeat := time.NewTicker(15 * time.Second)+ heartbeat := time.NewTicker(b.currentHeartbeatInterval())defer heartbeat.Stop()for {@@ -272,7 +286,8 @@ func (b *AgentEventBroadcaster) HandleAgentEvents(w http.ResponseWriter, r *httpwriteAgentSSEEvent(w, redactAgentEventCommandsForRequest(event, r))flusher.Flush()case <-heartbeat.C:- b.Publish(AgentEvent{Kind: AgentEventHeartbeat})+ writeAgentSSEEvent(w, b.stampEvent(AgentEvent{Kind: AgentEventHeartbeat}))+ flusher.Flush()}}}diff --git a/internal/api/agent_events_test.go b/internal/api/agent_events_test.goindex 5a0bad18cd..ac255bb5a0 100644--- a/internal/api/agent_events_test.go+++ b/internal/api/agent_events_test.go@@ -229,6 +229,70 @@ func TestHandleAgentEvents_StreamsConnectedAndPublishedEvents(t *testing.T) {}}+func TestHandleAgentEvents_HeartbeatsAreStreamLocal(t *testing.T) {+ b := NewAgentEventBroadcaster()+ b.heartbeatInterval = 20 * time.Millisecond++ otherEvents, unsubscribe := b.Subscribe()+ defer unsubscribe()++ server := httptest.NewServer(http.HandlerFunc(b.HandleAgentEvents))+ defer server.Close()++ ctx, cancel := context.WithCancel(context.Background())+ defer cancel()++ req, err := http.NewRequestWithContext(ctx, http.MethodGet, server.URL, nil)+ if err != nil {+ t.Fatalf("NewRequestWithContext: %v", err)+ }+ resp, err := http.DefaultClient.Do(req)+ if err != nil {+ t.Fatalf("Do: %v", err)+ }+ defer resp.Body.Close()++ deadline := time.Now().Add(time.Second)+ for time.Now().Before(deadline) && b.SubscriberCount() < 2 {+ time.Sleep(5 * time.Millisecond)+ }+ if b.SubscriberCount() < 2 {+ t.Fatalf("subscriber count = %d; want at least 2", b.SubscriberCount())+ }++ heartbeatSeen := make(chan string, 1)+ go func() {+ scanner := bufio.NewScanner(resp.Body)+ var collected strings.Builder+ for scanner.Scan() {+ line := scanner.Text()+ collected.WriteString(line)+ collected.WriteString("\n")+ if strings.Contains(line, "\"kind\":\"heartbeat\"") {+ heartbeatSeen <- collected.String()+ return+ }+ }+ }()++ select {+ case payload := <-heartbeatSeen:+ if !strings.Contains(payload, "event: heartbeat") {+ t.Fatalf("heartbeat must be serialized as an SSE event; payload=%s", payload)+ }+ case <-time.After(time.Second):+ t.Fatal("timed out waiting for stream-local heartbeat")+ }++ select {+ case event := <-otherEvents:+ t.Fatalf("stream-local heartbeat leaked to another subscriber: %+v", event)+ case <-time.After(3 * b.heartbeatInterval):+ // Pass: the direct subscriber did not receive the handler's+ // heartbeat. Real events still fan out through Publish.+ }+}+// nonFlushingResponseWriter is a ResponseWriter that explicitly does// NOT implement http.Flusher, so we can verify the SSE handler// degrades cleanly on writers that can't stream. Standarddiff --git a/internal/api/contract_test.go b/internal/api/contract_test.goindex 55f4da9a1e..0dea2ff110 100644--- a/internal/api/contract_test.go+++ b/internal/api/contract_test.go@@ -13440,6 +13440,26 @@ func TestContract_SubscribeEventsCapabilityListsApprovalPending(t *testing.T) {}}+// TestContract_AgentEventsHeartbeatIsStreamLocal pins that+// heartbeat keepalives are written to the connected SSE response+// rather than published through the broadcaster. Heartbeats are+// connection health signals, not product events; publishing them+// globally makes N subscribers create N heartbeat events that fan+// out to every other subscriber.+func TestContract_AgentEventsHeartbeatIsStreamLocal(t *testing.T) {+ source, err := os.ReadFile("agent_events.go")+ if err != nil {+ t.Fatalf("read agent_events.go: %v", err)+ }+ src := string(source)+ if !strings.Contains(src, "writeAgentSSEEvent(w, b.stampEvent(AgentEvent{Kind: AgentEventHeartbeat}))") {+ t.Error("HandleAgentEvents must write heartbeat events directly to the connected response")+ }+ if strings.Contains(src, "case <-heartbeat.C:\n\t\t\tb.Publish(AgentEvent{Kind: AgentEventHeartbeat})") {+ t.Error("HandleAgentEvents must not publish heartbeat events through the broadcaster")+ }+}+// TestContract_AgentEventsStreamPublishesOnActionCompleted pins the// agent SSE stream's third producer hook: the executor's// post-completion callback must publish action.completed events for