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
Surface Assistant idle progress on SSE streams
rcourtman42f4a7028d8c
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex a84d2a5661..97da38e5ca 100644--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md@@ -1652,6 +1652,10 @@ execution mode is AI/API-owned. Request-scoped `AutonomousMode:false` and`RequireCommandApproval:true` on `/api/ai/investigate-alert` are Assistantaction-governance facts, not agent install readiness, command reachability, orfleet-control capability signals.+Visible `stream_idle` workflow progress on that same legacy Assistant SSE+route, and on `/api/ai/execute/stream`, is likewise Assistant/API transport+liveness only. It must not be reused as agent heartbeat, enrollment progress,+installer status, command websocket liveness, or fleet freshness evidence.Patrol finding chat handoffs follow the same ownership split: when`/api/ai/chat` resolves a `finding_id` into model-only Patrol briefing,resource, or action context, the backend-enforced `autonomous_mode:false`diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.mdindex 5869823273..8dea0c2fde 100644--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md@@ -301,6 +301,10 @@ runtime cost control, and shared AI transport surfaces.reaches the browser for the governed idle interval while execution is stillrequest-bound, the handler must emit a neutral `workflow_state` with phase`stream_idle` rather than relying only on hidden SSE comment heartbeats.+ Legacy Assistant SSE routes that still use the older execute event envelope,+ including `/api/ai/execute/stream` and `/api/ai/investigate-alert`, share+ the same transport-liveness obligation while preserving their existing+ response payload shapes.Comment heartbeats and visible events must share a serialized writer so aprogress tick cannot interleave bytes with a provider/tool event. This is atransport liveness signal only; it must replace the active workflow status,diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.mdindex 0d14f2ece3..219c0e6e1c 100644--- a/docs/release-control/v6/internal/subsystems/api-contracts.md+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md@@ -547,6 +547,14 @@ payload shape change when the portal presents compact client rows.prove the visible stream contract, while tests may disable that pace to keepbackend proof fast.34. `internal/api/ai_handlers.go` shared with `ai-runtime`: AI settings and remediation handlers are both an AI runtime control surface and a canonical API payload contract boundary.+ Legacy Assistant SSE routes in this handler that still use the older+ execute envelope, including `/api/ai/execute/stream` and+ `/api/ai/investigate-alert`, must preserve their existing top-level+ `complete` payload shape while sharing the governed Assistant transport+ liveness contract: visible neutral `workflow_state` events with phase+ `stream_idle` during silent intervals, hidden SSE comments only as+ keepalives, serialized heartbeat/event writes, and no idle progress after+ terminal `complete`/`error`/`done`.Provider test responses from `/api/ai/test` and provider-specific`/api/ai/test/{provider}` preflight responses must return one safestructured diagnostic envelope: `success`, `message`, optional `model`,diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex beb2788ba2..d1ff891d6b 100644--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md@@ -571,6 +571,11 @@ recovery scope, or a storage/recovery-owned secret source.`RequireCommandApproval:true` are AI action-governance constraints, notstorage/recovery restore approval, recovery freshness, or storage diagnosticpayload semantics.+ Visible `stream_idle` workflow progress on legacy Assistant SSE routes in+ `internal/api/ai_handlers.go`, including direct execute and alert+ investigation streams, is likewise Assistant/API transport liveness only,+ not recovery acquisition progress, backup task freshness, restore readiness,+ provider health, or storage/recovery job status.Patrol finding chat handoff execution controls in `internal/api/ai_handler.go`follow the same boundary: backend-forced `autonomous_mode:false` for`finding_id` handoffs with model-only Patrol briefing, resource, or actiondiff --git a/internal/api/ai_handlers.go b/internal/api/ai_handlers.goindex 86de59ce23..3ead012ba1 100644--- a/internal/api/ai_handlers.go+++ b/internal/api/ai_handlers.go@@ -3388,6 +3388,184 @@ func (e aiExecuteStreamCompleteEvent) NormalizeCollections() aiExecuteStreamCompreturn e}+type legacyAssistantSSEWriter struct {+ w http.ResponseWriter+ flusher http.Flusher+ rc *http.ResponseController+ cancel context.CancelFunc+ cancelOnDisconnect bool+ writeMu sync.Mutex+ clientDisconnected atomic.Bool+ lastClientEventUnixMS atomic.Int64+ terminalEventsStarted atomic.Bool+ heartbeatDone chan struct{}+ heartbeatDoneClosed atomic.Bool+ executionDone chan struct{}+ executionDoneClosed atomic.Bool+}++func newLegacyAssistantSSEWriter(w http.ResponseWriter, flusher http.Flusher, rc *http.ResponseController, cancel context.CancelFunc, cancelOnDisconnect bool) *legacyAssistantSSEWriter {+ writer := &legacyAssistantSSEWriter{+ w: w,+ flusher: flusher,+ rc: rc,+ cancel: cancel,+ cancelOnDisconnect: cancelOnDisconnect,+ heartbeatDone: make(chan struct{}),+ executionDone: make(chan struct{}),+ }+ writer.lastClientEventUnixMS.Store(time.Now().UnixMilli())+ return writer+}++func (s *legacyAssistantSSEWriter) start(ctx context.Context) {+ s.startHeartbeat(ctx)+ s.startIdleProgress(ctx)+}++func (s *legacyAssistantSSEWriter) stop() {+ s.closeHeartbeat()+ s.finishExecution()+}++func (s *legacyAssistantSSEWriter) closeHeartbeat() {+ if s.heartbeatDoneClosed.CompareAndSwap(false, true) {+ close(s.heartbeatDone)+ }+}++func (s *legacyAssistantSSEWriter) finishExecution() {+ if s.executionDoneClosed.CompareAndSwap(false, true) {+ close(s.executionDone)+ }+}++func (s *legacyAssistantSSEWriter) disconnected() bool {+ return s.clientDisconnected.Load()+}++func (s *legacyAssistantSSEWriter) startHeartbeat(ctx context.Context) {+ go func() {+ ticker := time.NewTicker(5 * time.Second)+ defer ticker.Stop()+ for {+ select {+ case <-ctx.Done():+ return+ case <-ticker.C:+ s.writeMu.Lock()+ if s.clientDisconnected.Load() {+ s.writeMu.Unlock()+ return+ }+ _ = s.rc.SetWriteDeadline(time.Now().Add(10 * time.Second))+ _, err := s.w.Write([]byte(": heartbeat\n\n"))+ if err != nil {+ s.writeMu.Unlock()+ s.markDisconnected()+ return+ }+ s.flusher.Flush()+ s.writeMu.Unlock()+ log.Debug().Msg("Sent SSE heartbeat")+ case <-s.heartbeatDone:+ return+ }+ }+ }()+}++func (s *legacyAssistantSSEWriter) startIdleProgress(ctx context.Context) {+ if chatStreamIdleProgressInterval <= 0 {+ return+ }++ go func() {+ ticker := time.NewTicker(chatStreamIdleProgressInterval)+ defer ticker.Stop()+ for {+ select {+ case <-ctx.Done():+ return+ case <-s.heartbeatDone:+ return+ case <-s.executionDone:+ return+ case <-ticker.C:+ if s.clientDisconnected.Load() {+ return+ }+ if s.terminalEventsStarted.Load() || s.executionDoneClosed.Load() {+ return+ }+ lastEventAt := time.UnixMilli(s.lastClientEventUnixMS.Load())+ if time.Since(lastEventAt) < chatStreamIdleProgressInterval {+ continue+ }+ progressEvent := ai.StreamEvent{+ Type: "workflow_state",+ Data: chat.WorkflowStateData{+ Phase: "stream_idle",+ Message: chatStreamIdleProgressMessage,+ },+ }+ s.writePayloadIf(progressEvent, true, func() bool {+ return !s.terminalEventsStarted.Load() && !s.executionDoneClosed.Load()+ })+ }+ }+ }()+}++func (s *legacyAssistantSSEWriter) markDisconnected() {+ s.clientDisconnected.Store(true)+ if s.cancelOnDisconnect && s.cancel != nil {+ s.cancel()+ }+}++func (s *legacyAssistantSSEWriter) writePayload(payload interface{}) bool {+ return s.writePayloadIf(payload, true, nil)+}++func (s *legacyAssistantSSEWriter) writeTerminalPayload(payload interface{}) bool {+ s.terminalEventsStarted.Store(true)+ s.finishExecution()+ return s.writePayloadIf(payload, true, nil)+}++func (s *legacyAssistantSSEWriter) writePayloadIf(payload interface{}, visible bool, shouldWrite func() bool) bool {+ if s.clientDisconnected.Load() {+ return false+ }+ data, err := json.Marshal(payload)+ if err != nil {+ log.Error().Err(err).Msg("Failed to marshal SSE event")+ return false+ }++ s.writeMu.Lock()+ defer s.writeMu.Unlock()+ if s.clientDisconnected.Load() {+ return false+ }+ if shouldWrite != nil && !shouldWrite() {+ return false+ }+ _ = s.rc.SetWriteDeadline(time.Now().Add(10 * time.Second))+ _, err = s.w.Write([]byte("data: " + string(data) + "\n\n"))+ if err != nil {+ log.Debug().Err(err).Msg("Failed to write SSE event (client may have disconnected)")+ s.markDisconnected()+ return false+ }+ s.flusher.Flush()+ if visible {+ s.lastClientEventUnixMS.Store(time.Now().UnixMilli())+ }+ return true+}+type AIKubernetesAnalyzeRequest struct {ClusterID string `json:"cluster_id"`}@@ -3682,52 +3860,12 @@ func (h *AISettingsHandler) HandleExecuteStream(w http.ResponseWriter, r *http.Rctx, cancel := context.WithTimeout(context.Background(), 900*time.Second)defer cancel()- // Set up heartbeat to keep connection alive during long tool executions- // NOTE: We don't check r.Context().Done() because Vite proxy may close- // the request context prematurely. We detect real disconnection via write failures.- heartbeatDone := make(chan struct{})- var clientDisconnected atomic.Bool- go func() {- ticker := time.NewTicker(5 * time.Second)- defer ticker.Stop()- for {- select {- case <-ticker.C:- // Extend write deadline before heartbeat- _ = rc.SetWriteDeadline(time.Now().Add(10 * time.Second))- // Send SSE comment as heartbeat- _, err := w.Write([]byte(": heartbeat\n\n"))- if err != nil {- log.Debug().Err(err).Msg("Heartbeat write failed, stopping heartbeat (AI continues)")- clientDisconnected.Store(true)- // Don't cancel the AI request - let it complete with its own timeout- // The SSE connection may have issues but the AI work can still finish- return- }- flusher.Flush()- log.Debug().Msg("Sent SSE heartbeat")- case <-heartbeatDone:- return- }- }- }()- defer close(heartbeatDone)-- // Helper to safely write SSE events, tracking if client disconnected- safeWrite := func(data []byte) bool {- if clientDisconnected.Load() {- return false- }- _ = rc.SetWriteDeadline(time.Now().Add(10 * time.Second))- _, err := w.Write(data)- if err != nil {- log.Debug().Err(err).Msg("Failed to write SSE event (client may have disconnected)")- clientDisconnected.Store(true)- return false- }- flusher.Flush()- return true- }+ // Keep the historical background execution behavior for this legacy route,+ // but expose transport progress through the same visible idle event contract+ // as /api/ai/chat.+ streamWriter := newLegacyAssistantSSEWriter(w, flusher, rc, cancel, false)+ streamWriter.start(ctx)+ defer streamWriter.stop()// Stream callback - write SSE eventscallback := func(event ai.StreamEvent) {@@ -3738,18 +3876,15 @@ func (h *AISettingsHandler) HandleExecuteStream(w http.ResponseWriter, r *http.Rreturn}- data, err := json.Marshal(event)- if err != nil {- log.Error().Err(err).Msg("Failed to marshal stream event")- return- }-log.Debug().Str("event_type", event.Type).Msg("Streaming AI event")- // SSE format: data: <json>\n\n- safeWrite([]byte("data: " + string(data) + "\n\n"))+ if event.Type == "error" {+ streamWriter.writeTerminalPayload(event)+ return+ }+ streamWriter.writePayload(event)}// Convert history from API type to service type@@ -3767,10 +3902,9 @@ func (h *AISettingsHandler) HandleExecuteStream(w http.ResponseWriter, r *http.R// Ensure we always send a final 'done' eventdefer func() {- if !clientDisconnected.Load() {+ if !streamWriter.disconnected() {doneEvent := ai.StreamEvent{Type: "done"}- data, _ := json.Marshal(doneEvent)- safeWrite([]byte("data: " + string(data) + "\n\n"))+ streamWriter.writeTerminalPayload(doneEvent)log.Debug().Msg("Sent final 'done' event")}}()@@ -3791,8 +3925,7 @@ func (h *AISettingsHandler) HandleExecuteStream(w http.ResponseWriter, r *http.Rlog.Error().Err(err).Msg("AI streaming execution failed")// Send error event — use generic message to avoid leaking internal detailserrEvent := ai.StreamEvent{Type: "error", Data: map[string]string{"message": "AI request failed. Please try again."}}- data, _ := json.Marshal(errEvent)- safeWrite([]byte("data: " + string(data) + "\n\n"))+ streamWriter.writeTerminalPayload(errEvent)return}@@ -3811,8 +3944,7 @@ func (h *AISettingsHandler) HandleExecuteStream(w http.ResponseWriter, r *http.ROutputTokens: resp.OutputTokens,ToolCalls: resp.ToolCalls,}.NormalizeCollections()- data, _ := json.Marshal(finalEvent)- safeWrite([]byte("data: " + string(data) + "\n\n"))+ streamWriter.writeTerminalPayload(finalEvent)// 'done' event is sent by the defer above}@@ -4533,61 +4665,27 @@ func (h *AISettingsHandler) HandleInvestigateAlert(w http.ResponseWriter, r *httctx, cancel := context.WithTimeout(context.Background(), 300*time.Second)defer cancel()- // Heartbeat routine- heartbeatDone := make(chan struct{})- var clientDisconnected atomic.Bool- go func() {- ticker := time.NewTicker(5 * time.Second)- defer ticker.Stop()- for {- select {- case <-ticker.C:- _ = rc.SetWriteDeadline(time.Now().Add(10 * time.Second))- _, err := w.Write([]byte(": heartbeat\n\n"))- if err != nil {- clientDisconnected.Store(true)- return- }- flusher.Flush()- case <-heartbeatDone:- return- }- }- }()- defer close(heartbeatDone)-- safeWrite := func(data []byte) bool {- if clientDisconnected.Load() {- return false- }- _ = rc.SetWriteDeadline(time.Now().Add(10 * time.Second))- _, err := w.Write(data)- if err != nil {- clientDisconnected.Store(true)- return false- }- flusher.Flush()- return true- }+ streamWriter := newLegacyAssistantSSEWriter(w, flusher, rc, cancel, false)+ streamWriter.start(ctx)+ defer streamWriter.stop()// Stream callbackcallback := func(event ai.StreamEvent) {if event.Type == "done" {return}- data, err := json.Marshal(event)- if err != nil {+ if event.Type == "error" {+ streamWriter.writeTerminalPayload(event)return}- safeWrite([]byte("data: " + string(data) + "\n\n"))+ streamWriter.writePayload(event)}// Execute with streamingdefer func() {- if !clientDisconnected.Load() {+ if !streamWriter.disconnected() {doneEvent := ai.StreamEvent{Type: "done"}- data, _ := json.Marshal(doneEvent)- safeWrite([]byte("data: " + string(data) + "\n\n"))+ streamWriter.writeTerminalPayload(doneEvent)}}()@@ -4611,8 +4709,7 @@ func (h *AISettingsHandler) HandleInvestigateAlert(w http.ResponseWriter, r *httif err != nil {log.Error().Err(err).Msg("AI alert investigation failed")errEvent := ai.StreamEvent{Type: "error", Data: map[string]string{"message": "Alert investigation failed. Please try again."}}- data, _ := json.Marshal(errEvent)- safeWrite([]byte("data: " + string(data) + "\n\n"))+ streamWriter.writeTerminalPayload(errEvent)return}@@ -4624,8 +4721,7 @@ func (h *AISettingsHandler) HandleInvestigateAlert(w http.ResponseWriter, r *httOutputTokens: resp.OutputTokens,ToolCalls: resp.ToolCalls,}.NormalizeCollections()- data, _ := json.Marshal(finalEvent)- safeWrite([]byte("data: " + string(data) + "\n\n"))+ streamWriter.writeTerminalPayload(finalEvent)if alertIdentifier != "" {h.GetAIService(r.Context()).RecordIncidentAnalysis(alertIdentifier, "Pulse Assistant alert investigation completed", map[string]interface{}{diff --git a/internal/api/ai_handlers_stream_test.go b/internal/api/ai_handlers_stream_test.goindex 6de0a8b3ee..d6a18eb91f 100644--- a/internal/api/ai_handlers_stream_test.go+++ b/internal/api/ai_handlers_stream_test.go@@ -5,6 +5,7 @@ import ("encoding/json""strings""testing"+ "time""net/http""net/http/httptest"@@ -42,6 +43,40 @@ func newTestAISettingsHandlerWithService(t *testing.T) *AISettingsHandler {return handler}+func withLegacyAssistantStreamIdleInterval(t *testing.T, interval time.Duration) {+ t.Helper()+ previous := chatStreamIdleProgressInterval+ chatStreamIdleProgressInterval = interval+ t.Cleanup(func() {+ chatStreamIdleProgressInterval = previous+ })+}++func assertLegacyAssistantStreamIdleBeforeTerminal(t *testing.T, response string) {+ t.Helper()+ idleIndex := strings.Index(response, `"phase":"stream_idle"`)+ completeIndex := strings.Index(response, `"type":"complete"`)+ doneIndex := strings.LastIndex(response, `"type":"done"`)+ if idleIndex < 0 {+ t.Fatalf("response missing idle progress event: %s", response)+ }+ if !strings.Contains(response, chatStreamIdleProgressMessage) {+ t.Fatalf("response missing idle progress message: %s", response)+ }+ if completeIndex < 0 {+ t.Fatalf("response missing complete event: %s", response)+ }+ if doneIndex < 0 {+ t.Fatalf("response missing done event: %s", response)+ }+ if idleIndex > completeIndex {+ t.Fatalf("idle progress appeared after complete event: %s", response)+ }+ if idleIndex > doneIndex {+ t.Fatalf("idle progress appeared after done event: %s", response)+ }+}+func TestHandleExecuteStream_LicenseRequired(t *testing.T) {setMockModeForTest(t, true)@@ -97,6 +132,40 @@ func TestHandleExecuteStream_Success(t *testing.T) {}}+func TestHandleExecuteStream_EmitsIdleProgressWhileServiceIsSilent(t *testing.T) {+ setMockModeForTest(t, true)+ withLegacyAssistantStreamIdleInterval(t, 2*time.Millisecond)++ handler := newTestAISettingsHandlerWithService(t)++ body := `{"prompt":"disk usage"}`+ req := httptest.NewRequest(http.MethodPost, "/api/ai/execute/stream", strings.NewReader(body))+ rec := httptest.NewRecorder()+ handler.HandleExecuteStream(rec, req)++ if rec.Code != http.StatusOK {+ t.Fatalf("expected OK, got %d", rec.Code)+ }+ assertLegacyAssistantStreamIdleBeforeTerminal(t, rec.Body.String())+}++func TestHandleInvestigateAlert_EmitsIdleProgressWhileServiceIsSilent(t *testing.T) {+ setMockModeForTest(t, true)+ withLegacyAssistantStreamIdleInterval(t, 2*time.Millisecond)++ handler := newTestAISettingsHandlerWithService(t)++ body := `{"alertIdentifier":"alert-1","resource_id":"node-1","resource_name":"node-1","resource_type":"agent","alert_type":"cpu","level":"warning","message":"high cpu"}`+ req := newLoopbackRequest(http.MethodPost, "/api/ai/investigate-alert", strings.NewReader(body))+ rec := httptest.NewRecorder()+ handler.HandleInvestigateAlert(rec, req)++ if rec.Code != http.StatusOK {+ t.Fatalf("expected OK, got %d: %s", rec.Code, rec.Body.String())+ }+ assertLegacyAssistantStreamIdleBeforeTerminal(t, rec.Body.String())+}+func TestAIExecuteStreamCompleteEvent_UsesCanonicalEmptyCollections(t *testing.T) {payload, err := json.Marshal(emptyAIExecuteStreamCompleteEvent())if err != nil {diff --git a/internal/api/ai_handlers_test.go b/internal/api/ai_handlers_test.goindex 6800fed2b4..c6fb6c6da4 100644--- a/internal/api/ai_handlers_test.go+++ b/internal/api/ai_handlers_test.go@@ -2727,6 +2727,21 @@ func TestHandleInvestigateAlert_ForcesApprovalBoundExecuteRequest(t *testing.T)require.Contains(t, text, "RequireCommandApproval: true")}+func TestHandleInvestigateAlert_UsesVisibleIdleProgressStream(t *testing.T) {+ setMockModeForTest(t, true)+ withLegacyAssistantStreamIdleInterval(t, 2*time.Millisecond)++ handler := newTestAISettingsHandlerWithService(t)++ body := []byte(`{"alertIdentifier":"alert-1","resource_id":"node-1","resource_name":"node-1","resource_type":"agent","alert_type":"cpu","level":"warning","message":"high cpu"}`)+ req := newLoopbackRequest(http.MethodPost, "/api/ai/investigate-alert", bytes.NewReader(body))+ rec := httptest.NewRecorder()+ handler.HandleInvestigateAlert(rec, req)++ require.Equal(t, http.StatusOK, rec.Code, rec.Body.String())+ assertLegacyAssistantStreamIdleBeforeTerminal(t, rec.Body.String())+}+// ========================================// AISettingsHandler setter method tests// ========================================diff --git a/internal/api/contract_test.go b/internal/api/contract_test.goindex c2270e28ff..372c4034b3 100644--- a/internal/api/contract_test.go+++ b/internal/api/contract_test.go@@ -10772,6 +10772,22 @@ func TestContract_ChatStreamEventJSONSnapshots(t *testing.T) {}}+func TestContract_LegacyAssistantStreamIdleEventJSONSnapshot(t *testing.T) {+ event := ai.StreamEvent{+ Type: "workflow_state",+ Data: chat.WorkflowStateData{+ Phase: "stream_idle",+ Message: chatStreamIdleProgressMessage,+ },+ }+ got, err := json.Marshal(event)+ if err != nil {+ t.Fatalf("marshal legacy Assistant stream event: %v", err)+ }++ assertJSONSnapshot(t, got, `{"type":"workflow_state","data":{"phase":"stream_idle","message":"Assistant is still working; waiting for the next stream event."}}`)+}+func TestContract_AssistantChatStreamUsesClientSafeProjection(t *testing.T) {handlerSource, err := os.ReadFile(filepath.Clean("ai_handler.go"))if err != nil {