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.

Canonicalize Patrol blocked runtime state

rcourtmanbe265ba9420a
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index 6d923d3048..8a833bbad3 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -171,6 +171,11 @@ metadata through the shared unified-resource helper before it returns
resource payloads, so lifecycle-adjacent links keep the same canonical
metadata pass as the rest of the resource API instead of composing local
attach wrappers.
+That same shared `internal/api/` dependency now also keeps Patrol runtime
+availability explicit as API-owned state. Lifecycle-adjacent setup and install
+flows may touch the shared AI handler layer, but they must not collapse a
+blocked Patrol runtime back into generic healthy status just because the last
+successful summary snapshot was green.
Invalid `sourceAdapter` values are rejected at the API boundary, so the fleet
lane continues to consume only the canonical adapter set rather than
introducing a broader compatibility escape hatch.
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 18900508f9..a4c3ffc0be 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -455,6 +455,14 @@ The frontend Patrol intelligence page now also consumes that canonical
summary payload directly through the shared AI client and store, so the
visible summary card stays aligned with the same recent-change slice that the
runtime and API contracts expose.
+The Patrol runtime now also exports a canonical `runtime_state` alongside
+`blocked_reason` in the Patrol status payload, so blocked quickstart-credit or
+provider-availability conditions remain part of the governed runtime contract
+instead of being inferred later from the last successful patrol summary.
+That runtime-state contract must be derived from live Patrol runtime inputs,
+not only from the last failed run attempt: exhausted quickstart credits are a
+blocked Patrol runtime immediately, and the backend must also clear any stale
+quickstart block once credits or BYOK configuration return.
AI chat tool-name labels, pending-tool headers, and assistant status copy now
also route through the shared frontend identifier-label helper, so the chat
surfaces do not keep their own underscore-stripping behavior separate from
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 0d8dd17650..74bf4ba637 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -131,7 +131,8 @@ Own canonical runtime payload shapes between backend and frontend.
10. Add or change infrastructure operations token generation, lookup, assignment, the pure unified-agent inventory/install model, the split infrastructure install/reporting state owners, the split direct-node/discovery infrastructure settings owners, the shared infrastructure-operations state provider/context shell, and reporting/install presentation through `frontend-modern/src/components/Settings/InfrastructureOperationsController.tsx`, `frontend-modern/src/components/Settings/infrastructureOperationsModel.tsx`, `frontend-modern/src/components/Settings/useInfrastructureConfiguredNodesState.ts`, `frontend-modern/src/components/Settings/useInfrastructureDiscoveryRuntimeState.ts`, `frontend-modern/src/components/Settings/useInfrastructureInstallState.tsx`, `frontend-modern/src/components/Settings/useInfrastructureOperationsState.tsx`, and `frontend-modern/src/components/Settings/useInfrastructureReportingState.tsx`
11. Keep `internal/api/session_store.go` on a fail-closed auth-persistence boundary: persisted OIDC refresh tokens may only round-trip through encrypted-at-rest session payloads, and any missing-crypto or invalid-ciphertext path must drop the token instead of preserving plaintext-at-rest session state.
12. Keep tenant AI handler wiring on canonical provider ownership: `internal/api/ai_handlers.go` may wire tenant `ReadState` and tenant-scoped unified-resource providers into AI services, but it must not revive tenant snapshot-provider bridges once Patrol can initialize and verify from those canonical providers directly.
-13. Keep Pulse Mobile relay credential minting and permission ownership on backend ownership: `internal/api/router_routes_auth_security.go`, `internal/api/security_tokens.go`, `internal/api/auth.go`, `internal/api/router_routes_ai_relay.go`, and `frontend-modern/src/api/security.ts` may expose the canonical mobile runtime token creator and governed route gates, but browser callers must only consume that route and must not define the mobile runtime scope, compatibility gate list, or token-purpose metadata locally.
+13. Keep Patrol status transport semantics explicit in that same AI handler layer: the Patrol status endpoint must carry machine-readable runtime availability such as blocked, running, disabled, active, or unavailable rather than asking frontend consumers to infer operator state from stale summaries or run history.
+14. Keep Pulse Mobile relay credential minting and permission ownership on backend ownership: `internal/api/router_routes_auth_security.go`, `internal/api/security_tokens.go`, `internal/api/auth.go`, `internal/api/router_routes_ai_relay.go`, and `frontend-modern/src/api/security.ts` may expose the canonical mobile runtime token creator and governed route gates, but browser callers must only consume that route and must not define the mobile runtime scope, compatibility gate list, or token-purpose metadata locally.
## Forbidden Paths
@@ -162,6 +163,7 @@ Own canonical runtime payload shapes between backend and frontend.
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
5. Keep `/api/resources` policy metadata aligned across backend payload tests and canonical frontend resource consumers whenever sensitivity or routing fields change
+6. Keep Patrol status payloads explicit enough that the frontend can present blocked runtime state without treating a previously healthy summary snapshot as current runtime truth
## Current State
@@ -1197,11 +1199,20 @@ That same frontend run-history path must also preserve and expose
deterministic triage-only runs do not collapse into generic "no analysis"
history entries.
Patrol status payloads now also treat quickstart credit state as canonical API
-contract data: `/api/ai/patrol/status` must surface
+contract data: the Patrol status endpoint must surface
`quickstart_credits_remaining`, `quickstart_credits_total`, and
`using_quickstart` directly from backend runtime state so the frontend can
render Patrol quickstart availability without local heuristics or shadow
derived state.
+That same Patrol status contract now also carries a canonical `runtime_state`
+field, so the frontend can distinguish blocked, running, disabled, active,
+and unavailable Patrol runtime states without deriving operator status from
+stale health summaries, last-run history, or local blocked-reason heuristics.
+The backend status payload must derive that blocked runtime state directly
+from current quickstart-credit availability, and it must clear stale
+quickstart-exhausted block metadata once credits or BYOK return, so
+the Patrol status endpoint cannot leave Patrol looking healthy or paused based on
+an out-of-date last-run artifact.
Patrol mutate endpoints that depend on the background service must also fail
closed with `503 Service Unavailable` when AI service initialization is absent
rather than dereferencing a nil service and crashing before a contract response
diff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
index 0df1bbc59f..d4ab9242d9 100644
--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md
+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
@@ -714,6 +714,10 @@ header/banner/summary/workspace section files under
`frontend-modern/src/features/patrol/` own the heavy render surfaces. Shared
shell governance should reinforce that pattern instead of letting feature render
surfaces re-accumulate API and timer orchestration inline.
+That same route-owned page-health rule now also applies to Patrol: a feature
+surface may not present a green or all-clear primary summary when the owning
+runtime contract says the page is blocked or unavailable, even if the last
+successful snapshot was healthy.
Shared primitive consumers that split status-dot tone and status-text tone
must now keep both values routed through the same exported presentation helper.
diff --git a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md b/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
index ab3416f65a..24760612a9 100644
--- a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
+++ b/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
@@ -45,7 +45,8 @@ Patrol-specific presentation helpers.
22. `frontend-modern/src/utils/patrolFormat.ts`
23. `frontend-modern/src/utils/patrolRunPresentation.ts`
24. `frontend-modern/src/utils/patrolSummaryPresentation.ts`
-25. `frontend-modern/src/utils/textPresentation.ts`
+25. `frontend-modern/src/utils/patrolRuntimePresentation.ts`
+26. `frontend-modern/src/utils/textPresentation.ts`
## Shared Boundaries
@@ -56,10 +57,11 @@ Patrol-specific presentation helpers.
1. Add or change Patrol page orchestration through `frontend-modern/src/features/patrol/usePatrolIntelligenceState.ts`, keep `frontend-modern/src/features/patrol/patrolInvestigationContextModel.ts` as the canonical investigation-context derivation owner, keep `frontend-modern/src/features/patrol/PatrolIntelligenceSurface.tsx` as the feature shell, keep the Patrol-owned section files under `frontend-modern/src/features/patrol/` as the heavy render owners, keep `frontend-modern/src/pages/AIIntelligence.tsx` as the route shell, keep `frontend-modern/src/stores/aiIntelligenceSummaryModel.ts` as the canonical AI summary normalization owner, and update `frontend-modern/src/stores/aiIntelligence.ts` together
2. Add or change Patrol findings, approvals, investigation, or run-history presentation through `frontend-modern/src/components/AI/FindingsPanel.tsx` and `frontend-modern/src/components/patrol/`
3. Keep remediation execution badge copy and severity styling aligned through `frontend-modern/src/components/patrol/RemediationStatus.tsx` and `frontend-modern/src/utils/remediationPresentation.ts`
-4. Add or change Patrol header quickstart-credit or schedule presentation through `frontend-modern/src/features/patrol/PatrolIntelligenceHeader.tsx`, `frontend-modern/src/utils/aiQuickstartPresentation.ts`, and `frontend-modern/src/utils/aiPatrolSchedulePresentation.ts`
-5. Keep Patrol and chat identifier-label presentation aligned through the shared `frontend-modern/src/utils/textPresentation.ts`
-6. Keep Patrol and chat stream-matching / mention dedupe aligned through the shared `frontend-modern/src/utils/chatIdentifiers.ts`
-7. Keep Patrol transport and payload changes aligned through the governed AI runtime and API contract transport surfaces
+4. Add or change Patrol header, summary, or status runtime-state presentation through `frontend-modern/src/features/patrol/PatrolIntelligenceHeader.tsx`, `frontend-modern/src/features/patrol/PatrolIntelligenceSummary.tsx`, `frontend-modern/src/components/patrol/PatrolStatusBar.tsx`, and `frontend-modern/src/utils/patrolRuntimePresentation.ts`
+5. Add or change Patrol header quickstart-credit or schedule presentation through `frontend-modern/src/features/patrol/PatrolIntelligenceHeader.tsx`, `frontend-modern/src/utils/aiQuickstartPresentation.ts`, and `frontend-modern/src/utils/aiPatrolSchedulePresentation.ts`
+6. Keep Patrol and chat identifier-label presentation aligned through the shared `frontend-modern/src/utils/textPresentation.ts`
+7. Keep Patrol and chat stream-matching / mention dedupe aligned through the shared `frontend-modern/src/utils/chatIdentifiers.ts`
+8. Keep Patrol transport and payload changes aligned through the governed AI runtime and API contract transport surfaces
## Forbidden Paths
@@ -98,6 +100,11 @@ semantics, and `frontend-modern/src/stores/aiIntelligenceSummaryModel.ts` now
owns the canonical summary normalization so Patrol consumers inherit one
governed recent-change and policy-posture snapshot instead of reintroducing
hook-local fallback logic.
+The Patrol page now also treats Patrol runtime availability as a first-class
+render contract: the header chip, primary summary card, and status bar must
+all route through the shared `frontend-modern/src/utils/patrolRuntimePresentation.ts`
+helper plus the backend `runtime_state` payload instead of inferring operator
+state from the last healthy summary snapshot or run history alone.
hook-local fallback logic.
The Patrol header now also has explicit helper ownership for its quickstart and
schedule presentation. `frontend-modern/src/utils/aiQuickstartPresentation.ts`
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index c2c1ab6b98..4897f37187 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -144,6 +144,10 @@ handlers stay on canonical Patrol runtime wiring: recovery- and
storage-adjacent API helpers must not revive tenant snapshot-provider bridges
through `internal/api/ai_handlers.go` once Patrol can initialize from tenant
`ReadState` and unified-resource providers directly.
+That same adjacent AI handler boundary now also keeps Patrol runtime
+availability explicit as API-owned state. Storage and recovery consumers may
+share the handler layer, but they must not treat a blocked Patrol runtime as
+healthy only because the last completed summary snapshot remained green.
That same shared dependency also assumes the Patrol-backed recent-changes
API surface reads through the canonical intelligence facade first, so
storage and recovery handlers do not bypass the shared unified timeline
diff --git a/frontend-modern/src/api/__tests__/patrol.test.ts b/frontend-modern/src/api/__tests__/patrol.test.ts
index 55bef82118..0c421da92d 100644
--- a/frontend-modern/src/api/__tests__/patrol.test.ts
+++ b/frontend-modern/src/api/__tests__/patrol.test.ts
@@ -5,6 +5,7 @@ vi.mock('@/utils/apiClient', () => ({
}));
import {
+ getPatrolStatus,
getPatrolRun,
getPatrolRunHistory,
getPatrolRunHistoryWithToolCalls,
@@ -58,6 +59,20 @@ describe('patrol api', () => {
);
});
+ it('preserves the canonical patrol runtime state payload', async () => {
+ apiFetchJSONMock.mockResolvedValueOnce({
+ runtime_state: 'blocked',
+ blocked_reason: 'Quickstart credits exhausted. Connect your API key to continue using AI Patrol.',
+ healthy: false,
+ } as any);
+
+ await expect(getPatrolStatus()).resolves.toMatchObject({
+ runtime_state: 'blocked',
+ blocked_reason: 'Quickstart credits exhausted. Connect your API key to continue using AI Patrol.',
+ healthy: false,
+ });
+ });
+
it('normalizes patrol run alert identifiers', async () => {
apiFetchJSONMock.mockResolvedValueOnce([
{
diff --git a/frontend-modern/src/api/patrol.ts b/frontend-modern/src/api/patrol.ts
index 489be53d61..865a474c97 100644
--- a/frontend-modern/src/api/patrol.ts
+++ b/frontend-modern/src/api/patrol.ts
@@ -138,8 +138,10 @@ export interface FindingsSummary {
}
export type LicenseStatus = 'none' | 'active' | 'expired' | 'grace_period';
+export type PatrolRuntimeState = 'unavailable' | 'disabled' | 'running' | 'blocked' | 'active';
export interface PatrolStatus {
+ runtime_state: PatrolRuntimeState;
running: boolean;
enabled: boolean;
last_patrol_at?: string;
diff --git a/frontend-modern/src/components/patrol/PatrolStatusBar.tsx b/frontend-modern/src/components/patrol/PatrolStatusBar.tsx
index ae6dd981b1..875fb105a3 100644
--- a/frontend-modern/src/components/patrol/PatrolStatusBar.tsx
+++ b/frontend-modern/src/components/patrol/PatrolStatusBar.tsx
@@ -6,11 +6,12 @@
*/
import { Component, createResource, createMemo, Show } from 'solid-js';
-import { getPatrolRunHistory, type PatrolRunRecord } from '@/api/patrol';
+import { getPatrolRunHistory, type PatrolRunRecord, type PatrolRuntimeState } from '@/api/patrol';
import { aiIntelligenceStore } from '@/stores/aiIntelligence';
import { formatRelativeTime } from '@/utils/format';
import { formatTriggerReason } from '@/utils/patrolFormat';
import { isPatrolRunHealthy } from '@/utils/patrolRunPresentation';
+import { getPatrolRuntimePresentation } from '@/utils/patrolRuntimePresentation';
import CheckCircleIcon from 'lucide-solid/icons/check-circle';
import AlertCircleIcon from 'lucide-solid/icons/alert-circle';
import AlertTriangleIcon from 'lucide-solid/icons/alert-triangle';
@@ -18,6 +19,8 @@ import AlertTriangleIcon from 'lucide-solid/icons/alert-triangle';
interface PatrolStatusBarProps {
enabled?: boolean;
refreshTrigger?: number;
+ runtimeState?: PatrolRuntimeState;
+ blockedReason?: string;
}
export const PatrolStatusBar: Component<PatrolStatusBarProps> = (props) => {
@@ -52,6 +55,18 @@ export const PatrolStatusBar: Component<PatrolStatusBarProps> = (props) => {
});
const circuitBreaker = () => aiIntelligenceStore.circuitBreakerStatus;
+ const runtimePresentation = createMemo(() =>
+ getPatrolRuntimePresentation(props.runtimeState, props.blockedReason),
+ );
+ const showRuntimeState = createMemo(() => {
+ const runtimeState = props.runtimeState;
+ return (
+ runtimeState === 'blocked' ||
+ runtimeState === 'disabled' ||
+ runtimeState === 'unavailable' ||
+ runtimeState === 'running'
+ );
+ });
return (
<Show when={!runs.loading && stats()}>
@@ -79,19 +94,49 @@ export const PatrolStatusBar: Component<PatrolStatusBarProps> = (props) => {
{/* Status */}
<div class="flex items-center gap-1.5">
<Show
- when={s().isHealthy}
+ when={showRuntimeState()}
fallback={
- <>
- <AlertCircleIcon class="w-3.5 h-3.5 text-amber-500" />
- <span class="text-amber-600 dark:text-amber-400 font-medium text-xs">
- Issues detected
+ <Show
+ when={s().isHealthy}
+ fallback={
+ <>
+ <AlertCircleIcon class="w-3.5 h-3.5 text-amber-500" />
+ <span class="text-amber-600 dark:text-amber-400 font-medium text-xs">
+ Issues detected
+ </span>
+ </>
+ }
+ >
+ <CheckCircleIcon class="w-3.5 h-3.5 text-green-500" />
+ <span class="text-green-600 dark:text-green-400 font-medium text-xs">
+ Running normally
</span>
- </>
+ </Show>
}
>
- <CheckCircleIcon class="w-3.5 h-3.5 text-green-500" />
- <span class="text-green-600 dark:text-green-400 font-medium text-xs">
- Running normally
+ <Show
+ when={runtimePresentation().tone === 'warning'}
+ fallback={
+ <Show
+ when={runtimePresentation().tone === 'error'}
+ fallback={<AlertCircleIcon class="w-3.5 h-3.5 text-blue-500" />}
+ >
+ <AlertTriangleIcon class="w-3.5 h-3.5 text-red-500" />
+ </Show>
+ }
+ >
+ <AlertTriangleIcon class="w-3.5 h-3.5 text-amber-500" />
+ </Show>
+ <span
+ class={`font-medium text-xs ${
+ runtimePresentation().tone === 'warning'
+ ? 'text-amber-600 dark:text-amber-400'
+ : runtimePresentation().tone === 'error'
+ ? 'text-red-600 dark:text-red-400'
+ : 'text-blue-600 dark:text-blue-400'
+ }`}
+ >
+ {runtimePresentation().label}
</span>
</Show>
</div>
diff --git a/frontend-modern/src/components/patrol/__tests__/PatrolStatusBar.test.tsx b/frontend-modern/src/components/patrol/__tests__/PatrolStatusBar.test.tsx
index 585e316f17..2d1c3d014a 100644
--- a/frontend-modern/src/components/patrol/__tests__/PatrolStatusBar.test.tsx
+++ b/frontend-modern/src/components/patrol/__tests__/PatrolStatusBar.test.tsx
@@ -62,6 +62,52 @@ describe('PatrolStatusBar', () => {
});
});
+ it('shows patrol paused when the runtime is blocked even if the last run was healthy', async () => {
+ getPatrolRunHistoryMock.mockResolvedValue([
+ {
+ id: 'run-healthy',
+ started_at: '2026-03-12T10:00:00Z',
+ completed_at: '2026-03-12T10:01:00Z',
+ duration_ms: 60000,
+ type: 'patrol',
+ resources_checked: 1,
+ nodes_checked: 0,
+ guests_checked: 0,
+ docker_checked: 0,
+ storage_checked: 0,
+ hosts_checked: 0,
+ pbs_checked: 0,
+ pmg_checked: 0,
+ kubernetes_checked: 0,
+ new_findings: 0,
+ existing_findings: 0,
+ rejected_findings: 0,
+ resolved_findings: 0,
+ auto_fix_count: 0,
+ findings_summary: 'All clear',
+ finding_ids: [],
+ error_count: 0,
+ status: 'healthy',
+ triage_flags: 0,
+ tool_call_count: 0,
+ },
+ ]);
+
+ render(() => (
+ <PatrolStatusBar
+ refreshTrigger={1}
+ runtimeState="blocked"
+ blockedReason="Quickstart credits exhausted. Connect your API key to continue using AI Patrol."
+ />
+ ));
+
+ await waitFor(() => {
+ expect(screen.getByText('Patrol Paused')).toBeInTheDocument();
+ });
+
+ expect(screen.queryByText('Running normally')).not.toBeInTheDocument();
+ });
+
it('shows issues detected when the last patrol run found issues without transport errors', async () => {
getPatrolRunHistoryMock.mockResolvedValue([
{
diff --git a/frontend-modern/src/features/patrol/PatrolIntelligenceHeader.tsx b/frontend-modern/src/features/patrol/PatrolIntelligenceHeader.tsx
index 7019e8f969..97fba0d34f 100644
--- a/frontend-modern/src/features/patrol/PatrolIntelligenceHeader.tsx
+++ b/frontend-modern/src/features/patrol/PatrolIntelligenceHeader.tsx
@@ -12,6 +12,7 @@ import { formatRelativeTime } from '@/utils/format';
import { groupModelsByProvider } from '@/utils/patrolFormat';
import { getAIQuickstartCreditsPresentation } from '@/utils/aiQuickstartPresentation';
import { buildPatrolScheduleOptions } from '@/utils/aiPatrolSchedulePresentation';
+import { getPatrolRuntimePresentation } from '@/utils/patrolRuntimePresentation';
import type { PatrolIntelligenceState } from './usePatrolIntelligenceState';
export function PatrolIntelligenceHeader(props: { state: PatrolIntelligenceState }) {
@@ -22,8 +23,9 @@ export function PatrolIntelligenceHeader(props: { state: PatrolIntelligenceState
state.patrolStatus()?.quickstart_credits_total ?? 0,
),
);
- const scheduleOptions = createMemo(() =>
- buildPatrolScheduleOptions(state.patrolInterval()),
+ const scheduleOptions = createMemo(() => buildPatrolScheduleOptions(state.patrolInterval()));
+ const runtimePresentation = createMemo(() =>
+ getPatrolRuntimePresentation(state.runtimeState(), state.blockedReason()),
);
const patrolModelStale = createMemo(() => {
const model = state.patrolModel();
@@ -111,9 +113,7 @@ export function PatrolIntelligenceHeader(props: { state: PatrolIntelligenceState
size="sm"
ariaLabel="Toggle Patrol"
/>
- <span class="text-sm font-medium text-base-content">
- {state.patrolEnabledLocal() ? 'Patrol Active' : 'Patrol Disabled'}
- </span>
+ <span class="text-sm font-medium text-base-content">{runtimePresentation().label}</span>
</div>
<Show
@@ -238,8 +238,7 @@ export function PatrolIntelligenceHeader(props: { state: PatrolIntelligenceState
<For each={['monitor', 'approval', 'assisted'] as const}>
{(level) => {
const isProLocked = () =>
- state.autoFixLocked() &&
- (level === 'approval' || level === 'assisted');
+ state.autoFixLocked() && (level === 'approval' || level === 'assisted');
const isDisabled = () => !state.patrolEnabledLocal() || isProLocked();
const isActive = () =>
level === 'assisted'
@@ -369,8 +368,7 @@ export function PatrolIntelligenceHeader(props: { state: PatrolIntelligenceState
onChange={(e) => state.setFullModeUnlocked(e.currentTarget.checked)}
disabled={
state.autoFixLocked() ||
- !(state.autonomyLevel() === 'assisted' ||
- state.autonomyLevel() === 'full')
+ !(state.autonomyLevel() === 'assisted' || state.autonomyLevel() === 'full')
}
/>
</div>
diff --git a/frontend-modern/src/features/patrol/PatrolIntelligenceSummary.tsx b/frontend-modern/src/features/patrol/PatrolIntelligenceSummary.tsx
index 83824b4ca7..f7cb5b03d1 100644
--- a/frontend-modern/src/features/patrol/PatrolIntelligenceSummary.tsx
+++ b/frontend-modern/src/features/patrol/PatrolIntelligenceSummary.tsx
@@ -2,10 +2,17 @@ import { createMemo, Show } from 'solid-js';
import ActivityIcon from 'lucide-solid/icons/activity';
import ShieldAlertIcon from 'lucide-solid/icons/shield-alert';
import CheckCircleIcon from 'lucide-solid/icons/check-circle';
-import { getPatrolSummaryPresentation, PATROL_NO_ISSUES_LABEL } from '@/utils/patrolSummaryPresentation';
+import AlertCircleIcon from 'lucide-solid/icons/alert-circle';
+import {
+ getPatrolSummaryPresentation,
+ PATROL_NO_ISSUES_LABEL,
+} from '@/utils/patrolSummaryPresentation';
+import { getPatrolRuntimePresentation } from '@/utils/patrolRuntimePresentation';
+import { getSemanticTonePresentation } from '@/utils/semanticTonePresentation';
import { ResourcePolicySummary } from '@/components/Infrastructure/ResourcePolicySummary';
import { ResourceCorrelationSummary } from '@/components/Infrastructure/ResourceCorrelationSummary';
import { ResourceChangeSummary } from '@/components/Infrastructure/ResourceChangeSummary';
+import { formatRelativeTime } from '@/utils/format';
import type { PatrolIntelligenceState } from './usePatrolIntelligenceState';
export function PatrolIntelligenceSummary(props: { state: PatrolIntelligenceState }) {
@@ -19,103 +26,147 @@ export function PatrolIntelligenceSummary(props: { state: PatrolIntelligenceStat
const fixedSummaryPresentation = createMemo(() =>
getPatrolSummaryPresentation('success', state.summaryStats().fixedCount > 0),
);
+ const runtimePresentation = createMemo(() =>
+ getPatrolRuntimePresentation(state.runtimeState(), state.blockedReason()),
+ );
+ const runtimeTonePresentation = createMemo(() =>
+ getSemanticTonePresentation(runtimePresentation().tone),
+ );
+ const showRuntimeSummary = createMemo(() => {
+ const runtimeState = state.runtimeState();
+ return (
+ runtimeState === 'blocked' || runtimeState === 'disabled' || runtimeState === 'unavailable'
+ );
+ });
return (
<>
- <Show when={state.intelligenceSummary()}>
- {(summary) => (
- <section class="rounded-md border border-border bg-surface p-4">
- <div class="flex flex-wrap items-start justify-between gap-4">
- <div>
- <p class="text-xs font-semibold uppercase tracking-[0.16em] text-muted">
- Patrol summary
+ <Show when={showRuntimeSummary()}>
+ <section class={`rounded-md border p-4 ${runtimeTonePresentation().panelClass}`}>
+ <div class="flex items-start gap-3">
+ <div class="flex-shrink-0 rounded-md bg-base/70 p-2">
+ <AlertCircleIcon class={`w-5 h-5 ${runtimeTonePresentation().iconClass}`} />
+ </div>
+ <div>
+ <p class="text-xs font-semibold uppercase tracking-[0.16em] text-muted">
+ {runtimePresentation().title}
+ </p>
+ <h2 class="mt-1 text-lg font-semibold text-base-content">
+ {runtimePresentation().label}
+ </h2>
+ <p class="mt-1 text-sm text-base-content">{runtimePresentation().description}</p>
+ <Show when={state.patrolStatus()?.last_patrol_at}>
+ <p class="mt-2 text-xs text-muted">
+ Last completed patrol{' '}
+ {formatRelativeTime(state.patrolStatus()!.last_patrol_at, {
+ compact: true,
+ emptyText: 'never',
+ })}
+ .
</p>
- <h2 class="mt-1 text-lg font-semibold text-base-content">
- Health {summary().overall_health.grade} ·{' '}
- {Math.round(summary().overall_health.score)}/100
- </h2>
- <p class="mt-1 text-sm text-muted">{summary().overall_health.prediction}</p>
- </div>
-
- <div class="flex flex-wrap items-center gap-2">
- <span class="rounded-full border border-border-subtle bg-base px-2.5 py-1 text-xs font-medium text-base-content">
- Critical {summary().findings_count.critical}
- </span>
- <span class="rounded-full border border-border-subtle bg-base px-2.5 py-1 text-xs font-medium text-base-content">
- Warning {summary().findings_count.warning}
- </span>
- </div>
+ </Show>
</div>
+ </div>
+ </section>
+ </Show>
- <Show when={state.hasInvestigationContext()}>
- <div class="mt-4 rounded-md border border-border-subtle bg-base p-3">
- <div class="flex flex-wrap items-start justify-between gap-3">
- <div>
- <p class="text-xs font-semibold uppercase tracking-[0.16em] text-muted">
- Investigation context
- </p>
- <p class="mt-1 text-sm text-muted">
- Secondary change and policy signals for deeper investigation.
- </p>
- <Show when={state.investigationContextSummary()}>
- <p class="mt-1 text-xs text-base-content">
- {state.investigationContextSummary()}
- </p>
- </Show>
- </div>
+ <Show when={!showRuntimeSummary()}>
+ <Show when={state.intelligenceSummary()}>
+ {(summary) => (
+ <section class="rounded-md border border-border bg-surface p-4">
+ <div class="flex flex-wrap items-start justify-between gap-4">
+ <div>
+ <p class="text-xs font-semibold uppercase tracking-[0.16em] text-muted">
+ Patrol summary
+ </p>
+ <h2 class="mt-1 text-lg font-semibold text-base-content">
+ Health {summary().overall_health.grade} ·{' '}
+ {Math.round(summary().overall_health.score)}/100
+ </h2>
+ <p class="mt-1 text-sm text-muted">{summary().overall_health.prediction}</p>
+ </div>
- <button
- type="button"
- onClick={() => state.setShowInvestigationContext((value) => !value)}
- class="inline-flex items-center rounded-md border border-border bg-surface px-3 py-1.5 text-xs font-medium text-base-content transition-colors hover:bg-surface-hover"
- >
- {state.showInvestigationContext() ? 'Hide context' : 'Show context'}
- </button>
+ <div class="flex flex-wrap items-center gap-2">
+ <span class="rounded-full border border-border-subtle bg-base px-2.5 py-1 text-xs font-medium text-base-content">
+ Critical {summary().findings_count.critical}
+ </span>
+ <span class="rounded-full border border-border-subtle bg-base px-2.5 py-1 text-xs font-medium text-base-content">
+ Warning {summary().findings_count.warning}
+ </span>
</div>
+ </div>
+
+ <Show when={state.hasInvestigationContext()}>
+ <div class="mt-4 rounded-md border border-border-subtle bg-base p-3">
+ <div class="flex flex-wrap items-start justify-between gap-3">
+ <div>
+ <p class="text-xs font-semibold uppercase tracking-[0.16em] text-muted">
+ Investigation context
+ </p>
+ <p class="mt-1 text-sm text-muted">
+ Secondary change and policy signals for deeper investigation.
+ </p>
+ <Show when={state.investigationContextSummary()}>
+ <p class="mt-1 text-xs text-base-content">
+ {state.investigationContextSummary()}
+ </p>
+ </Show>
+ </div>
- <Show when={state.showInvestigationContext()}>
- <div class="mt-4 grid gap-4 lg:grid-cols-[minmax(0,1.4fr)_minmax(0,1fr)]">
- <Show when={state.recentChangeCount() > 0}>
- <ResourceChangeSummary
- class="space-y-0"
- title="Recent changes"
- subtitle="Last 24 hours"
- changes={summary().recent_changes}
- maxChanges={3}
- compact
- />
- </Show>
+ <button
+ type="button"
+ onClick={() => state.setShowInvestigationContext((value) => !value)}
+ class="inline-flex items-center rounded-md border border-border bg-surface px-3 py-1.5 text-xs font-medium text-base-content transition-colors hover:bg-surface-hover"
+ >
+ {state.showInvestigationContext() ? 'Hide context' : 'Show context'}
+ </button>
+ </div>
- <div class="space-y-4">
- <Show when={state.correlations().length > 0}>
- <ResourceCorrelationSummary
- title="Correlations"
- correlations={state.correlations()}
- summaryText={`${state.correlationTotal()} total`}
+ <Show when={state.showInvestigationContext()}>
+ <div class="mt-4 grid gap-4 lg:grid-cols-[minmax(0,1.4fr)_minmax(0,1fr)]">
+ <Show when={state.recentChangeCount() > 0}>
+ <ResourceChangeSummary
+ class="space-y-0"
+ title="Recent changes"
+ subtitle="Last 24 hours"
+ changes={summary().recent_changes}
+ maxChanges={3}
+ compact
/>
</Show>
- <ResourcePolicySummary
- posture={state.policyPosture()}
- title="Policy posture"
- />
+ <div class="space-y-4">
+ <Show when={state.correlations().length > 0}>
+ <ResourceCorrelationSummary
+ title="Correlations"
+ correlations={state.correlations()}
+ summaryText={`${state.correlationTotal()} total`}
+ />
+ </Show>
+
+ <ResourcePolicySummary
+ posture={state.policyPosture()}
+ title="Policy posture"
+ />
+ </div>
</div>
- </div>
- </Show>
- </div>
- </Show>
- </section>
- )}
+ </Show>
+ </div>
+ </Show>
+ </section>
+ )}
+ </Show>
</Show>
<Show
when={
- state.summaryStats().criticalFindings > 0 ||
- state.summaryStats().warningFindings > 0 ||
- state.summaryStats().fixedCount > 0
+ !showRuntimeSummary() &&
+ (state.summaryStats().criticalFindings > 0 ||
+ state.summaryStats().warningFindings > 0 ||
+ state.summaryStats().fixedCount > 0)
}
fallback={
- <Show when={state.patrolStatus()?.last_patrol_at}>
+ <Show when={!showRuntimeSummary() && state.patrolStatus()?.last_patrol_at}>
<div class="flex items-center gap-2 px-4 py-3 bg-surface rounded-md border border-border">
<CheckCircleIcon class="w-4 h-4 text-green-500 dark:text-green-400" />
<span class="text-sm text-muted">{PATROL_NO_ISSUES_LABEL}</span>
diff --git a/frontend-modern/src/features/patrol/PatrolIntelligenceWorkspace.tsx b/frontend-modern/src/features/patrol/PatrolIntelligenceWorkspace.tsx
index 6a22f4e91a..3580275e35 100644
--- a/frontend-modern/src/features/patrol/PatrolIntelligenceWorkspace.tsx
+++ b/frontend-modern/src/features/patrol/PatrolIntelligenceWorkspace.tsx
@@ -30,6 +30,8 @@ export function PatrolIntelligenceWorkspace(props: { state: PatrolIntelligenceSt
<PatrolStatusBar
enabled={state.patrolEnabledLocal()}
refreshTrigger={state.activityRefreshTrigger()}
+ runtimeState={state.runtimeState()}
+ blockedReason={state.blockedReason()}
/>
<div class="flex items-center gap-1 border-b border-border">
diff --git a/frontend-modern/src/features/patrol/usePatrolIntelligenceState.ts b/frontend-modern/src/features/patrol/usePatrolIntelligenceState.ts
index b9409d9f7b..a7e0b19d63 100644
--- a/frontend-modern/src/features/patrol/usePatrolIntelligenceState.ts
+++ b/frontend-modern/src/features/patrol/usePatrolIntelligenceState.ts
@@ -14,6 +14,7 @@ import {
updatePatrolAutonomySettings,
type PatrolAutonomyLevel,
type PatrolRunRecord,
+ type PatrolRuntimeState,
type PatrolStatus,
} from '@/api/patrol';
import { aiIntelligenceStore } from '@/stores/aiIntelligence';
@@ -387,13 +388,19 @@ export function usePatrolIntelligenceState() {
const licenseRequired = createMemo(() => patrolStatus()?.license_required ?? false);
const upgradeUrl = createMemo(() => getUpgradeActionUrlOrFallback('ai_autofix'));
const alertAnalysisUpgradeUrl = createMemo(() => getUpgradeActionUrlOrFallback('ai_alerts'));
+ const runtimeState = createMemo<PatrolRuntimeState>(() => {
+ if (!patrolEnabledLocal()) return 'disabled';
+ return patrolStatus()?.runtime_state ?? 'active';
+ });
const blockedReason = createMemo(() => patrolStatus()?.blocked_reason?.trim() ?? '');
const blockedAt = createMemo(() => patrolStatus()?.blocked_at);
- const showBlockedBanner = createMemo(() => patrolEnabledLocal() && !!blockedReason());
- const canTriggerPatrol = createMemo(() => patrolEnabledLocal() && !showBlockedBanner());
+ const showBlockedBanner = createMemo(() => runtimeState() === 'blocked');
+ const canTriggerPatrol = createMemo(() => runtimeState() === 'active');
const triggerPatrolDisabledReason = createMemo(() => {
- if (!patrolEnabledLocal()) return 'Patrol is disabled';
- if (showBlockedBanner()) return blockedReason() || 'Patrol is paused';
+ if (runtimeState() === 'disabled') return 'Patrol is disabled';
+ if (runtimeState() === 'blocked') return blockedReason() || 'Patrol is paused';
+ if (runtimeState() === 'running') return 'Patrol is already running';
+ if (runtimeState() === 'unavailable') return 'Patrol service is unavailable';
return '';
});
@@ -595,7 +602,8 @@ export function usePatrolIntelligenceState() {
const summaryStats = () => {
const allFindings = aiIntelligenceStore.findings;
const patrolFindings = allFindings.filter(
- (finding) => finding.source !== 'threshold' && !finding.isThreshold && !hasTriggeringAlert(finding),
+ (finding) =>
+ finding.source !== 'threshold' && !finding.isThreshold && !hasTriggeringAlert(finding),
);
const activeFindings = patrolFindings.filter((finding) => finding.status === 'active');
@@ -694,6 +702,7 @@ export function usePatrolIntelligenceState() {
patrolInterval,
patrolModel,
patrolRunHistory,
+ runtimeState,
patrolStatus,
patrolStream,
policyPosture,
diff --git a/frontend-modern/src/pages/__tests__/AIIntelligence.test.tsx b/frontend-modern/src/pages/__tests__/AIIntelligence.test.tsx
index c2245144e7..accf6f3da2 100644
--- a/frontend-modern/src/pages/__tests__/AIIntelligence.test.tsx
+++ b/frontend-modern/src/pages/__tests__/AIIntelligence.test.tsx
@@ -18,78 +18,73 @@ const { findingsPanelState, runHistoryState, intelligenceState } = vi.hoisted(()
selection: null as Record<string, unknown> | null,
},
intelligenceState: {
- summary: null as
- | {
- timestamp: string;
- overall_health: {
- score: number;
- grade: 'A' | 'B' | 'C' | 'D' | 'F';
- trend: 'improving' | 'stable' | 'declining';
- factors: Array<Record<string, unknown>>;
- prediction: string;
- };
- findings_count: {
- critical: number;
- warning: number;
- watch: number;
- info: number;
- total: number;
- };
- predictions_count: number;
- recent_changes_count: number;
- recent_changes: Array<{
- id: string;
- observedAt: string;
- resourceId: string;
- kind: string;
- sourceType: string;
- sourceAdapter?: string;
- confidence: string;
- reason?: string;
- relatedResources?: string[];
- }>;
- policy_posture?: {
- total_resources: number;
- sensitivity_counts: Record<string, number>;
- routing_counts: Record<string, number>;
- redaction_counts?: Record<string, number>;
- };
- learning: {
- resources_with_knowledge: number;
- total_notes: number;
- resources_with_baselines: number;
- patterns_detected: number;
- correlations_learned: number;
- incidents_tracked: number;
- };
- }
- | null,
- correlations: null as
- | {
- correlations: Array<{
- source_id: string;
- source_name: string;
- source_type: string;
- target_id: string;
- target_name: string;
- target_type: string;
- event_pattern: string;
- occurrences: number;
- avg_delay: number | string;
- confidence: number;
- last_seen: string;
- description?: string;
- }>;
- count: number;
- }
- | null,
+ summary: null as {
+ timestamp: string;
+ overall_health: {
+ score: number;
+ grade: 'A' | 'B' | 'C' | 'D' | 'F';
+ trend: 'improving' | 'stable' | 'declining';
+ factors: Array<Record<string, unknown>>;
+ prediction: string;
+ };
+ findings_count: {
+ critical: number;
+ warning: number;
+ watch: number;
+ info: number;
+ total: number;
+ };
+ predictions_count: number;
+ recent_changes_count: number;
+ recent_changes: Array<{
+ id: string;
+ observedAt: string;
+ resourceId: string;
+ kind: string;
+ sourceType: string;
+ sourceAdapter?: string;
+ confidence: string;
+ reason?: string;
+ relatedResources?: string[];
+ }>;
+ policy_posture?: {
+ total_resources: number;
+ sensitivity_counts: Record<string, number>;
+ routing_counts: Record<string, number>;
+ redaction_counts?: Record<string, number>;
+ };
+ learning: {
+ resources_with_knowledge: number;
+ total_notes: number;
+ resources_with_baselines: number;
+ patterns_detected: number;
+ correlations_learned: number;
+ incidents_tracked: number;
+ };
+ } | null,
+ correlations: null as {
+ correlations: Array<{
+ source_id: string;
+ source_name: string;
+ source_type: string;
+ target_id: string;
+ target_name: string;
+ target_type: string;
+ event_pattern: string;
+ occurrences: number;
+ avg_delay: number | string;
+ confidence: number;
+ last_seen: string;
+ description?: string;
+ }>;
+ count: number;
+ } | null,
},
}));
const getCorrelationsMock = vi.fn();
-const [correlationsState, setCorrelationsState] = createSignal<
- (typeof intelligenceState)['correlations']
->(null);
+const [correlationsState, setCorrelationsState] =
+ createSignal<(typeof intelligenceState)['correlations']>(null);
const getPatrolStatusMock = vi.fn();
const getPatrolAutonomySettingsMock = vi.fn();
const updatePatrolAutonomySettingsMock = vi.fn();
@@ -182,8 +177,7 @@ vi.mock('@/stores/aiIntelligence', () => {
vi.mock('@/components/AI/FindingsPanel', () => ({
FindingsPanel: (props: Record<string, unknown>) => {
findingsPanelState.latestProps = {
- filterOverride:
- typeof props.filterOverride === 'string' ? props.filterOverride : undefined,
+ filterOverride: typeof props.filterOverride === 'string' ? props.filterOverride : undefined,
filterFindingIds: Array.isArray(props.filterFindingIds)
? [...(props.filterFindingIds as string[])]
: undefined,
@@ -203,9 +197,7 @@ vi.mock('@/components/AI/FindingsPanel', () => ({
vi.mock('@/components/patrol', () => ({
ApprovalBanner: () => <div data-testid="approval-banner" />,
PatrolStatusBar: () => <div data-testid="patrol-status-bar" />,
- RunHistoryPanel: (props: {
- onSelectRun?: (run: Record<string, unknown> | null) => void;
- }) => (
+ RunHistoryPanel: (props: { onSelectRun?: (run: Record<string, unknown> | null) => void }) => (
<div data-testid="run-history-panel">
<button type="button" onClick={() => props.onSelectRun?.(runHistoryState.selection)}>
Select mocked run
@@ -225,10 +217,7 @@ vi.mock('@/hooks/usePatrolStream', () => ({
}));
vi.mock('@/components/shared/PageHeader', () => ({
- PageHeader: (props: {
- title?: string;
- actions?: unknown;
- }) => (
+ PageHeader: (props: { title?: string; actions?: unknown }) => (
<div>
<h1>{props.title}</h1>
<div>{props.actions as any}</div>
@@ -270,6 +259,7 @@ vi.mock('@/components/Brand/PulsePatrolLogo', () => ({
}));
const defaultPatrolStatus = (overrides: Record<string, unknown> = {}) => ({
+ runtime_state: 'active',
running: false,
using_quickstart: false,
quickstart_credits_total: 0,
@@ -342,7 +332,9 @@ describe('AIIntelligence entitlement gating', () => {
}
return {};
});
- hasFeatureMock.mockImplementation((feature: string) => !['ai_alerts', 'ai_autofix'].includes(feature));
+ hasFeatureMock.mockImplementation(
+ (feature: string) => !['ai_alerts', 'ai_autofix'].includes(feature),
+ );
licenseStatusMock.mockReturnValue({ subscription_state: 'expired' });
loadLicenseStatusMock.mockResolvedValue(undefined);
startProTrialMock.mockResolvedValue({ outcome: 'started' });
@@ -441,13 +433,14 @@ describe('AIIntelligence entitlement gating', () => {
name: 'Open source resource Storage 1 in Infrastructure',
});
expect(storage2Link).toHaveAttribute('href', '/infrastructure?resource=storage-2');
- expect(screen.getByRole('link', { name: 'Open target resource VM 200 in Infrastructure' }))
- .toHaveAttribute('href', '/infrastructure?resource=vm-200');
- expect(screen.getByRole('link', { name: 'Open target resource VM 100 in Infrastructure' }))
- .toHaveAttribute('href', '/infrastructure?resource=vm-100');
expect(
- storage2Link.compareDocumentPosition(storage1Link) &
- Node.DOCUMENT_POSITION_FOLLOWING,
+ screen.getByRole('link', { name: 'Open target resource VM 200 in Infrastructure' }),
+ ).toHaveAttribute('href', '/infrastructure?resource=vm-200');
+ expect(
+ screen.getByRole('link', { name: 'Open target resource VM 100 in Infrastructure' }),
+ ).toHaveAttribute('href', '/infrastructure?resource=vm-100');
+ expect(
+ storage2Link.compareDocumentPosition(storage1Link) & Node.DOCUMENT_POSITION_FOLLOWING,
).toBeTruthy();
expect(screen.getByText('Storage 1')).toBeInTheDocument();
expect(screen.getByText('VM 100')).toBeInTheDocument();
@@ -626,6 +619,64 @@ describe('AIIntelligence entitlement gating', () => {
expect(screen.getByText('IP Address 1')).toBeInTheDocument();
});
+ it('does not present a healthy patrol summary when patrol is blocked on exhausted quickstart credits', async () => {
+ hasFeatureMock.mockReturnValue(true);
+ licenseStatusMock.mockReturnValue({ subscription_state: 'active' });
+ getPatrolStatusMock.mockResolvedValue(
+ defaultPatrolStatus({
+ runtime_state: 'blocked',
+ using_quickstart: true,
+ quickstart_credits_total: 25,
+ quickstart_credits_remaining: 0,
+ blocked_reason:
+ 'Quickstart credits exhausted. Connect your API key to continue using AI Patrol.',
+ last_patrol_at: '2026-03-12T09:57:00Z',
+ }),
+ );
+ intelligenceState.summary = {
+ timestamp: '2026-03-12T10:00:00Z',
+ overall_health: {
+ score: 100,
+ grade: 'A',
+ trend: 'stable',
+ factors: [],
+ prediction: 'Infrastructure is healthy with no significant issues detected.',
+ },
+ findings_count: {
+ critical: 0,
+ warning: 0,
+ watch: 0,
+ info: 0,
+ total: 0,
+ },
+ predictions_count: 0,
+ recent_changes_count: 0,
+ learning: {
+ resources_with_knowledge: 0,
+ total_notes: 0,
+ resources_with_baselines: 0,
+ patterns_detected: 0,
+ correlations_learned: 0,
+ incidents_tracked: 0,
+ },
+ };
+
+ render(() => <AIIntelligence />);
+
+ await waitFor(() => {
+ expect(getPatrolStatusMock).toHaveBeenCalled();
+ expect(screen.getAllByText('Patrol Paused')).toHaveLength(2);
+ });
+
+ expect(screen.getAllByText('Patrol paused').length).toBeGreaterThan(0);
+ expect(
+ screen.getAllByText(
+ 'Quickstart credits exhausted. Connect your API key to continue using AI Patrol.',
+ ).length,
+ ).toBeGreaterThan(0);
+ expect(screen.queryByText(/Health A · 100\/100/)).not.toBeInTheDocument();
+ });
+
it('treats a selected zero-finding run as an empty snapshot and uses effective scope ids', async () => {
hasFeatureMock.mockReturnValue(true);
licenseStatusMock.mockReturnValue({ subscription_state: 'active' });
diff --git a/frontend-modern/src/utils/patrolRuntimePresentation.ts b/frontend-modern/src/utils/patrolRuntimePresentation.ts
new file mode 100644
index 0000000000..3869089115
--- /dev/null
+++ b/frontend-modern/src/utils/patrolRuntimePresentation.ts
@@ -0,0 +1,55 @@
+import type { PatrolRuntimeState } from '@/api/patrol';
+import type { SemanticTone } from '@/utils/semanticTonePresentation';
+
+export interface PatrolRuntimePresentation {
+ label: string;
+ title: string;
+ description: string;
+ tone: SemanticTone;
+}
+
+export function getPatrolRuntimePresentation(
+ runtimeState: PatrolRuntimeState | undefined,
+ blockedReason?: string,
+): PatrolRuntimePresentation {
+ switch (runtimeState) {
+ case 'blocked':
+ return {
+ label: 'Patrol Paused',
+ title: 'Patrol paused',
+ description:
+ blockedReason?.trim() ||
+ 'Pulse Patrol cannot start new analysis until the blocking condition is cleared.',
+ tone: 'warning',
+ };
+ case 'disabled':
+ return {
+ label: 'Patrol Disabled',
+ title: 'Patrol disabled',
+ description: 'Enable Patrol to resume monitoring and analysis.',
+ tone: 'info',
+ };
+ case 'running':
+ return {
+ label: 'Patrol Running',
+ title: 'Patrol running',
+ description: 'Pulse Patrol is actively analyzing your infrastructure.',
+ tone: 'info',
+ };
+ case 'unavailable':
+ return {
+ label: 'Patrol Unavailable',
+ title: 'Patrol unavailable',
+ description: 'Pulse Patrol is not ready yet. Check AI settings and runtime availability.',
+ tone: 'error',
+ };
+ case 'active':
+ default:
+ return {
+ label: 'Patrol Active',
+ title: 'Patrol summary',
+ description: 'Pulse Patrol is monitoring your infrastructure.',
+ tone: 'success',
+ };
+ }
+}
diff --git a/internal/ai/patrol.go b/internal/ai/patrol.go
index c79a456f97..0811e17418 100644
--- a/internal/ai/patrol.go
+++ b/internal/ai/patrol.go
@@ -78,19 +78,32 @@ type AlertResolver interface {
}
// PatrolStatus represents the current state of the patrol service
+type PatrolRuntimeState string
+
+const (
+ PatrolRuntimeStateUnavailable PatrolRuntimeState = "unavailable"
+ PatrolRuntimeStateDisabled PatrolRuntimeState = "disabled"
+ PatrolRuntimeStateRunning PatrolRuntimeState = "running"
+ PatrolRuntimeStateBlocked PatrolRuntimeState = "blocked"
+ PatrolRuntimeStateActive PatrolRuntimeState = "active"
+)
+
+const patrolQuickstartCreditsExhaustedReason = "Quickstart credits exhausted. Connect your API key to continue using AI Patrol."
+
type PatrolStatus struct {
- Running bool `json:"running"`
- Enabled bool `json:"enabled"`
- LastPatrolAt *time.Time `json:"last_patrol_at,omitempty"`
- NextPatrolAt *time.Time `json:"next_patrol_at,omitempty"`
- LastDuration time.Duration `json:"last_duration_ms"`
- ResourcesChecked int `json:"resources_checked"`
- FindingsCount int `json:"findings_count"`
- ErrorCount int `json:"error_count"`
- Healthy bool `json:"healthy"`
- IntervalMs int64 `json:"interval_ms"` // Patrol interval in milliseconds
- BlockedReason string `json:"blocked_reason,omitempty"`
- BlockedAt *time.Time `json:"blocked_at,omitempty"`
+ RuntimeState PatrolRuntimeState `json:"runtime_state"`
+ Running bool `json:"running"`
+ Enabled bool `json:"enabled"`
+ LastPatrolAt *time.Time `json:"last_patrol_at,omitempty"`
+ NextPatrolAt *time.Time `json:"next_patrol_at,omitempty"`
+ LastDuration time.Duration `json:"last_duration_ms"`
+ ResourcesChecked int `json:"resources_checked"`
+ FindingsCount int `json:"findings_count"`
+ ErrorCount int `json:"error_count"`
+ Healthy bool `json:"healthy"`
+ IntervalMs int64 `json:"interval_ms"` // Patrol interval in milliseconds
+ BlockedReason string `json:"blocked_reason,omitempty"`
+ BlockedAt *time.Time `json:"blocked_at,omitempty"`
// Quickstart credit info for the frontend
QuickstartCreditsRemaining int `json:"quickstart_credits_remaining"`
QuickstartCreditsTotal int `json:"quickstart_credits_total"`
diff --git a/internal/ai/patrol_run.go b/internal/ai/patrol_run.go
index a914ea2895..b70987ea90 100644
--- a/internal/ai/patrol_run.go
+++ b/internal/ai/patrol_run.go
@@ -339,7 +339,7 @@ func (p *PatrolService) runPatrolWithTrigger(ctx context.Context, trigger Trigge
if !aiServiceEnabled {
// Distinguish between exhausted credits and no AI configured
if qsMgr != nil && !qsMgr.HasBYOK() && !qsMgr.HasCredits() {
- reason = "Quickstart credits exhausted. Connect your API key to continue using AI Patrol."
+ reason = patrolQuickstartCreditsExhaustedReason
} else {
reason = "AI not configured - set up a provider in Settings > Pulse Assistant"
}
@@ -355,7 +355,7 @@ func (p *PatrolService) runPatrolWithTrigger(ctx context.Context, trigger Trigge
// Check if using quickstart credits — verify credits remain before starting
usingQuickstart := p.aiService != nil && p.aiService.IsUsingQuickstart()
if usingQuickstart && qsMgr != nil && !qsMgr.HasCredits() {
- p.setBlockedReason("Quickstart credits exhausted. Connect your API key to continue using AI Patrol.")
+ p.setBlockedReason(patrolQuickstartCreditsExhaustedReason)
log.Info().Msg("AI Patrol: Skipping run - quickstart credits exhausted")
return
}
@@ -794,7 +794,7 @@ func (p *PatrolService) runScopedPatrol(ctx context.Context, scope PatrolScope)
reason := "AI not configured - set up a provider in Settings > Pulse Assistant"
if !aiServiceEnabled {
if scopedQsMgr != nil && !scopedQsMgr.HasBYOK() && !scopedQsMgr.HasCredits() {
- reason = "Quickstart credits exhausted. Connect your API key to continue using AI Patrol."
+ reason = patrolQuickstartCreditsExhaustedReason
}
} else if !llmAllowed {
reason = "circuit breaker is open"
@@ -807,7 +807,7 @@ func (p *PatrolService) runScopedPatrol(ctx context.Context, scope PatrolScope)
// Check if using quickstart credits — verify credits remain before starting
if scopedUsingQuickstart && scopedQsMgr != nil && !scopedQsMgr.HasCredits() {
- p.setBlockedReason("Quickstart credits exhausted. Connect your API key to continue using AI Patrol.")
+ p.setBlockedReason(patrolQuickstartCreditsExhaustedReason)
log.Info().Msg("AI Patrol: Skipping scoped run - quickstart credits exhausted")
return
}
@@ -1507,6 +1507,7 @@ func (p *PatrolService) GetStatus() PatrolStatus {
analysisInProgress := p.runInProgress
status := PatrolStatus{
+ RuntimeState: PatrolRuntimeStateActive,
Running: analysisInProgress,
Enabled: p.config.Enabled,
LastDuration: p.lastDuration,
@@ -1517,10 +1518,37 @@ func (p *PatrolService) GetStatus() PatrolStatus {
BlockedReason: p.lastBlockedReason,
}
+ if p.quickstartCredits != nil {
+ status.QuickstartCreditsRemaining = p.quickstartCredits.CreditsRemaining()
+ status.QuickstartCreditsTotal = pkglicensing.QuickstartCreditsTotal
+ status.UsingQuickstart = p.aiService != nil && p.aiService.IsUsingQuickstart()
+ }
+
+ quickstartBlocked := p.config.Enabled &&
+ p.quickstartCredits != nil &&
+ !p.quickstartCredits.HasBYOK() &&
+ !p.quickstartCredits.HasCredits()
+ if quickstartBlocked {
+ status.BlockedReason = patrolQuickstartCreditsExhaustedReason
+ } else if strings.TrimSpace(status.BlockedReason) == patrolQuickstartCreditsExhaustedReason {
+ status.BlockedReason = ""
+ }
+
+ switch {
+ case analysisInProgress:
+ status.RuntimeState = PatrolRuntimeStateRunning
+ case !p.config.Enabled:
+ status.RuntimeState = PatrolRuntimeStateDisabled
+ case strings.TrimSpace(status.BlockedReason) != "":
+ status.RuntimeState = PatrolRuntimeStateBlocked
+ default:
+ status.RuntimeState = PatrolRuntimeStateActive
+ }
+
if !p.lastPatrol.IsZero() {
status.LastPatrolAt = &p.lastPatrol
}
- if !p.lastBlockedAt.IsZero() {
+ if strings.TrimSpace(status.BlockedReason) != "" && !p.lastBlockedAt.IsZero() {
status.BlockedAt = &p.lastBlockedAt
}
@@ -1532,12 +1560,8 @@ func (p *PatrolService) GetStatus() PatrolStatus {
summary := p.findings.GetSummary()
status.Healthy = summary.IsHealthy()
-
- // Populate quickstart credit info
- if p.quickstartCredits != nil {
- status.QuickstartCreditsRemaining = p.quickstartCredits.CreditsRemaining()
- status.QuickstartCreditsTotal = pkglicensing.QuickstartCreditsTotal
- status.UsingQuickstart = p.aiService != nil && p.aiService.IsUsingQuickstart()
+ if status.RuntimeState == PatrolRuntimeStateBlocked {
+ status.Healthy = false
}
return status
diff --git a/internal/ai/patrol_run_test.go b/internal/ai/patrol_run_test.go
index ad2de2e056..9119153ee0 100644
--- a/internal/ai/patrol_run_test.go
+++ b/internal/ai/patrol_run_test.go
@@ -7,10 +7,23 @@ import (
"time"
"github.com/prometheus/client_golang/prometheus/testutil"
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/providers"
"github.com/rcourtman/pulse-go-rewrite/internal/models"
"github.com/rcourtman/pulse-go-rewrite/internal/unifiedresources"
)
+type stubPatrolQuickstartCreditManager struct {
+ remaining int
+ byok bool
+}
+
+func (m *stubPatrolQuickstartCreditManager) HasCredits() bool { return m.remaining > 0 }
+func (m *stubPatrolQuickstartCreditManager) CreditsRemaining() int { return m.remaining }
+func (m *stubPatrolQuickstartCreditManager) ConsumeCredit() error { return nil }
+func (m *stubPatrolQuickstartCreditManager) HasBYOK() bool { return m.byok }
+func (m *stubPatrolQuickstartCreditManager) GetProvider() providers.Provider { return nil }
+func (m *stubPatrolQuickstartCreditManager) GrantCredits() error { return nil }
+
// --- filterStateByScope tests ---
func TestFilterStateByScope_NoScope(t *testing.T) {
@@ -1454,6 +1467,53 @@ func TestGetStatus_BlockedReason(t *testing.T) {
}
}
+func TestGetStatus_QuickstartCreditsExhaustedBlocksRuntimeWithoutWaitingForRun(t *testing.T) {
+ ps := NewPatrolService(nil, nil)
+ ps.SetQuickstartCredits(&stubPatrolQuickstartCreditManager{remaining: 0})
+
+ status := ps.GetStatus()
+ if status.RuntimeState != PatrolRuntimeStateBlocked {
+ t.Fatalf("runtime_state = %q, want %q", status.RuntimeState, PatrolRuntimeStateBlocked)
+ }
+ if status.BlockedReason != patrolQuickstartCreditsExhaustedReason {
+ t.Fatalf("blocked_reason = %q, want %q", status.BlockedReason, patrolQuickstartCreditsExhaustedReason)
+ }
+ if status.Healthy {
+ t.Fatal("expected blocked patrol status to report healthy=false")
+ }
+}
+
+func TestGetStatus_ClearsStaleQuickstartBlockedStateWhenCreditsReturn(t *testing.T) {
+ ps := NewPatrolService(nil, nil)
+ quickstart := &stubPatrolQuickstartCreditManager{remaining: 0}
+ ps.SetQuickstartCredits(quickstart)
+ ps.setBlockedReason(patrolQuickstartCreditsExhaustedReason)
+
+ blockedStatus := ps.GetStatus()
+ if blockedStatus.RuntimeState != PatrolRuntimeStateBlocked {
+ t.Fatalf("runtime_state = %q, want %q before refill", blockedStatus.RuntimeState, PatrolRuntimeStateBlocked)
+ }
+ if blockedStatus.BlockedAt == nil {
+ t.Fatal("expected blocked_at to be present before refill")
+ }
+
+ quickstart.remaining = 3
+
+ status := ps.GetStatus()
+ if status.RuntimeState != PatrolRuntimeStateActive {
+ t.Fatalf("runtime_state = %q, want %q after refill", status.RuntimeState, PatrolRuntimeStateActive)
+ }
+ if status.BlockedReason != "" {
+ t.Fatalf("expected stale quickstart blocked_reason to clear after refill, got %q", status.BlockedReason)
+ }
+ if status.BlockedAt != nil {
+ t.Fatalf("expected stale quickstart blocked_at to clear after refill, got %v", status.BlockedAt)
+ }
+ if !status.Healthy {
+ t.Fatal("expected refilled quickstart status to return to healthy when there are no findings")
+ }
+}
+
// --- appendStreamContent ---
func TestAppendStreamContent(t *testing.T) {
diff --git a/internal/api/ai_handlers.go b/internal/api/ai_handlers.go
index ae4036fdb2..9353706972 100644
--- a/internal/api/ai_handlers.go
+++ b/internal/api/ai_handlers.go
@@ -4665,19 +4665,20 @@ func (h *AISettingsHandler) HandleOAuthDisconnect(w http.ResponseWriter, r *http
// PatrolStatusResponse is the response for GET /api/ai/patrol/status
type PatrolStatusResponse struct {
- Running bool `json:"running"`
- Enabled bool `json:"enabled"`
- LastPatrolAt *time.Time `json:"last_patrol_at,omitempty"`
- NextPatrolAt *time.Time `json:"next_patrol_at,omitempty"`
- LastDurationMs int64 `json:"last_duration_ms"`
- ResourcesChecked int `json:"resources_checked"`
- FindingsCount int `json:"findings_count"`
- ErrorCount int `json:"error_count"`
- Healthy bool `json:"healthy"`
- IntervalMs int64 `json:"interval_ms"` // Patrol interval in milliseconds
- FixedCount int `json:"fixed_count"` // Number of issues auto-fixed by Patrol
- BlockedReason string `json:"blocked_reason,omitempty"`
- BlockedAt *time.Time `json:"blocked_at,omitempty"`
+ RuntimeState ai.PatrolRuntimeState `json:"runtime_state"`
+ Running bool `json:"running"`
+ Enabled bool `json:"enabled"`
+ LastPatrolAt *time.Time `json:"last_patrol_at,omitempty"`
+ NextPatrolAt *time.Time `json:"next_patrol_at,omitempty"`
+ LastDurationMs int64 `json:"last_duration_ms"`
+ ResourcesChecked int `json:"resources_checked"`
+ FindingsCount int `json:"findings_count"`
+ ErrorCount int `json:"error_count"`
+ Healthy bool `json:"healthy"`
+ IntervalMs int64 `json:"interval_ms"` // Patrol interval in milliseconds
+ FixedCount int `json:"fixed_count"` // Number of issues auto-fixed by Patrol
+ BlockedReason string `json:"blocked_reason,omitempty"`
+ BlockedAt *time.Time `json:"blocked_at,omitempty"`
// Quickstart credit info for Patrol quickstart mode
QuickstartCreditsRemaining int `json:"quickstart_credits_remaining"`
QuickstartCreditsTotal int `json:"quickstart_credits_total"`
@@ -4717,6 +4718,7 @@ func (h *AISettingsHandler) HandleGetPatrolStatus(w http.ResponseWriter, r *http
if aiService == nil {
// Service not initialized (e.g. no persistence/config yet). Return safe defaults.
response := PatrolStatusResponse{
+ RuntimeState: ai.PatrolRuntimeStateUnavailable,
Running: false,
Enabled: false,
Healthy: true,
@@ -4736,6 +4738,7 @@ func (h *AISettingsHandler) HandleGetPatrolStatus(w http.ResponseWriter, r *http
licenseStatus, _ := aiService.GetLicenseState()
hasAutoFixFeature := aiService.HasLicenseFeature(featureAIAutoFixValue)
response := PatrolStatusResponse{
+ RuntimeState: ai.PatrolRuntimeStateUnavailable,
Running: false,
Enabled: false,
Healthy: true,
@@ -4767,6 +4770,7 @@ func (h *AISettingsHandler) HandleGetPatrolStatus(w http.ResponseWriter, r *http
}
response := PatrolStatusResponse{
+ RuntimeState: status.RuntimeState,
Running: status.Running,
Enabled: status.Enabled,
LastPatrolAt: status.LastPatrolAt,
diff --git a/internal/api/ai_handlers_patrol_actions_additional_test.go b/internal/api/ai_handlers_patrol_actions_additional_test.go
index 03381a4211..ba3f73f138 100644
--- a/internal/api/ai_handlers_patrol_actions_additional_test.go
+++ b/internal/api/ai_handlers_patrol_actions_additional_test.go
@@ -119,6 +119,36 @@ func TestHandleGetPatrolStatus_IncludesQuickstartFields(t *testing.T) {
}
}
+func TestHandleGetPatrolStatus_DerivesBlockedRuntimeStateForExhaustedQuickstartCredits(t *testing.T) {
+ handler, _, _, _ := setupAIHandlerWithPatrol(t)
+
+ handler.defaultAIService.SetQuickstartCredits(&stubQuickstartCreditManager{remaining: 0})
+
+ req := httptest.NewRequest(http.MethodGet, "/api/ai/patrol/status", nil)
+ rec := httptest.NewRecorder()
+
+ handler.HandleGetPatrolStatus(rec, req)
+
+ if rec.Code != http.StatusOK {
+ t.Fatalf("status = %d, want 200", rec.Code)
+ }
+
+ var resp PatrolStatusResponse
+ if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("decode response: %v", err)
+ }
+
+ if resp.RuntimeState != ai.PatrolRuntimeStateBlocked {
+ t.Fatalf("runtime_state = %q, want %q", resp.RuntimeState, ai.PatrolRuntimeStateBlocked)
+ }
+ if resp.BlockedReason != "Quickstart credits exhausted. Connect your API key to continue using AI Patrol." {
+ t.Fatalf("blocked_reason = %q", resp.BlockedReason)
+ }
+ if resp.Healthy {
+ t.Fatal("expected blocked patrol response to report healthy=false")
+ }
+}
+
func TestPatrolActionHandlers_NoAIService_ReturnStructuredServiceUnavailable(t *testing.T) {
tmp := t.TempDir()
cfg := &config.Config{DataPath: tmp}
diff --git a/internal/api/ai_patrol_handlers_test.go b/internal/api/ai_patrol_handlers_test.go
index 02487de5aa..ed1365232e 100644
--- a/internal/api/ai_patrol_handlers_test.go
+++ b/internal/api/ai_patrol_handlers_test.go
@@ -52,6 +52,9 @@ func TestHandleGetPatrolStatus_NoPatrolService(t *testing.T) {
}
// When patrol service is not initialized, should return safe defaults
+ if resp.RuntimeState != ai.PatrolRuntimeStateUnavailable {
+ t.Errorf("expected RuntimeState %q when patrol not initialized, got %q", ai.PatrolRuntimeStateUnavailable, resp.RuntimeState)
+ }
if resp.Running {
t.Error("expected Running to be false when patrol not initialized")
}
@@ -86,6 +89,9 @@ func TestHandleGetPatrolStatus_NoAIService(t *testing.T) {
if resp.Running {
t.Error("expected Running to be false when AI service missing")
}
+ if resp.RuntimeState != ai.PatrolRuntimeStateUnavailable {
+ t.Errorf("expected RuntimeState %q when AI service missing, got %q", ai.PatrolRuntimeStateUnavailable, resp.RuntimeState)
+ }
if resp.Enabled {
t.Error("expected Enabled to be false when AI service missing")
}
diff --git a/internal/api/contract_test.go b/internal/api/contract_test.go
index e18fcdaa24..94f560c0be 100644
--- a/internal/api/contract_test.go
+++ b/internal/api/contract_test.go
@@ -3106,6 +3106,7 @@ func TestContract_PatrolStatusResponseJSONSnapshot(t *testing.T) {
blockedAt := lastPatrolAt.Add(15 * time.Minute)
payload := PatrolStatusResponse{
+ RuntimeState: ai.PatrolRuntimeStateBlocked,
Running: false,
Enabled: true,
LastPatrolAt: &lastPatrolAt,
@@ -3137,6 +3138,7 @@ func TestContract_PatrolStatusResponseJSONSnapshot(t *testing.T) {
}
const want = `{
+ "runtime_state":"blocked",
"running":false,
"enabled":true,
"last_patrol_at":"2026-03-12T09:30:00Z",