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 cached preflight in Patrol tools readiness check
rcourtman297556fb65a5
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.mdindex 1f69f02b78..d2ee53771a 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`, the `patrol_preflight` snapshot field added to `/api/settings/ai`, the auto-trigger preflight dispatch on settings save, and the startup-seed dispatch in `NewAISettingsHandler` — all 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`, the auto-trigger preflight dispatch on settings save, the startup-seed dispatch in `NewAISettingsHandler`, and the cached-preflight integration into the Patrol `tools` readiness check — 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 overridesdiff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.mdindex aef07e7fb5..2f09314cd8 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, 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, 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, and the startup-seed contract where the AI Service handler dispatches the same async preflight on Pulse boot when assistant is enabled and a Patrol model is configured so the cache is populated for the first `/api/settings/ai` poll after a restart instead of blanking back to "never verified"+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, 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, the startup-seed contract where the AI Service handler dispatches the same async preflight on Pulse boot when assistant is enabled and a Patrol model is configured so the cache is populated for the first `/api/settings/ai` poll after a restart instead of blanking back to "never verified", and the readiness-integration contract where the `tools` check in the Patrol readiness payload consults the cached preflight and surfaces the classified evidence (success, soft warning, or failure with classified summary plus "last preflight <age>") for the configured provider+model when available, falling back to the static `PatrolToolReadinessForModel` classifier only when the cache is empty or holds a result for a different model2. 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 changesPatrol 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.mdindex af4783389d..1b841c6d2e 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, the `patrol_preflight` snapshot field on `/api/settings/ai` that hydrates the Verify Patrol panel on page load, 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, and the startup-seed contract where `NewAISettingsHandler` dispatches the same async preflight after `LoadConfig()` succeeds so the first `/api/settings/ai` poll after a Pulse restart already carries a populated `patrol_preflight` snapshot+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, 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, the startup-seed contract where `NewAISettingsHandler` dispatches the same async preflight after `LoadConfig()` succeeds so the first `/api/settings/ai` poll after a Pulse restart already carries a populated `patrol_preflight` snapshot, and the GET-symmetry contract where `HandleGetAISettings` includes `patrol_readiness` (with the cached-preflight-augmented `tools` check) on the same response that already carries `patrol_preflight`, so the Patrol page picks up classified preflight evidence on first load instead of only after a save2. Update frontend API types in the same slice3. Route runtime changes through the explicit API-contract proof policies in `registry.json`; default fallback proof routing is not allowed4. Update this contract when canonical payload ownership changesdiff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.mdindex 29b17204a2..ea803785b3 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`, the `patrol_preflight` snapshot field added to `/api/settings/ai`, the auto-trigger preflight dispatch on settings save, and the startup-seed dispatch in `NewAISettingsHandler` — all 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`, the auto-trigger preflight dispatch on settings save, the startup-seed dispatch in `NewAISettingsHandler`, and the cached-preflight integration into the Patrol `tools` readiness check — 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 removed4. 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.tsindex 3e706c4444..90d7ba12e6 100644--- a/frontend-modern/src/api/__tests__/patrolPreflight.test.ts+++ b/frontend-modern/src/api/__tests__/patrolPreflight.test.ts@@ -128,6 +128,38 @@ describe('runPatrolPreflight', () => {expect(result.recorded_at_unix).toBe(1778430642);});+ it('keeps the response shape stable for cached snapshots regardless of whether the cache holds a success or failure', async () => {+ // The Patrol page reads patrol_readiness from /api/settings/ai+ // (now populated on GET as well as PUT). Pulse plugs the cached+ // preflight result into the "tools" check there, but the+ // /api/ai/patrol/preflight response itself stays single-shape so+ // the same client decoder works for both manual and cache-driven+ // surfaces. Verify the failure shape's required fields don't+ // regress.+ vi.mocked(apiFetchJSON).mockResolvedValueOnce({+ success: false,+ provider: 'deepseek',+ model: 'deepseek-v4-flash',+ tool_call_observed: false,+ duration_ms: 312,+ message: 'Provider rejected forced tool selection',+ cause: 'tool_choice_rejected',+ summary:+ 'Pulse Patrol reached the provider and the model accepts tools, but the provider rejected the specific tool-selection coercion Pulse sent.',+ recommendation:+ 'Pulse will retry with automatic tool selection on the next Patrol run.',+ recorded_at: '2026-05-10T15:30:42Z',+ recorded_at_unix: 1778430642,+ });++ const result = await runPatrolPreflight();++ expect(result.success).toBe(false);+ expect(result.cause).toBe('tool_choice_rejected');+ expect(result.recommendation).toContain('automatic tool selection');+ expect(result.recorded_at_unix).toBe(1778430642);+ });+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/api/ai_handlers.go b/internal/api/ai_handlers.goindex 16d2a348a8..c3999328b8 100644--- a/internal/api/ai_handlers.go+++ b/internal/api/ai_handlers.go@@ -2510,6 +2510,7 @@ func (h *AISettingsHandler) HandleGetAISettings(w http.ResponseWriter, r *http.RDiscoveryEnabled: settings.IsDiscoveryEnabled(),DiscoveryIntervalHours: settings.DiscoveryIntervalHours,PatrolPreflight: cachedPatrolPreflightSnapshot(aiService),+ PatrolReadiness: ptrToPatrolReadiness(h.buildPatrolReadiness(ctx, aiService, h.getPatrolService(ctx) != nil)),}.NormalizeCollections()if err := utils.WriteJSONResponse(w, response); err != nil {@@ -5102,16 +5103,77 @@ func (h *AISettingsHandler) buildPatrolReadiness(ctx context.Context, aiService}addCheck("model", patrolReadinessReady, ai.PatrolFailureCauseNone, "Patrol model", "Patrol has a model selected from a configured provider.", "")- toolStatus, toolCause, toolMessage := ai.PatrolToolReadinessForModel(provider, model)- toolAction := ""- if toolStatus != patrolReadinessReady {- toolAction = "open_provider_settings"- }+ toolStatus, toolCause, toolMessage, toolAction := resolvePatrolToolsCheck(aiService, provider, model)addCheck("tools", toolStatus, toolCause, "Patrol tools", toolMessage, toolAction)return summarizePatrolReadiness(provider, model, checks)}+// resolvePatrolToolsCheck grounds the "Patrol tools" readiness check in+// actual evidence when the preflight cache holds a recent result for+// the configured provider+model. The cache is populated by+// (a) auto-trigger on settings save when transport changes,+// (b) startup-seed when assistant + patrol model are configured, and+// (c) manual Verify Patrol clicks. When no cached evidence is+// available, fall back to the static `PatrolToolReadinessForModel`+// classifier so the check still has a meaningful baseline.+func resolvePatrolToolsCheck(aiService *ai.Service, provider, model string) (status string, cause ai.PatrolFailureCause, message, action string) {+ staticStatus, staticCause, staticMessage := ai.PatrolToolReadinessForModel(provider, model)+ staticAction := ""+ if staticStatus != patrolReadinessReady {+ staticAction = "open_provider_settings"+ }++ if aiService == nil {+ return staticStatus, staticCause, staticMessage, staticAction+ }+ cached, recordedAt := aiService.CachedPatrolPreflight()+ if cached == nil || recordedAt.IsZero() {+ return staticStatus, staticCause, staticMessage, staticAction+ }+ // Cache only carries the most recent result regardless of which+ // model was tested, so a mismatch means the configured model+ // hasn't been preflighted yet. Fall back to static.+ _, bareModel := config.ParseModelString(model)+ if !strings.EqualFold(cached.Provider, provider) || cached.Model != bareModel {+ return staticStatus, staticCause, staticMessage, staticAction+ }++ age := formatPatrolPreflightAge(time.Since(recordedAt))+ if cached.Success && cached.ToolCallObserved {+ return patrolReadinessReady, ai.PatrolFailureCauseNone,+ fmt.Sprintf("Tool calling verified %s against %s.", age, bareModel), ""+ }+ // Cached failure or soft warning — surface the classified summary+ // so the Patrol page reads the same diagnostic the operator would+ // see on the AI settings preflight panel.+ resolvedStatus := patrolReadinessNotReady+ if cached.Cause == ai.PatrolFailureCauseModelToolSupportUnverified {+ resolvedStatus = patrolReadinessWarning+ }+ msg := strings.TrimSpace(cached.Summary)+ if msg == "" {+ msg = strings.TrimSpace(cached.Title)+ }+ if msg == "" {+ msg = staticMessage+ }+ return resolvedStatus, cached.Cause, fmt.Sprintf("%s (last preflight %s).", msg, age), "open_provider_settings"+}++func formatPatrolPreflightAge(age time.Duration) string {+ switch {+ case age < time.Minute:+ return "just now"+ case age < time.Hour:+ return fmt.Sprintf("%dm ago", int(age.Minutes()))+ case age < 24*time.Hour:+ return fmt.Sprintf("%dh ago", int(age.Hours()))+ default:+ return fmt.Sprintf("%dd ago", int(age.Hours()/24))+ }+}+func summarizePatrolReadiness(provider, model string, checks []PatrolReadinessCheck) PatrolReadinessResponse {status := patrolReadinessReadycause := ""diff --git a/internal/api/ai_handlers_test.go b/internal/api/ai_handlers_test.goindex ba86f59101..0c9b3543f9 100644--- a/internal/api/ai_handlers_test.go+++ b/internal/api/ai_handlers_test.go@@ -2999,6 +2999,37 @@ func TestAISettingsUpdateRequiresPatrolPreflight(t *testing.T) {}}+// ========================================+// formatPatrolPreflightAge tests+// ========================================++func TestFormatPatrolPreflightAge(t *testing.T) {+ t.Parallel()++ cases := []struct {+ age time.Duration+ want string+ }{+ {age: 0, want: "just now"},+ {age: 30 * time.Second, want: "just now"},+ {age: 59 * time.Second, want: "just now"},+ {age: 1 * time.Minute, want: "1m ago"},+ {age: 5 * time.Minute, want: "5m ago"},+ {age: 59 * time.Minute, want: "59m ago"},+ {age: 1 * time.Hour, want: "1h ago"},+ {age: 12 * time.Hour, want: "12h ago"},+ {age: 23 * time.Hour, want: "23h ago"},+ {age: 24 * time.Hour, want: "1d ago"},+ {age: 72 * time.Hour, want: "3d ago"},+ }+ for _, tc := range cases {+ got := formatPatrolPreflightAge(tc.age)+ if got != tc.want {+ t.Errorf("formatPatrolPreflightAge(%v) = %q, want %q", tc.age, got, tc.want)+ }+ }+}+// ========================================// HandlePatrolPreflight tests// ========================================