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.

Auto-trigger Patrol preflight when settings save moves Patrol transport

rcourtman33b6bf97d1fa
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 8e953bd015..e9b1e8c4a0 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -743,7 +743,7 @@ profile and assignment columns, but embedded table framing must route through
## Completion Obligations
-1. Update this contract when agent lifecycle ownership changes. Routes added under the shared `internal/api/` extension point that are clearly outside lifecycle ownership (for example `POST /api/ai/patrol/preflight` and the `patrol_preflight` snapshot field added to `/api/settings/ai`, both owned by ai-runtime) do not extend this subsystem's contract; they live in their owning subsystem.
+1. Update this contract when agent lifecycle ownership changes. Routes added under the shared `internal/api/` extension point that are clearly outside lifecycle ownership (for example `POST /api/ai/patrol/preflight`, the `patrol_preflight` snapshot field added to `/api/settings/ai`, and the auto-trigger preflight dispatch on settings save — all owned by ai-runtime) do not extend this subsystem's contract; they live in their owning subsystem.
2. Keep shared API proof routing aligned whenever install, register, or profile payloads change.
3. Update runtime and settings tests in the same slice when lifecycle behavior changes.
4. Keep host-agent test hooks, command-client factories, and timing overrides
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 48b0b16fb6..8e2db4e91a 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -108,7 +108,7 @@ runtime cost control, and shared AI transport surfaces.
## Completion Obligations
-1. Update this contract when canonical AI runtime or transport entry points move, including transport-level provider request-shape changes such as DeepSeek `tool_choice` coercion, runtime-failure classification splits (for example separating forced tool selection rejection, no tool-capable endpoint, and generic model-level lack of tool support into distinct causes), Patrol-specific verification surfaces such as `POST /api/ai/patrol/preflight` that exercise the full chat-completions path with a minimal tool definition rather than only listing models, and Patrol-preflight cache observability where the AI Service caches the most recent preflight outcome (success, soft warning, or classified failure) and the AI settings response surfaces it as `patrol_preflight` so the UI can hydrate a "last verified" indicator without forcing operators to re-run preflight on every page load
+1. Update this contract when canonical AI runtime or transport entry points move, including transport-level provider request-shape changes such as DeepSeek `tool_choice` coercion, runtime-failure classification splits (for example separating forced tool selection rejection, no tool-capable endpoint, and generic model-level lack of tool support into distinct causes), Patrol-specific verification surfaces such as `POST /api/ai/patrol/preflight` that exercise the full chat-completions path with a minimal tool definition rather than only listing models, Patrol-preflight cache observability where the AI Service caches the most recent preflight outcome (success, soft warning, or classified failure) and the AI settings response surfaces it as `patrol_preflight` so the UI can hydrate a "last verified" indicator without forcing operators to re-run preflight on every page load, and the auto-trigger contract on `HandleUpdateAISettings` where the save handler runs `TriggerPatrolPreflightAsync` only when the change actually moved Patrol transport (model swap, provider key for that model changed, or assistant just enabled with a Patrol model) so routine settings saves do not burn provider tokens
2. Keep AI runtime and shared API proof routing aligned in `registry.json`
3. Preserve explicit coverage for chat, Patrol, remediation, and cost-control behavior when AI runtime changes
Patrol runtime failures are part of that runtime contract: provider, model,
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 02b2d8c358..3fbeb4bb67 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -894,7 +894,7 @@ the canonical monitored-system blocked payload.
## Completion Obligations
-1. Update contract tests when payloads change, including admin verification endpoints such as `POST /api/ai/patrol/preflight` whose response shape (`tool_call_observed`, `duration_ms`, classified `cause`/`summary`/`recommendation`, plus `recorded_at`/`recorded_at_unix` for the cached snapshot) is part of the canonical Patrol diagnostic surface, and the `patrol_preflight` snapshot field on `/api/settings/ai` that hydrates the Verify Patrol panel on page load
+1. Update contract tests when payloads change, including admin verification endpoints such as `POST /api/ai/patrol/preflight` whose response shape (`tool_call_observed`, `duration_ms`, classified `cause`/`summary`/`recommendation`, plus `recorded_at`/`recorded_at_unix` for the cached snapshot) is part of the canonical Patrol diagnostic surface, the `patrol_preflight` snapshot field on `/api/settings/ai` that hydrates the Verify Patrol panel on page load, and the auto-trigger contract on `POST/PUT /api/settings/ai` whose handler dispatches preflight in the background only when the change actually moved Patrol transport so routine saves do not write a new `patrol_preflight` snapshot
2. Update frontend API types in the same slice
3. Route runtime changes through the explicit API-contract proof policies in `registry.json`; default fallback proof routing is not allowed
4. Update this contract when canonical payload ownership changes
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index 8d36e3eecd..7640fe98e8 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -762,7 +762,7 @@ bypass the API fail-closed execution gate.
## Completion Obligations
-1. Update this contract when canonical storage or recovery entry points move. Routes added under the shared `internal/api/` extension point that are clearly outside storage/recovery ownership (for example `POST /api/ai/patrol/preflight` and the `patrol_preflight` snapshot field added to `/api/settings/ai`, both owned by ai-runtime) do not extend this subsystem's contract; they live in their owning subsystem.
+1. Update this contract when canonical storage or recovery entry points move. Routes added under the shared `internal/api/` extension point that are clearly outside storage/recovery ownership (for example `POST /api/ai/patrol/preflight`, the `patrol_preflight` snapshot field added to `/api/settings/ai`, and the auto-trigger preflight dispatch on settings save — all owned by ai-runtime) do not extend this subsystem's contract; they live in their owning subsystem.
2. Keep recovery store/runtime changes aligned with the storage and recovery frontend proofs in `registry.json`
3. Tighten guardrails when legacy storage or recovery presentation paths are removed
4. Preserve the dependency split: API payload ownership stays in `api-contracts`, settings shell ownership stays in `frontend-primitives`, and canonical resource truth stays in `unified-resources`
diff --git a/frontend-modern/src/api/__tests__/patrolPreflight.test.ts b/frontend-modern/src/api/__tests__/patrolPreflight.test.ts
index f798a6b330..c61d4090be 100644
--- a/frontend-modern/src/api/__tests__/patrolPreflight.test.ts
+++ b/frontend-modern/src/api/__tests__/patrolPreflight.test.ts
@@ -77,6 +77,31 @@ describe('runPatrolPreflight', () => {
expect(result.recorded_at_unix).toBe(1778421251);
});
+ it('handles auto-triggered preflight outcomes with the same shape as manual ones', async () => {
+ // The backend dispatches auto-preflight in the background after a
+ // settings save when the Patrol model or its provider key changes.
+ // The cached result then shows up on /api/settings/ai with the
+ // same shape this client uses for manual preflight, so the UI can
+ // render it through one code path. Verify the recorded_at fields
+ // on a successful auto-trigger result round-trip cleanly.
+ vi.mocked(apiFetchJSON).mockResolvedValueOnce({
+ success: true,
+ provider: 'deepseek',
+ model: 'deepseek-v4-flash',
+ tool_call_observed: true,
+ duration_ms: 1948,
+ message: 'Provider accepted the preflight request and the model emitted a tool call.',
+ recorded_at: '2026-05-10T13:54:11Z',
+ recorded_at_unix: 1778421251,
+ });
+
+ const result = await runPatrolPreflight();
+
+ expect(result.success).toBe(true);
+ expect(result.tool_call_observed).toBe(true);
+ expect(result.recorded_at_unix).toBe(1778421251);
+ });
+
it('exposes the soft-warning shape when the model accepted the request but did not call the tool', async () => {
vi.mocked(apiFetchJSON).mockResolvedValueOnce({
success: false,
diff --git a/internal/ai/patrol_preflight.go b/internal/ai/patrol_preflight.go
index 2f5ee9e46d..6517b8caa4 100644
--- a/internal/ai/patrol_preflight.go
+++ b/internal/ai/patrol_preflight.go
@@ -77,6 +77,21 @@ func (s *Service) recordPatrolPreflight(result PatrolPreflightResult, at time.Ti
s.patrolPreflightCache.recordedAt = at
}
+// TriggerPatrolPreflightAsync runs RunPatrolToolPreflight in the
+// background so callers (notably the settings save handler) don't block
+// on a 5-10 second LLM round-trip. The result populates the preflight
+// cache and the next /api/settings/ai poll surfaces it through the
+// patrol_preflight snapshot. The 30s timeout matches the manual
+// preflight handler so a stuck provider can't pin the goroutine
+// indefinitely.
+func (s *Service) TriggerPatrolPreflightAsync(provider, model string) {
+ go func() {
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+ s.RunPatrolToolPreflight(ctx, provider, model)
+ }()
+}
+
// RunPatrolToolPreflight performs a one-shot tool-call round-trip against
// the configured Patrol provider+model, or against the overrides supplied
// in providerName / model. Both override arguments are optional: empty
diff --git a/internal/ai/patrol_preflight_test.go b/internal/ai/patrol_preflight_test.go
index b973889ef3..e400627197 100644
--- a/internal/ai/patrol_preflight_test.go
+++ b/internal/ai/patrol_preflight_test.go
@@ -7,6 +7,7 @@ import (
"net/http/httptest"
"strings"
"testing"
+ "time"
"github.com/rcourtman/pulse-go-rewrite/internal/config"
)
@@ -286,6 +287,45 @@ func TestCachedPatrolPreflight_ReturnsDefensiveCopy(t *testing.T) {
}
}
+func TestTriggerPatrolPreflightAsync_PopulatesCacheInBackground(t *testing.T) {
+ // The settings save handler dispatches preflight via this entrypoint
+ // so the save response isn't blocked on a 5-10s LLM round-trip.
+ // Verify the goroutine actually populates the cache and the caller
+ // returns immediately.
+ called := make(chan struct{}, 1)
+ h := newPatrolPreflightTestService(t, "openai:gpt-4o-mini", func(w http.ResponseWriter, r *http.Request) {
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"id":"x","model":"gpt-4o-mini","choices":[{"finish_reason":"tool_calls","message":{"role":"assistant","content":"","tool_calls":[{"id":"1","type":"function","function":{"name":"verify_pulse_patrol","arguments":"{\"ok\":true}"}}]}}]}`))
+ select {
+ case called <- struct{}{}:
+ default:
+ }
+ })
+ defer h.close()
+
+ h.svc.TriggerPatrolPreflightAsync("", "")
+
+ // Caller does not block — wait for the background goroutine to hit
+ // the test server.
+ select {
+ case <-called:
+ case <-time.After(5 * time.Second):
+ t.Fatalf("async preflight did not invoke provider within 5s")
+ }
+
+ // Cache must populate eventually after the goroutine finishes.
+ deadline := time.Now().Add(2 * time.Second)
+ for time.Now().Before(deadline) {
+ cached, _ := h.svc.CachedPatrolPreflight()
+ if cached != nil && cached.Success && cached.ToolCallObserved {
+ return
+ }
+ time.Sleep(20 * time.Millisecond)
+ }
+ cached, _ := h.svc.CachedPatrolPreflight()
+ t.Fatalf("expected async preflight to populate cache with green result, got %+v", cached)
+}
+
func TestRunPatrolToolPreflight_RequestShapeIncludesVerifyTool(t *testing.T) {
// Locks the preflight request shape so a future refactor can't
// silently strip the tool definition or tool_choice (which would
diff --git a/internal/api/ai_handlers.go b/internal/api/ai_handlers.go
index 237ba07caf..9efcc79bf6 100644
--- a/internal/api/ai_handlers.go
+++ b/internal/api/ai_handlers.go
@@ -1674,6 +1674,42 @@ func shouldRestartAIChat(req AISettingsUpdateRequest) bool {
req.ClearOllamaPassword != nil
}
+// aiSettingsUpdateRequiresPatrolPreflight reports whether the settings
+// transition from oldCfg to newCfg warrants an automatic Patrol
+// tool-call preflight. We only auto-preflight when the configuration
+// that affects Patrol's transport actually moved, so routine settings
+// saves (theme, control level, discovery toggles, etc.) don't burn
+// provider tokens or add 5-10s of latency to every save.
+//
+// Triggers preflight when:
+// - assistant is now enabled and a Patrol model is selected, AND
+// - either the Patrol model changed, the new patrol model's provider
+// API key changed, OR there was no prior config (first save).
+func aiSettingsUpdateRequiresPatrolPreflight(oldCfg, newCfg *config.AIConfig) bool {
+ if newCfg == nil || !newCfg.Enabled {
+ return false
+ }
+ newPatrolModel := strings.TrimSpace(newCfg.GetPatrolModel())
+ if newPatrolModel == "" {
+ return false
+ }
+ if oldCfg == nil {
+ return true
+ }
+ if !oldCfg.Enabled {
+ return true
+ }
+ oldPatrolModel := strings.TrimSpace(oldCfg.GetPatrolModel())
+ if oldPatrolModel != newPatrolModel {
+ return true
+ }
+ provider, _ := config.ParseModelString(newPatrolModel)
+ if provider == "" {
+ return false
+ }
+ return oldCfg.GetAPIKeyForProvider(provider) != newCfg.GetAPIKeyForProvider(provider)
+}
+
func aiSettingsUpdateTouchesPatrolReadiness(req AISettingsUpdateRequest) bool {
return req.Enabled != nil ||
req.Model != nil ||
@@ -2513,6 +2549,12 @@ func (h *AISettingsHandler) HandleUpdateAISettings(w http.ResponseWriter, r *htt
settings = config.NewDefaultAIConfig()
}
+ // Snapshot the pre-mutation config so we can detect Patrol-affecting
+ // changes after save and decide whether to auto-trigger preflight.
+ // Shallow copy is fine — the detection helper only reads scalar
+ // fields (Enabled, PatrolModel, API keys).
+ originalSettings := *settings
+
// Parse request
r.Body = http.MaxBytesReader(w, r.Body, 16*1024)
var req AISettingsUpdateRequest
@@ -2788,6 +2830,16 @@ func (h *AISettingsHandler) HandleUpdateAISettings(w http.ResponseWriter, r *htt
analyzer.SetEnabled(settings.AlertTriggeredAnalysis)
}
+ // Auto-trigger Patrol tool-call preflight when the change actually
+ // moved the Patrol transport (model swap or new key for the model's
+ // provider). Runs in the background so the save response isn't
+ // blocked; the cached result surfaces on the next /api/settings/ai
+ // poll via patrol_preflight. Routine saves that don't touch Patrol
+ // transport skip this entirely so they don't burn provider tokens.
+ if aiSettingsUpdateRequiresPatrolPreflight(&originalSettings, settings) {
+ h.GetAIService(r.Context()).TriggerPatrolPreflightAsync("", "")
+ }
+
// Trigger AI chat service restart when provider-affecting settings change.
// The running service keeps provider configuration in memory, so credential,
// base URL, or model updates must restart the chat runtime to take effect.
diff --git a/internal/api/ai_handlers_test.go b/internal/api/ai_handlers_test.go
index a7c4b5cae6..70bfb60675 100644
--- a/internal/api/ai_handlers_test.go
+++ b/internal/api/ai_handlers_test.go
@@ -2877,6 +2877,105 @@ func TestAISettingsHandler_Approvals_RejectCrossOrgAccess(t *testing.T) {
require.Equal(t, approval.StatusPending, denyApp.Status)
}
+// ========================================
+// aiSettingsUpdateRequiresPatrolPreflight tests
+// ========================================
+
+func TestAISettingsUpdateRequiresPatrolPreflight(t *testing.T) {
+ t.Parallel()
+
+ enabled := func(model, key string) *config.AIConfig {
+ return &config.AIConfig{
+ Enabled: true,
+ PatrolModel: model,
+ DeepSeekAPIKey: key,
+ }
+ }
+ disabled := func() *config.AIConfig {
+ return &config.AIConfig{Enabled: false, PatrolModel: "deepseek:deepseek-v4-flash"}
+ }
+
+ cases := []struct {
+ name string
+ old *config.AIConfig
+ new *config.AIConfig
+ want bool
+ }{
+ {
+ name: "nil new → skip",
+ new: nil,
+ want: false,
+ },
+ {
+ name: "new disabled → skip",
+ old: enabled("deepseek:deepseek-v4-flash", "sk-old"),
+ new: disabled(),
+ want: false,
+ },
+ {
+ name: "new enabled with no patrol model → skip",
+ new: &config.AIConfig{Enabled: true, PatrolModel: ""},
+ want: false,
+ },
+ {
+ name: "first save (no prior config) → trigger",
+ old: nil,
+ new: enabled("deepseek:deepseek-v4-flash", "sk-new"),
+ want: true,
+ },
+ {
+ name: "assistant just enabled → trigger",
+ old: &config.AIConfig{Enabled: false, PatrolModel: "deepseek:deepseek-v4-flash", DeepSeekAPIKey: "sk-same"},
+ new: enabled("deepseek:deepseek-v4-flash", "sk-same"),
+ want: true,
+ },
+ {
+ name: "patrol model changed → trigger",
+ old: enabled("deepseek:deepseek-v4-flash", "sk-same"),
+ new: enabled("deepseek:deepseek-v4-pro", "sk-same"),
+ want: true,
+ },
+ {
+ name: "API key for patrol model's provider changed → trigger",
+ old: enabled("deepseek:deepseek-v4-flash", "sk-old"),
+ new: enabled("deepseek:deepseek-v4-flash", "sk-new"),
+ want: true,
+ },
+ {
+ name: "nothing relevant changed → skip",
+ old: enabled("deepseek:deepseek-v4-flash", "sk-same"),
+ new: enabled("deepseek:deepseek-v4-flash", "sk-same"),
+ want: false,
+ },
+ {
+ name: "unrelated provider key changed → skip",
+ old: &config.AIConfig{
+ Enabled: true,
+ PatrolModel: "deepseek:deepseek-v4-flash",
+ DeepSeekAPIKey: "sk-same",
+ OpenAIAPIKey: "sk-openai-old",
+ },
+ new: &config.AIConfig{
+ Enabled: true,
+ PatrolModel: "deepseek:deepseek-v4-flash",
+ DeepSeekAPIKey: "sk-same",
+ OpenAIAPIKey: "sk-openai-new",
+ },
+ want: false,
+ },
+ }
+
+ for _, tc := range cases {
+ tc := tc
+ t.Run(tc.name, func(t *testing.T) {
+ got := aiSettingsUpdateRequiresPatrolPreflight(tc.old, tc.new)
+ if got != tc.want {
+ t.Fatalf("got %v, want %v", got, tc.want)
+ }
+ })
+ }
+}
+
// ========================================
// HandlePatrolPreflight tests
// ========================================