Skip to content

armgit / Pulse

Public Imported from GitHub
0

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.

Add Assistant stream idle progress

rcourtmane4ac09287676
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index e8984cceaa..aa2482e6ef 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -691,6 +691,12 @@ profile and assignment columns, but embedded table framing must route through
5. Keep release-grade updater trust fail-closed across `internal/agentupdate/`, `internal/dockeragent/`, and the shared `internal/api/unified_agent.go` download helpers. When release builds embed trusted update signing keys, published agent binaries and installer assets must carry detached `.sig` plus `.sshsig` sidecars; updater/runtime paths must require `X-Signature-Ed25519` in addition to `X-Checksum-Sha256`, and installer-owned download flows must require the matching base64-encoded `X-Signature-SSHSIG`, instead of silently downgrading to checksum-only trust.
6. Keep shared `internal/api/` helper edits isolated from agent lifecycle semantics: Patrol-specific status transport or alert-trigger wiring changes in shared handlers must not bleed into auto-register, installer, or fleet-control behavior unless this contract moves in the same slice.
The same isolation rule applies to AI settings payload work in `internal/api/ai_handlers.go`: provider auth fields, masked-secret echoes, and provider-test model selection remain AI/runtime plus API-contract ownership and must not be reinterpreted as lifecycle setup or registration semantics just because they share backend helper layers.
+ The same isolation rule applies to Pulse Assistant chat SSE progress in
+ `internal/api/ai_handler.go`: neutral `workflow_state` transport liveness
+ such as `stream_idle`, provider startup, retry, fallback, and model-thinking
+ status remains AI/runtime plus API-contract ownership and must not be
+ reinterpreted as agent enrollment, install progress, command websocket
+ liveness, or fleet-control freshness.
The same isolation rule applies to report branding validation and rendering
request assembly in `internal/api/system_settings.go` and
`internal/api/metrics_reporting_handlers.go`: lifecycle-owned install,
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 8d1104bbae..11ed7b72f0 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -282,6 +282,16 @@ runtime cost control, and shared AI transport surfaces.
turns, and selected-provider startup. These events are runtime progress, not
Assistant-authored analysis, and they must not become keyword routers,
explore pre-passes, or instructions that choose the model's next action.
+ The HTTP chat stream handler also owns visible idle progress for silent
+ intervals after the stream has opened: if no client-visible Assistant event
+ reaches the browser for the governed idle interval while execution is still
+ request-bound, the handler must emit a neutral `workflow_state` with phase
+ `stream_idle` rather than relying only on hidden SSE comment heartbeats.
+ Comment heartbeats and visible events must share a serialized writer so a
+ progress tick cannot interleave bytes with a provider/tool event. This is a
+ transport liveness signal only; it must replace the active workflow status,
+ stop before terminal `done`/`error`, and must not become persisted assistant
+ prose or raw provider reasoning.
The drawer transcript owns detailed in-flight progress for the active turn:
a new assistant row must start with a neutral local preparation status until
stream progress arrives, must show the current effective model route while
@@ -297,6 +307,17 @@ runtime cost control, and shared AI transport surfaces.
so the drawer can show elapsed wait/run time for long provider starts and
tool calls instead of repeating a timeless waiting label.
The referenced OpenCode source at fetched `origin/dev` commit
+ `4519a1da329c1a4fc384054e7203ba7d06928205` mutates typed message parts as
+ events arrive in `packages/opencode/src/cli/cmd/tui/context/sync.tsx`
+ (`message.part.updated` and `message.part.delta`) and represents session
+ activity as separately updated status in
+ `packages/opencode/src/cli/cmd/tui/context/sync-v2.tsx`
+ (`session.next.step.started`, `session.next.text.delta`, and tool state
+ events). Pulse adapts that event-by-event activity model with browser-safe
+ `workflow_state` and typed tool rows, including replacing `stream_idle`
+ status while no provider event has arrived, rather than exposing terminal
+ UI internals or chain-of-thought.
+ The referenced OpenCode source at fetched `origin/dev` commit
`1399323b78a04229d9bfe00c7436d7f41770fda8` applies each typed event to the
active assistant message in
`packages/opencode/src/cli/cmd/tui/context/sync-v2.tsx`; Pulse adapts that
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 8c8caf81d6..eea639b03b 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -521,7 +521,15 @@ payload shape change when the portal presents compact client rows.
separate create-session request. That cold-stream model resolution must use
explicit configured chat routes or stable provider defaults without waiting
on provider model catalogs; `/api/ai/models` and settings responses own
- catalog-backed recommendation, not the first-response chat stream. The generated frontend union, stream parser
+ catalog-backed recommendation, not the first-response chat stream.
+ The same SSE transport must emit neutral `workflow_state` events with
+ phase `stream_idle` during governed silent intervals while request-bound
+ Assistant execution is still in flight. Hidden SSE comment heartbeats are
+ not sufficient user-visible progress. The handler must serialize comment
+ heartbeats and JSON event writes through one writer lock, and the
+ `stream_idle` event must stop before terminal `done`/`error` rather than
+ becoming assistant-authored transcript content.
+ The generated frontend union, stream parser
tests, and backend JSON snapshot proof must stay in lockstep with that payload;
`done.session_id` and `question.session_id` remain compatibility payloads,
not the primary cold-session creation contract. Assistant `done` events
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 86e2df9d16..0b6b77c998 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -554,6 +554,12 @@ recovery scope, or a storage/recovery-owned secret source.
19. Preserve shipped local security-doc guidance in shared `internal/api/` config/setup helpers so storage- and recovery-adjacent transport surfaces do not reintroduce GitHub `main` security links when the running build already serves its own local security documentation route.
20. Keep shared `internal/api/` Patrol transport and alert-trigger edits feature-isolated: Patrol-specific recency fields, callback fan-out, or alert-bridge wiring changes must not leak into recovery queries, storage links, or recovery-adjacent install/setup flows unless this contract changes in the same slice.
The same adjacency rule applies to AI settings transport in `internal/api/ai_handlers.go`: provider auth state, masked-secret payload fields, provider-test model selection, and safe provider preflight diagnostics remain AI/runtime plus API-contract concerns and must not be absorbed into storage/recovery transport ownership just because those handlers live under the shared backend API tree.
+ The same adjacency rule applies to Pulse Assistant chat SSE progress in
+ `internal/api/ai_handler.go`: neutral `workflow_state` transport liveness
+ such as `stream_idle`, provider startup, retry, fallback, and
+ model-thinking status is Assistant/API progress only, not recovery
+ acquisition, restore identity, backup task freshness, storage-provider
+ health, or storage/recovery job progress.
Direct alert-investigation execution controls in `internal/api/ai_handlers.go`
follow that same split: request-scoped `AutonomousMode:false` and
`RequireCommandApproval:true` are AI action-governance constraints, not
diff --git a/internal/api/ai_handler.go b/internal/api/ai_handler.go
index 7050e887ba..6547611123 100644
--- a/internal/api/ai_handler.go
+++ b/internal/api/ai_handler.go
@@ -158,6 +158,10 @@ type AIHandler struct {
costStoreResolver func(ctx context.Context) *cost.Store
}
+var chatStreamIdleProgressInterval = 2500 * time.Millisecond
+
+const chatStreamIdleProgressMessage = "Assistant is still working; waiting for the next stream event."
+
// SetReportNarratorResolver wires the optional per-tenant
// report-narrator resolver. When unset (or when the resolver returns
// nil), chat sessions construct their tool executor without report
@@ -2435,6 +2439,11 @@ func (h *AIHandler) HandleChat(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), 15*time.Minute)
defer cancel()
+ var writeMu sync.Mutex
+ var lastClientEventUnixMilli atomic.Int64
+ var terminalEventsStarted atomic.Bool
+ lastClientEventUnixMilli.Store(time.Now().UnixMilli())
+
// Heartbeat
heartbeatDone := make(chan struct{})
var clientDisconnected atomic.Bool
@@ -2448,14 +2457,17 @@ func (h *AIHandler) HandleChat(w http.ResponseWriter, r *http.Request) {
clientDisconnected.Store(true)
return
case <-ticker.C:
+ writeMu.Lock()
_ = rc.SetWriteDeadline(time.Now().Add(10 * time.Second))
_, err := w.Write([]byte(": heartbeat\n\n"))
if err != nil {
+ writeMu.Unlock()
clientDisconnected.Store(true)
cancel()
return
}
flusher.Flush()
+ writeMu.Unlock()
case <-heartbeatDone:
return
}
@@ -2464,7 +2476,7 @@ func (h *AIHandler) HandleChat(w http.ResponseWriter, r *http.Request) {
defer close(heartbeatDone)
// Write helper
- writeEvent := func(event chat.StreamEvent) {
+ writeEventIf := func(event chat.StreamEvent, shouldWrite func() bool) {
if clientDisconnected.Load() {
return
}
@@ -2477,6 +2489,11 @@ func (h *AIHandler) HandleChat(w http.ResponseWriter, r *http.Request) {
if err != nil {
return
}
+ writeMu.Lock()
+ defer writeMu.Unlock()
+ if shouldWrite != nil && !shouldWrite() {
+ return
+ }
_ = rc.SetWriteDeadline(time.Now().Add(10 * time.Second))
_, err = w.Write([]byte("data: " + string(data) + "\n\n"))
if err != nil {
@@ -2485,6 +2502,54 @@ func (h *AIHandler) HandleChat(w http.ResponseWriter, r *http.Request) {
return
}
flusher.Flush()
+ lastClientEventUnixMilli.Store(time.Now().UnixMilli())
+ }
+ writeEvent := func(event chat.StreamEvent) {
+ writeEventIf(event, nil)
+ }
+
+ assistantExecutionDone := make(chan struct{})
+ var assistantExecutionDoneClosed atomic.Bool
+ finishAssistantExecution := func() {
+ if assistantExecutionDoneClosed.CompareAndSwap(false, true) {
+ close(assistantExecutionDone)
+ }
+ }
+ defer finishAssistantExecution()
+
+ if chatStreamIdleProgressInterval > 0 {
+ go func() {
+ ticker := time.NewTicker(chatStreamIdleProgressInterval)
+ defer ticker.Stop()
+ for {
+ select {
+ case <-ctx.Done():
+ return
+ case <-heartbeatDone:
+ return
+ case <-assistantExecutionDone:
+ return
+ case <-ticker.C:
+ if clientDisconnected.Load() {
+ return
+ }
+ if terminalEventsStarted.Load() || assistantExecutionDoneClosed.Load() {
+ return
+ }
+ lastEventAt := time.UnixMilli(lastClientEventUnixMilli.Load())
+ if time.Since(lastEventAt) < chatStreamIdleProgressInterval {
+ continue
+ }
+ progressData, _ := json.Marshal(chat.WorkflowStateData{
+ Phase: "stream_idle",
+ Message: chatStreamIdleProgressMessage,
+ })
+ writeEventIf(chat.StreamEvent{Type: "workflow_state", Data: progressData}, func() bool {
+ return !terminalEventsStarted.Load() && !assistantExecutionDoneClosed.Load()
+ })
+ }
+ }
+ }()
}
requestSessionID := strings.TrimSpace(req.SessionID)
@@ -2605,22 +2670,27 @@ func (h *AIHandler) HandleChat(w http.ResponseWriter, r *http.Request) {
}, func(event chat.StreamEvent) {
if event.Type == "done" {
serviceSentDone = true
+ terminalEventsStarted.Store(true)
} else if event.Type == "error" {
serviceSentError = true
+ terminalEventsStarted.Store(true)
}
writeEvent(event)
})
+ finishAssistantExecution()
if err != nil {
log.Error().Err(err).Msg("Chat stream error")
if !serviceSentError {
errData, _ := json.Marshal(chat.ErrorData{Message: "An error occurred while processing your request"})
+ terminalEventsStarted.Store(true)
writeEvent(chat.StreamEvent{Type: "error", Data: errData})
}
}
// Send done
if !serviceSentDone {
+ terminalEventsStarted.Store(true)
writeEvent(chat.StreamEvent{Type: "done", Data: nil})
}
}
diff --git a/internal/api/ai_handler_test.go b/internal/api/ai_handler_test.go
index 8ec196180d..16fc5a95e5 100644
--- a/internal/api/ai_handler_test.go
+++ b/internal/api/ai_handler_test.go
@@ -767,6 +767,41 @@ func TestHandleChat_EmitsSessionBeforeExecuteStream(t *testing.T) {
assert.Equal(t, 1, strings.Count(response, `"type":"workflow_state"`))
}
+func TestHandleChat_EmitsIdleProgressWhileServiceIsSilent(t *testing.T) {
+ cfg := &config.Config{}
+ h := newTestAIHandler(cfg, nil, nil)
+ mockSvc := new(MockAIService)
+ h.defaultService = mockSvc
+
+ idleInterval := chatStreamIdleProgressInterval
+ mockSvc.On("IsRunning").Return(true)
+ mockSvc.On("ExecuteStream", mock.Anything, mock.Anything, mock.Anything).Return(nil).Run(func(args mock.Arguments) {
+ time.Sleep(idleInterval + 25*time.Millisecond)
+ })
+
+ body := `{"prompt": "hi", "session_id": "idle-progress-session"}`
+ req := httptest.NewRequest("POST", "/api/ai/chat", strings.NewReader(body))
+ w := httptest.NewRecorder()
+
+ h.HandleChat(w, req)
+
+ response := w.Body.String()
+ idleIndex := strings.Index(response, `"phase":"stream_idle"`)
+ 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 doneIndex < 0 {
+ t.Fatalf("response missing done event: %s", response)
+ }
+ if idleIndex > doneIndex {
+ t.Fatalf("idle progress appeared after done event: %s", response)
+ }
+}
+
func TestHandleChat_DoesNotLoadStoredHandoffForGeneratedSession(t *testing.T) {
cfg := &config.Config{}
h := newTestAIHandler(cfg, nil, nil)
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index 1451658865..50fa4084a0 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -10629,6 +10629,14 @@ func TestContract_ChatStreamEventJSONSnapshots(t *testing.T) {
}),
want: `{"type":"workflow_state","data":{"phase":"provider_retry","message":"Provider connection failed before any output; retrying.","state":"investigating","attempt":2,"max_attempts":2,"retry_after_ms":200}}`,
},
+ {
+ name: "workflow_state_stream_idle",
+ event: mustStreamEvent(t, "workflow_state", chat.WorkflowStateData{
+ Phase: "stream_idle",
+ Message: chatStreamIdleProgressMessage,
+ }),
+ want: `{"type":"workflow_state","data":{"phase":"stream_idle","message":"Assistant is still working; waiting for the next stream event."}}`,
+ },
{
name: "tool_start",
event: mustStreamEvent(t, "tool_start", chat.ToolStartData{