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.

fix: address AI patrol concurrency and streaming issues

rcourtman8720708e7075
diff --git a/internal/ai/chat/service.go b/internal/ai/chat/service.go
index c9dd6bdbe5..3c68fd4e91 100644
--- a/internal/ai/chat/service.go
+++ b/internal/ai/chat/service.go
@@ -339,20 +339,30 @@ func (s *Service) ExecuteStream(ctx context.Context, req ExecuteRequest, callbac
if overrideModel != "" {
selectedModel = overrideModel
}
- loop := agenticLoop
+ // Create a per-request AgenticLoop to ensure complete isolation between
+ // concurrent sessions. This prevents race conditions where concurrent
+ // ExecuteStream calls would overwrite each other's FSM, knowledge accumulator,
+ // autonomous mode, budget checker, and provider info on a shared loop.
+ var loop *AgenticLoop
if overrideModel != "" && overrideModel != configuredModel {
provider, err := s.createProviderForModel(overrideModel)
if err != nil {
return fmt.Errorf("failed to create provider for model override %q: %w", overrideModel, err)
}
systemPrompt := s.buildSystemPrompt()
- tempLoop := NewAgenticLoop(provider, executor, systemPrompt)
- tempLoop.SetAutonomousMode(autonomousMode)
- loop = tempLoop
+ loop = NewAgenticLoop(provider, executor, systemPrompt)
+ } else {
+ // Create a fresh loop with the configured provider for this request
+ s.mu.RLock()
+ provider := s.provider
+ s.mu.RUnlock()
+ if provider == nil {
+ return fmt.Errorf("provider not initialized")
+ }
+ systemPrompt := s.buildSystemPrompt()
+ loop = NewAgenticLoop(provider, executor, systemPrompt)
}
-
- // Reset token counts so per-request usage is accurate.
- loop.ResetTokenCounts()
+ loop.SetAutonomousMode(autonomousMode)
// Proactively gather context for mentioned resources
s.mu.RLock()
diff --git a/internal/ai/chat/service_execute_additional_test.go b/internal/ai/chat/service_execute_additional_test.go
index 13cea1638a..479cbacf68 100644
--- a/internal/ai/chat/service_execute_additional_test.go
+++ b/internal/ai/chat/service_execute_additional_test.go
@@ -60,6 +60,7 @@ func TestService_ExecuteStream_Success(t *testing.T) {
sessions: store,
executor: executor,
agenticLoop: loop,
+ provider: provider, // Required: per-request loops need a provider to create new instances
started: true,
}
diff --git a/internal/ai/patrol_run.go b/internal/ai/patrol_run.go
index a4bd89cb8f..e8e6cb172f 100644
--- a/internal/ai/patrol_run.go
+++ b/internal/ai/patrol_run.go
@@ -1077,12 +1077,19 @@ func (p *PatrolService) SubscribeToStream() chan PatrolStreamEvent {
p.streamMu.Lock()
p.streamSubscribers[ch] = sub
- // Send current state to new subscriber
+ // Send current state to new subscriber (late joiner)
if p.streamPhase != "idle" {
+ // First send the current phase so UI can update its phase display
ch <- PatrolStreamEvent{
- Type: "content",
- Content: p.currentOutput.String(),
- Phase: p.streamPhase,
+ Type: "phase",
+ Phase: p.streamPhase,
+ }
+ // Then send any accumulated content
+ if p.currentOutput.Len() > 0 {
+ ch <- PatrolStreamEvent{
+ Type: "content",
+ Content: p.currentOutput.String(),
+ }
}
}
p.streamMu.Unlock()
@@ -1143,17 +1150,26 @@ func (p *PatrolService) appendStreamContent(content string) {
})
}
-// setStreamPhase updates the current phase (internal state tracking only)
-// Does not broadcast phase changes - those are explicit via broadcast()
+// setStreamPhase updates the current phase and broadcasts it to all subscribers.
+// The frontend only updates its phase display when it receives a 'phase' event,
+// so we must broadcast phase changes to keep the UI in sync.
func (p *PatrolService) setStreamPhase(phase string) {
p.streamMu.Lock()
+ oldPhase := p.streamPhase
p.streamPhase = phase
if phase == "idle" {
p.currentOutput.Reset()
}
p.streamMu.Unlock()
- // Note: We don't broadcast phase changes automatically
- // The patrol explicitly broadcasts "start" and "complete" events
+
+ // Broadcast phase change (except for idle which just clears state)
+ // This ensures late joiners and continuous watchers see the current phase
+ if phase != "idle" && phase != oldPhase {
+ p.broadcast(PatrolStreamEvent{
+ Type: "phase",
+ Phase: phase,
+ })
+ }
}
// GetCurrentStreamOutput returns the current buffered output (for late joiners)
diff --git a/internal/ai/patrol_run_test.go b/internal/ai/patrol_run_test.go
index 38ec19d262..c3cacc0f3c 100644
--- a/internal/ai/patrol_run_test.go
+++ b/internal/ai/patrol_run_test.go
@@ -448,7 +448,20 @@ func TestSubscribeToStream_ReceivesCurrentState(t *testing.T) {
ch := ps.SubscribeToStream()
defer ps.UnsubscribeFromStream(ch)
- // New subscriber should receive current state
+ // New subscriber should receive current phase first
+ select {
+ case event := <-ch:
+ if event.Type != "phase" {
+ t.Errorf("expected phase event first, got %s", event.Type)
+ }
+ if event.Phase != "analyzing" {
+ t.Errorf("expected phase 'analyzing', got %q", event.Phase)
+ }
+ case <-time.After(100 * time.Millisecond):
+ t.Error("expected to receive phase event on subscribe")
+ }
+
+ // Then receive accumulated content
select {
case event := <-ch:
if event.Type != "content" {
@@ -457,11 +470,8 @@ func TestSubscribeToStream_ReceivesCurrentState(t *testing.T) {
if event.Content != "some output" {
t.Errorf("expected 'some output', got %q", event.Content)
}
- if event.Phase != "analyzing" {
- t.Errorf("expected phase 'analyzing', got %q", event.Phase)
- }
case <-time.After(100 * time.Millisecond):
- t.Error("expected to receive current state on subscribe")
+ t.Error("expected to receive content event on subscribe")
}
}
diff --git a/internal/ai/patrol_triggers.go b/internal/ai/patrol_triggers.go
index d50976ddee..005d9ea288 100644
--- a/internal/ai/patrol_triggers.go
+++ b/internal/ai/patrol_triggers.go
@@ -415,11 +415,11 @@ func (tm *TriggerManager) GetPendingCount() int {
// TriggerStatus returns the current status of the trigger manager
type TriggerStatus struct {
- Running bool `json:"running"`
- PendingTriggers int `json:"pending_triggers"`
- CurrentInterval time.Duration `json:"current_interval_ms"`
- RecentEvents int `json:"recent_events"`
- IsBusyMode bool `json:"is_busy_mode"`
+ Running bool `json:"running"`
+ PendingTriggers int `json:"pending_triggers"`
+ CurrentInterval int64 `json:"current_interval_ms"` // Milliseconds (converted from time.Duration)
+ RecentEvents int `json:"recent_events"`
+ IsBusyMode bool `json:"is_busy_mode"`
}
// GetStatus returns the current status
@@ -428,11 +428,15 @@ func (tm *TriggerManager) GetStatus() TriggerStatus {
defer tm.mu.Unlock()
tm.cleanupOldEvents()
+ // Recompute the adaptive interval after pruning old events.
+ // Without this, currentInterval can remain stuck in busy/quiet mode
+ // after events age out of the window.
+ tm.updateAdaptiveInterval()
return TriggerStatus{
Running: tm.running,
PendingTriggers: len(tm.pendingTriggers),
- CurrentInterval: tm.currentInterval,
+ CurrentInterval: int64(tm.currentInterval / time.Millisecond),
RecentEvents: len(tm.recentEvents),
IsBusyMode: len(tm.recentEvents) >= tm.busyThreshold,
}
diff --git a/internal/ai/patrol_triggers_test.go b/internal/ai/patrol_triggers_test.go
index 039984b314..09f7c072ab 100644
--- a/internal/ai/patrol_triggers_test.go
+++ b/internal/ai/patrol_triggers_test.go
@@ -384,8 +384,10 @@ func TestGetStatus(t *testing.T) {
if status.PendingTriggers != 1 {
t.Errorf("expected 1 pending trigger, got %d", status.PendingTriggers)
}
- if status.CurrentInterval != 15*time.Minute {
- t.Errorf("expected current interval 15m, got %v", status.CurrentInterval)
+ // CurrentInterval is now in milliseconds (15 minutes = 900000ms)
+ expectedMs := int64(15 * time.Minute / time.Millisecond)
+ if status.CurrentInterval != expectedMs {
+ t.Errorf("expected current interval %dms, got %dms", expectedMs, status.CurrentInterval)
}
}