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.

Cache Patrol preflight outcome and hydrate UI on settings load

rcourtmanadd1096ec86c
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 040df5d6a2..e7232ca331 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`, 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` 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.
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 f3e1483f61..48b0b16fb6 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), and 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
+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
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 622d2fe1e8..0d2ac663c8 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`) is part of the canonical Patrol diagnostic surface
+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
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/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
index 7961ff68a3..64bac65e2c 100644
--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md
+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
@@ -873,7 +873,10 @@ prompt explain the same operator-facing priority.
example the Verify Patrol button in
`AIModelSelectionSection.tsx`, which must drive the typed
`runPatrolPreflight` client through `useAISettingsState.ts` rather
- than inlining fetch calls in the section component)
+ than inlining fetch calls in the section component, and which must
+ hydrate its result panel from the `patrol_preflight` snapshot on
+ `/api/settings/ai` so the "last verified" state survives page
+ reloads without forcing a re-click)
2. Keep top-level settings surfaces routed through the canonical settings shell
and maintain both `frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts`
plus `tests/integration/tests/15-settings-shell-consistency.spec.ts`
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index a7bd6c0733..0601c8ea8d 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`, 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` 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.
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 1b188b34e0..f798a6b330 100644
--- a/frontend-modern/src/api/__tests__/patrolPreflight.test.ts
+++ b/frontend-modern/src/api/__tests__/patrolPreflight.test.ts
@@ -55,6 +55,28 @@ describe('runPatrolPreflight', () => {
expect(result.cause).toBe('tool_choice_rejected');
});
+ it('round-trips the recorded_at fields used to render the "last verified" indicator', async () => {
+ // Pulse caches preflight outcomes server-side and surfaces them
+ // through /api/settings/ai. The same response shape is also
+ // returned from the live POST so the inline result panel can render
+ // a "last verified" timestamp without forking shapes.
+ 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.recorded_at).toBe('2026-05-10T13:54:11Z');
+ 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/frontend-modern/src/api/patrol.ts b/frontend-modern/src/api/patrol.ts
index 6b392ae414..6b51ddd8c4 100644
--- a/frontend-modern/src/api/patrol.ts
+++ b/frontend-modern/src/api/patrol.ts
@@ -676,6 +676,11 @@ export interface PatrolPreflightResponse {
description?: string;
recommendation?: string;
action?: string;
+ // Wall-clock time when this preflight was recorded by Pulse. Present
+ // on hydrated cached state from /api/settings/ai; the live POST
+ // response also returns these fields when populated server-side.
+ recorded_at?: string;
+ recorded_at_unix?: number;
}
export interface PatrolPreflightRequest {
diff --git a/frontend-modern/src/components/Settings/AIModelSelectionSection.tsx b/frontend-modern/src/components/Settings/AIModelSelectionSection.tsx
index 76b3c10f17..351c4c8ed3 100644
--- a/frontend-modern/src/components/Settings/AIModelSelectionSection.tsx
+++ b/frontend-modern/src/components/Settings/AIModelSelectionSection.tsx
@@ -59,6 +59,19 @@ const PatrolPreflightControl: Component<{ state: AISettingsState }> = (controlPr
return `${(ms / 1000).toFixed(1)}s`;
};
+ const formatRecordedAt = (unix?: number) => {
+ if (!unix) return '';
+ const ageMs = Date.now() - unix * 1000;
+ if (ageMs < 0 || !Number.isFinite(ageMs)) return '';
+ if (ageMs < 60_000) return 'just now';
+ const minutes = Math.floor(ageMs / 60_000);
+ if (minutes < 60) return `${minutes}m ago`;
+ const hours = Math.floor(minutes / 60);
+ if (hours < 24) return `${hours}h ago`;
+ const days = Math.floor(hours / 24);
+ return `${days}d ago`;
+ };
+
return (
<div class="mt-2 flex flex-col gap-2">
<div class="flex items-center justify-between gap-2">
@@ -91,11 +104,16 @@ const PatrolPreflightControl: Component<{ state: AISettingsState }> = (controlPr
<Show when={r().recommendation}>
<p class="text-[11px] mt-1 opacity-90">{r().recommendation}</p>
</Show>
- <Show when={r().provider || r().model}>
+ <Show when={r().provider || r().model || r().recorded_at_unix}>
<p class="text-[11px] mt-1 opacity-70">
{r().provider}
{r().provider && r().model ? ' · ' : ''}
{r().model}
+ <Show when={r().recorded_at_unix}>
+ {(r().provider || r().model ? ' · ' : '') +
+ 'last verified ' +
+ formatRecordedAt(r().recorded_at_unix)}
+ </Show>
</p>
</Show>
</div>
diff --git a/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts b/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts
index 33f06ed2ba..8f1367a433 100644
--- a/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts
+++ b/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts
@@ -244,6 +244,18 @@ describe('settings architecture guardrails', () => {
expect(aiModelSelectionSectionSource).not.toContain('fetch(\'/api/ai/patrol/preflight');
});
+ it('hydrates the Patrol preflight panel from the cached settings snapshot', () => {
+ // The cached preflight outcome arrives on /api/settings/ai as
+ // patrol_preflight; loadSettings and updateSettings must project it
+ // back into the inline result panel so the "last verified" state
+ // survives page reloads without forcing a re-click.
+ expect(aiSettingsStateSource).toContain('hydratePatrolPreflightFromSettings');
+ expect(aiSettingsStateSource).toContain('patrol_preflight');
+ expect(aiSettingsStateSource).toContain('recorded_at_unix');
+ expect(aiModelSelectionSectionSource).toContain('formatRecordedAt');
+ expect(aiModelSelectionSectionSource).toContain('last verified');
+ });
+
it('keeps contextual settings feature gates free of retired commercial telemetry wrappers', () => {
for (const source of [
agentProfilesPanelSource,
diff --git a/frontend-modern/src/components/Settings/useAISettingsState.ts b/frontend-modern/src/components/Settings/useAISettingsState.ts
index 1448f11642..9b48b7688c 100644
--- a/frontend-modern/src/components/Settings/useAISettingsState.ts
+++ b/frontend-modern/src/components/Settings/useAISettingsState.ts
@@ -247,6 +247,33 @@ export const useAISettingsState = () => {
const [patrolPreflightResult, setPatrolPreflightResult] =
createSignal<PatrolPreflightResponse | null>(null);
+ // hydratePatrolPreflightFromSettings projects the cached preflight
+ // snapshot from /api/settings/ai into the same response shape the
+ // manual Verify Patrol button writes, so the inline result panel can
+ // render the most-recent outcome on page load without forcing a
+ // re-click. Returns null when preflight has never run on the
+ // current Pulse instance.
+ const hydratePatrolPreflightFromSettings = (data: AISettingsType | null) => {
+ const snapshot = data?.patrol_preflight;
+ if (!snapshot) {
+ setPatrolPreflightResult(null);
+ return;
+ }
+ setPatrolPreflightResult({
+ success: snapshot.success,
+ provider: snapshot.provider,
+ model: snapshot.model,
+ tool_call_observed: snapshot.tool_call_observed,
+ duration_ms: snapshot.duration_ms,
+ message: snapshot.title || snapshot.summary || '',
+ cause: snapshot.cause,
+ summary: snapshot.summary,
+ recommendation: snapshot.recommendation,
+ recorded_at: snapshot.recorded_at,
+ recorded_at_unix: snapshot.recorded_at_unix,
+ });
+ };
+
const [showSetupModal, setShowSetupModal] = createSignal(false);
const [setupProvider, setSetupProvider] = createSignal<AIProvider>('anthropic');
const [setupApiKey, setSetupApiKey] = createSignal('');
@@ -599,6 +626,7 @@ export const useAISettingsState = () => {
setSettings(data);
resetForm(data);
syncModelCatalogForSettings(data);
+ hydratePatrolPreflightFromSettings(data);
void runProviderPreflight(data);
} catch (error) {
logger.error('[AISettings] Failed to load settings:', error);
@@ -609,6 +637,7 @@ export const useAISettingsState = () => {
setModelsError('');
setProviderHealth(createInitialProviderHealth());
setPreflightLastCheckedAt(null);
+ setPatrolPreflightResult(null);
} finally {
setLoading(false);
}
@@ -663,6 +692,7 @@ export const useAISettingsState = () => {
setForm('enabled', true);
resetForm(updated);
syncModelCatalogForSettings(updated);
+ hydratePatrolPreflightFromSettings(updated);
void runProviderPreflight(updated);
handleCloseSetupModal();
const patrolReadinessMessage = getAISettingsPatrolReadinessSaveMessage(
@@ -898,6 +928,7 @@ export const useAISettingsState = () => {
setSettings(updated);
resetForm(updated);
syncModelCatalogForSettings(updated);
+ hydratePatrolPreflightFromSettings(updated);
void runProviderPreflight(updated);
const patrolReadinessMessage = getAISettingsPatrolReadinessSaveMessage(
updated.patrol_readiness,
diff --git a/frontend-modern/src/types/ai.ts b/frontend-modern/src/types/ai.ts
index 72dc8f7e65..27ba33bed2 100644
--- a/frontend-modern/src/types/ai.ts
+++ b/frontend-modern/src/types/ai.ts
@@ -77,6 +77,25 @@ export interface AISettings {
// Current Pulse Patrol runtime readiness for this settings snapshot
patrol_readiness?: PatrolReadiness;
+ // Most recent Patrol tool-call preflight result, recorded by Pulse so
+ // the UI can render a "last verified" indicator without forcing
+ // operators to re-run preflight on every page load. Absent when
+ // preflight has never run on this Pulse instance.
+ patrol_preflight?: PatrolPreflightSnapshot;
+}
+
+export interface PatrolPreflightSnapshot {
+ success: boolean;
+ provider?: string;
+ model?: string;
+ tool_call_observed: boolean;
+ duration_ms: number;
+ cause?: string;
+ title?: string;
+ summary?: string;
+ recommendation?: string;
+ recorded_at: string;
+ recorded_at_unix: number;
}
export interface AISettingsUpdateRequest {
diff --git a/internal/ai/patrol_preflight.go b/internal/ai/patrol_preflight.go
index de47a354d8..2f5ee9e46d 100644
--- a/internal/ai/patrol_preflight.go
+++ b/internal/ai/patrol_preflight.go
@@ -3,6 +3,7 @@ package ai
import (
"context"
"strings"
+ "sync"
"time"
"github.com/rcourtman/pulse-go-rewrite/internal/ai/providers"
@@ -41,6 +42,41 @@ type PatrolPreflightResult struct {
// outside preflight has no operational meaning.
const patrolPreflightToolName = "verify_pulse_patrol"
+// patrolPreflightCache holds the most recent PatrolPreflightResult plus
+// the wall-clock time it was recorded. Surfaced through the AI settings
+// response so the UI can render a "last verified" indicator without
+// requiring operators to re-run preflight on every page load.
+type patrolPreflightCache struct {
+ mu sync.RWMutex
+ result *PatrolPreflightResult
+ recordedAt time.Time
+}
+
+// CachedPatrolPreflight returns the most recent preflight result and the
+// time it was recorded, or nil + zero time if preflight has never run on
+// this Service instance.
+func (s *Service) CachedPatrolPreflight() (*PatrolPreflightResult, time.Time) {
+ s.patrolPreflightCache.mu.RLock()
+ defer s.patrolPreflightCache.mu.RUnlock()
+ if s.patrolPreflightCache.result == nil {
+ return nil, time.Time{}
+ }
+ // Return a defensive copy so callers can't mutate the cache.
+ clone := *s.patrolPreflightCache.result
+ return &clone, s.patrolPreflightCache.recordedAt
+}
+
+// recordPatrolPreflight stores the result in the cache. Called after
+// every RunPatrolToolPreflight invocation so the most recent outcome is
+// always observable, including failures.
+func (s *Service) recordPatrolPreflight(result PatrolPreflightResult, at time.Time) {
+ s.patrolPreflightCache.mu.Lock()
+ defer s.patrolPreflightCache.mu.Unlock()
+ clone := result
+ s.patrolPreflightCache.result = &clone
+ s.patrolPreflightCache.recordedAt = at
+}
+
// 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
@@ -66,6 +102,7 @@ func (s *Service) RunPatrolToolPreflight(ctx context.Context, providerName, mode
result.Summary = "Pulse Assistant settings could not be loaded"
result.Recommendation = "Confirm Pulse settings persistence is healthy, then re-run preflight."
result.DurationMs = time.Since(started).Milliseconds()
+ s.recordPatrolPreflight(result, time.Now())
return result
}
if !cfg.Enabled {
@@ -74,6 +111,7 @@ func (s *Service) RunPatrolToolPreflight(ctx context.Context, providerName, mode
result.Summary = "Pulse Assistant is not enabled"
result.Recommendation = "Enable Pulse Assistant in Assistant & Patrol settings, then re-run preflight."
result.DurationMs = time.Since(started).Milliseconds()
+ s.recordPatrolPreflight(result, time.Now())
return result
}
@@ -87,6 +125,7 @@ func (s *Service) RunPatrolToolPreflight(ctx context.Context, providerName, mode
result.Summary = "Patrol has no model selected"
result.Recommendation = "Select a Patrol model in Assistant & Patrol settings, then re-run preflight."
result.DurationMs = time.Since(started).Milliseconds()
+ s.recordPatrolPreflight(result, time.Now())
return result
}
@@ -109,6 +148,7 @@ func (s *Service) RunPatrolToolPreflight(ctx context.Context, providerName, mode
if err != nil {
applyPatrolPreflightDiagnostic(&result, err)
result.DurationMs = time.Since(started).Milliseconds()
+ s.recordPatrolPreflight(result, time.Now())
return result
}
@@ -146,6 +186,7 @@ func (s *Service) RunPatrolToolPreflight(ctx context.Context, providerName, mode
if err != nil {
applyPatrolPreflightDiagnostic(&result, err)
+ s.recordPatrolPreflight(result, time.Now())
return result
}
@@ -155,6 +196,7 @@ func (s *Service) RunPatrolToolPreflight(ctx context.Context, providerName, mode
result.Cause = PatrolFailureCauseNone
result.Title = "Pulse Patrol: Preflight succeeded"
result.Summary = "Provider accepted the preflight request and the model emitted a tool call."
+ s.recordPatrolPreflight(result, time.Now())
return result
}
@@ -166,6 +208,7 @@ func (s *Service) RunPatrolToolPreflight(ctx context.Context, providerName, mode
result.Title = "Pulse Patrol: Model did not emit a tool call during preflight"
result.Summary = "Provider accepted the preflight request but the model did not emit a tool call. Patrol may still work in practice."
result.Recommendation = "Trigger a real Patrol run to confirm tool calling. If that fails, switch to a model with stronger tool-following behaviour."
+ s.recordPatrolPreflight(result, time.Now())
return result
}
diff --git a/internal/ai/patrol_preflight_test.go b/internal/ai/patrol_preflight_test.go
index b1f63dfce3..b973889ef3 100644
--- a/internal/ai/patrol_preflight_test.go
+++ b/internal/ai/patrol_preflight_test.go
@@ -203,6 +203,89 @@ func TestRunPatrolToolPreflight_NoModelSelected(t *testing.T) {
}
}
+func TestRunPatrolToolPreflight_PopulatesCacheOnSuccessAndFailure(t *testing.T) {
+ // Cache must reflect the most recent preflight outcome regardless of
+ // whether it succeeded, soft-warned, or failed — that's what powers
+ // the "last verified" indicator on the settings page.
+ called := 0
+ h := newPatrolPreflightTestService(t, "openai:gpt-4o-mini", func(w http.ResponseWriter, r *http.Request) {
+ called++
+ if called == 1 {
+ // First call: green path
+ 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}"}}]}}]}`))
+ return
+ }
+ // Second call: provider error
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(http.StatusBadRequest)
+ _, _ = w.Write([]byte(`{"error":{"message":"deepseek-reasoner does not support this tool_choice"}}`))
+ })
+ defer h.close()
+
+ // Cache is empty before any preflight runs.
+ cached, recordedAt := h.svc.CachedPatrolPreflight()
+ if cached != nil {
+ t.Fatalf("expected empty cache before first preflight, got %+v", cached)
+ }
+ if !recordedAt.IsZero() {
+ t.Fatalf("expected zero recorded time before first preflight, got %v", recordedAt)
+ }
+
+ // First run records the success path.
+ first := h.svc.RunPatrolToolPreflight(context.Background(), "", "")
+ if !first.Success {
+ t.Fatalf("expected first preflight to succeed, got %+v", first)
+ }
+ cached, recordedAt = h.svc.CachedPatrolPreflight()
+ if cached == nil || !cached.Success || !cached.ToolCallObserved {
+ t.Fatalf("cache did not capture success path, got %+v", cached)
+ }
+ if recordedAt.IsZero() {
+ t.Fatalf("expected non-zero recorded time after first preflight")
+ }
+ firstRecorded := recordedAt
+
+ // Second run records the failure path, superseding the first cache entry.
+ second := h.svc.RunPatrolToolPreflight(context.Background(), "", "")
+ if second.Success {
+ t.Fatalf("expected second preflight to fail, got %+v", second)
+ }
+ cached, recordedAt = h.svc.CachedPatrolPreflight()
+ if cached == nil || cached.Success {
+ t.Fatalf("cache did not capture failure path, got %+v", cached)
+ }
+ if cached.Cause != PatrolFailureCauseToolChoiceRejected {
+ t.Fatalf("cache did not preserve classified cause, got %q", cached.Cause)
+ }
+ if !recordedAt.After(firstRecorded) {
+ t.Fatalf("expected recorded time to advance, got %v -> %v", firstRecorded, recordedAt)
+ }
+}
+
+func TestCachedPatrolPreflight_ReturnsDefensiveCopy(t *testing.T) {
+ // Mutating the returned result must not corrupt the cache.
+ 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}"}}]}}]}`))
+ })
+ defer h.close()
+
+ _ = h.svc.RunPatrolToolPreflight(context.Background(), "", "")
+ cached, _ := h.svc.CachedPatrolPreflight()
+ if cached == nil {
+ t.Fatalf("expected cached result")
+ }
+ cached.Success = false
+ cached.Title = "tampered"
+
+ // Re-read should still show the original successful result.
+ again, _ := h.svc.CachedPatrolPreflight()
+ if !again.Success || again.Title == "tampered" {
+ t.Fatalf("cache returned mutable reference: original=%+v, re-read=%+v", cached, again)
+ }
+}
+
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/ai/service.go b/internal/ai/service.go
index 70a80212dc..82bdbbc5d8 100644
--- a/internal/ai/service.go
+++ b/internal/ai/service.go
@@ -218,6 +218,11 @@ type Service struct {
modelsCache modelsCache
+ // patrolPreflightCache holds the most recent preflight result for the
+ // configured Patrol provider+model so operators can see when tools
+ // were last verified without re-running the call.
+ patrolPreflightCache patrolPreflightCache
+
// License checker for Pro feature gating
licenseChecker LicenseChecker
}
diff --git a/internal/api/ai_handlers.go b/internal/api/ai_handlers.go
index 820720022a..237ba07caf 100644
--- a/internal/api/ai_handlers.go
+++ b/internal/api/ai_handlers.go
@@ -2253,6 +2253,27 @@ type AISettingsResponse struct {
DiscoveryIntervalHours int `json:"discovery_interval_hours,omitempty"` // Hours between auto-scans (0 = manual only)
// Current Patrol runtime readiness after this settings snapshot is applied.
PatrolReadiness *PatrolReadinessResponse `json:"patrol_readiness,omitempty"`
+ // Most recent Patrol tool-call preflight outcome, surfaced so the UI
+ // can render a "last verified" indicator without forcing operators
+ // to re-click Verify Patrol on every page load. nil when preflight
+ // has never run on this service instance.
+ PatrolPreflight *PatrolPreflightSnapshot `json:"patrol_preflight,omitempty"`
+}
+
+// PatrolPreflightSnapshot is the API-shaped projection of the cached
+// PatrolPreflightResult plus the wall-clock time it was recorded.
+type PatrolPreflightSnapshot struct {
+ Success bool `json:"success"`
+ Provider string `json:"provider,omitempty"`
+ Model string `json:"model,omitempty"`
+ ToolCallObserved bool `json:"tool_call_observed"`
+ DurationMs int64 `json:"duration_ms"`
+ Cause string `json:"cause,omitempty"`
+ Title string `json:"title,omitempty"`
+ Summary string `json:"summary,omitempty"`
+ Recommendation string `json:"recommendation,omitempty"`
+ RecordedAt string `json:"recorded_at"`
+ RecordedAtUnix int64 `json:"recorded_at_unix"`
}
func EmptyAISettingsResponse() AISettingsResponse {
@@ -2443,6 +2464,7 @@ func (h *AISettingsHandler) HandleGetAISettings(w http.ResponseWriter, r *http.R
ProtectedGuests: settings.GetProtectedGuests(),
DiscoveryEnabled: settings.IsDiscoveryEnabled(),
DiscoveryIntervalHours: settings.DiscoveryIntervalHours,
+ PatrolPreflight: cachedPatrolPreflightSnapshot(aiService),
}.NormalizeCollections()
if err := utils.WriteJSONResponse(w, response); err != nil {
@@ -2841,6 +2863,7 @@ func (h *AISettingsHandler) HandleUpdateAISettings(w http.ResponseWriter, r *htt
DiscoveryEnabled: settings.DiscoveryEnabled,
DiscoveryIntervalHours: settings.DiscoveryIntervalHours,
PatrolReadiness: ptrToPatrolReadiness(patrolReadiness),
+ PatrolPreflight: cachedPatrolPreflightSnapshot(aiService),
}.NormalizeCollections()
if err := utils.WriteJSONResponse(w, response); err != nil {
@@ -2848,6 +2871,32 @@ func (h *AISettingsHandler) HandleUpdateAISettings(w http.ResponseWriter, r *htt
}
}
+// cachedPatrolPreflightSnapshot projects the AI Service's cached
+// preflight result onto the API's wire shape. Returns nil when no
+// preflight has run on this service instance.
+func cachedPatrolPreflightSnapshot(aiService *ai.Service) *PatrolPreflightSnapshot {
+ if aiService == nil {
+ return nil
+ }
+ result, recordedAt := aiService.CachedPatrolPreflight()
+ if result == nil || recordedAt.IsZero() {
+ return nil
+ }
+ return &PatrolPreflightSnapshot{
+ Success: result.Success,
+ Provider: result.Provider,
+ Model: result.Model,
+ ToolCallObserved: result.ToolCallObserved,
+ DurationMs: result.DurationMs,
+ Cause: string(result.Cause),
+ Title: result.Title,
+ Summary: result.Summary,
+ Recommendation: result.Recommendation,
+ RecordedAt: recordedAt.UTC().Format(time.RFC3339),
+ RecordedAtUnix: recordedAt.Unix(),
+ }
+}
+
// HandleTestAIConnection tests the AI provider connection (POST /api/ai/test)
// Auth is enforced by RequirePermission middleware at route registration; with
// default authorizer, non-admin proxy users are hard-denied (with RBAC, deferred