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.

Guide the Patrol model choice with cost preview and budget pause

rcourtmanac328e1eee68
diff --git a/docs/API.md b/docs/API.md
index f9c914dfb5..10e6cf0a98 100644
--- a/docs/API.md
+++ b/docs/API.md
@@ -1274,6 +1274,8 @@ Request bodies:
### Cost Tracking
- `GET /api/ai/cost/summary`
+- `GET /api/ai/patrol/cost-preview` (optional `model` as `provider:model`, `interval_minutes`; projects Patrol's 30-day cost for a model and schedule from Pulse's price table and the install's run history, with the per-run token assumption, 30-day spend against budget, and a recommended schedule)
+- `GET /api/ai/patrol/model-guidance` (recommended / suggested / caution markers for the Patrol model pickers, plus this install's cached readiness pass)
- `POST /api/ai/cost/reset` (admin)
- `GET /api/ai/cost/export` (admin)
diff --git a/docs/release-control/v6/internal/status.json b/docs/release-control/v6/internal/status.json
index 044f12c441..4698550429 100644
--- a/docs/release-control/v6/internal/status.json
+++ b/docs/release-control/v6/internal/status.json
@@ -9976,6 +9976,98 @@
}
]
},
+ {
+ "id": "ai-provider-guided-setup",
+ "summary": "Paying installs choose a Patrol model and schedule with no guidance on which models work with Patrol or what a schedule costs: 38 of 120 paid installs had no AI provider and 12 more had AI without Patrol in the 2026-09-01 assessment, a Pro customer picked Gemini Flash-Lite to save money and Patrol could not file verdicts, and a mispriced Opus row tripped the 20 USD budget and silently disabled Patrol (issue 1789). The provider settings need recommended, suggested, and caution markers drawn from the qualified set and known failures, a projected monthly Patrol cost from the price table and the install's run history, a cost-model schedule default for per-token providers, and a visible Patrol pause with a budget action when the budget is used up.",
+ "owner": "project-owner",
+ "status": "planned",
+ "recorded_at": "2026-09-02",
+ "lane_ids": [
+ "L6",
+ "L8"
+ ],
+ "subsystem_ids": [
+ "ai-runtime",
+ "api-contracts",
+ "frontend-primitives",
+ "patrol-intelligence"
+ ],
+ "proposed_resolution": "lane-expansion",
+ "coverage_impact": 3,
+ "evidence": [
+ {
+ "repo": "pulse",
+ "path": "docs/AI_PATROL_QUALIFICATION.md",
+ "kind": "file"
+ },
+ {
+ "repo": "pulse",
+ "path": "frontend-modern/src/utils/aiPatrolCostPresentation.ts",
+ "kind": "file"
+ },
+ {
+ "repo": "pulse",
+ "path": "internal/ai/patrol_cost_projection.go",
+ "kind": "file"
+ },
+ {
+ "repo": "pulse",
+ "path": "internal/ai/patrol_model_guidance.go",
+ "kind": "file"
+ },
+ {
+ "repo": "pulse",
+ "path": "internal/api/ai_patrol_cost_preview.go",
+ "kind": "file"
+ }
+ ]
+ },
+ {
+ "id": "ai-provider-guided-setup",
+ "summary": "Paying installs choose a Patrol model and schedule with no guidance on which models work with Patrol or what a schedule costs: 38 of 120 paid installs had no AI provider and 12 more had AI without Patrol in the 2026-09-01 assessment, a Pro customer picked Gemini Flash-Lite to save money and Patrol could not file verdicts, and a mispriced Opus row tripped the 20 USD budget and silently disabled Patrol (issue 1789). The provider settings need recommended, suggested, and caution markers drawn from the qualified set and known failures, a projected monthly Patrol cost from the price table and the install's run history, a cost-model schedule default for per-token providers, and a visible Patrol pause with a budget action when the budget is used up.",
+ "owner": "project-owner",
+ "status": "planned",
+ "recorded_at": "2026-09-02",
+ "lane_ids": [
+ "L6",
+ "L8"
+ ],
+ "subsystem_ids": [
+ "ai-runtime",
+ "api-contracts",
+ "frontend-primitives",
+ "patrol-intelligence"
+ ],
+ "proposed_resolution": "lane-expansion",
+ "coverage_impact": 3,
+ "evidence": [
+ {
+ "repo": "pulse",
+ "path": "docs/AI_PATROL_QUALIFICATION.md",
+ "kind": "file"
+ },
+ {
+ "repo": "pulse",
+ "path": "frontend-modern/src/utils/aiPatrolCostPresentation.ts",
+ "kind": "file"
+ },
+ {
+ "repo": "pulse",
+ "path": "internal/ai/patrol_cost_projection.go",
+ "kind": "file"
+ },
+ {
+ "repo": "pulse",
+ "path": "internal/ai/patrol_model_guidance.go",
+ "kind": "file"
+ },
+ {
+ "repo": "pulse",
+ "path": "internal/api/ai_patrol_cost_preview.go",
+ "kind": "file"
+ }
+ ]
+ },
{
"id": "patrol-findings-hygiene-attention-noise",
"summary": "Two users in a row (discussions #1623 and #1699) could not find Patrol's durable outcomes because Remember as expected, Dismiss: Not an issue, Dismiss: Later, and Create rule sat two levels below the Needs attention detail, which offered only Acknowledge and Suppress. The same screenshot showed an alert with eleven open/resolved transitions in a day rendered as eleven timeline rows, and Patrol findings that restate an active alert (same resource, same condition) listed as separate items. Telemetry on 2026-09-01 showed 4,709 findings across 736 installs but only 255 investigations across 27, so most findings are seen and ignored. Attention needs: alert-mirroring findings folded under the alert, flapping collapsed to one labelled item with a count, and the durable decisions on the detail with one-line explanations.",
@@ -10074,20 +10166,48 @@
"product-demand: pulse-pro/FEATURE_REQUESTS.md#fleet-scale-machine-availability-and-service-probes",
"telemetry: 339 of 6578 active persistent installs configured 2449 availability targets on 2026-08-29; 70 installs had at least 10 targets"
]
+ },
+ {
+ "id": "ai-provider-guided-setup",
+ "name": "Guided AI provider setup with cost preview",
+ "summary": "Answer 'which model should I pick and what will it cost' at the point of choice: recommended, suggested, and caution markers on the Patrol model pickers drawn from the qualified set and known failures; a projected monthly Patrol cost next to the model choice from Pulse's price table, the schedule, and the install's own run history; a cost-model schedule default for per-token providers that leaves chosen schedules untouched; 30-day spend against budget in the same place; and budget exhaustion surfaced as a Patrol pause with a budget action instead of a log line and a tripped breaker.",
+ "status": "accepted",
+ "recorded_at": "2026-09-02",
+ "target_id": "v6-product-lane-expansion",
+ "current_lane_ids": [
+ "L6",
+ "L8"
+ ],
+ "coverage_gap_ids": [
+ "ai-provider-guided-setup"
+ ],
+ "subsystem_ids": [
+ "ai-runtime",
+ "api-contracts",
+ "frontend-primitives",
+ "patrol-intelligence"
+ ],
+ "demand_evidence": [
+ "product-demand: pulse-pro/FEATURE_REQUESTS.md#guided-ai-provider-setup-with-cost-preview",
+ "support: 2026-07-20 Pro customer Flash-Lite could not file Patrol verdicts; 2026-07-30 prospect asked which models Pulse recommends",
+ "issue: https://github.com/rcourtman/Pulse/issues/1789 (104k-token full run, mispriced budget trip silently disabled Patrol)",
+ "telemetry: 2026-09-01 clean basis, 38 of 120 paid installs without an AI provider and 12 more without Patrol",
+ "named-bet: cloud starting points are price-driven and labelled unqualified until the install's own readiness pass verifies them"
+ ]
}
],
"work_claims": [
{
- "id": "claude-patrol-findings-hygiene-coverage-gap-patrol-findings-hygiene-attention-noise",
- "agent_id": "claude-patrol-findings-hygiene",
- "summary": "Fold alert-mirroring findings under the alert, collapse flapping, surface lasting Patrol decisions on the attention detail",
+ "id": "claude-ai-provider-guided-setup-candidate-lane-ai-provider-guided-setup",
+ "agent_id": "claude-ai-provider-guided-setup",
+ "summary": "Guided AI provider setup with cost preview",
"target_id": "v6-product-lane-expansion",
- "claimed_at": "2026-09-02T03:29:56Z",
- "heartbeat_at": "2026-09-02T03:29:56Z",
- "expires_at": "2026-09-02T09:29:56Z",
+ "claimed_at": "2026-09-02T05:31:42Z",
+ "heartbeat_at": "2026-09-02T05:31:42Z",
+ "expires_at": "2026-09-02T09:31:42Z",
"work_item": {
- "kind": "coverage-gap",
- "id": "patrol-findings-hygiene-attention-noise"
+ "kind": "candidate-lane",
+ "id": "ai-provider-guided-setup"
}
}
],
diff --git a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
index f5e4cf8c3b..c78ca52f83 100644
--- a/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
+++ b/docs/release-control/v6/internal/subsystems/agent-lifecycle.md
@@ -7674,3 +7674,13 @@ native lifecycle workflow proof together, so lifecycle qualification cannot
silently execute under a weaker checkout boundary.
`scripts/check_workflow_trust.py`, `scripts/tests/test_workflow_trust.py`, and
`scripts/installtests/install_ps1_test.go` pin that relationship.
+
+### Patrol cost preview and model guidance reads are not agent lifecycle authority
+
+The read-only `GET /api/ai/patrol/cost-preview` and `GET
+/api/ai/patrol/model-guidance` routes under `internal/api/` price the Patrol
+schedule and mark Patrol model choices from Pulse's price table, the
+install's Patrol run history, and the cached readiness pass. They read no
+agent identity, enrolment, or fleet state, issue no agent commands, and do
+not change the shared agent-install or setup-script boundaries; the
+agent-lifecycle contract keeps its authority over every agent surface.
diff --git a/docs/release-control/v6/internal/subsystems/ai-runtime.md b/docs/release-control/v6/internal/subsystems/ai-runtime.md
index 6d91c301b8..f25e0c7fb3 100644
--- a/docs/release-control/v6/internal/subsystems/ai-runtime.md
+++ b/docs/release-control/v6/internal/subsystems/ai-runtime.md
@@ -7878,3 +7878,30 @@ collapsed. `internal/ai/findings_flapping_test.go`,
`internal/ai/findings_storm_throttler_test.go`, and
`internal/ai/findings_alert_mirror_test.go` pin the threshold, the collapse,
the hydration, and the matcher.
+
+### Patrol cost projection, model guidance, and budget refusal are runtime-owned
+
+`internal/ai/patrol_cost_projection.go` owns the Patrol cost preview:
+`ProjectPatrolCost` prices a provider/model and schedule from
+`internal/ai/cost` and the install's own run history (median of the last
+thirty days of priced full runs once three exist, otherwise the measured
+104,528-in / 4,491-out run from issue #1789), separates scheduled from
+observed alert-triggered runs, reports 30-day spend and budget on the same
+basis `enforceBudget` uses, and recommends the slowest schedule preset that
+keeps scheduled runs under half the configured budget (20 USD reference when
+none is set), never faster than the 6-hour default. Every figure carries its
+assumption in the payload; the frontend never re-derives dollars.
+`internal/ai/patrol_model_guidance.go` owns the recommended / suggested /
+caution rules: the Ollama preflight blessing is the only recommended entry,
+Gemini Flash-Lite the only caution (support, 2026-07-20), and cloud starting
+points are labelled price-driven and unqualified; the cached readiness pass
+for the configured Patrol model is surfaced as "verified". Budget refusal is
+the `ErrCostBudgetExceeded` sentinel (`CostBudgetExceededError` carries the
+figures), classified as `PatrolFailureCauseBudgetExhausted`, excluded from
+circuit-breaker accounting, and promoted into the Patrol runtime block state.
+The cause is persisted with the runtime finding (`AIFindingRecord.FailureCause`),
+refreshed when the finding is re-raised, and not cleared by a provider preflight
+success, because a healthy provider says nothing about spend.
+`patrol_cost_projection_test.go` and `patrol_model_guidance_test.go` pin the
+arithmetic, the history/default switch, the recommendation ladder, and the
+guidance matching.
diff --git a/docs/release-control/v6/internal/subsystems/api-contracts.md b/docs/release-control/v6/internal/subsystems/api-contracts.md
index 25e9f5e2e9..f0840cb9c3 100644
--- a/docs/release-control/v6/internal/subsystems/api-contracts.md
+++ b/docs/release-control/v6/internal/subsystems/api-contracts.md
@@ -10508,3 +10508,17 @@ container ID, name, image, state, status, and creation summaries. Absence
retains the existing direct-runtime contract. Clients must treat unknown future
values defensively and must not infer stats, secondary inventories, update
checks, or lifecycle authority from a summary-mode report.
+
+### Patrol cost preview and model guidance routes
+
+`GET /api/ai/patrol/cost-preview` (optional `model` as `provider:model`,
+`interval_minutes`; `settings:read`) returns the `ai.PatrolCostProjection`
+payload for the configured or pending Patrol model and schedule, including
+per-run token assumptions, per-preset schedule estimates, 30-day spend
+against budget, and the recommended schedule. `GET
+/api/ai/patrol/model-guidance` (`settings:read`) returns the static
+guidance rules plus this install's cached readiness pass. Both are read-only
+and registered in `router_routes_ai_relay.go`, listed in
+`route_inventory_test.go`, and documented in `docs/API.md` and its public
+mirror. The frontend client lives in `frontend-modern/src/api/aiPatrolCost.ts`
+with `aiPatrolCost.test.ts` pinning the query encoding.
diff --git a/docs/release-control/v6/internal/subsystems/frontend-primitives.md b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
index 09523b1d7e..91757bd5be 100644
--- a/docs/release-control/v6/internal/subsystems/frontend-primitives.md
+++ b/docs/release-control/v6/internal/subsystems/frontend-primitives.md
@@ -7017,3 +7017,25 @@ zero update state or offer an action that the reporting collector cannot
execute. Unknown or absent values preserve the direct-runtime presentation.
Component and browser proofs cover the warning, action omission, mode
transition, and desktop/narrow containment.
+
+### Patrol model choice carries guidance and a cost preview
+
+The Pulse Intelligence settings surface answers "which model should I pick
+and what will it cost" at the point of choice instead of after the budget
+trips. The shared `AIModelPicker` accepts per-model annotations (badge, note,
+tone) rendered beside the model name and under its description in both
+pinned sections and provider groups, with the badge and note folded into the
+accessible option name. The Patrol model field and the shared default field
+(when no Patrol override is set) pin guided models in a "Suggested for
+Patrol" section, repeat the selected model's marker under the closed picker,
+and render the server-computed Patrol cost preview: monthly estimate,
+per-run assumption with tokens explained once, 30-day spend against budget,
+and the schedule recommendation. The Patrol schedule select prices each
+preset from the same projection and the schedule card explains a schedule
+that Pulse slowed for a per-token model; a schedule the install already
+chose is never changed. Dollars and prices never derive from model names in
+the settings surface; `useAISettingsState` fetches
+`/api/ai/patrol/cost-preview` and `/api/ai/patrol/model-guidance` and
+`aiPatrolCostPresentation.ts` owns the copy. `AIModelPicker.test.tsx`,
+`AISettings.test.tsx`, and `settingsArchitecture.test.ts` pin those
+distinctions.
diff --git a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md b/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
index 5aa2a6db6c..deaf9e5168 100644
--- a/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
+++ b/docs/release-control/v6/internal/subsystems/patrol-intelligence.md
@@ -2537,3 +2537,24 @@ options remain available; dismissed and resolved views keep them in place.
`PatrolAttentionWorkbench.test.tsx` pins the four decisions and their copy, the
rule reason requirement, the remembered-decision path, the alert-only
guidance, and the flapping collapse.
+
+### A used-up cost budget pauses Patrol visibly
+
+Patrol distinguishes "Pulse declined to spend" from "the provider failed".
+A 30-day budget refusal is the `ErrCostBudgetExceeded` sentinel with the
+spent and limit figures, classified as the `budget_exhausted` failure cause,
+never counted against the provider circuit breaker, and promoted into the
+runtime block state so `/api/ai/patrol/status` reports `blocked` with a
+`blocked_reason` that names the spend, the limit, and where to fix it. The
+Patrol page's paused banner, header run control, and setup card resolve
+their action from the block cause before the readiness cause, so an exhausted
+budget lands on "Raise the cost budget" (Provider & Models) instead of the
+model check, and the setup card subtitle says the pause is about spending,
+not a failed tool check. `patrolRuntimeActions.test.ts`,
+`usePatrolIntelligenceState.test.ts`, `PatrolIntelligenceHeader.test.ts`,
+`patrolControlPresentation.test.ts`, and the `internal/ai` projection tests
+pin those distinctions (issue #1789). The failure cause is persisted with the
+finding and carried onto the unified finding as `failureCause`, and a provider
+preflight success no longer clears a budget-exhausted runtime finding, so the
+setup card still routes to the budget after a restart clears the in-memory
+block state.
diff --git a/docs/release-control/v6/internal/subsystems/storage-recovery.md b/docs/release-control/v6/internal/subsystems/storage-recovery.md
index f480e684d2..0363fdce0e 100644
--- a/docs/release-control/v6/internal/subsystems/storage-recovery.md
+++ b/docs/release-control/v6/internal/subsystems/storage-recovery.md
@@ -5864,6 +5864,15 @@ explicit commit boundary. Persistence-failure proofs live in
`internal/api/alerting/notifications_test.go` with API ordering pinned by
`internal/api/contract_test.go`.
+### Patrol cost preview and model guidance reads are not storage or recovery authority
+
+The read-only `GET /api/ai/patrol/cost-preview` and `GET
+/api/ai/patrol/model-guidance` routes under `internal/api/` derive their
+figures from AI usage history, Patrol run history, and the readiness cache
+owned by `ai-runtime`. They read no backup, snapshot, or recovery record,
+write nothing to storage or recovery state, and are not evidence for any
+recovery posture.
+
### Mock alert incident notes are not recovery records
The shared `internal/api/alerting/alerts.go` transport now reads and annotates
diff --git a/frontend-modern/browser-verification.json b/frontend-modern/browser-verification.json
index 8c1fbdf410..dc4def48df 100644
--- a/frontend-modern/browser-verification.json
+++ b/frontend-modern/browser-verification.json
@@ -1,57 +1,70 @@
{
"version": 1,
- "base_sha": "d7a4dcf8e7c59fc35348236d8aeb3f25dc6062fe",
- "verified_at": "2026-09-02T06:02:51Z",
+ "base_sha": "fd36b3124c31bde2bea6b916652b9319827f890f",
+ "verified_at": "2026-09-02T06:55:42Z",
"result": "passed",
"changed_paths": [
- "frontend-modern/src/api/patrol.ts",
- "frontend-modern/src/api/patrolAttention.ts",
- "frontend-modern/src/components/AI/FindingsPanel.tsx",
- "frontend-modern/src/features/patrol/PatrolAttentionWorkbench.tsx",
- "frontend-modern/src/features/patrol/PatrolIntelligenceSurface.tsx",
- "frontend-modern/src/features/patrol/patrolHomePresentation.ts",
+ "frontend-modern/src/api/aiPatrolCost.ts",
+ "frontend-modern/src/components/Settings/AIModelSelectionSection.tsx",
+ "frontend-modern/src/components/Settings/AISettings.tsx",
+ "frontend-modern/src/components/Settings/useAISettingsState.ts",
+ "frontend-modern/src/components/shared/AIModelPicker.tsx",
+ "frontend-modern/src/features/patrol/PatrolIntelligenceBanners.tsx",
+ "frontend-modern/src/features/patrol/PatrolIntelligenceHeader.tsx",
+ "frontend-modern/src/features/patrol/PatrolIntelligenceWorkspace.tsx",
+ "frontend-modern/src/features/patrol/patrolControlPresentation.ts",
"frontend-modern/src/features/patrol/usePatrolIntelligenceState.ts",
"frontend-modern/src/stores/aiIntelligence.ts",
- "frontend-modern/src/utils/findingAlertIdentity.ts"
+ "frontend-modern/src/types/ai.ts",
+ "frontend-modern/src/utils/aiPatrolCostPresentation.ts",
+ "frontend-modern/src/utils/patrolRuntimeActions.ts"
],
"content_sha256": {
- "frontend-modern/src/api/patrol.ts": "962ddd9eccb31fcfa419cde956c90f319333de3c15f98118d6580b542b1f4825",
- "frontend-modern/src/api/patrolAttention.ts": "6729696d1966d62a38ebcc52bcc1d0a62479c6e025c1a7d4f23f02ed77c4428f",
- "frontend-modern/src/components/AI/FindingsPanel.tsx": "8a6f65c113e507e4d4016861559f5ca01c962b4173387a42a2140499ae1d3e30",
- "frontend-modern/src/features/patrol/PatrolAttentionWorkbench.tsx": "ababb1fd31897a9dd7ca518d574d30b21b8b4abeae597f6475937ad93f3ebf59",
- "frontend-modern/src/features/patrol/PatrolIntelligenceSurface.tsx": "f7fbdc4d43c42e12f08671a78a4b903bb1ed7b2d25d1551c395691c4991f1a40",
- "frontend-modern/src/features/patrol/patrolHomePresentation.ts": "78aa0072e9b6c8bed4bc5fa3a86010bd61c9aa0c2ed98b08accca2c42e5e68de",
- "frontend-modern/src/features/patrol/usePatrolIntelligenceState.ts": "b9632efe1d21f9c125b52795fa950b5f40167c4e11ccff18652f32ac1b3faf49",
- "frontend-modern/src/stores/aiIntelligence.ts": "177859f415e92bcd282844ececf6ef8edfd5d54bda612ae18f100aacc1b40921",
- "frontend-modern/src/utils/findingAlertIdentity.ts": "7988efd6dbf80c60e4d66312abb5ff95bcae9fc98445af0f57940a7ed3ea358b"
+ "frontend-modern/src/api/aiPatrolCost.ts": "be947370111a1efb7e2618f344b4b81481262f6b1fd8fc4ed2690a7729a05bff",
+ "frontend-modern/src/components/Settings/AIModelSelectionSection.tsx": "33b63989306752e5b852e5d2438dfcb99c0df78530ba50c1e157b895d7f1a623",
+ "frontend-modern/src/components/Settings/AISettings.tsx": "7103686e133e08d50563bf66da63ea161f73ae0386c59d6c770da78f0bdb78bb",
+ "frontend-modern/src/components/Settings/useAISettingsState.ts": "841fa917cf7c5a1f7867b992813984bbd1ce6f57ed9f1abe8db2b7183a4596a5",
+ "frontend-modern/src/components/shared/AIModelPicker.tsx": "79abf84c58d6baec0351bea8cfb7d828db8ff00f5bae7ed0fff4079bbef25b91",
+ "frontend-modern/src/features/patrol/PatrolIntelligenceBanners.tsx": "085c1d677ed5e15698e32759b4c01a05e0fd038fbf686ded48b390623de41d22",
+ "frontend-modern/src/features/patrol/PatrolIntelligenceHeader.tsx": "69ff486b95aafd445600571c977f8670e9686d9185f2c1285c2a6690e9c2d113",
+ "frontend-modern/src/features/patrol/PatrolIntelligenceWorkspace.tsx": "cd6d888b620e44fa8ec2125b818e59c8ed802f8aeae0c554c4ce5bd1d40e314f",
+ "frontend-modern/src/features/patrol/patrolControlPresentation.ts": "58ad626d6af2472343307c01583621d4cfd742684f36c5583a3b72de75f86929",
+ "frontend-modern/src/features/patrol/usePatrolIntelligenceState.ts": "7578f9e010bc36a1d5a3ec932a69a23a077e176755e7207905ec47f5e94d5fae",
+ "frontend-modern/src/stores/aiIntelligence.ts": "8b81de1c09f47555b148415641f9cc42a9db25e0a54cd0bc64bb24d03bb1a0ac",
+ "frontend-modern/src/types/ai.ts": "12473e6f0e6339094689ac77f9a32aa1ffb62def1e81c780f4263cbcf5923474",
+ "frontend-modern/src/utils/aiPatrolCostPresentation.ts": "3d1ffa67e0df24af89ca26bb40e29fe55ef859902145aa958d4331483952a032",
+ "frontend-modern/src/utils/patrolRuntimeActions.ts": "a71f234c2007dafd6e8773542ae238b8cd3cdb9501aaf5f1a403060335fbabd9"
},
"routes": [
- "/patrol",
- "/patrol?attention=mock-cluster-2-pve10-local-zfs%3A%3Ametric-threshold%3Ausage"
+ "/settings/pulse-intelligence/patrol",
+ "/settings/pulse-intelligence/provider",
+ "/patrol"
],
"viewports": [
{
"width": 1280,
- "height": 1400
+ "height": 1000
},
{
- "width": 390,
- "height": 1600
+ "width": 375,
+ "height": 812
}
],
"states": [
- "Patrol inbox queue with 47-50 mock decisions and the alert-only detail (no mirrored Patrol finding: Lasting decisions explains there is nothing for Patrol to remember and links alert thresholds)",
- "Attention detail for east-d-service-pool storage usage with a mirrored Patrol finding: Lifecycle short-term note, Lasting decisions listing Remember as expected, Dismiss: Not an issue, Dismiss: Later, Create rule with one-line explanations",
- "Inline confirmation form for Remember as expected with optional note",
- "Remembered-decision state (Remembered as expected, note, Reopen finding) after the dismissal, and the four options again after Reopen",
- "Activity tab findings list with the collapsed \"1 finding mirrors an active alert\" group, expanded to show the demoted finding with Finding options",
- "Narrow 390px detail layout with stacked lasting decisions and no horizontal overflow"
+ "Patrol model picker open with the Suggested for Patrol section and Recommended for Patrol badge (Ollama qwen3:8b)",
+ "estimate box for a local model (no per-token bill) with the 30-day budget line",
+ "estimate box for a per-token model (Anthropic Sonnet 5) with monthly figure, per-run assumption, token explainer, and schedule recommendation",
+ "schedule select priced per preset and current-schedule card after the auto-adjust to once a day",
+ "estimate box with the budget reached line after seeding an over-budget usage history",
+ "Patrol page paused banner with spend, limit, and Raise the cost budget action",
+ "Patrol page setup card after a backend restart: paused subtitle and Raise the cost budget action from the persisted finding cause",
+ "narrow viewport: settings Patrol tab, picker, and Patrol page with no horizontal overflow"
],
"interactions": [
- "Opened the deep-linked attention detail and read the Lifecycle and Lasting decisions sections",
- "Clicked Remember as expected, typed a note, confirmed; verified via /api/ai/patrol/findings?include_resolved=1 that the mirrored finding carried dismissed_reason=expected_behavior and the note",
- "Reloaded the detail and confirmed the Remembered as expected state, then clicked Reopen finding and confirmed the finding returned to active with the four decisions offered again",
- "Switched to the Activity tab, opened Finding options and history, expanded the mirrored-findings group",
- "Triggered POST /api/ai/patrol/run and confirmed mirrors_alert_id/mirrors_alert_type stamped on the storage finding"
+ "configured Ollama and a 20 USD budget on Provider & Models and saved",
+ "opened the Patrol model picker, searched a custom route, selected anthropic:claude-sonnet-5 and observed the schedule change to once a day",
+ "triggered a Patrol run against an over-budget usage history and observed the blocked status and finding",
+ "restarted the backend and reloaded the Patrol page",
+ "resized to 375x812 and repeated the settings and Patrol page checks"
]
}
diff --git a/frontend-modern/public/docs/API.md b/frontend-modern/public/docs/API.md
index f9c914dfb5..10e6cf0a98 100644
--- a/frontend-modern/public/docs/API.md
+++ b/frontend-modern/public/docs/API.md
@@ -1274,6 +1274,8 @@ Request bodies:
### Cost Tracking
- `GET /api/ai/cost/summary`
+- `GET /api/ai/patrol/cost-preview` (optional `model` as `provider:model`, `interval_minutes`; projects Patrol's 30-day cost for a model and schedule from Pulse's price table and the install's run history, with the per-run token assumption, 30-day spend against budget, and a recommended schedule)
+- `GET /api/ai/patrol/model-guidance` (recommended / suggested / caution markers for the Patrol model pickers, plus this install's cached readiness pass)
- `POST /api/ai/cost/reset` (admin)
- `GET /api/ai/cost/export` (admin)
diff --git a/frontend-modern/src/api/__tests__/aiPatrolCost.test.ts b/frontend-modern/src/api/__tests__/aiPatrolCost.test.ts
new file mode 100644
index 0000000000..02d8d2ce60
--- /dev/null
+++ b/frontend-modern/src/api/__tests__/aiPatrolCost.test.ts
@@ -0,0 +1,47 @@
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+vi.mock('@/utils/apiClient', () => ({
+ apiFetchJSON: vi.fn(),
+}));
+
+import { getPatrolCostPreview, getPatrolModelGuidance } from '@/api/aiPatrolCost';
+import { apiFetchJSON } from '@/utils/apiClient';
+
+describe('aiPatrolCost API', () => {
+ const apiFetchJSONMock = vi.mocked(apiFetchJSON);
+
+ beforeEach(() => {
+ apiFetchJSONMock.mockReset();
+ });
+
+ it('previews the configured Patrol model when no query is given', async () => {
+ apiFetchJSONMock.mockResolvedValueOnce({ provider: 'gemini' } as never);
+ await getPatrolCostPreview();
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/ai/patrol/cost-preview', undefined);
+ });
+
+ it('encodes a pending model route and schedule, including manual-only', async () => {
+ apiFetchJSONMock.mockResolvedValueOnce({} as never);
+ const controller = new AbortController();
+ await getPatrolCostPreview(
+ { model: ' anthropic:claude-haiku-4-5 ', intervalMinutes: 0 },
+ controller.signal,
+ );
+ expect(apiFetchJSONMock).toHaveBeenCalledWith(
+ '/api/ai/patrol/cost-preview?model=anthropic%3Aclaude-haiku-4-5&interval_minutes=0',
+ { signal: controller.signal },
+ );
+ });
+
+ it('drops blank models and non-finite intervals from the query', async () => {
+ apiFetchJSONMock.mockResolvedValueOnce({} as never);
+ await getPatrolCostPreview({ model: ' ', intervalMinutes: Number.NaN });
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/ai/patrol/cost-preview', undefined);
+ });
+
+ it('fetches model guidance from the canonical route', async () => {
+ apiFetchJSONMock.mockResolvedValueOnce({ rules: [] } as never);
+ await expect(getPatrolModelGuidance()).resolves.toEqual({ rules: [] });
+ expect(apiFetchJSONMock).toHaveBeenCalledWith('/api/ai/patrol/model-guidance');
+ });
+});
diff --git a/frontend-modern/src/api/aiPatrolCost.ts b/frontend-modern/src/api/aiPatrolCost.ts
new file mode 100644
index 0000000000..49c89bfbc3
--- /dev/null
+++ b/frontend-modern/src/api/aiPatrolCost.ts
@@ -0,0 +1,38 @@
+import { apiFetchJSON } from '@/utils/apiClient';
+import type { PatrolCostProjection, PatrolModelGuidanceResponse } from '@/types/ai';
+
+export interface PatrolCostPreviewQuery {
+ /** provider:model route to price; omit for the configured Patrol model. */
+ model?: string;
+ /** Schedule to price in minutes; 0 means manual only; omit for the configured one. */
+ intervalMinutes?: number;
+}
+
+/**
+ * Project what Patrol will cost per 30 days for a model and schedule. The
+ * server owns the price table and the install's run history, so the
+ * frontend never re-derives prices.
+ */
+export async function getPatrolCostPreview(
+ query: PatrolCostPreviewQuery = {},
+ signal?: AbortSignal,
+): Promise<PatrolCostProjection> {
+ const search = new URLSearchParams();
+ const model = query.model?.trim();
+ if (model) {
+ search.set('model', model);
+ }
+ if (typeof query.intervalMinutes === 'number' && Number.isFinite(query.intervalMinutes)) {
+ search.set('interval_minutes', String(Math.max(0, Math.round(query.intervalMinutes))));
+ }
+ const suffix = search.toString();
+ return apiFetchJSON<PatrolCostProjection>(
+ `/api/ai/patrol/cost-preview${suffix ? `?${suffix}` : ''}`,
+ signal ? { signal } : undefined,
+ );
+}
+
+/** Recommended, suggested, and caution markers for the model pickers. */
+export async function getPatrolModelGuidance(): Promise<PatrolModelGuidanceResponse> {
+ return apiFetchJSON<PatrolModelGuidanceResponse>('/api/ai/patrol/model-guidance');
+}
diff --git a/frontend-modern/src/components/Settings/AIModelSelectionSection.tsx b/frontend-modern/src/components/Settings/AIModelSelectionSection.tsx
index 0efc172f87..4d00d95251 100644
--- a/frontend-modern/src/components/Settings/AIModelSelectionSection.tsx
+++ b/frontend-modern/src/components/Settings/AIModelSelectionSection.tsx
@@ -1,11 +1,18 @@
import { A } from '@solidjs/router';
-import { Component, For, Show } from 'solid-js';
+import { Component, For, Show, createMemo } from 'solid-js';
import { AIProviderConfigurationSection } from '@/components/Settings/AIProviderConfigurationSection';
import { isModelProviderConfigured } from '@/components/Settings/aiSettingsModel';
import { settingsTabPath } from '@/components/Settings/settingsNavigationModel';
import type { AISettingsState } from '@/components/Settings/useAISettingsState';
import type { PatrolModelReadinessSnapshot } from '@/types/ai';
import { AIModelPicker } from '@/components/shared/AIModelPicker';
+import type { AIModelPickerAnnotation } from '@/components/shared/AIModelPicker';
+import {
+ getPatrolCostPresentation,
+ getPatrolGuidedModelIds,
+ resolvePatrolModelGuidance,
+ type PatrolCostTone,
+} from '@/utils/aiPatrolCostPresentation';
import { formField, labelClass, controlClass } from '@/components/shared/Form';
import {
formatAIModelRouteLabel,
@@ -368,6 +375,120 @@ export const PatrolModelReadinessControl: Component<{ state: AISettingsState }>
);
};
+const patrolCostToneClasses = (tone: PatrolCostTone) => {
+ switch (tone) {
+ case 'positive':
+ return 'border-green-200 dark:border-green-800 bg-green-50 dark:bg-green-900 text-green-800 dark:text-green-200';
+ case 'warning':
+ return 'border-amber-200 dark:border-amber-800 bg-amber-50 dark:bg-amber-900 text-amber-800 dark:text-amber-200';
+ case 'danger':
+ return 'border-red-200 dark:border-red-800 bg-red-50 dark:bg-red-900 text-red-800 dark:text-red-200';
+ default:
+ return 'border-border bg-surface-alt text-base-content';
+ }
+};
+
+const patrolCostLineToneClass = (tone: PatrolCostTone) => {
+ switch (tone) {
+ case 'warning':
+ return 'text-amber-700 dark:text-amber-300';
+ case 'danger':
+ return 'text-red-700 dark:text-red-300';
+ default:
+ return '';
+ }
+};
+
+/**
+ * What Patrol will cost on the chosen model and schedule, with the assumption
+ * and the 30-day spend against budget in the same place. Rendered under the
+ * Patrol model picker and under the shared default when it drives Patrol.
+ */
+export const PatrolCostPreview: Component<{ state: AISettingsState }> = (props) => {
+ const { state } = props;
+ const presentation = createMemo(() => getPatrolCostPresentation(state.patrolCostPreview()));
+ return (
+ <Show when={presentation()}>
+ {(view) => (
+ <div
+ class={`mt-2 rounded border px-3 py-2 ${patrolCostToneClasses(view().tone)}`}
+ data-testid="patrol-cost-preview"
+ role="status"
+ >
+ <div class="flex items-baseline justify-between gap-2">
+ <p class="text-xs font-medium">
+ <span class="mr-1 text-[10px] font-semibold uppercase opacity-70">Estimate</span>{' '}
+ {view().headline}
+ </p>
+ <Show when={state.patrolCostPreviewLoading()}>
+ <span class="text-[10px] opacity-70">updating…</span>
+ </Show>
+ </div>
+ <Show when={view().detail}>
+ <p class="mt-1 text-[11px] opacity-90">{view().detail}</p>
+ </Show>
+ <Show when={view().assumption}>
+ <p class="mt-1 text-[11px] opacity-75">{view().assumption}</p>
+ </Show>
+ <p
+ class={`mt-1 text-[11px] ${patrolCostLineToneClass(view().budgetTone) || 'opacity-90'}`}
+ >
+ {view().budget}
+ </p>
+ <Show when={view().schedule}>
+ <p class="mt-1 text-[11px] opacity-90">{view().schedule}</p>
+ </Show>
+ <Show when={state.patrolIntervalAutoAdjust()}>
+ {(adjust) => (
+ <p class="mt-1 text-[11px] font-medium" data-testid="patrol-schedule-auto-adjust">
+ {adjust().sentence}
+ </p>
+ )}
+ </Show>
+ </div>
+ )}
+ </Show>
+ );
+};
+
+const usePatrolModelGuidance = (
+ state: AISettingsState,
+ models: () => { id: string; provider?: string }[],
+) => {
+ const annotations = createMemo(() =>
+ resolvePatrolModelGuidance(models(), state.patrolModelGuidance()),
+ );
+ const annotationRecord = createMemo<Record<string, AIModelPickerAnnotation>>(() =>
+ Object.fromEntries(
+ Array.from(annotations().entries()).map(([id, annotation]) => [
+ id,
+ { badge: annotation.badge, note: annotation.note, tone: annotation.tone },
+ ]),
+ ),
+ );
+ const sections = createMemo(() => {
+ const ids = getPatrolGuidedModelIds(annotations());
+ return ids.length > 0 ? [{ title: 'Suggested for Patrol', modelIds: ids }] : [];
+ });
+ return { annotations, annotationRecord, sections };
+};
+
+const SelectedModelGuidanceNote: Component<{
+ annotation: () => AIModelPickerAnnotation | undefined;
+}> = (props) => (
+ <Show when={props.annotation()}>
+ {(annotation) => (
+ <p
+ class={`mt-1 text-xs ${
+ annotation().tone === 'warning' ? 'text-amber-600 dark:text-amber-400' : 'text-muted'
+ }`}
+ >
+ <span class="font-medium">{annotation().badge}:</span> {annotation().note}
+ </p>
+ )}
+ </Show>
+);
+
export const AIModelOverrideField: Component<{
state: AISettingsState;
kind: AIModelOverrideKind;
@@ -376,7 +497,9 @@ export const AIModelOverrideField: Component<{
const { state } = props;
const config = () => MODEL_OVERRIDE_CONFIG[props.kind];
const selectedModel = () => state.form[config().formKey];
- const setSelectedModel = (modelId: string) => state.setForm(config().formKey, modelId);
+ const setSelectedModel = (modelId: string) =>
+ state.handleModelSelection(config().formKey, modelId);
+ const guidesPatrol = () => props.kind === 'patrol';
const modelLabel = (modelId: string) => {
const trimmed = modelId.trim();
if (!trimmed) {
@@ -397,6 +520,9 @@ export const AIModelOverrideField: Component<{
`${controlClass()} flex items-center gap-2 justify-between text-left disabled:cursor-not-allowed disabled:opacity-60`;
const sharedDefaultDescription = () =>
state.form.model ? `Currently ${modelLabel(state.form.model)}` : 'No shared default model set';
+ const guidance = usePatrolModelGuidance(state, () => (guidesPatrol() ? selectableModels() : []));
+ const selectedAnnotation = () =>
+ guidesPatrol() ? guidance.annotationRecord()[selectedModel().trim()] : undefined;
return (
<div class={formField}>
@@ -450,8 +576,11 @@ export const AIModelOverrideField: Component<{
buttonClass={pickerButtonClass()}
buttonLabelClass="min-w-0 flex-1 truncate text-left font-normal"
dropdownClass="w-[calc(100vw-2rem)] max-w-xl"
+ modelSections={guidance.sections()}
+ modelAnnotations={guidance.annotationRecord()}
/>
</Show>
+ <SelectedModelGuidanceNote annotation={selectedAnnotation} />
<Show when={selectedModel() && !isModelProviderConfigured(selectedModel(), state.settings())}>
<p class="text-xs text-amber-600 dark:text-amber-400 mt-1 flex items-center gap-1">
<svg
@@ -473,6 +602,9 @@ export const AIModelOverrideField: Component<{
to be configured. Add an API key on Provider & Models or select a different model.
</p>
</Show>
+ <Show when={guidesPatrol()}>
+ <PatrolCostPreview state={state} />
+ </Show>
<Show when={props.includePatrolReadiness}>
<PatrolModelReadinessControl state={state} />
</Show>
@@ -491,6 +623,10 @@ export const AIModelSelectionSection: Component<AIModelSelectionSectionProps> =
);
};
const sharedModelOptions = () => selectableModels(state.form.model);
+ const sharedGuidance = usePatrolModelGuidance(state, sharedModelOptions);
+ const sharedDrivesPatrol = () => !state.form.patrolModel.trim();
+ const sharedSelectedAnnotation = () =>
+ sharedDrivesPatrol() ? sharedGuidance.annotationRecord()[state.form.model.trim()] : undefined;
const pickerButtonClass = () =>
`${controlClass()} flex items-center gap-2 justify-between text-left disabled:cursor-not-allowed disabled:opacity-60`;
const pickerLabelClass = 'min-w-0 flex-1 truncate text-left font-normal';
@@ -545,7 +681,7 @@ export const AIModelSelectionSection: Component<AIModelSelectionSectionProps> =
<AIModelPicker
models={sharedModelOptions()}
selectedModel={state.form.model}
- onModelSelect={(modelId) => state.setForm('model', modelId)}
+ onModelSelect={(modelId) => state.handleModelSelection('model', modelId)}
emptySelectionLabel="Select a model..."
title="Select shared default model"
searchPlaceholder="Search configured provider models"
@@ -558,8 +694,11 @@ export const AIModelSelectionSection: Component<AIModelSelectionSectionProps> =
buttonClass={pickerButtonClass()}
buttonLabelClass={pickerLabelClass}
dropdownClass={pickerDropdownClass}
+ modelSections={sharedGuidance.sections()}
+ modelAnnotations={sharedGuidance.annotationRecord()}
/>
</Show>
+ <SelectedModelGuidanceNote annotation={sharedSelectedAnnotation} />
<Show when={state.modelsError()}>
<p class="text-xs text-amber-600 dark:text-amber-400 mt-1 flex items-center gap-1">
<svg
@@ -606,6 +745,9 @@ export const AIModelSelectionSection: Component<AIModelSelectionSectionProps> =
Used by Pulse Assistant and Patrol unless you set a section-specific override. Service
context discovery follows the Patrol model when one is set.
</p>
+ <Show when={sharedDrivesPatrol()}>
+ <PatrolCostPreview state={state} />
+ </Show>
</div>
<div class={formField}>
diff --git a/frontend-modern/src/components/Settings/AISettings.tsx b/frontend-modern/src/components/Settings/AISettings.tsx
index 328053f417..4f05bed684 100644
--- a/frontend-modern/src/components/Settings/AISettings.tsx
+++ b/frontend-modern/src/components/Settings/AISettings.tsx
@@ -1,4 +1,4 @@
-import { Component, createMemo, Show } from 'solid-js';
+import { Component, For, createMemo, Show } from 'solid-js';
import { useNavigate } from '@solidjs/router';
import { AIChatMaintenanceSection } from '@/components/Settings/AIChatMaintenanceSection';
import { AISettingsDialogs } from '@/components/Settings/AISettingsDialogs';
@@ -26,6 +26,10 @@ import {
presentationPolicyHidesCommercialSurfaces,
presentationPolicyHidesUpgradePrompts,
} from '@/stores/sessionPresentationPolicy';
+import {
+ getPatrolCostPresentation,
+ getPatrolIntervalCostHint,
+} from '@/utils/aiPatrolCostPresentation';
import {
AI_SETTINGS_PANEL_TITLE,
getAISettingsLoadingState,
@@ -159,9 +163,18 @@ const PatrolSettingsContent: Component<{ state: ReturnType<typeof useAISettingsS
labelClass="text-xs font-medium text-muted"
selectBaseClass="w-full min-h-10 rounded-md border border-border bg-surface px-3 py-2 text-sm"
>
- {intervalOptions.map((option) => (
- <option value={option.value}>{option.label}</option>
- ))}
+ <For each={intervalOptions}>
+ {(option) => {
+ const hint = () =>
+ getPatrolIntervalCostHint(props.state.patrolCostPreview(), option.value);
+ return (
+ <option value={option.value}>
+ {option.label}
+ {hint() ? ` (${hint()})` : ''}
+ </option>
+ );
+ }}
+ </For>
</FormSelect>
<div class="rounded-md border border-border bg-surface-alt p-3">
@@ -169,6 +182,25 @@ const PatrolSettingsContent: Component<{ state: ReturnType<typeof useAISettingsS
<p class="mt-1 text-sm text-muted">
{formatPatrolInterval(props.state.form.patrolIntervalMinutes)}
</p>
+ <Show when={getPatrolCostPresentation(props.state.patrolCostPreview())}>
+ {(cost) => (
+ <p class="mt-1 text-xs text-muted" data-testid="patrol-schedule-cost">
+ {cost().headline} with {props.state.effectivePatrolModel()}.
+ <Show when={props.state.patrolCostPreview()?.billed_per_token}>
+ {' '}
+ Estimate. The Patrol model section below shows the assumptions.
+ </Show>
+ </p>
+ )}
+ </Show>
+ <Show when={props.state.patrolIntervalAutoAdjust()}>
+ {(adjust) => (
+ <p class="mt-1 text-xs text-amber-700 dark:text-amber-300">
+ Changed from {formatPatrolInterval(adjust().from).toLowerCase()} to keep the
+ per-token bill down. Pick another option above to override it.
+ </p>
+ )}
+ </Show>
</div>
</div>
diff --git a/frontend-modern/src/components/Settings/__tests__/AISettings.test.tsx b/frontend-modern/src/components/Settings/__tests__/AISettings.test.tsx
index 3f93f772d0..ed3f85bef9 100644
--- a/frontend-modern/src/components/Settings/__tests__/AISettings.test.tsx
+++ b/frontend-modern/src/components/Settings/__tests__/AISettings.test.tsx
@@ -20,6 +20,8 @@ const testProviderMock = vi.fn();
const testConnectionMock = vi.fn();
const runDiscoveryRefreshMock = vi.fn();
const runPatrolModelReadinessMock = vi.fn();
+const getPatrolCostPreviewMock = vi.fn();
+const getPatrolModelGuidanceMock = vi.fn();
const fetchAgentCapabilitiesManifestMock = vi.fn();
const listSessionsMock = vi.fn();
const summarizeSessionMock = vi.fn();
@@ -61,6 +63,11 @@ vi.mock('@/api/patrol', () => ({
runPatrolModelReadiness: (...args: unknown[]) => runPatrolModelReadinessMock(...args),
}));
+vi.mock('@/api/aiPatrolCost', () => ({
+ getPatrolCostPreview: (...args: unknown[]) => getPatrolCostPreviewMock(...args),
+ getPatrolModelGuidance: (...args: unknown[]) => getPatrolModelGuidanceMock(...args),
+}));
+
vi.mock('@/api/agentCapabilities', async (importOriginal) => {
const actual = await importOriginal<typeof import('@/api/agentCapabilities')>();
return {
@@ -157,6 +164,8 @@ const resetAllMocks = () => {
testConnectionMock.mockReset();
runDiscoveryRefreshMock.mockReset();
runPatrolModelReadinessMock.mockReset();
+ getPatrolCostPreviewMock.mockReset();
+ getPatrolModelGuidanceMock.mockReset();
fetchAgentCapabilitiesManifestMock.mockReset();
listSessionsMock.mockReset();
summarizeSessionMock.mockReset();
@@ -181,6 +190,8 @@ const setupDefaultMocks = () => {
entitlementsMock.mockReturnValue({ trial_eligible: true });
getSettingsMock.mockResolvedValue(baseSettings());
getModelsMock.mockResolvedValue({ models: [] });
+ getPatrolCostPreviewMock.mockResolvedValue(null);
+ getPatrolModelGuidanceMock.mockResolvedValue({ rules: [] });
testConnectionMock.mockResolvedValue({ success: true, message: 'ok' });
testProviderMock.mockResolvedValue({
success: true,
@@ -1544,3 +1555,280 @@ describe('AISettings provider setup flow', () => {
).not.toBeInTheDocument();
});
});
+
+describe('AISettings Patrol cost preview and model guidance', () => {
+ const flashProjection = (overrides: Record<string, unknown> = {}) => ({
+ provider: 'gemini',
+ model: 'gemini-2.5-flash',
+ model_route: 'gemini:gemini-2.5-flash',
+ billed_per_token: true,
+ pricing_known: true,
+ pricing_as_of: '2026-06-04',
+ input_usd_per_mtok: 0.3,
+ output_usd_per_mtok: 2.5,
+ per_run_input_tokens: 104_528,
+ per_run_output_tokens: 4_491,
+ per_run_source: 'default',
+ history_run_count: 0,
+ per_run_usd: 0.0426,
+ interval_minutes: 360,
+ scheduled_runs_per_day: 4,
+ triggered_runs_per_day: 0,
+ triggered_per_run_usd: 0,
+ scheduled_projected_30d_usd: 5.11,
+ projected_30d_usd: 5.11,
+ interval_estimates: [
+ { interval_minutes: 60, scheduled_runs_per_day: 24, projected_30d_usd: 30.67 },
+ { interval_minutes: 180, scheduled_runs_per_day: 8, projected_30d_usd: 10.22 },
+ { interval_minutes: 360, scheduled_runs_per_day: 4, projected_30d_usd: 5.11 },
+ { interval_minutes: 720, scheduled_runs_per_day: 2, projected_30d_usd: 2.56 },
+ { interval_minutes: 1440, scheduled_runs_per_day: 1, projected_30d_usd: 1.28 },
+ ],
+ budget_usd_30d: 20,
+ spend_30d_usd: 3.2,
+ spend_30d_known: true,
+ patrol_spend_30d_usd: 2.5,
+ budget_reached: false,
+ recommended_interval_minutes: 360,
+ recommendation_reason: 'fits_budget_share',
+ recommendation_target_usd: 10,
+ ...overrides,
+ });
+
+ const sonnetProjection = (intervalMinutes: number) =>
+ flashProjection({
+ provider: 'anthropic',
+ model: 'claude-sonnet-5',
+ model_route: 'anthropic:claude-sonnet-5',
+ input_usd_per_mtok: 2,
+ output_usd_per_mtok: 10,
+ per_run_usd: 0.254,
+ interval_minutes: intervalMinutes,
+ scheduled_runs_per_day: 1440 / intervalMinutes,
+ scheduled_projected_30d_usd: intervalMinutes === 360 ? 30.5 : 7.62,
+ projected_30d_usd: intervalMinutes === 360 ? 30.5 : 7.62,
+ interval_estimates: [
+ { interval_minutes: 60, scheduled_runs_per_day: 24, projected_30d_usd: 183 },
+ { interval_minutes: 180, scheduled_runs_per_day: 8, projected_30d_usd: 61 },
+ { interval_minutes: 360, scheduled_runs_per_day: 4, projected_30d_usd: 30.5 },
+ { interval_minutes: 720, scheduled_runs_per_day: 2, projected_30d_usd: 15.25 },
+ { interval_minutes: 1440, scheduled_runs_per_day: 1, projected_30d_usd: 7.62 },
+ ],
+ recommended_interval_minutes: 1440,
+ });
+
+ const cloudSettings = (overrides: Partial<AISettingsType> = {}): AISettingsType => ({
+ ...baseSettings(),
+ enabled: true,
+ configured: true,
+ model: 'gemini:gemini-2.5-flash',
+ gemini_configured: true,
+ anthropic_configured: true,
+ ollama_configured: true,
+ configured_providers: ['gemini', 'anthropic', 'ollama'],
+ patrol_interval_minutes: 360,
+ cost_budget_usd_30d: 20,
+ ...overrides,
+ });
+
+ const cloudModels = () => ({
+ models: [
+ {
+ id: 'gemini:gemini-2.5-flash',
+ name: 'Gemini 2.5 Flash',
+ provider: 'gemini',
+ notable: true,
+ },
+ {
+ id: 'gemini:gemini-2.5-flash-lite',
+ name: 'Gemini 2.5 Flash-Lite',
+ provider: 'gemini',
+ notable: true,
+ },
+ {
+ id: 'anthropic:claude-sonnet-5',
+ name: 'Claude Sonnet 5',
+ provider: 'anthropic',
+ notable: true,
+ },
+ { id: 'ollama:qwen3:8b', name: 'qwen3:8b', provider: 'ollama', notable: true },
+ ],
+ });
+
+ const guidance = () => ({
+ rules: [
+ {
+ provider: 'gemini',
+ model_prefix: 'gemini-',
+ exclude: ['!flash-lite'],
+ level: 'caution',
+ reason: 'Flash-Lite could not file Patrol verdicts on a Pro install.',
+ },
+ {
+ provider: 'gemini',
+ model_prefix: 'gemini-2.5-flash',
+ exclude: ['lite'],
+ level: 'suggested',
+ reason: 'Lowest-cost standard tier for this provider.',
+ },
+ {
+ provider: 'ollama',
+ model_prefix: 'qwen3:8b',
+ model_exact: true,
+ level: 'recommended',
+ reason: 'Passed the Patrol tool-call check.',
+ },
+ ],
+ });
+
+ it('shows the monthly estimate, assumptions, and spend against budget next to the Patrol model', async () => {
+ getSettingsMock.mockResolvedValue(cloudSettings());
+ getModelsMock.mockResolvedValue(cloudModels());
+ getPatrolCostPreviewMock.mockResolvedValue(flashProjection());
+ getPatrolModelGuidanceMock.mockResolvedValue(guidance());
+
+ renderComponent('patrol');
+
+ const preview = await screen.findByTestId('patrol-cost-preview');
+ expect(preview).toHaveTextContent('About $5.11 a month for Patrol');
+ expect(preview).toHaveTextContent(
+ '4 scheduled runs a day × about 105k tokens in and 4k out per run',
+ );
+ expect(preview).toHaveTextContent('roughly three quarters of a word');
+ expect(preview).toHaveTextContent(
+ 'Spent so far: about $3.20 of your $20 30-day budget ($2.50 of that was Patrol).',
+ );
+ expect(getPatrolCostPreviewMock).toHaveBeenCalledWith(
+ { model: 'gemini:gemini-2.5-flash', intervalMinutes: 360 },
+ expect.anything(),
+ );
+ // The schedule options carry the same estimate so the trade-off is visible where it is made.
+ const schedule = screen.getByLabelText('Schedule') as HTMLSelectElement;
+ const daily = Array.from(schedule.options).find((option) => option.value === '1440');
+ expect(daily?.textContent).toContain('≈ $1.28/month');
+ expect(screen.getByTestId('patrol-schedule-cost')).toHaveTextContent(
+ 'About $5.11 a month for Patrol with gemini:gemini-2.5-flash. Estimate.',
+ );
+ });
+
+ it('pins guided models at the top of the Patrol picker and warns on known failures', async () => {
+ getSettingsMock.mockResolvedValue(
+ cloudSettings({ patrol_model: 'gemini:gemini-2.5-flash-lite' }),
+ );
+ getModelsMock.mockResolvedValue(cloudModels());
+ getPatrolCostPreviewMock.mockResolvedValue(flashProjection());
+ getPatrolModelGuidanceMock.mockResolvedValue(guidance());
+
+ renderComponent('patrol');
+
+ // The selection itself carries the warning once the picker is closed.
+ expect(
+ await screen.findByText('Flash-Lite could not file Patrol verdicts on a Pro install.'),
+ ).toBeInTheDocument();
+
+ fireEvent.click(screen.getByTitle('Select Patrol model'));
+ expect(await screen.findByText('Suggested for Patrol')).toBeInTheDocument();
+ expect(screen.getByText('Recommended for Patrol')).toBeInTheDocument();
+ expect(screen.getByText('Suggested starting point')).toBeInTheDocument();
+ expect(screen.getAllByText('Caution').length).toBeGreaterThan(0);
+ const listbox = screen.getByRole('listbox', { name: 'Select Patrol model' });
+ const optionNames = within(listbox)
+ .getAllByRole('option')
+ .map((option) => option.getAttribute('aria-label') || '');
+ const pinnedOllama = optionNames.findIndex((name) => name.startsWith('qwen3:8b'));
+ const pinnedFlash = optionNames.findIndex((name) => name.startsWith('Gemini 2.5 Flash.'));
+ const groupedLite = optionNames.findIndex((name) => name.startsWith('Gemini 2.5 Flash-Lite'));
+ expect(pinnedOllama).toBeGreaterThanOrEqual(0);
+ expect(pinnedFlash).toBeGreaterThan(pinnedOllama);
+ expect(groupedLite).toBeGreaterThan(pinnedFlash);
+ });
+
+ it('slows the default schedule when a per-token model is picked and explains why', async () => {
+ getSettingsMock.mockResolvedValue(cloudSettings({ model: 'ollama:qwen3:8b' }));
+ getModelsMock.mockResolvedValue(cloudModels());
+ getPatrolCostPreviewMock.mockImplementation(
+ async (query: { model?: string; intervalMinutes?: number }) =>
+ query.model === 'anthropic:claude-sonnet-5'
+ ? sonnetProjection(query.intervalMinutes ?? 360)
+ : flashProjection({
+ provider: 'ollama',
+ model: 'qwen3:8b',
+ model_route: 'ollama:qwen3:8b',
+ billed_per_token: false,
+ projected_30d_usd: 0,
+ scheduled_projected_30d_usd: 0,
+ recommended_interval_minutes: 0,
+ recommendation_reason: 'not_billed_per_token',
+ }),
+ );
+
+ renderComponent('patrol');
+
+ expect(await screen.findByTestId('patrol-cost-preview')).toHaveTextContent(
+ 'No per-token bill for Patrol',
+ );
+ const schedule = screen.getByLabelText('Schedule') as HTMLSelectElement;
+ expect(schedule.value).toBe('360');
+
+ fireEvent.click(screen.getByTitle('Select Patrol model'));
+ fireEvent.click(await screen.findByRole('option', { name: /^Claude Sonnet 5/ }));
+
+ await waitFor(() => {
+ expect(schedule.value).toBe('1440');
+ });
+ expect(await screen.findByTestId('patrol-schedule-auto-adjust')).toHaveTextContent(
+ 'Schedule set to once a day because claude-sonnet-5 bills per token: about $7.62 a month instead of $30.50 at every 6 hours',
+ );
+ expect(screen.getByTestId('patrol-cost-preview')).toHaveTextContent(
+ 'Change it under Patrol › Schedule.',
+ );
+ expect(screen.getByTestId('patrol-schedule-cost').parentElement).toHaveTextContent(
+ 'Changed from every 6 hours to keep the per-token bill down.',
+ );
+ });
+
+ it('leaves a schedule the install already chose untouched when the model changes', async () => {
+ getSettingsMock.mockResolvedValue(
+ cloudSettings({ model: 'ollama:qwen3:8b', patrol_interval_minutes: 720 }),
+ );
+ getModelsMock.mockResolvedValue(cloudModels());
+ getPatrolCostPreviewMock.mockImplementation(
+ async (query: { model?: string; intervalMinutes?: number }) =>
+ query.model === 'anthropic:claude-sonnet-5'
+ ? sonnetProjection(query.intervalMinutes ?? 720)
+ : flashProjection({ billed_per_token: false, recommended_interval_minutes: 0 }),
+ );
+
+ renderComponent('patrol');
+ await screen.findByTestId('patrol-cost-preview');
+ const schedule = screen.getByLabelText('Schedule') as HTMLSelectElement;
+ expect(schedule.value).toBe('720');
+
+ fireEvent.click(screen.getByTitle('Select Patrol model'));
+ fireEvent.click(await screen.findByRole('option', { name: /^Claude Sonnet 5/ }));
+
+ await waitFor(() => {
+ expect(getPatrolCostPreviewMock).toHaveBeenCalledWith(
+ { model: 'anthropic:claude-sonnet-5', intervalMinutes: 720 },
+ expect.anything(),
+ );
+ });
+ expect(schedule.value).toBe('720');
+ expect(screen.queryByTestId('patrol-schedule-auto-adjust')).not.toBeInTheDocument();
+ });
+
+ it('shows a reached budget as a pause, not a healthy estimate', async () => {
+ getSettingsMock.mockResolvedValue(cloudSettings());
+ getModelsMock.mockResolvedValue(cloudModels());
+ getPatrolCostPreviewMock.mockResolvedValue(
+ flashProjection({ spend_30d_usd: 20.4, budget_reached: true }),
+ );
+
+ renderComponent('patrol');
+
+ const preview = await screen.findByTestId('patrol-cost-preview');
+ expect(preview).toHaveTextContent(
+ 'Budget reached: about $20.40 of your $20 30-day budget is spent, so Patrol is paused',
+ );
+ });
+});
diff --git a/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts b/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts
index 3a5cec67b4..d566946ce6 100644
--- a/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts
+++ b/frontend-modern/src/components/Settings/__tests__/settingsArchitecture.test.ts
@@ -116,6 +116,25 @@ const settingsRuntimeSources = import.meta.glob(['../*.tsx', '../ConnectionEdito
}) as Record<string, string>;
describe('settings architecture guardrails', () => {
+ it('keeps the Patrol cost preview on the canonical cost-preview API and presentation helper', () => {
+ // The price table and the install's run history live on the server; the
+ // settings surface must not re-derive dollars from model names.
+ expect(aiSettingsStateSource).toContain("from '@/api/aiPatrolCost'");
+ expect(aiSettingsStateSource).toContain('getPatrolCostPreview({ model, intervalMinutes }');
+ expect(aiSettingsStateSource).toContain('getPatrolIntervalAutoAdjust(projection, {');
+ expect(aiModelSelectionSectionSource).toContain(
+ 'getPatrolCostPresentation(state.patrolCostPreview())',
+ );
+ expect(aiModelSelectionSectionSource).toContain(
+ 'resolvePatrolModelGuidance(models(), state.patrolModelGuidance())',
+ );
+ expect(aiSettingsSource).toContain(
+ 'getPatrolIntervalCostHint(props.state.patrolCostPreview(), option.value)',
+ );
+ expect(aiSettingsSource).not.toMatch(/usd_per_mtok|per_million/i);
+ expect(aiModelSelectionSectionSource).not.toMatch(/usd_per_mtok/i);
+ });
+
it('keeps the audit log filter bar free of a saved-views affordance', () => {
// A saved view was only the page's URL query string; bookmarks already
// cover that and survive a new browser, so the control was removed.
diff --git a/frontend-modern/src/components/Settings/useAISettingsState.ts b/frontend-modern/src/components/Settings/useAISettingsState.ts
index e87d929c5d..1a2472425f 100644
--- a/frontend-modern/src/components/Settings/useAISettingsState.ts
+++ b/frontend-modern/src/components/Settings/useAISettingsState.ts
@@ -1,9 +1,10 @@
-import { createMemo, createSignal, onCleanup, onMount } from 'solid-js';
+import { createEffect, createMemo, createSignal, on, onCleanup, onMount } from 'solid-js';
import { createStore } from 'solid-js/store';
import { AIAPI } from '@/api/ai';
import { AIChatAPI, type ChatSession } from '@/api/aiChat';
import { runDiscoveryRefresh } from '@/api/discovery';
import { runPatrolModelReadiness, type PatrolModelReadinessResponse } from '@/api/patrol';
+import { getPatrolCostPreview, getPatrolModelGuidance } from '@/api/aiPatrolCost';
import {
AI_PROVIDERS,
createInitialProviderHealth,
@@ -24,7 +25,18 @@ import { getUpgradeActionDestination } from '@/stores/licenseCommercial';
import { presentationPolicyHidesUpgradePrompts } from '@/stores/sessionPresentationPolicy';
import { aiChatStore } from '@/stores/aiChat';
import { notificationStore } from '@/stores/notifications';
-import type { AISettings as AISettingsType, AIProvider, AuthMethod, ModelInfo } from '@/types/ai';
+import type {
+ AISettings as AISettingsType,
+ AIProvider,
+ AuthMethod,
+ ModelInfo,
+ PatrolCostProjection,
+ PatrolModelGuidanceResponse,
+} from '@/types/ai';
+import {
+ getPatrolIntervalAutoAdjust,
+ type PatrolIntervalAutoAdjust,
+} from '@/utils/aiPatrolCostPresentation';
import { normalizeAIControlLevel, type AIControlLevel } from '@/utils/aiControlLevelPresentation';
import { getAIProviderDisplayName, getProviderFromModelId } from '@/utils/aiProviderPresentation';
import {
@@ -270,6 +282,86 @@ export const useAISettingsState = (options: AISettingsStateOptions = {}) => {
setPatrolModelReadinessResult(data?.patrol_model_readiness ?? null);
};
+ // Cost preview and model guidance for the Patrol model choice. The server
+ // owns the price table and the install's run history; the form only says
+ // which model and schedule to price.
+ const [patrolCostPreview, setPatrolCostPreview] = createSignal<PatrolCostProjection | null>(null);
+ const [patrolCostPreviewLoading, setPatrolCostPreviewLoading] = createSignal(false);
+ const [patrolModelGuidance, setPatrolModelGuidance] =
+ createSignal<PatrolModelGuidanceResponse | null>(null);
+ const [patrolIntervalAutoAdjust, setPatrolIntervalAutoAdjust] =
+ createSignal<PatrolIntervalAutoAdjust | null>(null);
+ let patrolCostPreviewAbortController: AbortController | null = null;
+ let patrolCostPreviewTimer: ReturnType<typeof setTimeout> | null = null;
+ let patrolCostPreviewUserSelection = false;
+
+ const loadPatrolModelGuidance = async () => {
+ try {
+ setPatrolModelGuidance(await getPatrolModelGuidance());
+ } catch (error) {
+ logger.debug('[AISettings] Failed to load Patrol model guidance:', error);
+ }
+ };
+
+ const refreshPatrolCostPreview = async () => {
+ const userSelection = patrolCostPreviewUserSelection;
+ patrolCostPreviewUserSelection = false;
+ const model = effectivePatrolModel();
+ const intervalMinutes = form.patrolIntervalMinutes;
+ patrolCostPreviewAbortController?.abort();
+ if (!model) {
+ patrolCostPreviewAbortController = null;
+ setPatrolCostPreview(null);
+ setPatrolCostPreviewLoading(false);
+ return;
+ }
+ const controller = new AbortController();
+ patrolCostPreviewAbortController = controller;
+ setPatrolCostPreviewLoading(true);
+ try {
+ const projection = await getPatrolCostPreview({ model, intervalMinutes }, controller.signal);
+ if (controller.signal.aborted) return;
+ setPatrolCostPreview(projection ?? null);
+ if (userSelection && projection) {
+ const adjust = getPatrolIntervalAutoAdjust(projection, {
+ currentIntervalMinutes: form.patrolIntervalMinutes,
+ savedIntervalMinutes: settings()?.patrol_interval_minutes ?? 360,
+ });
+ if (adjust) {
+ setForm('patrolIntervalMinutes', adjust.to);
+ setPatrolIntervalAutoAdjust(adjust);
+ }
+ }
+ } catch (error) {
+ if (controller.signal.aborted) return;
+ logger.debug('[AISettings] Failed to load Patrol cost preview:', error);
+ setPatrolCostPreview(null);
+ } finally {
+ if (patrolCostPreviewAbortController === controller) {
+ patrolCostPreviewAbortController = null;
+ setPatrolCostPreviewLoading(false);
+ }
+ }
+ };
+
+ const schedulePatrolCostPreviewRefresh = () => {
+ if (patrolCostPreviewTimer) clearTimeout(patrolCostPreviewTimer);
+ patrolCostPreviewTimer = setTimeout(() => {
+ patrolCostPreviewTimer = null;
+ void refreshPatrolCostPreview();
+ }, 150);
+ };
+
+ type ModelFormKey = 'model' | 'chatModel' | 'patrolModel' | 'discoveryModel';
+ // Model picks made by the operator (as opposed to loads and resets) are
+ // the only moment the schedule may be defaulted for a per-token model.
+ const handleModelSelection = (formKey: ModelFormKey, modelId: string) => {
+ if (formKey === 'model' || formKey === 'patrolModel') {
+ patrolCostPreviewUserSelection = true;
+ }
+ setForm(formKey, modelId);
+ };
+
const [showSetupModal, setShowSetupModal] = createSignal(false);
const [setupProvider, setSetupProvider] = createSignal<AIProvider>('anthropic');
const [setupApiKey, setSetupApiKey] = createSignal('');
@@ -359,6 +451,8 @@ export const useAISettingsState = (options: AISettingsStateOptions = {}) => {
current.ollama_configured),
);
});
+
+ const effectivePatrolModel = createMemo(() => (form.patrolModel || form.model).trim());
const upgradeAutofixDestination = () => getUpgradeActionDestination('ai_autofix');
const hasProviderBackedModels = (data: AISettingsType | null | undefined) =>
@@ -692,6 +786,7 @@ export const useAISettingsState = (options: AISettingsStateOptions = {}) => {
controller.signal,
);
setPatrolModelReadinessResult(result);
+ void loadPatrolModelGuidance();
} catch (error) {
const errorName =
typeof error === 'object' && error !== null && 'name' in error ? String(error.name) : '';
@@ -747,6 +842,7 @@ export const useAISettingsState = (options: AISettingsStateOptions = {}) => {
resetForm(data);
syncModelCatalogForSettings(data);
hydratePatrolModelReadinessFromSettings(data);
+ void loadPatrolModelGuidance();
void runProviderPreflight(data);
} catch (error) {
logger.error('[AISettings] Failed to load settings:', error);
@@ -1317,7 +1413,21 @@ export const useAISettingsState = (options: AISettingsStateOptions = {}) => {
void loadSettings();
});
- onCleanup(() => patrolModelReadinessAbortController?.abort());
+ createEffect(
+ on([effectivePatrolModel, () => form.patrolIntervalMinutes, () => settings()], () => {
+ const adjust = patrolIntervalAutoAdjust();
+ if (adjust && form.patrolIntervalMinutes !== adjust.to) {
+ setPatrolIntervalAutoAdjust(null);
+ }
+ schedulePatrolCostPreviewRefresh();
+ }),
+ );
+
+ onCleanup(() => {
+ patrolModelReadinessAbortController?.abort();
+ patrolCostPreviewAbortController?.abort();
+ if (patrolCostPreviewTimer) clearTimeout(patrolCostPreviewTimer);
+ });
return {
alertAnalysisLocked,
@@ -1327,8 +1437,10 @@ export const useAISettingsState = (options: AISettingsStateOptions = {}) => {
chatSessionsError,
chatSessionsLoading,
discoveryRunRunning,
+ effectivePatrolModel,
expandedProviders,
form,
+ handleModelSelection,
formatSessionLabel,
handleClearProvider,
handleCloseSetupModal,
@@ -1348,6 +1460,10 @@ export const useAISettingsState = (options: AISettingsStateOptions = {}) => {
loadSettings,
modelsError,
modelsLoading,
+ patrolCostPreview,
+ patrolCostPreviewLoading,
+ patrolIntervalAutoAdjust,
+ patrolModelGuidance,
patrolModelReadinessResult,
patrolModelReadinessRunning,
preflightLastCheckedAt,
diff --git a/frontend-modern/src/components/shared/AIModelPicker.tsx b/frontend-modern/src/components/shared/AIModelPicker.tsx
index ebdb092ead..366cbf9f89 100644
--- a/frontend-modern/src/components/shared/AIModelPicker.tsx
+++ b/frontend-modern/src/components/shared/AIModelPicker.tsx
@@ -40,6 +40,17 @@ export type AIModelPickerModelSection = {
modelIds: string[];
};
+/**
+ * Per-model marker rendered beside the model name (badge) and under its
+ * description (note). Used for Patrol guidance: verified / recommended /
+ * suggested / caution, with the one-line reason.
+ */
+export type AIModelPickerAnnotation = {
+ badge: string;
+ note?: string;
+ tone?: 'positive' | 'warning' | 'neutral';
+};
+
export interface AIModelPickerProps {
models: ModelInfo[];
selectedModel: string;
@@ -47,6 +58,7 @@ export interface AIModelPickerProps {
defaultOption?: AIModelPickerDefaultOption;
extraOptions?: AIModelPickerExtraOption[];
modelSections?: AIModelPickerModelSection[];
+ modelAnnotations?: Record<string, AIModelPickerAnnotation>;
emptySelectionLabel?: string;
selectionBadge?: string;
title?: string;
@@ -119,6 +131,33 @@ const modelRouteSecondaryId = (entry: ResolvedModelRoute) => {
return model.id;
};
+const annotationBadgeClass = (tone?: AIModelPickerAnnotation['tone']) => {
+ switch (tone) {
+ case 'warning':
+ return 'shrink-0 rounded border border-amber-200 bg-amber-100 px-1.5 py-0.5 text-[10px] font-semibold text-amber-800 dark:border-amber-800 dark:bg-amber-950/60 dark:text-amber-200';
+ case 'positive':
+ return 'shrink-0 rounded border border-green-200 bg-green-100 px-1.5 py-0.5 text-[10px] font-semibold text-green-800 dark:border-green-800 dark:bg-green-950/60 dark:text-green-200';
+ default:
+ return 'shrink-0 rounded border border-border bg-surface-alt px-1.5 py-0.5 text-[10px] font-semibold text-muted';
+ }
+};
+
+const ModelAnnotationBadge: Component<{ annotation: AIModelPickerAnnotation }> = (props) => (
+ <span class={annotationBadgeClass(props.annotation.tone)}>{props.annotation.badge}</span>
+);
+
+const ModelAnnotationNote: Component<{ annotation: AIModelPickerAnnotation }> = (props) => (
+ <Show when={props.annotation.note}>
+ <div
+ class={`text-[10px] ${
+ props.annotation.tone === 'warning' ? 'text-amber-700 dark:text-amber-300' : 'text-muted'
+ }`}
+ >
+ {props.annotation.note}
+ </div>
+ </Show>
+);
+
const CurrentSelectionBadge: Component = () => (
<span class="shrink-0 rounded border border-blue-200 bg-blue-100 px-1.5 py-0.5 text-[10px] font-semibold uppercase text-blue-700 dark:border-blue-800 dark:bg-blue-950/60 dark:text-blue-200">
{' '}
@@ -168,6 +207,14 @@ export const AIModelPicker: Component<AIModelPickerProps> = (props) => {
let buttonRef: HTMLButtonElement | undefined;
let searchInputRef: HTMLInputElement | undefined;
const pickerId = createUniqueId();
+ const annotationFor = (modelId: string): AIModelPickerAnnotation | undefined =>
+ props.modelAnnotations?.[modelId];
+ // Aria details are joined with ". "; notes are full sentences, so drop the
+ // trailing period to avoid "install.." in the accessible name.
+ const annotationAria = (modelId: string): [string | undefined, string | undefined] => {
+ const annotation = annotationFor(modelId);
+ return [annotation?.badge, annotation?.note?.replace(/\.\s*$/, '')];
+ };
const optionRefs = new Map<string, HTMLButtonElement>();
let lastOpenRequest = props.openRequest || 0;
@@ -821,7 +868,12 @@ export const AIModelPicker: Component<AIModelPickerProps> = (props) => {
aria-label={optionAriaLabel(
modelRouteLabel(entry),
isSelectedRoute(entry.id),
- [modelRouteDescription(entry), modelRouteSecondaryId(entry)],
+ [
+ annotationAria(entry.id)[0],
+ modelRouteDescription(entry),
+ annotationAria(entry.id)[1],
+ modelRouteSecondaryId(entry),
+ ],
)}
class={optionClass(isSelectedRoute(entry.id))}
>
@@ -829,6 +881,9 @@ export const AIModelPicker: Component<AIModelPickerProps> = (props) => {
<span class="min-w-0 flex-1 truncate font-medium text-base-content">
{modelRouteLabel(entry)}
</span>
+ <Show when={annotationFor(entry.id)}>
+ {(annotation) => <ModelAnnotationBadge annotation={annotation()} />}
+ </Show>
<Show when={isSelectedRoute(entry.id)}>
<CurrentSelectionBadge />
</Show>
@@ -838,6 +893,9 @@ export const AIModelPicker: Component<AIModelPickerProps> = (props) => {
{modelRouteDescription(entry)}
</div>
</Show>
+ <Show when={annotationFor(entry.id)}>
+ {(annotation) => <ModelAnnotationNote annotation={annotation()} />}
+ </Show>
<Show when={modelRouteSecondaryId(entry)}>
{(modelId) => <div class="text-[10px] text-muted">{modelId()}</div>}
</Show>
@@ -878,7 +936,12 @@ export const AIModelPicker: Component<AIModelPickerProps> = (props) => {
aria-label={optionAriaLabel(
formatAIModelRouteLabel(model),
isSelectedRoute(model.id),
- [model.description, secondaryModelId()],
+ [
+ annotationAria(model.id)[0],
+ model.description,
+ annotationAria(model.id)[1],
+ secondaryModelId(),
+ ],
)}
class={optionClass(isSelectedRoute(model.id))}
>
@@ -886,6 +949,9 @@ export const AIModelPicker: Component<AIModelPickerProps> = (props) => {
<span class="min-w-0 flex-1 truncate font-medium text-base-content">
{formatAIModelRouteLabel(model)}
</span>
+ <Show when={annotationFor(model.id)}>
+ {(annotation) => <ModelAnnotationBadge annotation={annotation()} />}
+ </Show>
<Show when={isSelectedRoute(model.id)}>
<CurrentSelectionBadge />
</Show>
@@ -895,6 +961,9 @@ export const AIModelPicker: Component<AIModelPickerProps> = (props) => {
{model.description}
</div>
</Show>
+ <Show when={annotationFor(model.id)}>
+ {(annotation) => <ModelAnnotationNote annotation={annotation()} />}
+ </Show>
<Show when={secondaryModelId()}>
{(modelId) => <div class="text-[10px] text-muted">{modelId()}</div>}
</Show>
diff --git a/frontend-modern/src/components/shared/__tests__/AIModelPicker.test.tsx b/frontend-modern/src/components/shared/__tests__/AIModelPicker.test.tsx
index 473f8f449c..e15d66b0ac 100644
--- a/frontend-modern/src/components/shared/__tests__/AIModelPicker.test.tsx
+++ b/frontend-modern/src/components/shared/__tests__/AIModelPicker.test.tsx
@@ -802,4 +802,41 @@ describe('AIModelPicker', () => {
expect(screen.queryByText('Openrouter:')).not.toBeInTheDocument();
expect(screen.queryByText(/openrouter\.ai/)).not.toBeInTheDocument();
});
+
+ it('renders Patrol guidance badges and notes in pinned sections and provider groups', () => {
+ render(() => (
+ <AIModelPicker
+ models={models}
+ selectedModel=""
+ onModelSelect={vi.fn()}
+ title="Select Patrol model"
+ modelSections={[{ title: 'Suggested for Patrol', modelIds: ['openai:gpt-5.1-mini'] }]}
+ modelAnnotations={{
+ 'openai:gpt-5.1-mini': {
+ badge: 'Suggested starting point',
+ note: 'Lowest-cost standard tier for this provider.',
+ tone: 'positive',
+ },
+ 'openrouter:minimax/minimax-m2.5': {
+ badge: 'Caution',
+ note: 'Dropped Patrol tool calls on a Pro install.',
+ tone: 'warning',
+ },
+ }}
+ />
+ ));
+
+ fireEvent.click(screen.getByTitle('Select Patrol model'));
+
+ expect(screen.getByText('Suggested for Patrol')).toBeInTheDocument();
+ expect(screen.getByText('Suggested starting point')).toBeInTheDocument();
+ expect(screen.getByText('Lowest-cost standard tier for this provider.')).toBeInTheDocument();
+ expect(screen.getByText('Caution')).toBeInTheDocument();
+ expect(screen.getByText('Dropped Patrol tool calls on a Pro install.')).toBeInTheDocument();
+ expect(
+ screen.getByRole('option', {
+ name: 'MiniMax: MiniMax M2.5 via OpenRouter. Caution. Current OpenRouter model. Dropped Patrol tool calls on a Pro install. openrouter:minimax/minimax-m2.5',
+ }),
+ ).toBeInTheDocument();
+ });
});
diff --git a/frontend-modern/src/features/patrol/PatrolIntelligenceBanners.tsx b/frontend-modern/src/features/patrol/PatrolIntelligenceBanners.tsx
index be4a0dc71a..0a6c19ff17 100644
--- a/frontend-modern/src/features/patrol/PatrolIntelligenceBanners.tsx
+++ b/frontend-modern/src/features/patrol/PatrolIntelligenceBanners.tsx
@@ -11,7 +11,10 @@ import { formatRelativeTime } from '@/utils/format';
import { getAIProviderDisplayName } from '@/utils/aiProviderPresentation';
import { getPatrolSetupAction } from '@/utils/patrolRuntimeActions';
import { getPatrolAutonomyAvailabilityPresentation } from './patrolAutonomyAvailability';
-import type { PatrolIntelligenceState } from './usePatrolIntelligenceState';
+import {
+ resolvePatrolBlockedActionCause,
+ type PatrolIntelligenceState,
+} from './usePatrolIntelligenceState';
// Strip a provider prefix ("deepseek:deepseek-v4-flash" -> "deepseek-v4-flash")
// so the model id reads cleanly to operators without losing the provider
@@ -24,6 +27,11 @@ function modelIdWithoutProviderPrefix(modelId: string | undefined): string {
export function PatrolIntelligenceBanners(props: { state: PatrolIntelligenceState }) {
const state = props.state;
+ const setupAction = createMemo(() =>
+ getPatrolSetupAction(
+ resolvePatrolBlockedActionCause(state.blockedCause(), state.patrolReadiness()?.cause),
+ ),
+ );
const autonomyAvailability = createMemo(() =>
getPatrolAutonomyAvailabilityPresentation({
autoFixLocked: state.autoFixLocked(),
@@ -229,11 +237,11 @@ export function PatrolIntelligenceBanners(props: { state: PatrolIntelligenceStat
</div>
<Show when={shouldShowReadinessAction()}>
<a
- href={getPatrolSetupAction(state.patrolReadiness()?.cause).href}
+ href={setupAction().href}
class="inline-flex items-center justify-center gap-2 px-3 py-1.5 text-xs font-semibold rounded-md border border-amber-200 bg-amber-100 text-amber-900 transition-colors hover:bg-amber-200 dark:border-amber-700 dark:bg-amber-900 dark:text-amber-100 dark:hover:bg-amber-900"
>
<SettingsIcon class="w-3.5 h-3.5" />
- {getPatrolSetupAction(state.patrolReadiness()?.cause).label}
+ {setupAction().label}
</a>
</Show>
</div>
@@ -261,11 +269,11 @@ export function PatrolIntelligenceBanners(props: { state: PatrolIntelligenceStat
</div>
<div class="flex items-center gap-2">
<a
- href={getPatrolSetupAction(state.patrolReadiness()?.cause).href}
+ href={setupAction().href}
class="inline-flex items-center justify-center gap-2 px-3 py-1.5 text-xs font-semibold text-amber-900 dark:text-amber-100 bg-amber-100 dark:bg-amber-900 border border-amber-200 dark:border-amber-700 rounded-md hover:bg-amber-200 dark:hover:bg-amber-900 transition-colors"
>
<SettingsIcon class="w-3.5 h-3.5" />
- {getPatrolSetupAction(state.patrolReadiness()?.cause).label}
+ {setupAction().label}
</a>
</div>
</div>
diff --git a/frontend-modern/src/features/patrol/PatrolIntelligenceHeader.tsx b/frontend-modern/src/features/patrol/PatrolIntelligenceHeader.tsx
index 91fe7ba455..0d2721d7df 100644
--- a/frontend-modern/src/features/patrol/PatrolIntelligenceHeader.tsx
+++ b/frontend-modern/src/features/patrol/PatrolIntelligenceHeader.tsx
@@ -24,7 +24,10 @@ import type { PatrolConfigurationFailureInput } from './patrolInvestigationConte
import { getPatrolAutonomyAvailabilityPresentation } from './patrolAutonomyAvailability';
import { PATROL_AUTONOMY_POLICY_PRESENTATION } from './patrolControlPresentation';
import { PATROL_AUTONOMY_EXPERIENCE } from './patrolHomePresentation';
-import type { PatrolIntelligenceState } from './usePatrolIntelligenceState';
+import {
+ resolvePatrolBlockedActionCause,
+ type PatrolIntelligenceState,
+} from './usePatrolIntelligenceState';
import { PatrolAutopilotAcknowledgementDialog } from './PatrolAutopilotAcknowledgementDialog';
export { PATROL_AUTONOMY_POLICY_PRESENTATION } from './patrolControlPresentation';
@@ -79,7 +82,10 @@ export function PatrolIntelligenceHeader(props: { state: PatrolIntelligenceState
manualRunBlockedReason: state.triggerPatrolDisabledReason(),
}),
);
- const providerSetupAction = () => getPatrolSetupAction(state.patrolReadiness()?.cause);
+ const providerSetupAction = () =>
+ getPatrolSetupAction(
+ resolvePatrolBlockedActionCause(state.blockedCause(), state.patrolReadiness()?.cause),
+ );
const runControlBusy = createMemo(
() =>
state.isTriggeringPatrol() || state.manualRunRequested() || state.patrolStream.isStreaming(),
diff --git a/frontend-modern/src/features/patrol/PatrolIntelligenceWorkspace.tsx b/frontend-modern/src/features/patrol/PatrolIntelligenceWorkspace.tsx
index fee5d40c01..1c2846e356 100644
--- a/frontend-modern/src/features/patrol/PatrolIntelligenceWorkspace.tsx
+++ b/frontend-modern/src/features/patrol/PatrolIntelligenceWorkspace.tsx
@@ -33,10 +33,13 @@ import {
PATROL_WORKSPACE_QUEUE_TITLE,
PATROL_WORKSPACE_RUN_RECORD_DESCRIPTION,
PATROL_WORKSPACE_RUN_RECORD_TITLE,
- PATROL_WORKSPACE_SETUP_DESCRIPTION,
PATROL_WORKSPACE_SETUP_TITLE,
+ getPatrolWorkspaceSetupDescription,
} from './patrolControlPresentation';
-import type { PatrolIntelligenceState } from './usePatrolIntelligenceState';
+import {
+ resolvePatrolBlockedActionCause,
+ type PatrolIntelligenceState,
+} from './usePatrolIntelligenceState';
import { getUpgradeActionDestination } from '@/stores/licenseCommercial';
import {
presentationPolicyHidesCommercialSurfaces,
@@ -63,9 +66,19 @@ export function PatrolIntelligenceWorkspace(props: {
const isHistoryOpen = () => state.activeTab() === 'history';
const isSetupOnly = () =>
!isHistoryOpen() && !state.selectedRun() && state.shouldShowPatrolSetupOnly();
- const setupAction = () => getPatrolSetupAction(state.patrolReadiness()?.cause);
- const setupHint = () => getPatrolSetupHint(state.patrolReadiness()?.cause);
const setupFinding = () => state.findingsTabBadgeFindings().find(isPatrolRuntimeFinding);
+ // A runtime block (a used-up cost budget) outranks the readiness cause,
+ // which reads "none" while Patrol is configured but paused. The block state
+ // is in memory, so after a restart the persisted runtime finding's own
+ // failure cause carries the same answer until the next run (#1789).
+ const setupFindingCause = () => setupFinding()?.failureCause;
+ const setupCause = () =>
+ resolvePatrolBlockedActionCause(
+ state.blockedCause() || setupFindingCause(),
+ state.patrolReadiness()?.cause,
+ );
+ const setupAction = () => getPatrolSetupAction(setupCause());
+ const setupHint = () => getPatrolSetupHint(setupCause());
const setupReason = () => {
const finding = setupFinding();
return getPatrolSetupIssueReason({
@@ -87,7 +100,7 @@ export function PatrolIntelligenceWorkspace(props: {
isHistoryOpen()
? PATROL_WORKSPACE_HISTORY_DESCRIPTION
: isSetupOnly()
- ? PATROL_WORKSPACE_SETUP_DESCRIPTION
+ ? getPatrolWorkspaceSetupDescription(setupCause())
: state.selectedRun()
? PATROL_WORKSPACE_RUN_RECORD_DESCRIPTION
: getPatrolQueueWorkspaceDescription({
diff --git a/frontend-modern/src/features/patrol/__tests__/PatrolIntelligenceHeader.test.ts b/frontend-modern/src/features/patrol/__tests__/PatrolIntelligenceHeader.test.ts
index 690c13da3e..d3e17b1700 100644
--- a/frontend-modern/src/features/patrol/__tests__/PatrolIntelligenceHeader.test.ts
+++ b/frontend-modern/src/features/patrol/__tests__/PatrolIntelligenceHeader.test.ts
@@ -16,6 +16,14 @@ const headerSource = readFileSync(
resolve(__dirname, '..', 'PatrolIntelligenceHeader.tsx'),
'utf-8',
);
+const workspaceSource = readFileSync(
+ resolve(__dirname, '..', 'PatrolIntelligenceWorkspace.tsx'),
+ 'utf-8',
+);
+const bannersSource = readFileSync(
+ resolve(__dirname, '..', 'PatrolIntelligenceBanners.tsx'),
+ 'utf-8',
+);
describe('PatrolIntelligenceHeader', () => {
it('does not present the server zero-time sentinel as an Autopilot expiry', () => {
@@ -88,7 +96,9 @@ describe('PatrolIntelligenceHeader', () => {
expect(headerSource).toContain('getPatrolSetupAction');
expect(headerSource).toContain('providerSetupAction().href');
expect(headerSource).toContain('Fix setup');
- expect(headerSource).toContain('getPatrolSetupAction(state.patrolReadiness()?.cause)');
+ expect(headerSource).toContain(
+ 'resolvePatrolBlockedActionCause(state.blockedCause(), state.patrolReadiness()?.cause)',
+ );
expect(headerSource).toContain('runButtonDisabled');
expect(headerSource).not.toContain('!state.canTriggerPatrol() ||');
});
@@ -311,4 +321,24 @@ describe('PatrolIntelligenceHeader', () => {
expect(headerSource).not.toContain('trust.regressed_at_least_once');
expect(headerSource).not.toContain('trust.fix_verified');
});
+
+ it('routes every Patrol setup action through the runtime block cause (#1789)', () => {
+ // A used-up cost budget blocks Patrol while readiness still reads
+ // "none"; the header, setup card, and paused banner must all resolve the
+ // action from the block cause first so the operator lands on the budget
+ // field instead of the model check.
+ for (const source of [headerSource, bannersSource]) {
+ expect(source).toContain(
+ 'resolvePatrolBlockedActionCause(state.blockedCause(), state.patrolReadiness()?.cause)',
+ );
+ }
+ for (const source of [headerSource, workspaceSource, bannersSource]) {
+ expect(source).not.toContain('getPatrolSetupAction(state.patrolReadiness()?.cause)');
+ }
+ // The setup card also reads the persisted runtime finding's cause, because
+ // the in-memory block state does not survive a restart.
+ expect(workspaceSource).toContain('state.blockedCause() || setupFindingCause(),');
+ expect(workspaceSource).toContain('setupFinding()?.failureCause');
+ expect(workspaceSource).toContain('getPatrolSetupHint(setupCause())');
+ });
});
diff --git a/frontend-modern/src/features/patrol/__tests__/PatrolIntelligenceWorkspace.test.ts b/frontend-modern/src/features/patrol/__tests__/PatrolIntelligenceWorkspace.test.ts
index 614860574a..30d77ddaa1 100644
--- a/frontend-modern/src/features/patrol/__tests__/PatrolIntelligenceWorkspace.test.ts
+++ b/frontend-modern/src/features/patrol/__tests__/PatrolIntelligenceWorkspace.test.ts
@@ -42,7 +42,7 @@ describe('PatrolIntelligenceWorkspace trust strip', () => {
expect(workspaceSource).not.toContain('showInvestigationContext');
expect(workspaceSource).not.toContain('shouldSurfaceInvestigationContext');
expect(workspaceSource).toContain('PATROL_WORKSPACE_SETUP_TITLE');
- expect(workspaceSource).toContain('PATROL_WORKSPACE_SETUP_DESCRIPTION');
+ expect(workspaceSource).toContain('getPatrolWorkspaceSetupDescription(setupCause())');
expect(workspaceSource).toContain('buildPatrolFindingDisplayGroups');
expect(workspaceSource).not.toContain('getPatrolQueueBadgeLabel');
expect(workspaceSource).toContain('queueIssueCount');
diff --git a/frontend-modern/src/features/patrol/__tests__/patrolControlPresentation.test.ts b/frontend-modern/src/features/patrol/__tests__/patrolControlPresentation.test.ts
index ab2a4d4fc6..dd3769db55 100644
--- a/frontend-modern/src/features/patrol/__tests__/patrolControlPresentation.test.ts
+++ b/frontend-modern/src/features/patrol/__tests__/patrolControlPresentation.test.ts
@@ -11,13 +11,26 @@ import {
getMonitorContextPatrolProtectionPosture,
getPatrolReadyWorkDetail,
getPatrolSetupIssueReason,
+ getPatrolWorkspaceSetupDescription,
getPatrolWorkspaceWorkGroups,
isPatrolCoverageStale,
PATROL_AUTONOMY_POLICY_PRESENTATION,
+ PATROL_WORKSPACE_BUDGET_PAUSED_DESCRIPTION,
PATROL_WORKSPACE_QUEUE_TITLE,
+ PATROL_WORKSPACE_SETUP_DESCRIPTION,
} from '../patrolControlPresentation';
describe('patrolControlPresentation', () => {
+ it('describes a budget pause as spending, not a failed model check (#1789)', () => {
+ expect(getPatrolWorkspaceSetupDescription('budget_exhausted')).toBe(
+ PATROL_WORKSPACE_BUDGET_PAUSED_DESCRIPTION,
+ );
+ expect(PATROL_WORKSPACE_BUDGET_PAUSED_DESCRIPTION).not.toMatch(/tool check/);
+ for (const cause of ['model_unsupported_tools', 'none', undefined, null]) {
+ expect(getPatrolWorkspaceSetupDescription(cause)).toBe(PATROL_WORKSPACE_SETUP_DESCRIPTION);
+ }
+ });
+
it.each([
['fresh', 'complete', 'Evidence current', 'Evidence current', 'success'],
['stale', 'complete', 'Evidence out of date', 'Evidence out of date', 'warning'],
diff --git a/frontend-modern/src/features/patrol/__tests__/usePatrolIntelligenceState.test.ts b/frontend-modern/src/features/patrol/__tests__/usePatrolIntelligenceState.test.ts
index cbd7bc7600..4dcef31829 100644
--- a/frontend-modern/src/features/patrol/__tests__/usePatrolIntelligenceState.test.ts
+++ b/frontend-modern/src/features/patrol/__tests__/usePatrolIntelligenceState.test.ts
@@ -10,6 +10,7 @@ import {
recordPatrolWorkflowStarterActivity,
resolvePatrolAutonomyLevelForSave,
resolvePatrolAutonomySettingsForSave,
+ resolvePatrolBlockedActionCause,
} from '../usePatrolIntelligenceState';
import patrolIntelligenceStateSource from '../usePatrolIntelligenceState.ts?raw';
import type { AIChatContext } from '@/stores/aiChat';
@@ -399,4 +400,16 @@ describe('usePatrolIntelligenceState', () => {
});
});
});
+
+ it('lets the runtime block cause drive the blocked-banner action (#1789)', () => {
+ expect(resolvePatrolBlockedActionCause('budget_exhausted', 'none')).toBe('budget_exhausted');
+ expect(resolvePatrolBlockedActionCause('none', 'model_unsupported_tools')).toBe(
+ 'model_unsupported_tools',
+ );
+ expect(resolvePatrolBlockedActionCause(undefined, ' provider_not_configured ')).toBe(
+ 'provider_not_configured',
+ );
+ expect(resolvePatrolBlockedActionCause('', '')).toBeUndefined();
+ expect(patrolIntelligenceStateSource).toContain('blockedCause: patrolStatus()?.blocked_cause');
+ });
});
diff --git a/frontend-modern/src/features/patrol/patrolControlPresentation.ts b/frontend-modern/src/features/patrol/patrolControlPresentation.ts
index a3fbe70bd1..fdb43d180a 100644
--- a/frontend-modern/src/features/patrol/patrolControlPresentation.ts
+++ b/frontend-modern/src/features/patrol/patrolControlPresentation.ts
@@ -50,6 +50,19 @@ export const PATROL_WORKSPACE_SETUP_TITLE = 'Patrol needs setup';
export const PATROL_WORKSPACE_SETUP_DESCRIPTION =
'Patrol cannot check infrastructure until its selected model passes the Patrol tool check.';
+export const PATROL_WORKSPACE_BUDGET_PAUSED_DESCRIPTION =
+ 'Patrol is paused until the 30-day AI cost budget is raised or the 30-day window rolls on.';
+
+/**
+ * The setup workspace subtitle follows the block cause: a used-up cost budget
+ * is a spending decision, not a model that failed the tool check (#1789).
+ */
+export function getPatrolWorkspaceSetupDescription(cause?: string | null): string {
+ return cause === 'budget_exhausted'
+ ? PATROL_WORKSPACE_BUDGET_PAUSED_DESCRIPTION
+ : PATROL_WORKSPACE_SETUP_DESCRIPTION;
+}
+
export const PATROL_WORKSPACE_QUEUE_TITLE = 'Open work';
export const PATROL_WORKSPACE_RUN_RECORD_TITLE = 'Check details';
diff --git a/frontend-modern/src/features/patrol/usePatrolIntelligenceState.ts b/frontend-modern/src/features/patrol/usePatrolIntelligenceState.ts
index 7572c50b51..d2eb5d4dd6 100644
--- a/frontend-modern/src/features/patrol/usePatrolIntelligenceState.ts
+++ b/frontend-modern/src/features/patrol/usePatrolIntelligenceState.ts
@@ -232,6 +232,22 @@ export function buildPatrolSettingsReadinessFailure({
};
}
+/**
+ * The blocked banner's action must follow the runtime block cause when there
+ * is one: a used-up cost budget is fixed on Provider & Models, while the
+ * readiness cause (often "none" while blocked) would send the operator to
+ * the model check (#1789).
+ */
+export function resolvePatrolBlockedActionCause(
+ blockedCause?: string | null,
+ readinessCause?: string | null,
+): string | undefined {
+ const blocked = blockedCause?.trim();
+ if (blocked && blocked !== 'none') return blocked;
+ const readiness = readinessCause?.trim();
+ return readiness || undefined;
+}
+
export function usePatrolIntelligenceState() {
const [initialSurfaceReady, setInitialSurfaceReady] = createSignal(false);
const [activeTab, setActiveTab] = createSignal<PatrolTab>('findings');
@@ -512,6 +528,7 @@ export function usePatrolIntelligenceState() {
normalizePatrolRuntimeBlockedReason(patrolStatus()?.blocked_reason),
);
const blockedAt = createMemo(() => patrolStatus()?.blocked_at);
+ const blockedCause = createMemo(() => patrolStatus()?.blocked_cause);
const patrolReadiness = createMemo(() => patrolStatus()?.readiness ?? null);
// Pulse records the last preflight result on AISettings.patrol_preflight
// (provider/model/duration/recommendation) so we can surface a concrete
@@ -1058,6 +1075,7 @@ export function usePatrolIntelligenceState() {
autoFixCapabilityBlock,
autoFixLocked,
blockedAt,
+ blockedCause,
blockedReason,
canTriggerPatrol,
circuitBreakerStatus,
diff --git a/frontend-modern/src/stores/__tests__/aiIntelligence.test.ts b/frontend-modern/src/stores/__tests__/aiIntelligence.test.ts
index 86734f0bcb..eb7b91f5f3 100644
--- a/frontend-modern/src/stores/__tests__/aiIntelligence.test.ts
+++ b/frontend-modern/src/stores/__tests__/aiIntelligence.test.ts
@@ -109,6 +109,36 @@ describe('aiIntelligenceStore', () => {
});
});
+ it('keeps the Patrol runtime failure cause on unified findings (#1789)', async () => {
+ vi.mocked(getPatrolFindings).mockResolvedValueOnce([
+ {
+ id: 'patrol-runtime',
+ key: 'ai-patrol-error',
+ severity: 'warning',
+ category: 'reliability',
+ resource_id: 'pulse-patrol-service',
+ resource_name: 'Pulse Patrol Service',
+ resource_type: 'service',
+ title: 'Pulse Patrol: 30-day cost budget reached',
+ description: 'Pulse Patrol skipped its analysis because spend reached the budget.',
+ detected_at: '2026-09-01T00:00:00Z',
+ last_seen_at: '2026-09-01T00:05:00Z',
+ auto_resolved: false,
+ times_raised: 2,
+ suppressed: false,
+ investigation_attempts: 0,
+ failure_cause: 'budget_exhausted',
+ } as never,
+ ]);
+
+ await aiIntelligenceStore.loadPatrolFindings();
+
+ expect(aiIntelligenceStore.patrolFindings[0]).toMatchObject({
+ id: 'patrol-runtime',
+ failureCause: 'budget_exhausted',
+ });
+ });
+
it('loads direct Patrol findings for Patrol surfaces', async () => {
vi.mocked(getPatrolFindings).mockResolvedValueOnce([
{
diff --git a/frontend-modern/src/stores/aiIntelligence.ts b/frontend-modern/src/stores/aiIntelligence.ts
index fb926c80b3..18abd3a3a0 100644
--- a/frontend-modern/src/stores/aiIntelligence.ts
+++ b/frontend-modern/src/stores/aiIntelligence.ts
@@ -163,6 +163,9 @@ export interface UnifiedFinding {
previousResolvedFixSummary?: string;
recommendation?: string;
evidence?: string;
+ // Patrol runtime failure cause (for example budget_exhausted) carried by
+ // the persisted runtime finding; drives the setup action after a restart.
+ failureCause?: string;
aiConfidence?: number;
detectedAt: string;
lastSeenAt?: string;
@@ -311,6 +314,9 @@ function normalizePatrolFindingRecord(item: PatrolFinding, now: number): Unified
previousResolvedFixSummary: item.previous_resolved_fix_summary,
recommendation: item.recommendation,
evidence: item.evidence,
+ // The shared Finding type in api/patrol.ts does not declare the wire
+ // field yet, so read it through a narrow local shape.
+ failureCause: (item as { failure_cause?: string }).failure_cause,
detectedAt: item.detected_at,
lastSeenAt: item.last_seen_at || item.detected_at,
resolvedAt: item.resolved_at,
diff --git a/frontend-modern/src/types/ai.ts b/frontend-modern/src/types/ai.ts
index 47ab13843b..d512bb578f 100644
--- a/frontend-modern/src/types/ai.ts
+++ b/frontend-modern/src/types/ai.ts
@@ -568,3 +568,82 @@ export interface AIChatSessionSummary {
updated_at: string;
handoff_summary?: AIChatSessionHandoffSummary;
}
+
+// ============================================
+// Patrol cost preview and model guidance
+// ============================================
+
+export interface PatrolCostIntervalEstimate {
+ interval_minutes: number;
+ scheduled_runs_per_day: number;
+ projected_30d_usd: number;
+}
+
+export type PatrolCostPerRunSource = 'history' | 'default';
+
+export type PatrolCostRecommendationReason =
+ | 'keep'
+ | 'fits_budget_share'
+ | 'exceeds_budget_share_even_daily'
+ | 'not_billed_per_token'
+ | 'pricing_unknown';
+
+/**
+ * Server-computed estimate of what Patrol costs per 30 days on a model and
+ * schedule. Every figure is an estimate from Pulse's price table and a
+ * per-run token estimate; the assumptions travel with the numbers.
+ */
+export interface PatrolCostProjection {
+ provider: string;
+ model: string;
+ model_route: string;
+ billed_per_token: boolean;
+ pricing_known: boolean;
+ pricing_as_of?: string;
+ input_usd_per_mtok: number;
+ output_usd_per_mtok: number;
+ per_run_input_tokens: number;
+ per_run_output_tokens: number;
+ per_run_source: PatrolCostPerRunSource;
+ history_run_count: number;
+ per_run_usd: number;
+ interval_minutes: number;
+ scheduled_runs_per_day: number;
+ triggered_runs_per_day: number;
+ triggered_per_run_usd: number;
+ scheduled_projected_30d_usd: number;
+ projected_30d_usd: number;
+ interval_estimates: PatrolCostIntervalEstimate[];
+ budget_usd_30d: number;
+ spend_30d_usd: number;
+ spend_30d_known: boolean;
+ patrol_spend_30d_usd: number;
+ budget_reached: boolean;
+ recommended_interval_minutes: number;
+ recommendation_reason: PatrolCostRecommendationReason | string;
+ recommendation_target_usd: number;
+}
+
+export type PatrolModelGuidanceLevel = 'verified' | 'recommended' | 'suggested' | 'caution';
+
+export interface PatrolModelGuidanceRule {
+ provider: string;
+ model_prefix: string;
+ model_exact?: boolean;
+ exclude?: string[];
+ level: PatrolModelGuidanceLevel | string;
+ reason: string;
+ evidence?: string;
+}
+
+export interface PatrolModelVerifiedGuidance {
+ provider: string;
+ model: string;
+ max_verified_mode?: string;
+ recorded_at_unix: number;
+}
+
+export interface PatrolModelGuidanceResponse {
+ rules: PatrolModelGuidanceRule[];
+ verified?: PatrolModelVerifiedGuidance | null;
+}
diff --git a/frontend-modern/src/utils/__tests__/aiPatrolCostPresentation.test.ts b/frontend-modern/src/utils/__tests__/aiPatrolCostPresentation.test.ts
new file mode 100644
index 0000000000..6758a03526
--- /dev/null
+++ b/frontend-modern/src/utils/__tests__/aiPatrolCostPresentation.test.ts
@@ -0,0 +1,307 @@
+import { describe, expect, it } from 'vitest';
+import type { PatrolCostProjection, PatrolModelGuidanceResponse } from '@/types/ai';
+import {
+ formatPatrolCostUSD,
+ formatPatrolIntervalPhrase,
+ formatPatrolTokenCount,
+ getPatrolCostPresentation,
+ getPatrolGuidedModelIds,
+ getPatrolIntervalAutoAdjust,
+ getPatrolIntervalCostHint,
+ resolvePatrolModelGuidance,
+} from '@/utils/aiPatrolCostPresentation';
+
+const flashProjection = (overrides: Partial<PatrolCostProjection> = {}): PatrolCostProjection => ({
+ provider: 'gemini',
+ model: 'gemini-2.5-flash',
+ model_route: 'gemini:gemini-2.5-flash',
+ billed_per_token: true,
+ pricing_known: true,
+ pricing_as_of: '2026-06-04',
+ input_usd_per_mtok: 0.3,
+ output_usd_per_mtok: 2.5,
+ per_run_input_tokens: 104_528,
+ per_run_output_tokens: 4_491,
+ per_run_source: 'default',
+ history_run_count: 0,
+ per_run_usd: 0.0426,
+ interval_minutes: 360,
+ scheduled_runs_per_day: 4,
+ triggered_runs_per_day: 0,
+ triggered_per_run_usd: 0,
+ scheduled_projected_30d_usd: 5.11,
+ projected_30d_usd: 5.11,
+ interval_estimates: [
+ { interval_minutes: 60, scheduled_runs_per_day: 24, projected_30d_usd: 30.67 },
+ { interval_minutes: 180, scheduled_runs_per_day: 8, projected_30d_usd: 10.22 },
+ { interval_minutes: 360, scheduled_runs_per_day: 4, projected_30d_usd: 5.11 },
+ { interval_minutes: 720, scheduled_runs_per_day: 2, projected_30d_usd: 2.56 },
+ { interval_minutes: 1440, scheduled_runs_per_day: 1, projected_30d_usd: 1.28 },
+ ],
+ budget_usd_30d: 20,
+ spend_30d_usd: 3.2,
+ spend_30d_known: true,
+ patrol_spend_30d_usd: 2.5,
+ budget_reached: false,
+ recommended_interval_minutes: 360,
+ recommendation_reason: 'fits_budget_share',
+ recommendation_target_usd: 10,
+ ...overrides,
+});
+
+const sonnetProjection = (): PatrolCostProjection =>
+ flashProjection({
+ provider: 'anthropic',
+ model: 'claude-sonnet-5',
+ model_route: 'anthropic:claude-sonnet-5',
+ input_usd_per_mtok: 2,
+ output_usd_per_mtok: 10,
+ per_run_usd: 0.254,
+ scheduled_projected_30d_usd: 30.5,
+ projected_30d_usd: 30.5,
+ interval_estimates: [
+ { interval_minutes: 60, scheduled_runs_per_day: 24, projected_30d_usd: 183 },
+ { interval_minutes: 180, scheduled_runs_per_day: 8, projected_30d_usd: 61 },
+ { interval_minutes: 360, scheduled_runs_per_day: 4, projected_30d_usd: 30.5 },
+ { interval_minutes: 720, scheduled_runs_per_day: 2, projected_30d_usd: 15.25 },
+ { interval_minutes: 1440, scheduled_runs_per_day: 1, projected_30d_usd: 7.62 },
+ ],
+ recommended_interval_minutes: 1440,
+ });
+
+describe('aiPatrolCostPresentation formatting', () => {
+ it('formats dollars, tokens, and schedules the way a bill reads', () => {
+ expect(formatPatrolCostUSD(0)).toBe('$0');
+ expect(formatPatrolCostUSD(0.004)).toBe('under $0.01');
+ expect(formatPatrolCostUSD(0.0426)).toBe('$0.04');
+ expect(formatPatrolCostUSD(5.11)).toBe('$5.11');
+ expect(formatPatrolCostUSD(20)).toBe('$20');
+ expect(formatPatrolCostUSD(183)).toBe('$183');
+ expect(formatPatrolTokenCount(104_528)).toBe('105k');
+ expect(formatPatrolTokenCount(4_491)).toBe('4k');
+ expect(formatPatrolTokenCount(2_400_000)).toBe('2.4M');
+ expect(formatPatrolIntervalPhrase(0)).toBe('manual runs only');
+ expect(formatPatrolIntervalPhrase(60)).toBe('every hour');
+ expect(formatPatrolIntervalPhrase(360)).toBe('every 6 hours');
+ expect(formatPatrolIntervalPhrase(1440)).toBe('once a day');
+ });
+
+ it('prices each schedule option only when something is billed', () => {
+ expect(getPatrolIntervalCostHint(flashProjection(), 720)).toBe('≈ $2.56/month');
+ expect(getPatrolIntervalCostHint(flashProjection(), 0)).toBe('no scheduled cost');
+ expect(getPatrolIntervalCostHint(flashProjection({ billed_per_token: false }), 720)).toBe('');
+ expect(getPatrolIntervalCostHint(null, 720)).toBe('');
+ });
+});
+
+describe('getPatrolCostPresentation', () => {
+ it('states the monthly estimate, the assumption, and spend against budget', () => {
+ const presentation = getPatrolCostPresentation(flashProjection());
+ expect(presentation).not.toBeNull();
+ expect(presentation!.headline).toBe('About $5.11 a month for Patrol');
+ expect(presentation!.detail).toBe(
+ '4 scheduled runs a day × about 105k tokens in and 4k out per run ≈ $0.04 a run, at $0.30 in / $2.50 out per million tokens, prices as of 2026-06-04. Alert-triggered runs add to this when alerts fire.',
+ );
+ expect(presentation!.assumption).toContain('measured on a real install');
+ expect(presentation!.assumption).toContain('roughly three quarters of a word');
+ expect(presentation!.budget).toBe(
+ 'Spent so far: about $3.20 of your $20 30-day budget ($2.50 of that was Patrol).',
+ );
+ expect(presentation!.budgetTone).toBe('neutral');
+ expect(presentation!.schedule).toBe('');
+ expect(presentation!.tone).toBe('neutral');
+ });
+
+ it('uses the install history wording and counts triggered runs when present', () => {
+ const presentation = getPatrolCostPresentation(
+ flashProjection({
+ per_run_source: 'history',
+ history_run_count: 12,
+ triggered_runs_per_day: 1.5,
+ triggered_per_run_usd: 0.01,
+ projected_30d_usd: 5.56,
+ }),
+ );
+ expect(presentation!.headline).toBe('About $5.56 a month for Patrol');
+ expect(presentation!.assumption).toContain('median of your last 12 full Patrol runs');
+ expect(presentation!.detail).toContain(
+ 'Alert-triggered runs added about 1.5 a day recently and are included.',
+ );
+ });
+
+ it('warns when the projection would pass the budget and flags a reached budget', () => {
+ const nearLimit = getPatrolCostPresentation(flashProjection({ spend_30d_usd: 16 }));
+ expect(nearLimit!.budget).toContain('At this pace Patrol would pass the budget this month');
+ expect(nearLimit!.budgetTone).toBe('warning');
+ expect(nearLimit!.tone).toBe('warning');
+
+ const reached = getPatrolCostPresentation(
+ flashProjection({ spend_30d_usd: 20.4, budget_reached: true }),
+ );
+ expect(reached!.budget).toBe(
+ 'Budget reached: about $20.40 of your $20 30-day budget is spent, so Patrol is paused until you raise it or the 30-day window rolls on.',
+ );
+ expect(reached!.tone).toBe('danger');
+ });
+
+ it('explains an unset budget and manual-only pricing', () => {
+ const noBudget = getPatrolCostPresentation(
+ flashProjection({ budget_usd_30d: 0, interval_minutes: 0, scheduled_runs_per_day: 0 }),
+ );
+ expect(noBudget!.headline).toBe('About $0.04 per manual Patrol run');
+ expect(noBudget!.budget).toContain('No 30-day budget is set, so Patrol will not stop for cost');
+ });
+
+ it('recommends a slower schedule for expensive models and names the trade', () => {
+ const presentation = getPatrolCostPresentation(sonnetProjection());
+ expect(presentation!.headline).toBe('About $30.50 a month for Patrol');
+ expect(presentation!.schedule).toBe(
+ 'Pulse suggests once a day (about $7.62 a month) to keep scheduled runs under $10, half of your budget. Every 6 hours is about $30.50 a month.',
+ );
+ });
+
+ it('points at a cheaper model when even daily runs exceed the target', () => {
+ const presentation = getPatrolCostPresentation(
+ sonnetProjection() && {
+ ...sonnetProjection(),
+ budget_usd_30d: 0,
+ recommendation_reason: 'exceeds_budget_share_even_daily',
+ interval_estimates: [
+ { interval_minutes: 1440, scheduled_runs_per_day: 1, projected_30d_usd: 38.1 },
+ ],
+ },
+ );
+ expect(presentation!.schedule).toBe(
+ 'Even once a day costs about $38.10 a month, above $10 (half of a $20 budget). A cheaper model is the better lever.',
+ );
+ expect(presentation!.tone).toBe('warning');
+ });
+
+ it('tells local and unpriced models apart from a bill', () => {
+ const local = getPatrolCostPresentation(
+ flashProjection({ provider: 'ollama', model: 'qwen3:8b', billed_per_token: false }),
+ );
+ expect(local!.headline).toBe('No per-token bill for Patrol');
+ expect(local!.tone).toBe('positive');
+
+ const unknown = getPatrolCostPresentation(
+ flashProjection({ model: 'gpt-9-unpriced', pricing_known: false, billed_per_token: false }),
+ );
+ expect(unknown!.headline).toBe('No price on file for this model');
+ expect(unknown!.detail).toContain('gpt-9-unpriced');
+ expect(getPatrolCostPresentation(null)).toBeNull();
+ });
+});
+
+describe('getPatrolIntervalAutoAdjust', () => {
+ it('slows the default schedule for a per-token model and explains the trade-off', () => {
+ const adjust = getPatrolIntervalAutoAdjust(sonnetProjection(), {
+ currentIntervalMinutes: 360,
+ savedIntervalMinutes: 360,
+ });
+ expect(adjust).toEqual({
+ from: 360,
+ to: 1440,
+ sentence:
+ 'Schedule set to once a day because claude-sonnet-5 bills per token: about $7.62 a month instead of $30.50 at every 6 hours, at the cost of a quiet problem waiting up to 24 hours for a scheduled check (alert-triggered runs still fire at once). Change it under Patrol › Schedule.',
+ });
+ });
+
+ it('leaves installs that already chose a schedule alone', () => {
+ expect(
+ getPatrolIntervalAutoAdjust(sonnetProjection(), {
+ currentIntervalMinutes: 360,
+ savedIntervalMinutes: 720,
+ }),
+ ).toBeNull();
+ expect(
+ getPatrolIntervalAutoAdjust(sonnetProjection(), {
+ currentIntervalMinutes: 180,
+ savedIntervalMinutes: 360,
+ }),
+ ).toBeNull();
+ });
+
+ it('does nothing for local models or when the default already fits', () => {
+ expect(
+ getPatrolIntervalAutoAdjust(flashProjection({ billed_per_token: false }), {
+ currentIntervalMinutes: 360,
+ savedIntervalMinutes: 360,
+ }),
+ ).toBeNull();
+ expect(
+ getPatrolIntervalAutoAdjust(flashProjection(), {
+ currentIntervalMinutes: 360,
+ savedIntervalMinutes: 360,
+ }),
+ ).toBeNull();
+ });
+});
+
+describe('resolvePatrolModelGuidance', () => {
+ const guidance: PatrolModelGuidanceResponse = {
+ rules: [
+ {
+ provider: 'ollama',
+ model_prefix: 'qwen3:8b',
+ model_exact: true,
+ level: 'recommended',
+ reason: 'Passed the tool-call check.',
+ },
+ {
+ provider: 'gemini',
+ model_prefix: 'gemini-',
+ exclude: ['!flash-lite'],
+ level: 'caution',
+ reason: 'Could not file verdicts.',
+ },
+ {
+ provider: 'gemini',
+ model_prefix: 'gemini-2.5-flash',
+ exclude: ['lite'],
+ level: 'suggested',
+ reason: 'Lowest-cost standard tier.',
+ },
+ ],
+ verified: {
+ provider: 'ollama',
+ model: 'qwen3:8b',
+ max_verified_mode: 'approval',
+ recorded_at_unix: 1,
+ },
+ };
+ const models = [
+ { id: 'ollama:qwen3:8b', provider: 'ollama' },
+ { id: 'ollama:qwen3:4b', provider: 'ollama' },
+ { id: 'gemini:gemini-2.5-flash', provider: 'gemini' },
+ { id: 'gemini:gemini-2.5-flash-lite', provider: 'gemini' },
+ { id: 'gemini:gemini-2.5-pro' },
+ ];
+
+ it('marks verified, suggested, and caution models and pins the good ones first', () => {
+ const annotations = resolvePatrolModelGuidance(models, guidance);
+ expect(annotations.get('ollama:qwen3:8b')).toEqual({
+ level: 'verified',
+ badge: 'Verified on this install',
+ note: 'Passed Check Patrol model here for Watch only and Ask first.',
+ tone: 'positive',
+ });
+ expect(annotations.get('ollama:qwen3:4b')).toBeUndefined();
+ expect(annotations.get('gemini:gemini-2.5-flash')?.badge).toBe('Suggested starting point');
+ expect(annotations.get('gemini:gemini-2.5-flash-lite')).toEqual({
+ level: 'caution',
+ badge: 'Caution',
+ note: 'Could not file verdicts.',
+ tone: 'warning',
+ });
+ expect(annotations.get('gemini:gemini-2.5-pro')).toBeUndefined();
+ expect(getPatrolGuidedModelIds(annotations)).toEqual([
+ 'ollama:qwen3:8b',
+ 'gemini:gemini-2.5-flash',
+ ]);
+ });
+
+ it('returns nothing without guidance', () => {
+ expect(resolvePatrolModelGuidance(models, null).size).toBe(0);
+ });
+});
diff --git a/frontend-modern/src/utils/__tests__/docsLinks.test.ts b/frontend-modern/src/utils/__tests__/docsLinks.test.ts
index 86fcebc199..1d5063ada3 100644
--- a/frontend-modern/src/utils/__tests__/docsLinks.test.ts
+++ b/frontend-modern/src/utils/__tests__/docsLinks.test.ts
@@ -327,4 +327,17 @@ describe('docsLinks', () => {
},
runtimeDocsLinkScanTimeoutMs,
);
+
+ it('ships the Patrol cost preview and model guidance contract', () => {
+ const apiReference = readFileSync(path.join(repoRoot, 'docs', 'API.md'), 'utf8');
+ const shippedApiReference = readFileSync(
+ path.join(frontendRoot, 'public', 'docs', 'API.md'),
+ 'utf8',
+ );
+ for (const reference of [apiReference, shippedApiReference]) {
+ expect(reference).toContain('`GET /api/ai/patrol/cost-preview`');
+ expect(reference).toContain('`GET /api/ai/patrol/model-guidance`');
+ expect(reference).toContain('recommended schedule');
+ }
+ });
});
diff --git a/frontend-modern/src/utils/__tests__/patrolRuntimeActions.test.ts b/frontend-modern/src/utils/__tests__/patrolRuntimeActions.test.ts
index d6e0a7005a..1136cf72f2 100644
--- a/frontend-modern/src/utils/__tests__/patrolRuntimeActions.test.ts
+++ b/frontend-modern/src/utils/__tests__/patrolRuntimeActions.test.ts
@@ -3,6 +3,7 @@ import {
getPatrolProviderSettingsAction,
getPatrolSetupAction,
getPatrolSetupHint,
+ PATROL_BUDGET_EXHAUSTED_CAUSE,
PATROL_PROVIDER_SETTINGS_ACTION,
} from '@/utils/patrolRuntimeActions';
@@ -33,6 +34,14 @@ describe('patrolRuntimeActions', () => {
}
});
+ it('routes an exhausted cost budget to the budget field, not the model check (#1789)', () => {
+ expect(getPatrolSetupAction(PATROL_BUDGET_EXHAUSTED_CAUSE)).toEqual({
+ label: 'Raise the cost budget',
+ href: '/settings/pulse-intelligence/provider',
+ });
+ expect(getPatrolSetupHint(PATROL_BUDGET_EXHAUSTED_CAUSE)).toBe('');
+ });
+
it('suppresses the tool-check hint for config-level causes', () => {
expect(getPatrolSetupHint('assistant_disabled')).toBe('');
expect(getPatrolSetupHint('provider_not_configured')).toBe('');
diff --git a/frontend-modern/src/utils/aiPatrolCostPresentation.ts b/frontend-modern/src/utils/aiPatrolCostPresentation.ts
new file mode 100644
index 0000000000..7a66472b9e
--- /dev/null
+++ b/frontend-modern/src/utils/aiPatrolCostPresentation.ts
@@ -0,0 +1,337 @@
+import type {
+ ModelInfo,
+ PatrolCostProjection,
+ PatrolModelGuidanceLevel,
+ PatrolModelGuidanceResponse,
+ PatrolModelGuidanceRule,
+} from '@/types/ai';
+import { getProviderFromModelId } from '@/utils/aiProviderPresentation';
+
+/**
+ * Presentation for the Patrol cost preview and model guidance markers.
+ *
+ * Vocabulary is pinned at a home-lab user who has never bought API credits:
+ * say what a token is once, say what the number means for their bill, and
+ * keep every figure labelled as an estimate with its assumption visible.
+ */
+
+export const PATROL_TOKEN_EXPLAINER =
+ 'Cloud providers charge per token (roughly three quarters of a word). Each Patrol run sends the model a snapshot of your infrastructure, so run size and how often it runs decide the bill.';
+
+export const PATROL_COST_DEFAULT_INTERVAL_MINUTES = 360;
+
+export type PatrolCostTone = 'neutral' | 'positive' | 'warning' | 'danger';
+
+export interface PatrolCostPresentation {
+ tone: PatrolCostTone;
+ headline: string;
+ detail: string;
+ assumption: string;
+ budget: string;
+ budgetTone: PatrolCostTone;
+ schedule: string;
+}
+
+export function formatPatrolCostUSD(usd: number): string {
+ if (!Number.isFinite(usd) || usd <= 0) return '$0';
+ if (usd < 0.01) return 'under $0.01';
+ if (usd < 1) return `$${usd.toFixed(2)}`;
+ if (usd < 100) return `$${usd.toFixed(2).replace(/\.00$/, '')}`;
+ return `$${Math.round(usd).toLocaleString()}`;
+}
+
+export function formatPatrolTokenCount(tokens: number): string {
+ if (!Number.isFinite(tokens) || tokens <= 0) return '0';
+ if (tokens >= 1_000_000) return `${(tokens / 1_000_000).toFixed(1).replace(/\.0$/, '')}M`;
+ if (tokens >= 1_000) return `${Math.round(tokens / 1_000)}k`;
+ return String(Math.round(tokens));
+}
+
+export function formatPatrolIntervalPhrase(minutes: number): string {
+ if (!Number.isFinite(minutes) || minutes <= 0) return 'manual runs only';
+ if (minutes === 60) return 'every hour';
+ if (minutes < 60) return `every ${minutes} minutes`;
+ if (minutes === 1440) return 'once a day';
+ if (minutes % 60 === 0) return `every ${minutes / 60} hours`;
+ return `every ${minutes} minutes`;
+}
+
+function formatRunsPerDay(runsPerDay: number): string {
+ if (!Number.isFinite(runsPerDay) || runsPerDay <= 0) return 'no scheduled runs';
+ if (runsPerDay === 1) return '1 scheduled run a day';
+ if (runsPerDay < 1) {
+ const rounded = Math.round(runsPerDay * 10) / 10;
+ return `${rounded} scheduled runs a day`;
+ }
+ return `${Math.round(runsPerDay)} scheduled runs a day`;
+}
+
+function intervalEstimate(projection: PatrolCostProjection, minutes: number): number | null {
+ const match = projection.interval_estimates?.find((entry) => entry.interval_minutes === minutes);
+ return match ? match.projected_30d_usd : null;
+}
+
+/** "≈ $5.11/mo" for a schedule option, or '' when nothing is billed. */
+export function getPatrolIntervalCostHint(
+ projection: PatrolCostProjection | null | undefined,
+ minutes: number,
+): string {
+ if (!projection || !projection.pricing_known || !projection.billed_per_token) return '';
+ if (minutes <= 0) return 'no scheduled cost';
+ const usd = intervalEstimate(projection, minutes);
+ if (usd == null) return '';
+ return `≈ ${formatPatrolCostUSD(usd)}/month`;
+}
+
+export function getPatrolCostPresentation(
+ projection: PatrolCostProjection | null | undefined,
+): PatrolCostPresentation | null {
+ if (!projection || !projection.model) return null;
+ const modelLabel = projection.model;
+ const budgetSet = projection.budget_usd_30d > 0;
+ const spendKnown = projection.spend_30d_known;
+
+ let budget: string;
+ let budgetTone: PatrolCostTone = 'neutral';
+ if (projection.budget_reached && budgetSet) {
+ budget = `Budget reached: about ${formatPatrolCostUSD(projection.spend_30d_usd)} of your ${formatPatrolCostUSD(projection.budget_usd_30d)} 30-day budget is spent, so Patrol is paused until you raise it or the 30-day window rolls on.`;
+ budgetTone = 'danger';
+ } else if (budgetSet) {
+ const patrolShare =
+ projection.patrol_spend_30d_usd > 0
+ ? ` (${formatPatrolCostUSD(projection.patrol_spend_30d_usd)} of that was Patrol)`
+ : '';
+ budget = spendKnown
+ ? `Spent so far: about ${formatPatrolCostUSD(projection.spend_30d_usd)} of your ${formatPatrolCostUSD(projection.budget_usd_30d)} 30-day budget${patrolShare}.`
+ : `Nothing priced yet against your ${formatPatrolCostUSD(projection.budget_usd_30d)} 30-day budget.`;
+ if (
+ spendKnown &&
+ projection.billed_per_token &&
+ projection.spend_30d_usd + projection.projected_30d_usd > projection.budget_usd_30d
+ ) {
+ budget += ' At this pace Patrol would pass the budget this month and pause.';
+ budgetTone = 'warning';
+ }
+ } else {
+ budget = spendKnown
+ ? `Spent so far: about ${formatPatrolCostUSD(projection.spend_30d_usd)} in the last 30 days. No 30-day budget is set, so Patrol will not stop for cost. Set one under Provider & Models to cap surprises.`
+ : 'No 30-day budget is set, so Patrol will not stop for cost. Set one under Provider & Models to cap surprises.';
+ }
+
+ if (!projection.pricing_known) {
+ return {
+ tone: 'neutral',
+ headline: 'No price on file for this model',
+ detail: `Pulse cannot estimate the bill for ${modelLabel}. Check the provider's pricing page. Pulse still counts the tokens each run uses.`,
+ assumption: PATROL_TOKEN_EXPLAINER,
+ budget,
+ budgetTone,
+ schedule: '',
+ };
+ }
+
+ if (!projection.billed_per_token) {
+ return {
+ tone: 'positive',
+ headline: 'No per-token bill for Patrol',
+ detail: `${modelLabel} runs on your own hardware or a free route, so Patrol adds nothing to a provider bill. Only the schedule's load on that hardware changes.`,
+ assumption: '',
+ budget,
+ budgetTone,
+ schedule: '',
+ };
+ }
+
+ const perRun = formatPatrolCostUSD(projection.per_run_usd);
+ const rates = `${formatPatrolCostUSD(projection.input_usd_per_mtok)} in / ${formatPatrolCostUSD(projection.output_usd_per_mtok)} out per million tokens`;
+ const priceDate = projection.pricing_as_of ? `, prices as of ${projection.pricing_as_of}` : '';
+ const perRunTokens = `about ${formatPatrolTokenCount(projection.per_run_input_tokens)} tokens in and ${formatPatrolTokenCount(projection.per_run_output_tokens)} out per run`;
+
+ let headline: string;
+ let detail: string;
+ if (projection.interval_minutes <= 0) {
+ headline = `About ${perRun} per manual Patrol run`;
+ detail = `Manual runs only: ${perRunTokens} at ${rates}${priceDate}.`;
+ } else {
+ headline = `About ${formatPatrolCostUSD(projection.projected_30d_usd)} a month for Patrol`;
+ detail = `${formatRunsPerDay(projection.scheduled_runs_per_day)} × ${perRunTokens} ≈ ${perRun} a run, at ${rates}${priceDate}.`;
+ }
+ if (projection.triggered_runs_per_day > 0) {
+ const perDay = Math.round(projection.triggered_runs_per_day * 10) / 10;
+ detail += ` Alert-triggered runs added about ${perDay} a day recently and are included.`;
+ } else {
+ detail += ' Alert-triggered runs add to this when alerts fire.';
+ }
+
+ const assumption =
+ projection.per_run_source === 'history'
+ ? `Run size is the median of your last ${projection.history_run_count} full Patrol runs. ${PATROL_TOKEN_EXPLAINER}`
+ : `Run size is a full Patrol run measured on a real install, and installs with more resources send more. ${PATROL_TOKEN_EXPLAINER}`;
+
+ let schedule = '';
+ const recommended = projection.recommended_interval_minutes;
+ const current = projection.interval_minutes;
+ const target = formatPatrolCostUSD(projection.recommendation_target_usd);
+ const budgetWord = budgetSet
+ ? 'your budget'
+ : `a ${formatPatrolCostUSD(projection.recommendation_target_usd * 2)} budget`;
+ if (projection.recommendation_reason === 'exceeds_budget_share_even_daily') {
+ const daily = intervalEstimate(projection, 1440);
+ schedule = `Even once a day costs about ${formatPatrolCostUSD(daily ?? 0)} a month, above ${target} (half of ${budgetWord}). A cheaper model is the better lever.`;
+ } else if (recommended > 0 && current > 0 && recommended > current) {
+ const recommendedUSD = intervalEstimate(projection, recommended);
+ const currentPhrase = formatPatrolIntervalPhrase(current);
+ schedule = `Pulse suggests ${formatPatrolIntervalPhrase(recommended)} (about ${formatPatrolCostUSD(recommendedUSD ?? 0)} a month) to keep scheduled runs under ${target}, half of ${budgetWord}. ${currentPhrase.charAt(0).toUpperCase()}${currentPhrase.slice(1)} is about ${formatPatrolCostUSD(projection.scheduled_projected_30d_usd)} a month.`;
+ }
+
+ let tone: PatrolCostTone = 'neutral';
+ if (budgetTone === 'danger') tone = 'danger';
+ else if (
+ budgetTone === 'warning' ||
+ projection.recommendation_reason === 'exceeds_budget_share_even_daily'
+ )
+ tone = 'warning';
+
+ return { tone, headline, detail, assumption, budget, budgetTone, schedule };
+}
+
+export interface PatrolIntervalAutoAdjust {
+ from: number;
+ to: number;
+ sentence: string;
+}
+
+/**
+ * When a per-token model is picked and the schedule is still at the 6-hour
+ * default (both in the form and as saved), propose the cost model's slower
+ * schedule. Installs that already chose a schedule are never touched.
+ */
+export function getPatrolIntervalAutoAdjust(
+ projection: PatrolCostProjection | null | undefined,
+ options: { currentIntervalMinutes: number; savedIntervalMinutes: number },
+): PatrolIntervalAutoAdjust | null {
+ if (!projection || !projection.pricing_known || !projection.billed_per_token) return null;
+ const { currentIntervalMinutes, savedIntervalMinutes } = options;
+ if (
+ currentIntervalMinutes !== PATROL_COST_DEFAULT_INTERVAL_MINUTES ||
+ savedIntervalMinutes !== PATROL_COST_DEFAULT_INTERVAL_MINUTES
+ ) {
+ return null;
+ }
+ const to = projection.recommended_interval_minutes;
+ if (!to || to <= currentIntervalMinutes) return null;
+ const before = intervalEstimate(projection, currentIntervalMinutes);
+ const after = intervalEstimate(projection, to);
+ const hours = Math.round(to / 60);
+ const sentence = `Schedule set to ${formatPatrolIntervalPhrase(to)} because ${projection.model} bills per token: about ${formatPatrolCostUSD(after ?? 0)} a month instead of ${formatPatrolCostUSD(before ?? 0)} at ${formatPatrolIntervalPhrase(currentIntervalMinutes)}, at the cost of a quiet problem waiting up to ${hours} hours for a scheduled check (alert-triggered runs still fire at once). Change it under Patrol › Schedule.`;
+ return { from: currentIntervalMinutes, to, sentence };
+}
+
+export interface PatrolModelAnnotation {
+ level: PatrolModelGuidanceLevel;
+ badge: string;
+ note: string;
+ tone: 'positive' | 'warning' | 'neutral';
+}
+
+const GUIDANCE_PRIORITY: Record<PatrolModelGuidanceLevel, number> = {
+ verified: 4,
+ caution: 3,
+ recommended: 2,
+ suggested: 1,
+};
+
+const GUIDANCE_BADGES: Record<PatrolModelGuidanceLevel, string> = {
+ verified: 'Verified on this install',
+ recommended: 'Recommended for Patrol',
+ suggested: 'Suggested starting point',
+ caution: 'Caution',
+};
+
+function isGuidanceLevel(value: string): value is PatrolModelGuidanceLevel {
+ return value in GUIDANCE_PRIORITY;
+}
+
+export function splitModelRoute(modelId: string): { provider: string; model: string } {
+ const trimmed = modelId.trim();
+ const colon = trimmed.indexOf(':');
+ if (colon > 0) {
+ return { provider: trimmed.slice(0, colon), model: trimmed.slice(colon + 1) };
+ }
+ return { provider: getProviderFromModelId(trimmed), model: trimmed };
+}
+
+export function matchesPatrolModelGuidanceRule(
+ rule: PatrolModelGuidanceRule,
+ provider: string,
+ model: string,
+): boolean {
+ if (rule.provider.toLowerCase() !== provider.trim().toLowerCase()) return false;
+ const candidate = model.trim().toLowerCase();
+ const prefix = rule.model_prefix.toLowerCase();
+ if (rule.model_exact ? candidate !== prefix : !candidate.startsWith(prefix)) return false;
+ for (const needle of rule.exclude ?? []) {
+ const lower = needle.toLowerCase();
+ if (lower.startsWith('!')) {
+ if (!candidate.includes(lower.slice(1))) return false;
+ continue;
+ }
+ if (candidate.includes(lower)) return false;
+ }
+ return true;
+}
+
+/**
+ * Resolve guidance markers for a model list. The install's own readiness
+ * pass outranks the static table; a caution outranks a suggestion.
+ */
+export function resolvePatrolModelGuidance(
+ models: Pick<ModelInfo, 'id' | 'provider'>[],
+ guidance: PatrolModelGuidanceResponse | null | undefined,
+): Map<string, PatrolModelAnnotation> {
+ const result = new Map<string, PatrolModelAnnotation>();
+ if (!guidance) return result;
+ const verified = guidance.verified ?? null;
+ for (const entry of models) {
+ const route = splitModelRoute(entry.id);
+ const provider = entry.provider?.trim() || route.provider;
+ let best: PatrolModelAnnotation | null = null;
+ for (const rule of guidance.rules ?? []) {
+ if (!isGuidanceLevel(rule.level)) continue;
+ if (!matchesPatrolModelGuidanceRule(rule, provider, route.model)) continue;
+ const candidate: PatrolModelAnnotation = {
+ level: rule.level,
+ badge: GUIDANCE_BADGES[rule.level],
+ note: rule.reason,
+ tone: rule.level === 'caution' ? 'warning' : 'positive',
+ };
+ if (!best || GUIDANCE_PRIORITY[candidate.level] > GUIDANCE_PRIORITY[best.level]) {
+ best = candidate;
+ }
+ }
+ if (
+ verified &&
+ verified.provider.toLowerCase() === provider.toLowerCase() &&
+ verified.model === route.model
+ ) {
+ const mode =
+ verified.max_verified_mode === 'approval' ? 'Watch only and Ask first' : 'Watch only';
+ best = {
+ level: 'verified',
+ badge: GUIDANCE_BADGES.verified,
+ note: `Passed Check Patrol model here for ${mode}.${best?.level === 'caution' ? ` ${best.note}` : ''}`,
+ tone: 'positive',
+ };
+ }
+ if (best) result.set(entry.id, best);
+ }
+ return result;
+}
+
+/** Model ids to pin at the top of a picker, best guidance first. */
+export function getPatrolGuidedModelIds(annotations: Map<string, PatrolModelAnnotation>): string[] {
+ return Array.from(annotations.entries())
+ .filter(([, annotation]) => annotation.level !== 'caution')
+ .sort(([, a], [, b]) => GUIDANCE_PRIORITY[b.level] - GUIDANCE_PRIORITY[a.level])
+ .map(([id]) => id);
+}
diff --git a/frontend-modern/src/utils/patrolRuntimeActions.ts b/frontend-modern/src/utils/patrolRuntimeActions.ts
index 93030420ae..9e1d1e7057 100644
--- a/frontend-modern/src/utils/patrolRuntimeActions.ts
+++ b/frontend-modern/src/utils/patrolRuntimeActions.ts
@@ -19,7 +19,15 @@ export const getPatrolProviderSettingsAction = (): PatrolRuntimeActionPresentati
...PATROL_PROVIDER_SETTINGS_ACTION,
});
+// A used-up 30-day cost budget is a spending decision, not a model fault:
+// the fix is the budget field on Provider & Models (or a cheaper model), so
+// "Check Patrol model" would send the operator to a dead end (#1789).
+export const PATROL_BUDGET_EXHAUSTED_CAUSE = 'budget_exhausted';
+
export const getPatrolSetupAction = (cause?: string): PatrolRuntimeActionPresentation => {
+ if (cause === PATROL_BUDGET_EXHAUSTED_CAUSE) {
+ return { label: 'Raise the cost budget', href: settingsTabPath('system-ai') };
+ }
if (cause && PATROL_CONFIG_LEVEL_CAUSES.has(cause)) {
return { label: 'Open Provider & Models', href: settingsTabPath('system-ai') };
}
@@ -29,6 +37,9 @@ export const getPatrolSetupAction = (cause?: string): PatrolRuntimeActionPresent
// The tool-check explainer only makes sense once a provider exists; for
// config-level causes the readiness summary already says what to do.
export const getPatrolSetupHint = (cause?: string): string => {
+ if (cause === PATROL_BUDGET_EXHAUSTED_CAUSE) {
+ return '';
+ }
if (cause && PATROL_CONFIG_LEVEL_CAUSES.has(cause)) {
return '';
}
diff --git a/internal/ai/findings.go b/internal/ai/findings.go
index 7bd30671b1..b21e2a8566 100644
--- a/internal/ai/findings.go
+++ b/internal/ai/findings.go
@@ -2022,6 +2022,11 @@ func (s *FindingsStore) Add(f *Finding) bool {
existing.Impact = f.Impact
existing.Recommendation = f.Recommendation
existing.Evidence = f.Evidence
+ // The runtime failure finding is re-raised with a fresh cause each run
+ // (provider fault, then budget exhaustion); the cause must follow the
+ // prose it explains, or the Patrol page routes the operator to the
+ // wrong fix after a restart clears the in-memory block state (#1789).
+ existing.FailureCause = f.FailureCause
if f.ObjectiveContext != nil {
existing.ObjectiveContext = clonePatrolObjectiveContext(f.ObjectiveContext)
}
diff --git a/internal/ai/findings_failure_cause_test.go b/internal/ai/findings_failure_cause_test.go
new file mode 100644
index 0000000000..a55eb672fc
--- /dev/null
+++ b/internal/ai/findings_failure_cause_test.go
@@ -0,0 +1,77 @@
+package ai
+
+import (
+ "errors"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+)
+
+func TestFindingsStoreAdd_ReRaiseRefreshesFailureCause(t *testing.T) {
+ store := NewFindingsStore()
+ now := time.Now()
+
+ first := newPatrolRuntimeFailureFinding(patrolRuntimeFailureFromError(errors.New("failed to connect: connection refused")), now)
+ if !store.Add(first) {
+ t.Fatal("expected first runtime finding to be added")
+ }
+ if got := store.Get(first.ID); got == nil || got.FailureCause != string(PatrolFailureCauseProviderConnection) {
+ t.Fatalf("expected provider_connection cause on first raise, got %+v", got)
+ }
+
+ budget := newPatrolRuntimeFailureFinding(patrolRuntimeFailureFromError(&CostBudgetExceededError{SpentUSD: 21, BudgetUSD: 20, Days: 30}), now.Add(time.Minute))
+ if store.Add(budget) {
+ t.Fatal("expected the re-raised runtime finding to merge into the existing record")
+ }
+ got := store.Get(first.ID)
+ if got == nil {
+ t.Fatal("runtime finding missing after re-raise")
+ }
+ if got.FailureCause != string(PatrolFailureCauseBudgetExhausted) {
+ t.Fatalf("re-raise must carry the new cause, got %q", got.FailureCause)
+ }
+ if got.Title != budget.Title {
+ t.Fatalf("re-raise should refresh the title, got %q", got.Title)
+ }
+}
+
+func TestResolvePatrolRuntimeFailureFinding_PreflightSuccessKeepsBudgetPause(t *testing.T) {
+ p := &PatrolService{findings: NewFindingsStore()}
+ budget := newPatrolRuntimeFailureFinding(patrolRuntimeFailureFromError(&CostBudgetExceededError{SpentUSD: 21, BudgetUSD: 20, Days: 30}), time.Now())
+ if !p.findings.Add(budget) {
+ t.Fatal("expected budget finding to be added")
+ }
+ if p.resolvePatrolRuntimeFailureFinding(patrolRuntimeResolveReasonPreflight) {
+ t.Fatal("a provider preflight must not clear a budget pause")
+ }
+ if got := p.findings.Get(budget.ID); got == nil || got.IsResolved() {
+ t.Fatal("budget finding should stay open after preflight success")
+ }
+ if !p.resolvePatrolRuntimeFailureFinding("full_patrol_success") {
+ t.Fatal("a run that got past the budget check resolves the finding")
+ }
+
+ provider := &PatrolService{findings: NewFindingsStore()}
+ fault := newPatrolRuntimeFailureFinding(patrolRuntimeFailureFromError(errors.New("failed to connect: connection refused")), time.Now())
+ provider.findings.Add(fault)
+ if !provider.resolvePatrolRuntimeFailureFinding(patrolRuntimeResolveReasonPreflight) {
+ t.Fatal("a provider fault is still cleared by a successful preflight")
+ }
+}
+
+func TestFindingsPersistence_RoundTripsFailureCause(t *testing.T) {
+ adapter := NewFindingsPersistenceAdapter(config.NewConfigPersistence(t.TempDir()))
+ budget := newPatrolRuntimeFailureFinding(patrolRuntimeFailureFromError(&CostBudgetExceededError{SpentUSD: 21, BudgetUSD: 20, Days: 30}), time.Now())
+ if err := adapter.SaveFindings(map[string]*Finding{budget.ID: budget}); err != nil {
+ t.Fatalf("save: %v", err)
+ }
+ loaded, err := adapter.LoadFindings()
+ if err != nil {
+ t.Fatalf("load: %v", err)
+ }
+ got := loaded[budget.ID]
+ if got == nil || got.FailureCause != string(PatrolFailureCauseBudgetExhausted) {
+ t.Fatalf("failure cause must survive a restart, got %+v", got)
+ }
+}
diff --git a/internal/ai/findings_persistence.go b/internal/ai/findings_persistence.go
index 4e5cabecf9..e7c6f20bf1 100644
--- a/internal/ai/findings_persistence.go
+++ b/internal/ai/findings_persistence.go
@@ -56,6 +56,7 @@ func findingsToRecords(findings map[string]*Finding) map[string]*config.AIFindin
Description: f.Description,
Recommendation: f.Recommendation,
Evidence: f.Evidence,
+ FailureCause: f.FailureCause,
Source: f.Source,
DetectedAt: f.DetectedAt,
LastSeenAt: f.LastSeenAt,
@@ -116,6 +117,7 @@ func recordsToFindings(records map[string]*config.AIFindingRecord) map[string]*F
Description: r.Description,
Recommendation: r.Recommendation,
Evidence: r.Evidence,
+ FailureCause: r.FailureCause,
Source: r.Source,
DetectedAt: r.DetectedAt,
LastSeenAt: r.LastSeenAt,
diff --git a/internal/ai/patrol_cost_projection.go b/internal/ai/patrol_cost_projection.go
new file mode 100644
index 0000000000..1154456bab
--- /dev/null
+++ b/internal/ai/patrol_cost_projection.go
@@ -0,0 +1,381 @@
+package ai
+
+import (
+ "errors"
+ "fmt"
+ "math"
+ "sort"
+ "strings"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/cost"
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+)
+
+// ErrCostBudgetExceeded is the sentinel behind every budget refusal so Patrol
+// can tell "Pulse declined to spend" apart from "the provider failed". The
+// two used to share one generic provider-error path, which is how a mispriced
+// model tripped the circuit breaker and silently disabled Patrol (#1789).
+var ErrCostBudgetExceeded = errors.New("cost budget exceeded")
+
+// CostBudgetExceededError carries the numbers behind a budget refusal so the
+// Patrol page can say what was spent against what limit.
+type CostBudgetExceededError struct {
+ SpentUSD float64
+ BudgetUSD float64
+ Days int
+}
+
+func (e *CostBudgetExceededError) Error() string {
+ return fmt.Sprintf("Pulse Intelligence cost budget exceeded (%.2f/%.2f USD over %d days) - raise the 30-day budget, choose a cheaper model, or wait for the window to roll on",
+ e.SpentUSD, e.BudgetUSD, e.Days)
+}
+
+func (e *CostBudgetExceededError) Is(target error) bool { return target == ErrCostBudgetExceeded }
+
+// patrolBudgetBlockedReason is the operator-facing sentence shown on the
+// Patrol page while runs are being skipped for budget.
+func patrolBudgetBlockedReason(err error) string {
+ var budgetErr *CostBudgetExceededError
+ if errors.As(err, &budgetErr) && budgetErr.BudgetUSD > 0 {
+ return fmt.Sprintf("Your 30-day AI cost budget is used up (about $%.2f spent of the $%.2f limit), so Patrol is skipping analysis. Raise the budget under Provider & Models, choose a cheaper model or a slower schedule, or wait for the 30-day window to roll on.",
+ budgetErr.SpentUSD, budgetErr.BudgetUSD)
+ }
+ return "Your 30-day AI cost budget is used up, so Patrol is skipping analysis. Raise the budget under Provider & Models, choose a cheaper model or a slower schedule, or wait for the 30-day window to roll on."
+}
+
+// blockOnExhaustedBudget promotes a budget refusal from a log line into the
+// Patrol runtime block state, so the Patrol page shows "Patrol paused" with
+// the reason instead of a healthy schedule that quietly never runs.
+func (p *PatrolService) blockOnExhaustedBudget(err error, failure patrolRuntimeFailure) {
+ if p == nil || failure.Cause != PatrolFailureCauseBudgetExhausted {
+ return
+ }
+ p.setBlockedReasonWithCause(patrolBudgetBlockedReason(err), PatrolFailureCauseBudgetExhausted)
+}
+
+const (
+ // DefaultPatrolRunInputTokens and DefaultPatrolRunOutputTokens are the
+ // per-run estimate used before an install has its own history. They are a
+ // full Patrol run measured on a real Proxmox install and reported in
+ // issue #1789 (104,528 input / 4,491 output tokens). Installs with many
+ // resources send more; the projection switches to the install's own
+ // median as soon as three priced full runs exist.
+ DefaultPatrolRunInputTokens int64 = 104_528
+ DefaultPatrolRunOutputTokens int64 = 4_491
+
+ // PatrolCostReferenceBudgetUSD is the reference 30-day budget the
+ // schedule recommendation targets when the operator has not set one.
+ // It is the figure support conversations and issue #1789 use, not a
+ // product default: an unset budget means unlimited spend.
+ PatrolCostReferenceBudgetUSD = 20.0
+
+ // PatrolCostRecommendedBudgetShare is how much of the budget scheduled
+ // Patrol runs may use before the schedule recommendation slows them
+ // down. The other half is headroom for alert-triggered runs, Assistant
+ // chat, and provider price drift.
+ PatrolCostRecommendedBudgetShare = 0.5
+
+ // PatrolCostDefaultIntervalMinutes mirrors the config default; the
+ // recommendation never proposes a schedule more frequent than it.
+ PatrolCostDefaultIntervalMinutes = 360
+
+ patrolCostProjectionWindowDays = 30
+ patrolCostProjectionMinHistoryRuns = 3
+
+ PatrolCostPerRunSourceHistory = "history"
+ PatrolCostPerRunSourceDefault = "default"
+
+ PatrolCostRecommendationKeep = "keep"
+ PatrolCostRecommendationFitsBudgetShare = "fits_budget_share"
+ PatrolCostRecommendationExceedsEvenDaily = "exceeds_budget_share_even_daily"
+ PatrolCostRecommendationNotBilledPerToken = "not_billed_per_token"
+ PatrolCostRecommendationPricingUnknown = "pricing_unknown"
+)
+
+// PatrolCostIntervalOptionsMinutes are the schedule presets the settings
+// page offers; the projection prices each one so the operator can compare.
+var PatrolCostIntervalOptionsMinutes = []int{60, 180, 360, 720, 1440}
+
+// PatrolCostIntervalEstimate prices one schedule preset.
+type PatrolCostIntervalEstimate struct {
+ IntervalMinutes int `json:"interval_minutes"`
+ ScheduledRunsPerDay float64 `json:"scheduled_runs_per_day"`
+ Projected30dUSD float64 `json:"projected_30d_usd"`
+}
+
+// PatrolCostProjection is the cost preview shown next to the Patrol model
+// choice. Every figure is an estimate from Pulse's price table and a per-run
+// token estimate; the assumptions travel with the numbers so the UI can show
+// them.
+type PatrolCostProjection struct {
+ Provider string `json:"provider"`
+ Model string `json:"model"`
+ ModelRoute string `json:"model_route"`
+
+ // BilledPerToken is true for providers that charge per token at a known
+ // non-zero price. Local models and free routes are not billed per token.
+ BilledPerToken bool `json:"billed_per_token"`
+ PricingKnown bool `json:"pricing_known"`
+ PricingAsOf string `json:"pricing_as_of,omitempty"`
+ InputUSDPerMTok float64 `json:"input_usd_per_mtok"`
+ OutputUSDPerMTok float64 `json:"output_usd_per_mtok"`
+
+ PerRunInputTokens int64 `json:"per_run_input_tokens"`
+ PerRunOutputTokens int64 `json:"per_run_output_tokens"`
+ PerRunSource string `json:"per_run_source"`
+ HistoryRunCount int `json:"history_run_count"`
+ PerRunUSD float64 `json:"per_run_usd"`
+
+ IntervalMinutes int `json:"interval_minutes"`
+ ScheduledRunsPerDay float64 `json:"scheduled_runs_per_day"`
+ TriggeredRunsPerDay float64 `json:"triggered_runs_per_day"`
+ TriggeredPerRunUSD float64 `json:"triggered_per_run_usd"`
+ ScheduledProjected30dUSD float64 `json:"scheduled_projected_30d_usd"`
+ Projected30dUSD float64 `json:"projected_30d_usd"`
+ IntervalEstimates []PatrolCostIntervalEstimate `json:"interval_estimates"`
+
+ BudgetUSD30d float64 `json:"budget_usd_30d"`
+ Spend30dUSD float64 `json:"spend_30d_usd"`
+ Spend30dKnown bool `json:"spend_30d_known"`
+ PatrolSpend30dUSD float64 `json:"patrol_spend_30d_usd"`
+ BudgetReached bool `json:"budget_reached"`
+
+ // RecommendedIntervalMinutes is the slowest-acceptable schedule the cost
+ // model proposes for a per-token provider, never more frequent than the
+ // default. Zero means "keep whatever is set".
+ RecommendedIntervalMinutes int `json:"recommended_interval_minutes"`
+ RecommendationReason string `json:"recommendation_reason"`
+ // RecommendationTargetUSD is the 30-day spend the recommendation aimed
+ // to stay under (the budget share of the configured or reference budget).
+ RecommendationTargetUSD float64 `json:"recommendation_target_usd"`
+}
+
+// PatrolCostProjectionInput is everything the projection needs; it carries
+// no live dependencies so it stays a pure function for tests.
+type PatrolCostProjectionInput struct {
+ Provider string
+ Model string
+ IntervalMinutes int
+ BudgetUSD30d float64
+ Runs []PatrolRunRecord
+ Spend cost.Summary
+ Now time.Time
+}
+
+func patrolRunIsFull(run PatrolRunRecord) bool {
+ if len(run.ScopeResourceIDs) > 0 || len(run.ScopeResourceTypes) > 0 || len(run.EffectiveScopeResourceIDs) > 0 {
+ return false
+ }
+ switch TriggerReason(strings.TrimSpace(run.TriggerReason)) {
+ case "", TriggerReasonScheduled, TriggerReasonManual, TriggerReasonStartup, TriggerReasonConfigChanged:
+ return true
+ }
+ return false
+}
+
+func medianInt64(values []int64) int64 {
+ if len(values) == 0 {
+ return 0
+ }
+ sorted := append([]int64(nil), values...)
+ sort.Slice(sorted, func(i, j int) bool { return sorted[i] < sorted[j] })
+ mid := len(sorted) / 2
+ if len(sorted)%2 == 0 {
+ return (sorted[mid-1] + sorted[mid]) / 2
+ }
+ return sorted[mid]
+}
+
+func roundUSD(v float64) float64 {
+ if math.IsNaN(v) || math.IsInf(v, 0) {
+ return 0
+ }
+ return math.Round(v*10000) / 10000
+}
+
+// ProjectPatrolCost estimates what Patrol will cost per 30 days on the given
+// provider/model at the given schedule, using the install's own run history
+// when it has enough and a documented default otherwise.
+func ProjectPatrolCost(in PatrolCostProjectionInput) PatrolCostProjection {
+ now := in.Now
+ if now.IsZero() {
+ now = time.Now()
+ }
+ provider := strings.ToLower(strings.TrimSpace(in.Provider))
+ model := strings.TrimSpace(in.Model)
+ out := PatrolCostProjection{
+ Provider: provider,
+ Model: model,
+ IntervalMinutes: in.IntervalMinutes,
+ BudgetUSD30d: in.BudgetUSD30d,
+ }
+ if provider != "" && model != "" {
+ out.ModelRoute = provider + ":" + model
+ }
+ if in.IntervalMinutes < 0 {
+ out.IntervalMinutes = 0
+ }
+
+ // Per-run token estimate: the install's own median full run when it has
+ // enough priced history, else the measured default.
+ windowStart := now.AddDate(0, 0, -patrolCostProjectionWindowDays)
+ oldest := now
+ var fullInputs, fullOutputs, trigInputs, trigOutputs []int64
+ triggeredCount := 0
+ for _, run := range in.Runs {
+ if run.InputTokens <= 0 || run.StartedAt.Before(windowStart) {
+ continue
+ }
+ if run.StartedAt.Before(oldest) {
+ oldest = run.StartedAt
+ }
+ if patrolRunIsFull(run) {
+ fullInputs = append(fullInputs, int64(run.InputTokens))
+ fullOutputs = append(fullOutputs, int64(run.OutputTokens))
+ continue
+ }
+ triggeredCount++
+ trigInputs = append(trigInputs, int64(run.InputTokens))
+ trigOutputs = append(trigOutputs, int64(run.OutputTokens))
+ }
+ out.PerRunSource = PatrolCostPerRunSourceDefault
+ out.PerRunInputTokens = DefaultPatrolRunInputTokens
+ out.PerRunOutputTokens = DefaultPatrolRunOutputTokens
+ if len(fullInputs) >= patrolCostProjectionMinHistoryRuns {
+ out.PerRunSource = PatrolCostPerRunSourceHistory
+ out.PerRunInputTokens = medianInt64(fullInputs)
+ out.PerRunOutputTokens = medianInt64(fullOutputs)
+ out.HistoryRunCount = len(fullInputs)
+ }
+
+ // Observed window for rates: at least one day, at most the projection
+ // window, so a fresh install does not extrapolate a burst.
+ observedDays := now.Sub(oldest).Hours() / 24
+ if observedDays < 1 {
+ observedDays = 1
+ }
+ if observedDays > patrolCostProjectionWindowDays {
+ observedDays = patrolCostProjectionWindowDays
+ }
+ if triggeredCount > 0 {
+ out.TriggeredRunsPerDay = float64(triggeredCount) / observedDays
+ }
+
+ if out.IntervalMinutes > 0 {
+ out.ScheduledRunsPerDay = 1440 / float64(out.IntervalMinutes)
+ }
+
+ // Pricing.
+ _, known, price := cost.EstimateUSD(provider, model, out.PerRunInputTokens, out.PerRunOutputTokens)
+ out.PricingKnown = known
+ if known {
+ out.PricingAsOf = price.AsOf
+ out.InputUSDPerMTok = price.InputUSDPerMTok
+ out.OutputUSDPerMTok = price.OutputUSDPerMTok
+ out.BilledPerToken = price.InputUSDPerMTok > 0 || price.OutputUSDPerMTok > 0
+ }
+ perRun := func(inputTokens, outputTokens int64) float64 {
+ if !known {
+ return 0
+ }
+ usd, _, _ := cost.EstimateUSD(provider, model, inputTokens, outputTokens)
+ return usd
+ }
+ out.PerRunUSD = roundUSD(perRun(out.PerRunInputTokens, out.PerRunOutputTokens))
+ if triggeredCount > 0 {
+ out.TriggeredPerRunUSD = roundUSD(perRun(medianInt64(trigInputs), medianInt64(trigOutputs)))
+ }
+ scheduled30d := func(intervalMinutes int) float64 {
+ if intervalMinutes <= 0 {
+ return 0
+ }
+ return (1440 / float64(intervalMinutes)) * out.PerRunUSD * patrolCostProjectionWindowDays
+ }
+ out.ScheduledProjected30dUSD = roundUSD(scheduled30d(out.IntervalMinutes))
+ out.Projected30dUSD = roundUSD(out.ScheduledProjected30dUSD + out.TriggeredRunsPerDay*out.TriggeredPerRunUSD*patrolCostProjectionWindowDays)
+ for _, option := range PatrolCostIntervalOptionsMinutes {
+ out.IntervalEstimates = append(out.IntervalEstimates, PatrolCostIntervalEstimate{
+ IntervalMinutes: option,
+ ScheduledRunsPerDay: 1440 / float64(option),
+ Projected30dUSD: roundUSD(scheduled30d(option)),
+ })
+ }
+
+ // Spend against budget, on the same basis enforceBudget uses.
+ out.Spend30dKnown = in.Spend.Totals.PricingKnown
+ out.Spend30dUSD = roundUSD(in.Spend.Totals.EstimatedUSD)
+ for _, useCase := range in.Spend.UseCases {
+ if strings.EqualFold(useCase.UseCase, "patrol") && useCase.PricingKnown {
+ out.PatrolSpend30dUSD = roundUSD(useCase.EstimatedUSD)
+ }
+ }
+ out.BudgetReached = in.BudgetUSD30d > 0 && out.Spend30dKnown && in.Spend.Totals.EstimatedUSD >= in.BudgetUSD30d
+
+ // Schedule recommendation for per-token providers.
+ switch {
+ case !known:
+ out.RecommendationReason = PatrolCostRecommendationPricingUnknown
+ case !out.BilledPerToken:
+ out.RecommendationReason = PatrolCostRecommendationNotBilledPerToken
+ default:
+ referenceBudget := in.BudgetUSD30d
+ if referenceBudget <= 0 {
+ referenceBudget = PatrolCostReferenceBudgetUSD
+ }
+ target := referenceBudget * PatrolCostRecommendedBudgetShare
+ out.RecommendationTargetUSD = roundUSD(target)
+ recommended := 0
+ for _, option := range PatrolCostIntervalOptionsMinutes {
+ if option < PatrolCostDefaultIntervalMinutes {
+ continue
+ }
+ if scheduled30d(option) <= target {
+ recommended = option
+ break
+ }
+ }
+ if recommended == 0 {
+ out.RecommendedIntervalMinutes = PatrolCostIntervalOptionsMinutes[len(PatrolCostIntervalOptionsMinutes)-1]
+ out.RecommendationReason = PatrolCostRecommendationExceedsEvenDaily
+ } else {
+ out.RecommendedIntervalMinutes = recommended
+ out.RecommendationReason = PatrolCostRecommendationFitsBudgetShare
+ }
+ }
+ return out
+}
+
+// ProjectPatrolCostForConfig resolves the effective Patrol model, interval,
+// and budget from config, overriding model/interval when the caller is
+// previewing a pending selection.
+func ProjectPatrolCostForConfig(cfg *config.AIConfig, modelRoute string, intervalMinutes int, runs []PatrolRunRecord, spend cost.Summary, now time.Time) PatrolCostProjection {
+ route := strings.TrimSpace(modelRoute)
+ interval := intervalMinutes
+ var budget float64
+ if cfg != nil {
+ if route == "" {
+ route = cfg.GetPatrolModel()
+ }
+ if interval < 0 {
+ interval = cfg.PatrolIntervalMinutes
+ }
+ budget = cfg.CostBudgetUSD30d
+ }
+ if interval < 0 {
+ interval = PatrolCostDefaultIntervalMinutes
+ }
+ provider, model := "", ""
+ if route != "" {
+ provider, model = config.ParseModelString(route)
+ }
+ return ProjectPatrolCost(PatrolCostProjectionInput{
+ Provider: provider,
+ Model: model,
+ IntervalMinutes: interval,
+ BudgetUSD30d: budget,
+ Runs: runs,
+ Spend: spend,
+ Now: now,
+ })
+}
diff --git a/internal/ai/patrol_cost_projection_test.go b/internal/ai/patrol_cost_projection_test.go
new file mode 100644
index 0000000000..c31098272c
--- /dev/null
+++ b/internal/ai/patrol_cost_projection_test.go
@@ -0,0 +1,233 @@
+package ai
+
+import (
+ "errors"
+ "strings"
+ "testing"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/cost"
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+)
+
+func TestProjectPatrolCost_DefaultRunUsesMeasuredTokensAndPriceTable(t *testing.T) {
+ now := time.Date(2026, 9, 1, 12, 0, 0, 0, time.UTC)
+ got := ProjectPatrolCost(PatrolCostProjectionInput{
+ Provider: "gemini",
+ Model: "gemini-2.5-flash",
+ IntervalMinutes: 360,
+ BudgetUSD30d: 20,
+ Now: now,
+ })
+ if got.PerRunSource != PatrolCostPerRunSourceDefault || got.PerRunInputTokens != DefaultPatrolRunInputTokens {
+ t.Fatalf("expected default per-run estimate, got %+v", got)
+ }
+ if !got.PricingKnown || !got.BilledPerToken {
+ t.Fatalf("expected known per-token pricing for gemini flash, got %+v", got)
+ }
+ // 104,528 * 0.30/M + 4,491 * 2.50/M = 0.0314 + 0.0112 = 0.0426 per run.
+ if got.PerRunUSD < 0.042 || got.PerRunUSD > 0.044 {
+ t.Fatalf("unexpected per-run cost %.4f", got.PerRunUSD)
+ }
+ if got.ScheduledRunsPerDay != 4 {
+ t.Fatalf("expected 4 scheduled runs a day at 6h, got %v", got.ScheduledRunsPerDay)
+ }
+ // 4 runs * 30 days * 0.0426 = 5.11.
+ if got.ScheduledProjected30dUSD < 5.0 || got.ScheduledProjected30dUSD > 5.3 {
+ t.Fatalf("unexpected scheduled 30d projection %.4f", got.ScheduledProjected30dUSD)
+ }
+ if got.Projected30dUSD != got.ScheduledProjected30dUSD {
+ t.Fatalf("no triggered history: projection should equal scheduled, got %+v", got)
+ }
+ if len(got.IntervalEstimates) != len(PatrolCostIntervalOptionsMinutes) {
+ t.Fatalf("expected one estimate per preset, got %d", len(got.IntervalEstimates))
+ }
+ // Half of a $20 budget is $10; 6h ($5.11) already fits, so keep 6h.
+ if got.RecommendedIntervalMinutes != 360 || got.RecommendationReason != PatrolCostRecommendationFitsBudgetShare {
+ t.Fatalf("expected 6h recommendation within budget share, got %d (%s)", got.RecommendedIntervalMinutes, got.RecommendationReason)
+ }
+ if got.RecommendationTargetUSD != 10 {
+ t.Fatalf("expected $10 target, got %v", got.RecommendationTargetUSD)
+ }
+}
+
+func TestProjectPatrolCost_ExpensiveModelSlowsScheduleToFitBudgetShare(t *testing.T) {
+ got := ProjectPatrolCost(PatrolCostProjectionInput{
+ Provider: "anthropic",
+ Model: "claude-sonnet-5",
+ IntervalMinutes: 360,
+ BudgetUSD30d: 20,
+ })
+ // Sonnet 5: 104,528*2/M + 4,491*10/M = 0.209 + 0.045 = 0.254 per run.
+ // 6h -> $30.5, 12h -> $15.2, daily -> $7.6: only daily fits under $10.
+ if got.RecommendedIntervalMinutes != 1440 || got.RecommendationReason != PatrolCostRecommendationFitsBudgetShare {
+ t.Fatalf("expected daily recommendation, got %d (%s) scheduled=%.2f", got.RecommendedIntervalMinutes, got.RecommendationReason, got.ScheduledProjected30dUSD)
+ }
+ if got.ScheduledProjected30dUSD < 29 || got.ScheduledProjected30dUSD > 32 {
+ t.Fatalf("unexpected 6h projection for sonnet %.2f", got.ScheduledProjected30dUSD)
+ }
+}
+
+func TestProjectPatrolCost_OpusExceedsBudgetShareEvenDaily(t *testing.T) {
+ got := ProjectPatrolCost(PatrolCostProjectionInput{
+ Provider: "anthropic",
+ Model: "claude-fable-5-1",
+ IntervalMinutes: 360,
+ })
+ // No budget configured: the $20 reference applies. Fable 5: 104,528*10/M
+ // + 4,491*50/M = 1.045 + 0.225 = 1.27 per run; daily is $38 > $10.
+ if got.RecommendedIntervalMinutes != 1440 || got.RecommendationReason != PatrolCostRecommendationExceedsEvenDaily {
+ t.Fatalf("expected exceeds-even-daily, got %d (%s)", got.RecommendedIntervalMinutes, got.RecommendationReason)
+ }
+ if got.RecommendationTargetUSD != PatrolCostReferenceBudgetUSD*PatrolCostRecommendedBudgetShare {
+ t.Fatalf("expected reference-budget target, got %v", got.RecommendationTargetUSD)
+ }
+}
+
+func TestProjectPatrolCost_LocalModelIsNotBilledPerToken(t *testing.T) {
+ got := ProjectPatrolCost(PatrolCostProjectionInput{
+ Provider: "ollama",
+ Model: "qwen3:8b",
+ IntervalMinutes: 60,
+ })
+ if !got.PricingKnown || got.BilledPerToken {
+ t.Fatalf("expected local model to be known and unbilled, got %+v", got)
+ }
+ if got.Projected30dUSD != 0 || got.RecommendedIntervalMinutes != 0 || got.RecommendationReason != PatrolCostRecommendationNotBilledPerToken {
+ t.Fatalf("expected zero projection and no schedule change for local model, got %+v", got)
+ }
+}
+
+func TestProjectPatrolCost_UnknownPricingStaysHonest(t *testing.T) {
+ got := ProjectPatrolCost(PatrolCostProjectionInput{
+ Provider: "openai",
+ Model: "gpt-9-unpriced",
+ IntervalMinutes: 360,
+ })
+ if got.PricingKnown || got.BilledPerToken || got.Projected30dUSD != 0 {
+ t.Fatalf("expected unknown pricing with no projection, got %+v", got)
+ }
+ if got.RecommendationReason != PatrolCostRecommendationPricingUnknown {
+ t.Fatalf("expected pricing-unknown reason, got %q", got.RecommendationReason)
+ }
+}
+
+func TestProjectPatrolCost_UsesInstallHistoryMedianAndTriggeredRate(t *testing.T) {
+ now := time.Date(2026, 9, 1, 12, 0, 0, 0, time.UTC)
+ runs := []PatrolRunRecord{
+ {StartedAt: now.Add(-6 * time.Hour), TriggerReason: string(TriggerReasonScheduled), InputTokens: 200_000, OutputTokens: 6_000},
+ {StartedAt: now.Add(-12 * time.Hour), TriggerReason: string(TriggerReasonScheduled), InputTokens: 220_000, OutputTokens: 8_000},
+ {StartedAt: now.Add(-18 * time.Hour), TriggerReason: string(TriggerReasonManual), InputTokens: 240_000, OutputTokens: 7_000},
+ // Skipped run (budget) records no tokens and must not drag the median down.
+ {StartedAt: now.Add(-24 * time.Hour), TriggerReason: string(TriggerReasonScheduled), InputTokens: 0},
+ // Alert-triggered scoped runs count toward the triggered rate, not the full-run median.
+ {StartedAt: now.Add(-30 * time.Hour), TriggerReason: string(TriggerReasonAlertFired), ScopeResourceIDs: []string{"vm/100"}, InputTokens: 30_000, OutputTokens: 1_000},
+ {StartedAt: now.Add(-40 * time.Hour), TriggerReason: string(TriggerReasonAlertFired), ScopeResourceIDs: []string{"vm/101"}, InputTokens: 32_000, OutputTokens: 1_200},
+ // Outside the 30-day window: ignored.
+ {StartedAt: now.Add(-31 * 24 * time.Hour), TriggerReason: string(TriggerReasonScheduled), InputTokens: 900_000, OutputTokens: 50_000},
+ }
+ got := ProjectPatrolCost(PatrolCostProjectionInput{
+ Provider: "gemini",
+ Model: "gemini-2.5-flash",
+ IntervalMinutes: 360,
+ BudgetUSD30d: 20,
+ Runs: runs,
+ Now: now,
+ })
+ if got.PerRunSource != PatrolCostPerRunSourceHistory || got.HistoryRunCount != 3 {
+ t.Fatalf("expected history-based estimate from 3 full runs, got %+v", got)
+ }
+ if got.PerRunInputTokens != 220_000 || got.PerRunOutputTokens != 7_000 {
+ t.Fatalf("expected median of full runs, got in=%d out=%d", got.PerRunInputTokens, got.PerRunOutputTokens)
+ }
+ // Two triggered runs over an observed window of 40h (clamped to >= 1 day): 2/1.667 = 1.2 a day.
+ if got.TriggeredRunsPerDay < 1.1 || got.TriggeredRunsPerDay > 1.3 {
+ t.Fatalf("unexpected triggered rate %.3f", got.TriggeredRunsPerDay)
+ }
+ if got.TriggeredPerRunUSD <= 0 || got.Projected30dUSD <= got.ScheduledProjected30dUSD {
+ t.Fatalf("expected triggered runs to add to the projection, got %+v", got)
+ }
+}
+
+func TestProjectPatrolCost_BudgetReachedMirrorsEnforcement(t *testing.T) {
+ store := cost.NewStore(30)
+ store.Record(cost.UsageEvent{Timestamp: time.Now(), Provider: "anthropic", RequestModel: "claude-opus-5", UseCase: "patrol", InputTokens: 3_000_000, OutputTokens: 200_000})
+ summary := store.GetSummary(30)
+ got := ProjectPatrolCost(PatrolCostProjectionInput{
+ Provider: "anthropic",
+ Model: "claude-opus-5",
+ IntervalMinutes: 360,
+ BudgetUSD30d: 20,
+ Spend: summary,
+ })
+ if !got.Spend30dKnown || got.Spend30dUSD < 19.9 {
+ t.Fatalf("expected known spend of about $20, got %+v", got)
+ }
+ if !got.BudgetReached || got.PatrolSpend30dUSD != got.Spend30dUSD {
+ t.Fatalf("expected budget reached with patrol spend attributed, got %+v", got)
+ }
+}
+
+func TestProjectPatrolCostForConfig_ResolvesPatrolModelAndInterval(t *testing.T) {
+ cfg := config.NewDefaultAIConfig()
+ cfg.Model = "gemini:gemini-2.5-flash"
+ cfg.PatrolModel = "anthropic:claude-haiku-4-5"
+ cfg.PatrolIntervalMinutes = 720
+ cfg.CostBudgetUSD30d = 15
+ got := ProjectPatrolCostForConfig(cfg, "", -1, nil, cost.Summary{}, time.Time{})
+ if got.Provider != "anthropic" || got.Model != "claude-haiku-4-5" || got.ModelRoute != "anthropic:claude-haiku-4-5" {
+ t.Fatalf("expected patrol override to win, got %+v", got)
+ }
+ if got.IntervalMinutes != 720 || got.BudgetUSD30d != 15 {
+ t.Fatalf("expected config interval and budget, got %+v", got)
+ }
+ pending := ProjectPatrolCostForConfig(cfg, "gemini:gemini-2.5-flash", 60, nil, cost.Summary{}, time.Time{})
+ if pending.Provider != "gemini" || pending.IntervalMinutes != 60 {
+ t.Fatalf("expected pending selection to override config, got %+v", pending)
+ }
+}
+
+func TestCostBudgetExceededError_IsSentinelAndKeepsLegacyWording(t *testing.T) {
+ err := &CostBudgetExceededError{SpentUSD: 27.08, BudgetUSD: 20, Days: 30}
+ if !errors.Is(err, ErrCostBudgetExceeded) {
+ t.Fatal("expected budget error to match the sentinel")
+ }
+ if !strings.Contains(err.Error(), "budget exceeded (27.08/20.00 USD over 30 days)") {
+ t.Fatalf("unexpected wording %q", err.Error())
+ }
+ reason := patrolBudgetBlockedReason(err)
+ if !strings.Contains(reason, "$27.08") || !strings.Contains(reason, "$20.00") || !strings.Contains(reason, "Provider & Models") {
+ t.Fatalf("blocked reason should name spend, limit, and where to fix it: %q", reason)
+ }
+}
+
+func TestPatrolRuntimeFailureFromError_BudgetExhaustedIsNotAProviderFault(t *testing.T) {
+ failure := patrolRuntimeFailureFromError(&CostBudgetExceededError{SpentUSD: 21, BudgetUSD: 20, Days: 30})
+ if failure.Cause != PatrolFailureCauseBudgetExhausted {
+ t.Fatalf("expected budget cause, got %q", failure.Cause)
+ }
+ if !strings.Contains(failure.Recommendation, "Provider & Models") {
+ t.Fatalf("recommendation should point at the budget setting: %q", failure.Recommendation)
+ }
+ if strings.Contains(strings.ToLower(failure.Summary), "provider") {
+ t.Fatalf("summary must not blame the provider: %q", failure.Summary)
+ }
+}
+
+func TestBlockOnExhaustedBudget_SetsPatrolBlockedState(t *testing.T) {
+ p := &PatrolService{}
+ err := &CostBudgetExceededError{SpentUSD: 21, BudgetUSD: 20, Days: 30}
+ p.blockOnExhaustedBudget(err, patrolRuntimeFailureFromError(err))
+ p.mu.RLock()
+ reason, cause := p.lastBlockedReason, p.lastBlockedCause
+ p.mu.RUnlock()
+ if cause != PatrolFailureCauseBudgetExhausted || !strings.Contains(reason, "used up") {
+ t.Fatalf("expected blocked state for budget, got cause=%q reason=%q", cause, reason)
+ }
+ // Any other failure leaves the block state alone.
+ other := &PatrolService{}
+ other.blockOnExhaustedBudget(errors.New("boom"), patrolRuntimeFailureFromError(errors.New("boom")))
+ if other.lastBlockedCause != "" {
+ t.Fatalf("non-budget failures must not block, got %q", other.lastBlockedCause)
+ }
+}
diff --git a/internal/ai/patrol_model_guidance.go b/internal/ai/patrol_model_guidance.go
new file mode 100644
index 0000000000..aecde89c3f
--- /dev/null
+++ b/internal/ai/patrol_model_guidance.go
@@ -0,0 +1,183 @@
+package ai
+
+import (
+ "fmt"
+ "strings"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/cost"
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+)
+
+// Patrol model guidance answers the question every prospect asks before
+// trying Patrol: "which model should I pick?" (support, 2026-07-30). Pulse
+// has one qualified answer today (the Ollama blessing verified by
+// RunPatrolToolPreflight) and one verified failure (Gemini Flash-Lite could
+// not file per-finding verdicts, support 2026-07-20). Everything else here
+// is a labelled starting point chosen by price, not a qualification claim:
+// the per-install "Check Patrol model" run is what turns a suggestion into
+// evidence, and its cached pass is surfaced as the strongest marker.
+const (
+ // PatrolModelGuidanceVerified: this install's own readiness check passed.
+ PatrolModelGuidanceVerified = "verified"
+ // PatrolModelGuidanceRecommended: passed Pulse's Patrol preflight.
+ PatrolModelGuidanceRecommended = "recommended"
+ // PatrolModelGuidanceSuggested: cheapest standard tier on Pulse's price
+ // list for the provider; not yet qualified by Pulse.
+ PatrolModelGuidanceSuggested = "suggested"
+ // PatrolModelGuidanceCaution: known to fail or drop Patrol tool calls.
+ PatrolModelGuidanceCaution = "caution"
+)
+
+// PatrolModelGuidanceRule matches models by provider and id prefix so it
+// survives dated model ids (claude-haiku-4-5-20251001) and previews.
+// Exclude entries are forbidden substrings; an entry starting with "!" is a
+// required substring instead.
+type PatrolModelGuidanceRule struct {
+ Provider string `json:"provider"`
+ ModelPrefix string `json:"model_prefix"`
+ ModelExact bool `json:"model_exact,omitempty"`
+ Exclude []string `json:"exclude,omitempty"`
+ Level string `json:"level"`
+ Reason string `json:"reason"`
+ Evidence string `json:"evidence,omitempty"`
+}
+
+// PatrolModelVerifiedGuidance is the cached readiness pass for the model
+// this install currently runs Patrol on.
+type PatrolModelVerifiedGuidance struct {
+ Provider string `json:"provider"`
+ Model string `json:"model"`
+ MaxVerifiedMode string `json:"max_verified_mode,omitempty"`
+ RecordedAtUnix int64 `json:"recorded_at_unix"`
+}
+
+// PatrolModelGuidanceResponse is the payload behind the model picker markers.
+type PatrolModelGuidanceResponse struct {
+ Rules []PatrolModelGuidanceRule `json:"rules"`
+ Verified *PatrolModelVerifiedGuidance `json:"verified,omitempty"`
+}
+
+func patrolFullRunCostSentence(provider, model string) string {
+ usd, ok, _ := cost.EstimateUSD(provider, model, DefaultPatrolRunInputTokens, DefaultPatrolRunOutputTokens)
+ if !ok {
+ return ""
+ }
+ if usd == 0 {
+ return "No per-token charge on Pulse's price list."
+ }
+ if usd < 0.01 {
+ return "Under a cent per full Patrol run on Pulse's price list."
+ }
+ return fmt.Sprintf("About $%.2f per full Patrol run on Pulse's price list.", usd)
+}
+
+func patrolSuggestedGuidance(provider, prefix string, exclude ...string) PatrolModelGuidanceRule {
+ return PatrolModelGuidanceRule{
+ Provider: provider,
+ ModelPrefix: prefix,
+ Exclude: exclude,
+ Level: PatrolModelGuidanceSuggested,
+ Reason: strings.TrimSpace(fmt.Sprintf(
+ "Lowest-cost standard tier for this provider. %s Not yet qualified by Pulse: run Check Patrol model before relying on it.",
+ patrolFullRunCostSentence(provider, prefix))),
+ Evidence: "price-table",
+ }
+}
+
+// StaticPatrolModelGuidance returns the maintained guidance table. Cloud
+// entries are price-driven starting points and say so; only the Ollama
+// blessing and the Flash-Lite caution carry evidence.
+func StaticPatrolModelGuidance() []PatrolModelGuidanceRule {
+ ollamaReason := "Passed Pulse's Patrol tool-call check and runs on your own hardware, so there is no per-token bill."
+ var ollamaEquivalents []string
+ if def, ok := config.LookupAIProviderDefinition(config.AIProviderOllama); ok {
+ if note := strings.TrimSpace(def.SuggestedModelNote); note != "" {
+ ollamaReason += " " + note
+ }
+ ollamaEquivalents = def.SuggestedModelEquivalents
+ }
+ rules := []PatrolModelGuidanceRule{
+ {
+ Provider: config.AIProviderOllama,
+ ModelPrefix: config.OllamaSuggestedPatrolModel,
+ ModelExact: true,
+ Level: PatrolModelGuidanceRecommended,
+ Reason: ollamaReason,
+ Evidence: "patrol-preflight",
+ },
+ }
+ for _, equivalent := range ollamaEquivalents {
+ rules = append(rules, PatrolModelGuidanceRule{
+ Provider: config.AIProviderOllama,
+ ModelPrefix: equivalent,
+ ModelExact: true,
+ Level: PatrolModelGuidanceRecommended,
+ Reason: ollamaReason,
+ Evidence: "patrol-preflight",
+ })
+ }
+ rules = append(rules,
+ PatrolModelGuidanceRule{
+ Provider: config.AIProviderGemini,
+ ModelPrefix: "gemini-",
+ Exclude: []string{"!flash-lite"},
+ Level: PatrolModelGuidanceCaution,
+ Reason: "Flash-Lite could not file Patrol's per-finding verdicts, so every run on a Pro install ended in an assessment error. Pick a standard Flash or Pro tier instead.",
+ Evidence: "support-2026-07-20",
+ },
+ patrolSuggestedGuidance(config.AIProviderGemini, "gemini-2.5-flash", "lite", "image", "live"),
+ patrolSuggestedGuidance(config.AIProviderAnthropic, "claude-haiku-4-5"),
+ patrolSuggestedGuidance(config.AIProviderOpenAI, "gpt-4o-mini"),
+ patrolSuggestedGuidance(config.AIProviderDeepSeek, config.DeepSeekModelV4Flash),
+ patrolSuggestedGuidance(config.AIProviderOpenRouter, "deepseek/deepseek-v4-flash"),
+ )
+ return rules
+}
+
+// MatchesPatrolModelGuidance reports whether a rule applies to a model id.
+func MatchesPatrolModelGuidance(rule PatrolModelGuidanceRule, provider, model string) bool {
+ if !strings.EqualFold(strings.TrimSpace(provider), rule.Provider) {
+ return false
+ }
+ candidate := strings.ToLower(strings.TrimSpace(model))
+ prefix := strings.ToLower(rule.ModelPrefix)
+ if rule.ModelExact {
+ if candidate != prefix {
+ return false
+ }
+ } else if !strings.HasPrefix(candidate, prefix) {
+ return false
+ }
+ for _, needle := range rule.Exclude {
+ lower := strings.ToLower(needle)
+ if strings.HasPrefix(lower, "!") {
+ if !strings.Contains(candidate, strings.TrimPrefix(lower, "!")) {
+ return false
+ }
+ continue
+ }
+ if strings.Contains(candidate, lower) {
+ return false
+ }
+ }
+ return true
+}
+
+// PatrolModelGuidance combines the static table with this install's cached
+// readiness pass for the configured Patrol model.
+func (s *Service) PatrolModelGuidance() PatrolModelGuidanceResponse {
+ response := PatrolModelGuidanceResponse{Rules: StaticPatrolModelGuidance()}
+ if s == nil {
+ return response
+ }
+ result, recordedAt := s.CachedPatrolModelReadiness()
+ if result != nil && result.Status == PatrolModelReadinessPass && result.PatrolCapable {
+ response.Verified = &PatrolModelVerifiedGuidance{
+ Provider: result.Provider,
+ Model: result.Model,
+ MaxVerifiedMode: result.MaxVerifiedMode,
+ RecordedAtUnix: recordedAt.Unix(),
+ }
+ }
+ return response
+}
diff --git a/internal/ai/patrol_model_guidance_test.go b/internal/ai/patrol_model_guidance_test.go
new file mode 100644
index 0000000000..7ddd5a41fa
--- /dev/null
+++ b/internal/ai/patrol_model_guidance_test.go
@@ -0,0 +1,83 @@
+package ai
+
+import (
+ "strings"
+ "testing"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+)
+
+func findGuidance(t *testing.T, provider, model string) []PatrolModelGuidanceRule {
+ t.Helper()
+ var matched []PatrolModelGuidanceRule
+ for _, rule := range StaticPatrolModelGuidance() {
+ if MatchesPatrolModelGuidance(rule, provider, model) {
+ matched = append(matched, rule)
+ }
+ }
+ return matched
+}
+
+func TestStaticPatrolModelGuidance_OllamaBlessingIsRecommendedWithHardwareNote(t *testing.T) {
+ rules := findGuidance(t, config.AIProviderOllama, config.OllamaSuggestedPatrolModel)
+ if len(rules) != 1 || rules[0].Level != PatrolModelGuidanceRecommended {
+ t.Fatalf("expected one recommended rule for the Ollama blessing, got %+v", rules)
+ }
+ if !strings.Contains(rules[0].Reason, "8 GB") || !strings.Contains(rules[0].Reason, "no per-token bill") {
+ t.Fatalf("reason should carry the hardware note and the no-bill point: %q", rules[0].Reason)
+ }
+ if len(findGuidance(t, config.AIProviderOllama, "qwen3:4b")) != 0 {
+ t.Fatal("smaller qwen3 tags failed preflight and must not inherit the blessing")
+ }
+}
+
+func TestStaticPatrolModelGuidance_FlashLiteIsCautionAndFlashIsSuggested(t *testing.T) {
+ lite := findGuidance(t, config.AIProviderGemini, "gemini-2.5-flash-lite")
+ if len(lite) != 1 || lite[0].Level != PatrolModelGuidanceCaution {
+ t.Fatalf("expected a single caution rule for flash-lite, got %+v", lite)
+ }
+ if !strings.Contains(lite[0].Reason, "verdicts") {
+ t.Fatalf("caution should say what failed: %q", lite[0].Reason)
+ }
+ flash := findGuidance(t, config.AIProviderGemini, "gemini-2.5-flash")
+ if len(flash) != 1 || flash[0].Level != PatrolModelGuidanceSuggested {
+ t.Fatalf("expected flash to be suggested, got %+v", flash)
+ }
+ if !strings.Contains(flash[0].Reason, "$0.04") || !strings.Contains(flash[0].Reason, "Not yet qualified") {
+ t.Fatalf("suggested reason should show the per-run price and the qualification caveat: %q", flash[0].Reason)
+ }
+ if len(findGuidance(t, config.AIProviderGemini, "gemini-2.5-flash-image")) != 0 {
+ t.Fatal("image and live variants are not Patrol starting points")
+ }
+}
+
+func TestStaticPatrolModelGuidance_CloudStartingPointsMatchDatedIDs(t *testing.T) {
+ haiku := findGuidance(t, config.AIProviderAnthropic, "claude-haiku-4-5-20251001")
+ if len(haiku) != 1 || haiku[0].Level != PatrolModelGuidanceSuggested {
+ t.Fatalf("expected dated haiku id to match the prefix rule, got %+v", haiku)
+ }
+ if len(findGuidance(t, config.AIProviderAnthropic, "claude-opus-5")) != 0 {
+ t.Fatal("opus carries no guidance: price alone is not a caution")
+ }
+ if len(findGuidance(t, config.AIProviderOpenAI, "gpt-4o-mini")) != 1 {
+ t.Fatal("expected gpt-4o-mini starting point")
+ }
+ if len(findGuidance(t, "openai", "GPT-4O")) != 0 {
+ t.Fatal("full gpt-4o is not the lowest-cost tier")
+ }
+}
+
+func TestPatrolModelGuidance_VerifiedRequiresCachedPassForConfiguredModel(t *testing.T) {
+ svc := NewService(nil, nil)
+ response := svc.PatrolModelGuidance()
+ if response.Verified != nil {
+ t.Fatal("no cached readiness: verified marker must be absent")
+ }
+ if len(response.Rules) == 0 {
+ t.Fatal("static rules must always be present")
+ }
+ var nilService *Service
+ if got := nilService.PatrolModelGuidance(); len(got.Rules) == 0 || got.Verified != nil {
+ t.Fatalf("nil service should still return static rules, got %+v", got)
+ }
+}
diff --git a/internal/ai/patrol_preflight.go b/internal/ai/patrol_preflight.go
index a63c1c5156..094083ed04 100644
--- a/internal/ai/patrol_preflight.go
+++ b/internal/ai/patrol_preflight.go
@@ -337,7 +337,7 @@ func (s *Service) recoverPatrolAfterToolPreflight(result PatrolPreflightResult)
return false
}
breakerRecovered := patrol.recoverCircuitBreakerAfterVerifiedPreflight()
- runtimeFindingResolved := patrol.resolvePatrolRuntimeFailureFinding("patrol_preflight_success")
+ runtimeFindingResolved := patrol.resolvePatrolRuntimeFailureFinding(patrolRuntimeResolveReasonPreflight)
return breakerRecovered || runtimeFindingResolved
}
diff --git a/internal/ai/patrol_readiness.go b/internal/ai/patrol_readiness.go
index 02d618aa85..34d4646e3e 100644
--- a/internal/ai/patrol_readiness.go
+++ b/internal/ai/patrol_readiness.go
@@ -46,6 +46,12 @@ const (
// or model did. It must never be presented as a model verdict (#1640).
PatrolFailureCauseInternalError PatrolFailureCause = "internal_error"
PatrolFailureCauseCircuitOpen PatrolFailureCause = "circuit_open"
+ // PatrolFailureCauseBudgetExhausted marks a run skipped because the
+ // operator's 30-day cost budget is used up. It is a spending decision,
+ // not a provider or model fault: the provider was never called, so it
+ // must not feed the circuit breaker or read as a model verdict, and the
+ // Patrol page must say so instead of leaving the skip in the logs (#1789).
+ PatrolFailureCauseBudgetExhausted PatrolFailureCause = "budget_exhausted"
)
type PatrolConfigReadiness struct {
diff --git a/internal/ai/patrol_run.go b/internal/ai/patrol_run.go
index 17d8c2e48f..3afb1175ec 100644
--- a/internal/ai/patrol_run.go
+++ b/internal/ai/patrol_run.go
@@ -6,6 +6,7 @@ package ai
import (
"context"
"crypto/sha256"
+ "errors"
"fmt"
"regexp"
"strconv"
@@ -632,6 +633,7 @@ func (p *PatrolService) runPatrolWithTriggerStart(ctx context.Context, trigger T
failure := patrolRuntimeFailureFromError(aiErr)
runStats.errorSummary = failure.Summary
runStats.errorDetail = failure.Detail
+ p.blockOnExhaustedBudget(aiErr, failure)
// Create a finding to surface this error to the user
errorFinding := newPatrolRuntimeFailureFinding(failure, time.Now())
@@ -1149,6 +1151,7 @@ func (p *PatrolService) runScopedPatrolWithStart(ctx context.Context, scope Patr
failure := patrolRuntimeFailureFromError(aiErr)
runStats.errorSummary = failure.Summary
runStats.errorDetail = failure.Detail
+ p.blockOnExhaustedBudget(aiErr, failure)
errorFinding := newPatrolRuntimeFailureFinding(failure, time.Now())
if p.recordFinding(errorFinding) {
runStats.newFindings++
@@ -1305,6 +1308,11 @@ func recordPatrolCircuitResult(breaker *circuit.Breaker, attempted bool, errorCo
if runErr == nil {
runErr = fmt.Errorf("patrol completed with %d errors", errorCount)
}
+ if errors.Is(runErr, ErrCostBudgetExceeded) {
+ // Pulse declined to spend; the provider was never called, so there
+ // is no provider failure to count (#1789).
+ return
+ }
breaker.RecordFailureWithCategory(runErr, circuit.CategorizeError(runErr))
}
diff --git a/internal/ai/patrol_runtime_failure.go b/internal/ai/patrol_runtime_failure.go
index eb9e0a909a..e73e5f8758 100644
--- a/internal/ai/patrol_runtime_failure.go
+++ b/internal/ai/patrol_runtime_failure.go
@@ -298,6 +298,13 @@ func patrolRuntimeFailureFromErrorCtx(ctx context.Context, err error) patrolRunt
failure.Cause = PatrolFailureCauseInterrupted
failure.Description = "The Patrol run was cancelled before the provider finished, either by an operator cancel or because the client connection closed mid-analysis. An interrupted run is not evidence about the provider or model."
failure.Recommendation = "Run the analysis again when you are ready. If you did not cancel it, check for reverse proxies or load balancers that close long-running requests."
+ case errors.Is(err, ErrCostBudgetExceeded):
+ // The provider was never called: Pulse itself declined to spend.
+ failure.Title = "Pulse Patrol: 30-day cost budget reached"
+ failure.Summary = "30-day cost budget reached"
+ failure.Cause = PatrolFailureCauseBudgetExhausted
+ failure.Description = "Pulse Patrol skipped its analysis because estimated spend on AI providers reached the 30-day budget you set. Nothing was sent to the provider, so this says nothing about the model."
+ failure.Recommendation = "Raise the 30-day budget under Pulse Intelligence › Provider & Models, choose a cheaper Patrol model or a slower schedule, or wait for the 30-day window to roll on. Patrol resumes on its next scheduled run once spend is back under budget."
case setupFailure:
failure.Title = "Pulse Patrol: Local " + setup.displayName + " CLI not ready"
failure.Summary = "Local " + setup.displayName + " CLI not ready"
@@ -567,12 +574,23 @@ func newPatrolRuntimeFailureFinding(failure patrolRuntimeFailure, now time.Time)
}
}
+// patrolRuntimeResolveReasonPreflight is the resolve reason a successful
+// provider preflight reports; see patrol_preflight.go.
+const patrolRuntimeResolveReasonPreflight = "patrol_preflight_success"
+
func (p *PatrolService) resolvePatrolRuntimeFailureFinding(reason string) bool {
if p == nil || p.findings == nil {
return false
}
errorFindingID := generateFindingID(patrolRuntimeResourceID, "reliability", patrolRuntimeFindingKey)
- if existing := p.findings.Get(errorFindingID); existing == nil || existing.IsResolved() {
+ existing := p.findings.Get(errorFindingID)
+ if existing == nil || existing.IsResolved() {
+ return false
+ }
+ // A healthy provider preflight says nothing about spend: a budget pause
+ // stays until a run actually gets past the budget check (#1789).
+ if reason == patrolRuntimeResolveReasonPreflight && existing.FailureCause == string(PatrolFailureCauseBudgetExhausted) {
+ log.Debug().Str("reason", reason).Msg("AI Patrol: Keeping budget-exhausted runtime finding despite provider preflight success")
return false
}
diff --git a/internal/ai/service.go b/internal/ai/service.go
index 9d3ff75e08..ac9d5d7bb2 100644
--- a/internal/ai/service.go
+++ b/internal/ai/service.go
@@ -525,8 +525,11 @@ func (s *Service) enforceBudget(useCase string) error {
if normalized == "" {
normalized = "chat"
}
- return fmt.Errorf("Pulse Assistant cost budget exceeded (%.2f/%.2f USD over %d days) - disable Pulse Assistant or raise budget to continue",
- summary.Totals.EstimatedUSD, cfg.CostBudgetUSD30d, summary.EffectiveDays)
+ return &CostBudgetExceededError{
+ SpentUSD: summary.Totals.EstimatedUSD,
+ BudgetUSD: cfg.CostBudgetUSD30d,
+ Days: summary.EffectiveDays,
+ }
}
return nil
diff --git a/internal/api/ai_patrol_cost_preview.go b/internal/api/ai_patrol_cost_preview.go
new file mode 100644
index 0000000000..64de95a619
--- /dev/null
+++ b/internal/api/ai_patrol_cost_preview.go
@@ -0,0 +1,81 @@
+package api
+
+import (
+ "net/http"
+ "strconv"
+ "strings"
+ "time"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai"
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai/cost"
+ "github.com/rcourtman/pulse-go-rewrite/internal/utils"
+ "github.com/rs/zerolog/log"
+)
+
+// HandleGetPatrolCostPreview (GET /api/ai/patrol/cost-preview) projects what
+// Patrol will cost per 30 days for a model and schedule, so the settings page
+// can show the bill next to the model choice instead of after the budget
+// trips (#1789, support 2026-07-20/30).
+//
+// Query parameters:
+// - model: a provider:model route to preview; defaults to the configured
+// Patrol model.
+// - interval_minutes: schedule to price; defaults to the configured one.
+// 0 means manual-only.
+func (h *AISettingsHandler) HandleGetPatrolCostPreview(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet {
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+
+ query := r.URL.Query()
+ modelRoute := strings.TrimSpace(query.Get("model"))
+ intervalMinutes := -1
+ if raw := strings.TrimSpace(query.Get("interval_minutes")); raw != "" {
+ parsed, err := strconv.Atoi(raw)
+ if err != nil || parsed < 0 {
+ http.Error(w, "interval_minutes must be a non-negative integer", http.StatusBadRequest)
+ return
+ }
+ intervalMinutes = parsed
+ }
+
+ aiService := h.GetAIService(r.Context())
+ if aiService == nil {
+ projection := ai.ProjectPatrolCostForConfig(nil, modelRoute, intervalMinutes, nil, cost.Summary{}, time.Now())
+ if err := utils.WriteJSONResponse(w, projection); err != nil {
+ log.Error().Err(err).Msg("Failed to write Patrol cost preview response")
+ }
+ return
+ }
+
+ var runs []ai.PatrolRunRecord
+ if patrol := aiService.GetPatrolService(); patrol != nil {
+ runs = patrol.GetRunHistory(0)
+ }
+ projection := ai.ProjectPatrolCostForConfig(
+ aiService.GetConfig(),
+ modelRoute,
+ intervalMinutes,
+ runs,
+ aiService.GetCostSummary(30),
+ time.Now(),
+ )
+ if err := utils.WriteJSONResponse(w, projection); err != nil {
+ log.Error().Err(err).Msg("Failed to write Patrol cost preview response")
+ }
+}
+
+// HandleGetPatrolModelGuidance (GET /api/ai/patrol/model-guidance) returns
+// the recommended / suggested / caution markers the model pickers render,
+// plus this install's cached readiness pass when there is one.
+func (h *AISettingsHandler) HandleGetPatrolModelGuidance(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodGet {
+ http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
+ return
+ }
+ response := h.GetAIService(r.Context()).PatrolModelGuidance()
+ if err := utils.WriteJSONResponse(w, response); err != nil {
+ log.Error().Err(err).Msg("Failed to write Patrol model guidance response")
+ }
+}
diff --git a/internal/api/ai_patrol_cost_preview_test.go b/internal/api/ai_patrol_cost_preview_test.go
new file mode 100644
index 0000000000..d91aad545c
--- /dev/null
+++ b/internal/api/ai_patrol_cost_preview_test.go
@@ -0,0 +1,124 @@
+package api
+
+import (
+ "encoding/json"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/rcourtman/pulse-go-rewrite/internal/ai"
+ "github.com/rcourtman/pulse-go-rewrite/internal/config"
+)
+
+func newPatrolCostPreviewHandler(t *testing.T, mutate func(cfg *config.AIConfig)) *AISettingsHandler {
+ t.Helper()
+ tmp := t.TempDir()
+ cfg := &config.Config{DataPath: tmp}
+ persistence := config.NewConfigPersistence(tmp)
+ aiCfg := config.NewDefaultAIConfig()
+ if mutate != nil {
+ mutate(aiCfg)
+ }
+ if err := persistence.SaveAIConfig(*aiCfg); err != nil {
+ t.Fatalf("SaveAIConfig: %v", err)
+ }
+ return newTestAISettingsHandler(cfg, persistence, nil)
+}
+
+func TestHandleGetPatrolCostPreview_DefaultsToConfiguredPatrolModelAndSchedule(t *testing.T) {
+ t.Parallel()
+ handler := newPatrolCostPreviewHandler(t, func(cfg *config.AIConfig) {
+ cfg.Enabled = true
+ cfg.Model = "gemini:gemini-2.5-flash"
+ cfg.PatrolIntervalMinutes = 720
+ cfg.CostBudgetUSD30d = 20
+ })
+
+ req := newLoopbackRequest(http.MethodGet, "/api/ai/patrol/cost-preview", nil)
+ rec := httptest.NewRecorder()
+ handler.HandleGetPatrolCostPreview(rec, req)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d: %s", rec.Code, rec.Body.String())
+ }
+ var resp ai.PatrolCostProjection
+ if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("decode: %v", err)
+ }
+ if resp.Provider != "gemini" || resp.Model != "gemini-2.5-flash" || resp.IntervalMinutes != 720 {
+ t.Fatalf("expected configured model and schedule, got %+v", resp)
+ }
+ if !resp.PricingKnown || !resp.BilledPerToken || resp.Projected30dUSD <= 0 {
+ t.Fatalf("expected a priced projection, got %+v", resp)
+ }
+ if resp.BudgetUSD30d != 20 || resp.PerRunSource != ai.PatrolCostPerRunSourceDefault {
+ t.Fatalf("expected configured budget and default per-run source, got %+v", resp)
+ }
+}
+
+func TestHandleGetPatrolCostPreview_PreviewsPendingSelection(t *testing.T) {
+ t.Parallel()
+ handler := newPatrolCostPreviewHandler(t, func(cfg *config.AIConfig) {
+ cfg.Enabled = true
+ cfg.Model = "ollama:qwen3:8b"
+ })
+
+ req := newLoopbackRequest(http.MethodGet, "/api/ai/patrol/cost-preview?model=anthropic:claude-sonnet-5&interval_minutes=60", nil)
+ rec := httptest.NewRecorder()
+ handler.HandleGetPatrolCostPreview(rec, req)
+ if rec.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d: %s", rec.Code, rec.Body.String())
+ }
+ var resp ai.PatrolCostProjection
+ if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("decode: %v", err)
+ }
+ if resp.Provider != "anthropic" || resp.Model != "claude-sonnet-5" || resp.IntervalMinutes != 60 {
+ t.Fatalf("expected pending selection, got %+v", resp)
+ }
+ if resp.RecommendedIntervalMinutes != 1440 {
+ t.Fatalf("expected the cost model to propose a daily schedule for sonnet on the reference budget, got %d", resp.RecommendedIntervalMinutes)
+ }
+}
+
+func TestHandleGetPatrolCostPreview_RejectsBadIntervalAndMethod(t *testing.T) {
+ t.Parallel()
+ handler := newPatrolCostPreviewHandler(t, nil)
+
+ rec := httptest.NewRecorder()
+ handler.HandleGetPatrolCostPreview(rec, newLoopbackRequest(http.MethodGet, "/api/ai/patrol/cost-preview?interval_minutes=-5", nil))
+ if rec.Code != http.StatusBadRequest {
+ t.Fatalf("expected 400 for negative interval, got %d", rec.Code)
+ }
+ rec = httptest.NewRecorder()
+ handler.HandleGetPatrolCostPreview(rec, newLoopbackRequest(http.MethodPost, "/api/ai/patrol/cost-preview", nil))
+ if rec.Code != http.StatusMethodNotAllowed {
+ t.Fatalf("expected 405 for POST, got %d", rec.Code)
+ }
+}
+
+func TestHandleGetPatrolModelGuidance_ReturnsRulesWithoutVerifiedMarker(t *testing.T) {
+ t.Parallel()
+ handler := newPatrolCostPreviewHandler(t, nil)
+
+ rec := httptest.NewRecorder()
+ handler.HandleGetPatrolModelGuidance(rec, newLoopbackRequest(http.MethodGet, "/api/ai/patrol/model-guidance", nil))
+ if rec.Code != http.StatusOK {
+ t.Fatalf("expected 200, got %d: %s", rec.Code, rec.Body.String())
+ }
+ var resp ai.PatrolModelGuidanceResponse
+ if err := json.Unmarshal(rec.Body.Bytes(), &resp); err != nil {
+ t.Fatalf("decode: %v", err)
+ }
+ if len(resp.Rules) == 0 || resp.Verified != nil {
+ t.Fatalf("expected static rules and no verified marker, got %+v", resp)
+ }
+ sawOllama := false
+ for _, rule := range resp.Rules {
+ if rule.Provider == config.AIProviderOllama && rule.Level == ai.PatrolModelGuidanceRecommended {
+ sawOllama = true
+ }
+ }
+ if !sawOllama {
+ t.Fatal("expected the Ollama blessing in the guidance rules")
+ }
+}
diff --git a/internal/api/route_inventory_test.go b/internal/api/route_inventory_test.go
index ffae2879d8..4a1e962cd1 100644
--- a/internal/api/route_inventory_test.go
+++ b/internal/api/route_inventory_test.go
@@ -644,6 +644,8 @@ var allRouteAllowlist = []string{
"/api/ai/patrol/run",
"/api/ai/patrol/preflight",
"/api/ai/patrol/readiness",
+ "/api/ai/patrol/cost-preview",
+ "/api/ai/patrol/model-guidance",
"/api/ai/patrol/acknowledge",
"/api/ai/patrol/dismiss",
"/api/ai/patrol/findings/note",
diff --git a/internal/api/router_routes_ai_relay.go b/internal/api/router_routes_ai_relay.go
index 184270e5f4..2ab4176392 100644
--- a/internal/api/router_routes_ai_relay.go
+++ b/internal/api/router_routes_ai_relay.go
@@ -110,6 +110,11 @@ func (r *Router) registerAIRelayRoutesGroup() {
// Mutation endpoints (run, acknowledge, dismiss, etc.) return 402 to prevent unauthorized actions
// SECURITY: Patrol status and stream require ai:execute scope to access findings
r.mux.HandleFunc("/api/ai/patrol/status", RequireAuth(r.config, RequireScope(config.ScopeAIExecute, r.aiSettingsHandler.HandleGetPatrolStatus)))
+ // Cost preview and model guidance for the Patrol model choice. Read-only
+ // and priced from Pulse's own table, but they reveal spend and budget, so
+ // they sit behind the same settings:read scope as the cost summary.
+ r.mux.HandleFunc("/api/ai/patrol/cost-preview", RequireAuth(r.config, RequireScope(config.ScopeSettingsRead, r.aiSettingsHandler.HandleGetPatrolCostPreview)))
+ r.mux.HandleFunc("/api/ai/patrol/model-guidance", RequireAuth(r.config, RequireScope(config.ScopeSettingsRead, r.aiSettingsHandler.HandleGetPatrolModelGuidance)))
r.mux.HandleFunc("/api/ai/patrol/stream", RequireAuth(r.config, RequireScope(config.ScopeAIExecute, r.aiSettingsHandler.HandlePatrolStream)))
r.mux.HandleFunc("/api/ai/patrol/findings", RequireAuth(r.config, r.routeAIPatrolFindings))
r.mux.HandleFunc("/api/ai/patrol/objectives", RequireAuth(r.config, RequireScope(config.ScopeAIExecute, r.aiSettingsHandler.HandlePatrolObjectives)))
diff --git a/internal/config/persistence.go b/internal/config/persistence.go
index b0e8fdee7b..0060ac9810 100644
--- a/internal/config/persistence.go
+++ b/internal/config/persistence.go
@@ -2507,6 +2507,7 @@ type AIFindingRecord struct {
Description string `json:"description"`
Recommendation string `json:"recommendation,omitempty"`
Evidence string `json:"evidence,omitempty"`
+ FailureCause string `json:"failure_cause,omitempty"`
Source string `json:"source,omitempty"`
DetectedAt time.Time `json:"detected_at"`
LastSeenAt time.Time `json:"last_seen_at"`